answer
stringlengths
17
10.2M
package uk.ac.manchester.cs.owl.semspreadsheets.ui.action; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import uk.ac.manchester.cs.owl.semspreadsheets.ui.ErrorHandler; import uk.ac.manchester.cs.owl.semspreadsheets.ui.WorkbookFrame; /** * @author Stuart Owen * @author Matthew Horridge */ @SuppressWarnings("serial") public class OpenFromBioPortalAction extends WorkbookFrameAction { public OpenFromBioPortalAction(WorkbookFrame workbookFrame) { super("Open ontology from BioPortal...", workbookFrame); setAcceleratorKey(KeyEvent.VK_B,true,false); } public void actionPerformed(ActionEvent e) { try { getWorkbookFrame().loadBioportalOntology(); } catch (Exception e1) { ErrorHandler.getErrorHandler().handleError(e1); } } }
package natlab.backends.x10; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import natlab.tame.valueanalysis.*; import natlab.tame.valueanalysis.advancedMatrix.AdvancedMatrixValue; import natlab.tame.valueanalysis.aggrvalue.*; import natlab.tame.AdvancedTamerTool; import natlab.toolkits.filehandling.GenericFile; import natlab.toolkits.path.FileEnvironment; import natlab.backends.x10.IRx10.ast.AssignStmt; import natlab.backends.x10.IRx10.ast.DeclStmt; import natlab.backends.x10.IRx10.ast.Program; import natlab.backends.x10.codegen.*; public class Main { public static void main(String[] args) { // String file = // "/home/2011/vkumar5/mclab/Project/languages/Natlab/src/natlab/backends/x10/testing/unitTests/ut8" String file = "/home/2011/vkumar5/mclab_git/mclab/languages/Natlab/src/natlab/backends/x10/benchmarks/unit/forTest1"; //String file = "/home/2011/vkumar5/hello1"; String fileIn = file + ".m"; String fileOut = file + ".x10"; String fileOutTame = file + "_tame.m"; GenericFile gFile = GenericFile.create(fileIn); /* /home/xuli/test/hello.m */ FileEnvironment env = new FileEnvironment(gFile); // get path // environment obj //String x10Code = ""; AdvancedTamerTool tool = new AdvancedTamerTool(); // System.out.println(args[0]); ValueAnalysis<AggrValue<AdvancedMatrixValue>> analysis = tool.analyze( args, env); int size = analysis.getNodeList().size(); try { StringBuffer tamedCode = new StringBuffer(); BufferedWriter out = new BufferedWriter(new FileWriter(fileOutTame)); for (int i = 0; i < analysis.getNodeList().size(); i++) { tamedCode.append(ValueAnalysisPrinter.prettyPrint(analysis .getNodeList().get(i).getAnalysis())); } out.write(tamedCode.toString()); out.close(); } catch (IOException e) { System.out.println("Exception "); } System.out.println("\n System.out.println("\n //HashMap<String, String> usedBuiltins = new HashMap<String, String>(); ArrayList<collectBuiltins> listOfUsedBuiltins = new ArrayList<collectBuiltins>(); listOfUsedBuiltins = collectBuiltins.collect(analysis,size); // System.out.println("UNCOMMENT IN MAIN"); Program irx10Program = new Program(); irx10Program.setClassBlock(IRx10ASTGenerator.x10ClassMaker(analysis, size, listOfUsedBuiltins, "home/2011/vkumar5/", "testclass")); String x10Program = irx10Program.pp("","testclass"); System.out .println("\n~~~~~~~~~~~~~~~~X10 code~~~~~~~~~~~~~~~~~~~~~~~\n"); System.out.println(x10Program); System.out .println("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); try { BufferedWriter out = new BufferedWriter(new FileWriter(fileOut)); out.write(x10Program); out.close(); } catch (IOException e) { System.out.println("Exception "); } BuiltinWriter.classWriter(); } }
import java.io.File; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.FlowLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelListener; import java.awt.event.MouseWheelEvent; import java.awt.Font; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.BorderFactory; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.JTextArea; import javax.swing.KeyStroke; import javax.swing.JLabel; import javax.swing.JButton; /** * JFrame showing a map * @author Jawaherul * */ public class StacFrame extends JFrame { private JMenuBar menuBar; private JMenu menuFile, menuSearch, menuNavigation, menuCustomize, menuHelp; private int width, height; private JSplitPane centerSplitPane; public VizPanel vizPanel, contextPanel; private JPanel menuPanel, leftPanel, rightPanel; public JCheckBox showContext, showEdge; private boolean context = false, mouseDrag = false; public enum searchType { ID, INSTRUCTION, METHOD, ALL_LEAVES, ALL_SOURCES, OUT_OPEN, OUT_CLOSED, IN_OPEN, IN_CLOSED, ROOT_PATH } public StacFrame() { super("STAC Visualization"); width = Parameters.width; height = Parameters.height; this.setLocation(0, 0); setSize(this.width,this.height); makeMenuBar(); makeLayout(); this.setVisible(true); } public void makeMenuBar() { menuBar = new JMenuBar(); //File menu menuFile = new JMenu("File"); menuBar.add(menuFile); JMenuItem loadGraph = new JMenuItem("Load graph from JSON"); //Will be removed soon menuFile.add(loadGraph); loadGraph.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ev) { loadGraph(false); } } ); JMenuItem loadMessages = new JMenuItem("Load graph from message file"); menuFile.add(loadMessages); loadMessages.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { loadGraph(true); } } ); /*final JMenuItem loadJavaCode = new JMenuItem("Load matching decompiled code"); menuFile.add(loadJavaCode); loadJavaCode.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { TakeInput.loadDecompiledCode(); } } );*/ //Search menu menuSearch = new JMenu("Search"); menuBar.add(menuSearch); JMenuItem searchByID = new JMenuItem("by ID"); menuSearch.add(searchByID); searchByID.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { searchAndHighlight(searchType.ID); Parameters.repaintAll(); } } ); JMenuItem searchByInst = new JMenuItem("by Instruction"); menuSearch.add(searchByInst); searchByInst.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { searchAndHighlight(searchType.INSTRUCTION); Parameters.repaintAll(); } } ); JMenuItem searchByMethod = new JMenuItem("by Method"); menuSearch.add(searchByMethod); searchByMethod.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { searchAndHighlight(searchType.METHOD); Parameters.repaintAll(); } } ); JMenuItem searchLeaves = new JMenuItem("All leaves"); menuSearch.add(searchLeaves); searchLeaves.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { searchAndHighlight(searchType.ALL_LEAVES); Parameters.repaintAll(); } } ); JMenuItem searchSources = new JMenuItem("All sources"); menuSearch.add(searchSources); searchSources.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { searchAndHighlight(searchType.ALL_SOURCES); Parameters.repaintAll(); } } ); JMenuItem searchOutgoing = new JMenuItem("Outgoing neighborhood (open)"); menuSearch.add(searchOutgoing); searchOutgoing.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { searchAndHighlight(searchType.OUT_OPEN); Parameters.repaintAll(); } } ); JMenuItem searchOutgoingclosed = new JMenuItem("Outgoing neighborhood (closed)"); menuSearch.add(searchOutgoingclosed); searchOutgoingclosed.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { searchAndHighlight(searchType.OUT_CLOSED); Parameters.repaintAll(); } } ); JMenuItem searchIncoming = new JMenuItem("Incoming neighborhood (open)"); menuSearch.add(searchIncoming); searchIncoming.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { searchAndHighlight(searchType.IN_OPEN); Parameters.repaintAll(); } } ); JMenuItem searchIncomingclosed = new JMenuItem("Incoming neighborhood (closed)"); menuSearch.add(searchIncomingclosed); searchIncomingclosed.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { searchAndHighlight(searchType.IN_CLOSED); Parameters.repaintAll(); } } ); JMenuItem searchPathToRoot = new JMenuItem("Path to Root"); menuSearch.add(searchPathToRoot); searchPathToRoot.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { searchAndHighlight(searchType.ROOT_PATH); Parameters.repaintAll(); } } ); JMenuItem clearAll = new JMenuItem("Clear All"); menuSearch.add(clearAll); clearAll.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { Main.graph.clearHighlights(); Parameters.leftArea.clear(); Parameters.repaintAll(); } } ); //Navigation menu menuNavigation = new JMenu("Navigation"); menuBar.add(menuNavigation); JMenuItem zoomIn = new JMenuItem("Zoom in (Mouse wheel up)"); menuNavigation.add(zoomIn); zoomIn.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { Main.graph.increaseZoom(Parameters.zoomFactor, -1, -1); Parameters.repaintAll(); } } ); JMenuItem zoomOut = new JMenuItem("Zoom out (Mouse wheel down)"); menuNavigation.add(zoomOut); zoomOut.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { Main.graph.increaseZoom(1/Parameters.zoomFactor, -1, -1); Parameters.repaintAll(); } } ); JMenuItem resetGraph = new JMenuItem("Reset view"); menuNavigation.add(resetGraph); resetGraph.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { Main.graph.resetZoom(); Parameters.repaintAll(); } } ); resetGraph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, 0)); JMenuItem collapse = new JMenuItem("Collapse nodes"); menuNavigation.add(collapse); collapse.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { Main.graph.collapseOnce(); Parameters.repaintAll(); } } ); collapse.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, 0)); JMenuItem decollapse = new JMenuItem("Expand nodes"); menuNavigation.add(decollapse); decollapse.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { Main.graph.deCollapseOnce(); Parameters.repaintAll(); } } ); decollapse.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0)); JMenuItem previous = new JMenuItem("Previous view"); menuNavigation.add(previous); previous.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { Main.graph.loadPreviousView(); Parameters.repaintAll(); } } ); previous.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, 0)); JMenuItem next = new JMenuItem("Return to next view"); menuNavigation.add(next); next.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { Main.graph.restoreNewView(); Parameters.repaintAll(); } } ); next.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, 0)); JMenuItem panUp = new JMenuItem("Pan up"); menuNavigation.add(panUp); panUp.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { Main.graph.shiftView(0, -1); Parameters.repaintAll(); } } ); panUp.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0)); JMenuItem panDown = new JMenuItem("Pan down"); menuNavigation.add(panDown); panDown.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { Main.graph.shiftView(0, 1); Parameters.repaintAll(); } } ); panDown.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0)); JMenuItem panLeft = new JMenuItem("Pan left"); menuNavigation.add(panLeft); panLeft.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { Main.graph.shiftView(-1, 0); Parameters.repaintAll(); } } ); panLeft.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0)); JMenuItem panRight = new JMenuItem("Pan right"); menuNavigation.add(panRight); panRight.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { Main.graph.shiftView(1, 0); Parameters.repaintAll(); } } ); panRight.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0)); //Customize display menuCustomize = new JMenu("Customize"); menuBar.add(menuCustomize); JMenuItem changeFont = new JMenuItem("Change font size"); menuCustomize.add(changeFont); changeFont.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { String newFontSize = JOptionPane.showInputDialog(null, "The current font size is: " + Parameters.font.getSize() + ". Please enter a new font size"); Parameters.font = new Font("Serif", Font.PLAIN, Integer.parseInt(newFontSize)); Parameters.leftArea.setFont(Parameters.font); Parameters.rightArea.setFont(Parameters.font); Parameters.repaintAll(); } } ); changeFont.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, 0)); //Help menu menuHelp = new JMenu("Help"); menuBar.add(menuHelp); JMenuItem help = new JMenuItem("Shortcuts"); menuHelp.add(help); help.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent ev) { JOptionPane.showMessageDialog(getParent(), "The following keyboard shortcuts are implemented.\n" + "R: Reset zoom level to show entire graph \n" + "C: Collapse all nodes by method \n" + "D: Uncollapse all nodes \n" + "P: Return to previous view \n" + "N: Continue from previous to next view \n" + "F: Change font size \n" + "Arrows: Pan up, down, left or right \n" + "Left-Click: Uncollapse a node \n" + "Right-Click: Collapse all nodes of a single method \n" + "Shift-click: Select/de-select multiple vertices \n" + "CTRL + <Digit>: Hotkey view with all vertices currently on screen to <Digit> \n" + "<Digit>: Go to hotkeyed view \n" + "H: Open this list of shortcuts" ); } } ); help.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, 0)); } public void makeLayout() { //centerPanel and vizPanel this.setLayout(new BorderLayout()); setSplitScreen(); this.addMouseToViz(); this.addKeyboard(vizPanel); this.addMouseToContext(); this.addKeyboard(contextPanel); //menuPanel this.menuPanel = new JPanel(); this.menuPanel.setBorder(BorderFactory.createEtchedBorder()); this.menuPanel.setLayout(new FlowLayout()); this.getContentPane().add(this.menuPanel, BorderLayout.NORTH); JPanel contextPanel = new JPanel(); contextPanel.setBorder(BorderFactory.createEtchedBorder()); contextPanel.setLayout(new GridLayout(1,1)); this.menuPanel.add(contextPanel); showEdge = new JCheckBox("Show Edge"); showEdge.setEnabled(true); showEdge.setSelected(true); showEdge.addItemListener ( new ItemListener() { public void itemStateChanged(ItemEvent e) { vizPanel.showEdge = showEdge.isSelected(); StacFrame.this.repaint(); } } ); contextPanel.add(showEdge); JPanel sizePanel = new JPanel(); sizePanel.setBorder(BorderFactory.createEtchedBorder()); sizePanel.setLayout(new GridLayout(1,3)); this.menuPanel.add(sizePanel); JButton sizeMinus = new JButton("-"); sizeMinus.setEnabled(true); sizeMinus.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent e) { vizPanel.boxSize *= Parameters.boxFactor; Parameters.repaintAll(); } } ); sizePanel.add(sizeMinus); JLabel sizeL = new JLabel("box size"); sizeL.setHorizontalAlignment(SwingConstants.CENTER); sizePanel.add(sizeL); JButton sizePlus = new JButton("+"); sizePlus.setEnabled(true); sizePlus.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent e) { vizPanel.boxSize /= Parameters.boxFactor; Parameters.repaintAll(); } } ); sizePanel.add(sizePlus); this.setJMenuBar(menuBar); this.setVisible(true); this.repaint(); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void setSplitScreen() { System.out.println("Setting split screen"); centerSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true); JSplitPane leftSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true); JSplitPane rightSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true); centerSplitPane.setLeftComponent(leftSplitPane); centerSplitPane.setRightComponent(rightSplitPane); this.getContentPane().add(this.centerSplitPane, BorderLayout.CENTER); centerSplitPane.setOneTouchExpandable(true); leftSplitPane.setOneTouchExpandable(true); rightSplitPane.setOneTouchExpandable(true); leftPanel = new JPanel(); leftSplitPane.setLeftComponent(leftPanel); rightPanel = new JPanel(); rightSplitPane.setRightComponent(rightPanel); this.vizPanel = new VizPanel(this, false); rightSplitPane.setLeftComponent(this.vizPanel); this.contextPanel = new VizPanel(this,true); leftSplitPane.setRightComponent(this.contextPanel); JLabel leftL = new JLabel("Context", JLabel.CENTER); Parameters.leftArea = new CodeArea(); leftPanel.setLayout(new BorderLayout()); leftPanel.add(leftL,BorderLayout.NORTH); JScrollPane scrollL = new JScrollPane (Parameters.leftArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); leftPanel.add(scrollL, BorderLayout.CENTER); leftPanel.setFont(Parameters.font); JLabel rightL = new JLabel("Description", JLabel.CENTER); Parameters.rightArea = new JTextArea(); Parameters.rightArea.setEditable(false); rightPanel.setLayout(new BorderLayout()); rightPanel.add(rightL, BorderLayout.NORTH); JScrollPane scrollR = new JScrollPane (Parameters.rightArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); rightPanel.add(scrollR, BorderLayout.CENTER); rightPanel.setFont(Parameters.font); double rw1 = 0.2, rw2 = 0.75, rw3 = 0.6; centerSplitPane.setResizeWeight(rw1); rightSplitPane.setResizeWeight(rw2); leftSplitPane.setResizeWeight(rw3); centerSplitPane.resetToPreferredSizes(); rightSplitPane.resetToPreferredSizes(); leftSplitPane.resetToPreferredSizes(); } public void loadGraph(boolean fromMessages) { File file = Parameters.openFile(false); if(file == null) return; TakeInput ti = new TakeInput(); ti.run(file.getAbsolutePath(), fromMessages); Parameters.repaintAll(); } public void searchAndHighlight(searchType search) { String title = ""; System.out.println("Search type: " + search); if(search == searchType.ID || search == searchType.ROOT_PATH) { title = "Enter node ID(s)"; } else if(search == searchType.INSTRUCTION) { title = "Instruction contains ..."; } else if(search == searchType.METHOD) { title = "Method name contains ..."; } else if(search == searchType.OUT_OPEN || search == searchType.OUT_CLOSED || search == searchType.IN_OPEN || search == searchType.IN_CLOSED) { title = "Enter node ID"; } String input = ""; if(search != searchType.ALL_LEAVES && search != searchType.ALL_SOURCES) { input = JOptionPane.showInputDialog(null, title); if(input == null) return; else input = input.trim(); if(input.equals("")) return; } Main.graph.searchNodes(search, input); Parameters.vertexHighlight = true; Parameters.highlightOutgoing = search != searchType.OUT_OPEN; Parameters.highlightIncoming = search != searchType.IN_OPEN; } public boolean isGraphLoaded() { return (Main.graph != null); } public void addMouseToViz() { vizPanel.addMouseListener ( new MouseListener() { public void mouseClicked(MouseEvent m) { if(!isGraphLoaded()) return; vizPanel.requestFocusInWindow(); context = false; double x = vizPanel.getRelativeFracFromAbsolutePixelX(getRelativeXPixels(m))*Main.graph.getWidth(); double y = vizPanel.getRelativeFracFromAbsolutePixelY(getRelativeYPixels(m))*Main.graph.getHeight(); if(System.currentTimeMillis() - Parameters.mouseLastTime > Parameters.mouseInterval) { Parameters.mouseLastTime = System.currentTimeMillis(); if(SwingUtilities.isLeftMouseButton(m) && Main.graph != null) { if(m.isShiftDown()) { AbstractVertex ver = Main.graph.getVertexNearestCoordinate(x, y); if(ver != null) { if(ver.isHighlighted()) { ver.clearAllHighlights(); Main.graph.redoCycleHighlights(); } else { ver.addHighlight(true, true, true); if(ver.vertexType == AbstractVertex.VertexType.LINE) ((Vertex) ver).highlightCycles(); } } } else if(m.getClickCount() == 1) { AbstractVertex ver = Main.graph.getVertexNearestCoordinate(x, y); Parameters.leftArea.clear(); Main.graph.clearHighlights(); if(ver != null) { Parameters.highlightIncoming = true; Parameters.highlightOutgoing = true; Parameters.vertexHighlight = true; ver.addHighlight(true, true, true); if(ver.vertexType == AbstractVertex.VertexType.LINE) ((Vertex) ver).highlightCycles(); } } else if(m.getClickCount() == 2) { AbstractVertex ver = Main.graph.getVertexNearestCoordinate(x, y); if(ver != null) { if(ver.getMergeChildren().size() > 0) //We have a merge vertex { ver.deCollapse(); Parameters.repaintAll(); } } } } if(SwingUtilities.isRightMouseButton(m) && Main.graph != null) { //if(m.getClickCount() == 1) { AbstractVertex ver = Main.graph.getVertexNearestCoordinate(x, y); if(ver != null) { if(ver.getMergeParent() != null) { ver.getMergeParent().collapse(); } } } } Parameters.repaintAll(); } } public void mouseEntered(MouseEvent arg0){} public void mouseExited(MouseEvent arg0){} public void mousePressed(MouseEvent m) { if(!isGraphLoaded()) return; context = false; vizPanel.selectLeft = getRelativeXPixels(m); vizPanel.selectTop = getRelativeYPixels(m); vizPanel.showSelection = true; Parameters.startTime = System.currentTimeMillis(); Parameters.lastInterval = -1; } public void mouseReleased(MouseEvent ev) { if(!isGraphLoaded()) return; vizPanel.requestFocus(); vizPanel.showSelection = false; context = false; if(mouseDrag) { mouseDrag = false; if(Main.graph != null) { double x1 = vizPanel.getIndexFromCurrentPixelX(vizPanel.selectLeft); double x2 = vizPanel.getIndexFromCurrentPixelX(vizPanel.selectRight); double y1 = vizPanel.getIndexFromCurrentPixelY(vizPanel.selectTop); double y2 = vizPanel.getIndexFromCurrentPixelY(vizPanel.selectBottom); Main.graph.selectVertices(x1, x2, y1, y2); } Parameters.repaintAll(); } } } ); vizPanel.addMouseMotionListener ( new MouseMotionListener() { public void mouseMoved(MouseEvent m){} public void mouseDragged(MouseEvent m) { if(!isGraphLoaded()) return; context = false; mouseDrag = true; vizPanel.selectRight = getRelativeXPixels(m); vizPanel.selectBottom = getRelativeYPixels(m); if((System.currentTimeMillis()-Parameters.startTime)/Parameters.refreshInterval > Parameters.lastInterval) { StacFrame.this.repaint(); Parameters.lastInterval = (System.currentTimeMillis()-Parameters.startTime)/Parameters.refreshInterval; } } } ); vizPanel.addMouseWheelListener ( new MouseWheelListener() { public void mouseWheelMoved(MouseWheelEvent e) { if(!isGraphLoaded()) return; int notches = e.getWheelRotation(); //Zoom in or box++ for mouse wheel up, zoom out or box-- for mouse wheel down if(notches > 0) { if(e.isShiftDown()) { vizPanel.boxSize /= Parameters.boxFactor; } else { double x = vizPanel.getRelativeFracFromAbsolutePixelX(getRelativeXPixels(e)); double y = vizPanel.getRelativeFracFromAbsolutePixelY(getRelativeYPixels(e)); Main.graph.increaseZoom(Parameters.zoomFactor, x, y); } } else { if(e.isShiftDown()) { vizPanel.boxSize *= Parameters.boxFactor; } else { double x = vizPanel.getRelativeFracFromAbsolutePixelX(getRelativeXPixels(e)); double y = vizPanel.getRelativeFracFromAbsolutePixelY(getRelativeYPixels(e)); Main.graph.increaseZoom(1/Parameters.zoomFactor, x, y); } } Parameters.repaintAll(); } } ); } public void addMouseToContext() { contextPanel.addMouseListener ( new MouseListener() { public void mouseClicked(MouseEvent m) { if(!isGraphLoaded()) return; contextPanel.requestFocusInWindow(); context = true; double x = contextPanel.getRelativeFracFromAbsolutePixelX(getRelativeXPixels(m)); double y = contextPanel.getRelativeFracFromAbsolutePixelY(getRelativeYPixels(m)); Main.graph.zoomNPan(x, y, 1.0); Parameters.repaintAll(); if(System.currentTimeMillis() - Parameters.mouseLastTime > Parameters.mouseInterval) { Parameters.mouseLastTime = System.currentTimeMillis(); } } public void mouseEntered(MouseEvent arg0) { } public void mouseExited(MouseEvent arg0) { } public void mousePressed(MouseEvent m) { if(!isGraphLoaded()) return; context = true; contextPanel.selectLeft = getRelativeXPixels(m); contextPanel.selectTop = getRelativeYPixels(m); contextPanel.showSelection = true; Parameters.startTime = System.currentTimeMillis(); Parameters.lastInterval = -1; } public void mouseReleased(MouseEvent ev) { if(!isGraphLoaded()) return; context = true; // vizPanel.requestFocus(); contextPanel.showSelection = false; if(mouseDrag) { mouseDrag = false; if(Main.graph != null) { double x1 = contextPanel.getRelativeFracFromAbsolutePixelX(contextPanel.selectLeft); double x2 = contextPanel.getRelativeFracFromAbsolutePixelX(contextPanel.selectRight); double y1 = contextPanel.getRelativeFracFromAbsolutePixelY(contextPanel.selectTop); double y2 = contextPanel.getRelativeFracFromAbsolutePixelY(contextPanel.selectBottom); Main.graph.zoomNPan(x1, x2, y1, y2); } Parameters.repaintAll(); } } } ); contextPanel.addMouseMotionListener ( new MouseMotionListener() { public void mouseMoved(MouseEvent m){} public void mouseDragged(MouseEvent m) { if(!isGraphLoaded()) return; context = true; mouseDrag = true; contextPanel.selectRight = getRelativeXPixels(m); contextPanel.selectBottom = getRelativeYPixels(m); if((System.currentTimeMillis()-Parameters.startTime)/Parameters.refreshInterval > Parameters.lastInterval) { StacFrame.this.repaint(); Parameters.lastInterval = (System.currentTimeMillis()-Parameters.startTime)/Parameters.refreshInterval; } } } ); contextPanel.addMouseWheelListener ( new MouseWheelListener() { public void mouseWheelMoved(MouseWheelEvent e) { if(!isGraphLoaded()) return; int notches = e.getWheelRotation(); //box++ for mouse wheel up, box-- for mouse wheel down if(notches > 0) { contextPanel.boxSize /= Parameters.boxFactor; } else { contextPanel.boxSize *= Parameters.boxFactor; } Parameters.repaintAll(); } } ); } //Gets the x location of a mouse event in pixels, shifted so that the left side is 0. public double getRelativeXPixels(MouseEvent m) { if(this.context) return m.getX() - contextPanel.getLocation().x; else return m.getX() - vizPanel.getLocation().x - this.leftPanel.getWidth() - centerSplitPane.getDividerSize(); } //Gets the y location of a mouse event in pixels, shifted so that the top of the current panel is 0. public double getRelativeYPixels(MouseEvent m) { //TODO: Why is this not different for the context menu? //Subtract the top bar, the menu panel height, and the start height of the current panel return m.getY() - (this.getHeight() - this.getContentPane().getSize().height) - vizPanel.getY() - this.menuPanel.getHeight(); } public void addKeyboard(JPanel viz) { viz.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent ev){} public void keyPressed(KeyEvent ev) { int code = ev.getKeyCode(); // System.out.println("Key pressed: " + code); if(code == 'L') { String lim = JOptionPane.showInputDialog(null, "Set Limit on the number of vertices:"); Parameters.limitV = Long.parseLong(lim); Parameters.repaintAll(); } if(Character.isDigit(code)) { int digit = code - '0'; if(ev.isControlDown()) { //Assign hotkey to view System.out.println("Assigning hotkey to " + digit); Main.graph.addHotkeyedView(digit); } else { //Go to hotkeyed view System.out.println("Loading hotkeyed view: " + digit); Main.graph.loadHotkeyedView(digit); Parameters.repaintAll(); } } } public void keyReleased(KeyEvent ev) { // System.out.println("key released: "+ev.getKeyCode()); } }); viz.setFocusable(true); viz.requestFocusInWindow(); } }
import java.util.*; class HelloWorld { static final List<String> CENSUS = new ArrayList<String>(); static { CENSUS.add("Allen Comp Sci @ https://github.com/AllenCompSci"); CENSUS.add("Mr. Hudson @ https://github.com/theshrewedshrew"); CENSUS.add("BEST Team 58 @ https://github.com/BESTTeam58"); CENSUS.add("Texas Snow @ https://github.com/TexasSnow"); CENSUS.add("Rahultheman12 @ https://github.com/Rahultheman12"); CENSUS.add("John Nguyen @ https://github.com/jawnlovesfreestuff"); CENSUS.add("Carson Mires @ https://github.com/carsonmires"); CENSUS.add("Cameron Mathis @ https://github.com/Phylux"); CENSUS.add("YourFriendlyNeighborhoodSpiderman @ https://github.com/YourFriendlyNeighborhoodSpiderman"); CENSUS.add("Devin Petersen @ https://github.com/DevinPetersen"); CENSUS.add("Kaushik Malapati@ https://github.com/KaushikMalapati"); CENSUS.add("Kyleaustin36 @ https://github.com/kyleaustin36"); CENSUS.add("Zak Ishak @ https://github.com/zakishak"); CENSUS.add("Maaz Kamal @ https://github.com/Maze-Camel"); CENSUS.add("Justin Van Nimwegen @ https://github.com/JustinV10"); CENSUS.add("bingood4ever @ https://github.com/bingood4ever"); CENSUS.add("Gainz101 @ https://github.com/Gainz101"); CENSUS.add("zachdogg @ https://github.com/Zachdogg1"); CENSUS.add("Johnathan G. @ https://github.com/SodaCan0515"); CENSUS.add("MJHudson618 @ https://github.com/MJHudson618"); CENSUS.add("Abhi1458 @ https://github.com/Abhi1458"); CENSUS.add("Maxwell Cody @ https://github.com/MaxwellCody"); } public static void main(String[] args) { for(String entry : CENSUS) { System.out.println("Hello World from " + entry); } } }
package cx2x.xcodeml.xelement; import org.w3c.dom.Element; import org.w3c.dom.Node; import cx2x.xcodeml.exception.*; import cx2x.xcodeml.helper.*; /** * The XdoStatement represents the FdoStatement (6.5) element in XcodeML * intermediate representation. * * Elements: * - Required: * - Var (Xvar) * - indexRange (XindexRange) * - body (Xbody) * Attributes: * - Optional: construct_name (text) * * @author clementval */ public class XdoStatement extends XbaseElement { private XloopIterationRange _iterationRange = null; private Xbody _body = null; private String _construct_name = null; /** * Xelement standard ctor. Pass the base element to the base class and read * inner information (elements and attributes). * @param baseElement The root element of the Xelement */ public XdoStatement(Element baseElement){ super(baseElement); findRangeElements(); _body = XelementHelper.findBody(this, false); _construct_name = XelementHelper.getAttributeValue(this, XelementName.ATTR_CONSTRUCT_NAME); } /** * Find the different elements that are included in the iteration range. */ public void findRangeElements(){ Xvar inductionVar = XelementHelper.findVar(this, false); XindexRange indexRange = XelementHelper.findIndexRange(this, false); if(inductionVar != null && indexRange != null){ _iterationRange = new XloopIterationRange(inductionVar, indexRange); } } /** * Create an empty arrayIndex element in the given program */ public static XdoStatement createEmpty(XcodeProg xcodeml, XloopIterationRange range) { Element element = xcodeml.getDocument(). createElement(XelementName.DO_STMT); if(range != null){ element.appendChild(range.getInductionVar().cloneNode()); element.appendChild(range.getIndexRange().cloneNode()); } Element body = xcodeml.getDocument().createElement(XelementName.BODY); element.appendChild(body); return new XdoStatement(element); } /** * Apply a new iteration range to the do statement. * @param range The range to be applied. */ public void setNewRange(XloopIterationRange range){ Element body = _body.getBaseElement(); Node newVar = range.getInductionVar().cloneNode(); Node newRange = range.getIndexRange().cloneNode(); baseElement.insertBefore(newVar, body); baseElement.insertBefore(newRange, body); findRangeElements(); } /** * Delete the range elements (induction variable and index range). */ public void deleteRangeElements(){ baseElement.removeChild(_iterationRange.getInductionVar().getBaseElement()); baseElement.removeChild(_iterationRange.getIndexRange().getBaseElement()); } /** * Swap the range elements between two loop statements. * @param otherLoop The loop to swap range elements with this one. */ protected void swapRangeElementsWith(XdoStatement otherLoop){ otherLoop.setNewRange(_iterationRange); setNewRange(otherLoop.getIterationRange()); } /** * Get the do statement iteration range. * @return A XloopIterationRange containing the loop iteration range * information. */ public XloopIterationRange getIterationRange(){ return _iterationRange; } /** * Get the do statement's body. * @return A Xbody object for the do statement. */ public Xbody getBody(){ return _body; } public void appendToBody(XdoStatement otherLoop) throws IllegalTransformationException { XelementHelper.appendBody(_body, otherLoop.getBody()); } /** * Get the induction variable of the do statement. * @return The induction variable as a String value. */ public String getInductionVariable(){ return _iterationRange.getInductionVar().getValue(); } /** * Get the lower bound value of the do statement. * @return The lower bound value as a String value. */ public String getLowerBoundValue(){ return _iterationRange.getIndexRange().getLowerBound().getValue(); } /** * Get the upper bound value of the do statement. * @return The upper bound value as a String value. */ public String getUpperBoundValue(){ return _iterationRange.getIndexRange().getUpperBound().getValue(); } /** * Get the step value of the do statement. * @return The step value as a String value. */ public String getStepValue(){ return _iterationRange.getIndexRange().getStep().getValue(); } /** * @return A string representation of the iterarion range. */ public String getFormattedRange(){ return _iterationRange.toString(); } /** * Check whether two do statements share the same iteration range. * @param other The do statement to be compared with the current one. * @return True if the two do statements share the same iteration range. False * otherwise. */ public boolean hasSameRangeWith(XdoStatement other){ return _iterationRange.isFullyIdentical(other.getIterationRange()); } /** * Check whether the element has a construct name attribute defined. * @return True the attribute is defined. False otherwise. */ public boolean hasConstructName(){ return _construct_name != null; } /** * Get the construct name attribute value. * @return Construct name value. Null if the attribute is not defined. */ public String getConstructName(){ return _construct_name; } }
import Model.FuncionarioModel; import Model.HospedeModel; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Scanner; public class Main{ private static Scanner reader = new Scanner(System.in); private static SimpleDateFormat formatter = new SimpleDateFormat("dd-mm-yyyy"); public static void main(String[] args) throws ParseException { int op = -1; do { System.out.println(" \n" + " _ _ _ _ \n" + " | | | | ___ | |_ ___| | _ __ ___ __ _ _ __ __ _ __ _ ___ _ __ \n" + " | |_| |/ _ \\| __/ _ \\ | | '_ ` _ \\ / _` | '_ \\ / _` |/ _` |/ _ \\ '__|\n" + " | _ | (_) | || __/ | | | | | | | (_| | | | | (_| | (_| | __/ | \n" + " |_| |_|\\___/ \\__\\___|_| |_| |_| |_|\\__,_|_| |_|\\__,_|\\__, |\\___|_| \n" + " |___/ \n" + " \n" + "==========================================================================="); System.out.println("=======================| SELECIONE UMA OPO |======================="); System.out.println("==========================================================================="); System.out.println("=======================| [1] Cadastrar hospede |======================="); System.out.println("=======================| [2] Realizar reserva |======================="); System.out.println("=======================| [3] Fazer check-in |======================="); System.out.println("=======================| [4] Fazer check-out |======================="); System.out.println("=======================| [5] Cadastrar funcionrio |======================="); System.out.println("=======================| [6] Cadastrar quarto |======================="); System.out.println("=======================| [7] Calcular despesas |======================="); System.out.println("=======================| [0] SAIR |======================="); System.out.println("==========================================================================="); System.out.print("Digite a opo: "); op=reader.nextInt(); clearConsole(); switch (op){ case 0: break; case 1: cadastrarHospede(); clearConsole(); break; case 5: cadastrarFuncionario(); clearConsole(); break; default: System.out.println("Opo invlida! Pressione enter para digitar uma nova opo."); reader.next(); clearConsole(); break; } }while(op!=0); } private static void clearConsole(){ char c = '\n'; int length = 30; char[] chars = new char[length]; Arrays.fill(chars, c); System.out.print(String.valueOf(chars)); } public static void cadastrarHospede() throws ParseException { HospedeModel hospede = new HospedeModel(); clearConsole(); System.out.print("Nome Completo do Hspede: "); hospede.setNome(reader.next()); System.out.print("CPF: "); hospede.setCpf(reader.nextLong()); System.out.print("Data de nascimento (DD-MM-AAAA): "); hospede.setDataNasc(formatter.parse(reader.next())); System.out.print("Sexo: "); hospede.setSexo(reader.next()); System.out.print("Endereo Completo: "); hospede.setEndereco(reader.next()); System.out.print("Telefone (principal): "); hospede.setTelefone(reader.next()); System.out.print("Hospede estrangeiro? digite 'true' para SIM ou 'false' para NO. "); hospede.setEstrangeiro(reader.nextBoolean()); } public static void cadastrarFuncionario() throws ParseException { FuncionarioModel funcionario = new FuncionarioModel(); clearConsole(); System.out.print("Nome Completo do Funcionrio: "); funcionario.setNome(reader.next()); System.out.print("CPF: "); funcionario.setCpf(reader.nextLong()); System.out.print("Data de nascimento (DD-MM-AAAA): "); funcionario.setDataNasc(formatter.parse(reader.next())); System.out.print("Sexo: "); funcionario.setSexo(reader.next()); System.out.print("Endereo Completo: "); funcionario.setEndereco(reader.next()); System.out.print("Telefone (principal): "); funcionario.setTelefone(reader.next()); System.out.print("Cdigo de Identificao: "); funcionario.setCodigo(reader.nextLong()); System.out.print("Salario"); funcionario.setSalario(reader.nextLong()); System.out.print(" administrador do Sistema? digite 'true' para SIM ou 'false' para NO. "); funcionario.setAdmin(reader.nextBoolean()); } }
package jolie.net; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.server.rpc.RPC; import com.google.gwt.user.server.rpc.RPCRequest; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.StringReader; import java.net.URI; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Base64; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import jolie.Interpreter; import jolie.js.JsUtils; import jolie.lang.Constants; import jolie.lang.NativeType; import jolie.net.http.HttpMessage; import jolie.net.http.HttpParser; import jolie.net.http.HttpUtils; import jolie.net.http.Method; import jolie.net.http.MultiPartFormDataParser; import jolie.net.ports.Interface; import jolie.net.protocols.CommProtocol; import jolie.runtime.ByteArray; import jolie.runtime.Value; import jolie.runtime.ValueVector; import jolie.runtime.VariablePath; import jolie.runtime.typing.OneWayTypeDescription; import jolie.runtime.typing.OperationTypeDescription; import jolie.runtime.typing.RequestResponseTypeDescription; import jolie.runtime.typing.Type; import jolie.runtime.typing.TypeCastingException; import jolie.util.LocationParser; import jolie.xml.XmlUtils; import joliex.gwt.client.JolieService; import joliex.gwt.server.JolieGWTConverter; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * HTTP protocol implementation * @author Fabrizio Montesi * 14 Nov 2012 - Saverio Giallorenzo - Fabrizio Montesi: support for status codes */ public class HttpProtocol extends CommProtocol implements HttpUtils.HttpProtocol { private static final int DEFAULT_STATUS_CODE = 200; private static final int DEFAULT_REDIRECTION_STATUS_CODE = 303; private static final String DEFAULT_CONTENT_TYPE = "application/octet-stream"; // default content type per RFC 2616#7.2.1 private static final String DEFAULT_FORMAT = "xml"; private static final Map< Integer, String > statusCodeDescriptions = new HashMap<>(); private static final Set< Integer > locationRequiredStatusCodes = new HashSet<>(); static { locationRequiredStatusCodes.add( 301 ); locationRequiredStatusCodes.add( 302 ); locationRequiredStatusCodes.add( 303 ); locationRequiredStatusCodes.add( 307 ); locationRequiredStatusCodes.add( 308 ); } static { // Initialise the HTTP Status code map. statusCodeDescriptions.put( 100,"Continue" ); statusCodeDescriptions.put( 101,"Switching Protocols" ); statusCodeDescriptions.put( 102,"Processing" ); statusCodeDescriptions.put( 200,"OK" ); statusCodeDescriptions.put( 201,"Created" ); statusCodeDescriptions.put( 202,"Accepted" ); statusCodeDescriptions.put( 203,"Non-Authoritative Information" ); statusCodeDescriptions.put( 204,"No Content" ); statusCodeDescriptions.put( 205,"Reset Content" ); statusCodeDescriptions.put( 206,"Partial Content" ); statusCodeDescriptions.put( 207,"Multi-Status" ); statusCodeDescriptions.put( 208,"Already Reported" ); statusCodeDescriptions.put( 226,"IM Used" ); statusCodeDescriptions.put( 300,"Multiple Choices" ); statusCodeDescriptions.put( 301,"Moved Permanently" ); statusCodeDescriptions.put( 302,"Found" ); statusCodeDescriptions.put( 303,"See Other" ); statusCodeDescriptions.put( 304,"Not Modified" ); statusCodeDescriptions.put( 305,"Use Proxy" ); statusCodeDescriptions.put( 306,"Reserved" ); statusCodeDescriptions.put( 307,"Temporary Redirect" ); statusCodeDescriptions.put( 308,"Permanent Redirect" ); statusCodeDescriptions.put( 400,"Bad Request" ); statusCodeDescriptions.put( 401,"Unauthorized" ); statusCodeDescriptions.put( 402,"Payment Required" ); statusCodeDescriptions.put( 403,"Forbidden" ); statusCodeDescriptions.put( 404,"Not Found" ); statusCodeDescriptions.put( 405,"Method Not Allowed" ); statusCodeDescriptions.put( 406,"Not Acceptable" ); statusCodeDescriptions.put( 407,"Proxy Authentication Required" ); statusCodeDescriptions.put( 408,"Request Timeout" ); statusCodeDescriptions.put( 409,"Conflict" ); statusCodeDescriptions.put( 410,"Gone" ); statusCodeDescriptions.put( 411,"Length Required" ); statusCodeDescriptions.put( 412,"Precondition Failed" ); statusCodeDescriptions.put( 413,"Request Entity Too Large" ); statusCodeDescriptions.put( 414,"Request-URI Too Long" ); statusCodeDescriptions.put( 415,"Unsupported Media Type" ); statusCodeDescriptions.put( 416,"Requested Range Not Satisfiable" ); statusCodeDescriptions.put( 417,"Expectation Failed" ); statusCodeDescriptions.put( 422,"Unprocessable Entity" ); statusCodeDescriptions.put( 423,"Locked" ); statusCodeDescriptions.put( 424,"Failed Dependency" ); statusCodeDescriptions.put( 426,"Upgrade Required" ); statusCodeDescriptions.put( 427,"Unassigned" ); statusCodeDescriptions.put( 428,"Precondition Required" ); statusCodeDescriptions.put( 429,"Too Many Requests" ); statusCodeDescriptions.put( 430,"Unassigned" ); statusCodeDescriptions.put( 431,"Request Header Fields Too Large" ); statusCodeDescriptions.put( 500,"Internal Server Error" ); statusCodeDescriptions.put( 501,"Not Implemented" ); statusCodeDescriptions.put( 502,"Bad Gateway" ); statusCodeDescriptions.put( 503,"Service Unavailable" ); statusCodeDescriptions.put( 504,"Gateway Timeout" ); statusCodeDescriptions.put( 505,"HTTP Version Not Supported" ); statusCodeDescriptions.put( 507,"Insufficient Storage" ); statusCodeDescriptions.put( 508,"Loop Detected" ); statusCodeDescriptions.put( 509,"Unassigned" ); statusCodeDescriptions.put( 510,"Not Extended" ); statusCodeDescriptions.put( 511,"Network Authentication Required" ); } private static class Parameters { private static final String KEEP_ALIVE = "keepAlive"; private static final String DEBUG = "debug"; private static final String COOKIES = "cookies"; private static final String METHOD = "method"; private static final String ALIAS = "alias"; private static final String MULTIPART_HEADERS = "multipartHeaders"; private static final String CONCURRENT = "concurrent"; private static final String USER_AGENT = "userAgent"; private static final String HOST = "host"; private static final String HEADERS = "headers"; private static final String ADD_HEADERS = "addHeader"; private static final String STATUS_CODE = "statusCode"; private static final String REDIRECT = "redirect"; private static final String DEFAULT_OPERATION = "default"; private static final String COMPRESSION = "compression"; private static final String COMPRESSION_TYPES = "compressionTypes"; private static final String REQUEST_COMPRESSION = "requestCompression"; private static final String FORMAT = "format"; private static final String JSON_ENCODING = "json_encoding"; private static final String REQUEST_USER = "request"; private static final String RESPONSE_USER = "response"; private static final String HEADER_USER = "headers"; private static final String CHARSET = "charset"; private static final String CONTENT_TYPE = "contentType"; private static final String CONTENT_TRANSFER_ENCODING = "contentTransferEncoding"; private static final String CONTENT_DISPOSITION = "contentDisposition"; private static final String DROP_URI_PATH = "dropURIPath"; private static final String CACHE_CONTROL = "cacheControl"; private static class MultiPartHeaders { private static final String FILENAME = "filename"; } } private static class Headers { private static final String JOLIE_MESSAGE_ID = "X-Jolie-MessageID"; } private static class ContentTypes { private static final String APPLICATION_JSON = "application/json"; } private String inputId = null; private final Transformer transformer; private final DocumentBuilderFactory docBuilderFactory; private final DocumentBuilder docBuilder; private final URI uri; private final boolean inInputPort; private MultiPartFormDataParser multiPartFormDataParser = null; @Override public String name() { return "http"; } @Override public boolean isThreadSafe() { return checkBooleanParameter( Parameters.CONCURRENT ); } public HttpProtocol( VariablePath configurationPath, URI uri, boolean inInputPort, TransformerFactory transformerFactory, DocumentBuilderFactory docBuilderFactory, DocumentBuilder docBuilder ) throws TransformerConfigurationException { super( configurationPath ); this.uri = uri; this.inInputPort = inInputPort; this.transformer = transformerFactory.newTransformer(); this.docBuilderFactory = docBuilderFactory; this.docBuilder = docBuilder; transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" ); transformer.setOutputProperty( OutputKeys.INDENT, "no" ); } public String getMultipartHeaderForPart( String operationName, String partName ) { if ( hasOperationSpecificParameter( operationName, Parameters.MULTIPART_HEADERS ) ) { Value v = getOperationSpecificParameterFirstValue( operationName, Parameters.MULTIPART_HEADERS ); if ( v.hasChildren( partName ) ) { v = v.getFirstChild( partName ); if ( v.hasChildren( Parameters.MultiPartHeaders.FILENAME ) ) { v = v.getFirstChild( Parameters.MultiPartHeaders.FILENAME ); return v.strValue(); } } } return null; } private final static String BOUNDARY = "----jol13h77p77bound4r155"; private void send_appendCookies( CommMessage message, String hostname, StringBuilder headerBuilder ) { Value cookieParam = null; if ( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) { cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES ); } else if ( hasParameter( Parameters.COOKIES ) ) { cookieParam = getParameterFirstValue( Parameters.COOKIES ); } if ( cookieParam != null ) { Value cookieConfig; String domain; StringBuilder cookieSB = new StringBuilder(); for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) { cookieConfig = entry.getValue().first(); if ( message.value().hasChildren( cookieConfig.strValue() ) ) { domain = cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : ""; if ( domain.isEmpty() || hostname.endsWith( domain ) ) { cookieSB .append( entry.getKey() ) .append( '=' ) .append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() ) .append( ";" ); } } } if ( cookieSB.length() > 0 ) { headerBuilder .append( "Cookie: " ) .append( cookieSB ) .append( HttpUtils.CRLF ); } } } private void send_appendSetCookieHeader( CommMessage message, StringBuilder headerBuilder ) { Value cookieParam = null; if ( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) { cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES ); } else if ( hasParameter( Parameters.COOKIES ) ) { cookieParam = getParameterFirstValue( Parameters.COOKIES ); } if ( cookieParam != null ) { Value cookieConfig; for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) { cookieConfig = entry.getValue().first(); if ( message.value().hasChildren( cookieConfig.strValue() ) ) { headerBuilder .append( "Set-Cookie: " ) .append( entry.getKey() ).append( '=' ) .append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() ) .append( "; expires=" ) .append( cookieConfig.hasChildren( "expires" ) ? cookieConfig.getFirstChild( "expires" ).strValue() : "" ) .append( "; domain=" ) .append( cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : "" ) .append( "; path=" ) .append( cookieConfig.hasChildren( "path" ) ? cookieConfig.getFirstChild( "path" ).strValue() : "" ); if ( cookieConfig.hasChildren( "secure" ) && cookieConfig.getFirstChild( "secure" ).intValue() > 0 ) { headerBuilder.append( "; secure" ); } headerBuilder.append( HttpUtils.CRLF ); } } } } private String encoding = null; private String responseFormat = null; private boolean headRequest = false; private static void send_appendQuerystring( Value value, StringBuilder headerBuilder ) throws IOException { if ( !value.children().isEmpty() ) { headerBuilder.append( '?' ); for( Entry< String, ValueVector > entry : value.children().entrySet() ) { for( Value v : entry.getValue() ) { headerBuilder .append( URLEncoder.encode( entry.getKey(), HttpUtils.URL_DECODER_ENC ) ) .append( '=' ) .append( URLEncoder.encode( v.strValue(), HttpUtils.URL_DECODER_ENC ) ) .append( '&' ); } } } } private void send_appendJsonQueryString( CommMessage message, StringBuilder headerBuilder ) throws IOException { if ( message.value().isDefined() || message.value().hasChildren() ) { headerBuilder.append( "?" ); StringBuilder builder = new StringBuilder(); JsUtils.valueToJsonString( message.value(), true, getSendType( message ), builder ); headerBuilder.append( URLEncoder.encode( builder.toString(), HttpUtils.URL_DECODER_ENC ) ); } } private static void send_appendParsedAlias( String alias, Value value, StringBuilder headerBuilder ) throws IOException { int offset = 0; List< String > aliasKeys = new ArrayList<>(); String currStrValue; String currKey; StringBuilder result = new StringBuilder( alias ); Matcher m = Pattern.compile( "%(!)?\\{[^\\}]*\\}" ).matcher( alias ); while( m.find() ) { int displacement = 2; if ( m.group( 1 ) == null ) { // ! is missing after %: We have to use URLEncoder currKey = alias.substring( m.start() + displacement, m.end() - 1 ); if ( "$".equals( currKey ) ) { currStrValue = URLEncoder.encode( value.strValue(), HttpUtils.URL_DECODER_ENC ); } else { currStrValue = URLEncoder.encode( value.getFirstChild( currKey ).strValue(), HttpUtils.URL_DECODER_ENC ); aliasKeys.add( currKey ); } } else { // ! is given after %: We have to insert the string raw displacement = 3; currKey = alias.substring( m.start() + displacement, m.end() - 1 ); if ( "$".equals( currKey ) ) { currStrValue = value.strValue(); } else { currStrValue = value.getFirstChild( currKey ).strValue(); aliasKeys.add( currKey ); } } result.replace( m.start() + offset, m.end() + offset, currStrValue ); displacement++; //considering also } offset += currStrValue.length() - displacement - currKey.length(); } // removing used keys for( String aliasKey : aliasKeys ) { value.children().remove( aliasKey ); } headerBuilder.append( result ); } private String send_getFormat() { String format = DEFAULT_FORMAT; if ( inInputPort && responseFormat != null ) { format = responseFormat; responseFormat = null; } else if ( hasParameter( Parameters.FORMAT ) ) { format = getStringParameter( Parameters.FORMAT ); } return format; } private static class EncodedContent { private ByteArray content = null; private String contentType = DEFAULT_CONTENT_TYPE; private String contentDisposition = ""; } private EncodedContent send_encodeContent( CommMessage message, Method method, String charset, String format ) throws IOException { EncodedContent ret = new EncodedContent(); if ( inInputPort == false && method == Method.GET ) { // We are building a GET request return ret; } if ( "xml".equals( format ) ) { ret.contentType = "text/xml"; Document doc = docBuilder.newDocument(); Element root = doc.createElement( message.operationName() + (( inInputPort ) ? "Response" : "") ); doc.appendChild( root ); if ( message.isFault() ) { Element faultElement = doc.createElement( message.fault().faultName() ); root.appendChild( faultElement ); XmlUtils.valueToDocument( message.fault().value(), faultElement, doc ); } else { XmlUtils.valueToDocument( message.value(), root, doc ); } Source src = new DOMSource( doc ); ByteArrayOutputStream tmpStream = new ByteArrayOutputStream(); Result dest = new StreamResult( tmpStream ); transformer.setOutputProperty( OutputKeys.ENCODING, charset ); try { transformer.transform( src, dest ); } catch( TransformerException e ) { throw new IOException( e ); } ret.content = new ByteArray( tmpStream.toByteArray() ); } else if ( "binary".equals( format ) ) { ret.contentType = "application/octet-stream"; ret.content = message.value().byteArrayValue(); } else if ( "html".equals( format ) ) { ret.contentType = "text/html"; if ( message.isFault() ) { StringBuilder builder = new StringBuilder(); builder.append( "<html><head><title>" ); builder.append( message.fault().faultName() ); builder.append( "</title></head><body>" ); builder.append( message.fault().value().strValue() ); builder.append( "</body></html>" ); ret.content = new ByteArray( builder.toString().getBytes( charset ) ); } else { ret.content = new ByteArray( message.value().strValue().getBytes( charset ) ); } } else if ( "multipart/form-data".equals( format ) ) { ret.contentType = "multipart/form-data; boundary=" + BOUNDARY; ByteArrayOutputStream bStream = new ByteArrayOutputStream(); StringBuilder builder = new StringBuilder(); for( Entry< String, ValueVector > entry : message.value().children().entrySet() ) { if ( !entry.getKey().startsWith( "@" ) ) { builder.append( "--" ).append( BOUNDARY ).append( HttpUtils.CRLF ); builder.append( "Content-Disposition: form-data; name=\"" ).append( entry.getKey() ).append( '\"' ); boolean isBinary = false; if ( hasOperationSpecificParameter( message.operationName(), Parameters.MULTIPART_HEADERS ) ) { Value specOpParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.MULTIPART_HEADERS ); if ( specOpParam.hasChildren( "partName" ) ) { ValueVector partNames = specOpParam.getChildren( "partName" ); for( int p = 0; p < partNames.size(); p++ ) { if ( partNames.get( p ).hasChildren( "part" ) ) { if ( partNames.get( p ).getFirstChild( "part" ).strValue().equals( entry.getKey() ) ) { isBinary = true; if ( partNames.get( p ).hasChildren( "filename" ) ) { builder.append( "; filename=\"" ).append( partNames.get( p ).getFirstChild( "filename" ).strValue() ).append( "\"" ); } if ( partNames.get( p ).hasChildren( "contentType" ) ) { builder.append( HttpUtils.CRLF ).append( "Content-Type:" ).append( partNames.get( p ).getFirstChild( "contentType" ).strValue() ); } } } } } } builder.append( HttpUtils.CRLF ).append( HttpUtils.CRLF ); if ( isBinary ) { bStream.write( builder.toString().getBytes( charset ) ); bStream.write( entry.getValue().first().byteArrayValue().getBytes() ); builder.delete( 0, builder.length() - 1 ); builder.append( HttpUtils.CRLF ); } else { builder.append( entry.getValue().first().strValue() ).append( HttpUtils.CRLF ); } } } builder.append( "--" + BOUNDARY + "--" ); bStream.write( builder.toString().getBytes( charset )); ret.content = new ByteArray( bStream.toByteArray() ); } else if ( "x-www-form-urlencoded".equals( format ) ) { ret.contentType = "application/x-www-form-urlencoded"; Iterator< Entry< String, ValueVector > > it = message.value().children().entrySet().iterator(); StringBuilder builder = new StringBuilder(); if ( message.isFault() ) { builder.append( "faultName=" ); builder.append( URLEncoder.encode( message.fault().faultName(), HttpUtils.URL_DECODER_ENC ) ); builder.append( "&data=" ); builder.append( URLEncoder.encode( message.fault().value().strValue(), HttpUtils.URL_DECODER_ENC ) ); } else { Entry< String, ValueVector > entry; while( it.hasNext() ) { entry = it.next(); builder.append( URLEncoder.encode( entry.getKey(), HttpUtils.URL_DECODER_ENC ) ) .append( "=" ) .append( URLEncoder.encode( entry.getValue().first().strValue(), HttpUtils.URL_DECODER_ENC ) ); if ( it.hasNext() ) { builder.append( '&' ); } } } ret.content = new ByteArray( builder.toString().getBytes( charset ) ); } else if ( "text/x-gwt-rpc".equals( format ) ) { ret.contentType = "text/x-gwt-rpc"; try { if ( inInputPort ) { // It's a response if ( message.isFault() ) { ret.content = new ByteArray( RPC.encodeResponseForFailure( JolieService.class.getMethods()[0], JolieGWTConverter.jolieToGwtFault( message.fault() ) ).getBytes( charset ) ); } else { joliex.gwt.client.Value v = new joliex.gwt.client.Value(); JolieGWTConverter.jolieToGwtValue( message.value(), v ); ret.content = new ByteArray( RPC.encodeResponseForSuccess( JolieService.class.getMethods()[0], v ).getBytes( charset ) ); } } else { // It's a request throw new IOException( "Sending requests to a GWT server is currently unsupported." ); } } catch( SerializationException e ) { throw new IOException( e ); } } else if ( "json".equals( format ) ) { ret.contentType = ContentTypes.APPLICATION_JSON; StringBuilder jsonStringBuilder = new StringBuilder(); if ( message.isFault() ) { Value error = message.value().getFirstChild( "error" ); error.getFirstChild( "code" ).setValue( -32000 ); error.getFirstChild( "message" ).setValue( message.fault().faultName() ); error.getChildren( "data" ).set( 0, message.fault().value() ); JsUtils.faultValueToJsonString( message.value(), getSendType( message ), jsonStringBuilder ); } else { JsUtils.valueToJsonString( message.value(), true, getSendType( message ), jsonStringBuilder ); } ret.content = new ByteArray( jsonStringBuilder.toString().getBytes( charset ) ); } else if ( "raw".equals( format ) ) { ret.contentType = "text/plain"; if ( message.isFault() ) { ret.content = new ByteArray( message.fault().value().strValue().getBytes( charset ) ); } else { ret.content = new ByteArray( message.value().strValue().getBytes( charset ) ); } } return ret; } private static boolean isLocationNeeded( int statusCode ) { return locationRequiredStatusCodes.contains( statusCode ); } private void send_appendResponseUserHeader( CommMessage message, StringBuilder headerBuilder ) { Value responseHeaderParameters = null; if ( hasOperationSpecificParameter(message.operationName(), Parameters.RESPONSE_USER) ) { responseHeaderParameters = getOperationSpecificParameterFirstValue(message.operationName(), Parameters.RESPONSE_USER); if ( ( responseHeaderParameters != null ) && ( responseHeaderParameters.hasChildren(Parameters.HEADER_USER) ) ) { for ( Entry< String, ValueVector > entry : responseHeaderParameters.getFirstChild(Parameters.HEADER_USER).children().entrySet() ) headerBuilder.append( entry.getKey() ).append(": ").append( entry.getValue().first().strValue() ).append( HttpUtils.CRLF ); } } responseHeaderParameters = null; if ( hasParameter(Parameters.RESPONSE_USER) ) { responseHeaderParameters = getParameterFirstValue(Parameters.RESPONSE_USER); if ( ( responseHeaderParameters != null ) && ( responseHeaderParameters.hasChildren(Parameters.HEADER_USER) ) ) { for ( Entry< String, ValueVector > entry : responseHeaderParameters.getFirstChild(Parameters.HEADER_USER).children().entrySet() ) headerBuilder.append( entry.getKey() ).append(": ").append( entry.getValue().first().strValue() ).append( HttpUtils.CRLF ); } } } private void send_appendResponseHeaders( CommMessage message, StringBuilder headerBuilder ) { int statusCode = DEFAULT_STATUS_CODE; String statusDescription = null; if( hasParameter( Parameters.STATUS_CODE ) ) { statusCode = getIntParameter( Parameters.STATUS_CODE ); if ( !statusCodeDescriptions.containsKey( statusCode ) ) { Interpreter.getInstance().logWarning( "HTTP protocol for operation " + message.operationName() + " is sending a message with status code " + statusCode + ", which is not in the HTTP specifications." ); statusDescription = "Internal Server Error"; } else if ( isLocationNeeded( statusCode ) && !hasParameter( Parameters.REDIRECT ) ) { // if statusCode is a redirection code, location parameter is needed Interpreter.getInstance().logWarning( "HTTP protocol for operation " + message.operationName() + " is sending a message with status code " + statusCode + ", which expects a redirect parameter but the latter is not set." ); } } else if ( hasParameter( Parameters.REDIRECT ) ) { statusCode = DEFAULT_REDIRECTION_STATUS_CODE; } if ( statusDescription == null ) { statusDescription = statusCodeDescriptions.get( statusCode ); } headerBuilder.append( "HTTP/1.1 " + statusCode + " " + statusDescription + HttpUtils.CRLF ); // if redirect has been set, the redirect location parameter is set if ( hasParameter( Parameters.REDIRECT ) ) { headerBuilder.append( "Location: " + getStringParameter( Parameters.REDIRECT ) + HttpUtils.CRLF ); } send_appendSetCookieHeader( message, headerBuilder ); headerBuilder.append( "Server: Jolie" ).append( HttpUtils.CRLF ); StringBuilder cacheControlHeader = new StringBuilder(); if ( hasParameter( Parameters.CACHE_CONTROL ) ) { Value cacheControl = getParameterFirstValue( Parameters.CACHE_CONTROL ); if ( cacheControl.hasChildren( "maxAge" ) ) { cacheControlHeader.append( "max-age=" ).append( cacheControl.getFirstChild( "maxAge" ).intValue() ); } } if ( cacheControlHeader.length() > 0 ) { headerBuilder.append( "Cache-Control: " ).append( cacheControlHeader ).append( HttpUtils.CRLF ); } } private static void send_appendRequestMethod( Method method, StringBuilder headerBuilder ) { headerBuilder.append( method.id() ); } private void send_appendRequestPath( CommMessage message, Method method, String qsFormat, StringBuilder headerBuilder ) throws IOException { String path = uri.getRawPath(); if ( path == null || path.isEmpty() || checkBooleanParameter( Parameters.DROP_URI_PATH, false ) ) { headerBuilder.append( '/' ); } else { if ( path.charAt( 0 ) != '/' ) { headerBuilder.append( '/' ); } headerBuilder.append( path ); } if ( hasOperationSpecificParameter( message.operationName(), Parameters.ALIAS ) ) { String alias = getOperationSpecificStringParameter( message.operationName(), Parameters.ALIAS ); send_appendParsedAlias( alias, message.value(), headerBuilder ); } else { headerBuilder.append( message.operationName() ); } if ( method == Method.GET ) { if ( qsFormat.equals( "json" ) ) { send_appendJsonQueryString( message, headerBuilder ); } else { send_appendQuerystring( message.value(), headerBuilder ); } } } private static void send_appendAuthorizationHeader( CommMessage message, StringBuilder headerBuilder ) { if ( message.value().hasChildren( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ) ) { Value v = message.value().getFirstChild( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ); //String realm = v.getFirstChild( "realm" ).strValue(); String userpass = v.getFirstChild( "userid" ).strValue() + ":" + v.getFirstChild( "password" ).strValue(); Base64.Encoder encoder = Base64.getEncoder(); userpass = encoder.encodeToString( userpass.getBytes() ); headerBuilder.append( "Authorization: Basic " ).append( userpass ).append( HttpUtils.CRLF ); } } private void send_appendRequestUserHeader( CommMessage message, StringBuilder headerBuilder ) { Value responseHeaderParameters = null; if ( hasOperationSpecificParameter(message.operationName(), Parameters.REQUEST_USER ) ) { responseHeaderParameters = getOperationSpecificParameterFirstValue(message.operationName(), Parameters.RESPONSE_USER); if ( ( responseHeaderParameters != null ) && ( responseHeaderParameters.hasChildren(Parameters.HEADER_USER) ) ) { for ( Entry< String, ValueVector > entry : responseHeaderParameters.getFirstChild(Parameters.HEADER_USER).children().entrySet() ) headerBuilder.append( entry.getKey() ).append(": ").append( entry.getValue().first().strValue() ).append( HttpUtils.CRLF ); } } responseHeaderParameters = null; if ( hasParameter(Parameters.RESPONSE_USER) ){ responseHeaderParameters = getParameterFirstValue(Parameters.REQUEST_USER); if ( ( responseHeaderParameters != null ) && ( responseHeaderParameters.hasChildren(Parameters.HEADER_USER) ) ) { for ( Entry< String, ValueVector > entry : responseHeaderParameters.getFirstChild(Parameters.HEADER_USER).children().entrySet() ) headerBuilder.append( entry.getKey() ).append(": ").append( entry.getValue().first().strValue() ).append( HttpUtils.CRLF ); } } } private void send_appendHeader( StringBuilder headerBuilder ) { Value v = getParameterFirstValue( Parameters.ADD_HEADERS ); if ( v != null ) { if ( v.hasChildren( "header" ) ) { for( Value head : v.getChildren( "header" ) ) { String header = head.strValue() + ": " + head.getFirstChild( "value" ).strValue(); headerBuilder.append( header ).append( HttpUtils.CRLF ); } } } } private Method send_getRequestMethod( CommMessage message ) throws IOException { Method method = hasOperationSpecificParameter( message.operationName(), Parameters.METHOD ) ? Method.fromString( getOperationSpecificStringParameter( message.operationName(), Parameters.METHOD ) ) : hasParameterValue( Parameters.METHOD ) ? Method.fromString( getStringParameter( Parameters.METHOD ) ) : Method.POST; return method; } private void send_appendRequestHeaders( CommMessage message, Method method, String qsFormat, StringBuilder headerBuilder ) throws IOException { send_appendRequestMethod( method, headerBuilder ); headerBuilder.append( ' ' ); send_appendRequestPath( message, method, qsFormat, headerBuilder ); headerBuilder.append( " HTTP/1.1" + HttpUtils.CRLF ); headerBuilder.append( "Host: " + uri.getHost() + HttpUtils.CRLF ); send_appendCookies( message, uri.getHost(), headerBuilder ); send_appendAuthorizationHeader( message, headerBuilder ); if ( checkBooleanParameter( Parameters.COMPRESSION, true ) ) { String requestCompression = getStringParameter( Parameters.REQUEST_COMPRESSION ); if ( requestCompression.equals( "gzip" ) || requestCompression.equals( "deflate" ) ) { encoding = requestCompression; headerBuilder.append( "Accept-Encoding: " + encoding + HttpUtils.CRLF ); } else { headerBuilder.append( "Accept-Encoding: gzip, deflate" + HttpUtils.CRLF ); } } send_appendHeader( headerBuilder ); } private void send_appendGenericHeaders( CommMessage message, EncodedContent encodedContent, String charset, StringBuilder headerBuilder ) throws IOException { if ( checkBooleanParameter( Parameters.KEEP_ALIVE, true ) == false || channel().toBeClosed() ) { channel().setToBeClosed( true ); headerBuilder.append( "Connection: close" + HttpUtils.CRLF ); } if ( checkBooleanParameter( Parameters.CONCURRENT, true ) ) { headerBuilder.append( Headers.JOLIE_MESSAGE_ID ).append( ": " ).append( message.id() ).append( HttpUtils.CRLF ); } String contentType = getStringParameter( Parameters.CONTENT_TYPE ); if ( contentType.length() > 0 ) { encodedContent.contentType = contentType; } encodedContent.contentType = encodedContent.contentType.toLowerCase(); headerBuilder.append( "Content-Type: " + encodedContent.contentType ); if ( charset != null ) { headerBuilder.append( "; charset=" + charset.toLowerCase() ); } headerBuilder.append( HttpUtils.CRLF ); if ( encodedContent.content != null ) { String transferEncoding = getStringParameter( Parameters.CONTENT_TRANSFER_ENCODING ); if ( transferEncoding.length() > 0 ) { headerBuilder.append( "Content-Transfer-Encoding: " + transferEncoding + HttpUtils.CRLF ); } String contentDisposition = getStringParameter( Parameters.CONTENT_DISPOSITION ); if ( contentDisposition.length() > 0 ) { encodedContent.contentDisposition = contentDisposition; headerBuilder.append( "Content-Disposition: " + encodedContent.contentDisposition + HttpUtils.CRLF ); } boolean compression = encoding != null && checkBooleanParameter( Parameters.COMPRESSION, true ); String compressionTypes = getStringParameter( Parameters.COMPRESSION_TYPES, "text/html text/css text/plain text/xml text/x-js text/x-gwt-rpc application/json application/javascript application/x-www-form-urlencoded application/xhtml+xml application/xml" ).toLowerCase(); if ( compression && !compressionTypes.equals( "*" ) && !compressionTypes.contains( encodedContent.contentType ) ) { compression = false; } if ( compression ) { encodedContent.content = HttpUtils.encode( encoding, encodedContent.content, headerBuilder ); } headerBuilder.append( "Content-Length: " + encodedContent.content.size() + HttpUtils.CRLF ); } else { headerBuilder.append( "Content-Length: 0" + HttpUtils.CRLF ); } } private void send_logDebugInfo( CharSequence header, EncodedContent encodedContent, String charset ) throws IOException { if ( checkBooleanParameter( Parameters.DEBUG ) ) { StringBuilder debugSB = new StringBuilder(); debugSB.append( "[HTTP debug] Sending:\n" ); debugSB.append( header ); if ( getParameterVector( Parameters.DEBUG ).first().getFirstChild( "showContent" ).intValue() > 0 && encodedContent.content != null ) { debugSB.append( encodedContent.content.toString( charset ) ); } Interpreter.getInstance().logInfo( debugSB.toString() ); } } public void send_internal( OutputStream ostream, CommMessage message, InputStream istream ) throws IOException { Method method = send_getRequestMethod( message ); String charset = HttpUtils.getCharset( getStringParameter( Parameters.CHARSET, "utf-8" ), null ); String format = send_getFormat(); EncodedContent encodedContent = send_encodeContent( message, method, charset, format ); StringBuilder headerBuilder = new StringBuilder(); if ( inInputPort ) { // We're responding to a request send_appendResponseHeaders( message, headerBuilder ); send_appendResponseUserHeader(message, headerBuilder); } else { // We're sending a notification or a solicit String qsFormat = ""; if ( method == Method.GET && getParameterFirstValue( Parameters.METHOD ).hasChildren( "queryFormat" ) ) { if ( getParameterFirstValue( Parameters.METHOD ).getFirstChild( "queryFormat" ).strValue().equals( "json" ) ) { qsFormat = format = "json"; encodedContent.contentType = ContentTypes.APPLICATION_JSON; } } send_appendRequestUserHeader(message, headerBuilder); send_appendRequestHeaders( message, method, qsFormat, headerBuilder ); } send_appendGenericHeaders( message, encodedContent, charset, headerBuilder ); headerBuilder.append( HttpUtils.CRLF ); send_logDebugInfo( headerBuilder, encodedContent, charset ); inputId = message.operationName(); ostream.write( headerBuilder.toString().getBytes( HttpUtils.URL_DECODER_ENC ) ); if ( encodedContent.content != null && !headRequest ) { ostream.write( encodedContent.content.getBytes() ); } headRequest = false; } @Override public void send( OutputStream ostream, CommMessage message, InputStream istream ) throws IOException { HttpUtils.send( ostream, message, istream, inInputPort, channel(), this ); } private void parseXML( HttpMessage message, Value value, String charset ) throws IOException { try { if ( message.size() > 0 ) { DocumentBuilder builder = docBuilderFactory.newDocumentBuilder(); InputSource src = new InputSource( new ByteArrayInputStream( message.content() ) ); src.setEncoding( charset ); Document doc = builder.parse( src ); XmlUtils.documentToValue( doc, value ); } } catch( ParserConfigurationException pce ) { throw new IOException( pce ); } catch( SAXException saxe ) { throw new IOException( saxe ); } } private static void parseJson( HttpMessage message, Value value, boolean strictEncoding, String charset ) throws IOException { JsUtils.parseJsonIntoValue( new InputStreamReader( new ByteArrayInputStream( message.content() ), charset ), value, strictEncoding ); } private static void parseForm( HttpMessage message, Value value, String charset ) throws IOException { String line = new String( message.content(), charset ); String[] pair; for( String item : line.split( "&" ) ) { pair = item.split( "=", 2 ); if ( pair.length > 1 ) { value.getChildren( URLDecoder.decode( pair[0], HttpUtils.URL_DECODER_ENC ) ).first().setValue( URLDecoder.decode( pair[1], HttpUtils.URL_DECODER_ENC ) ); } } } private void parseMultiPartFormData( HttpMessage message, Value value, String charset ) throws IOException { multiPartFormDataParser = new MultiPartFormDataParser( message, value ); multiPartFormDataParser.parse(); } private static String parseGWTRPC( HttpMessage message, Value value, String charset ) throws IOException { RPCRequest request = RPC.decodeRequest( new String( message.content(), charset ) ); String operationName = (String)request.getParameters()[0]; joliex.gwt.client.Value requestValue = (joliex.gwt.client.Value)request.getParameters()[1]; JolieGWTConverter.gwtToJolieValue( requestValue, value ); return operationName; } private void recv_checkForSetCookie( HttpMessage message, Value value ) throws IOException { if ( hasParameter( Parameters.COOKIES ) ) { String type; Value cookies = getParameterFirstValue( Parameters.COOKIES ); Value cookieConfig; Value v; for( HttpMessage.Cookie cookie : message.setCookies() ) { if ( cookies.hasChildren( cookie.name() ) ) { cookieConfig = cookies.getFirstChild( cookie.name() ); if ( cookieConfig.isString() ) { v = value.getFirstChild( cookieConfig.strValue() ); type = cookieConfig.hasChildren( "type" ) ? cookieConfig.getFirstChild( "type" ).strValue() : "string"; recv_assignCookieValue( cookie.value(), v, type ); } } /*currValue = Value.create(); currValue.getNewChild( "expires" ).setValue( cookie.expirationDate() ); currValue.getNewChild( "path" ).setValue( cookie.path() ); currValue.getNewChild( "name" ).setValue( cookie.name() ); currValue.getNewChild( "value" ).setValue( cookie.value() ); currValue.getNewChild( "domain" ).setValue( cookie.domain() ); currValue.getNewChild( "secure" ).setValue( (cookie.secure() ? 1 : 0) ); cookieVec.add( currValue );*/ } } } private static void recv_assignCookieValue( String cookieValue, Value value, String typeKeyword ) throws IOException { NativeType type = NativeType.fromString( typeKeyword ); if ( NativeType.INT == type ) { try { value.setValue( new Integer( cookieValue ) ); } catch( NumberFormatException e ) { throw new IOException( e ); } } else if ( NativeType.LONG == type ) { try { value.setValue( new Long( cookieValue ) ); } catch( NumberFormatException e ) { throw new IOException( e ); } } else if ( NativeType.STRING == type ) { value.setValue( cookieValue ); } else if ( NativeType.DOUBLE == type ) { try { value.setValue( new Double( cookieValue ) ); } catch( NumberFormatException e ) { throw new IOException( e ); } } else if ( NativeType.BOOL == type ) { value.setValue( Boolean.valueOf( cookieValue ) ); } else { value.setValue( cookieValue ); } } private void recv_checkForCookies( HttpMessage message, DecodedMessage decodedMessage ) throws IOException { Value cookies = null; if ( hasOperationSpecificParameter( decodedMessage.operationName, Parameters.COOKIES ) ) { cookies = getOperationSpecificParameterFirstValue( decodedMessage.operationName, Parameters.COOKIES ); } else if ( hasParameter( Parameters.COOKIES ) ) { cookies = getParameterFirstValue( Parameters.COOKIES ); } if ( cookies != null ) { Value v; String type; for( Entry< String, String > entry : message.cookies().entrySet() ) { if ( cookies.hasChildren( entry.getKey() ) ) { Value cookieConfig = cookies.getFirstChild( entry.getKey() ); if ( cookieConfig.isString() ) { v = decodedMessage.value.getFirstChild( cookieConfig.strValue() ); if ( cookieConfig.hasChildren( "type" ) ) { type = cookieConfig.getFirstChild( "type" ).strValue(); } else { type = "string"; } recv_assignCookieValue( entry.getValue(), v, type ); } } } } } private void recv_checkForGenericHeader( HttpMessage message, DecodedMessage decodedMessage ) throws IOException { Value headers = null; if ( hasOperationSpecificParameter( decodedMessage.operationName, Parameters.HEADERS ) ) { headers = getOperationSpecificParameterFirstValue( decodedMessage.operationName, Parameters.HEADERS ); } else if ( hasParameter( Parameters.HEADERS ) ) { headers = getParameterFirstValue( Parameters.HEADERS ); } if ( headers != null ) { for( String headerName : headers.children().keySet() ) { String headerAlias = headers.getFirstChild( headerName ).strValue(); headerName = headerName.replace( "_", "-" ); decodedMessage.value.getFirstChild( headerAlias ).setValue( message.getPropertyOrEmptyString( headerName ) ); } } } private static void recv_parseQueryString( HttpMessage message, Value value, String contentType, boolean strictEncoding ) throws IOException { if ( message.isGet() && contentType.equals( ContentTypes.APPLICATION_JSON ) ) { recv_parseJsonQueryString( message, value, strictEncoding ); } else { Map< String, Integer > indexes = new HashMap<>(); String queryString = message.requestPath(); String[] kv = queryString.split( "\\?", 2 ); Integer index; if ( kv.length > 1 ) { queryString = kv[1]; String[] params = queryString.split( "&" ); for( String param : params ) { String[] ikv = param.split( "=", 2 ); if ( ikv.length > 1 ) { index = indexes.get( ikv[0] ); if ( index == null ) { index = 0; indexes.put( ikv[0], index ); } // the query string was already URL decoded by the HttpParser value.getChildren( ikv[0] ).get( index ).setValue( ikv[1] ); indexes.put( ikv[0], index + 1 ); } } } } } private static void recv_parseJsonQueryString( HttpMessage message, Value value, boolean strictEncoding ) throws IOException { String queryString = message.requestPath(); String[] kv = queryString.split( "\\?", 2 ); if ( kv.length > 1 ) { // the query string was already URL decoded by the HttpParser JsUtils.parseJsonIntoValue( new StringReader( kv[1] ), value, strictEncoding ); } } /* * Prints debug information about a received message */ private void recv_logDebugInfo( HttpMessage message, String charset ) throws IOException { StringBuilder debugSB = new StringBuilder(); debugSB.append( "[HTTP debug] Receiving:\n" ); debugSB.append( "HTTP Code: " + message.statusCode() + "\n" ); debugSB.append( "Resource: " + message.requestPath() + "\n" ); debugSB.append( "--> Header properties\n" ); for( Entry< String, String > entry : message.properties() ) { debugSB.append( '\t' + entry.getKey() + ": " + entry.getValue() + '\n' ); } for( HttpMessage.Cookie cookie : message.setCookies() ) { debugSB.append( "\tset-cookie: " + cookie.toString() + '\n' ); } for( Entry< String, String > entry : message.cookies().entrySet() ) { debugSB.append( "\tcookie: " + entry.getKey() + '=' + entry.getValue() + '\n' ); } if ( getParameterFirstValue( Parameters.DEBUG ).getFirstChild( "showContent" ).intValue() > 0 && message.size() > 0 ) { debugSB.append( "--> Message content\n" ); debugSB.append( new String( message.content(), charset ) ); } Interpreter.getInstance().logInfo( debugSB.toString() ); } private void recv_parseRequestFormat( String type ) throws IOException { responseFormat = null; if ( "text/xml".equals( type ) ) { responseFormat = "xml"; } else if ( "text/x-gwt-rpc".equals( type ) ) { responseFormat = "text/x-gwt-rpc"; } else if ( ContentTypes.APPLICATION_JSON.equals( type ) ) { responseFormat = "json"; } } private void recv_parseMessage( HttpMessage message, DecodedMessage decodedMessage, String type, String charset ) throws IOException { if ( "text/html".equals( type ) ) { decodedMessage.value.setValue( new String( message.content(), charset ) ); } else if ( "application/x-www-form-urlencoded".equals( type ) ) { parseForm( message, decodedMessage.value, charset ); } else if ( "text/xml".equals( type ) || type.contains( "xml" ) ) { parseXML( message, decodedMessage.value, charset ); } else if ( "text/x-gwt-rpc".equals( type ) ) { decodedMessage.operationName = parseGWTRPC( message, decodedMessage.value, charset ); } else if ( "multipart/form-data".equals( type ) ) { parseMultiPartFormData( message, decodedMessage.value, charset ); } else if ( "application/octet-stream".equals( type ) || type.startsWith( "image/" ) || "application/zip".equals( type ) ) { decodedMessage.value.setValue( new ByteArray( message.content() ) ); } else if ( ContentTypes.APPLICATION_JSON.equals( type ) || type.contains( "json" ) ) { boolean strictEncoding = checkStringParameter( Parameters.JSON_ENCODING, "strict" ); parseJson( message, decodedMessage.value, strictEncoding, charset ); } else { decodedMessage.value.setValue( new String( message.content(), charset ) ); } } private String getDefaultOperation( HttpMessage.Type t ) { if ( hasParameter( Parameters.DEFAULT_OPERATION ) ) { Value dParam = getParameterFirstValue( Parameters.DEFAULT_OPERATION ); String method = HttpUtils.httpMessageTypeToString( t ); if ( method == null || dParam.hasChildren( method ) == false ) { return dParam.strValue(); } else { return dParam.getFirstChild( method ).strValue(); } } return null; } private void recv_checkReceivingOperation( HttpMessage message, DecodedMessage decodedMessage ) { if ( decodedMessage.operationName == null ) { String requestPath = message.requestPath().split( "\\?", 2 )[0]; decodedMessage.operationName = requestPath.substring( 1 ); Matcher m = LocationParser.RESOURCE_SEPARATOR_PATTERN.matcher( decodedMessage.operationName ); if ( m.find() ) { int resourceStart = m.end(); if ( m.find() ) { decodedMessage.resourcePath = requestPath.substring( resourceStart - 1, m.start() ); decodedMessage.operationName = requestPath.substring( m.end(), requestPath.length() ); } } } if ( decodedMessage.resourcePath.equals( "/" ) && !channel().parentInputPort().canHandleInputOperation( decodedMessage.operationName ) ) { String defaultOpId = getDefaultOperation( message.type() ); if ( defaultOpId != null ) { Value body = decodedMessage.value; decodedMessage.value = Value.create(); decodedMessage.value.getChildren( "data" ).add( body ); decodedMessage.value.getFirstChild( "operation" ).setValue( decodedMessage.operationName ); decodedMessage.value.setFirstChild( "requestUri", message.requestPath() ); if ( message.userAgent() != null ) { decodedMessage.value.getFirstChild( Parameters.USER_AGENT ).setValue( message.userAgent() ); } Value cookies = decodedMessage.value.getFirstChild( "cookies" ); for( Entry< String, String > cookie : message.cookies().entrySet() ) { cookies.getFirstChild( cookie.getKey() ).setValue( cookie.getValue() ); } decodedMessage.operationName = defaultOpId; } } } private void recv_checkForMultiPartHeaders( DecodedMessage decodedMessage ) { if ( multiPartFormDataParser != null ) { String target; for( Entry< String, MultiPartFormDataParser.PartProperties > entry : multiPartFormDataParser.getPartPropertiesSet() ) { if ( entry.getValue().filename() != null ) { target = getMultipartHeaderForPart( decodedMessage.operationName, entry.getKey() ); if ( target != null ) { decodedMessage.value.getFirstChild( target ).setValue( entry.getValue().filename() ); } } } multiPartFormDataParser = null; } } private void recv_checkForMessageProperties( HttpMessage message, DecodedMessage decodedMessage ) throws IOException { recv_checkForCookies( message, decodedMessage ); recv_checkForGenericHeader( message, decodedMessage ); recv_checkForMultiPartHeaders( decodedMessage ); if ( message.userAgent() != null && hasParameter( Parameters.USER_AGENT ) ) { getParameterFirstValue( Parameters.USER_AGENT ).setValue( message.userAgent() ); } if ( getParameterVector( Parameters.HOST ) != null ) { getParameterFirstValue( Parameters.HOST ).setValue( message.getPropertyOrEmptyString( Parameters.HOST ) ); } } private static class DecodedMessage { private String operationName = null; private Value value = Value.create(); private String resourcePath = "/"; private long id = CommMessage.GENERIC_ID; } private void recv_checkForStatusCode( HttpMessage message ) { if ( hasParameter( Parameters.STATUS_CODE ) ) { getParameterFirstValue( Parameters.STATUS_CODE ).setValue( message.statusCode() ); } } public CommMessage recv_internal( InputStream istream, OutputStream ostream ) throws IOException { HttpMessage message = new HttpParser( istream ).parse(); String charset = HttpUtils.getCharset( null, message ); CommMessage retVal = null; DecodedMessage decodedMessage = new DecodedMessage(); HttpUtils.recv_checkForChannelClosing( message, channel() ); if ( checkBooleanParameter( Parameters.DEBUG ) ) { recv_logDebugInfo( message, charset ); } recv_checkForStatusCode( message ); encoding = message.getProperty( "accept-encoding" ); headRequest = inInputPort && message.isHead(); String contentType = DEFAULT_CONTENT_TYPE; if ( message.getProperty( "content-type" ) != null ) { contentType = message.getProperty( "content-type" ).split( ";", 2 )[0].toLowerCase(); } // URI parameter parsing if ( message.requestPath() != null ) { boolean strictEncoding = checkStringParameter( Parameters.JSON_ENCODING, "strict" ); recv_parseQueryString( message, decodedMessage.value, contentType, strictEncoding ); } recv_parseRequestFormat( contentType ); if ( !message.isGet() && !message.isHead() && !message.isDelete() ) { // body parsing if ( message.size() > 0 ) { recv_parseMessage( message, decodedMessage, contentType, charset ); } } if ( checkBooleanParameter( Parameters.CONCURRENT ) ) { String messageId = message.getProperty( Headers.JOLIE_MESSAGE_ID ); if ( messageId != null ) { try { decodedMessage.id = Long.parseLong( messageId ); } catch( NumberFormatException e ) {} } } if ( message.isResponse() ) { recv_checkForSetCookie( message, decodedMessage.value ); retVal = new CommMessage( decodedMessage.id, inputId, decodedMessage.resourcePath, decodedMessage.value, null ); } else if ( message.isError() == false ) { recv_checkReceivingOperation( message, decodedMessage ); recv_checkForMessageProperties( message, decodedMessage ); retVal = new CommMessage( decodedMessage.id, decodedMessage.operationName, decodedMessage.resourcePath, decodedMessage.value, null ); } if ( retVal != null && "/".equals( retVal.resourcePath() ) && channel().parentPort() != null && (channel().parentPort().getInterface().containsOperation( retVal.operationName() ) || channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) != null) ) { try { // The message is for this service boolean hasInput = false; OneWayTypeDescription oneWayTypeDescription = null; if ( channel().parentInputPort() != null ) { if ( channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) != null ) { oneWayTypeDescription = channel().parentInputPort().getAggregatedOperation( retVal.operationName() ).getOperationTypeDescription().asOneWayTypeDescription(); hasInput = true; } } if ( !hasInput ) { Interface iface = channel().parentPort().getInterface(); oneWayTypeDescription = iface.oneWayOperations().get( retVal.operationName() ); } if ( oneWayTypeDescription != null ) { // We are receiving a One-Way message oneWayTypeDescription.requestType().cast( retVal.value() ); } else { hasInput = false; RequestResponseTypeDescription rrTypeDescription = null; if ( channel().parentInputPort() != null ) { if ( channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) != null ) { rrTypeDescription = channel().parentInputPort().getAggregatedOperation( retVal.operationName() ).getOperationTypeDescription().asRequestResponseTypeDescription(); hasInput = true; } } if ( !hasInput ) { Interface iface = channel().parentPort().getInterface(); rrTypeDescription = iface.requestResponseOperations().get( retVal.operationName() ); } if ( retVal.isFault() ) { Type faultType = rrTypeDescription.faults().get( retVal.fault().faultName() ); if ( faultType != null ) { faultType.cast( retVal.value() ); } } else { if ( message.isResponse() ) { rrTypeDescription.responseType().cast( retVal.value() ); } else { rrTypeDescription.requestType().cast( retVal.value() ); } } } } catch( TypeCastingException e ) { // TODO: do something here? } } return retVal; } @Override public CommMessage recv( InputStream istream, OutputStream ostream ) throws IOException { return HttpUtils.recv( istream, ostream, inInputPort, channel(), this ); } private Type getSendType( CommMessage message ) throws IOException { Type ret = null; if ( channel().parentPort() == null ) { throw new IOException( "Could not retrieve communication port for HTTP protocol" ); } OperationTypeDescription opDesc = channel().parentPort().getOperationTypeDescription( message.operationName(), Constants.ROOT_RESOURCE_PATH ); if ( opDesc == null ) { return null; } if ( opDesc.asOneWayTypeDescription() != null ) { if ( message.isFault() ) { ret = Type.UNDEFINED; } else { OneWayTypeDescription ow = opDesc.asOneWayTypeDescription(); ret = ow.requestType(); } } else if ( opDesc.asRequestResponseTypeDescription() != null ) { RequestResponseTypeDescription rr = opDesc.asRequestResponseTypeDescription(); if ( message.isFault() ) { ret = rr.getFaultType( message.fault().faultName() ); if ( ret == null ) { ret = Type.UNDEFINED; } } else { ret = ( inInputPort ) ? rr.responseType() : rr.requestType(); } } return ret; } }
package jolie.net; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.server.rpc.RPC; import com.google.gwt.user.server.rpc.RPCRequest; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.URI; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import jolie.Interpreter; import jolie.lang.NativeType; import jolie.net.http.HttpMessage; import jolie.net.http.HttpParser; import jolie.net.http.HttpUtils; import jolie.net.http.json.JsonUtils; import joliex.gwt.server.JolieGWTConverter; import jolie.net.http.Method; import jolie.net.http.MultiPartFormDataParser; import jolie.net.ports.Interface; import jolie.net.protocols.CommProtocol; import jolie.runtime.ByteArray; import jolie.runtime.Value; import jolie.runtime.ValueVector; import jolie.runtime.VariablePath; import jolie.runtime.typing.OneWayTypeDescription; import jolie.runtime.typing.RequestResponseTypeDescription; import jolie.runtime.typing.Type; import jolie.runtime.typing.TypeCastingException; import jolie.util.LocationParser; import jolie.xml.XmlUtils; import joliex.gwt.client.JolieService; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * HTTP protocol implementation * @author Fabrizio Montesi * 14 Nov 2012 - Saverio Giallorenzo - Fabrizio Montesi: support for status codes */ public class HttpProtocol extends CommProtocol { private static final byte[] NOT_IMPLEMENTED_HEADER = "HTTP/1.1 501 Not Implemented".getBytes(); private static final int defaultStatusCode = 200; private static final Map< Integer, String > statusCodeDescriptions = new HashMap< Integer, String >(); private static final Set< Integer > locationRequiredStatusCodes = new HashSet< Integer >(); static { locationRequiredStatusCodes.add( 301 ); locationRequiredStatusCodes.add( 302 ); locationRequiredStatusCodes.add( 303 ); locationRequiredStatusCodes.add( 307 ); locationRequiredStatusCodes.add( 308 ); } static { // Initialise the HTTP Status code map. statusCodeDescriptions.put( 100,"Continue" ); statusCodeDescriptions.put( 101,"Switching Protocols" ); statusCodeDescriptions.put( 102,"Processing" ); statusCodeDescriptions.put( 200,"OK" ); statusCodeDescriptions.put( 201,"Created" ); statusCodeDescriptions.put( 202,"Accepted" ); statusCodeDescriptions.put( 203,"Non-Authoritative Information" ); statusCodeDescriptions.put( 204,"No Content" ); statusCodeDescriptions.put( 205,"Reset Content" ); statusCodeDescriptions.put( 206,"Partial Content" ); statusCodeDescriptions.put( 207,"Multi-Status" ); statusCodeDescriptions.put( 208,"Already Reported" ); statusCodeDescriptions.put( 226,"IM Used" ); statusCodeDescriptions.put( 300,"Multiple Choices" ); statusCodeDescriptions.put( 301,"Moved Permanently" ); statusCodeDescriptions.put( 302,"Found" ); statusCodeDescriptions.put( 303,"See Other" ); statusCodeDescriptions.put( 304,"Not Modified" ); statusCodeDescriptions.put( 305,"Use Proxy" ); statusCodeDescriptions.put( 306,"Reserved" ); statusCodeDescriptions.put( 307,"Temporary Redirect" ); statusCodeDescriptions.put( 308,"Permanent Redirect" ); statusCodeDescriptions.put( 400,"Bad Request" ); statusCodeDescriptions.put( 401,"Unauthorized" ); statusCodeDescriptions.put( 402,"Payment Required" ); statusCodeDescriptions.put( 403,"Forbidden" ); statusCodeDescriptions.put( 404,"Not Found" ); statusCodeDescriptions.put( 405,"Method Not Allowed" ); statusCodeDescriptions.put( 406,"Not Acceptable" ); statusCodeDescriptions.put( 407,"Proxy Authentication Required" ); statusCodeDescriptions.put( 408,"Request Timeout" ); statusCodeDescriptions.put( 409,"Conflict" ); statusCodeDescriptions.put( 410,"Gone" ); statusCodeDescriptions.put( 411,"Length Required" ); statusCodeDescriptions.put( 412,"Precondition Failed" ); statusCodeDescriptions.put( 413,"Request Entity Too Large" ); statusCodeDescriptions.put( 414,"Request-URI Too Long" ); statusCodeDescriptions.put( 415,"Unsupported Media Type" ); statusCodeDescriptions.put( 416,"Requested Range Not Satisfiable" ); statusCodeDescriptions.put( 417,"Expectation Failed" ); statusCodeDescriptions.put( 422,"Unprocessable Entity" ); statusCodeDescriptions.put( 423,"Locked" ); statusCodeDescriptions.put( 424,"Failed Dependency" ); statusCodeDescriptions.put( 426,"Upgrade Required" ); statusCodeDescriptions.put( 427,"Unassigned" ); statusCodeDescriptions.put( 428,"Precondition Required" ); statusCodeDescriptions.put( 429,"Too Many Requests" ); statusCodeDescriptions.put( 430,"Unassigned" ); statusCodeDescriptions.put( 431,"Request Header Fields Too Large" ); statusCodeDescriptions.put( 500,"Internal Server Error" ); statusCodeDescriptions.put( 501,"Not Implemented" ); statusCodeDescriptions.put( 502,"Bad Gateway" ); statusCodeDescriptions.put( 503,"Service Unavailable" ); statusCodeDescriptions.put( 504,"Gateway Timeout" ); statusCodeDescriptions.put( 505,"HTTP Version Not Supported" ); statusCodeDescriptions.put( 507,"Insufficient Storage" ); statusCodeDescriptions.put( 508,"Loop Detected" ); statusCodeDescriptions.put( 509,"Unassigned" ); statusCodeDescriptions.put( 510,"Not Extended" ); statusCodeDescriptions.put( 511,"Network Authentication Required" ); } private static class Parameters { private static final String DEBUG = "debug"; private static final String COOKIES = "cookies"; private static final String METHOD = "method"; private static final String ALIAS = "alias"; private static final String MULTIPART_HEADERS = "multipartHeaders"; private static final String CONCURRENT = "concurrent"; private static final String USER_AGENT = "userAgent"; private static final String HEADERS = "headers"; private static final String STATUS_CODE = "statusCode"; private static final String REDIRECT = "redirect"; private static class MultiPartHeaders { private static final String FILENAME = "filename"; } } private static class Headers { private static String JOLIE_MESSAGE_ID = "X-Jolie-MessageID"; } private String inputId = null; private final Transformer transformer; private final DocumentBuilderFactory docBuilderFactory; private final DocumentBuilder docBuilder; private final URI uri; private final boolean inInputPort; private MultiPartFormDataParser multiPartFormDataParser = null; public final static String CRLF = new String( new char[] { 13, 10 } ); public String name() { return "http"; } public boolean isThreadSafe() { return checkBooleanParameter( Parameters.CONCURRENT ); } public HttpProtocol( VariablePath configurationPath, URI uri, boolean inInputPort, TransformerFactory transformerFactory, DocumentBuilderFactory docBuilderFactory, DocumentBuilder docBuilder ) throws TransformerConfigurationException { super( configurationPath ); this.uri = uri; this.inInputPort = inInputPort; this.transformer = transformerFactory.newTransformer(); this.docBuilderFactory = docBuilderFactory; this.docBuilder = docBuilder; transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" ); } private void valueToDocument( Value value, Node node, Document doc ) { node.appendChild( doc.createTextNode( value.strValue() ) ); Element currentElement; for( Entry< String, ValueVector > entry : value.children().entrySet() ) { if ( !entry.getKey().startsWith( "@" ) ) { for( Value val : entry.getValue() ) { currentElement = doc.createElement( entry.getKey() ); node.appendChild( currentElement ); Map< String, ValueVector > attrs = jolie.xml.XmlUtils.getAttributesOrNull( val ); if ( attrs != null ) { for( Entry< String, ValueVector > attrEntry : attrs.entrySet() ) { currentElement.setAttribute( attrEntry.getKey(), attrEntry.getValue().first().strValue() ); } } valueToDocument( val, currentElement, doc ); } } } } public String getMultipartHeaderForPart( String operationName, String partName ) { if ( hasOperationSpecificParameter( operationName, Parameters.MULTIPART_HEADERS ) ) { Value v = getOperationSpecificParameterFirstValue( operationName, Parameters.MULTIPART_HEADERS ); if ( v.hasChildren( partName ) ) { v = v.getFirstChild( partName ); if ( v.hasChildren( Parameters.MultiPartHeaders.FILENAME ) ) { v = v.getFirstChild( Parameters.MultiPartHeaders.FILENAME ); return v.strValue(); } } } return null; } private final static String BOUNDARY = "----Jol13H77p$$Bound4r1$$"; private void send_appendCookies( CommMessage message, String hostname, StringBuilder headerBuilder ) { Value cookieParam = null; if ( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) { cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES ); } else if ( hasParameter( Parameters.COOKIES ) ) { cookieParam = getParameterFirstValue( Parameters.COOKIES ); } if ( cookieParam != null ) { Value cookieConfig; String domain; StringBuilder cookieSB = new StringBuilder(); for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) { cookieConfig = entry.getValue().first(); if ( message.value().hasChildren( cookieConfig.strValue() ) ) { domain = cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : ""; if ( domain.isEmpty() || hostname.endsWith( domain ) ) { cookieSB .append( entry.getKey() ) .append( '=' ) .append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() ) .append( ";" ); } } } if ( cookieSB.length() > 0 ) { headerBuilder .append( "Cookie: " ) .append( cookieSB ) .append( CRLF ); } } } private void send_appendSetCookieHeader( CommMessage message, StringBuilder headerBuilder ) { Value cookieParam = null; if ( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) { cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES ); } else if ( hasParameter( Parameters.COOKIES ) ) { cookieParam = getParameterFirstValue( Parameters.COOKIES ); } if ( cookieParam != null ) { Value cookieConfig; for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) { cookieConfig = entry.getValue().first(); if ( message.value().hasChildren( cookieConfig.strValue() ) ) { headerBuilder .append( "Set-Cookie: " ) .append( entry.getKey() ).append( '=' ) .append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() ) .append( "; expires=" ) .append( cookieConfig.hasChildren( "expires" ) ? cookieConfig.getFirstChild( "expires" ).strValue() : "" ) .append( "; domain=" ) .append( cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : "" ) .append( "; path=" ) .append( cookieConfig.hasChildren( "path" ) ? cookieConfig.getFirstChild( "path" ).strValue() : "" ); if ( cookieConfig.hasChildren( "secure" ) && cookieConfig.getFirstChild( "secure" ).intValue() > 0 ) { headerBuilder.append( "; secure" ); } headerBuilder.append( CRLF ); } } } } private String requestFormat = null; private void send_appendQuerystring( Value value, String charset, StringBuilder headerBuilder ) throws IOException { if ( value.children().isEmpty() == false ) { headerBuilder.append( '?' ); for( Entry< String, ValueVector > entry : value.children().entrySet() ) { for( Value v : entry.getValue() ) { headerBuilder .append( entry.getKey() ) .append( '=' ) .append( URLEncoder.encode( v.strValue(), charset ) ) .append( '&' ); } } } } private void send_appendParsedAlias( String alias, Value value, String charset, StringBuilder headerBuilder ) throws IOException { int offset = 0; String currStrValue; String currKey; StringBuilder result = new StringBuilder( alias ); Matcher m = Pattern.compile( "%(!)?\\{[^\\}]*\\}" ).matcher( alias ); while( m.find() ) { if ( m.group( 1 ) == null ) { // We have to use URLEncoder currKey = alias.substring( m.start() + 2, m.end() - 1 ); if ( "$".equals( currKey ) ) { currStrValue = URLEncoder.encode( value.strValue(), charset ); } else { currStrValue = URLEncoder.encode( value.getFirstChild( currKey ).strValue(), charset ); } } else { // We have to insert the string raw currKey = alias.substring( m.start() + 3, m.end() - 1 ); if ( "$".equals( currKey ) ) { currStrValue = value.strValue(); } else { currStrValue = value.getFirstChild( currKey ).strValue(); } } result.replace( m.start() + offset, m.end() + offset, currStrValue ); offset += currStrValue.length() - 3 - currKey.length(); } headerBuilder.append( result ); } private String getCharset() { String charset = "UTF-8"; if ( hasParameter( "charset" ) ) { charset = getStringParameter( "charset" ); } return charset; } private String send_getFormat() { String format = "xml"; if ( inInputPort && requestFormat != null ) { format = requestFormat; requestFormat = null; } else if ( hasParameter( "format" ) ) { format = getStringParameter( "format" ); } return format; } private static class EncodedContent { private ByteArray content = null; private String contentType = ""; private String contentDisposition = ""; } private EncodedContent send_encodeContent( CommMessage message, Method method, String charset, String format ) throws IOException { EncodedContent ret = new EncodedContent(); if ( inInputPort == false && method == Method.GET ) { // We are building a GET request return ret; } if ( "xml".equals( format ) ) { Document doc = docBuilder.newDocument(); Element root = doc.createElement( message.operationName() + (( inInputPort ) ? "Response" : "") ); doc.appendChild( root ); if ( message.isFault() ) { Element faultElement = doc.createElement( message.fault().faultName() ); root.appendChild( faultElement ); valueToDocument( message.fault().value(), faultElement, doc ); } else { valueToDocument( message.value(), root, doc ); } Source src = new DOMSource( doc ); ByteArrayOutputStream tmpStream = new ByteArrayOutputStream(); Result dest = new StreamResult( tmpStream ); try { transformer.transform( src, dest ); } catch( TransformerException e ) { throw new IOException( e ); } ret.content = new ByteArray( tmpStream.toByteArray() ); ret.contentType = "text/xml"; } else if ( "binary".equals( format ) ) { if ( message.value().isByteArray() ) { ret.content = (ByteArray) message.value().valueObject(); ret.contentType = "application/octet-stream"; } } else if ( "html".equals( format ) ) { ret.content = new ByteArray( message.value().strValue().getBytes( charset ) ); ret.contentType = "text/html"; } else if ( "multipart/form-data".equals( format ) ) { ret.contentType = "multipart/form-data; boundary=" + BOUNDARY; StringBuilder builder = new StringBuilder(); for( Entry< String, ValueVector > entry : message.value().children().entrySet() ) { if ( !entry.getKey().startsWith( "@" ) ) { builder.append( "--" ).append( BOUNDARY ).append( CRLF ); builder.append( "Content-Disposition: form-data; name=\"" ).append( entry.getKey() ).append( '\"' ).append( CRLF ).append( CRLF ); builder.append( entry.getValue().first().strValue() ).append( CRLF ); } } builder.append( "--" + BOUNDARY + "--" ); ret.content = new ByteArray( builder.toString().getBytes( charset ) ); } else if ( "x-www-form-urlencoded".equals( format ) ) { ret.contentType = "application/x-www-form-urlencoded"; Iterator< Entry< String, ValueVector > > it = message.value().children().entrySet().iterator(); Entry< String, ValueVector > entry; StringBuilder builder = new StringBuilder(); while( it.hasNext() ) { entry = it.next(); builder.append( entry.getKey() ) .append( "=" ) .append( URLEncoder.encode( entry.getValue().first().strValue(), "UTF-8" ) ); if ( it.hasNext() ) { builder.append( '&' ); } } ret.content = new ByteArray( builder.toString().getBytes( charset ) ); } else if ( "text/x-gwt-rpc".equals( format ) ) { ret.contentType = "text/x-gwt-rpc"; try { if ( message.isFault() ) { ret.content = new ByteArray( RPC.encodeResponseForFailure( JolieService.class.getMethods()[0], JolieGWTConverter.jolieToGwtFault( message.fault() ) ).getBytes( charset ) ); } else { joliex.gwt.client.Value v = new joliex.gwt.client.Value(); JolieGWTConverter.jolieToGwtValue( message.value(), v ); ret.content = new ByteArray( RPC.encodeResponseForSuccess( JolieService.class.getMethods()[0], v ).getBytes( charset ) ); } } catch( SerializationException e ) { throw new IOException( e ); } } else if ( "json".equals( format ) || "application/json".equals( format ) ) { ret.contentType = "application/json"; StringBuilder jsonStringBuilder = new StringBuilder(); JsonUtils.valueToJsonString( message.value(), jsonStringBuilder ); ret.content = new ByteArray( jsonStringBuilder.toString().getBytes( charset ) ); } return ret; } private boolean isLocationNeeded( int statusCode ) { return locationRequiredStatusCodes.contains( statusCode ); } private void send_appendResponseHeaders( CommMessage message, StringBuilder headerBuilder ) { int statusCode = defaultStatusCode; String statusDescription = null; if( hasParameter( Parameters.STATUS_CODE ) ) { statusCode = getIntParameter( Parameters.STATUS_CODE ); if ( !statusCodeDescriptions.containsKey( statusCode ) ) { Interpreter.getInstance().logWarning( "HTTP protocol for operation " + message.operationName() + " is sending a message with status code " + statusCode + ", which is not in the HTTP specifications." ); statusDescription = "Internal Server Error"; } else if ( isLocationNeeded( statusCode ) && !hasParameter( Parameters.REDIRECT ) ) { // if statusCode is a redirection code, location parameter is needed Interpreter.getInstance().logWarning( "HTTP protocol for operation " + message.operationName() + " is sending a message with status code " + statusCode + ", which expects a redirect parameter but the latter is not set." ); } } if ( statusDescription == null ) { statusDescription = statusCodeDescriptions.get( statusCode ); } headerBuilder.append( "HTTP/1.1 " + statusCode + " " + statusDescription + CRLF ); // if redirect has been set, the redirect location parameter is set if ( hasParameter( Parameters.REDIRECT ) ) { headerBuilder.append( "Location: " + getStringParameter( Parameters.REDIRECT ) + CRLF ); } send_appendSetCookieHeader( message, headerBuilder ); headerBuilder.append( "Server: Jolie" ).append( CRLF ); StringBuilder cacheControlHeader = new StringBuilder(); if ( hasParameter( "cacheControl" ) ) { Value cacheControl = getParameterFirstValue( "cacheControl" ); if ( cacheControl.hasChildren( "maxAge" ) ) { cacheControlHeader.append( "max-age=" ).append( cacheControl.getFirstChild( "maxAge" ).intValue() ); } } if ( cacheControlHeader.length() > 0 ) { headerBuilder.append( "Cache-Control: " ).append( cacheControlHeader ).append( CRLF ); } } private void send_appendRequestMethod( Method method, StringBuilder headerBuilder ) { headerBuilder.append( method.id() ); } private void send_appendRequestPath( CommMessage message, Method method, StringBuilder headerBuilder, String charset ) throws IOException { if ( uri.getPath().length() < 1 || uri.getPath().charAt( 0 ) != '/' ) { headerBuilder.append( '/' ); } headerBuilder.append( uri.getPath() ); String alias = getOperationSpecificStringParameter( message.operationName(), Parameters.ALIAS ); if ( alias.isEmpty() ) { headerBuilder.append( message.operationName() ); } else { send_appendParsedAlias( alias, message.value(), charset, headerBuilder ); } if ( method == Method.GET ) { send_appendQuerystring( message.value(), charset, headerBuilder ); } } private static void send_appendAuthorizationHeader( CommMessage message, StringBuilder headerBuilder ) { if ( message.value().hasChildren( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ) ) { Value v = message.value().getFirstChild( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ); //String realm = v.getFirstChild( "realm" ).strValue(); String userpass = v.getFirstChild( "userid" ).strValue() + ":" + v.getFirstChild( "password" ).strValue(); sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder(); userpass = encoder.encode( userpass.getBytes() ); headerBuilder.append( "Authorization: Basic " ).append( userpass ).append( CRLF ); } } private Method send_getRequestMethod( CommMessage message ) throws IOException { try { Method method; if ( hasOperationSpecificParameter( message.operationName(), Parameters.METHOD ) ) { method = Method.fromString( getOperationSpecificStringParameter( message.operationName(), Parameters.METHOD ).toUpperCase() ); } else if ( hasParameter( Parameters.METHOD ) ) { method = Method.fromString( getStringParameter( Parameters.METHOD ).toUpperCase() ); } else { method = Method.POST; } return method; } catch( Method.UnsupportedMethodException e ) { throw new IOException( e ); } } private void send_appendRequestHeaders( CommMessage message, Method method, StringBuilder headerBuilder, String charset ) throws IOException { send_appendRequestMethod( method, headerBuilder ); headerBuilder.append( ' ' ); send_appendRequestPath( message, method, headerBuilder, charset ); headerBuilder.append( " HTTP/1.1" + CRLF ); headerBuilder.append( "Host: " + uri.getHost() + CRLF ); send_appendCookies( message, uri.getHost(), headerBuilder ); send_appendAuthorizationHeader( message, headerBuilder ); } private void send_appendGenericHeaders( CommMessage message, EncodedContent encodedContent, String charset, StringBuilder headerBuilder ) { String param; if ( checkBooleanParameter( "keepAlive", true ) == false || channel().toBeClosed() ) { channel().setToBeClosed( true ); headerBuilder.append( "Connection: close" + CRLF ); } if ( checkBooleanParameter( Parameters.CONCURRENT, true ) ) { headerBuilder.append( Headers.JOLIE_MESSAGE_ID ).append( ": " ).append( message.id() ).append( CRLF ); } if ( encodedContent.content != null ) { String contentType = getStringParameter( "contentType" ); if ( contentType.length() > 0 ) { encodedContent.contentType = contentType; } headerBuilder.append( "Content-Type: " + encodedContent.contentType ); if ( charset != null ) { headerBuilder.append( "; charset=" + charset.toLowerCase() ); } headerBuilder.append( CRLF ); param = getStringParameter( "contentTransferEncoding" ); if ( !param.isEmpty() ) { headerBuilder.append( "Content-Transfer-Encoding: " + param + CRLF ); } String contentDisposition = getStringParameter( "contentDisposition" ); if ( contentDisposition.length() > 0 ) { encodedContent.contentDisposition = contentDisposition; headerBuilder.append( "Content-Disposition: " + encodedContent.contentDisposition + CRLF ); } headerBuilder.append( "Content-Length: " + (encodedContent.content.size() + 2) + CRLF ); } else { headerBuilder.append( "Content-Length: 0" + CRLF ); } } private void send_logDebugInfo( CharSequence header, EncodedContent encodedContent ) { if ( checkBooleanParameter( "debug" ) ) { StringBuilder debugSB = new StringBuilder(); debugSB.append( "[HTTP debug] Sending:\n" ); debugSB.append( header ); if ( getParameterVector( "debug" ).first().getFirstChild( "showContent" ).intValue() > 0 && encodedContent.content != null ) { debugSB.append( encodedContent.content.toString() ); } Interpreter.getInstance().logInfo( debugSB.toString() ); } } public void send( OutputStream ostream, CommMessage message, InputStream istream ) throws IOException { Method method = send_getRequestMethod( message ); String charset = getCharset(); String format = send_getFormat(); EncodedContent encodedContent = send_encodeContent( message, method, charset, format ); StringBuilder headerBuilder = new StringBuilder(); if ( inInputPort ) { // We're responding to a request send_appendResponseHeaders( message, headerBuilder ); } else { // We're sending a notification or a solicit send_appendRequestHeaders( message, method, headerBuilder, charset ); } send_appendGenericHeaders( message, encodedContent, charset, headerBuilder ); headerBuilder.append( CRLF ); send_logDebugInfo( headerBuilder, encodedContent ); inputId = message.operationName(); /*if ( charset == null ) { charset = "UTF8"; }*/ ostream.write( headerBuilder.toString().getBytes( charset ) ); if ( encodedContent.content != null ) { ostream.write( encodedContent.content.getBytes() ); ostream.write( CRLF.getBytes( charset ) ); } } private void parseXML( HttpMessage message, Value value ) throws IOException { try { if ( message.size() > 0 ) { DocumentBuilder builder = docBuilderFactory.newDocumentBuilder(); InputSource src = new InputSource( new ByteArrayInputStream( message.content() ) ); Document doc = builder.parse( src ); XmlUtils.documentToValue( doc, value ); } } catch( ParserConfigurationException pce ) { throw new IOException( pce ); } catch( SAXException saxe ) { throw new IOException( saxe ); } } private static void parseJson( HttpMessage message, Value value ) throws IOException { JsonUtils.parseJsonIntoValue( new InputStreamReader( new ByteArrayInputStream( message.content() ) ), value ); } private static void parseForm( HttpMessage message, Value value, String charset ) throws IOException { String line = new String( message.content(), "UTF8" ); String[] s, pair; s = line.split( "&" ); for( int i = 0; i < s.length; i++ ) { pair = s[i].split( "=", 2 ); value.getChildren( pair[0] ).first().setValue( URLDecoder.decode( pair[1], charset ) ); } } private void parseMultiPartFormData( HttpMessage message, Value value ) throws IOException { multiPartFormDataParser = new MultiPartFormDataParser( message, value ); multiPartFormDataParser.parse(); } private static String parseGWTRPC( HttpMessage message, Value value ) throws IOException { RPCRequest request = RPC.decodeRequest( new String( message.content(), "UTF8" ) ); String operationName = (String)request.getParameters()[0]; joliex.gwt.client.Value requestValue = (joliex.gwt.client.Value)request.getParameters()[1]; JolieGWTConverter.gwtToJolieValue( requestValue, value ); return operationName; } private void recv_checkForSetCookie( HttpMessage message, Value value ) throws IOException { if ( hasParameter( Parameters.COOKIES ) ) { String type; Value cookies = getParameterFirstValue( Parameters.COOKIES ); Value cookieConfig; Value v; for( HttpMessage.Cookie cookie : message.setCookies() ) { if ( cookies.hasChildren( cookie.name() ) ) { cookieConfig = cookies.getFirstChild( cookie.name() ); if ( cookieConfig.isString() ) { v = value.getFirstChild( cookieConfig.strValue() ); if ( cookieConfig.hasChildren( "type" ) ) { type = cookieConfig.getFirstChild( "type" ).strValue(); } else { type = "string"; } recv_assignCookieValue( cookie.value(), v, type ); } } /*currValue = Value.create(); currValue.getNewChild( "expires" ).setValue( cookie.expirationDate() ); currValue.getNewChild( "path" ).setValue( cookie.path() ); currValue.getNewChild( "name" ).setValue( cookie.name() ); currValue.getNewChild( "value" ).setValue( cookie.value() ); currValue.getNewChild( "domain" ).setValue( cookie.domain() ); currValue.getNewChild( "secure" ).setValue( (cookie.secure() ? 1 : 0) ); cookieVec.add( currValue );*/ } } } private void recv_assignCookieValue( String cookieValue, Value value, String typeKeyword ) throws IOException { NativeType type = NativeType.fromString( typeKeyword ); if ( NativeType.INT == type ) { try { value.setValue( new Integer( cookieValue ) ); } catch( NumberFormatException e ) { throw new IOException( e ); } } else if ( NativeType.LONG == type ) { try { value.setValue( new Long( cookieValue ) ); } catch( NumberFormatException e ) { throw new IOException( e ); } } else if ( NativeType.STRING == type ) { value.setValue( cookieValue ); } else if ( NativeType.DOUBLE == type ) { try { value.setValue( new Double( cookieValue ) ); } catch( NumberFormatException e ) { throw new IOException( e ); } } else if ( NativeType.BOOL == type ) { value.setValue( Boolean.valueOf( cookieValue ) ); } else { value.setValue( cookieValue ); } } private void recv_checkForCookies( HttpMessage message, DecodedMessage decodedMessage ) throws IOException { Value cookies = null; if ( hasOperationSpecificParameter( decodedMessage.operationName, Parameters.COOKIES ) ) { cookies = getOperationSpecificParameterFirstValue( decodedMessage.operationName, Parameters.COOKIES ); } else if ( hasParameter( Parameters.COOKIES ) ) { cookies = getParameterFirstValue( Parameters.COOKIES ); } if ( cookies != null ) { Value v; String type; for( Entry< String, String > entry : message.cookies().entrySet() ) { if ( cookies.hasChildren( entry.getKey() ) ) { Value cookieConfig = cookies.getFirstChild( entry.getKey() ); if ( cookieConfig.isString() ) { v = decodedMessage.value.getFirstChild( cookieConfig.strValue() ); if ( cookieConfig.hasChildren( "type" ) ) { type = cookieConfig.getFirstChild( "type" ).strValue(); } else { type = "string"; } recv_assignCookieValue( entry.getValue(), v, type ); } } } } } private void recv_checkForGenericHeader( HttpMessage message, DecodedMessage decodedMessage ) throws IOException { Value header = null; if ( hasOperationSpecificParameter( decodedMessage.operationName, Parameters.HEADERS ) ) { header = getOperationSpecificParameterFirstValue( decodedMessage.operationName, Parameters.HEADERS ); } else if ( hasParameter( Parameters.HEADERS ) ) { header = getParameterFirstValue( Parameters.HEADERS ); } if ( header != null ) { Iterator<String> iterator = header.children().keySet().iterator(); while( iterator.hasNext() ){ String name = iterator.next(); String val = header.getFirstChild( name ).strValue(); name = name.replace( "_", "-" ); decodedMessage.value.getFirstChild(val).setValue(message.getPropertyOrEmptyString(name)); } } } private static void recv_parseQueryString( HttpMessage message, Value value ) { Map< String, Integer > indexes = new HashMap< String, Integer >(); String queryString = message.requestPath() == null ? "" : message.requestPath(); String[] kv = queryString.split( "\\?" ); Integer index; if ( kv.length > 1 ) { queryString = kv[1]; String[] params = queryString.split( "&" ); for( String param : params ) { kv = param.split( "=", 2 ); if ( kv.length > 1 ) { index = indexes.get( kv[0] ); if ( index == null ) { index = 0; indexes.put( kv[0], index ); } value.getChildren( kv[0] ).get( index ).setValue( kv[1] ); indexes.put( kv[0], index + 1 ); } } } } /* * Prints debug information about a received message */ private void recv_logDebugInfo( HttpMessage message ) { StringBuilder debugSB = new StringBuilder(); debugSB.append( "[HTTP debug] Receiving:\n" ); debugSB.append( "HTTP Code: " + message.statusCode() + "\n" ); debugSB.append( "Resource: " + message.requestPath() + "\n" ); debugSB.append( "--> Header properties\n" ); for( Entry< String, String > entry : message.properties() ) { debugSB.append( '\t' + entry.getKey() + ": " + entry.getValue() + '\n' ); } for( HttpMessage.Cookie cookie : message.setCookies() ) { debugSB.append( "\tset-cookie: " + cookie.toString() + '\n' ); } for( Entry< String, String > entry : message.cookies().entrySet() ) { debugSB.append( "\tcookie: " + entry.getKey() + '=' + entry.getValue() + '\n' ); } if ( getParameterFirstValue( "debug" ).getFirstChild( "showContent" ).intValue() > 0 && message.content() != null ) { debugSB.append( "--> Message content\n" ); debugSB.append( new String( message.content() ) ); } Interpreter.getInstance().logInfo( debugSB.toString() ); } private void recv_parseRequestFormat( HttpMessage message ) throws IOException { requestFormat = null; String type = message.getPropertyOrEmptyString( "content-type" ).split( ";" )[0]; if ( "text/x-gwt-rpc".equals( type ) ) { requestFormat = "text/x-gwt-rpc"; } else if ( "application/json".equals( type ) ) { requestFormat = "application/json"; } } private void recv_parseMessage( HttpMessage message, DecodedMessage decodedMessage, String charset ) throws IOException { String format = "xml"; if ( hasParameter( "format" ) ) { format = getStringParameter( "format" ); } String type = message.getProperty( "content-type" ).split( ";" )[0]; if ( "text/html".equals( type ) ) { decodedMessage.value.setValue( new String( message.content() ) ); } else if ( "application/x-www-form-urlencoded".equals( type ) ) { parseForm( message, decodedMessage.value, charset ); } else if ( "text/xml".equals( type ) ) { parseXML( message, decodedMessage.value ); } else if ( "text/x-gwt-rpc".equals( type ) ) { decodedMessage.operationName = parseGWTRPC( message, decodedMessage.value ); } else if ( "multipart/form-data".equals( type ) ) { parseMultiPartFormData( message, decodedMessage.value ); } else if ( "application/octet-stream".equals( type ) || type.startsWith( "image/" ) ) { decodedMessage.value.setValue( new ByteArray( message.content() ) ); } else if ( "application/json".equals( type ) ) { parseJson( message, decodedMessage.value ); } else if ( "xml".equals( format ) || "rest".equals( format ) ) { parseXML( message, decodedMessage.value ); } else if ( "json".equals( format ) ) { parseJson( message, decodedMessage.value ); } else { decodedMessage.value.setValue( new String( message.content() ) ); } } private void recv_checkReceivingOperation( HttpMessage message, DecodedMessage decodedMessage ) { if ( decodedMessage.operationName == null ) { String requestPath = message.requestPath().split( "\\?" )[0]; decodedMessage.operationName = requestPath; Matcher m = LocationParser.RESOURCE_SEPARATOR_PATTERN.matcher( decodedMessage.operationName ); if ( m.find() ) { int resourceStart = m.end(); if ( m.find() ) { decodedMessage.resourcePath = requestPath.substring( resourceStart - 1, m.start() ); decodedMessage.operationName = requestPath.substring( m.end(), requestPath.length() ); } } } if ( decodedMessage.resourcePath.equals( "/" ) && !channel().parentInputPort().canHandleInputOperation( decodedMessage.operationName ) ) { String defaultOpId = getStringParameter( "default" ); if ( defaultOpId.length() > 0 ) { Value body = decodedMessage.value; decodedMessage.value = Value.create(); decodedMessage.value.getChildren( "data" ).add( body ); decodedMessage.value.getFirstChild( "operation" ).setValue( decodedMessage.operationName ); decodedMessage.value.getFirstChild( Parameters.USER_AGENT).setValue( message.userAgent() ); Value cookies = decodedMessage.value.getFirstChild( "cookies" ); for( Entry< String, String > cookie : message.cookies().entrySet() ) { cookies.getFirstChild( cookie.getKey() ).setValue( cookie.getValue() ); } decodedMessage.operationName = defaultOpId; } } } private void recv_checkForMultiPartHeaders( DecodedMessage decodedMessage ) { if ( multiPartFormDataParser != null ) { String target; for( Entry< String, MultiPartFormDataParser.PartProperties > entry : multiPartFormDataParser.getPartPropertiesSet() ) { if ( entry.getValue().filename() != null ) { target = getMultipartHeaderForPart( decodedMessage.operationName, entry.getKey() ); if ( target != null ) { decodedMessage.value.getFirstChild( target ).setValue( entry.getValue().filename() ); } } } multiPartFormDataParser = null; } } private void recv_checkForMessageProperties( HttpMessage message, DecodedMessage decodedMessage ) throws IOException { recv_checkForCookies( message, decodedMessage ); recv_checkForGenericHeader( message, decodedMessage ); recv_checkForMultiPartHeaders( decodedMessage ); if ( message.userAgent() != null && hasParameter( Parameters.USER_AGENT ) ) { getParameterFirstValue( Parameters.USER_AGENT ).setValue( message.userAgent() ); } } private static class DecodedMessage { private String operationName = null; private Value value = Value.create(); private String resourcePath = "/"; private long id = CommMessage.GENERIC_ID; } private void recv_checkForStatusCode( HttpMessage message ) { if ( hasParameter( Parameters.STATUS_CODE ) ) { getParameterFirstValue( Parameters.STATUS_CODE ).setValue( message.statusCode() ); } } public CommMessage recv( InputStream istream, OutputStream ostream ) throws IOException { CommMessage retVal = null; DecodedMessage decodedMessage = new DecodedMessage(); HttpMessage message = new HttpParser( istream ).parse(); if ( message.isSupported() == false ) { ostream.write( NOT_IMPLEMENTED_HEADER ); ostream.write( CRLF.getBytes() ); ostream.write( CRLF.getBytes() ); ostream.flush(); return null; } String charset = getCharset(); if ( message.getProperty( "connection" ) != null ) { HttpUtils.recv_checkForChannelClosing( message, channel() ); } else { channel().setToBeClosed( checkBooleanParameter( "keepAlive", true ) == false ); } if ( checkBooleanParameter( Parameters.DEBUG ) ) { recv_logDebugInfo( message ); } recv_checkForStatusCode( message ); recv_parseRequestFormat( message ); if ( message.size() > 0 ) { recv_parseMessage( message, decodedMessage, charset ); } if ( checkBooleanParameter( Parameters.CONCURRENT ) ) { String messageId = message.getProperty( Headers.JOLIE_MESSAGE_ID ); if ( messageId != null ) { try { decodedMessage.id = Long.parseLong( messageId ); } catch( NumberFormatException e ) {} } } if ( message.isResponse() ) { recv_checkForSetCookie( message, decodedMessage.value ); retVal = new CommMessage( decodedMessage.id, inputId, decodedMessage.resourcePath, decodedMessage.value, null ); } else if ( message.isError() == false ) { if ( message.isGet() ) { recv_parseQueryString( message, decodedMessage.value ); } recv_checkReceivingOperation( message, decodedMessage ); recv_checkForMessageProperties( message, decodedMessage ); retVal = new CommMessage( decodedMessage.id, decodedMessage.operationName, decodedMessage.resourcePath, decodedMessage.value, null ); } if ( "/".equals( retVal.resourcePath() ) && channel().parentPort() != null && channel().parentPort().getInterface().containsOperation( retVal.operationName() ) ) { try { // The message is for this service Interface iface = channel().parentPort().getInterface(); OneWayTypeDescription oneWayTypeDescription = iface.oneWayOperations().get( retVal.operationName() ); if ( oneWayTypeDescription != null && message.isResponse() == false ) { // We are receiving a One-Way message oneWayTypeDescription.requestType().cast( retVal.value() ); } else { RequestResponseTypeDescription rrTypeDescription = iface.requestResponseOperations().get( retVal.operationName() ); if ( retVal.isFault() ) { Type faultType = rrTypeDescription.faults().get( retVal.fault().faultName() ); if ( faultType != null ) { faultType.cast( retVal.value() ); } } else { if ( message.isResponse() ) { rrTypeDescription.responseType().cast( retVal.value() ); } else { rrTypeDescription.requestType().cast( retVal.value() ); } } } } catch( TypeCastingException e ) { // TODO: do something here? } } return retVal; } }
package jolie.net; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.server.rpc.RPC; import com.google.gwt.user.server.rpc.RPCRequest; import java.io.ByteArrayInputStream; 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.io.Writer; import java.net.URI; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.DeflaterOutputStream; import java.util.zip.GZIPOutputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import jolie.Interpreter; import jolie.lang.Constants; import jolie.lang.NativeType; import jolie.net.http.HttpMessage; import jolie.net.http.HttpParser; import jolie.net.http.HttpUtils; import jolie.net.http.Method; import jolie.net.http.MultiPartFormDataParser; import jolie.net.http.json.JsonUtils; import jolie.net.ports.Interface; import jolie.net.protocols.CommProtocol; import jolie.runtime.ByteArray; import jolie.runtime.Value; import jolie.runtime.ValueVector; import jolie.runtime.VariablePath; import jolie.runtime.typing.OneWayTypeDescription; import jolie.runtime.typing.OperationTypeDescription; import jolie.runtime.typing.RequestResponseTypeDescription; import jolie.runtime.typing.Type; import jolie.runtime.typing.TypeCastingException; import jolie.util.LocationParser; import jolie.xml.XmlUtils; import joliex.gwt.client.JolieService; import joliex.gwt.server.JolieGWTConverter; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * HTTP protocol implementation * @author Fabrizio Montesi * 14 Nov 2012 - Saverio Giallorenzo - Fabrizio Montesi: support for status codes */ public class HttpProtocol extends CommProtocol { private static final int DEFAULT_STATUS_CODE = 200; private static final int DEFAULT_REDIRECTION_STATUS_CODE = 303; private static final Map< Integer, String > statusCodeDescriptions = new HashMap< Integer, String >(); private static final Set< Integer > locationRequiredStatusCodes = new HashSet< Integer >(); static { locationRequiredStatusCodes.add( 301 ); locationRequiredStatusCodes.add( 302 ); locationRequiredStatusCodes.add( 303 ); locationRequiredStatusCodes.add( 307 ); locationRequiredStatusCodes.add( 308 ); } static { // Initialise the HTTP Status code map. statusCodeDescriptions.put( 100,"Continue" ); statusCodeDescriptions.put( 101,"Switching Protocols" ); statusCodeDescriptions.put( 102,"Processing" ); statusCodeDescriptions.put( 200,"OK" ); statusCodeDescriptions.put( 201,"Created" ); statusCodeDescriptions.put( 202,"Accepted" ); statusCodeDescriptions.put( 203,"Non-Authoritative Information" ); statusCodeDescriptions.put( 204,"No Content" ); statusCodeDescriptions.put( 205,"Reset Content" ); statusCodeDescriptions.put( 206,"Partial Content" ); statusCodeDescriptions.put( 207,"Multi-Status" ); statusCodeDescriptions.put( 208,"Already Reported" ); statusCodeDescriptions.put( 226,"IM Used" ); statusCodeDescriptions.put( 300,"Multiple Choices" ); statusCodeDescriptions.put( 301,"Moved Permanently" ); statusCodeDescriptions.put( 302,"Found" ); statusCodeDescriptions.put( 303,"See Other" ); statusCodeDescriptions.put( 304,"Not Modified" ); statusCodeDescriptions.put( 305,"Use Proxy" ); statusCodeDescriptions.put( 306,"Reserved" ); statusCodeDescriptions.put( 307,"Temporary Redirect" ); statusCodeDescriptions.put( 308,"Permanent Redirect" ); statusCodeDescriptions.put( 400,"Bad Request" ); statusCodeDescriptions.put( 401,"Unauthorized" ); statusCodeDescriptions.put( 402,"Payment Required" ); statusCodeDescriptions.put( 403,"Forbidden" ); statusCodeDescriptions.put( 404,"Not Found" ); statusCodeDescriptions.put( 405,"Method Not Allowed" ); statusCodeDescriptions.put( 406,"Not Acceptable" ); statusCodeDescriptions.put( 407,"Proxy Authentication Required" ); statusCodeDescriptions.put( 408,"Request Timeout" ); statusCodeDescriptions.put( 409,"Conflict" ); statusCodeDescriptions.put( 410,"Gone" ); statusCodeDescriptions.put( 411,"Length Required" ); statusCodeDescriptions.put( 412,"Precondition Failed" ); statusCodeDescriptions.put( 413,"Request Entity Too Large" ); statusCodeDescriptions.put( 414,"Request-URI Too Long" ); statusCodeDescriptions.put( 415,"Unsupported Media Type" ); statusCodeDescriptions.put( 416,"Requested Range Not Satisfiable" ); statusCodeDescriptions.put( 417,"Expectation Failed" ); statusCodeDescriptions.put( 422,"Unprocessable Entity" ); statusCodeDescriptions.put( 423,"Locked" ); statusCodeDescriptions.put( 424,"Failed Dependency" ); statusCodeDescriptions.put( 426,"Upgrade Required" ); statusCodeDescriptions.put( 427,"Unassigned" ); statusCodeDescriptions.put( 428,"Precondition Required" ); statusCodeDescriptions.put( 429,"Too Many Requests" ); statusCodeDescriptions.put( 430,"Unassigned" ); statusCodeDescriptions.put( 431,"Request Header Fields Too Large" ); statusCodeDescriptions.put( 500,"Internal Server Error" ); statusCodeDescriptions.put( 501,"Not Implemented" ); statusCodeDescriptions.put( 502,"Bad Gateway" ); statusCodeDescriptions.put( 503,"Service Unavailable" ); statusCodeDescriptions.put( 504,"Gateway Timeout" ); statusCodeDescriptions.put( 505,"HTTP Version Not Supported" ); statusCodeDescriptions.put( 507,"Insufficient Storage" ); statusCodeDescriptions.put( 508,"Loop Detected" ); statusCodeDescriptions.put( 509,"Unassigned" ); statusCodeDescriptions.put( 510,"Not Extended" ); statusCodeDescriptions.put( 511,"Network Authentication Required" ); } private static class Parameters { private static final String DEBUG = "debug"; private static final String COOKIES = "cookies"; private static final String METHOD = "method"; private static final String ALIAS = "alias"; private static final String MULTIPART_HEADERS = "multipartHeaders"; private static final String CONCURRENT = "concurrent"; private static final String USER_AGENT = "userAgent"; private static final String HOST = "host"; private static final String HEADERS = "headers"; private static final String STATUS_CODE = "statusCode"; private static final String REDIRECT = "redirect"; private static final String DEFAULT_OPERATION = "default"; private static final String COMPRESSION = "compression"; private static final String COMPRESSION_TYPES = "compressionTypes"; private static final String REQUEST_COMPRESSION = "requestCompression"; private static class MultiPartHeaders { private static final String FILENAME = "filename"; } } private static class Headers { private static final String JOLIE_MESSAGE_ID = "X-Jolie-MessageID"; } private String inputId = null; private final Transformer transformer; private final DocumentBuilderFactory docBuilderFactory; private final DocumentBuilder docBuilder; private final URI uri; private final boolean inInputPort; private MultiPartFormDataParser multiPartFormDataParser = null; public final static String CRLF = new String( new char[] { 13, 10 } ); public String name() { return "http"; } public boolean isThreadSafe() { return checkBooleanParameter( Parameters.CONCURRENT ); } public HttpProtocol( VariablePath configurationPath, URI uri, boolean inInputPort, TransformerFactory transformerFactory, DocumentBuilderFactory docBuilderFactory, DocumentBuilder docBuilder ) throws TransformerConfigurationException { super( configurationPath ); this.uri = uri; this.inInputPort = inInputPort; this.transformer = transformerFactory.newTransformer(); this.docBuilderFactory = docBuilderFactory; this.docBuilder = docBuilder; transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" ); } private void valueToDocument( Value value, Node node, Document doc ) { node.appendChild( doc.createTextNode( value.strValue() ) ); Element currentElement; for( Entry< String, ValueVector > entry : value.children().entrySet() ) { if ( !entry.getKey().startsWith( "@" ) ) { for( Value val : entry.getValue() ) { currentElement = doc.createElement( entry.getKey() ); node.appendChild( currentElement ); Map< String, ValueVector > attrs = jolie.xml.XmlUtils.getAttributesOrNull( val ); if ( attrs != null ) { for( Entry< String, ValueVector > attrEntry : attrs.entrySet() ) { currentElement.setAttribute( attrEntry.getKey(), attrEntry.getValue().first().strValue() ); } } valueToDocument( val, currentElement, doc ); } } } } public String getMultipartHeaderForPart( String operationName, String partName ) { if ( hasOperationSpecificParameter( operationName, Parameters.MULTIPART_HEADERS ) ) { Value v = getOperationSpecificParameterFirstValue( operationName, Parameters.MULTIPART_HEADERS ); if ( v.hasChildren( partName ) ) { v = v.getFirstChild( partName ); if ( v.hasChildren( Parameters.MultiPartHeaders.FILENAME ) ) { v = v.getFirstChild( Parameters.MultiPartHeaders.FILENAME ); return v.strValue(); } } } return null; } private final static String BOUNDARY = "----Jol13H77p77Bound4r155"; private void send_appendCookies( CommMessage message, String hostname, StringBuilder headerBuilder ) { Value cookieParam = null; if ( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) { cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES ); } else if ( hasParameter( Parameters.COOKIES ) ) { cookieParam = getParameterFirstValue( Parameters.COOKIES ); } if ( cookieParam != null ) { Value cookieConfig; String domain; StringBuilder cookieSB = new StringBuilder(); for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) { cookieConfig = entry.getValue().first(); if ( message.value().hasChildren( cookieConfig.strValue() ) ) { domain = cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : ""; if ( domain.isEmpty() || hostname.endsWith( domain ) ) { cookieSB .append( entry.getKey() ) .append( '=' ) .append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() ) .append( ";" ); } } } if ( cookieSB.length() > 0 ) { headerBuilder .append( "Cookie: " ) .append( cookieSB ) .append( CRLF ); } } } private void send_appendSetCookieHeader( CommMessage message, StringBuilder headerBuilder ) { Value cookieParam = null; if ( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) { cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES ); } else if ( hasParameter( Parameters.COOKIES ) ) { cookieParam = getParameterFirstValue( Parameters.COOKIES ); } if ( cookieParam != null ) { Value cookieConfig; for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) { cookieConfig = entry.getValue().first(); if ( message.value().hasChildren( cookieConfig.strValue() ) ) { headerBuilder .append( "Set-Cookie: " ) .append( entry.getKey() ).append( '=' ) .append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() ) .append( "; expires=" ) .append( cookieConfig.hasChildren( "expires" ) ? cookieConfig.getFirstChild( "expires" ).strValue() : "" ) .append( "; domain=" ) .append( cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : "" ) .append( "; path=" ) .append( cookieConfig.hasChildren( "path" ) ? cookieConfig.getFirstChild( "path" ).strValue() : "" ); if ( cookieConfig.hasChildren( "secure" ) && cookieConfig.getFirstChild( "secure" ).intValue() > 0 ) { headerBuilder.append( "; secure" ); } headerBuilder.append( CRLF ); } } } } private String encoding = null; private String requestFormat = null; private void send_appendQuerystring( Value value, String charset, StringBuilder headerBuilder ) throws IOException { if ( value.children().isEmpty() == false ) { headerBuilder.append( '?' ); for( Entry< String, ValueVector > entry : value.children().entrySet() ) { for( Value v : entry.getValue() ) { headerBuilder .append( entry.getKey() ) .append( '=' ) .append( URLEncoder.encode( v.strValue(), charset ) ) .append( '&' ); } } } } private void send_appendJsonQueryString( CommMessage message, String charset, StringBuilder headerBuilder ) throws IOException { if ( message.value().hasChildren() == false ) { headerBuilder.append( "?=" ); JsonUtils.valueToJsonString( message.value(), getSendType( message ), headerBuilder ); } } private void send_appendParsedAlias( String alias, Value value, String charset, StringBuilder headerBuilder ) throws IOException { int offset = 0; ArrayList<String> aliasKeys = new ArrayList<String>(); String currStrValue; String currKey; StringBuilder result = new StringBuilder( alias ); Matcher m = Pattern.compile( "%(!)?\\{[^\\}]*\\}" ).matcher( alias ); while( m.find() ) { if ( m.group( 1 ) == null ) { // We have to use URLEncoder currKey = alias.substring( m.start() + 2, m.end() - 1 ); if ( "$".equals( currKey ) ) { currStrValue = URLEncoder.encode( value.strValue(), charset ); } else { currStrValue = URLEncoder.encode( value.getFirstChild( currKey ).strValue(), charset ); aliasKeys.add( currKey ); } } else { // We have to insert the string raw currKey = alias.substring( m.start() + 3, m.end() - 1 ); if ( "$".equals( currKey ) ) { currStrValue = value.strValue(); } else { currStrValue = value.getFirstChild( currKey ).strValue(); aliasKeys.add( currKey ); } } result.replace( m.start() + offset, m.end() + offset, currStrValue ); offset += currStrValue.length() - 3 - currKey.length(); } // removing used keys for( int k = 0; k < aliasKeys.size(); k++ ) { value.children().remove( aliasKeys.get( k ) ); } headerBuilder.append( result ); } private String getCharset() { String charset = "UTF-8"; if ( hasParameter( "charset" ) ) { charset = getStringParameter( "charset" ); } return charset; } private String send_getFormat() { String format = "xml"; if ( inInputPort && requestFormat != null ) { format = requestFormat; requestFormat = null; } else if ( hasParameter( "format" ) ) { format = getStringParameter( "format" ); } return format; } private static class EncodedContent { private ByteArray content = null; private String contentType = ""; private String contentDisposition = ""; } private EncodedContent send_encodeContent( CommMessage message, Method method, String charset, String format ) throws IOException { EncodedContent ret = new EncodedContent(); if ( inInputPort == false && method == Method.GET ) { // We are building a GET request return ret; } if ( "xml".equals( format ) ) { Document doc = docBuilder.newDocument(); Element root = doc.createElement( message.operationName() + (( inInputPort ) ? "Response" : "") ); doc.appendChild( root ); if ( message.isFault() ) { Element faultElement = doc.createElement( message.fault().faultName() ); root.appendChild( faultElement ); valueToDocument( message.fault().value(), faultElement, doc ); } else { valueToDocument( message.value(), root, doc ); } Source src = new DOMSource( doc ); ByteArrayOutputStream tmpStream = new ByteArrayOutputStream(); Result dest = new StreamResult( tmpStream ); try { transformer.transform( src, dest ); } catch( TransformerException e ) { throw new IOException( e ); } ret.content = new ByteArray( tmpStream.toByteArray() ); ret.contentType = "text/xml"; } else if ( "binary".equals( format ) ) { if ( message.value().isByteArray() ) { ret.content = (ByteArray) message.value().valueObject(); ret.contentType = "application/octet-stream"; } } else if ( "html".equals( format ) ) { ret.content = new ByteArray( message.value().strValue().getBytes( charset ) ); ret.contentType = "text/html"; } else if ( "multipart/form-data".equals( format ) ) { ret.contentType = "multipart/form-data; boundary=" + BOUNDARY; ByteArrayOutputStream bStream = new ByteArrayOutputStream(); StringBuilder builder = new StringBuilder(); for( Entry< String, ValueVector > entry : message.value().children().entrySet() ) { if ( !entry.getKey().startsWith( "@" ) ) { builder.append( "--" ).append( BOUNDARY ).append( CRLF ); builder.append( "Content-Disposition: form-data; name=\"" ).append( entry.getKey() ).append( '\"' ); boolean isBinary = false; if ( hasOperationSpecificParameter( message.operationName(), Parameters.MULTIPART_HEADERS ) ) { Value specOpParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.MULTIPART_HEADERS ); if ( specOpParam.hasChildren( "partName" ) ) { ValueVector partNames = specOpParam.getChildren( "partName" ); for( int p = 0; p < partNames.size(); p++ ) { if ( partNames.get( p ).hasChildren( "part" ) ) { if ( partNames.get( p ).getFirstChild( "part" ).strValue().equals( entry.getKey() ) ) { isBinary = true; if ( partNames.get( p ).hasChildren( "filename" ) ) { builder.append( "; filename=\"" ).append( partNames.get( p ).getFirstChild( "filename" ).strValue() ).append( "\"" ); } if ( partNames.get( p ).hasChildren( "contentType" ) ) { builder.append( CRLF ).append( "Content-Type:" ).append( partNames.get( p ).getFirstChild( "contentType" ).strValue() ); } } } } } } builder.append( CRLF ).append( CRLF ); if ( isBinary ) { bStream.write( builder.toString().getBytes( charset ) ); bStream.write( entry.getValue().first().byteArrayValue().getBytes() ); builder.delete( 0, builder.length() - 1 ); builder.append( CRLF ); } else { builder.append( entry.getValue().first().strValue() ).append( CRLF ); } } } builder.append( "--" + BOUNDARY + "--" ); bStream.write( builder.toString().getBytes( charset )); ret.content = new ByteArray( bStream.toByteArray() ); } else if ( "x-www-form-urlencoded".equals( format ) ) { ret.contentType = "application/x-www-form-urlencoded"; Iterator< Entry< String, ValueVector > > it = message.value().children().entrySet().iterator(); Entry< String, ValueVector > entry; StringBuilder builder = new StringBuilder(); while( it.hasNext() ) { entry = it.next(); builder.append( entry.getKey() ) .append( "=" ) .append( URLEncoder.encode( entry.getValue().first().strValue(), "UTF-8" ) ); if ( it.hasNext() ) { builder.append( '&' ); } } ret.content = new ByteArray( builder.toString().getBytes( charset ) ); } else if ( "text/x-gwt-rpc".equals( format ) ) { ret.contentType = "text/x-gwt-rpc"; try { if ( message.isFault() ) { ret.content = new ByteArray( RPC.encodeResponseForFailure( JolieService.class.getMethods()[0], JolieGWTConverter.jolieToGwtFault( message.fault() ) ).getBytes( charset ) ); } else { joliex.gwt.client.Value v = new joliex.gwt.client.Value(); JolieGWTConverter.jolieToGwtValue( message.value(), v ); ret.content = new ByteArray( RPC.encodeResponseForSuccess( JolieService.class.getMethods()[0], v ).getBytes( charset ) ); } } catch( SerializationException e ) { throw new IOException( e ); } } else if ( "json".equals( format ) || "application/json".equals( format ) ) { ret.contentType = "application/json"; StringBuilder jsonStringBuilder = new StringBuilder(); if ( message.isFault() ) { Value jolieJSONFault = Value.create(); jolieJSONFault.getFirstChild( "jolieFault" ).getFirstChild( "faultName" ).setValue( message.fault().faultName() ); if ( message.fault().value().hasChildren() ) { jolieJSONFault.getFirstChild( "jolieFault" ).getFirstChild( "data" ).deepCopy( message.fault().value() ); } JsonUtils.valueToJsonString( jolieJSONFault, getSendType( message ), jsonStringBuilder ); } else { JsonUtils.valueToJsonString( message.value(), getSendType( message ), jsonStringBuilder ); } ret.content = new ByteArray( jsonStringBuilder.toString().getBytes( charset ) ); } else if ( "raw".equals( format ) ) { ret.content = new ByteArray( message.value().strValue().getBytes( charset ) ); } return ret; } private boolean isLocationNeeded( int statusCode ) { return locationRequiredStatusCodes.contains( statusCode ); } private void send_appendResponseHeaders( CommMessage message, StringBuilder headerBuilder ) { int statusCode = DEFAULT_STATUS_CODE; String statusDescription = null; if( hasParameter( Parameters.STATUS_CODE ) ) { statusCode = getIntParameter( Parameters.STATUS_CODE ); if ( !statusCodeDescriptions.containsKey( statusCode ) ) { Interpreter.getInstance().logWarning( "HTTP protocol for operation " + message.operationName() + " is sending a message with status code " + statusCode + ", which is not in the HTTP specifications." ); statusDescription = "Internal Server Error"; } else if ( isLocationNeeded( statusCode ) && !hasParameter( Parameters.REDIRECT ) ) { // if statusCode is a redirection code, location parameter is needed Interpreter.getInstance().logWarning( "HTTP protocol for operation " + message.operationName() + " is sending a message with status code " + statusCode + ", which expects a redirect parameter but the latter is not set." ); } } else if ( hasParameter( Parameters.REDIRECT ) ) { statusCode = DEFAULT_REDIRECTION_STATUS_CODE; } if ( statusDescription == null ) { statusDescription = statusCodeDescriptions.get( statusCode ); } headerBuilder.append( "HTTP/1.1 " + statusCode + " " + statusDescription + CRLF ); // if redirect has been set, the redirect location parameter is set if ( hasParameter( Parameters.REDIRECT ) ) { headerBuilder.append( "Location: " + getStringParameter( Parameters.REDIRECT ) + CRLF ); } send_appendSetCookieHeader( message, headerBuilder ); headerBuilder.append( "Server: Jolie" ).append( CRLF ); StringBuilder cacheControlHeader = new StringBuilder(); if ( hasParameter( "cacheControl" ) ) { Value cacheControl = getParameterFirstValue( "cacheControl" ); if ( cacheControl.hasChildren( "maxAge" ) ) { cacheControlHeader.append( "max-age=" ).append( cacheControl.getFirstChild( "maxAge" ).intValue() ); } } if ( cacheControlHeader.length() > 0 ) { headerBuilder.append( "Cache-Control: " ).append( cacheControlHeader ).append( CRLF ); } } private void send_appendRequestMethod( Method method, StringBuilder headerBuilder ) { headerBuilder.append( method.id() ); } private void send_appendRequestPath( CommMessage message, Method method, StringBuilder headerBuilder, String charset ) throws IOException { if ( uri.getPath().length() < 1 || uri.getPath().charAt( 0 ) != '/' ) { headerBuilder.append( '/' ); } headerBuilder.append( uri.getPath() ); String alias = getOperationSpecificStringParameter( message.operationName(), Parameters.ALIAS ); if ( alias.isEmpty() ) { headerBuilder.append( message.operationName() ); } else { send_appendParsedAlias( alias, message.value(), charset, headerBuilder ); } if ( method == Method.GET ) { boolean jsonFormat = false; if ( getParameterFirstValue( "method" ).hasChildren( "queryFormat" ) ) { if ( getParameterFirstValue( "method" ).getFirstChild( "queryFormat" ).strValue().equals( "json" ) ) { jsonFormat = true; send_appendJsonQueryString( message, charset, headerBuilder ); } } if ( !jsonFormat ) { send_appendQuerystring( message.value(), charset, headerBuilder ); } } } private static void send_appendAuthorizationHeader( CommMessage message, StringBuilder headerBuilder ) { if ( message.value().hasChildren( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ) ) { Value v = message.value().getFirstChild( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ); //String realm = v.getFirstChild( "realm" ).strValue(); String userpass = v.getFirstChild( "userid" ).strValue() + ":" + v.getFirstChild( "password" ).strValue(); sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder(); userpass = encoder.encode( userpass.getBytes() ); headerBuilder.append( "Authorization: Basic " ).append( userpass ).append( CRLF ); } } private void send_appendHeader( CommMessage message, StringBuilder headerBuilder ) { Value v = getParameterFirstValue( "addHeader" ); if ( v != null ) { if ( v.hasChildren("header") ) { for( Value head : v.getChildren("header") ) { String header = head.strValue() + ": " + head.getFirstChild( "value" ).strValue(); headerBuilder.append( header ).append( CRLF ); } } } } private Method send_getRequestMethod( CommMessage message ) throws IOException { try { Method method = hasOperationSpecificParameter( message.operationName(), Parameters.METHOD ) ? Method.fromString( getOperationSpecificStringParameter( message.operationName(), Parameters.METHOD ).toUpperCase() ) : hasParameter( Parameters.METHOD ) ? Method.fromString( getStringParameter( Parameters.METHOD ).toUpperCase() ) : Method.POST; return method; } catch( Method.UnsupportedMethodException e ) { throw new IOException( e ); } } private void send_appendRequestHeaders( CommMessage message, Method method, StringBuilder headerBuilder, String charset ) throws IOException { send_appendRequestMethod( method, headerBuilder ); headerBuilder.append( ' ' ); send_appendRequestPath( message, method, headerBuilder, charset ); headerBuilder.append( " HTTP/1.1" + CRLF ); headerBuilder.append( "Host: " + uri.getHost() + CRLF ); send_appendCookies( message, uri.getHost(), headerBuilder ); send_appendAuthorizationHeader( message, headerBuilder ); if ( checkBooleanParameter( Parameters.COMPRESSION, true ) ) { String requestCompression = getStringParameter( Parameters.REQUEST_COMPRESSION ); if ( requestCompression.equals( "gzip" ) || requestCompression.equals( "deflate" ) ) { encoding = requestCompression; headerBuilder.append( "Accept-Encoding: " + encoding + CRLF ); } else { headerBuilder.append( "Accept-Encoding: gzip, deflate" + CRLF ); } } send_appendHeader( message, headerBuilder ); } private void send_appendGenericHeaders( CommMessage message, EncodedContent encodedContent, String charset, StringBuilder headerBuilder ) throws IOException { String param; if ( checkBooleanParameter( "keepAlive", true ) == false || channel().toBeClosed() ) { channel().setToBeClosed( true ); headerBuilder.append( "Connection: close" + CRLF ); } if ( checkBooleanParameter( Parameters.CONCURRENT, true ) ) { headerBuilder.append( Headers.JOLIE_MESSAGE_ID ).append( ": " ).append( message.id() ).append( CRLF ); } if ( encodedContent.content != null ) { String contentType = getStringParameter( "contentType" ); if ( contentType.length() > 0 ) { encodedContent.contentType = contentType; } headerBuilder.append( "Content-Type: " + encodedContent.contentType ); if ( charset != null ) { headerBuilder.append( "; charset=" + charset.toLowerCase() ); } headerBuilder.append( CRLF ); param = getStringParameter( "contentTransferEncoding" ); if ( !param.isEmpty() ) { headerBuilder.append( "Content-Transfer-Encoding: " + param + CRLF ); } String contentDisposition = getStringParameter( "contentDisposition" ); if ( contentDisposition.length() > 0 ) { encodedContent.contentDisposition = contentDisposition; headerBuilder.append( "Content-Disposition: " + encodedContent.contentDisposition + CRLF ); } boolean compression = ( encoding != null ) && checkBooleanParameter( Parameters.COMPRESSION, true ); String compressionTypes = getStringParameter( Parameters.COMPRESSION_TYPES, "text/html text/css text/plain text/xml text/x-js application/json application/javascript" ); if ( !compressionTypes.equals( "*" ) && !compressionTypes.contains( encodedContent.contentType ) ) { compression = false; } if ( compression ) { if ( encoding.contains( "gzip" ) ) { ByteArrayOutputStream baOutStream = new ByteArrayOutputStream(); GZIPOutputStream outStream = new GZIPOutputStream( baOutStream ); outStream.write( encodedContent.content.getBytes() ); outStream.close(); encodedContent.content = new ByteArray( baOutStream.toByteArray() ); headerBuilder.append( "Content-Encoding: gzip" + CRLF ); } else if ( encoding.contains( "deflate" ) ) { ByteArrayOutputStream baOutStream = new ByteArrayOutputStream(); DeflaterOutputStream outStream = new DeflaterOutputStream( baOutStream ); outStream.write( encodedContent.content.getBytes() ); outStream.close(); encodedContent.content = new ByteArray( baOutStream.toByteArray() ); headerBuilder.append( "Content-Encoding: deflate" + CRLF ); } } headerBuilder.append( "Content-Length: " + (encodedContent.content.size()) + CRLF ); //headerBuilder.append( "Content-Length: " + (encodedContent.content.size() + 2) + CRLF ); } else { headerBuilder.append( "Content-Length: 0" + CRLF ); } } private void send_logDebugInfo( CharSequence header, EncodedContent encodedContent ) { if ( checkBooleanParameter( "debug" ) ) { StringBuilder debugSB = new StringBuilder(); debugSB.append( "[HTTP debug] Sending:\n" ); debugSB.append( header ); if ( getParameterVector( "debug" ).first().getFirstChild( "showContent" ).intValue() > 0 && encodedContent.content != null ) { debugSB.append( encodedContent.content.toString() ); } Interpreter.getInstance().logInfo( debugSB.toString() ); } } public void send( OutputStream ostream, CommMessage message, InputStream istream ) throws IOException { Method method = send_getRequestMethod( message ); String charset = getCharset(); String format = send_getFormat(); EncodedContent encodedContent = send_encodeContent( message, method, charset, format ); StringBuilder headerBuilder = new StringBuilder(); if ( inInputPort ) { // We're responding to a request send_appendResponseHeaders( message, headerBuilder ); } else { // We're sending a notification or a solicit send_appendRequestHeaders( message, method, headerBuilder, charset ); } send_appendGenericHeaders( message, encodedContent, charset, headerBuilder ); headerBuilder.append( CRLF ); send_logDebugInfo( headerBuilder, encodedContent ); inputId = message.operationName(); /*if ( charset == null ) { charset = "UTF8"; }*/ ostream.write( headerBuilder.toString().getBytes( charset ) ); if ( encodedContent.content != null ) { ostream.write( encodedContent.content.getBytes() ); //ostream.write( CRLF.getBytes( charset ) ); } } private void parseXML( HttpMessage message, Value value ) throws IOException { try { if ( message.size() > 0 ) { DocumentBuilder builder = docBuilderFactory.newDocumentBuilder(); InputSource src = new InputSource( new ByteArrayInputStream( message.content() ) ); Document doc = builder.parse( src ); XmlUtils.documentToValue( doc, value ); } } catch( ParserConfigurationException pce ) { throw new IOException( pce ); } catch( SAXException saxe ) { throw new IOException( saxe ); } } private static void parseJson( HttpMessage message, Value value, boolean strictEncoding ) throws IOException { JsonUtils.parseJsonIntoValue( new InputStreamReader( new ByteArrayInputStream( message.content() ) ), value, strictEncoding ); } private static void parseForm( HttpMessage message, Value value, String charset ) throws IOException { String line = new String( message.content(), "UTF8" ); String[] pair; for( String item : line.split( "&" ) ) { pair = item.split( "=", 2 ); value.getChildren( pair[0] ).first().setValue( URLDecoder.decode( pair[1], charset ) ); } } private void parseMultiPartFormData( HttpMessage message, Value value ) throws IOException { multiPartFormDataParser = new MultiPartFormDataParser( message, value ); multiPartFormDataParser.parse(); } private static String parseGWTRPC( HttpMessage message, Value value ) throws IOException { RPCRequest request = RPC.decodeRequest( new String( message.content(), "UTF8" ) ); String operationName = (String)request.getParameters()[0]; joliex.gwt.client.Value requestValue = (joliex.gwt.client.Value)request.getParameters()[1]; JolieGWTConverter.gwtToJolieValue( requestValue, value ); return operationName; } private void recv_checkForSetCookie( HttpMessage message, Value value ) throws IOException { if ( hasParameter( Parameters.COOKIES ) ) { String type; Value cookies = getParameterFirstValue( Parameters.COOKIES ); Value cookieConfig; Value v; for( HttpMessage.Cookie cookie : message.setCookies() ) { if ( cookies.hasChildren( cookie.name() ) ) { cookieConfig = cookies.getFirstChild( cookie.name() ); if ( cookieConfig.isString() ) { v = value.getFirstChild( cookieConfig.strValue() ); type = cookieConfig.hasChildren( "type" ) ? cookieConfig.getFirstChild( "type" ).strValue() : "string"; recv_assignCookieValue( cookie.value(), v, type ); } } /*currValue = Value.create(); currValue.getNewChild( "expires" ).setValue( cookie.expirationDate() ); currValue.getNewChild( "path" ).setValue( cookie.path() ); currValue.getNewChild( "name" ).setValue( cookie.name() ); currValue.getNewChild( "value" ).setValue( cookie.value() ); currValue.getNewChild( "domain" ).setValue( cookie.domain() ); currValue.getNewChild( "secure" ).setValue( (cookie.secure() ? 1 : 0) ); cookieVec.add( currValue );*/ } } } private void recv_assignCookieValue( String cookieValue, Value value, String typeKeyword ) throws IOException { NativeType type = NativeType.fromString( typeKeyword ); if ( NativeType.INT == type ) { try { value.setValue( new Integer( cookieValue ) ); } catch( NumberFormatException e ) { throw new IOException( e ); } } else if ( NativeType.LONG == type ) { try { value.setValue( new Long( cookieValue ) ); } catch( NumberFormatException e ) { throw new IOException( e ); } } else if ( NativeType.STRING == type ) { value.setValue( cookieValue ); } else if ( NativeType.DOUBLE == type ) { try { value.setValue( new Double( cookieValue ) ); } catch( NumberFormatException e ) { throw new IOException( e ); } } else if ( NativeType.BOOL == type ) { value.setValue( Boolean.valueOf( cookieValue ) ); } else { value.setValue( cookieValue ); } } private void recv_checkForCookies( HttpMessage message, DecodedMessage decodedMessage ) throws IOException { Value cookies = null; if ( hasOperationSpecificParameter( decodedMessage.operationName, Parameters.COOKIES ) ) { cookies = getOperationSpecificParameterFirstValue( decodedMessage.operationName, Parameters.COOKIES ); } else if ( hasParameter( Parameters.COOKIES ) ) { cookies = getParameterFirstValue( Parameters.COOKIES ); } if ( cookies != null ) { Value v; String type; for( Entry< String, String > entry : message.cookies().entrySet() ) { if ( cookies.hasChildren( entry.getKey() ) ) { Value cookieConfig = cookies.getFirstChild( entry.getKey() ); if ( cookieConfig.isString() ) { v = decodedMessage.value.getFirstChild( cookieConfig.strValue() ); if ( cookieConfig.hasChildren( "type" ) ) { type = cookieConfig.getFirstChild( "type" ).strValue(); } else { type = "string"; } recv_assignCookieValue( entry.getValue(), v, type ); } } } } } private void recv_checkForGenericHeader( HttpMessage message, DecodedMessage decodedMessage ) throws IOException { Value headers = null; if ( hasOperationSpecificParameter( decodedMessage.operationName, Parameters.HEADERS ) ) { headers = getOperationSpecificParameterFirstValue( decodedMessage.operationName, Parameters.HEADERS ); } else if ( hasParameter( Parameters.HEADERS ) ) { headers = getParameterFirstValue( Parameters.HEADERS ); } if ( headers != null ) { for( String headerName : headers.children().keySet() ) { String headerAlias = headers.getFirstChild( headerName ).strValue(); headerName = headerName.replace( "_", "-" ); decodedMessage.value.getFirstChild( headerAlias ).setValue( message.getPropertyOrEmptyString( headerName ) ); } } } private static void recv_parseQueryString( HttpMessage message, Value value ) { Map< String, Integer > indexes = new HashMap< String, Integer >(); String queryString = message.requestPath() == null ? "" : message.requestPath(); String[] kv = queryString.split( "\\?" ); Integer index; if ( kv.length > 1 ) { queryString = kv[1]; String[] params = queryString.split( "&" ); for( String param : params ) { kv = param.split( "=", 2 ); if ( kv.length > 1 ) { index = indexes.get( kv[0] ); if ( index == null ) { index = 0; indexes.put( kv[0], index ); } value.getChildren( kv[0] ).get( index ).setValue( kv[1] ); indexes.put( kv[0], index + 1 ); } } } } /* * Prints debug information about a received message */ private void recv_logDebugInfo( HttpMessage message ) { StringBuilder debugSB = new StringBuilder(); debugSB.append( "[HTTP debug] Receiving:\n" ); debugSB.append( "HTTP Code: " + message.statusCode() + "\n" ); debugSB.append( "Resource: " + message.requestPath() + "\n" ); debugSB.append( "--> Header properties\n" ); for( Entry< String, String > entry : message.properties() ) { debugSB.append( '\t' + entry.getKey() + ": " + entry.getValue() + '\n' ); } for( HttpMessage.Cookie cookie : message.setCookies() ) { debugSB.append( "\tset-cookie: " + cookie.toString() + '\n' ); } for( Entry< String, String > entry : message.cookies().entrySet() ) { debugSB.append( "\tcookie: " + entry.getKey() + '=' + entry.getValue() + '\n' ); } if ( getParameterFirstValue( "debug" ).getFirstChild( "showContent" ).intValue() > 0 && message.content() != null ) { debugSB.append( "--> Message content\n" ); debugSB.append( new String( message.content() ) ); } Interpreter.getInstance().logInfo( debugSB.toString() ); } private void recv_parseRequestFormat( HttpMessage message ) throws IOException { requestFormat = null; String type = message.getPropertyOrEmptyString( "content-type" ).split( ";" )[0]; if ( "text/x-gwt-rpc".equals( type ) ) { requestFormat = "text/x-gwt-rpc"; } else if ( "application/json".equals( type ) ) { requestFormat = "application/json"; } } private void recv_parseMessage( HttpMessage message, DecodedMessage decodedMessage, String charset ) throws IOException { String format = "xml"; if ( hasParameter( "format" ) ) { format = getStringParameter( "format" ); } String type = message.getProperty( "content-type" ).split( ";" )[0]; if ( "text/html".equals( type ) ) { decodedMessage.value.setValue( new String( message.content() ) ); } else if ( "application/x-www-form-urlencoded".equals( type ) ) { parseForm( message, decodedMessage.value, charset ); } else if ( "text/xml".equals( type ) ) { parseXML( message, decodedMessage.value ); } else if ( "text/x-gwt-rpc".equals( type ) ) { decodedMessage.operationName = parseGWTRPC( message, decodedMessage.value ); } else if ( "multipart/form-data".equals( type ) ) { parseMultiPartFormData( message, decodedMessage.value ); } else if ( "application/octet-stream".equals( type ) || type.startsWith( "image/" ) || "application/zip".equals( type ) ) { decodedMessage.value.setValue( new ByteArray( message.content() ) ); } else if ( "application/json".equals( type ) || "json".equals( format ) ) { boolean strictEncoding = checkStringParameter( "json_encoding", "strict" ); parseJson( message, decodedMessage.value, strictEncoding ); } else if ( "xml".equals( format ) || "rest".equals( format ) ) { parseXML( message, decodedMessage.value ); } else { decodedMessage.value.setValue( new String( message.content() ) ); } } private String getDefaultOperation( HttpMessage.Type t ) { if ( hasParameter( Parameters.DEFAULT_OPERATION ) ) { Value dParam = getParameterFirstValue( Parameters.DEFAULT_OPERATION ); String method = t == HttpMessage.Type.GET ? "get" : t == HttpMessage.Type.HEAD ? "head" : t == HttpMessage.Type.POST ? "post" : t == HttpMessage.Type.PUT ? "put" : t == HttpMessage.Type.DELETE ? "delete" : null; if ( method == null || dParam.hasChildren( method ) == false ) { return dParam.strValue(); } else { return dParam.getFirstChild( method ).strValue(); } } return null; } private void recv_checkReceivingOperation( HttpMessage message, DecodedMessage decodedMessage ) { if ( decodedMessage.operationName == null ) { String requestPath = message.requestPath().split( "\\?" )[0]; decodedMessage.operationName = requestPath; Matcher m = LocationParser.RESOURCE_SEPARATOR_PATTERN.matcher( decodedMessage.operationName ); if ( m.find() ) { int resourceStart = m.end(); if ( m.find() ) { decodedMessage.resourcePath = requestPath.substring( resourceStart - 1, m.start() ); decodedMessage.operationName = requestPath.substring( m.end(), requestPath.length() ); } } } if ( decodedMessage.resourcePath.equals( "/" ) && !channel().parentInputPort().canHandleInputOperation( decodedMessage.operationName ) ) { String defaultOpId = getDefaultOperation( message.type() ); if ( defaultOpId != null ) { Value body = decodedMessage.value; decodedMessage.value = Value.create(); decodedMessage.value.getChildren( "data" ).add( body ); decodedMessage.value.getFirstChild( "operation" ).setValue( decodedMessage.operationName ); if ( message.userAgent() != null ) { decodedMessage.value.getFirstChild( Parameters.USER_AGENT ).setValue( message.userAgent() ); } Value cookies = decodedMessage.value.getFirstChild( "cookies" ); for( Entry< String, String > cookie : message.cookies().entrySet() ) { cookies.getFirstChild( cookie.getKey() ).setValue( cookie.getValue() ); } decodedMessage.operationName = defaultOpId; } } } private void recv_checkForMultiPartHeaders( DecodedMessage decodedMessage ) { if ( multiPartFormDataParser != null ) { String target; for( Entry< String, MultiPartFormDataParser.PartProperties > entry : multiPartFormDataParser.getPartPropertiesSet() ) { if ( entry.getValue().filename() != null ) { target = getMultipartHeaderForPart( decodedMessage.operationName, entry.getKey() ); if ( target != null ) { decodedMessage.value.getFirstChild( target ).setValue( entry.getValue().filename() ); } } } multiPartFormDataParser = null; } } private void recv_checkForMessageProperties( HttpMessage message, DecodedMessage decodedMessage ) throws IOException { recv_checkForCookies( message, decodedMessage ); recv_checkForGenericHeader( message, decodedMessage ); recv_checkForMultiPartHeaders( decodedMessage ); if ( message.userAgent() != null && hasParameter( Parameters.USER_AGENT ) ) { getParameterFirstValue( Parameters.USER_AGENT ).setValue( message.userAgent() ); } if ( getParameterVector( Parameters.HOST ) != null ) { getParameterFirstValue( Parameters.HOST ).setValue( message.getPropertyOrEmptyString( Parameters.HOST ) ); } } private static class DecodedMessage { private String operationName = null; private Value value = Value.create(); private String resourcePath = "/"; private long id = CommMessage.GENERIC_ID; } private void recv_checkForStatusCode( HttpMessage message ) { if ( hasParameter( Parameters.STATUS_CODE ) ) { getParameterFirstValue( Parameters.STATUS_CODE ).setValue( message.statusCode() ); } } public CommMessage recv( InputStream istream, OutputStream ostream ) throws IOException { CommMessage retVal = null; DecodedMessage decodedMessage = new DecodedMessage(); HttpMessage message = new HttpParser( istream ).parse(); HttpUtils.recv_checkForChannelClosing( message, channel() ); if ( checkBooleanParameter( Parameters.DEBUG ) ) { recv_logDebugInfo( message ); } if ( !message.isSupported() ) { int error = 501; Writer writer = new OutputStreamWriter(ostream); writer.write( "HTTP/1.1 " + error + " " + statusCodeDescriptions.get( error ) + CRLF ); writer.write( "Content-Type: text/plain; charset=\"utf-8\"" + CRLF ); writer.write( "Content-Length: " + statusCodeDescriptions.get( error ).length() + CRLF + CRLF ); writer.write( statusCodeDescriptions.get( error ) ); writer.flush(); return null; } recv_checkForStatusCode( message ); String charset = getCharset(); encoding = message.getProperty( "accept-encoding" ); recv_parseRequestFormat( message ); if ( message.size() > 0 ) { recv_parseMessage( message, decodedMessage, charset ); } if ( checkBooleanParameter( Parameters.CONCURRENT ) ) { String messageId = message.getProperty( Headers.JOLIE_MESSAGE_ID ); if ( messageId != null ) { try { decodedMessage.id = Long.parseLong( messageId ); } catch( NumberFormatException e ) {} } } if ( message.isResponse() ) { recv_checkForSetCookie( message, decodedMessage.value ); retVal = new CommMessage( decodedMessage.id, inputId, decodedMessage.resourcePath, decodedMessage.value, null ); } else if ( message.isError() == false ) { if ( message.isGet() ) { recv_parseQueryString( message, decodedMessage.value ); } recv_checkReceivingOperation( message, decodedMessage ); recv_checkForMessageProperties( message, decodedMessage ); retVal = new CommMessage( decodedMessage.id, decodedMessage.operationName, decodedMessage.resourcePath, decodedMessage.value, null ); } if ( retVal != null && "/".equals( retVal.resourcePath() ) && channel().parentPort() != null && (channel().parentPort().getInterface().containsOperation( retVal.operationName() ) || channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) != null) ) { try { // The message is for this service boolean hasInput = false; OneWayTypeDescription oneWayTypeDescription = null; if ( channel().parentInputPort() != null ) { if ( channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) != null ) { oneWayTypeDescription = channel().parentInputPort().getAggregatedOperation( retVal.operationName() ).getOperationTypeDescription().asOneWayTypeDescription(); hasInput = true; } } if ( !hasInput ) { Interface iface = channel().parentPort().getInterface(); oneWayTypeDescription = iface.oneWayOperations().get( retVal.operationName() ); } if ( oneWayTypeDescription != null ) { // We are receiving a One-Way message oneWayTypeDescription.requestType().cast( retVal.value() ); } else { hasInput = false; RequestResponseTypeDescription rrTypeDescription = null; if ( channel().parentInputPort() != null ) { if ( channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) != null ) { rrTypeDescription = channel().parentInputPort().getAggregatedOperation( retVal.operationName() ).getOperationTypeDescription().asRequestResponseTypeDescription(); hasInput = true; } } if ( !hasInput ) { Interface iface = channel().parentPort().getInterface(); rrTypeDescription = iface.requestResponseOperations().get( retVal.operationName() ); } if ( retVal.isFault() ) { Type faultType = rrTypeDescription.faults().get( retVal.fault().faultName() ); if ( faultType != null ) { faultType.cast( retVal.value() ); } } else { if ( message.isResponse() ) { rrTypeDescription.responseType().cast( retVal.value() ); } else { rrTypeDescription.requestType().cast( retVal.value() ); } } } } catch( TypeCastingException e ) { // TODO: do something here? } } return retVal; } private Type getSendType( CommMessage message ) throws IOException { Type ret = null; if ( channel().parentPort() == null ) { throw new IOException( "Could not retrieve communication port for HTTP protocol" ); } OperationTypeDescription opDesc = channel().parentPort().getOperationTypeDescription( message.operationName(), Constants.ROOT_RESOURCE_PATH ); if ( opDesc == null ) { throw new IOException( "Operation " + message.operationName() + " not declared in port interface for HTTP protocol" ); } if ( opDesc.asOneWayTypeDescription() != null ) { if ( message.isFault() ) { ret = Type.UNDEFINED; } else { OneWayTypeDescription ow = opDesc.asOneWayTypeDescription(); ret = ow.requestType(); } } else if ( opDesc.asRequestResponseTypeDescription() != null ) { RequestResponseTypeDescription rr = opDesc.asRequestResponseTypeDescription(); if ( message.isFault() ) { ret = rr.getFaultType( message.fault().faultName() ); if ( ret == null ) { ret = Type.UNDEFINED; } } else { ret = ( inInputPort ) ? rr.responseType() : rr.requestType(); } } else { throw new IOException( "Internal error" ); } return ret; } }
package codequiz; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.DataLine; import javax.swing.*; public class MainUI { private MainGUI mainGUI; public MainUI() { showGUI(); playSoundClip(); } public void showGUI() { mainGUI = new MainGUI(); JFrame mainFrame = new JFrame("MainUI"); mainFrame.setTitle("Code Quiz"); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.add(mainGUI); mainFrame.pack(); mainFrame.setVisible(true); } public void playSoundClip() { try { File filename = new File("C:/Code Quiz/HarryPotterThemeSong.wav"); AudioInputStream audioInputStream; AudioFormat audioFormat; DataLine.Info info; Clip clip; audioInputStream = AudioSystem.getAudioInputStream(filename); audioFormat = audioInputStream.getFormat(); info = new DataLine.Info(Clip.class, audioFormat); clip = (Clip) AudioSystem.getLine(info); clip.open(audioInputStream); clip.start(); } catch(Exception e) { System.out.println("Ljudfilen kunde inte spelas upp."); e.printStackTrace(); } } private class MainGUI extends JPanel { // Paneler private JPanel northPanel; private JPanel centerPanel; private JPanel eastPanel; // Labels private JLabel lblTitle = new JLabel("Code Quiz"); private JLabel lblSlogan = new JLabel( "- Ett magiskt sätt att lära sig programmering"); private JLabel lblMenu = new JLabel("Meny"); private JLabel lblInvisible = new JLabel(); private JLabel lblInvisible2 = new JLabel(); private JLabel lblInvisible3 = new JLabel(); private JLabel lblInvisible4 = new JLabel(); private JLabel lblInvisible5 = new JLabel(); // Knappar private JButton btnPlay = new JButton("Spela"); private JButton btnSignIn = new JButton("Logga in"); private JButton btnCreateAccount = new JButton("Skapa ett nytt konto"); private JButton btnHowToPlay = new JButton("Om spelet"); private JButton btnHighScore = new JButton("High score"); // private ButtonGroup btnGroup = new ButtonGroup(); // Image private ImageIcon iconHogwarts; public MainGUI() { setLayout(new BorderLayout()); setPreferredSize(new Dimension(900, 500)); add(northPanel(), BorderLayout.NORTH); add(centerPanel(), BorderLayout.CENTER); add(eastPanel(), BorderLayout.EAST); } /** * Visar titel och slogan. * * @return */ public JPanel northPanel() { northPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); northPanel.setPreferredSize(new Dimension(100, 100)); northPanel.setBackground(Color.BLACK); northPanel.add(Box.createRigidArea(new Dimension(150, 20))); northPanel.add(lblTitle); lblTitle.setForeground(Color.WHITE); lblTitle.setFont(new Font("SansSerif", Font.BOLD, 50)); northPanel.add(Box.createRigidArea(new Dimension(220, 20))); northPanel.add(lblSlogan); lblSlogan.setForeground(Color.WHITE); lblSlogan.setFont(new Font("SansSerif", Font.ITALIC, 15)); return northPanel; } public JPanel centerPanel() { centerPanel = new JPanel(new FlowLayout()); centerPanel.setPreferredSize(new Dimension(400, 150)); centerPanel.setBackground(Color.BLACK); centerPanel.add(Box.createRigidArea(new Dimension(500, 25))); iconHogwarts = new ImageIcon("C:/Code Quiz/Hogwarts.png"); centerPanel.add(new JLabel(iconHogwarts)); return centerPanel; } /** * Visar menyn. * * @return */ public JPanel eastPanel() { eastPanel = new JPanel(new GridLayout(15, 1)); eastPanel.setPreferredSize(new Dimension(150, 10)); eastPanel.setBorder(BorderFactory.createLineBorder(Color.WHITE)); eastPanel.setBackground(Color.BLACK); eastPanel.add(lblMenu); lblMenu.setForeground(Color.WHITE); lblMenu.setFont(new Font("SansSerif", Font.BOLD, 26)); eastPanel.add(lblInvisible); eastPanel.add(btnPlay); eastPanel.add(lblInvisible2); eastPanel.add(btnSignIn); eastPanel.add(lblInvisible3); eastPanel.add(btnCreateAccount); eastPanel.add(lblInvisible4); eastPanel.add(btnHowToPlay); eastPanel.add(lblInvisible5); eastPanel.add(btnHighScore); btnPlay.setBackground(Color.BLACK); btnPlay.setForeground(Color.WHITE); btnSignIn.setBackground(Color.BLACK); btnSignIn.setForeground(Color.WHITE); btnCreateAccount.setBackground(Color.BLACK); btnCreateAccount.setForeground(Color.WHITE); btnHowToPlay.setBackground(Color.BLACK); btnHowToPlay.setForeground(Color.WHITE); btnHighScore.setBackground(Color.BLACK); btnHighScore.setForeground(Color.WHITE); return eastPanel; } private class MenuListener implements ActionListener { public void actionPerformed(ActionEvent e) { } } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new MainUI(); } }); } }
package infodoc.core.container; import infodoc.core.dto.Activity; import infodoc.core.dto.ActivityInstance; import infodoc.core.dto.Case; import infodoc.core.dto.ClassificationValue; import infodoc.core.dto.Form; import infodoc.core.dto.Property; import infodoc.core.dto.PropertyValue; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Set; import org.hibernate.Query; @SuppressWarnings("unchecked") public class CaseContainer extends UserGroupFilteredContainer<Case> { private static final long serialVersionUID = 1L; public CaseContainer() { super(Case.class, "form.userGroup.id"); } public Case getCurrentByNumber(Long number) { return singleQuery( "select c" + " from Case c" + " where c.number = ?" + " order by c.id desc" + " limit 1", new Object[] {number}); } public List<Case> findMyCases(Long userId, Long formId) { return query( "select distinct c" + " from Case c" + " join c.activityInstances ai" + " join ai.activity.nextActivities nextAct" + " left join ai.assignedUsers assignedU1" + " left join ai.assignedUserGroups assignedUG" + " left join assignedUG.users assignedU2" + " where ai.id = (select max(ai2.id) from ActivityInstance ai2 where ai2.caseDto.id = c.id)" + " and (assignedU1.id = ? or assignedU2.id = ? or (ai.assignedUsers is empty and ai.assignedUserGroups is empty))" + " and (? = null or c.form.id = ?)" + " order by ai.executionTime desc", new Object [] {userId, userId, formId, formId} ); } public List<Case> findAvailableByUserIdAndNextActivityId(Long userId, Long activityId) { return query( "select distinct c" + " from Case c" + " join c.activityInstances ai" + " join ai.activity.nextActivities nextAct" + " left join ai.assignedUsers assignedU1" + " left join ai.assignedUserGroups assignedUG" + " left join assignedUG.users assignedU2" + " where ai.id = (select max(ai2.id) from ActivityInstance ai2 where ai2.caseDto.id = c.id)" + " and (assignedU1.id = ? or assignedU2.id = ? or (ai.assignedUsers is empty and ai.assignedUserGroups is empty))" + " and nextAct.id = ?" + " order by ai.executionTime desc", new Object [] {userId, userId, activityId} ); } public List<Case> findAvailableByUserIdAndActivityId(Long userId, Long activityId) { return query( "select distinct c" + " from Case c" + " join c.activityInstances ai" + " left join ai.assignedUsers assignedU1" + " left join ai.assignedUserGroups assignedUG" + " left join assignedUG.users assignedU2" + " where ai.id = (select max(ai2.id) from ActivityInstance ai2 where ai2.caseDto.id = c.id)" + " and (assignedU1.id = ? or assignedU2.id = ? or (ai.assignedUsers is empty and ai.assignedUserGroups is empty))" + " and ai.activity.id = ?" + " order by ai.executionTime desc", new Object [] {userId, userId, activityId} ); } public List<Case> findAssignedToOtherUserByUserIdAndNextActivityId(Long userId, Long activityId) { return query( "select distinct c" + " from Case c" + " join c.activityInstances ai" + " join ai.activity.nextActivities nextAct" + " where ai.id = (select max(ai2.id) from ActivityInstance ai2 where ai.caseDto.id = c.id)" + " and ai.user.id = ?" + " and nextAct.id = ?" + " and ai.user.id not in (select u.id from ActivityInstance ai2 join ai2.assignedUsers u where ai2.id = ai.id)", new Object [] {userId, activityId} ); } public List<Case> findAssignedByUserIdAndCurrentActivityId(Long userId, Long activityId) { return query( "select distinct c" + " from Case c" + " join c.activityInstances ai" + " where ai.id = (select max(ai2.id) from ActivityInstance ai2 where ai2.caseDto.id = c.id)" + " and ai.user.id = ?" + " and ai.activity.id = ?", new Object [] {userId, activityId} ); } public List<Case> findByActivityId(Long activityId) { String condition = getHqlConditionToFilterByUserGroup(); if(!condition.isEmpty()) { condition = " and c." + condition; } return query( "select distinct c" + " from Case c" + " join c.activityInstances ai" + " where ai.id = (select max(ai2.id) from ActivityInstance ai2 where ai2.caseDto.id = c.id)" + " and ai.activity.id = ?" + condition, new Object [] {activityId} ); } public List<Case> findByLastActivityId(Long activityId) { return query( "select distinct c" + " from Case c" + " join c.activityInstances lastAi" + " where lastAi.id = (select max(ai2.id) from ActivityInstance ai2 where ai2.caseDto.id = c.id)" + " and lastAi.activity.id = ?", new Object [] {activityId} ); } public List<Case> findPendingByFormId(Long formId, Date from, Date to) { return query( "select distinct c" + " from Case c" + " join c.activityInstances lastAi" + " join c.activityInstances firstAi" + " where firstAi.id = (select min(ai.id) from ActivityInstance ai where ai.caseDto.id = c.id)" + " and lastAi.id = (select max(ai2.id) from ActivityInstance ai2 where ai2.caseDto.id = c.id)" + " and lastAi.activity.nextActivities is not empty" + " and c.form.id = ?" + " and date(firstAi.executionTime) >= date(?)" + " and date(lastAi.executionTime) <= date(?)", new Object [] {formId, from, to} ); } public List<Case> findPendingByFormId(Long formId) { return query( "select distinct c" + " from Case c" + " join c.activityInstances lastAi" + " join c.activityInstances firstAi" + " where firstAi.id = (select min(ai.id) from ActivityInstance ai where ai.caseDto.id = c.id)" + " and lastAi.id = (select max(ai2.id) from ActivityInstance ai2 where ai2.caseDto.id = c.id)" + " and lastAi.activity.nextActivities is not empty" + " and c.form.id = ?" + new Object [] {formId} ); } public boolean isPending(Case caseDto) { Set<Activity> nextActivities = getLastActivityInstance(caseDto).getActivity().getNextActivities(); return nextActivities != null && !nextActivities.isEmpty(); } public List<Case> findFinishedByFormId(Long formId, Date from, Date to) { return query( "select distinct c" + " from Case c" + " join c.activityInstances lastAi" + " join c.activityInstances firstAi" + " left join lastAi.activity.nextActivities nextAct" + " where firstAi.id = (select min(ai.id) from ActivityInstance ai where ai.caseDto.id = c.id)" + " and lastAi.id = (select max(ai2.id) from ActivityInstance ai2 where ai2.caseDto.id = c.id)" + " and c.form.id = ?" + " and nextAct is null" + " and date(firstAi.executionTime) >= date(?)" + " and date(lastAi.executionTime) <= date(?)", new Object [] {formId, from, to} ); } public List<Case> findByNumberAndFormId(Long number, Long formId) { return query( "select distinct c" + " from Case c" + " where c.form.id = ?" + " and c.number = ?" + " and c." + getHqlConditionToFilterByUserGroup(), new Object[] {number, formId}); } public List<Case> findReferencingCases(Long referencingPropertyId, Long referencedCaseId, Long formId) { return query( "select c" + " from Case c" + " join c.propertyValues pv" + " join pv.property p" + " join pv.caseDtosValue cv" + " where p.id = ?" + " and cv.id = ?" + " and c.form.id = ?", new Object[] {referencingPropertyId, referencedCaseId, formId} ); } // TODO: validate consistency public Case saveInstace(Case caseDto, Collection<PropertyValue> propertyValues, ActivityInstance activityInstace, boolean useNumeration) { try { if(useNumeration) { Long nextValue = InfodocContainerFactory.getNumerationContainer().getNextCaseNumber(caseDto.getForm().getId()); caseDto.setNumber(nextValue); } InfodocContainerFactory.getCaseContainer().saveEntity(caseDto); saveActivityInstance(caseDto, propertyValues, activityInstace); savePropertyValues(propertyValues); return InfodocContainerFactory.getCaseContainer().getEntity(caseDto.getId()); } catch (Exception e) { sessionManager.getSession().getTransaction().rollback(); throw new RuntimeException(e); } } // TODO: validate consistency public Case updateInstance(Case caseDto, Collection<PropertyValue> propertyValues, ActivityInstance activityInstance) { try { saveActivityInstance(caseDto, propertyValues, activityInstance); savePropertyValues(propertyValues); if(propertyValues != null) { caseDto.getPropertyValues().addAll(propertyValues); } InfodocContainerFactory.getCaseContainer().saveOrUpdateEntity(caseDto); return InfodocContainerFactory.getCaseContainer().getEntity(caseDto.getId()); } catch (Exception e) { sessionManager.getSession().getTransaction().rollback(); throw new RuntimeException(e); } } private void saveActivityInstance(Case caseDto, Collection<PropertyValue> propertyValues, ActivityInstance activityInstance) { activityInstance.setCaseDto(caseDto); InfodocContainerFactory.getActivityInstanceContainer().saveEntity(activityInstance); } private void savePropertyValues(Collection<PropertyValue> propertyValues) { if(propertyValues != null) { for(PropertyValue value : propertyValues) { InfodocContainerFactory.getPropertyValueContainer().saveOrUpdateEntity(value); } } } public Object getValue(Case c, Property property) { if(c.getPropertyValues() != null) { for(PropertyValue value : c.getPropertyValues()) { if(value.getProperty().getId().equals(property.getId())) { return InfodocContainerFactory.getPropertyValueContainer().getValue(value); } } } return null; } public ActivityInstance getFisrtActivityInstance(Case instance) { ActivityInstance activityInstance = null; if(instance.getActivityInstances() != null && !instance.getActivityInstances().isEmpty()) { activityInstance = (ActivityInstance) instance.getActivityInstances().toArray()[0]; } return activityInstance; } public ActivityInstance getLastActivityInstance(Case instance) { ActivityInstance activityInstance = null; if(instance.getActivityInstances() != null && !instance.getActivityInstances().isEmpty()) { activityInstance = (ActivityInstance) instance.getActivityInstances().toArray()[instance.getActivityInstances().size() - 1]; } return activityInstance; } public Collection<Long> search( Form form, Collection<PropertyValue> propertyValues, String number, Activity activity, Date startDate, Date endDate, String initialUser, String endUser, String initialUserGroup, String endUserGroup, String comments, boolean lastActivityInstance, boolean pending ) { List<Long> foundInstancesIds = new ArrayList<Long>(); for(PropertyValue value : propertyValues) { String query = "select distinct c.id" + " from Case c" + " left join c.propertyValues value" + " left join value.classificationsValueValue classificationsValueValue" + " left join value.caseDtosValue caseDtosValue" + " left join c.activityInstances activityInstance" + " left join activityInstance.assignedUsers assignedUser" + " left join activityInstance.user.userGroup initialUserGroup" + " left join activityInstance.assignedUserGroups assignedUserGroup1" + " left join assignedUser.userGroup assignedUserGroup2" + " where c.form.id = :formId" + " :foundFilter" + " :lastAcitivityFilter" + " :pendingFilter" + " and ('' || :number is null or '' || c.number like :number)" + " and ('' || :activityId is null or activityInstance.activity.id = :activityId)" + " and ('' || :startDate is null or activityInstance.executionTime >= :startDate)" + " and ('' || :endDate is null or activityInstance.executionTime <= :endDate)" + " and ('' || :initialUser is null or lower(activityInstance.user.login) like lower(:initialUser))" + " and ('' || :endUser is null or lower(assignedUser.login) like lower(:endUser))" + " and ('' || :initialUserGroup is null or lower(initialUserGroup.name) like lower(:initialUserGroup))" + " and ('' || :endUserGroup is null or lower(assignedUserGroup1.name) like lower(:endUserGroup) or lower(assignedUserGroup2.name) like lower(:endUserGroup))" + " and ('' || :comments is null or lower(activityInstance.comments) like lower(:comments))" + " and (" + " (" + " value.property.id = :propertyId" + " and (" + " (:stringValue is null or lower(value.stringValue) like lower(:stringValue))" + " and (:booleanValue is null or :booleanValue is false or value.booleanValue = :booleanValue)" + " and (:dateValue is null or date(value.dateValue) = date(:dateValue))" + " and (:longValue is null or value.longValue = :longValue)" + " :classificationsValueFilter" + " :caseDtosValueFilter" + " )" + " ) or " + " (" + " (value.property.id != :propertyId or value is null)" + " and (" + " (:stringValue is null)" + " and (:booleanValue is null)" + " and (:dateValue is null)" + " and (:longValue is null)" + " :falseClassificationsValueFilter" + " :falseCasesValueFilter" + " )" + " )" + " )"; List<Long> classificationsValuesIds = new ArrayList<Long>(); List<Long> caseDtosIds = new ArrayList<Long>(); if(value.getClassificationsValueValue() != null && !value.getClassificationsValueValue().isEmpty()) { for(ClassificationValue classification : value.getClassificationsValueValue()) { if(classification != null && classification.getId() != null) { classificationsValuesIds.add(classification.getId()); } } query = query.replace(":classificationsValueFilter", "and (classificationsValueValue.id in (:classificationsIds))"); query = query.replace(":falseClassificationsValueFilter", "and (1 = 2)"); } else { query = query.replace(":classificationsValueFilter", ""); query = query.replace(":falseClassificationsValueFilter", ""); } if(value.getCaseDtosValue() != null && !value.getCaseDtosValue().isEmpty()) { for(Case c : value.getCaseDtosValue()) { if(c != null && c.getId() != null) { caseDtosIds.add(c.getId()); } } query = query.replace(":caseDtosValueFilter", "and (caseDtosValue.id in (:caseDtosIds))"); query = query.replace(":falseCasesValueFilter", "and (1 = 2)"); } else { query = query.replace(":caseDtosValueFilter", ""); query = query.replace(":falseCasesValueFilter", ""); } if(foundInstancesIds.isEmpty()) { query = query.replace(":foundFilter", ""); } else { query = query.replace(":foundFilter", "and c.id in (:foundInstancesIds)"); } if(lastActivityInstance) { query = query.replace(":lastAcitivityFilter", "and activityInstance.id = (select max(ai.id) from ActivityInstance ai where ai.caseDto.id = c.id)"); } else { query = query.replace(":lastAcitivityFilter", ""); } if(pending) { query = query.replace(":pendingFilter", "and activityInstance.activity.nextActivities is not empty"); } else { query = query.replace(":pendingFilter", ""); } Query q = sessionManager.getSession().createQuery(query); q.setParameter("formId", form.getId()); q.setParameter("propertyId", value.getProperty().getId()); q.setParameter("stringValue", value.getStringValue() == null || value.getStringValue().isEmpty() ? null : "%" + value.getStringValue() + "%"); q.setParameter("booleanValue", value.isBooleanValue() == null || ! value.isBooleanValue() ? null : value.isBooleanValue()); q.setParameter("dateValue", value.getDateValue()); q.setParameter("longValue", value.getLongValue()); q.setParameter("number", number == null || number.isEmpty() ? null : number); q.setParameter("activityId", activity == null ? null : activity.getId()); q.setParameter("startDate", startDate); q.setParameter("endDate", endDate); q.setParameter("initialUser", initialUser == null || initialUser.isEmpty()? null : "%" + initialUser + "%"); q.setParameter("endUser", endUser == null || endUser.isEmpty() ? null : "%" + endUser + "%"); q.setParameter("initialUserGroup", initialUserGroup == null || initialUserGroup.isEmpty() ? null : "%" + initialUserGroup + "%"); q.setParameter("endUserGroup", endUserGroup == null || endUserGroup.isEmpty() ? null : "%" + endUserGroup + "%"); q.setParameter("comments", comments == null || comments.isEmpty() ? null : "%" + comments + "%"); if(value.getClassificationsValueValue() != null && !value.getClassificationsValueValue().isEmpty()) { q.setParameterList("classificationsIds", classificationsValuesIds); } if(value.getCaseDtosValue() != null && !value.getCaseDtosValue().isEmpty()) { q.setParameterList("caseDtosIds", caseDtosIds); } if(foundInstancesIds.isEmpty()) { foundInstancesIds.addAll(q.list()); } else { q.setParameterList("foundInstancesIds", foundInstancesIds); List<Long> newOnes = q.list(); foundInstancesIds.retainAll(newOnes); } if(foundInstancesIds.isEmpty()) { break; } } return foundInstancesIds; } }
package org.eigenbase.util; import java.lang.reflect.*; import java.nio.*; import java.util.*; /** * Static utilities for Java reflection. * * @author John V. Sichi * @version $Id$ */ public abstract class ReflectUtil { private static Map<Class, Class> primitiveToBoxingMap; private static Map<Class, Method> primitiveToByteBufferReadMethod; private static Map<Class, Method> primitiveToByteBufferWriteMethod; static { primitiveToBoxingMap = new HashMap<Class, Class>(); primitiveToBoxingMap.put(Boolean.TYPE, Boolean.class); primitiveToBoxingMap.put(Byte.TYPE, Byte.class); primitiveToBoxingMap.put(Character.TYPE, Character.class); primitiveToBoxingMap.put(Double.TYPE, Double.class); primitiveToBoxingMap.put(Float.TYPE, Float.class); primitiveToBoxingMap.put(Integer.TYPE, Integer.class); primitiveToBoxingMap.put(Long.TYPE, Long.class); primitiveToBoxingMap.put(Short.TYPE, Short.class); primitiveToByteBufferReadMethod = new HashMap<Class, Method>(); primitiveToByteBufferWriteMethod = new HashMap<Class, Method>(); Method [] methods = ByteBuffer.class.getDeclaredMethods(); for (int i = 0; i < methods.length; ++i) { Method method = methods[i]; Class [] paramTypes = method.getParameterTypes(); if (method.getName().startsWith("get")) { if (!method.getReturnType().isPrimitive()) { continue; } if (paramTypes.length != 1) { continue; } primitiveToByteBufferReadMethod.put( method.getReturnType(), method); // special case for Boolean: treat as byte if (method.getReturnType().equals(Byte.TYPE)) { primitiveToByteBufferReadMethod.put(Boolean.TYPE, method); } } else if (method.getName().startsWith("put")) { if (paramTypes.length != 2) { continue; } if (!paramTypes[1].isPrimitive()) { continue; } primitiveToByteBufferWriteMethod.put(paramTypes[1], method); // special case for Boolean: treat as byte if (paramTypes[1].equals(Byte.TYPE)) { primitiveToByteBufferWriteMethod.put(Boolean.TYPE, method); } } } } /** * Uses reflection to find the correct java.nio.ByteBuffer "absolute get" * method for a given primitive type. * * @param clazz the Class object representing the primitive type * * @return corresponding method */ public static Method getByteBufferReadMethod(Class clazz) { assert (clazz.isPrimitive()); return primitiveToByteBufferReadMethod.get(clazz); } /** * Uses reflection to find the correct java.nio.ByteBuffer "absolute put" * method for a given primitive type. * * @param clazz the Class object representing the primitive type * * @return corresponding method */ public static Method getByteBufferWriteMethod(Class clazz) { assert (clazz.isPrimitive()); return primitiveToByteBufferWriteMethod.get(clazz); } /** * Gets the Java boxing class for a primitive class. * * @param primitiveClass representative class for primitive (e.g. * java.lang.Integer.TYPE) * * @return corresponding boxing Class (e.g. java.lang.Integer) */ public static Class getBoxingClass(Class primitiveClass) { assert (primitiveClass.isPrimitive()); return primitiveToBoxingMap.get(primitiveClass); } /** * Gets the name of a class with no package qualifiers; if it's an inner * class, it will still be qualified by the containing class (X$Y). * * @param c the class of interest * * @return the unqualified name */ public static String getUnqualifiedClassName(Class c) { String className = c.getName(); int lastDot = className.lastIndexOf('.'); if (lastDot < 0) { return className; } return className.substring(lastDot + 1); } /** * Composes a string representing a human-readable method name (with neither * exception nor return type information). * * @param declaringClass class on which method is defined * @param methodName simple name of method without signature * @param paramTypes method parameter types * * @return unmangled method name */ public static String getUnmangledMethodName( Class declaringClass, String methodName, Class [] paramTypes) { StringBuilder sb = new StringBuilder(); sb.append(declaringClass.getName()); sb.append("."); sb.append(methodName); sb.append("("); for (int i = 0; i < paramTypes.length; ++i) { if (i > 0) { sb.append(", "); } sb.append(paramTypes[i].getName()); } sb.append(")"); return sb.toString(); } /** * Composes a string representing a human-readable method name (with neither * exception nor return type information). * * @param method method whose name is to be generated * * @return unmangled method name */ public static String getUnmangledMethodName( Method method) { return getUnmangledMethodName( method.getDeclaringClass(), method.getName(), method.getParameterTypes()); } public static boolean invokeVisitor( ReflectiveVisitor visitor, Object visitee, Class hierarchyRoot, String visitMethodName) { return invokeVisitorInternal( visitor, visitee, hierarchyRoot, visitMethodName); } /** * Shared implementation of the two forms of invokeVisitor. * * @param visitor object whose visit method is to be invoked * @param visitee object to be passed as a parameter to the visit method * @param hierarchyRoot if non-null, visitor method will only be invoked if * it takes a parameter whose type is a subtype of hierarchyRoot * @param visitMethodName name of visit method, e.g. "visit" * * @return true if a matching visit method was found and invoked */ private static boolean invokeVisitorInternal( Object visitor, Object visitee, Class hierarchyRoot, String visitMethodName) { Class<?> visitorClass = visitor.getClass(); Class visiteeClass = visitee.getClass(); Method method = lookupVisitMethod( visitorClass, visiteeClass, visitMethodName); if (method == null) { return false; } if (hierarchyRoot != null) { Class paramType = method.getParameterTypes()[0]; if (!hierarchyRoot.isAssignableFrom(paramType)) { return false; } } try { method.invoke( visitor, visitee); } catch (IllegalAccessException ex) { throw Util.newInternal(ex); } catch (InvocationTargetException ex) { // visit methods aren't allowed to have throws clauses, // so the only exceptions which should come // to us are RuntimeExceptions and Errors Throwable t = ex.getTargetException(); if (t instanceof RuntimeException) { throw (RuntimeException) t; } else if (t instanceof Error) { throw (Error) t; } else { throw new AssertionError(t.getClass().getName()); } } return true; } /** * Looks up a visit method. * * @param visitorClass class of object whose visit method is to be invoked * @param visiteeClass class of object to be passed as a parameter to the * visit method * @param visitMethodName name of visit method * * @return method found, or null if none found */ public static Method lookupVisitMethod( Class<?> visitorClass, Class<?> visiteeClass, String visitMethodName) { return lookupVisitMethod( visitorClass, visiteeClass, visitMethodName, Collections.<Class>emptyList()); } /** * Looks up a visit method taking additional parameters beyond the * overloaded visitee type. * * @see #createDispatcher(Class,Class) * * @param visitorClass class of object whose visit method is to be invoked * @param visiteeClass class of object to be passed as a parameter to the * visit method * @param visitMethodName name of visit method * @param additionalParameterTypes list of additional parameter types * * @return method found, or null if none found */ public static Method lookupVisitMethod( Class<?> visitorClass, Class<?> visiteeClass, String visitMethodName, List<Class> additionalParameterTypes) { // Prepare an array to re-use in recursive calls. The first argument // will have the visitee class substituted into it. Class<?>[] paramTypes = new Class[1 + additionalParameterTypes.size()]; int iParam = 0; paramTypes[iParam++] = null; for (Class<?> paramType : additionalParameterTypes) { paramTypes[iParam++] = paramType; } // Cache Class to candidate Methods, to optimize the case where // the original visiteeClass has a diamond-shaped interface inheritance // graph. (This is common, for example, in JMI.) The idea is to avoid // iterating over a single interface's method more than once in a call. Map<Class<?>, Method> cache = new HashMap<Class<?>, Method>(); return lookupVisitMethod( visitorClass, visiteeClass, visitMethodName, paramTypes, cache); } private static Method lookupVisitMethod( final Class<?> visitorClass, final Class<?> visiteeClass, final String visitMethodName, final Class<?>[] paramTypes, final Map<Class<?>, Method> cache) { // Use containsKey since the result for a Class might be null. if (cache.containsKey(visiteeClass)) { return cache.get(visiteeClass); } Method candidateMethod = null; paramTypes[0] = visiteeClass; try { candidateMethod = visitorClass.getMethod( visitMethodName, paramTypes); cache.put(visiteeClass, candidateMethod); return candidateMethod; } catch (NoSuchMethodException ex) { // not found: carry on with lookup } Class<?> superClass = visiteeClass.getSuperclass(); if (superClass != null) { candidateMethod = lookupVisitMethod( visitorClass, superClass, visitMethodName, paramTypes, cache); } Class<?>[] interfaces = visiteeClass.getInterfaces(); for (int i = 0; i < interfaces.length; ++i) { Method method = lookupVisitMethod( visitorClass, interfaces[i], visitMethodName, paramTypes, cache); if (method != null) { if (candidateMethod != null) { if (!method.equals(candidateMethod)) { Class<?> c1 = method.getParameterTypes()[0]; Class<?> c2 = candidateMethod.getParameterTypes()[0]; if (c1.isAssignableFrom(c2)) { // c2 inherits from c1, so keep candidateMethod // (which is more specific than method) continue; } else if (c2.isAssignableFrom(c1)) { // c1 inherits from c2 (method is more specific // than candidate method), so fall through // to set candidateMethod = method } else { // c1 and c2 are not directly related throw new IllegalArgumentException( "dispatch ambiguity between " + candidateMethod + " and " + method); } } } candidateMethod = method; } } cache.put(visiteeClass, candidateMethod); return candidateMethod; } /** * Creates a dispatcher for calls to {@link #lookupVisitMethod}. * The dispatcher caches methods between invocations. * * @param visitorBaseClazz Visitor base class * @param visiteeBaseClazz Visitee base class * * @return cache of methods */ public static <R extends ReflectiveVisitor, E> ReflectiveVisitDispatcher<R, E> createDispatcher( final Class<R> visitorBaseClazz, final Class<E> visiteeBaseClazz) { assert ReflectiveVisitor.class.isAssignableFrom(visitorBaseClazz); assert Object.class.isAssignableFrom(visiteeBaseClazz); return new ReflectiveVisitDispatcher<R, E>() { final Map<List<Object>, Method> map = new HashMap<List<Object>, Method>(); public Method lookupVisitMethod( Class<? extends R> visitorClass, Class<? extends E> visiteeClass, String visitMethodName) { return lookupVisitMethod( visitorClass, visiteeClass, visitMethodName, Collections.<Class>emptyList()); } public Method lookupVisitMethod( Class<? extends R> visitorClass, Class<? extends E> visiteeClass, String visitMethodName, List<Class> additionalParameterTypes) { final List<Object> key = Arrays.asList( visitorClass, visiteeClass, visitMethodName, additionalParameterTypes); Method method = map.get(key); if (method == null) { if (map.containsKey(key)) { // We already looked for the method and found nothing. } else { method = ReflectUtil.lookupVisitMethod( visitorClass, visiteeClass, visitMethodName, additionalParameterTypes); map.put(key, method); } } return method; } public boolean invokeVisitor( R visitor, E visitee, String visitMethodName) { return ReflectUtil.invokeVisitor( visitor, visitee, visiteeBaseClazz, visitMethodName); } }; } /** * Looks up a class by name. This is like Class.forName, except that it * handles primitive type names. * * @param name fully-qualified name of class to look up * * @return class */ public static Class<?> getClassForName(String name) throws Exception { if (name.equals("boolean")) { return boolean.class; } else if (name.equals("byte")) { return byte.class; } else if (name.equals("char")) { return char.class; } else if (name.equals("double")) { return double.class; } else if (name.equals("float")) { return float.class; } else if (name.equals("int")) { return int.class; } else if (name.equals("long")) { return long.class; } else if (name.equals("short")) { return short.class; } else if (name.equals("void")) { return void.class; } else { return Class.forName(name); } } } // End ReflectUtil.java
package org.odlabs.wiquery.ui.slider; import org.odlabs.wiquery.core.options.IComplexOption; import org.odlabs.wiquery.core.options.LiteralOption; /** * $Id: SliderRange.java * <p> * Bean for the range option into the Slider component * </p> * * @author Julien Roche * @since 1.0 */ public class SliderRange implements IComplexOption { public enum RangeEnum { MIN(new LiteralOption("min")), MAX(new LiteralOption("max")); // Properties private LiteralOption literalParam; RangeEnum(LiteralOption literalParam) { this.literalParam = literalParam; } @Override public String toString() { return literalParam.toString(); } } // Constants /** Constant of serialization */ private static final long serialVersionUID = 3404088696595137949L; // Properties private Boolean booleanParam; private RangeEnum rangeEnumParam; /** * Constructor * * @param booleanParam * Boolean parameter */ public SliderRange(Boolean booleanParam) { this(booleanParam, null); } /** * Constructor * * @param rangeEnumParam * RangeEnum parameter */ public SliderRange(RangeEnum rangeEnumParam) { this(null, rangeEnumParam); } /** * Constructor * * @param booleanParam * Boolean parameter * @param rangeEnumParam * RangeEnum parameter */ private SliderRange(Boolean booleanParam, RangeEnum rangeEnumParam) { super(); setParam(booleanParam, rangeEnumParam); } /** * @return the booleanParam */ public boolean isBooleanParam() { return booleanParam; } /** * @return the rangeEnumParam */ public RangeEnum getRangeEnumParam() { return rangeEnumParam; } public CharSequence getJavascriptOption() { if (booleanParam == null && rangeEnumParam == null) { throw new IllegalArgumentException("The SliderRange must have one not null parameter"); } CharSequence sequence = null; if (booleanParam != null) { sequence = booleanParam.toString(); } else if (rangeEnumParam != null) { sequence = rangeEnumParam.toString(); } else { throw new IllegalArgumentException("The SliderRange must have one not null parameter"); } return sequence; } /** * Set's the boolean parameter * * @param booleanParam * the booleanParam to set */ public void setBooleanParam(boolean booleanParam) { setParam(booleanParam, null); } /** * Set's the literal parameter * * @param rangeEnumParam * the literal to set */ public void setRangeEnumParam(RangeEnum rangeEnumParam) { setParam(null, rangeEnumParam); } /** * Method setting the right parameter * * @param booleanParam * Boolean parameter * @param rangeEnumParam * RangeEnum parameter */ private void setParam(Boolean booleanParam, RangeEnum rangeEnumParam) { this.booleanParam = booleanParam; this.rangeEnumParam = rangeEnumParam; } }
package org.knowm.xchange.kucoin.dto; import java.math.BigDecimal; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order.OrderStatus; import org.knowm.xchange.dto.Order.OrderType; import org.knowm.xchange.dto.account.AccountInfo; import org.knowm.xchange.dto.account.Balance; import org.knowm.xchange.dto.account.FundingRecord; import org.knowm.xchange.dto.account.Wallet; import org.knowm.xchange.dto.marketdata.OrderBook; import org.knowm.xchange.dto.marketdata.Ticker; import org.knowm.xchange.dto.marketdata.Trade; import org.knowm.xchange.dto.marketdata.Trades.TradeSortType; import org.knowm.xchange.dto.meta.CurrencyMetaData; import org.knowm.xchange.dto.meta.CurrencyPairMetaData; import org.knowm.xchange.dto.meta.ExchangeMetaData; import org.knowm.xchange.dto.trade.LimitOrder; import org.knowm.xchange.dto.trade.OpenOrders; import org.knowm.xchange.dto.trade.UserTrade; import org.knowm.xchange.dto.trade.UserTrades; import org.knowm.xchange.kucoin.dto.account.KucoinCoinBalance; import org.knowm.xchange.kucoin.dto.account.KucoinWalletRecord; import org.knowm.xchange.kucoin.dto.marketdata.KucoinCoin; import org.knowm.xchange.kucoin.dto.marketdata.KucoinDealOrder; import org.knowm.xchange.kucoin.dto.marketdata.KucoinOrderBook; import org.knowm.xchange.kucoin.dto.marketdata.KucoinTicker; import org.knowm.xchange.kucoin.dto.trading.KucoinActiveOrder; import org.knowm.xchange.kucoin.dto.trading.KucoinActiveOrders; import org.knowm.xchange.kucoin.dto.trading.KucoinDealtOrder; public class KucoinAdapters { public static String adaptCurrencyPair(CurrencyPair pair) { return pair.base.getCurrencyCode() + "-" + pair.counter.getCurrencyCode(); } public static Ticker adaptTicker(KucoinResponse<KucoinTicker> tickResponse, CurrencyPair pair) { KucoinTicker kcTick = tickResponse.getData(); return new Ticker.Builder() .currencyPair(pair) .bid(kcTick.getBuy()) .ask(kcTick.getSell()) .high(kcTick.getHigh()) .low(kcTick.getLow()) .last(kcTick.getLastDealPrice()) .volume(kcTick.getVol()) .quoteVolume(kcTick.getVolValue()) .timestamp(new Date(kcTick.getDatetime())) .build(); } public static OrderBook adaptOrderBook(KucoinResponse<KucoinOrderBook> response, CurrencyPair currencyPair) { KucoinOrderBook kcOrders = response.getData(); Date timestamp = new Date(response.getTimestamp()); List<LimitOrder> asks = new LinkedList<>(); kcOrders.getSell().stream() .forEach(s -> asks.add(adaptLimitOrder(currencyPair, OrderType.ASK, s, timestamp))); List<LimitOrder> bids = new LinkedList<>(); kcOrders.getBuy().stream() .forEach(s -> bids.add(adaptLimitOrder(currencyPair, OrderType.BID, s, timestamp))); return new OrderBook(timestamp, asks, bids); } public static Trade adaptTrade(KucoinDealOrder kucoinTrade, CurrencyPair currencyPair) { return new Trade(kucoinTrade.getOrderType().getOrderType(), kucoinTrade.getAmount(), currencyPair, kucoinTrade.getPrice(), new Date(kucoinTrade.getTimestamp()), null); } private static LimitOrder adaptLimitOrder(CurrencyPair currencyPair, OrderType orderType, List<BigDecimal> kucoinLimitOrder, Date timestamp) { return new LimitOrder(orderType, kucoinLimitOrder.get(1), currencyPair, null, timestamp, kucoinLimitOrder.get(0)); } public static OpenOrders adaptActiveOrders(CurrencyPair currencyPair, KucoinActiveOrders data) { List<LimitOrder> openOrders = new LinkedList<>(); data.getBuy().stream().forEach(order -> openOrders.add(adaptActiveOrder(currencyPair, order))); data.getSell().stream().forEach(order -> openOrders.add(adaptActiveOrder(currencyPair, order))); return new OpenOrders(openOrders); } private static LimitOrder adaptActiveOrder(CurrencyPair currencyPair, KucoinActiveOrder order) { return new LimitOrder.Builder(order.getOrderType().getOrderType(), currencyPair) .timestamp(order.getTimestamp()) .id(order.getOrderOid()) .limitPrice(order.getPrice()) .originalAmount(order.getAmount()) // this might be the remaining amount, not sure .cumulativeAmount(order.getDealAmount()) .orderStatus(order.getDealAmount().compareTo(BigDecimal.ZERO) == 0 ? OrderStatus.NEW : OrderStatus.PARTIALLY_FILLED) .build(); } public static UserTrades adaptUserTrades(List<KucoinDealtOrder> orders) { List<UserTrade> trades = new LinkedList<>(); orders.stream().forEach(order -> trades.add(adaptUserTrade(order))); return new UserTrades(trades, TradeSortType.SortByTimestamp); } private static UserTrade adaptUserTrade(KucoinDealtOrder order) { return new UserTrade.Builder() .currencyPair(new CurrencyPair(order.getCoinType(), order.getCoinTypePair())) .orderId(order.getOid()) .originalAmount(order.getAmount()) .price(order.getDealPrice()) .timestamp(new Date(order.getCreatedAt())) .type(order.getDirection().getOrderType()) .feeAmount(order.getFee()) .feeCurrency(order.getDirection().equals(KucoinOrderType.BUY) ? new Currency(order.getCoinType()) : new Currency(order.getCoinTypePair())) .build(); } public static ExchangeMetaData adaptExchangeMetadata(List<KucoinTicker> tickers, List<KucoinCoin> coins) { Map<String, KucoinCoin> coinMap = coins.stream().collect(Collectors.toMap(c -> c.getCoin(), c -> c)); Map<CurrencyPair, CurrencyPairMetaData> pairMeta = adaptCurrencyPairMap(tickers, coinMap); Map<Currency, CurrencyMetaData> coinMeta = adaptCurrencyMap(coins); return new ExchangeMetaData(pairMeta, coinMeta, null, null, null); } private static Map<Currency, CurrencyMetaData> adaptCurrencyMap(List<KucoinCoin> coins) { return coins.stream().collect(Collectors.toMap( c -> new Currency(c.getCoin()), c -> adaptCurrencyMetadata(c))); } private static CurrencyMetaData adaptCurrencyMetadata(KucoinCoin coin) { // Unfortunately the scale for the wallet is not available in the API, take 8 by default return new CurrencyMetaData(8, coin.getWithdrawMinFee()); } private static Map<CurrencyPair, CurrencyPairMetaData> adaptCurrencyPairMap( List<KucoinTicker> symbols, Map<String, KucoinCoin> coins) { return symbols.stream().collect(Collectors.toMap( t -> new CurrencyPair(t.getCoinType(), t.getCoinTypePair()), t -> adaptCurrencyPairMetadata(t, coins.get(t.getCoinTypePair())))); } private static CurrencyPairMetaData adaptCurrencyPairMetadata(KucoinTicker tick, KucoinCoin coin) { // trading scale is determined by the base currency's trade precision return new CurrencyPairMetaData(tick.getFeeRate(), null, null, coin.getTradePrecision()); } public static AccountInfo adaptAccountInfo( List<KucoinCoinBalance> balances) { return new AccountInfo(new Wallet(balances.stream() .map(KucoinAdapters::adaptBalance) .collect(Collectors.toList()))); } private static Balance adaptBalance(KucoinCoinBalance balance) { return new Balance(new Currency(balance.getCoinType()), balance.getBalance()); } public static List<FundingRecord> adaptFundingHistory(List<KucoinWalletRecord> records) { return records.stream().map(KucoinAdapters::adaptFundingRecord).collect(Collectors.toList()); } private static FundingRecord adaptFundingRecord(KucoinWalletRecord record) { return new FundingRecord.Builder() .setAmount(record.getAmount()) .setAddress(record.getAddress()) .setCurrency(new Currency(record.getCoinType())) .setDate(new Date(record.getCreatedAt())) .setFee(record.getFee()) .setStatus(record.getStatus().getFundingRecordStatus()) .setExternalId(record.getOuterWalletTxid()) .setInternalId(record.getOid()) .setDescription(record.getRemark()) .setType(record.getType().getFundingRecordType()) .build(); } }
package com.thoughtworks.xstream.core.util; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * ClassLoader that is composed of other classloaders. Each loader will be used to try to load the particular class, until * one of them succeeds. <b>Note:</b> The loaders will always be called in the REVERSE order they were added in. * * <p>The Composite class loader also has registered the classloader that loaded xstream.jar * and (if available) the thread's context classloader.</p> * * <h1>Example</h1> * <pre><code>CompositeClassLoader loader = new CompositeClassLoader(); * loader.add(MyClass.class.getClassLoader()); * loader.add(new AnotherClassLoader()); * &nbsp; * loader.loadClass("com.blah.ChickenPlucker"); * </code></pre> * * <p>The above code will attempt to load a class from the following classloaders (in order):</p> * * <ul> * <li>AnotherClassLoader (and all its parents)</li> * <li>The classloader for MyClas (and all its parents)</li> * <li>The thread's context classloader (and all its parents)</li> * <li>The classloader for XStream (and all its parents)</li> * </ul> * * <p>The added classloaders are kept with weak references to allow an application container to reload classes.</p> * * @author Joe Walnes * @author J&ouml;rg Schaible * @since 1.0.3 */ public class CompositeClassLoader extends ClassLoader { private final ReferenceQueue queue = new ReferenceQueue(); private final List classLoaders = new ArrayList(); public CompositeClassLoader() { addInternal(Object.class.getClassLoader()); // bootstrap loader. addInternal(getClass().getClassLoader()); // whichever classloader loaded this jar. } /** * Add a loader to the n * @param classLoader */ public synchronized void add(ClassLoader classLoader) { cleanup(); if (classLoader != null) { addInternal(classLoader); } } private void addInternal(ClassLoader classLoader) { WeakReference refClassLoader = null; for (Iterator iterator = classLoaders.iterator(); iterator.hasNext();) { WeakReference ref = (WeakReference) iterator.next(); ClassLoader cl = (ClassLoader)ref.get(); if (cl == null) { iterator.remove(); } else if (cl == classLoader) { iterator.remove(); refClassLoader = ref; } } classLoaders.add(0, refClassLoader != null ? refClassLoader : new WeakReference(classLoader, queue)); } public Class loadClass(String name) throws ClassNotFoundException { List copy = new ArrayList(classLoaders.size()) { public boolean addAll(Collection c) { boolean result = false; for(Iterator iter = c.iterator(); iter.hasNext(); ) { result |= super.add(iter.next()); } return result; } public boolean add(Object ref) { Object classLoader = ((WeakReference)ref).get(); if (classLoader != null) { return super.add(classLoader); } return false; } }; synchronized(this) { cleanup(); copy.addAll(classLoaders); } ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); for (Iterator iterator = copy.iterator(); iterator.hasNext();) { ClassLoader classLoader = (ClassLoader) iterator.next(); if (classLoader == contextClassLoader) { contextClassLoader = null; } try { return classLoader.loadClass(name); } catch (ClassNotFoundException notFound) { // ok.. try another one } } // One last try - the context class loader associated with the current thread. Often used in j2ee servers. // Note: The contextClassLoader cannot be added to the classLoaders list up front as the thread that constructs // XStream is potentially different to thread that uses it. if (contextClassLoader != null) { return contextClassLoader.loadClass(name); } else { throw new ClassNotFoundException(name); } } private void cleanup() { WeakReference ref; while ((ref = (WeakReference)queue.poll()) != null) { classLoaders.remove(ref); } } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // * Neither the name of the <organization> nor the // names of its contributors may be used to endorse or promote products // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package wybs.util; import java.io.IOException; import java.util.*; import wybs.lang.*; /** * <p> * Provides a straightforward implementation of NameSpace and a basic build * system supporting an arbitrary number of build rules. The namespace is * defined by one or more "path roots" which are locations on the file system * where named items may be found. Such locations may be, for example, * directories. However, they may also be jar files, or even potentially network * locations. * </p> * * @author David J. Pearce */ public class StandardProject implements NameSpace { /** * The roots of all entries known to the system which form the global * namespace used by the builder(s). */ protected final ArrayList<Path.Root> roots; /** * The rules associated with this project for transforming content. It is * assumed that for any given transformation there is only one possible * pathway described. */ protected final ArrayList<BuildRule> rules; public StandardProject(Collection<Path.Root> roots) { this.roots = new ArrayList<Path.Root>(roots); this.rules = new ArrayList<BuildRule>(); } public StandardProject(Collection<Path.Root>... roots) { this.rules = new ArrayList<BuildRule>(); this.roots = new ArrayList<Path.Root>(); for(Collection<Path.Root> root : roots) { this.roots.addAll(root); } } // Configuration Interface /** * Add a new builder to this project. * * @param data.builder */ public void add(BuildRule rule) { rules.add(rule); } /** * Get the roots associated with this project. * * @return */ public List<Path.Root> roots() { return roots; } // Accessors public boolean exists(Path.ID id, Content.Type<?> ct) throws Exception { for(int i=0;i!=roots.size();++i) { if(roots.get(i).exists(id, ct)) { return true; } } return false; } public <T> Path.Entry<T> get(Path.ID id, Content.Type<T> ct) throws Exception { for(int i=0;i!=roots.size();++i) { Path.Entry<T> e = roots.get(i).get(id, ct); if(e != null) { return e; } } return null; } public <T> ArrayList<Path.Entry<T>> get(Content.Filter<T> filter) throws Exception { ArrayList<Path.Entry<T>> r = new ArrayList<Path.Entry<T>>(); for(int i=0;i!=roots.size();++i) { r.addAll(roots.get(i).get(filter)); } return r; } public <T> HashSet<Path.ID> match(Content.Filter<T> filter) throws Exception { HashSet<Path.ID> r = new HashSet<Path.ID>(); for(int i=0;i!=roots.size();++i) { r.addAll(roots.get(i).match(filter)); } return r; } // Mutators public void flush() throws Exception { for(int i=0;i!=roots.size();++i) { roots.get(i).flush(); } } public void refresh() throws Exception { for(int i=0;i!=roots.size();++i) { roots.get(i).refresh(); } } /** * Build a given set of source entries, including all files which dependent * upon them. * * @param sources * @throws Exception */ public void build(Collection<? extends Path.Entry<?>> sources) throws Exception { HashSet<Path.Entry<?>> allTargets = new HashSet(); // Firstly, initialise list of targets to rebuild. for (BuildRule r : rules) { for (Path.Entry<?> source : sources) { allTargets.addAll(r.dependentsOf(source)); } } // Secondly, add all dependents on those being rebuilt. int oldSize; do { oldSize = allTargets.size(); addVerticalDeps(allTargets); addHorizontalDeps(allTargets); } while (allTargets.size() != oldSize); // Finally, build all identified targets! do { oldSize = allTargets.size(); for(BuildRule r : rules) { r.apply(allTargets); } } while(allTargets.size() < oldSize); // If we didn't manage to build all the targets, then this indicates // that some kind of cyclic dependency situation is present. if(!allTargets.isEmpty()) { // FIXME: to something proper here. System.out.println("Cyclic dependency!"); } } /** * Vertical dependencies are those between files of differing content type. * For example, a file such as Test.wyil depends vertically on the file * Test.whiley if there is a build rule where Test.whiley => Test.class * * @param allTargets * @throws IOException */ private void addVerticalDeps(HashSet<Path.Entry<?>> allTargets) throws IOException { HashSet<Path.Entry<?>> delta = new HashSet(); for (BuildRule r : rules) { for (Path.Entry<?> target : allTargets) { delta.addAll(r.dependentsOf(target)); } } allTargets.addAll(delta); } /** * Horizontal dependencies are those between files of the same content type. * These are trickier to identify as we need to maintain dependence * information between them. For example, Test1.wyil will depende * horizontally on Test2.wyil if Test1.wyil uses something defined in * Test2.wyil. * * @param allTargets * @throws IOException */ private void addHorizontalDeps(HashSet<Path.Entry<?>> allTargets) throws IOException { } }
package org.zanata.service.impl; import java.util.List; import java.util.Map; import java.util.Set; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.zanata.common.EntityStatus; import org.zanata.common.LocaleId; import org.zanata.dao.ProjectIterationDAO; import org.zanata.dao.VersionGroupDAO; import org.zanata.model.HIterationGroup; import org.zanata.model.HLocale; import org.zanata.model.HPerson; import org.zanata.model.HProjectIteration; import org.zanata.service.LocaleService; import org.zanata.service.VersionGroupService; import org.zanata.service.VersionLocaleKey; import org.zanata.service.VersionStateCache; import org.zanata.ui.model.statistic.WordStatistic; import org.zanata.util.StatisticsUtil; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; /** * @author Alex Eng <a href="mailto:aeng@redhat.com">aeng@redhat.com</a> */ @Name("versionGroupServiceImpl") @Scope(ScopeType.STATELESS) public class VersionGroupServiceImpl implements VersionGroupService { @In private VersionGroupDAO versionGroupDAO; @In private ProjectIterationDAO projectIterationDAO; @In private VersionStateCache versionStateCacheImpl; @In private LocaleService localeServiceImpl; @Override public Map<VersionLocaleKey, WordStatistic> getLocaleStatistic( String groupSlug, LocaleId localeId) { Map<VersionLocaleKey, WordStatistic> statisticMap = Maps.newHashMap(); HIterationGroup group = versionGroupDAO.getBySlug(groupSlug); for (HProjectIteration version : group.getProjectIterations()) { if (version.getStatus() == EntityStatus.ACTIVE) { WordStatistic statistic = versionStateCacheImpl.getVersionStatistics( version.getId(), localeId); statistic.setRemainingHours(StatisticsUtil .getRemainingHours(statistic)); statisticMap.put( new VersionLocaleKey(version.getId(), localeId), statistic); } } return statisticMap; } @Override public int getTotalMessageCount(String groupSlug) { int result = 0; HIterationGroup group = versionGroupDAO.getBySlug(groupSlug); for (HProjectIteration version : group.getProjectIterations()) { result += projectIterationDAO.getTotalMessageCountForIteration( version.getId()).intValue(); } result = result * group.getActiveLocales().size(); return result; } @Override public List<HIterationGroup> getAllActiveAndMaintainedGroups(HPerson person) { List<HIterationGroup> activeVersions = getAllActiveGroups(); if (person == null) { return activeVersions; } List<HIterationGroup> obsoleteVersions = versionGroupDAO.getAllObsoleteVersionGroups(); List<HIterationGroup> filteredList = Lists.newArrayList(); for (HIterationGroup obsoleteGroup : obsoleteVersions) { if (person.isMaintainer(obsoleteGroup)) { filteredList.add(obsoleteGroup); } } activeVersions.addAll(filteredList); return activeVersions; } @Override public List<HIterationGroup> getAllActiveGroups() { return versionGroupDAO.getAllActiveVersionGroups(); } @Override public List<HProjectIteration> searchLikeSlugOrProjectSlug(String searchTerm) { return projectIterationDAO.searchLikeSlugOrProjectSlug(searchTerm); } @Override public List<HPerson> getMaintainersBySlug(String groupSlug) { return versionGroupDAO.getMaintainersBySlug(groupSlug); } @Override public boolean isVersionInGroup(String groupSlug, Long projectIterationId) { HIterationGroup group = versionGroupDAO.getBySlug(groupSlug); if (group != null && projectIterationId != null) { for (HProjectIteration iteration : group.getProjectIterations()) { if (iteration.getId().equals(projectIterationId)) { return true; } } } return false; } @Override public Set<HLocale> getGroupActiveLocales(String groupSlug) { HIterationGroup group = versionGroupDAO.getBySlug(groupSlug); if (group != null) { return group.getActiveLocales(); } return Sets.newHashSet(); } @Override public List<HProjectIteration> getProjectIterationsBySlug(String groupSlug) { HIterationGroup group = versionGroupDAO.getBySlug(groupSlug); return projectIterationDAO.getByGroup(group); } /** * Return versions that don't contained all active locales of the group. * * @param groupSlug */ @Override public Map<LocaleId, List<HProjectIteration>> getMissingLocaleVersionMap( String groupSlug) { Map<LocaleId, List<HProjectIteration>> result = Maps.newHashMap(); HIterationGroup group = versionGroupDAO.getBySlug(groupSlug); if (group != null) { for (HLocale activeLocale : group.getActiveLocales()) { List<HProjectIteration> versionList = Lists.newArrayList(); List<HProjectIteration> notObsoleteProjectIterations = projectIterationDAO.getByGroup(group); for (HProjectIteration version : notObsoleteProjectIterations) { if (!isLocaleActivatedInVersion(version, activeLocale)) { versionList.add(version); } } result.put(activeLocale.getLocaleId(), versionList); } } return result; } /** * Return if the locale enabled by default in server and is activate in the * version. Return true if version and project doesn't overrides locale. * * Fallback to project customised locale if version doesn't overrides * locales * * @param version * @param locale */ private boolean isLocaleActivatedInVersion(HProjectIteration version, HLocale locale) { List<HLocale> versionLocales = localeServiceImpl.getSupportedLangugeByProjectIteration(version .getProject().getSlug(), version.getSlug()); return versionLocales.contains(locale); } }
package wyc.builder; import static wyc.lang.WhileyFile.*; import static wyil.util.ErrorMessages.INVALID_BINARY_EXPRESSION; import static wyil.util.ErrorMessages.INVALID_BOOLEAN_EXPRESSION; import static wyil.util.ErrorMessages.INVALID_SET_OR_LIST_EXPRESSION; import static wyil.util.ErrorMessages.UNKNOWN_VARIABLE; import static wyil.util.ErrorMessages.VARIABLE_POSSIBLY_UNITIALISED; import static wyil.util.ErrorMessages.errorMessage; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import wybs.lang.SyntacticElement; import wybs.lang.SyntaxError; import wybs.util.ResolveError; import wyc.lang.Expr; import wyc.lang.UnresolvedType; import wyc.lang.WhileyFile.Context; import wyil.lang.Attribute; import wyil.lang.Block; import wyil.lang.Code; import wyil.lang.Type; import wyil.lang.Constant; import wyil.util.Pair; import wyil.util.Triple; /** * <p> * Responsible for compiling source-level expressions into wyil bytecodes in a * given context. This includes generating wyil code for constraints as * necessary using a global generator. For example: * </p> * * <pre> * define natlist as [nat] * * natlist check([int] ls): * if ls is natlist: * return ls * else: * return [] * </pre> * <p> * Here, a local generator will be called to compile the expression * <code>ls is natlist</code> into wyil bytecode (amongst other expressions). To * this, it must in turn obtain the bytecodes for the type <code>natlist</code>. * Since <code>natlist</code> is defined at the global level, the global * generator will be called to do this (which, in turn, may call a local * generator again). * </p> * <p> * <b>NOTE:</b> it is currently assumed that all expressions being generated are * already typed. This restriction may be lifted in the future. * </p> * * @author David J. Pearce * */ public final class LocalGenerator { private final GlobalGenerator global; private final Context context; public LocalGenerator(GlobalGenerator global, Context context) { this.context = context; this.global = global; } public Context context() { return context; } public Block generateAssertion(String message, Expr condition, boolean isAssumption, int freeRegister, HashMap<String, Integer> environment) { try { if (condition instanceof Expr.Constant || condition instanceof Expr.ConstantAccess || condition instanceof Expr.LocalVariable || condition instanceof Expr.UnOp || condition instanceof Expr.AbstractInvoke || condition instanceof Expr.RecordAccess || condition instanceof Expr.IndexOf || condition instanceof Expr.Comprehension) { // fall through to default case } else if (condition instanceof Expr.BinOp) { return generateAssertion(message, (Expr.BinOp) condition, isAssumption, freeRegister, environment); } else { syntaxError(errorMessage(INVALID_BOOLEAN_EXPRESSION), context, condition); } // The default case simply compares the computed value against // true. In some cases, we could do better. For example, !(x < 5) // could be rewritten into x>=5. Block blk = generate(condition,freeRegister,freeRegister+1,environment); blk.append(Code.Const(freeRegister+1,Constant.V_BOOL(true)),attributes(condition)); if(isAssumption) { blk.append(Code.Assume(Type.T_BOOL, freeRegister, freeRegister + 1, Code.Comparator.EQ, message), attributes(condition)); } else { blk.append(Code.Assert(Type.T_BOOL, freeRegister, freeRegister + 1, Code.Comparator.EQ, message), attributes(condition)); } return blk; } catch (SyntaxError se) { throw se; } catch (Exception ex) { internalFailure(ex.getMessage(), context, condition, ex); } return null; } protected Block generateAssertion(String message, Expr.BinOp v, boolean isAssumption, int freeRegister, HashMap<String, Integer> environment) { Block blk = new Block(environment.size()); Expr.BOp bop = v.op; if (bop == Expr.BOp.OR) { String lab = Block.freshLabel(); blk.append(generateCondition(lab, v.lhs, freeRegister, environment)); blk.append(generateAssertion(message, v.rhs, isAssumption, freeRegister, environment)); blk.append(Code.Label(lab)); return blk; } else if (bop == Expr.BOp.AND) { blk.append(generateAssertion(message, v.lhs, isAssumption, freeRegister, environment)); blk.append(generateAssertion(message, v.rhs, isAssumption, freeRegister, environment)); return blk; } // TODO: there are some cases which will break here. In particular, // those involving type tests. If/When WYIL changes to be register based // this should fall out in the wash. Code.Comparator cop = OP2COP(bop,v); blk.append(generate(v.lhs, freeRegister, freeRegister + 1, environment)); blk.append(generate(v.rhs, freeRegister + 1, freeRegister + 2, environment)); if (isAssumption) { blk.append(Code.Assume(v.srcType.raw(), freeRegister, freeRegister + 1, cop, message), attributes(v)); } else { blk.append(Code.Assert(v.srcType.raw(), freeRegister, freeRegister + 1, cop, message), attributes(v)); } return blk; } public void generateCondition(String target, Expr condition, Environment environment, Block codes) { try { if (condition instanceof Expr.Constant) { return generateCondition(target, (Expr.Constant) condition, freeRegister, environment); } else if (condition instanceof Expr.ConstantAccess || condition instanceof Expr.LocalVariable || condition instanceof Expr.AbstractInvoke || condition instanceof Expr.RecordAccess || condition instanceof Expr.IndexOf) { // fall through to default case } else if (condition instanceof Expr.UnOp) { return generateCondition(target, (Expr.UnOp) condition, freeRegister, environment); } else if (condition instanceof Expr.BinOp) { return generateCondition(target, (Expr.BinOp) condition, freeRegister, environment); } else if (condition instanceof Expr.Comprehension) { return generateCondition(target, (Expr.Comprehension) condition, freeRegister, environment); } else { syntaxError(errorMessage(INVALID_BOOLEAN_EXPRESSION), context, condition); } // The default case simply compares the computed value against // true. In some cases, we could do better. For example, !(x < 5) // could be rewritten into x>=5. Block blk = generate(condition, freeRegister, freeRegister + 1, environment); blk.append(Code.Const(freeRegister + 1, Constant.V_BOOL(true)), attributes(condition)); blk.append(Code.If(Type.T_BOOL, freeRegister, freeRegister + 1, Code.Comparator.EQ, target), attributes(condition)); return blk; } catch (SyntaxError se) { throw se; } catch (Exception ex) { internalFailure(ex.getMessage(), context, condition, ex); } return null; } private Block generateCondition(String target, Expr.Constant c, Environment environment, Block codes) { Constant.Bool b = (Constant.Bool) c.value; Block blk = new Block(environment.size()); if (b.value) { blk.append(Code.Goto(target)); } else { // do nout } return blk; } private Block generateCondition(String target, Expr.BinOp v, Environment environment, Block codes) throws Exception { Expr.BOp bop = v.op; Block blk = new Block(environment.size()); if (bop == Expr.BOp.OR) { blk.append(generateCondition(target, v.lhs, freeRegister, environment)); blk.append(generateCondition(target, v.rhs, freeRegister, environment)); return blk; } else if (bop == Expr.BOp.AND) { String exitLabel = Block.freshLabel(); blk.append(generateCondition(exitLabel, invert(v.lhs), freeRegister, environment)); blk.append(generateCondition(target, v.rhs, freeRegister, environment)); blk.append(Code.Label(exitLabel)); return blk; } else if (bop == Expr.BOp.IS) { return generateTypeCondition(target, v, freeRegister, environment); } Code.Comparator cop = OP2COP(bop,v); if (cop == Code.Comparator.EQ && v.lhs instanceof Expr.LocalVariable && v.rhs instanceof Expr.Constant && ((Expr.Constant) v.rhs).value == Constant.V_NULL) { // this is a simple rewrite to enable type inference. Expr.LocalVariable lhs = (Expr.LocalVariable) v.lhs; if (!environment.containsKey(lhs.var)) { syntaxError(errorMessage(UNKNOWN_VARIABLE), context, v.lhs); } int slot = environment.get(lhs.var); blk.append(Code.IfIs(v.srcType.raw(), slot, Type.T_NULL, target), attributes(v)); } else if (cop == Code.Comparator.NEQ && v.lhs instanceof Expr.LocalVariable && v.rhs instanceof Expr.Constant && ((Expr.Constant) v.rhs).value == Constant.V_NULL) { // this is a simple rewrite to enable type inference. String exitLabel = Block.freshLabel(); Expr.LocalVariable lhs = (Expr.LocalVariable) v.lhs; if (!environment.containsKey(lhs.var)) { syntaxError(errorMessage(UNKNOWN_VARIABLE), context, v.lhs); } int slot = environment.get(lhs.var); blk.append(Code.IfIs(v.srcType.raw(), slot, Type.T_NULL, exitLabel), attributes(v)); blk.append(Code.Goto(target)); blk.append(Code.Label(exitLabel)); } else { blk.append(generate(v.lhs, freeRegister, freeRegister + 1, environment)); blk.append(generate(v.rhs, freeRegister + 1, freeRegister + 2, environment)); blk.append(Code.If(v.srcType.raw(), freeRegister, freeRegister + 1, cop, target), attributes(v)); } return blk; } private Block generateTypeCondition(String target, Expr.BinOp v, Environment environment, Block codes) throws Exception { Block blk; int leftOperand; if (v.lhs instanceof Expr.LocalVariable) { Expr.LocalVariable lhs = (Expr.LocalVariable) v.lhs; if (!environment.containsKey(lhs.var)) { syntaxError(errorMessage(UNKNOWN_VARIABLE), context, v.lhs); } leftOperand = environment.get(lhs.var); blk = new Block(environment.size()); } else { blk = generate(v.lhs, freeRegister, freeRegister + 1, environment); leftOperand = freeRegister++; } Expr.TypeVal rhs = (Expr.TypeVal) v.rhs; Block constraint = global.generate(rhs.unresolvedType, context); if (constraint != null) { String exitLabel = Block.freshLabel(); Type glb = Type.intersect(v.srcType.raw(), Type.Negation(rhs.type.raw())); if (glb != Type.T_VOID) { // Only put the actual type test in if it is necessary. String nextLabel = Block.freshLabel(); // FIXME: should be able to just test the glb here and branch to // exit label directly. However, this currently doesn't work // because of limitations with intersection of open records. blk.append( Code.IfIs(v.srcType.raw(), leftOperand, rhs.type.raw(), nextLabel), attributes(v)); blk.append(Code.Goto(exitLabel)); blk.append(Code.Label(nextLabel)); } constraint = shiftBlockExceptionZero(environment.size() - 1, leftOperand, constraint); blk.append(chainBlock(exitLabel, constraint)); blk.append(Code.Goto(target)); blk.append(Code.Label(exitLabel)); } else { blk.append(Code.IfIs(v.srcType.raw(), leftOperand, rhs.type.raw(), target), attributes(v)); } return blk; } private Block generateCondition(String target, Expr.UnOp v, Environment environment, Block codes) { Expr.UOp uop = v.op; switch (uop) { case NOT : String label = Block.freshLabel(); Block blk = generateCondition(label, v.mhs, freeRegister, environment); blk.append(Code.Goto(target)); blk.append(Code.Label(label)); return blk; } syntaxError(errorMessage(INVALID_BOOLEAN_EXPRESSION), context, v); return null; } private Block generateCondition(String target, Expr.Comprehension e, Environment _environment, Block codes) { if (e.cop != Expr.COp.NONE && e.cop != Expr.COp.SOME) { syntaxError(errorMessage(INVALID_BOOLEAN_EXPRESSION), context, e); } HashMap<String,Integer> environment = new HashMap<String,Integer>(_environment); // Ok, non-boolean case. Block blk = new Block(environment.size()); ArrayList<Triple<Integer,Integer,Type.EffectiveCollection>> slots = new ArrayList(); for (Pair<String, Expr> src : e.sources) { int srcSlot; int varSlot = freeRegister++; environment.put(src.first(), varSlot); Nominal srcType = src.second().result(); if(src.second() instanceof Expr.LocalVariable) { // this is a little optimisation to produce slightly better // code. Expr.LocalVariable v = (Expr.LocalVariable) src.second(); if(environment.containsKey(v.var)) { srcSlot = environment.get(v.var); } else { // fall-back plan ... srcSlot = freeRegister++; blk.append(generate(src.second(), srcSlot, freeRegister, environment)); } } else { srcSlot = freeRegister++; blk.append(generate(src.second(), srcSlot, freeRegister, environment)); } slots.add(new Triple(varSlot,srcSlot,srcType.raw())); } ArrayList<String> labels = new ArrayList<String>(); String loopLabel = Block.freshLabel(); for (Triple<Integer, Integer, Type.EffectiveCollection> p : slots) { Type.EffectiveCollection srcType = p.third(); String lab = loopLabel + "$" + p.first(); blk.append(Code.ForAll(srcType, p.second(), p.first(), Collections.EMPTY_LIST, lab), attributes(e)); labels.add(lab); } if (e.cop == Expr.COp.NONE) { String exitLabel = Block.freshLabel(); blk.append(generateCondition(exitLabel, e.condition, freeRegister, environment)); for (int i = (labels.size() - 1); i >= 0; --i) { blk.append(Code.LoopEnd(labels.get(i))); } blk.append(Code.Goto(target)); blk.append(Code.Label(exitLabel)); } else { // SOME blk.append(generateCondition(target, e.condition, freeRegister, environment)); for (int i = (labels.size() - 1); i >= 0; --i) { blk.append(Code.LoopEnd(labels.get(i))); } } // ALL, LONE and ONE will be harder return blk; } public int generate(Expr expression, Environment environment, Block codes) { try { if (expression instanceof Expr.Constant) { return generate((Expr.Constant) expression, environment, codes); } else if (expression instanceof Expr.LocalVariable) { return generate((Expr.LocalVariable) expression, environment, codes); } else if (expression instanceof Expr.ConstantAccess) { return generate((Expr.ConstantAccess) expression, environment, codes); } else if (expression instanceof Expr.Set) { return generate((Expr.Set) expression, environment, codes); } else if (expression instanceof Expr.List) { return generate((Expr.List) expression, environment, codes); } else if (expression instanceof Expr.SubList) { return generate((Expr.SubList) expression, environment, codes); } else if (expression instanceof Expr.SubString) { return generate((Expr.SubString) expression, environment, codes); } else if (expression instanceof Expr.BinOp) { return generate((Expr.BinOp) expression, environment, codes); } else if (expression instanceof Expr.LengthOf) { return generate((Expr.LengthOf) expression, environment, codes); } else if (expression instanceof Expr.Dereference) { return generate((Expr.Dereference) expression, environment, codes); } else if (expression instanceof Expr.Convert) { return generate((Expr.Convert) expression, environment, codes); } else if (expression instanceof Expr.IndexOf) { return generate((Expr.IndexOf) expression, environment, codes); } else if (expression instanceof Expr.UnOp) { return generate((Expr.UnOp) expression, environment, codes); } else if (expression instanceof Expr.FunctionCall) { return generate((Expr.FunctionCall) expression, environment, codes); } else if (expression instanceof Expr.MethodCall) { return generate((Expr.MethodCall) expression, environment, codes); } else if (expression instanceof Expr.IndirectFunctionCall) { return generate((Expr.IndirectFunctionCall) expression, environment, codes); } else if (expression instanceof Expr.IndirectMethodCall) { return generate((Expr.IndirectMethodCall) expression, environment, codes); } else if (expression instanceof Expr.Comprehension) { return generate((Expr.Comprehension) expression, environment, codes); } else if (expression instanceof Expr.RecordAccess) { return generate((Expr.RecordAccess) expression, environment, codes); } else if (expression instanceof Expr.Record) { return generate((Expr.Record) expression, environment, codes); } else if (expression instanceof Expr.Tuple) { return generate((Expr.Tuple) expression, environment, codes); } else if (expression instanceof Expr.Map) { return generate((Expr.Map) expression, environment, codes); } else if (expression instanceof Expr.FunctionOrMethod) { return generate((Expr.FunctionOrMethod) expression, environment, codes); } else if (expression instanceof Expr.New) { return generate((Expr.New) expression, environment, codes); } else { // should be dead-code internalFailure("unknown expression: " + expression.getClass().getName(), context, expression); } } catch (ResolveError rex) { syntaxError(rex.getMessage(), context, expression, rex); } catch (SyntaxError se) { throw se; } catch (Exception ex) { internalFailure(ex.getMessage(), context, expression, ex); } return -1; // deadcode } public int generate(Expr.MethodCall expr, Environment environment, Block codes) throws ResolveError { int[] operands = generate(expr.arguments, environment, codes); int target = environment.allocate(expr.result().raw()); codes.append( Code.Invoke(expr.methodType.raw(), target, operands, expr.nid()), attributes(expr)); return target; } public int generate(Expr.FunctionCall expr, Environment environment, Block codes) throws ResolveError { int[] operands = generate(expr.arguments, environment, codes); int target = environment.allocate(expr.result().raw()); codes.append( Code.Invoke(expr.functionType.raw(), target, operands, expr.nid()), attributes(expr)); return target; } public int generate(Expr.IndirectFunctionCall expr, Environment environment, Block codes) throws ResolveError { int operand = generate(expr.src, environment, codes); int[] operands = generate(expr.arguments, environment, codes); int target = environment.allocate(expr.result().raw()); codes.append(Code.IndirectInvoke(expr.functionType.raw(), target, operand, operands), attributes(expr)); return target; } public int generate(Expr.IndirectMethodCall expr, Environment environment, Block codes) throws ResolveError { int operand = generate(expr.src, environment, codes); int[] operands = generate(expr.arguments, environment, codes); int target = environment.allocate(expr.result().raw()); codes.append(Code.IndirectInvoke(expr.methodType.raw(), target, operand, operands), attributes(expr)); return target; } private int generate(Expr.Constant expr, Environment environment, Block codes) { Constant val = expr.value; int target = environment.allocate(val.type()); codes.append(Code.Const(target, expr.value), attributes(expr)); return target; } private int generate(Expr.FunctionOrMethod expr, Environment environment, Block codes) { Constant val = Constant.V_FUN(expr.nid, expr.type.raw()); int target = environment.allocate(val.type()); codes.append(Code.Const(target, val), attributes(expr)); return target; } private int generate(Expr.ConstantAccess expr, Environment environment, Block codes) throws ResolveError { Constant val = expr.value; int target = environment.allocate(val.type()); codes.append(Code.Const(target,val),attributes(expr)); return target; } private int generate(Expr.LocalVariable expr, Environment environment, Block codes) throws ResolveError { if (environment.get(expr.var) != null) { return environment.get(expr.var); } else { syntaxError(errorMessage(VARIABLE_POSSIBLY_UNITIALISED), context, expr); } // must be an error syntaxError("unknown variable \"" + expr.var + "\"", context,expr); return -1; } private int generate(Expr.UnOp expr, Environment environment, Block codes) { int operand = generate(expr.mhs, environment, codes); int target = environment.allocate(expr.result().raw()); switch (expr.op) { case NEG: codes.append(Code.UnArithOp(expr.result().raw(), target, operand, Code.UnArithKind.NEG), attributes(expr)); break; case INVERT: codes.append(Code.Invert(expr.result().raw(), target, operand), attributes(expr)); break; case NOT: String falseLabel = Block.freshLabel(); String exitLabel = Block.freshLabel(); generateCondition(falseLabel, expr.mhs, environment, codes); codes.append(Code.Const(target,Constant.V_BOOL(true)), attributes(expr)); codes.append(Code.Goto(exitLabel)); codes.append(Code.Label(falseLabel)); codes.append(Code.Const(target,Constant.V_BOOL(false)), attributes(expr)); codes.append(Code.Label(exitLabel)); break; default: // should be dead-code internalFailure("unexpected unary operator encountered", context, expr); return -1; } return target; } private int generate(Expr.LengthOf expr, Environment environment, Block codes) { int operand = generate(expr.src, environment, codes); int target = environment.allocate(expr.result().raw()); codes.append(Code.LengthOf(expr.srcType.raw(), target, operand), attributes(expr)); return target; } private int generate(Expr.Dereference expr, Environment environment, Block codes) { int operand = generate(expr.src, environment, codes); int target = environment.allocate(expr.result().raw()); codes.append(Code.Dereference(expr.srcType.raw(), target, operand), attributes(expr)); return target; } private int generate(Expr.IndexOf expr, Environment environment, Block codes) { int srcOperand = generate(expr.src, environment, codes); int idxOperand = generate(expr.index, environment, codes); int target = environment.allocate(expr.result().raw()); codes.append( Code.IndexOf(expr.srcType.raw(), target, srcOperand, idxOperand), attributes(expr)); return target; } private int generate(Expr.Convert expr, Environment environment, Block codes) { int operand = generate(expr.expr, environment, codes); Type from = expr.expr.result().raw(); Type to = expr.result().raw(); int target = environment.allocate(to); // TODO: include constraints codes.append(Code.Convert(from, target, operand, to), attributes(expr)); return target; } private int generate(Expr.BinOp v, Environment environment, Block codes) throws Exception { // could probably use a range test for this somehow if (v.op == Expr.BOp.EQ || v.op == Expr.BOp.NEQ || v.op == Expr.BOp.LT || v.op == Expr.BOp.LTEQ || v.op == Expr.BOp.GT || v.op == Expr.BOp.GTEQ || v.op == Expr.BOp.SUBSET || v.op == Expr.BOp.SUBSETEQ || v.op == Expr.BOp.ELEMENTOF || v.op == Expr.BOp.AND || v.op == Expr.BOp.OR) { String trueLabel = Block.freshLabel(); String exitLabel = Block.freshLabel(); Block blk = generateCondition(trueLabel, v, freeRegister, environment); blk.append(Code.Const(target,Constant.V_BOOL(false)), attributes(v)); blk.append(Code.Goto(exitLabel)); blk.append(Code.Label(trueLabel)); blk.append(Code.Const(target,Constant.V_BOOL(true)), attributes(v)); blk.append(Code.Label(exitLabel)); return blk; } Expr.BOp bop = v.op; Block blk = new Block(environment.size()); blk.append(generate(v.lhs, freeRegister, freeRegister+1, environment)); blk.append(generate(v.rhs, freeRegister+1, freeRegister+2, environment)); Type result = v.result().raw(); switch(bop) { case UNION: blk.append(Code.BinSetOp((Type.EffectiveSet) result, target, freeRegister, freeRegister+1, Code.BinSetKind.UNION), attributes(v)); return blk; case INTERSECTION: blk.append(Code.BinSetOp((Type.EffectiveSet) result, target, freeRegister, freeRegister+1, Code.BinSetKind.INTERSECTION), attributes(v)); return blk; case DIFFERENCE: blk.append(Code.BinSetOp((Type.EffectiveSet) result, target, freeRegister, freeRegister+1, Code.BinSetKind.DIFFERENCE), attributes(v)); return blk; case LISTAPPEND: blk.append(Code.BinListOp((Type.EffectiveList) result, target, freeRegister, freeRegister+1, Code.BinListKind.APPEND), attributes(v)); return blk; case STRINGAPPEND: Type lhs = v.lhs.result().raw(); Type rhs = v.rhs.result().raw(); Code.BinStringKind op; if(lhs == Type.T_STRING && rhs == Type.T_STRING) { op = Code.BinStringKind.APPEND; } else if(lhs == Type.T_STRING && Type.isSubtype(Type.T_CHAR, rhs)) { op = Code.BinStringKind.LEFT_APPEND; } else if(rhs == Type.T_STRING && Type.isSubtype(Type.T_CHAR, lhs)) { op = Code.BinStringKind.RIGHT_APPEND; } else { // this indicates that one operand must be explicitly converted // into a string. op = Code.BinStringKind.APPEND; } blk.append(Code.BinStringOp(target,freeRegister, freeRegister+1,op),attributes(v)); return blk; default: blk.append(Code.BinArithOp(result, target, freeRegister, freeRegister+1, OP2BOP(bop, v)), attributes(v)); return blk; } } private int generate(Expr.Set expr, Environment environment, Block codes) { int[] operands = generate(expr.arguments, environment, codes); int target = environment.allocate(expr.result().raw()); codes.append(Code.NewSet(expr.type.raw(), target, operands), attributes(expr)); return target; } private int generate(Expr.List expr, Environment environment, Block codes) { int[] operands = generate(expr.arguments, environment, codes); int target = environment.allocate(expr.result().raw()); codes.append(Code.NewList(expr.type.raw(), target, operands), attributes(expr)); return target; } private int generate(Expr.SubList expr, Environment environment, Block codes) { int srcOperand = generate(expr.src, environment, codes); int startOperand = generate(expr.start, environment, codes); int endOperand = generate(expr.end, environment, codes); int target = environment.allocate(expr.result().raw()); codes.append(Code.SubList(expr.type.raw(), target, srcOperand, startOperand, endOperand), attributes(expr)); return target; } private int generate(Expr.SubString v, Environment environment, Block codes) { int srcOperand = generate(v.src, environment, codes); int startOperand = generate(v.start, environment, codes); int endOperand = generate(v.end, environment, codes); int target = environment.allocate(v.result().raw()); codes.append( Code.SubString(target, srcOperand, startOperand, endOperand), attributes(v)); return target; } private int generate(Expr.Comprehension e, Environment environment, Block codes) { // First, check for boolean cases which are handled mostly by // generateCondition. if (e.cop == Expr.COp.SOME || e.cop == Expr.COp.NONE) { String trueLabel = Block.freshLabel(); String exitLabel = Block.freshLabel(); Block blk = generateCondition(trueLabel, e, freeRegister, _environment); blk.append(Code.Const(target, Constant.V_BOOL(false)), attributes(e)); blk.append(Code.Goto(exitLabel)); blk.append(Code.Label(trueLabel)); blk.append(Code.Const(target, Constant.V_BOOL(true)), attributes(e)); blk.append(Code.Label(exitLabel)); return blk; } // Ok, non-boolean case. HashMap<String,Integer> environment = new HashMap<String,Integer>(_environment); Block blk = new Block(environment.size()); ArrayList<Triple<Integer,Integer,Type.EffectiveCollection>> slots = new ArrayList(); for (Pair<String, Expr> p : e.sources) { int srcSlot; int varSlot = freeRegister++; environment.put(p.first(), varSlot); Expr src = p.second(); Type rawSrcType = src.result().raw(); if(src instanceof Expr.LocalVariable) { // this is a little optimisation to produce slightly better // code. Expr.LocalVariable v = (Expr.LocalVariable) src; if(environment.containsKey(v.var)) { srcSlot = environment.get(v.var); } else { // fall-back plan ... srcSlot = freeRegister++; blk.append(generate(src, srcSlot, freeRegister, environment)); } } else { srcSlot = freeRegister++; blk.append(generate(src, srcSlot, freeRegister, environment)); } slots.add(new Triple(varSlot,srcSlot,rawSrcType)); } Type resultType; if (e.cop == Expr.COp.LISTCOMP) { resultType = e.type.raw(); blk.append(Code.NewList((Type.List) resultType, target, Collections.EMPTY_LIST), attributes(e)); } else { resultType = e.type.raw(); blk.append(Code.NewSet((Type.Set) resultType, target, Collections.EMPTY_LIST), attributes(e)); } // At this point, it would be good to determine an appropriate loop // invariant for a set comprehension. This is easy enough in the case of // a single variable comprehension, but actually rather difficult for a // multi-variable comprehension. // For example, consider <code>{x+y | x in xs, y in ys, x<0 && y<0}</code> // What is an appropriate loop invariant here? String continueLabel = Block.freshLabel(); ArrayList<String> labels = new ArrayList<String>(); String loopLabel = Block.freshLabel(); for (Triple<Integer, Integer, Type.EffectiveCollection> p : slots) { String label = loopLabel + "$" + p.first(); blk.append(Code.ForAll(p.third(), p.second(), p.first(), Collections.EMPTY_LIST, label), attributes(e)); labels.add(label); } if (e.condition != null) { blk.append(generateCondition(continueLabel, invert(e.condition), freeRegister, environment)); } blk.append(generate(e.value, freeRegister, freeRegister + 1, environment)); // FIXME: following broken for list comprehensions blk.append(Code.BinSetOp((Type.Set) resultType, target, target, freeRegister, Code.BinSetKind.LEFT_UNION), attributes(e)); if(e.condition != null) { blk.append(Code.Label(continueLabel)); } for (int i = (labels.size() - 1); i >= 0; --i) { blk.append(Code.LoopEnd(labels.get(i))); } return blk; } private int generate(Expr.Record expr, Environment environment, Block codes) { ArrayList<String> keys = new ArrayList<String>(expr.fields.keySet()); Collections.sort(keys); int[] operands = new int[expr.fields.size()]; for (int i = 0; i != operands.length; ++i) { String key = keys.get(i); Expr arg = expr.fields.get(key); operands[i] = generate(arg, environment, codes); } int target = environment.allocate(expr.result().raw()); codes.append(Code.NewRecord(expr.result().raw(), target, operands), attributes(expr)); return target; } private int generate(Expr.Tuple expr, Environment environment, Block codes) { int[] operands = generate(expr.fields, environment, codes); int target = environment.allocate(expr.result().raw()); codes.append(Code.NewTuple(expr.result().raw(), target, operands), attributes(expr)); return target; } private int generate(Expr.Map expr, Environment environment, Block codes) { int[] operands = new int[expr.pairs.size() * 2]; for (int i = 0; i != expr.pairs.size(); ++i) { Pair<Expr, Expr> e = expr.pairs.get(i); operands[i << 1] = generate(e.first(), environment, codes); operands[(i << 1) + 1] = generate(e.second(), environment, codes); } int target = environment.allocate(expr.result().raw()); codes.append(Code.NewMap(expr.result().raw(), target, operands), attributes(expr)); return target; } private int generate(Expr.RecordAccess expr, Environment environment, Block codes) { int operand = generate(expr.src, environment, codes); int target = environment.allocate(expr.result().raw()); codes.append(Code.FieldLoad(expr.srcType.raw(), target, operand, expr.name), attributes(expr)); return target; } private int generate(Expr.New expr, Environment environment, Block codes) throws ResolveError { int operand = generate(expr.expr, environment, codes); int target = environment.allocate(expr.result().raw()); codes.append(Code.NewObject(expr.type.raw(), target, operand)); return target; } private int[] generate(List<Expr> arguments, Environment environment, Block codes) { int[] operands = new int[arguments.size()]; for (int i = 0; i != operands.length; ++i) { Expr arg = arguments.get(i); operands[i] = generate(arg, environment, codes); } return operands; } private Code.BinArithKind OP2BOP(Expr.BOp bop, SyntacticElement elem) { switch (bop) { case ADD: return Code.BinArithKind.ADD; case SUB: return Code.BinArithKind.SUB; case MUL: return Code.BinArithKind.MUL; case DIV: return Code.BinArithKind.DIV; case REM: return Code.BinArithKind.REM; case RANGE: return Code.BinArithKind.RANGE; case BITWISEAND: return Code.BinArithKind.BITWISEAND; case BITWISEOR: return Code.BinArithKind.BITWISEOR; case BITWISEXOR: return Code.BinArithKind.BITWISEXOR; case LEFTSHIFT: return Code.BinArithKind.LEFTSHIFT; case RIGHTSHIFT: return Code.BinArithKind.RIGHTSHIFT; } syntaxError(errorMessage(INVALID_BINARY_EXPRESSION), context, elem); return null; } private Code.Comparator OP2COP(Expr.BOp bop, SyntacticElement elem) { switch (bop) { case EQ: return Code.Comparator.EQ; case NEQ: return Code.Comparator.NEQ; case LT: return Code.Comparator.LT; case LTEQ: return Code.Comparator.LTEQ; case GT: return Code.Comparator.GT; case GTEQ: return Code.Comparator.GTEQ; case SUBSET: return Code.Comparator.SUBSET; case SUBSETEQ: return Code.Comparator.SUBSETEQ; case ELEMENTOF: return Code.Comparator.ELEMOF; } syntaxError(errorMessage(INVALID_BOOLEAN_EXPRESSION), context, elem); return null; } private static int allocate(HashMap<String,Integer> environment) { return allocate("$" + environment.size(),environment); } private static int allocate(String var, HashMap<String,Integer> environment) { // this method is a bit of a hack Integer r = environment.get(var); if(r == null) { int slot = environment.size(); environment.put(var, slot); return slot; } else { return r; } } private static Expr invert(Expr e) { if (e instanceof Expr.BinOp) { Expr.BinOp bop = (Expr.BinOp) e; Expr.BinOp nbop = null; switch (bop.op) { case AND: nbop = new Expr.BinOp(Expr.BOp.OR, invert(bop.lhs), invert(bop.rhs), attributes(e)); break; case OR: nbop = new Expr.BinOp(Expr.BOp.AND, invert(bop.lhs), invert(bop.rhs), attributes(e)); break; case EQ: nbop = new Expr.BinOp(Expr.BOp.NEQ, bop.lhs, bop.rhs, attributes(e)); break; case NEQ: nbop = new Expr.BinOp(Expr.BOp.EQ, bop.lhs, bop.rhs, attributes(e)); break; case LT: nbop = new Expr.BinOp(Expr.BOp.GTEQ, bop.lhs, bop.rhs, attributes(e)); break; case LTEQ: nbop = new Expr.BinOp(Expr.BOp.GT, bop.lhs, bop.rhs, attributes(e)); break; case GT: nbop = new Expr.BinOp(Expr.BOp.LTEQ, bop.lhs, bop.rhs, attributes(e)); break; case GTEQ: nbop = new Expr.BinOp(Expr.BOp.LT, bop.lhs, bop.rhs, attributes(e)); break; } if(nbop != null) { nbop.srcType = bop.srcType; return nbop; } } else if (e instanceof Expr.UnOp) { Expr.UnOp uop = (Expr.UnOp) e; switch (uop.op) { case NOT: return uop.mhs; } } Expr.UnOp r = new Expr.UnOp(Expr.UOp.NOT, e); r.type = Nominal.T_BOOL; return r; } /** * The shiftBlock method takes a block and shifts every slot a given amount * to the right. The number of inputs remains the same. This method is used * * @param amount * @param blk * @return */ private static Block shiftBlockExceptionZero(int amount, int zeroDest, Block blk) { HashMap<Integer,Integer> binding = new HashMap<Integer,Integer>(); for(int i=1;i!=blk.numSlots();++i) { binding.put(i,i+amount); } binding.put(0, zeroDest); Block nblock = new Block(blk.numInputs()); for(Block.Entry e : blk) { Code code = e.code.remap(binding); nblock.append(code,e.attributes()); } return nblock.relabel(); } /** * The chainBlock method takes a block and replaces every fail statement * with a goto to a given label. This is useful for handling constraints in * union types, since if the constraint is not met that doesn't mean its * game over. * * @param target * @param blk * @return */ private static Block chainBlock(String target, Block blk) { Block nblock = new Block(blk.numInputs()); for (Block.Entry e : blk) { if (e.code instanceof Code.Assert) { Code.Assert a = (Code.Assert) e.code; Code.Comparator iop = Code.invert(a.op); if(iop != null) { nblock.append(Code.If(a.type,a.leftOperand,a.rightOperand,iop,target), e.attributes()); } else { // FIXME: avoid the branch here. This can be done by // ensuring that every Code.COp is invertible. String lab = Block.freshLabel(); nblock.append(Code.If(a.type,a.leftOperand,a.rightOperand,a.op,lab), e.attributes()); nblock.append(Code.Goto(target)); nblock.append(Code.Label(lab)); } } else { nblock.append(e.code, e.attributes()); } } return nblock.relabel(); } /** * The attributes method extracts those attributes of relevance to wyil, and * discards those which are only used for the wyc front end. * * @param elem * @return */ private static Collection<Attribute> attributes(SyntacticElement elem) { ArrayList<Attribute> attrs = new ArrayList<Attribute>(); attrs.add(elem.attribute(Attribute.Source.class)); return attrs; } private final class Environment { private final HashMap<String, Integer> var2idx = new HashMap<String, Integer>(); private final ArrayList<Type> idx2type = new ArrayList<Type>(); public int allocate(Type t) { int idx = idx2type.size(); idx2type.add(t); return idx; } public int allocate(Type t, String v) { int r = allocate(t); var2idx.put(v, r); return r; } public Integer get(String v) { return var2idx.get(v); } public void put(int idx, String v) { var2idx.put(v, idx); } public ArrayList<Type> asList() { return idx2type; } public String toString() { return idx2type.toString() + "," + var2idx.toString(); } } }
package com.ociweb.iot.project.lightblink; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import com.ociweb.iot.hardware.impl.test.TestHardware; import com.ociweb.iot.maker.DeviceRuntime; import com.ociweb.pronghorn.stage.scheduling.NonThreadScheduler; /** * Unit test for simple App. */ public class AppTest { @Test public void testApp() { DeviceRuntime runtime = DeviceRuntime.test(new IoTApp()); NonThreadScheduler scheduler = (NonThreadScheduler)runtime.getScheduler(); scheduler.startup(); TestHardware hardware = (TestHardware)runtime.getHardware(); int iterations = 4; boolean isFirst = true; int expected = 0; long lastTime = 0; while (iterations>0) { scheduler.run(); long time = hardware.getLastTime(IoTApp.LED_PORT); if (0!=time) { iterations assertEquals(expected, hardware.read(IoTApp.LED_PORT)); expected = 1&(expected+1); if (0!=lastTime) { long durationMs = (time-lastTime); if (!isFirst) { assertTrue(Long.toString(durationMs),durationMs>=400);//first difference may be short because first transition is later due to startup. } else { isFirst = false; } assertTrue(durationMs<=750); } lastTime = time; hardware.clearCaputuredLastTimes(); hardware.clearCaputuredHighs(); } } } }
package org.glob3.mobile.generated; public abstract class ElevationDataProvider { protected ChangedListener _changedListener; protected boolean _enabled; public ElevationDataProvider() { _changedListener = null; _enabled = true; } public void dispose() { } public abstract boolean isReadyToRender(G3MRenderContext rc); public abstract void initialize(G3MContext context); public abstract long requestElevationData(Sector sector, Vector2I extent, IElevationDataListener listener, boolean autodeleteListener); public abstract void cancelRequest(long requestId); public abstract java.util.ArrayList<Sector> getSectors(); public abstract Vector2I getMinResolution(); public final void setChangedListener(ChangedListener changedListener) { _changedListener = changedListener; } public final void onChanged() { if (_changedListener != null) { _changedListener.changed(); } } public final void setEnabled(boolean enabled) { if (_enabled != enabled) { _enabled = enabled; onChanged(); } } public final boolean isEnabled() { return _enabled; } }
package ca.ualberta.cs.f14t07_application.test; import java.util.ArrayList; import ca.ualberta.cs.f14t07_application.PostList; import ca.ualberta.cs.f14t07_application.Question; import android.test.ActivityInstrumentationTestCase2; public class SortTest extends ActivityInstrumentationTestCase2<QuestionList> { /* TODO: The Class generic that goes with ActivityInstrumentationTestCase2 is * an activity class - the activity which will be active when the test cases * are called. */ public SortTest(){ super(PostList.class); } public void sortByTimeTest(){ PostList questions=new PostList(); questions.add(new Question("test 1")); questions.add(new Question("test 2")); questions.add(new Question("test 3")); //set time using index, day month year hour minute questions.setTime(0,30,01,1982,17,04); questions.setTime(1,30,01, 1987,17,04); questions.setTime(1,30,01,1987,17,05); questions.sortByTime(); ArrayList<Question> testList= new ArrayList<Question>(); testList.add(new Question("test 3")); testList.add(new Question("test 2")); testList.add(new Question("test 1")); assertEquals(questions.getlist(),testList); } public void sortByRatingTest(){ PostList questions=new PostList; questions.add(new Question("test 1")); questions.add(new Question("test 2")); questions.add(new Question("test 3")); questions.changeRating(0,5); questions.changeRating(1,-1); questions.changeRating(2,10); questions.sortByRating(); ArrayList<Question> testList= new ArrayList<Question>(); testList.add(new Question("test 3")); testList.add(new Question("test 1")); testList.add(new Question("test 2")); assertEquals(questions.getlist(),testList); } public void sortByHasPictureTest(){ PostList questions=new PostList; questions.add(new Question("test 1")); questions.add(new Question("test 2")); questions.add(new Question("test 3")); questions.addPicture(1); questions.sortByHasPicture(); ArrayList<Question> testList= new ArrayList<Question>(); testList.add(new Question("test 2")); testList.add(new Question("test 1")); testList.add(new Question("test 3")); assertEquals(questions.getlist(),testList); } }
package ca.firstvoices.listeners; import ca.firstvoices.utils.FVExportWordProperties; import ca.firstvoices.workers.FVAbstractExportWork; import ca.firstvoices.workers.FVCyclicExportWorker; import ca.firstvoices.workers.FVExportWorker; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.ecm.automation.core.util.StringList; import org.nuxeo.ecm.core.event.Event; import org.nuxeo.ecm.core.event.EventContext; import org.nuxeo.ecm.core.event.EventListener; import org.nuxeo.ecm.core.work.api.WorkManager; import org.nuxeo.runtime.api.Framework; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static ca.firstvoices.utils.FVExportConstants.*; import static ca.firstvoices.utils.FVExportUtils.makeExportFileName; public class FVExportListener implements EventListener { private static final Log log = LogFactory.getLog(FVExportListener.class); protected WorkManager workManager = Framework.getService(WorkManager.class); @Override public void handleEvent(Event event) { EventContext ctx = event.getContext(); switch( event.getName() ) { case PRODUCE_FORMATTED_DOCUMENT: String id = makeExportFileName( (String)ctx.getProperty(INITIATING_PRINCIPAL), (String)ctx.getProperty(DIALECT_NAME_EXPORT), (String)ctx.getProperty(EXPORT_FORMAT) ); if( checkForRunningWorkerBeforeProceeding( id ) ) { // TODO: ??? delete old file if exists and create a new one workManager.schedule(produceWorker(ctx, new FVExportWorker( id )), true); } break; case FINISH_EXPORT_BY_WRAPPING_BLOB: break; case AUTO_PRODUCE_FORMATTED_DOCUMENT: if( checkForRunningWorkerBeforeProceeding( CYCLIC_WORKER_ID ) ) { workManager.schedule( produceWorker(ctx, new FVCyclicExportWorker() ), true); } break; } } private boolean checkForRunningWorkerBeforeProceeding( String workId ) { if( workManager.find( workId, null ) != null ) return false; // worker is running return true; // worker is not running } private FVAbstractExportWork produceWorker( EventContext ctx, FVAbstractExportWork work ) { if( ctx.hasProperty( QUERY_TO_PREPARE_WORK_FOR_EXPORT) ) { work.setExportQuery(ctx.getProperty( QUERY_TO_PREPARE_WORK_FOR_EXPORT ).toString()); work.setInitiatorName(ctx.getProperty( INITIATING_PRINCIPAL ).toString()); work.setDialectName(ctx.getProperty( DIALECT_NAME_EXPORT ).toString()); work.setDialectGUID(ctx.getProperty( DIALECT_GUID).toString()); work.setExportFormat(ctx.getProperty( EXPORT_FORMAT ).toString()); StringList pc = (StringList)ctx.getProperty(COLUMNS_TO_EXPORT); if( pc.size() == 1 ) { work.setExportColumns( new ArrayList<>() ); } else { work.setExportColumns( (ArrayList<String>)ctx.getProperty(COLUMNS_TO_EXPORT)); } work.setDocuments("FV", (ArrayList<String>) ctx.getProperty( WORDS_TO_EXPORT ) ); } else { work.setExportQuery( INHERITED_FROM_OTHER ); work.setInitiatorName( "System" ); work.setDialectName( INHERITED_FROM_OTHER ); work.setDialectGUID( INHERITED_FROM_OTHER ); work.setExportFormat( INHERITED_FROM_OTHER ); } return work; } }
package com.qualcomm.ftcrobotcontroller; import com.qualcomm.ftccommon.DbgLog; import com.qualcomm.ftcrobotcontroller.control.Control; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.Servo; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.IOException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; public abstract class RMOpMode extends OpMode { protected Map<String, Motor> motorMap = new HashMap<String, Motor>(); protected Map<String, rServo> servoMap = new HashMap<String, rServo>(); //protected Map<Motor, Motor> motorSlaveMap = new HashMap<Motor, Motor>(); protected Control control; public int opType; @Override public void init() { telemetry.addData("init", "init start"); try { this.configureHardware(this.setConfigurationPath()); } catch (IOException e) { e.printStackTrace(); DbgLog.error(e.getMessage()); } catch (ParseException e) { e.printStackTrace(); DbgLog.error(e.getMessage()); } this.control = new Control(gamepad1, gamepad2); for (Motor m : motorMap.values()) { m.resetEncoder(); } for (rServo r : servoMap.values()) { //testing only r.setInitPos(); } telemetry.addData("init", "init start2"); } @Override public void loop() { this.updateInput(); this.calculate(); this.updateHardware(); } protected void updateInput() { control.update(gamepad1, gamepad2); } protected abstract void calculate(); protected void updateHardware() { telemetry.addData("updateHardware", "Starting updating hardware"); //motorMap.get("DriveLeftTwo").setDesiredPower(motorMap.get("DriveLeftOne").getDesiredPower()); //motorMap.get("DriveRightTwo").setDesiredPower(motorMap.get("DriveRightOne").getDesiredPower()); /*for (Motor sl : motorSlaveMap.keySet()) { sl.setDesiredPower(motorSlaveMap.get(sl).getDesiredPower()); }*/ for (Motor m : motorMap.values()) { if (opType == 0) { m.runToPosition(); } else { m.runWithoutEncoders(); } /*for (Motor sl : motorSlaveMap.keySet()) { if (sl==m) { sl.setDesiredPower(motorSlaveMap.get(sl).getDesiredPower()); } }*/ m.updateCurrentPower(); m.setCurrentPower(); } for (rServo s : servoMap.values()) { s.updateCurrentPosition(); s.setPosition(); } telemetry.addData("updateHardware", "Finishing updating hardware"); } protected abstract String setConfigurationPath(); protected void configureHardware(String pathName) throws IOException, ParseException { telemetry.addData("configureHardware", "Starting configuring hardware"); String configSource = readFile(pathName, Charset.defaultCharset()); JSONParser jsonParser = new JSONParser(); JSONObject jsonFile = (JSONObject) jsonParser.parse(configSource); JSONArray jsonMotors = (JSONArray) jsonFile.get("motors"); JSONArray jsonServos = (JSONArray) jsonFile.get("servos"); //JSONArray jsonSlave = (JSONArray) jsonFile.get("slave"); this.configureMotors(jsonMotors); this.configureServos(jsonServos); //this.configureSlave(jsonSlave); //Todo add methods for configuring and sensors telemetry.addData("configureHardware", "Finishing updating hardware"); } private static String readFile(String path, Charset encoding) throws IOException { /*byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded, encoding); */ return path; } private void configureMotors(JSONArray JSONMotors) { telemetry.addData("configureMotors", "Starting updating motors"); for (Object mObj : JSONMotors) { JSONObject mJSON = (JSONObject) mObj; String motorName = (String) mJSON.get("name"); double minPower = (Double) mJSON.get("minPower"); double maxPower = (Double) mJSON.get("maxPower"); DcMotor dcParent = hardwareMap.dcMotor.get(motorName); DcMotor.Direction d = stringToMotorDirection((String) mJSON.get("direction")); Motor m = new Motor(dcParent, d, minPower, maxPower); motorMap.put(motorName, m); } telemetry.addData("configureMotors", "Finishing updating motors"); } private void configureServos(JSONArray JSONServos) { telemetry.addData("configureServos", "Starting updating servos"); for (Object sObj : JSONServos) { JSONObject sJSON = (JSONObject) sObj; String servoName = (String) sJSON.get("name"); double minPosition = (Double) sJSON.get("minPosition"); double maxPosition = (Double) sJSON.get("maxPosition"); Servo sParent = hardwareMap.servo.get(servoName); Servo.Direction d = stringToServoDirection((String) sJSON.get("direction")); double init = (Double) sJSON.get("init"); rServo s = new rServo(sParent, d, minPosition, maxPosition, init); servoMap.put(servoName, s); } telemetry.addData("configureServos", "Finishing updating servos"); } /*private void configureSlave(JSONArray JSONSlave) { for (Object slObj : JSONSlave) { JSONObject slJSON = (JSONObject) slObj; String motorName = (String) slJSON.get("name"); String slaveToName = (String) slJSON.get("slaveTo"); Motor m1 = stringToMotorMapObject(motorName); Motor m2 = stringToMotorMapObject(slaveToName); motorSlaveMap.put(m1, m2); } }*/ private DcMotor.Direction stringToMotorDirection(String stringD) { //ToDo check if valueOf works as expected telemetry.addData("stringToMotorDirection", "Setting motor direction"); if (stringD.equals("FORWARD")) { telemetry.addData("stringToMotorDirection", "Finish setting motor direction forward"); return DcMotor.Direction.FORWARD; } else if (stringD.equals("REVERSE")) { telemetry.addData("stringToMotorDirection", "Finish setting motor direction reverse"); return DcMotor.Direction.REVERSE; } else { telemetry.addData("stringToMotorDirection", "Finish setting motor direction to value"); return DcMotor.Direction.valueOf(stringD); } } private Servo.Direction stringToServoDirection(String stringD) { telemetry.addData("stringToServoDirection", "Setting servo direction"); if (stringD.equals("FORWARD")) { telemetry.addData("stringToServoDirection", "Finish setting servo direction forward"); return Servo.Direction.FORWARD; } else if (stringD.equals("REVERSE")) { telemetry.addData("stringToServoDirection", "Finish setting servo direction backward"); return Servo.Direction.REVERSE; } else { telemetry.addData("stringToServoDirection", "Finish setting servo direction to value"); return Servo.Direction.valueOf(stringD); } } private Motor stringToMotorMapObject(String motorName){ telemetry.addData("stringToMotorMapObject", "Creating motors"); for (Motor m : motorMap.values()) { if (motorMap.get(motorName)==m) { return m; } } telemetry.addData("stringToMotorMapObject", "Finishing creating motors"); return null; //TODO fix bad coding practice of using null as an invalid return value. Create a standard null motor for error detection. } }
package org.waterforpeople.mapping.app.web.rest; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.waterforpeople.mapping.analytics.dao.SurveyQuestionSummaryDao; import org.waterforpeople.mapping.app.gwt.client.surveyinstance.QuestionAnswerStoreDto; import org.waterforpeople.mapping.app.util.DtoMarshaller; import org.waterforpeople.mapping.app.web.rest.dto.QuestionAnswerStorePayload; import org.waterforpeople.mapping.app.web.rest.dto.RestStatusDto; import org.waterforpeople.mapping.dao.QuestionAnswerStoreDao; import org.waterforpeople.mapping.dao.SurveyInstanceDAO; import org.waterforpeople.mapping.domain.QuestionAnswerStore; import com.gallatinsystems.survey.dao.QuestionDao; import com.gallatinsystems.survey.domain.Question; import com.gallatinsystems.surveyal.domain.SurveyalValue; import com.gallatinsystems.surveyal.dao.SurveyedLocaleDao; @Controller @RequestMapping("/question_answers") public class QuestionAnswerRestService { // list questionAnswerStores by id @RequestMapping(method = RequestMethod.GET, value = "") @ResponseBody public Map<String, List<QuestionAnswerStoreDto>> listQABySurveyInstanceId( @RequestParam(value = "surveyInstanceId", defaultValue = "") Long surveyInstanceId) { final Map<String, List<QuestionAnswerStoreDto>> response = new HashMap<String, List<QuestionAnswerStoreDto>>(); List<QuestionAnswerStoreDto> results = new ArrayList<QuestionAnswerStoreDto>(); List<QuestionAnswerStore> questionAnswerStores = null; SurveyInstanceDAO siDao = new SurveyInstanceDAO(); QuestionDao qDao = new QuestionDao(); // get list of question-answers if (surveyInstanceId != null) { questionAnswerStores = siDao.listQuestionAnswerStore( surveyInstanceId, null); if (questionAnswerStores != null && questionAnswerStores.size() > 0) { // get the list of questions belonging to this surveyInstance in // the right order List<Question> qList = qDao .listQuestionsInOrder(questionAnswerStores.get(0) .getSurveyId()); Map<Integer, QuestionAnswerStoreDto> orderedResults = new TreeMap<Integer, QuestionAnswerStoreDto>(); // sort the questionAnswers in the order of the questions int notFoundCount = 0; if (qList != null) { for (QuestionAnswerStore qas : questionAnswerStores) { QuestionAnswerStoreDto qasDto = new QuestionAnswerStoreDto(); DtoMarshaller.copyToDto(qas, qasDto); int idx = -1 - notFoundCount; for (int i = 0; i < qList.size(); i++) { if (Long.parseLong(qas.getQuestionID()) == qList .get(i).getKey().getId()) { qasDto.setQuestionText(qList.get(i).getText()); idx = i; break; } } // do this to prevent collisions on the -1 key if there // is more than one questionAnswerStore item that isn't // in the question list. QuestionAnswerStores that don't // have a corresponding question are put at the front // of the map. if (idx < 0) { notFoundCount++; } orderedResults.put(idx, qasDto); } } results = new ArrayList<QuestionAnswerStoreDto>( orderedResults.values()); } } response.put("question_answers", results); return response; } // find a single questionAnswerStore by the questionAnswerStoreId // TODO include question text in dto @RequestMapping(method = RequestMethod.GET, value = "/{id}") @ResponseBody public Map<String, QuestionAnswerStoreDto> findQuestionAnswerStore( @PathVariable("id") Long id) { final Map<String, QuestionAnswerStoreDto> response = new HashMap<String, QuestionAnswerStoreDto>(); QuestionAnswerStoreDao qaDao = new QuestionAnswerStoreDao(); QuestionAnswerStore s = qaDao.getByKey(id); QuestionAnswerStoreDto dto = null; if (s != null) { dto = new QuestionAnswerStoreDto(); DtoMarshaller.copyToDto(s, dto); } response.put("question_answer", dto); return response; } // update existing questionAnswerStore @RequestMapping(method = RequestMethod.PUT, value = "/{id}") @ResponseBody public Map<String, Object> saveExistingQuestionAnswerStore( @RequestBody QuestionAnswerStorePayload payLoad) { final QuestionAnswerStoreDto questionAnswerStoreDto = payLoad .getQuestion_answer(); final Map<String, Object> response = new HashMap<String, Object>(); QuestionAnswerStoreDto dto = null; QuestionAnswerStoreDao qaDao = new QuestionAnswerStoreDao(); RestStatusDto statusDto = new RestStatusDto(); statusDto.setStatus("failed"); // if the POST data contains a valid questionAnswerStoreDto, continue. // Otherwise, // server will respond with 400 Bad Request if (questionAnswerStoreDto != null) { Long keyId = questionAnswerStoreDto.getKeyId(); QuestionAnswerStore qa; // if the questionAnswerStoreDto has a key, try to get the // questionAnswerStore. if (keyId != null) { qa = qaDao.getByKey(keyId); // if we find the questionAnswerStore, update it's properties if (qa != null) { //Before updating the properties, fix the questionAnswerSummary counts if it is an OPTION question QuestionDao qDao = new QuestionDao(); Question q = qDao.getByKey(Long.parseLong(qa.getQuestionID())); if (q != null && Question.Type.OPTION.equals(q.getType())) { // decrease count of current item SurveyQuestionSummaryDao.incrementCount(qa, -1); // increase count of new item String newVal = questionAnswerStoreDto.getValue(); if (newVal != null && newVal.trim().length() > 0){ SurveyQuestionSummaryDao.incrementCount(constructQAS(qa.getQuestionID(),newVal),1); } } // copy the properties, except the createdDateTime property, // because it is set in the Dao. BeanUtils.copyProperties(questionAnswerStoreDto, qa, new String[] { "createdDateTime", "status", "version", "lastUpdateDateTime", "displayName", "questionGroupList", "questionText" }); qa = qaDao.save(qa); // next, update the corresponding surveyalValue object // find surveyalValue based on surveyInstanceId and questionId Long surveyInstanceId = qa.getSurveyInstanceId(); String questionId = qa.getQuestionID(); SurveyedLocaleDao slDao = new SurveyedLocaleDao(); List<SurveyalValue> svals = slDao.listSVByQuestionAndSurveyInstance(surveyInstanceId,Long.parseLong(questionId)); if (svals != null && svals.size() > 0){ SurveyalValue sval = svals.get(0); sval.setStringValue(qa.getValue()); slDao.save(sval); } // return result to the Dashboard dto = new QuestionAnswerStoreDto(); DtoMarshaller.copyToDto(qa, dto); // give back the question text as we received it dto.setQuestionText(questionAnswerStoreDto.getQuestionText()); statusDto.setStatus("ok"); } } } response.put("meta", statusDto); response.put("question_answer", dto); return response; } /** * helper method to create a new QuestionAnswerStore object using the values * passed in. * Same method as in SurveyQuestionSummaryUpdater * @param id * @param value * @return */ private QuestionAnswerStore constructQAS(String id, String value) { QuestionAnswerStore qas = new QuestionAnswerStore(); qas.setQuestionID(id); qas.setValue(value); return qas; } }
package alma.acs.alarmsystem.source; import java.sql.Timestamp; import java.util.Properties; import alma.JavaContainerError.wrappers.AcsJContainerServicesEx; import alma.acs.container.ContainerServicesBase; import alma.acs.logging.AcsLogLevel; import alma.acsErrTypeAlarmSourceFactory.ACSASFactoryNotInitedEx; import alma.acsErrTypeAlarmSourceFactory.SourceCreationErrorEx; import alma.alarmsystem.source.ACSAlarmSystemInterface; import alma.alarmsystem.source.ACSAlarmSystemInterfaceFactory; import alma.alarmsystem.source.ACSFaultState; /** * A support class for sending alarms. * * @author acaproni * */ public class AlarmSender { /** * The source to send alarms. */ private ACSAlarmSystemInterface source=null; /** * Signal that the alarm factory has been closed and it is not * possible to send alarms anymore */ private volatile boolean closed=false; /** * The ContainerServicesBase */ private final ContainerServicesBase containerServices; /** * Constructor * * @param containerServices The ContainerServicesBase */ public AlarmSender(ContainerServicesBase containerServices) { if (containerServices==null) { throw new IllegalArgumentException("The containerServices can't be null"); } this.containerServices=containerServices; } /** * Send an alarm with user properties * * @param FF The fault family * @param FM The fault member * @param FC The fault code * @param properties The properties (can be <code>null</code> or empty) * @param active If <code>true</code> the alarm is activated otherwise it is terminated */ public void sendAlarm( String FF, String FM, int FC, Properties properties, boolean active) { if (closed) { StringBuilder str = new StringBuilder("Alarm factory closed alarm sending disabled"); containerServices.getLogger().log(AcsLogLevel.WARNING,str.toString()); return; } if (source==null) { try { init(); } catch (Throwable t) { containerServices.getLogger().log(AcsLogLevel.ERROR,"Error initializing the alarm service structs",t); } } try { ACSFaultState fs = ACSAlarmSystemInterfaceFactory.createFaultState(FF, FM, FC); if (active) { fs.setDescriptor(ACSFaultState.ACTIVE); } else { fs.setDescriptor(ACSFaultState.TERMINATE); } fs.setUserTimestamp(new Timestamp(System.currentTimeMillis())); fs.setUserProperties(properties); source.push(fs); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Send an alarm with no user properties * * @param FF The fault family * @param FM The fault member * @param FC The fault code * @param active If <code>true</code> the alarm is activated otherwise it is terminated * * @see AlarmSender#sendAlarm(String, String, int, Properties, boolean) */ public void sendAlarm( String FF, String FM, int FC, boolean active) { sendAlarm(FF,FM,FC,null,active); } /** * Create the source and initialize the alarm service factory * if needed. * <P> * If an error happens initializing the factory, * @throws AcsJContainerServicesEx In case of error initializing the factory * @throws SourceCreationErrorEx in Case of error creating the source * @throws ACSASFactoryNotInitedEx In case of error initializing the factory */ private void init() throws AcsJContainerServicesEx, ACSASFactoryNotInitedEx, SourceCreationErrorEx { // Check if the factory has been already initialized try { ACSAlarmSystemInterfaceFactory.usingACSAlarmSystem(); } catch (ACSASFactoryNotInitedEx e) { // The factory has not yet been initialized ACSAlarmSystemInterfaceFactory.init(containerServices); } source = ACSAlarmSystemInterfaceFactory.createSource(); } /** * Closes the alarm sending and frees the resources. * <P> * This is the last method to be executed: after it is not possible to send alarms anymore. */ public void close() { closed=true; } }
package alma.acs.alarmsystem.source; import java.util.Properties; import java.util.concurrent.TimeUnit; /** * The AlarmSource interface offers a set of useful methods * to handle alarms from a source. * <P> * This class, on one side, allows the sending of alarms with * a shorter syntax compared to the original API and, * on the other side, offers some common functionalities * useful while sending alarms in ACS. * <P> * This class implements a guard in the sense that a active (terminated) * alarm is not sent to the alarm service if it has been already * activated (terminated). * <P> * To damp the effect of oscillation an active alarm is immediately forwarded * to the alarm service but the sending of a terminated alarm is delayed * of approximately one second to catch a reactivation in that period * of time. * <P> * AlarmSource allows to queue the alarms instead of sending them immediately * by calling <code>queueAlarms(...)</code>. To stop queuing the alarms * and send them to the alarm service the method <code>flushAlarms()</code> * must be executed. * The queuing of the alarms has the advantage that if an alarm is activated * and then deactivated during the queuing time, it is not sent to the * alarm service. * This functionalities can be useful for example when starting up a piece * of software connected to an hardware device. In that case it is quite * common that before initialization some of the values returned by the * device are wrong and can trigger the sending of alarms that will be cleared * only when the device is fully operative. * With the queuing the operator does not receive this kind of (false) * alarms. It is left to developer the responsibility to enable/disable * the queuing at the right moment. * * @author acaproni */ public interface AlarmSource { /** * Raise an alarm with the given triplet. * <P> * If the alarm is already active, it is not sent again * to the alarm service. * * @param faultFamily The FaultFamily * @param faultMember The FaultMember * @param faultCode The FaultCode */ public void raiseAlarm( String faultFamily, String faultMember, int faultCode); /** * Raise an alarm with the given triplet and a set of properties. * <P> * If the alarm is already active, it is not sent again * to the alarm service. * * @param faultFamily The FaultFamily * @param faultMember The FaultMember * @param faultCode The FaultCode * @param properties The user properties. * It can be <code>null</code> or empty. */ public void raiseAlarm( String faultFamily, String faultMember, int faultCode, Properties properties); /** * Clear the alarm with the passed triplet. * <P> * If the alarm is already terminated, it is not sent again * to the alarm service. * * @param faultFamily The FaultFamily * @param faultMember The FaultMember * @param faultCode The FaultCode */ public void clearAlarm( String faultFamily, String faultMember, int faultCode); /** * Send the alarm with the passed triplet and properties to the * alarm service. The state activate/terminate of the alarm * depends on the passed boolean. * <P> * This method is the most complete way to send an alarm. * <P> * If the alarm is already active, it is not sent again * to the alarm service. * If the alarm is already terminated, it is not sent again * to the alarm service. * * @param faultFamily The FaultFamily * @param faultMember The FaultMember * @param faultCode The FaultCode * @param alarmProps The user properties. * It can be <code>null</code> or empty. * @param active if <code>true</code> the alarm is activated * otherwise it is terminated. */ public void setAlarm( String faultFamily, String faultMember, int faultCode, Properties alarmProps, boolean active); /** * Send the alarm with the passed triplet to the * alarm service. The state activate/terminate of the alarm * depends on the passed boolean. * <P> * This method is the most complete way to send an alarm. * <P> * If the alarm is already active, it is not sent again * to the alarm service. * If the alarm is already terminated, it is not sent again * to the alarm service. * * @param faultFamily The FaultFamily * @param faultMember The FaultMember * @param faultCode The FaultCode * @param active if <code>true</code> the alarm is activated * otherwise it is terminated. */ public void setAlarm( String faultFamily, String faultMember, int faultCode, boolean active); /** * Terminate all the active alarms. */ public void terminateAllAlarms(); /** * Start queuing the alarms. * <P> * The alarms are flushed when the passed time expires. * * @param delayTime The time to queue alarms in milliseconds */ public void queueAlarms(long delayTime); /** * Start queuing the alarms. * <P> * The alarms are flushed when the passed time expires. * * @param delayTime The time to queue alarms * @param unit The unit of the delay */ public void queueAlarms(long delayTime, TimeUnit unit); /** * Start queuing the alarms. * <P> * The alarms are queued until <code>flushAlarms()</code> is executed. * * @param time The time to queue alarms * @see AlarmSource#flushAlarms() */ public void queueAlarms(); /** * Flush the alarms queued and stop queuing. * * @see {@link AlarmSource#queueAlarms()} */ public void flushAlarms(); /** * Disable the sending of alarms. * <P> * When the alarms are disabled, all the alarms submitted with * raise, clear and set are discarded. This means that those alarms * never arrive to the alarm service neither be part of queuing neither * guarded. * * @see AlarmSource#enableAlarms() */ public void disableAlarms(); /** * Enable the sending of alarms. * <P> * This method has to be called after disableAlarms(). * <P> * Alarms are enabled by default. * * @see AlarmSource#disableAlarms() */ public void enableAlarms(); /** * Lifecycle: this method must be called before using this class. */ public void start(); /** * Lifecycle: tearDown must be called when terminated using this class */ public void tearDown(); }
package com.example.ohta.mirrorhack01; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.speech.RecognizerIntent; import android.speech.tts.TextToSpeech; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Locale; public class MainActivity extends Activity implements TextToSpeech.OnInitListener{ private static final int REQUEST_CODE = 0; TextToSpeech tts = null; private TextView message; private int count = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // ActionBar actionBar = getActionBar(); // actionBar.hide(); message = (TextView)findViewById(R.id.message); tts = new TextToSpeech(this, this); } @Override public boolean onTouchEvent(MotionEvent event) { if(event.getAction()==MotionEvent.ACTION_UP) { try { // "android.speech.action.RECOGNIZE_SPEECH" Intent intent = new Intent( RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, ""); startActivityForResult(intent, REQUEST_CODE); } catch (ActivityNotFoundException e) { Toast.makeText(this, "", Toast.LENGTH_LONG).show(); } } return super.onTouchEvent(event); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) { ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); String s = results.get(0); Toast.makeText(this, s, Toast.LENGTH_LONG).show(); if(tts.isSpeaking()) { tts.stop(); } tts.speak(s, TextToSpeech.QUEUE_FLUSH, null); } super.onActivityResult(requestCode, resultCode, data); } @Override public void onInit(int status) { if(status == TextToSpeech.SUCCESS) { float pitch = 1.0f; float rate = 1.0f; Locale locale = Locale.US; tts.setPitch(pitch); tts.setSpeechRate(rate); tts.setLanguage(locale); } } @Override protected void onDestroy() { super.onDestroy(); if( tts != null ) { tts.shutdown(); } } }
package chanedi.generator; import chanedi.enums.DBDialectType; import chanedi.generator.file.FilesGenerator; import chanedi.generator.file.GlobalConfig; import org.junit.Test; public class FilesGeneratorTest { @Test public void generate() throws Exception { FilesGenerator generator = new FilesGenerator(); GlobalConfig globalConfig = generator.getGlobalConfig(); // globalConfig.setOutProjectPath("D:/"); // globalConfig.setBeanNameRegex("^BUS_(\\w+)$"); // globalConfig.setBeanNameRegex("^T_[A-Z]{3}_(\\w+)$"); globalConfig.setJavaPackageName("com.xx.common.file"); globalConfig.setJavaPackagePath("com"); globalConfig.setDbDialectType(DBDialectType.ORACLE); globalConfig.setTmplPath("classpath:/tmpl/file/example2"); globalConfig.setIgnoreExists(false); generator.process(); } }
package com.facebook.react.devsupport; import javax.annotation.Nullable; import java.io.File; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; /** * Helper class converting JS and Java stack traces into arrays of {@link StackFrame} objects. */ public class StackTraceHelper { /** * Represents a generic entry in a stack trace, be it originally from JS or Java. */ public static class StackFrame { private final String mFile; private final String mMethod; private final int mLine; private final int mColumn; private final String mFileName; private StackFrame(String file, String method, int line, int column) { mFile = file; mMethod = method; mLine = line; mColumn = column; mFileName = new File(file).getName(); } private StackFrame(String file, String fileName, String method, int line, int column) { mFile = file; mFileName = fileName; mMethod = method; mLine = line; mColumn = column; } /** * Get the file this stack frame points to. * * JS traces return the full path to the file here, while Java traces only return the file name * (the path is not known). */ public String getFile() { return mFile; } /** * Get the name of the method this frame points to. */ public String getMethod() { return mMethod; } /** * Get the line number this frame points to in the file returned by {@link #getFile()}. */ public int getLine() { return mLine; } /** * Get the column this frame points to in the file returned by {@link #getFile()}. */ public int getColumn() { return mColumn; } /** * Get just the name of the file this frame points to. * * For JS traces this is different from {@link #getFile()} in that it only returns the file * name, not the full path. For Java traces there is no difference. */ public String getFileName() { return mFileName; } } /** * Convert a JavaScript stack trace (see {@code parseErrorStack} JS module) to an array of * {@link StackFrame}s. */ public static StackFrame[] convertJsStackTrace(@Nullable ReadableArray stack) { int size = stack != null ? stack.size() : 0; StackFrame[] result = new StackFrame[size]; for (int i = 0; i < size; i++) { ReadableMap frame = stack.getMap(i); String methodName = frame.getString("methodName"); String fileName = frame.getString("file"); int lineNumber = frame.getInt("lineNumber"); int columnNumber = -1; if (frame.hasKey("column") && !frame.isNull("column")) { columnNumber = frame.getInt("column"); } result[i] = new StackFrame(fileName, methodName, lineNumber, columnNumber); } return result; } /** * Convert a {@link Throwable} to an array of {@link StackFrame}s. */ public static StackFrame[] convertJavaStackTrace(Throwable exception) { StackTraceElement[] stackTrace = exception.getStackTrace(); StackFrame[] result = new StackFrame[stackTrace.length]; for (int i = 0; i < stackTrace.length; i++) { result[i] = new StackFrame( stackTrace[i].getClassName(), stackTrace[i].getFileName(), stackTrace[i].getMethodName(), stackTrace[i].getLineNumber(), -1); } return result; } /** * Format a {@link StackFrame} to a String (method name is not included). */ public static String formatFrameSource(StackFrame frame) { String lineInfo = ""; final int column = frame.getColumn(); // If the column is 0, don't show it in red box. final String columnString = column <= 0 ? "" : ":" + column; lineInfo += frame.getFileName() + ":" + frame.getLine() + columnString; return lineInfo; } /** * Format an array of {@link StackFrame}s with the error title to a String. */ public static String formatStackTrace(String title, StackFrame[] stack) { StringBuilder stackTrace = new StringBuilder(); stackTrace.append(title).append("\n"); for (StackFrame frame: stack) { stackTrace.append(frame.getMethod()) .append("\n") .append(" ") .append(formatFrameSource(frame)) .append("\n"); } return stackTrace.toString(); } }
package org.reldb.dbrowser.ui.content.conversion; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.ToolBar; import org.reldb.dbrowser.ui.DbTab; import org.reldb.dbrowser.ui.preferences.PreferenceChangeAdapter; import org.reldb.dbrowser.ui.preferences.PreferenceChangeEvent; import org.reldb.dbrowser.ui.preferences.PreferenceChangeListener; import org.reldb.dbrowser.ui.preferences.PreferencePageGeneral; import org.reldb.dbrowser.ui.preferences.Preferences; public class DbTabContentConversion extends Composite { private Label conversion; private PreferenceChangeListener preferenceChangeListener; public DbTabContentConversion(DbTab parentTab, String dbURL, Composite contentParent) { super(contentParent, SWT.None); setLayout(new FormLayout()); ToolBar toolBar = new ToolBar(this, SWT.None); FormData fd_toolBar = new FormData(); fd_toolBar.left = new FormAttachment(0); fd_toolBar.top = new FormAttachment(0); fd_toolBar.right = new FormAttachment(100); toolBar.setLayoutData(fd_toolBar); conversion = new Label(this, SWT.None); conversion.setText("Conversion content goes here."); FormData fd_composite = new FormData(); fd_composite.left = new FormAttachment(0); fd_composite.top = new FormAttachment(toolBar); fd_composite.right = new FormAttachment(100); fd_composite.bottom = new FormAttachment(100); conversion.setLayoutData(fd_composite); setupIcons(); preferenceChangeListener = new PreferenceChangeAdapter("DbTabContentConversion") { @Override public void preferenceChange(PreferenceChangeEvent evt) { setupIcons(); } }; Preferences.addPreferenceChangeListener(PreferencePageGeneral.LARGE_ICONS, preferenceChangeListener); } public void dispose() { Preferences.removePreferenceChangeListener(PreferencePageGeneral.LARGE_ICONS, preferenceChangeListener); super.dispose(); } private void setupIcons() { } public void notifyIconSizeChange() { setupIcons(); } }
package mondrian.rolap; import mondrian.olap.*; import java.util.List; import java.util.ArrayList; import java.util.HashMap; /** * A <code>RolapSchemaReader</code> allows you to read schema objects while * observing the access-control profile specified by a given role. * * @author jhyde * @since Feb 24, 2003 * @version $Id$ **/ abstract class RolapSchemaReader implements SchemaReader { private Role role; private HashMap hierarchyReaders = new HashMap(); RolapSchemaReader(Role role) { this.role = role; } public Role getRole() { return role; } public Member[] getHierarchyRootMembers(Hierarchy hierarchy) { final Role.HierarchyAccess hierarchyAccess = role.getAccessDetails(hierarchy); Level firstLevel; if (hierarchyAccess == null) { firstLevel = hierarchy.getLevels()[0]; } else { firstLevel = hierarchyAccess.getTopLevel(); if (firstLevel == null) { firstLevel = hierarchy.getLevels()[0]; } } return getLevelMembers(firstLevel); } private synchronized MemberReader getMemberReader(Hierarchy hierarchy) { MemberReader memberReader = (MemberReader) hierarchyReaders.get(hierarchy); if (memberReader == null) { memberReader = ((RolapHierarchy) hierarchy).getMemberReader(role); hierarchyReaders.put(hierarchy, memberReader); } return memberReader; } public void getMemberRange(Level level, Member startMember, Member endMember, List list) { getMemberReader(level.getHierarchy()).getMemberRange( (RolapLevel) level, (RolapMember) startMember, (RolapMember) endMember, list); } public int compareMembersHierarchically(Member m1, Member m2) { final RolapHierarchy hierarchy = (RolapHierarchy) m1.getHierarchy(); Util.assertPrecondition(hierarchy == m2.getHierarchy()); return getMemberReader(hierarchy).compare((RolapMember) m1, (RolapMember) m2, true); } public Member getMemberParent(Member member) { final Member parentMember = member.getParentMember(); if (parentMember != null) { final Role.HierarchyAccess hierarchyAccess = role.getAccessDetails(member.getHierarchy()); if (hierarchyAccess != null && hierarchyAccess.getAccess(parentMember) == Access.NONE) { return null; } } return parentMember; } public int getMemberDepth(Member member) { final Role.HierarchyAccess hierarchyAccess = role.getAccessDetails(member.getHierarchy()); if (hierarchyAccess != null) { int memberDepth = member.getLevel().getDepth(); final Level topLevel = hierarchyAccess.getTopLevel(); if (topLevel != null) { memberDepth -= topLevel.getDepth(); } return memberDepth; } else if (((RolapLevel) member.getLevel()).parentExp != null) { // For members of parent-child hierarchy, members in the same level may have // different depths. int depth = 0; for (Member m = member.getParentMember(); m != null; m = m.getParentMember()) { depth++; } return depth; } else { return member.getLevel().getDepth(); } } public Member[] getMemberChildren(Member member) { ArrayList children = new ArrayList(); getMemberReader(member.getHierarchy()).getMemberChildren( (RolapMember) member, children); return RolapUtil.toArray(children); } public Member[] getMemberChildren(Member[] members) { if (members.length == 0) { return RolapUtil.emptyMemberArray; } else { final MemberReader memberReader = getMemberReader(members[0].getHierarchy()); ArrayList children = new ArrayList(); for (int i = 0; i < members.length; i++) { memberReader.getMemberChildren((RolapMember) members[i], children); } return RolapUtil.toArray(children); } } public abstract Cube getCube(); public OlapElement getElementChild(OlapElement parent, String name) { return parent.lookupChild(this, name); } public Member getMemberByUniqueName(String[] uniqueNameParts, boolean failIfNotFound) { return Util.lookupMemberCompound(this, getCube(), uniqueNameParts, failIfNotFound); } public Member getLeadMember(Member member, int n) { return getMemberReader(member.getHierarchy()).getLeadMember((RolapMember) member, n); } public Member[] getLevelMembers(Level level) { final List membersInLevel = getMemberReader(level.getHierarchy()).getMembersInLevel( (RolapLevel) level, 0, Integer.MAX_VALUE); return RolapUtil.toArray(membersInLevel); } public Level[] getHierarchyLevels(Hierarchy hierarchy) { Util.assertPrecondition(hierarchy != null, "hierarchy != null"); final Role.HierarchyAccess hierarchyAccess = role.getAccessDetails(hierarchy); final Level[] levels = hierarchy.getLevels(); if (hierarchyAccess == null) { return levels; } Level topLevel = hierarchyAccess.getTopLevel(); Level bottomLevel = hierarchyAccess.getBottomLevel(); if (topLevel == null && bottomLevel == null) { return levels; } if (topLevel == null) { topLevel = levels[0]; } if (bottomLevel == null) { bottomLevel = levels[levels.length - 1]; } final int levelCount = bottomLevel.getDepth() - topLevel.getDepth() + 1; Level[] restrictedLevels = new Level[levelCount]; System.arraycopy(levels, topLevel.getDepth(), restrictedLevels, 0, levelCount); Util.assertPostcondition(restrictedLevels.length >= 1, "return.length >= 1"); return restrictedLevels; } public Member getHierarchyDefaultMember(Hierarchy hierarchy) { RolapMember member = (RolapMember) hierarchy.getDefaultMember(); final Role.HierarchyAccess hierarchyAccess = role.getAccessDetails(hierarchy); if (hierarchyAccess != null) { final Level level = member.getLevel(); final int levelDepth = level.getDepth(); final Level topLevel = hierarchyAccess.getTopLevel(); final MemberReader unrestrictedMemberReader = ((RolapHierarchy) hierarchy).memberReader; if (topLevel != null && topLevel.getDepth() > levelDepth) { // Find the first child of the first child... until we get to // a level we can see. ArrayList children = new ArrayList(); do { unrestrictedMemberReader.getMemberChildren(member, children); Util.assertTrue(children.size() > 0); member = (RolapMember) children.get(0); children.clear(); } while (member.getLevel() != topLevel); return member; } final Level bottomLevel = hierarchyAccess.getBottomLevel(); if (bottomLevel != null && bottomLevel.getDepth() < levelDepth) { do { member = (RolapMember) member.getParentMember(); Util.assertTrue(member != null); } while (member.getLevel() != bottomLevel); return member; } } return member; } public boolean isDrillable(Member member) { final RolapLevel level = (RolapLevel) member.getLevel(); if (level.parentExp != null) { // This is a parent-child level, so its children, if any, come from // the same level. // todo: More efficient implementation return getMemberChildren(member).length > 0; } else { // This is a regular level. It has children iff there is a lower // level. final Level childLevel = level.getChildLevel(); return childLevel != null && role.getAccess(childLevel) != Access.NONE; } } } // End RolapSchemaReader.java
// S i g R e d u c e r // // <editor-fold defaultstate="collapsed" desc="hdr"> // This program is free software: you can redistribute it and/or modify it under the terms of the // </editor-fold> package org.audiveris.omr.sig; import org.audiveris.omr.constant.ConstantSet; import org.audiveris.omr.glyph.Shape; import org.audiveris.omr.glyph.ShapeSet; import static org.audiveris.omr.glyph.ShapeSet.Alterations; import static org.audiveris.omr.glyph.ShapeSet.CoreBarlines; import static org.audiveris.omr.glyph.ShapeSet.Flags; import org.audiveris.omr.math.GeoOrder; import org.audiveris.omr.math.GeoUtil; import org.audiveris.omr.sheet.Scale; import org.audiveris.omr.sheet.Staff; import org.audiveris.omr.sheet.SystemInfo; import org.audiveris.omr.sheet.header.StaffHeader; import org.audiveris.omr.sheet.rhythm.SystemBackup; import org.audiveris.omr.sig.inter.AbstractBeamInter; import org.audiveris.omr.sig.inter.AbstractChordInter; import org.audiveris.omr.sig.inter.AbstractNoteInter; import org.audiveris.omr.sig.inter.AbstractTimeInter; import org.audiveris.omr.sig.inter.AlterInter; import org.audiveris.omr.sig.inter.AugmentationDotInter; import org.audiveris.omr.sig.inter.BarlineInter; import org.audiveris.omr.sig.inter.BeamHookInter; import org.audiveris.omr.sig.inter.BeamInter; import org.audiveris.omr.sig.inter.DeletedInterException; import org.audiveris.omr.sig.inter.HeadInter; import org.audiveris.omr.sig.inter.Inter; import org.audiveris.omr.sig.inter.InterEnsemble; import org.audiveris.omr.sig.inter.KeyAlterInter; import org.audiveris.omr.sig.inter.LedgerInter; import org.audiveris.omr.sig.inter.SlurInter; import org.audiveris.omr.sig.inter.SmallBeamInter; import org.audiveris.omr.sig.inter.StemInter; import org.audiveris.omr.sig.inter.StringSymbolInter; import org.audiveris.omr.sig.inter.TimeNumberInter; import org.audiveris.omr.sig.inter.TupletInter; import org.audiveris.omr.sig.inter.WordInter; import org.audiveris.omr.sig.relation.AbstractConnection; import org.audiveris.omr.sig.relation.AlterHeadRelation; import org.audiveris.omr.sig.relation.AugmentationRelation; import org.audiveris.omr.sig.relation.BeamHeadRelation; import org.audiveris.omr.sig.relation.BeamPortion; import org.audiveris.omr.sig.relation.BeamStemRelation; import org.audiveris.omr.sig.relation.CrossExclusion; import org.audiveris.omr.sig.relation.DoubleDotRelation; import org.audiveris.omr.sig.relation.Exclusion; import org.audiveris.omr.sig.relation.HeadHeadRelation; import org.audiveris.omr.sig.relation.HeadStemRelation; import org.audiveris.omr.sig.relation.Relation; import org.audiveris.omr.sig.relation.StemPortion; import static org.audiveris.omr.sig.relation.StemPortion.*; import org.audiveris.omr.sig.relation.TimeTopBottomRelation; import org.audiveris.omr.util.HorizontalSide; import static org.audiveris.omr.util.HorizontalSide.*; import org.audiveris.omr.util.Navigable; import org.audiveris.omr.util.Predicate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.awt.Rectangle; import java.awt.geom.Line2D; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumMap; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; public class SigReducer { private static final Constants constants = new Constants(); private static final Logger logger = LoggerFactory.getLogger(SigReducer.class); /** Shapes for which overlap detection is (currently) disabled. */ private static final EnumSet<Shape> disabledShapes = EnumSet.copyOf( Arrays.asList(Shape.LEDGER, Shape.CRESCENDO, Shape.DIMINUENDO)); /** Predicate for non-disabled overlap. */ private static final Predicate<Inter> overlapPredicate = new Predicate<Inter>() { @Override public boolean check (Inter inter) { // Take all non-disabled shapes // Excluding inters within headers return !disabledShapes.contains(inter.getShape()); } }; /** Shapes that can overlap with a beam. */ private static final EnumSet<Shape> beamCompShapes = EnumSet.copyOf(CoreBarlines); /** Shapes that can overlap with a slur. */ private static final EnumSet<Shape> slurCompShapes = EnumSet.noneOf(Shape.class); static { slurCompShapes.addAll(Alterations.getShapes()); slurCompShapes.addAll(CoreBarlines); slurCompShapes.addAll(Flags.getShapes()); } /** Shapes that can overlap with a stem. */ private static final EnumSet<Shape> stemCompShapes = EnumSet.copyOf( Arrays.asList(Shape.SLUR, Shape.CRESCENDO, Shape.DIMINUENDO)); /** Standard vs Small size. */ private static enum Size { STANDARD, SMALL; } /** The dedicated system. */ @Navigable(false) private final SystemInfo system; /** Scale. */ @Navigable(false) private final Scale scale; /** The related SIG. */ private final SIGraph sig; /** Should we purge weak inter instances?. */ private final boolean purgeWeaks; /** * Creates a new {@code SigReducer} object. * * @param system the related system * @param purgeWeaks true for purging weak inters */ public SigReducer (SystemInfo system, boolean purgeWeaks) { this.system = system; this.purgeWeaks = purgeWeaks; sig = system.getSig(); scale = system.getSheet().getScale(); } // detectCrossOverlaps // // /** // * Detect all cases where 2 Inters actually overlap and, if there is no support // * relation between them, insert a mutual exclusion. // * <p> // * This method is key! // * // * @param list1 the collection of inters to process from one system // * @param list2 the collection of inters to process from another system // */ public static void detectCrossOverlaps (List<Inter> list1, List<Inter> list2) { Collections.sort(list2, Inter.byAbscissa); NextLeft: for (Inter left : list1) { if (left.isDeleted()) { continue; } final Rectangle leftBox = left.getBounds(); final double xMax = leftBox.getMaxX(); for (Inter right : list2) { if (right.isDeleted()) { continue; } // Overlap is accepted in some cases if (compatible(new Inter[]{left, right})) { continue; } Rectangle rightBox = right.getBounds(); if (leftBox.intersects(rightBox)) { // Have a more precise look if (left.isVip() && right.isVip()) { ////////logger.info("VIP check overlap {} vs {}", left, right); } try { if (left.overlaps(right) && right.overlaps(left)) { // Specific case: Word vs "string" Symbol if (left instanceof WordInter && right instanceof StringSymbolInter) { if (wordMatchesSymbol((WordInter) left, (StringSymbolInter) right)) { left.decrease(0.5); } } else if (left instanceof StringSymbolInter && right instanceof WordInter) { if (wordMatchesSymbol((WordInter) right, (StringSymbolInter) left)) { right.decrease(0.5); } } logger.info("crossExclusion {} & {}", left, right); CrossExclusion.insert(left, right); // Cross-system } } catch (DeletedInterException diex) { if (diex.inter == left) { continue NextLeft; } } } else if (rightBox.x > xMax) { break; // Since right list is sorted by abscissa } } } } // reduceFoundations // /** * Reduce all the interpretations and relations of the SIG, on the founding inters * (Heads, Stems and Beams). * This is meant for the REDUCTION step. */ public void reduceFoundations () { reduce(new AdapterForFoundations()); } // reduceLinks // /** * Final global reduction. * This is meant for the LINKS step. */ public void reduceLinks () { reduce(new AdapterForLinks()); } // reduceRhythms // /** * Reduce interpretations while saving reduced rhythm data. * This is meant for the RHYTHMS step. * * @param systemPoorFrats (output) where selected inters must be backed up * @param classes FRAT classes */ public void reduceRhythms (SystemBackup systemPoorFrats, Class<?>... classes) { AdapterForRhythms adapter = new AdapterForRhythms(systemPoorFrats, classes); Set<Inter> allRemoved = reduce(adapter); allRemoved.retainAll(adapter.selected); systemPoorFrats.setSeeds(allRemoved); } // reduceSymbols // /** * Reduce symbols interpretations. * This is meant for the SYMBOLS step. * * @return the removed inters */ public Set<Inter> reduceSymbols () { AdapterForSymbols adapter = new AdapterForSymbols(); return reduce(adapter); } // analyzeChords // /** * Analyze consistency of note heads & beams attached to a (good) stem. * <ul> * <li>All (standard) black, all (standard) void, all small black or all small void. * <li>All (standard) beams or all small beams. * <li>(standard) beams with (standard) heads only. * <li>Small beams with small heads only. * </ul> */ private void analyzeChords () { // All stems of the sig List<Inter> stems = sig.inters(Shape.STEM); // Heads organized by shape (black, void, and small versions) Map<Shape, Set<Inter>> heads = new HashMap<Shape, Set<Inter>>(); // Beams organized by size (standard vs small versions) Map<Size, Set<Inter>> beams = new EnumMap<Size, Set<Inter>>(Size.class); for (Inter stem : stems) { if (stem.isVip()) { // logger.info("VIP analyzeChords with {}", stem); } // Consider only good stems if (!stem.isGood()) { continue; } heads.clear(); beams.clear(); // Populate the various head & beam classes around this stem for (Relation rel : sig.edgesOf(stem)) { if (rel instanceof HeadStemRelation) { Inter head = sig.getEdgeSource(rel); Shape shape = head.getShape(); Set<Inter> set = heads.get(shape); if (set == null) { heads.put(shape, set = new LinkedHashSet<Inter>()); } set.add(head); } else if (rel instanceof BeamStemRelation) { Inter beam = sig.getEdgeSource(rel); Size size = (beam instanceof SmallBeamInter) ? Size.SMALL : Size.STANDARD; Set<Inter> set = beams.get(size); if (set == null) { beams.put(size, set = new LinkedHashSet<Inter>()); } set.add(beam); } } // Mutual head exclusion based on head shape List<Shape> headShapes = new ArrayList<Shape>(heads.keySet()); for (int ic = 0; ic < (headShapes.size() - 1); ic++) { Shape c1 = headShapes.get(ic); Set<Inter> set1 = heads.get(c1); for (Shape c2 : headShapes.subList(ic + 1, headShapes.size())) { Set<Inter> set2 = heads.get(c2); exclude(set1, set2); } } // Mutual head support within same shape for (Shape shape : heads.keySet()) { List<Inter> list = new ArrayList<Inter>(heads.get(shape)); for (int i = 0; i < list.size(); i++) { HeadInter h1 = (HeadInter) list.get(i); for (Inter other : list.subList(i + 1, list.size())) { HeadInter h2 = (HeadInter) other; sig.insertSupport(h1, h2, HeadHeadRelation.class); } } } // Mutual beam exclusion based on beam size List<Size> beamSizes = new ArrayList<Size>(beams.keySet()); for (int ic = 0; ic < (beamSizes.size() - 1); ic++) { Size c1 = beamSizes.get(ic); Set<Inter> set1 = beams.get(c1); for (Size c2 : beamSizes.subList(ic + 1, beamSizes.size())) { Set<Inter> set2 = beams.get(c2); exclude(set1, set2); } } // Head/Beam support or exclusion based on size for (Entry<Size, Set<Inter>> entry : beams.entrySet()) { Size size = entry.getKey(); Set<Inter> beamSet = entry.getValue(); if (size == Size.SMALL) { // Small beams exclude standard heads for (Shape shape : new Shape[]{Shape.NOTEHEAD_BLACK, Shape.NOTEHEAD_VOID}) { Set<Inter> headSet = heads.get(shape); if (headSet != null) { exclude(beamSet, headSet); } } // Small beams support small black heads Set<Inter> smallHeadSet = heads.get(Shape.NOTEHEAD_BLACK_SMALL); if (smallHeadSet != null) { for (Inter smallBeam : beamSet) { BeamStemRelation bs = (BeamStemRelation) sig.getRelation( smallBeam, stem, BeamStemRelation.class); for (Inter smallHead : smallHeadSet) { if (sig.getRelation(smallBeam, smallHead, BeamHeadRelation.class) == null) { // Use average of beam-stem and head-stem relation grades HeadStemRelation hs = (HeadStemRelation) sig.getRelation( smallHead, stem, HeadStemRelation.class); double grade = (bs.getGrade() + hs.getGrade()) / 2; sig.addEdge(smallBeam, smallHead, new BeamHeadRelation(grade)); } } } } } else { // Standard beams exclude small heads Set<Inter> smallHeadSet = heads.get(Shape.NOTEHEAD_BLACK_SMALL); if (smallHeadSet != null) { exclude(beamSet, smallHeadSet); } // Standard beams support black heads (not void) Set<Inter> blackHeadSet = heads.get(Shape.NOTEHEAD_BLACK); if (blackHeadSet != null) { for (Inter beam : beamSet) { BeamStemRelation bs = (BeamStemRelation) sig.getRelation( beam, stem, BeamStemRelation.class); for (Inter head : blackHeadSet) { if (sig.getRelation(beam, head, BeamHeadRelation.class) == null) { // Use average of beam-stem and head-stem relation grades HeadStemRelation hs = (HeadStemRelation) sig.getRelation( head, stem, HeadStemRelation.class); double grade = (bs.getGrade() + hs.getGrade()) / 2; sig.addEdge(beam, head, new BeamHeadRelation(grade)); } } } } } } } } // analyzeFrozenInters // /** * Browse all the frozen inters and simply delete any inter that conflicts with them. */ private void analyzeFrozenInters () { Set<Inter> toDelete = new LinkedHashSet<Inter>(); for (Inter inter : sig.vertexSet()) { if (inter.isFrozen()) { for (Relation rel : sig.getRelations(inter, Exclusion.class)) { Inter other = sig.getOppositeInter(inter, rel); if (other.isFrozen()) { logger.error("Conflicting frozen inters {} & {}", inter, other); } else { toDelete.add(other); if (other.isVip()) { logger.info("VIP deleting {} conflicting with frozen {}", other, inter); } } } } } sig.deleteInters(toDelete); } // analyzeHeadStems // /** * Check any head has at most one stem on left side and one stem on right side. * If not, the various stems on a same side are mutually exclusive. */ private void analyzeHeadStems () { final List<Inter> heads = sig.inters(ShapeSet.NoteHeads.getShapes()); for (Inter hi : heads) { HeadInter head = (HeadInter) hi; // Retrieve connected stems into left and right sides Map<HorizontalSide, Set<StemInter>> map = head.getSideStems(); // Check each side for (Entry<HorizontalSide, Set<StemInter>> entry : map.entrySet()) { Set<StemInter> set = entry.getValue(); if (set.size() > 1) { //////////////////////////////////////////////////HB sig.insertExclusions(set, Exclusion.Cause.OVERLAP); //TODO: // Instead of stem exclusion, we should disconnect head from some of these stems // Either all the stems above or all the stems below } } } } // beamHasBothStems // private boolean beamHasBothStems (BeamInter beam) { boolean hasLeft = false; boolean hasRight = false; // if (beam.isVip()) { // logger.info("VIP beamHasBothStems for {}", beam); for (Relation rel : sig.edgesOf(beam)) { if (rel instanceof BeamStemRelation) { BeamStemRelation bsRel = (BeamStemRelation) rel; BeamPortion portion = bsRel.getBeamPortion(); if (portion == BeamPortion.LEFT) { hasLeft = true; } else if (portion == BeamPortion.RIGHT) { hasRight = true; } } } return hasLeft && hasRight; } // checkAugmentationDots // /** * Perform checks on augmentation dots. * <p> * An augmentation dot needs a target to augment (note, rest or another augmentation dot). * * @return the count of modifications done */ private int checkAugmentationDots () { int modifs = 0; final List<Inter> dots = sig.inters(AugmentationDotInter.class); for (Inter inter : dots) { final AugmentationDotInter dot = (AugmentationDotInter) inter; // Check whether the augmentation dot has a target (note or rest or other dot) if (!sig.hasRelation(dot, AugmentationRelation.class, DoubleDotRelation.class)) { if (dot.isVip() || logger.isDebugEnabled()) { logger.info("Deleting augmentation dot lacking target {}", dot); } dot.delete(); modifs++; } } return modifs; } // checkAugmented // /** * Perform checks on augmented entities. * <p> * An entity (note, rest or augmentation dot) can have at most one augmentation dot. * <p> * NOTA: This is OK for rests but not always for heads. * TODO: We could address head-chords rather than individual heads and handle the chord * augmentation dots as a whole (in parallel with chord heads) and link each chord head with its * 'facing' dot. * * @return the count of modifications done */ private int checkAugmented () { int modifs = 0; List<Inter> entities = sig.inters(AbstractNoteInter.class); for (Inter entity : entities) { Set<Relation> rels = sig.getRelations(entity, AugmentationRelation.class); if (rels.size() > 1) { modifs += reduceAugmentations(rels); if (entity.isVip() || logger.isDebugEnabled()) { logger.info("Reduced augmentations for {}", entity); } } } return modifs; } // checkBeams // /** * Perform checks on beams. * * @return the count of modifications done */ private int checkBeams () { int modifs = 0; final List<Inter> beams = sig.inters(BeamInter.class); for (Inter inter : beams) { final BeamInter beam = (BeamInter) inter; if (!beamHasBothStems(beam)) { if (beam.isVip() || logger.isDebugEnabled()) { logger.info("VIP deleting beam lacking stem {}", beam); } beam.delete(); modifs++; } } return modifs; } // checkDoubleAlters // /** * Perform checks on double alterations (double sharp or double flat). * They need a note head nearby. * * @return the count of modifications done */ private int checkDoubleAlters () { int modifs = 0; final List<Inter> doubles = sig.inters( Arrays.asList(Shape.DOUBLE_FLAT, Shape.DOUBLE_SHARP)); for (Inter inter : doubles) { final AlterInter alter = (AlterInter) inter; // Check whether the double-alter is connected to a note head if (!sig.hasRelation(alter, AlterHeadRelation.class)) { if (alter.isVip() || logger.isDebugEnabled()) { logger.info("VIP deleting {} lacking note head", alter); } alter.delete(); modifs++; } } return modifs; } // checkHeadSide // /** * If head is on the wrong side of the stem, check if there is a head on the other * side, located one or two step(s) further. * <p> * If the side is wrong and there is no head on the other side, simply remove this head-stem * relation and insert exclusion instead. * * @param head the head inter (black or void) * @return the number of modifications done */ private int checkHeadSide (Inter head) { if (head.isVip()) { // logger.info("VIP checkHeadSide for {}", head); } int modifs = 0; // Check all connected stems Set<Relation> stemRels = sig.getRelations(head, HeadStemRelation.class); RelsLoop: for (Relation relation : stemRels) { HeadStemRelation rel = (HeadStemRelation) relation; StemInter stem = (StemInter) sig.getEdgeTarget(rel); // What is the stem direction? (up: dir < 0, down: dir > 0, unknown: 0) int dir = stem.computeDirection(); if (dir == 0) { if (stem.isVip()) { logger.info("VIP deleting {} with no correct head on either end", stem); } stem.delete(); modifs++; continue; } // Side is normal? HorizontalSide headSide = rel.getHeadSide(); if (((headSide == LEFT) && (dir > 0)) || ((headSide == RIGHT) && (dir < 0))) { continue; // It's OK } // Pitch of the note head int pitch = ((HeadInter) head).getIntegerPitch(); // Target side and target pitches of other head // Look for presence of head on other side with target pitch HorizontalSide targetSide = headSide.opposite(); for (int targetPitch = pitch - 1; targetPitch <= (pitch + 1); targetPitch++) { if (stem.lookupHead(targetSide, targetPitch) != null) { continue RelsLoop; } } // We have a bad head+stem couple, so let's remove the relationship if (head.isVip() || logger.isDebugEnabled()) { logger.info("VIP wrong side for {} on {}", head, stem); } sig.removeEdge(rel); sig.insertExclusion(head, stem, Exclusion.Cause.INCOMPATIBLE); modifs++; } return modifs; } // checkHeads // /** * Perform checks on heads. * * @return the count of modifications done */ private int checkHeads () { int modifs = 0; final List<Inter> heads = sig.inters(ShapeSet.NoteHeads.getShapes()); for (Inter head : heads) { // Check if the head has a stem relation if (!sig.hasRelation(head, HeadStemRelation.class)) { if (head.isVip() || logger.isDebugEnabled()) { logger.info("VIP no stem for {}", head); } head.delete(); modifs++; continue; } // Check head location relative to stem modifs += checkHeadSide(head); } return modifs; } // checkHooks // /** * Perform checks on hooks. * * @return the count of modifications done */ private int checkHooks () { int modifs = 0; final List<Inter> inters = sig.inters(BeamHookInter.class); for (Inter inter : inters) { // Check if the hook has a stem relation if (!sig.hasRelation(inter, BeamStemRelation.class)) { if (inter.isVip() || logger.isDebugEnabled()) { logger.info("VIP no stem for {}", inter); } inter.delete(); } } return modifs; } // checkIsolatedAlters // /** * Perform checks on isolated alterations. * <p> * They are discarded is there is no relation with a nearby head (or turn sign?). * TODO: rework this when stand-alone key signatures are supported. * * @return the count of modifications done */ private int checkIsolatedAlters () { int modifs = 0; final List<Inter> alters = sig.inters(ShapeSet.Alterations.getShapes()); for (Inter inter : alters) { if (inter instanceof KeyAlterInter) { continue; // Don't consider alters within a key-sig } final AlterInter alter = (AlterInter) inter; // Check whether the alter is connected to a note head if (!sig.hasRelation(alter, AlterHeadRelation.class)) { if (alter.isVip() || logger.isDebugEnabled()) { logger.info("VIP deleting {} lacking note head", alter); } alter.delete(); modifs++; } } return modifs; } // checkLedgers // /** * Perform checks on ledger. * * @return the count of modifications done */ private int checkLedgers () { // All system note heads, sorted by abscissa List<Inter> allHeads = sig.inters( ShapeSet.shapesOf(ShapeSet.NoteHeads.getShapes(), ShapeSet.StemLessHeads.getShapes())); Collections.sort(allHeads, Inter.byAbscissa); final List<LedgerInter> toDelete = new ArrayList<LedgerInter>(); boolean modified; do { modified = false; for (Staff staff : system.getStaves()) { SortedMap<Integer, List<LedgerInter>> map = staff.getLedgerMap(); for (Entry<Integer, List<LedgerInter>> entry : map.entrySet()) { int index = entry.getKey(); List<LedgerInter> ledgers = entry.getValue(); List<LedgerInter> toRemove = new ArrayList<LedgerInter>(); for (LedgerInter ledger : ledgers) { if (!ledgerHasHeadOrLedger(staff, index, ledger, allHeads)) { if (ledger.isVip() || logger.isDebugEnabled()) { logger.info("VIP deleting orphan ledger {}", ledger); } toDelete.add(ledger); toRemove.add(ledger); modified = true; } } if (!toRemove.isEmpty()) { ledgers.removeAll(toRemove); } } } } while (modified); if (!toDelete.isEmpty()) { for (LedgerInter ledger : toDelete) { ledger.delete(); // This updates the ledgerMap in relevant staves } } return toDelete.size(); } // checkSlurOnTuplet // /** * Detect and remove a small slur around a tuplet sign. * * @return the slurs removed */ private Set<Inter> checkSlurOnTuplet () { Set<Inter> deleted = new LinkedHashSet<Inter>(); final int maxSlurWidth = scale.toPixels(constants.maxTupletSlurWidth); final List<Inter> slurs = sig.inters( new Predicate<Inter>() { @Override public boolean check (Inter inter) { return !inter.isDeleted() && (inter instanceof SlurInter) && (inter.getBounds().width <= maxSlurWidth); } }); final List<Inter> tuplets = sig.inters( new Predicate<Inter>() { @Override public boolean check (Inter inter) { return !inter.isDeleted() && (inter instanceof TupletInter) && (inter.isContextuallyGood()); } }); for (Inter slurInter : slurs) { final SlurInter slur = (SlurInter) slurInter; // Look for a tuplet sign embraced final int above = slur.isAbove() ? 1 : (-1); Rectangle box = slur.getBounds(); box.translate(0, above * box.height); for (Inter tuplet : tuplets) { if (box.intersects(tuplet.getBounds())) { if (slur.isVip() || logger.isDebugEnabled()) { logger.info("VIP deleting tuplet-slur {}", slur); } slur.delete(); deleted.add(slur); break; } } } return deleted; } // checkStemEndingHeads // /** * Perform checks on correct side for ending heads of stems. * * @return the count of modifications done */ private int checkStemEndingHeads () { int modifs = 0; final List<Inter> stems = sig.inters(Shape.STEM); for (Inter inter : stems) { final StemInter stem = (StemInter) inter; // Cut links to ending heads on wrong stem side if (pruneStemHeads(stem)) { modifs++; } } return modifs; } // checkStems // /** * Perform checks on stems. * * @return the count of modifications done */ private int checkStems () { int modifs = 0; final List<Inter> stems = sig.inters(Shape.STEM); for (Inter inter : stems) { final StemInter stem = (StemInter) inter; if (!stemHasHeadAtEnd(stem)) { if (stem.isVip() || logger.isDebugEnabled()) { logger.info("VIP deleting stem lacking starting head {}", stem); } stem.delete(); modifs++; continue; } if (!stemHasSingleHeadEnd(stem)) { modifs++; } } return modifs; } // checkTimeNumbers // /** * Perform checks on time numbers. * * @return the count of modifications done */ private int checkTimeNumbers () { int modifs = 0; final List<Inter> numbers = sig.inters(TimeNumberInter.class); for (Inter inter : numbers) { final TimeNumberInter number = (TimeNumberInter) inter; // Check this number has a sibling number if (!sig.hasRelation(number, TimeTopBottomRelation.class)) { if (number.isVip() || logger.isDebugEnabled()) { logger.info("VIP deleting time number lacking sibling {}", number); } number.delete(); modifs++; } } return modifs; } // checkTimeSignatures // /** * Perform checks on time signatures. * <p> * Check there is no note between measure start and time signature, otherwise insert exclusion. */ private void checkTimeSignatures () { List<Inter> systemNotes = sig.inters(AbstractNoteInter.class); if (systemNotes.isEmpty()) { return; } final List<Inter> systemTimes = sig.inters(AbstractTimeInter.class); Collections.sort(systemNotes, Inter.byAbscissa); for (Staff staff : system.getStaves()) { List<Inter> staffTimes = SIGraph.inters(staff, systemTimes); if (staffTimes.isEmpty()) { continue; } List<Inter> notes = SIGraph.inters(staff, systemNotes); for (Inter inter : staffTimes) { AbstractTimeInter timeSig = (AbstractTimeInter) inter; // Position WRT Notes in staff int notePrev = -2 - Collections.binarySearch(notes, timeSig, Inter.byAbscissa); if (notePrev != -1) { // Position WRT Bars in staff List<BarlineInter> bars = staff.getBars(); int barPrev = -2 - Collections.binarySearch( bars, timeSig, Inter.byAbscissa); int xMin = (barPrev != -1) ? bars.get(barPrev).getCenter().x : 0; for (int i = notePrev; i >= 0; i Inter note = notes.get(i); if (note.getCenter().x < xMin) { break; } if (timeSig.isVip() || note.isVip() || logger.isDebugEnabled()) { logger.info("VIP {} preceding {}", note, timeSig); } sig.insertExclusion(note, timeSig, Exclusion.Cause.INCOMPATIBLE); } } } } } // compatible // /** * Check whether the two provided Inter instance can overlap. * * @param inters array of exactly 2 instances * @return true if overlap is accepted, false otherwise */ private static boolean compatible (Inter[] inters) { for (int i = 0; i <= 1; i++) { Inter inter = inters[i]; Inter other = inters[1 - i]; if (inter instanceof AbstractBeamInter) { if (other instanceof AbstractBeamInter) { return true; } if (beamCompShapes.contains(other.getShape())) { return true; } } else if (inter instanceof SlurInter) { if (slurCompShapes.contains(other.getShape())) { return true; } } else if (inter instanceof StemInter) { if (stemCompShapes.contains(other.getShape())) { return true; } } } return false; } // detectOverlaps // /** * Detect all cases where 2 Inters actually overlap and, if there is no support * relation between them, insert a mutual exclusion. * <p> * This method is key! * * @param inters the collection of inters to process */ private void detectOverlaps (List<Inter> inters, Adapter adapter) { Collections.sort(inters, Inter.byAbscissa); NextLeft: for (int i = 0, iBreak = inters.size() - 1; i < iBreak; i++) { Inter left = inters.get(i); if (left.isDeleted()) { continue; } final Rectangle leftBox = left.getBounds(); Set<Inter> mirrors = null; final Inter leftMirror = left.getMirror(); if (leftMirror != null) { mirrors = new LinkedHashSet<Inter>(); mirrors.add(leftMirror); if (left.getEnsemble() != null) { AbstractChordInter leftChord = (AbstractChordInter) left.getEnsemble(); Inter leftChordMirror = leftChord.getMirror(); if (leftChordMirror != null) { mirrors.add(leftChordMirror); mirrors.addAll(((AbstractChordInter) leftChordMirror).getNotes()); } } else if (leftMirror instanceof AbstractChordInter) { mirrors.addAll(((AbstractChordInter) leftMirror).getNotes()); } } final double xMax = leftBox.getMaxX(); for (Inter right : inters.subList(i + 1, inters.size())) { if (right.isDeleted()) { continue; } // Mirror entities do not exclude one another if ((mirrors != null) && mirrors.contains(right)) { continue; } // Overlap is accepted in some cases if (compatible(new Inter[]{left, right})) { continue; } Rectangle rightBox = right.getBounds(); if (leftBox.intersects(rightBox)) { // Have a more precise look if (left.isVip() && right.isVip()) { ///logger.info("VIP check overlap {} vs {}", left, right); } try { if (left.overlaps(right) && right.overlaps(left)) { // Specific case: Word vs "string" Symbol if (left instanceof WordInter && right instanceof StringSymbolInter) { if (wordMatchesSymbol((WordInter) left, (StringSymbolInter) right)) { left.decrease(0.5); } } else if (left instanceof StringSymbolInter && right instanceof WordInter) { if (wordMatchesSymbol((WordInter) right, (StringSymbolInter) left)) { right.decrease(0.5); } } exclude(left, right); } } catch (DeletedInterException diex) { if (diex.inter == left) { continue NextLeft; } } } else if (rightBox.x > xMax) { break; // Since inters list is sorted by abscissa } } } } // exclude // /** * Insert exclusion between (the members of) the 2 sets. * * @param set1 one set * @param set2 the other set */ private void exclude (Set<Inter> set1, Set<Inter> set2) { for (Inter i1 : set1) { for (Inter i2 : set2) { sig.insertExclusion(i1, i2, Exclusion.Cause.INCOMPATIBLE); } } } // exclude // private void exclude (Inter left, Inter right) { // Special overlap case between a stem and a standard-size note head if ((left instanceof StemInter && right instanceof HeadInter && !right.getShape().isSmall()) || (right instanceof StemInter && left instanceof HeadInter && !left.getShape().isSmall())) { return; } // If there is no support between left & right, insert an exclusion final SIGraph leftSig = left.getSig(); if (leftSig.noSupport(left, right)) { leftSig.insertExclusion(left, right, Exclusion.Cause.OVERLAP); } } // getHeadersInters // /** * Collect inters that belong to staff headers in this system. * * @return the headers inters */ private List<Inter> getHeadersInters () { List<Inter> inters = new ArrayList<Inter>(); for (Staff staff : system.getStaves()) { StaffHeader header = staff.getHeader(); if (header.clef != null) { inters.add(header.clef); } if (header.key != null) { inters.add(header.key); inters.addAll(header.key.getMembers()); } if (header.time != null) { inters.add(header.time); if (header.time instanceof InterEnsemble) { inters.addAll(((InterEnsemble) header.time).getMembers()); } } } logger.debug("S#{} headers inters: {}", system.getId(), inters); return inters; } // ledgerHasHeadOrLedger // /** * Check if the provided ledger has either a note head centered on it * (or one step further) or another ledger just further. * * @param staff the containing staff * @param index the ledger line index * @param ledger the ledger to check * @param allHeads the abscissa-ordered list of heads in the system * @return true if OK */ private boolean ledgerHasHeadOrLedger (Staff staff, int index, LedgerInter ledger, List<Inter> allHeads) { Rectangle ledgerBox = new Rectangle(ledger.getBounds()); ledgerBox.grow(0, scale.getInterline()); // Very high box, but that's OK // Check for another ledger on next line int nextIndex = index + Integer.signum(index); List<LedgerInter> nextLedgers = staff.getLedgers(nextIndex); if (nextLedgers != null) { for (LedgerInter nextLedger : nextLedgers) { // Check abscissa compatibility if (GeoUtil.xOverlap(ledgerBox, nextLedger.getBounds()) > 0) { return true; } } } // Else, check for a note centered on ledger, or just on next pitch final int ledgerPitch = Staff.getLedgerPitchPosition(index); final int nextPitch = ledgerPitch + Integer.signum(index); final List<Inter> heads = sig.intersectedInters(allHeads, GeoOrder.BY_ABSCISSA, ledgerBox); for (Inter inter : heads) { final HeadInter head = (HeadInter) inter; final int notePitch = head.getIntegerPitch(); if ((notePitch == ledgerPitch) || (notePitch == nextPitch)) { return true; } } return false; } // pruneStemHeads // /** * Cut links between the provided stem and its ending head(s) on wrong side. * * @param stem the stem to process * @return true if one or several heads were pruned from the stem */ private boolean pruneStemHeads (StemInter stem) { if (stem.isVip()) { // logger.info("VIP pruneStemHeads for {}", stem); } final Set<Relation> links = sig.getRelations(stem, HeadStemRelation.class); int modifs = 0; boolean modified; StemGeometryScan: do { modified = false; final Line2D stemLine = stem.computeExtendedLine(); // Update geometry for (Relation rel : links) { // Retrieve the stem portion for this Head -> Stem link HeadInter head = (HeadInter) sig.getEdgeSource(rel); HeadStemRelation link = (HeadStemRelation) rel; StemPortion portion = link.getStemPortion(head, stemLine, scale); HorizontalSide headSide = link.getHeadSide(); if (((portion == STEM_BOTTOM) && (headSide != RIGHT)) || ((portion == STEM_TOP) && (headSide != LEFT))) { sig.removeEdge(rel); links.remove(rel); modifs++; modified = true; if (stem.isVip() || head.isVip() || logger.isDebugEnabled()) { logger.info("VIP pruned {} from {}", head, stem); } continue StemGeometryScan; } } } while (modified); return modifs > 0; } // reduce // /** * Reduce all the interpretations and relations of the SIG. * * @return the collection of removed inters */ private Set<Inter> reduce (Adapter adapter) { final Set<Inter> allRemoved = new LinkedHashSet<Inter>(); logger.debug("S#{} reducing sig ...", system.getId()); // General exclusions based on overlap List<Inter> inters = sig.inters(overlapPredicate); inters.removeAll(getHeadersInters()); detectOverlaps(inters, adapter); // Inters that conflict with frozen inters must be deleted adapter.checkFrozens(); // Make sure all inters have their contextual grade up-to-date sig.contextualize(); adapter.prolog(); Set<Inter> reduced = new LinkedHashSet<Inter>(); // Reduced inters Set<Inter> deleted = new LinkedHashSet<Inter>(); // Deleted inters do { reduced.clear(); deleted.clear(); // First, remove all inters with too low contextual grade deleted.addAll(updateAndPurge()); deleted.addAll(adapter.checkSlurs()); allRemoved.addAll(deleted); int modifs; // modifications done in current iteration while ((modifs = adapter.checkConsistencies()) > 0) { logger.debug("S#{} modifs: {}", system.getId(), modifs); } // Remaining exclusions reduced.addAll(sig.reduceExclusions()); allRemoved.addAll(reduced); logger.debug("S#{} reductions: {}", system.getId(), reduced); } while (!reduced.isEmpty() || !deleted.isEmpty()); return allRemoved; } // reduceAugmentations // /** * Reduce the number of augmentation relations to one. * * @param rels the augmentation links for the same entity * @return the number of relation deleted */ private int reduceAugmentations (Set<Relation> rels) { int modifs = 0; // Simply select the relation with best grade double bestGrade = 0; AbstractConnection bestLink = null; for (Relation rel : rels) { AbstractConnection link = (AbstractConnection) rel; double grade = link.getGrade(); if (grade > bestGrade) { bestGrade = grade; bestLink = link; } } for (Relation rel : rels) { if (rel != bestLink) { sig.removeEdge(rel); modifs++; } } return modifs; } // stemHasHeadAtEnd // /** * Check if the stem has at least a head at some end. * * @param stem the stem inter * @return true if OK */ private boolean stemHasHeadAtEnd (StemInter stem) { if (stem.isVip()) { // logger.info("VIP stemHasHeadAtEnd for {}", stem); } final Line2D stemLine = stem.computeExtendedLine(); for (Relation rel : sig.getRelations(stem, HeadStemRelation.class)) { // Check stem portion HeadStemRelation hsRel = (HeadStemRelation) rel; Inter head = sig.getOppositeInter(stem, rel); if (hsRel.getStemPortion(head, stemLine, scale) != STEM_MIDDLE) { return true; } } return false; } // stemHasSingleHeadEnd // /** * Check if the stem does not have heads at both ends. * <p> * If heads are found at the "tail side" of the stem, their relations to the stem are removed. * * @param stem the stem inter * @return true if OK */ private boolean stemHasSingleHeadEnd (StemInter stem) { final Line2D stemLine = stem.computeExtendedLine(); final int stemDir = stem.computeDirection(); if (stemDir == 0) { return true; // We cannot decide } final StemPortion forbidden = (stemDir > 0) ? STEM_BOTTOM : STEM_TOP; final List<Relation> toRemove = new ArrayList<Relation>(); for (Relation rel : sig.getRelations(stem, HeadStemRelation.class)) { // Check stem portion HeadStemRelation hsRel = (HeadStemRelation) rel; Inter head = sig.getOppositeInter(stem, rel); StemPortion portion = hsRel.getStemPortion(head, stemLine, scale); if (portion == forbidden) { if (stem.isVip() || logger.isDebugEnabled()) { logger.info( "VIP cutting relation between {} and {}", stem, sig.getEdgeSource(rel)); } toRemove.add(rel); } } if (!toRemove.isEmpty()) { sig.removeAllEdges(toRemove); } return toRemove.isEmpty(); } // updateAndPurge // /** * Update the contextual grade of each Inter in SIG, and remove the weak ones if so * desired. * * @return the set of inters removed */ private Set<Inter> updateAndPurge () { sig.contextualize(); if (purgeWeaks) { return sig.deleteWeakInters(); } return Collections.emptySet(); } // wordMatchesSymbol // /** * Check whether the word and the symbol might represent the same thing, after all. * * @param wordInter text word * @param symbol symbol */ private static boolean wordMatchesSymbol (WordInter wordInter, StringSymbolInter symbol) { logger.debug("Comparing {} and {}", wordInter, symbol); final String symbolString = symbol.getSymbolString(); if (wordInter.getValue().equalsIgnoreCase(symbolString)) { logger.debug("Math found"); //TODO: Perhaps more checks on word/sentence? return true; } return false; } // Adapter // private abstract static class Adapter { Set<Inter> deleted = new LinkedHashSet<Inter>(); Set<Inter> reduced = new LinkedHashSet<Inter>(); public int checkConsistencies () { return 0; // Void by default } public void checkFrozens () { // Void by default } public Set<Inter> checkSlurs () { return Collections.emptySet(); } public void prolog () { // Void by default } } // AdapterForFoundations // private class AdapterForFoundations extends Adapter { @Override public int checkConsistencies () { int modifs = 0; modifs += checkStemEndingHeads(); deleted.addAll(updateAndPurge()); modifs += checkHeads(); deleted.addAll(updateAndPurge()); modifs += checkHooks(); deleted.addAll(updateAndPurge()); modifs += checkBeams(); deleted.addAll(updateAndPurge()); modifs += checkLedgers(); deleted.addAll(updateAndPurge()); modifs += checkStems(); deleted.addAll(updateAndPurge()); return modifs; } @Override public void prolog () { analyzeHeadStems(); // Check there is at most one stem on each side of any head analyzeChords(); // Heads & beams compatibility } } // AdapterForLinks // private class AdapterForLinks extends Adapter { @Override public int checkConsistencies () { int modifs = 0; modifs += checkIsolatedAlters(); deleted.addAll(updateAndPurge()); return modifs; } @Override public void checkFrozens () { analyzeFrozenInters(); } } // AdapterForRhythms // private class AdapterForRhythms extends Adapter { private final SystemBackup systemPoorFrats; private final Class[] classes; public List<Inter> selected; public AdapterForRhythms (SystemBackup systemPoorFrats, Class[] classes) { this.systemPoorFrats = systemPoorFrats; this.classes = classes; } @Override public int checkConsistencies () { int modifs = 0; modifs += checkDoubleAlters(); deleted.addAll(updateAndPurge()); modifs += checkTimeNumbers(); checkTimeSignatures(); deleted.addAll(updateAndPurge()); modifs += checkAugmentationDots(); modifs += checkAugmented(); deleted.addAll(updateAndPurge()); return modifs; } @Override public Set<Inter> checkSlurs () { return checkSlurOnTuplet(); } @Override public void prolog () { // Still needed because of cue beams analyzeChords(); // All inters of selected classes (with all their relations) selected = sig.inters(classes); systemPoorFrats.save(selected); } } // AdapterForSymbols // private class AdapterForSymbols extends Adapter { @Override public int checkConsistencies () { int modifs = 0; modifs += checkDoubleAlters(); deleted.addAll(updateAndPurge()); modifs += checkTimeNumbers(); checkTimeSignatures(); deleted.addAll(updateAndPurge()); modifs += checkAugmentationDots(); modifs += checkAugmented(); deleted.addAll(updateAndPurge()); return modifs; } } // Constants // private static final class Constants extends ConstantSet { private final Scale.Fraction maxTupletSlurWidth = new Scale.Fraction( 3, "Maximum width for slur around tuplet"); } }
// $Id: ChannelTest.java,v 1.4 2006/11/22 20:27:53 vlada Exp $ package org.jgroups.tests; import junit.framework.Test; import junit.framework.TestSuite; import org.jgroups.Channel; import org.jgroups.ChannelClosedException; import org.jgroups.ChannelException; import org.jgroups.ChannelNotConnectedException; import org.jgroups.TimeoutException; import org.jgroups.View; /** * Tests various methods in JChannel * @author Bela Ban * @version $Id: ChannelTest.java,v 1.4 2006/11/22 20:27:53 vlada Exp $ */ public class ChannelTest extends ChannelTestBase { Channel ch; private static final String GROUP="DiscardTestGroup"; public void setUp() throws Exception { super.setUp(); ch=createChannel(); ch.connect(GROUP); } public void tearDown() throws Exception { ch.close(); super.tearDown(); } public void testBasicOperations() throws Exception { String groupName = GROUP; Channel c1 = createChannel("A"); c1.connect(groupName); sleepThread(1000); assertTrue(c1.isOpen()); assertTrue(c1.isConnected()); assertNotNull(c1.getLocalAddress()); assertNotNull(c1.getView()); assertTrue(c1.getView().getMembers().contains(c1.getLocalAddress())); try{ c1.connect(groupName); } catch (Exception e) { fail("Should have NOT generated exception"); } c1.disconnect(); assertFalse(c1.isConnected()); assertTrue(c1.isOpen()); assertNull(c1.getLocalAddress()); assertNull(c1.getView()); assertNull(c1.getClusterName()); try{ c1.connect(groupName); } catch (Exception e) { fail("Should have NOT generated exception"); } c1.close(); try{ c1.connect(groupName); fail("Should generated exception, and it has NOT"); } catch (Exception e) { assertTrue(e instanceof ChannelClosedException); } assertFalse(c1.isConnected()); assertFalse(c1.isOpen()); assertNull(c1.getLocalAddress()); assertNull(c1.getView()); assertNull(c1.getClusterName()); c1 = createChannel("A"); c1.connect(groupName); Channel c2 = createChannel("A"); c2.connect(groupName); sleepThread(1000); assertTrue(c1.isOpen()); assertTrue(c1.isConnected()); assertNotNull(c1.getLocalAddress()); assertNotNull(c1.getView()); assertTrue(c1.getView().getMembers().contains(c1.getLocalAddress())); assertTrue(c1.getView().getMembers().contains(c2.getLocalAddress())); assertTrue(c2.isOpen()); assertTrue(c2.isConnected()); assertNotNull(c2.getLocalAddress()); assertNotNull(c2.getView()); assertTrue(c2.getView().getMembers().contains(c2.getLocalAddress())); assertTrue(c2.getView().getMembers().contains(c1.getLocalAddress())); c2.close(); sleepThread(1000); assertFalse(c2.isOpen()); assertFalse(c2.isConnected()); assertNull(c2.getLocalAddress()); assertNull(c2.getView()); assertTrue(c1.isOpen()); assertTrue(c1.isConnected()); assertNotNull(c1.getLocalAddress()); assertNotNull(c1.getView()); assertTrue(c1.getView().getMembers().contains(c1.getLocalAddress())); assertFalse(c1.getView().getMembers().contains(c2.getLocalAddress())); c1.close(); } public void testFirstView() throws Exception { Object obj=ch.receive(5000); if(!(obj instanceof View)) { fail("first object returned needs to be a View (was " + obj + ")"); } else { System.out.println("view is " + obj); } } public void testReceiveTimeout() throws ChannelException, TimeoutException { ch.receive(1000); // this one works, because we're expecting a View // .. but this one doesn't (no msg available) - needs to throw a TimeoutException try { ch.receive(2000); } catch(ChannelNotConnectedException e) { fail("channel should be connected"); } catch(ChannelClosedException e) { fail("channel should not be closed"); } catch(TimeoutException e) { System.out.println("caught a TimeoutException - this is the expected behavior"); } } public void testNullMessage() throws ChannelClosedException, ChannelNotConnectedException { try { ch.send(null); fail("null message should throw an exception - we should not get here"); } catch(NullPointerException e) { System.out.println("caught NullPointerException - this is expected"); } } public static Test suite() { TestSuite s=new TestSuite(ChannelTest.class); return s; } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } }
package Transportation; import javax.swing.JLabel; import javax.swing.JPanel; import Person.Role.Role; import interfaces.GuiPanel; /** An animation panel for bus stops. * * @author Team29 * */ public class BusStopAnimationPanel extends JPanel implements GuiPanel{ public BusStopAnimationPanel() { this.add(new JLabel("BusStopAnimationPanel!!!!!!!!!!!!!")); } @Override public void addGuiForRole(Role r) { // TODO Auto-generated method stub } @Override public void removeGuiForRole(Role r) { // TODO Auto-generated method stub } }
package algorithms.compGeometry; import algorithms.compGeometry.convexHull.GrahamScan; import algorithms.compGeometry.convexHull.GrahamScanTooFewPointsException; import algorithms.imageProcessing.util.PairIntWithIndex; import algorithms.util.PairInt; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; /** * find the furthest pair between points by finding the upper and lower * convex hull and then compare the distances between upper and lower hull * points. * * @author nichole */ public class FurthestPair { public PairInt[] find(Set<PairInt> points) { int n = points.size(); if (n < 2) { return null; } else if (n == 2) { Iterator<PairInt> iter = points.iterator(); return new PairInt[]{iter.next(), iter.next()}; } float[] x = new float[n]; float[] y = new float[n]; int count = 0; for (PairInt p : points) { x[count] = p.getX(); y[count] = p.getY(); count++; } GrahamScan scan = new GrahamScan(); try { scan.computeHull(x, y); } catch (GrahamScanTooFewPointsException ex) { // this can happen for colinear points reducting sorted size < 3 //Logger.getLogger(FurthestPair.class.getName()).log(Level.SEVERE, null, ex); return findWithBruteForce(points); } float[] xHull = scan.getXHull(); float[] yHull = scan.getYHull(); float maxDistSq = Float.MIN_VALUE; int idx1 = -1; int idx2 = -1; for (int i = 0; i < xHull.length; ++i) { for (int j = (i + 1); j < xHull.length; ++j) { float distSq = distanceSq(xHull[i], yHull[i], xHull[j], yHull[j]); if (distSq > maxDistSq) { maxDistSq = distSq; idx1 = i; idx2 = j; } } } if (idx1 != -1) { PairInt p0 = new PairInt(Math.round(xHull[idx1]), Math.round(yHull[idx1])); PairInt p1 = new PairInt(Math.round(xHull[idx2]), Math.round(yHull[idx2])); return new PairInt[]{p0, p1}; } return null; } int distanceSq(PairIntWithIndex p1, PairIntWithIndex p2) { int dx = p1.getX() - p2.getX(); int dy = p1.getY() - p2.getY(); return (dx*dx + dy*dy); } int distanceSq(PairInt p1, PairInt p2) { int dx = p1.getX() - p2.getX(); int dy = p1.getY() - p2.getY(); return (dx*dx + dy*dy); } float distanceSq(float x1, float y1, float x2, float y2) { float dx = x1 - x2; float dy = y1 - y2; return (dx*dx + dy*dy); } PairInt[] findWithBruteForce(Set<PairInt> points) { if (points.size() < 2) { return null; } float max = Float.MIN_VALUE; PairInt maxP1 = null; PairInt maxP2 = null; List<PairInt> list = new ArrayList<PairInt>(points); for (int i = 0; i < list.size(); ++i) { PairInt p1 = list.get(i); for (int j = (i + 1); j < list.size(); ++j) { PairInt p2 = list.get(j); float d = distanceSq(p1, p2); if (d > max) { max = d; maxP1 = p1; maxP2 = p2; } } } return new PairInt[]{maxP1, maxP2}; } }
package org.helioviewer.jhv.plugins.eveplugin.draw; import java.awt.Rectangle; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.helioviewer.base.interval.Interval; import org.helioviewer.base.logging.Log; import org.helioviewer.jhv.data.datatype.event.JHVEvent; import org.helioviewer.jhv.data.datatype.event.JHVEventHighlightListener; import org.helioviewer.jhv.display.TimeListener; import org.helioviewer.jhv.layers.Layers; import org.helioviewer.jhv.layers.LayersListener; import org.helioviewer.jhv.plugins.eveplugin.base.Range; import org.helioviewer.jhv.plugins.eveplugin.lines.data.BandController; import org.helioviewer.jhv.plugins.eveplugin.lines.data.DownloadController; import org.helioviewer.jhv.plugins.eveplugin.settings.BandType; import org.helioviewer.jhv.plugins.eveplugin.view.chart.ChartConstants; import org.helioviewer.jhv.plugins.eveplugin.view.linedataselector.LineDataSelectorElement; import org.helioviewer.jhv.plugins.eveplugin.view.linedataselector.LineDataSelectorModel; import org.helioviewer.jhv.plugins.eveplugin.view.linedataselector.LineDataSelectorModelListener; import org.helioviewer.viewmodel.view.View; public class DrawController implements LineDataSelectorModelListener, JHVEventHighlightListener, LayersListener, TimeListener, PlotAreaSpaceListener { private static final DrawController instance = new DrawController(); private Interval<Date> selectedInterval = new Interval<Date>(null, null); private Interval<Date> availableInterval = new Interval<Date>(null, null); private final PlotAreaSpace pas; private final List<TimingListener> tListeners; private boolean keepFullValueRange; private Rectangle graphSize; // private Rectangle graphArea; // private Rectangle plotArea; // private Rectangle leftAxisArea; private final List<GraphDimensionListener> gdListeners; private Set<YAxisElement> yAxisSet; private final Map<DrawableType, Set<DrawableElement>> drawableElements; private final List<DrawControllerListener> listeners; // private final Map<YAxisElement, String> axisUnitMap; private DrawController() { drawableElements = new HashMap<DrawableType, Set<DrawableElement>>(); listeners = new ArrayList<DrawControllerListener>(); yAxisSet = new HashSet<YAxisElement>(); tListeners = new ArrayList<TimingListener>(); LineDataSelectorModel.getSingletonInstance().addLineDataSelectorModelListener(this); addDrawControllerListener(LineDataSelectorModel.getSingletonInstance()); keepFullValueRange = false; pas = PlotAreaSpace.getSingletonInstance(); pas.addPlotAreaSpaceListener(this); gdListeners = new ArrayList<GraphDimensionListener>(); graphSize = new Rectangle(); // axisUnitMap = new HashMap<YAxisElement, String>(); } public static DrawController getSingletonInstance() { return instance; } public void addDrawControllerListener(DrawControllerListener listener) { listeners.add(listener); } public void removeDrawControllerListener(DrawControllerListener listener) { listeners.remove(listener); } public void addGraphDimensionListener(GraphDimensionListener l) { gdListeners.add(l); } public void addTimingListener(TimingListener listener) { tListeners.add(listener); } public void updateDrawableElement(DrawableElement drawableElement) { removeDrawableElement(drawableElement, false); this.addDrawableElement(drawableElement, false); if (drawableElement.hasElementsToDraw()) { this.fireRedrawRequest(); } } private void addDrawableElement(DrawableElement element, boolean redraw) { Set<DrawableElement> elements = drawableElements.get(element.getDrawableElementType().getLevel()); if (elements == null) { elements = new HashSet<DrawableElement>(); drawableElements.put(element.getDrawableElementType().getLevel(), elements); } elements.add(element); Set<YAxisElement> tempSet = new HashSet<YAxisElement>(yAxisSet); if (element.getYAxisElement() != null) { tempSet.add(element.getYAxisElement()); yAxisSet = tempSet; } if (redraw) { this.fireRedrawRequest(); } } private void removeDrawableElement(DrawableElement element, boolean redraw) { Set<DrawableElement> elements = drawableElements.get(element.getDrawableElementType().getLevel()); if (elements != null) { elements.remove(element); createYAxisSet(); } if (redraw) { this.fireRedrawRequest(); } } public void removeDrawableElement(DrawableElement element) { removeDrawableElement(element, true); } public Set<YAxisElement> getYAxisElements() { return yAxisSet; } public Map<DrawableType, Set<DrawableElement>> getDrawableElements() { return drawableElements; } public List<DrawableElement> getAllDrawableElements() { Collection<Set<DrawableElement>> allValues = getDrawableElements().values(); ArrayList<DrawableElement> deList = new ArrayList<DrawableElement>(); for (Set<DrawableElement> tempList : allValues) { deList.addAll(tempList); } return deList; } public boolean hasElementsToBeDrawn() { List<DrawableElement> allElements = this.getAllDrawableElements(); return !allElements.isEmpty(); } public boolean getIntervalAvailable() { if (selectedInterval == null) { return false; } else { return selectedInterval.getStart() != null && selectedInterval.getEnd() != null; } } public void setSelectedRange(Range selectedRange) { fireRedrawRequest(); } private void fireRedrawRequest() { for (DrawControllerListener l : listeners) { l.drawRequest(); } } public void setAvailableInterval(final Interval<Date> interval) { availableInterval = makeCompleteDay(interval); // Log.debug("New available interval : " + availableInterval); fireAvailableIntervalChanged(availableInterval); // request data if needed final Calendar calendar = new GregorianCalendar(); calendar.clear(); calendar.setTime(availableInterval.getEnd()); calendar.add(Calendar.DAY_OF_MONTH, -1); final Interval<Date> downloadInterval = new Interval<Date>(availableInterval.getStart(), calendar.getTime()); final BandType[] bandTypes = BandController.getSingletonInstance().getAllAvailableBandTypes(); DownloadController.getSingletonInstance().updateBands(bandTypes, downloadInterval, selectedInterval); // check if selected interval is in available interval and correct it if // needed setSelectedInterval(selectedInterval, false); // PlotTimeSpace.getInstance().setSelectedMinAndMaxTime(interval.getStart(), // interval.getEnd()); } public final Interval<Date> getAvailableInterval() { return availableInterval; } @Override public void downloadStartded(LineDataSelectorElement element) { } @Override public void downloadFinished(LineDataSelectorElement element) { } @Override public void lineDataAdded(LineDataSelectorElement element) { } @Override public void lineDataRemoved(LineDataSelectorElement element) { fireRedrawRequest(); } @Override public void lineDataUpdated(LineDataSelectorElement element) { fireRedrawRequest(); } private void fireRedrawRequestMovieFrameChanged(final Date time) { for (DrawControllerListener l : listeners) { l.drawMovieLineRequest(time); } } @Override public void timeChanged(Date date) { fireRedrawRequestMovieFrameChanged(date); } public Date getLastDateWithData() { Date lastDate = null; Date tempLastDate = null; for (Set<DrawableElement> des : drawableElements.values()) { for (DrawableElement de : des) { if (de.getLastDateWithData() != null) { if (tempLastDate == null || de.getLastDateWithData().before(tempLastDate)) { tempLastDate = de.getLastDateWithData(); } } } } if (tempLastDate != null) { if (lastDate == null || lastDate.before(tempLastDate)) { lastDate = tempLastDate; } } return lastDate; } @Override public void eventHightChanged(JHVEvent event) { fireRedrawRequest(); } @Override public void layerAdded(View view) { final Interval<Date> interval = new Interval<Date>(Layers.getFirstDate(), Layers.getLastDate()); if (availableInterval == null || availableInterval.getStart() == null || availableInterval.getEnd() == null) { availableInterval = interval; } else { Date start = availableInterval.getStart(); if (interval.getStart().before(start)) { start = interval.getStart(); } Date end = availableInterval.getEnd(); if (interval.getEnd().after(end)) { end = interval.getEnd(); } setAvailableInterval(new Interval<Date>(start, end)); } } @Override public void activeLayerChanged(View view) { if (view == null) { fireRedrawRequestMovieFrameChanged(null); } } private Interval<Date> makeCompleteDay(final Interval<Date> interval) { return makeCompleteDay(interval.getStart(), interval.getEnd()); } private Interval<Date> makeCompleteDay(final Date start, final Date end) { final Interval<Date> interval = new Interval<Date>(null, null); Date endDate = end; if (start == null || end == null) { return interval; } if (end.getTime() > System.currentTimeMillis()) { endDate = new Date(); } final Calendar calendar = new GregorianCalendar(); calendar.clear(); calendar.setTime(start); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); interval.setStart(calendar.getTime()); calendar.clear(); calendar.setTime(endDate); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); calendar.add(Calendar.DAY_OF_MONTH, 1); interval.setEnd(calendar.getTime()); return interval; } public Interval<Date> setSelectedInterval(final Interval<Date> newSelectedInterval, boolean useFullValueSpace) { return setSelectedInterval(newSelectedInterval, useFullValueSpace, true); } private Interval<Date> setSelectedInterval(final Interval<Date> newSelectedInterval, boolean useFullValueSpace, boolean updatePlotAreaSpace) { keepFullValueRange = useFullValueSpace; if (availableInterval.getStart() == null || availableInterval.getEnd() == null) { selectedInterval = new Interval<Date>(null, null); } else if (newSelectedInterval.getStart() == null || newSelectedInterval.getEnd() == null) { selectedInterval = availableInterval; } else if (newSelectedInterval.getStart().before(newSelectedInterval.getEnd())) { if (availableInterval.containsInclusive(newSelectedInterval)) { selectedInterval = newSelectedInterval; } else { Date start = newSelectedInterval.getStart(); Date end = newSelectedInterval.getEnd(); // start = availableInterval.containsPointInclusive(start) ? // start : availableInterval.getStart(); // end = availableInterval.containsPointInclusive(end) ? end : // availableInterval.getEnd(); Date availableStart = availableInterval.getStart(); Date availableEnd = availableInterval.getEnd(); boolean changeAvailableInterval = false; if (!availableInterval.containsPointInclusive(start) && !availableInterval.containsPointInclusive(end)) { changeAvailableInterval = true; availableStart = start; availableEnd = end; } if (start.equals(end)) { selectedInterval = new Interval<Date>(availableStart, availableEnd); } else { selectedInterval = new Interval<Date>(start, end); } if (changeAvailableInterval) { setAvailableInterval(new Interval<Date>(availableStart, availableEnd)); } } if (updatePlotAreaSpace) { updatePlotAreaSpace(selectedInterval); } fireSelectedIntervalChanged(); fireRedrawRequest(); } else { Log.debug("Start was after end. Set by: "); Thread.dumpStack(); } return selectedInterval; } public Interval<Date> getSelectedInterval() { return selectedInterval; } private void fireSelectedIntervalChanged() { for (TimingListener listener : tListeners) { listener.selectedIntervalChanged(); } } private void updatePlotAreaSpace(Interval<Date> selectedInterval) { if (availableInterval != null && availableInterval.getStart() != null && availableInterval.getEnd() != null && selectedInterval != null && selectedInterval.getStart() != null && selectedInterval.getEnd() != null) { long diffAvailable = availableInterval.getEnd().getTime() - availableInterval.getStart().getTime(); double diffPlotAreaTime = pas.getScaledMaxTime() - pas.getScaledMinTime(); double scaledSelectedStart = pas.getScaledMinTime() + (1.0 * (selectedInterval.getStart().getTime() - availableInterval.getStart().getTime()) * diffPlotAreaTime / diffAvailable); double scaledSelectedEnd = pas.getScaledMinTime() + (1.0 * (selectedInterval.getEnd().getTime() - availableInterval.getStart().getTime()) * diffPlotAreaTime / diffAvailable); pas.setScaledSelectedTimeAndValue(scaledSelectedStart, scaledSelectedEnd, pas.getScaledMinValue(), pas.getScaledMaxValue()); } } private void fireAvailableIntervalChanged(final Interval<Date> newInterval) { for (TimingListener listener : tListeners) { listener.availableIntervalChanged(); } } @Override public void plotAreaSpaceChanged(double scaledMinValue, double scaledMaxValue, double scaledMinTime, double scaledMaxTime, double scaledSelectedMinValue, double scaledSelectedMaxValue, double scaledSelectedMinTime, double scaledSelectedMaxTime, boolean forced) { if (availableInterval.getStart() != null && availableInterval.getEnd() != null && selectedInterval.getStart() != null && selectedInterval.getEnd() != null) { long diffTime = availableInterval.getEnd().getTime() - availableInterval.getStart().getTime(); double scaleDiff = scaledMaxTime - scaledMinTime; double selectedMin = (scaledSelectedMinTime - scaledMinTime) / scaleDiff; double selectedMax = (scaledSelectedMaxTime - scaledMinTime) / scaleDiff; Date newSelectedStartTime = new Date(availableInterval.getStart().getTime() + Math.round(diffTime * selectedMin)); Date newSelectedEndTime = new Date(availableInterval.getStart().getTime() + Math.round(diffTime * selectedMax)); // Log.info("plotareachanged starttime: " + newSelectedStartTime // + " endtime: " + newSelectedEndTime); if (forced || !(newSelectedEndTime.equals(selectedInterval.getEnd()) && newSelectedStartTime.equals(selectedInterval.getStart()))) { setSelectedInterval(new Interval<Date>(newSelectedStartTime, newSelectedEndTime), false, false); } } } @Override public void availablePlotAreaSpaceChanged(double oldMinValue, double oldMaxValue, double oldMinTime, double oldMaxTime, double newMinValue, double newMaxValue, double newMinTime, double newMaxTime) { if (availableInterval != null && availableInterval.getStart() != null && availableInterval.getEnd() != null && (oldMinTime > newMinTime || oldMaxTime < newMaxTime)) { double timeRatio = (availableInterval.getEnd().getTime() - availableInterval.getStart().getTime()) / (oldMaxTime - oldMinTime); double startDifference = oldMinTime - newMinTime; double endDifference = newMaxTime - oldMaxTime; Date tempStartDate = new Date(availableInterval.getStart().getTime() - Math.round(startDifference * timeRatio)); Date tempEndDate = new Date(availableInterval.getEnd().getTime() + Math.round(endDifference * timeRatio)); setAvailableInterval(new Interval<Date>(tempStartDate, tempEndDate)); } } public boolean keepfullValueRange() { return keepFullValueRange; } public PlotAreaSpace getPlotAreaSpace() { return pas; } public void setGraphInformation(Rectangle graphSize) { this.graphSize = graphSize; fireGraphDimensionsChanged(); fireRedrawRequest(); } private void fireGraphDimensionsChanged() { for (GraphDimensionListener l : gdListeners) { l.graphDimensionChanged(); } } public Rectangle getPlotArea() { return new Rectangle(0, 0, getGraphWidth(), getGraphHeight()); } public Rectangle getGraphArea() { return new Rectangle(ChartConstants.getGraphLeftSpace(), ChartConstants.getGraphTopSpace(), getGraphWidth(), getGraphHeight()); } public Rectangle getLeftAxisArea() { return new Rectangle(0, ChartConstants.getGraphTopSpace(), ChartConstants.getGraphLeftSpace(), getGraphHeight() - (ChartConstants.getGraphTopSpace() + ChartConstants.getGraphBottomSpace())); } private int getGraphHeight() { return graphSize.height - (ChartConstants.getGraphTopSpace() + ChartConstants.getGraphBottomSpace()); } private int getGraphWidth() { int twoYAxis = 0; if (getYAxisElements().size() >= 2) { twoYAxis = 1; } return graphSize.width - (ChartConstants.getGraphLeftSpace() + ChartConstants.getGraphRightSpace() + twoYAxis * ChartConstants.getTwoAxisGraphRight()); } private void createYAxisSet() { Set<YAxisElement> tempSet = new HashSet<YAxisElement>(); for (Set<DrawableElement> elementsSet : drawableElements.values()) { for (DrawableElement de : elementsSet) { if (de.getYAxisElement() != null) { tempSet.add(de.getYAxisElement()); } } } yAxisSet = tempSet; } public boolean hasAxisAvailable() { return yAxisSet.size() < 2; } public boolean canBePutOnAxis(String unit) { for (YAxisElement el : yAxisSet) { if (el.getLabel().toLowerCase().equals(unit.toLowerCase())) { return true; } } return false; } public YAxisElement getYAxisElementForUnit(String unit) { for (YAxisElement el : yAxisSet) { if (el.getOriginalLabel().toLowerCase().equals(unit.toLowerCase())) { return el; } } return null; } public List<YAxisElement> getAllYAxisElementsForUnit(String unit) { List<YAxisElement> all = new ArrayList<YAxisElement>(); for (YAxisElement el : yAxisSet) { if (el.getOriginalLabel().toLowerCase().equals(unit.toLowerCase())) { all.add(el); } } return all; } public boolean canChangeAxis(String unitLabel) { return getAllYAxisElementsForUnit(unitLabel).size() == 2 || yAxisSet.size() < 2; } }
package org.ringingmaster.engine.parser.assignparse; import org.junit.Test; import org.ringingmaster.engine.NumberOfBells; import org.ringingmaster.engine.notation.NotationBody; import org.ringingmaster.engine.notation.impl.NotationBuilder; import org.ringingmaster.engine.parser.Parse; import org.ringingmaster.engine.touch.ObservableTouch; import org.ringingmaster.engine.touch.TableType; import org.ringingmaster.engine.touch.checkingtype.CheckingType; import static org.ringingmaster.engine.parser.AssertParse.assertParse; import static org.ringingmaster.engine.parser.AssertParse.unparsed; import static org.ringingmaster.engine.parser.AssertParse.valid; import static org.ringingmaster.engine.parser.ParseType.CALL; import static org.ringingmaster.engine.parser.ParseType.DEFINITION; import static org.ringingmaster.engine.parser.ParseType.SPLICE; import static org.ringingmaster.engine.touch.TableType.TOUCH_TABLE; import static org.ringingmaster.engine.touch.checkingtype.CheckingType.COURSE_BASED; import static org.ringingmaster.engine.touch.tableaccess.DefinitionTableAccess.DEFINITION_COLUMN; import static org.ringingmaster.engine.touch.tableaccess.DefinitionTableAccess.SHORTHAND_COLUMN; /** * TODO comments??? * * @author stevelake */ public class AssignParseTypeDEFINITIONTest { @Test public void definitionUnparsedInCallingPoitionArea() { ObservableTouch touch = buildSingleCellTouch(buildPlainBobMinor(), "def1"); touch.setTouchCheckingType(COURSE_BASED); touch.setSpliced(true); Parse parse = new AssignParseType().apply(touch.get()); assertParse(parse.allTouchCells().get(0, 0), unparsed(4)); } @Test public void definitionParsedInMainBody() { ObservableTouch touch = buildSingleCellTouch(buildPlainBobMinor(), "def1"); Parse parse = new AssignParseType().apply(touch.get()); assertParse(parse.allTouchCells().get(0, 0), valid(4, DEFINITION)); } @Test public void definitionParsedInSplice() { ObservableTouch touch = buildSingleCellTouch(buildPlainBobMinor(), "-"); touch.addCharacters(TOUCH_TABLE,0,1,"def1"); touch.setSpliced(true); Parse parse = new AssignParseType().apply(touch.get()); assertParse(parse.allTouchCells().get(0, 1), valid(4, DEFINITION)); } @Test public void correctlyParsesDefinitionTokenInMainBody() { ObservableTouch touch = buildSingleCellTouch(buildPlainBobMinor(), "-def1-"); Parse parse = new AssignParseType().apply(touch.get()); assertParse(parse.allTouchCells().get(0, 0), valid(CALL), valid(4, DEFINITION), valid(CALL)); } @Test public void correctlyParsesDefinitionTokenInSplice() { ObservableTouch touch = buildSingleCellTouch(buildPlainBobMinor(), "-"); touch.setSpliced(true); touch.addCharacters(TOUCH_TABLE, 0, 1, "Pdef1P"); Parse parse = new AssignParseType().apply(touch.get()); assertParse(parse.allTouchCells().get(0, 1), valid(SPLICE), valid(4, DEFINITION), valid(SPLICE)); } @Test public void definitionShorthandsParsedAsDefinitions() { ObservableTouch touch = buildSingleCellTouch(buildPlainBobMinor(), null); touch.addDefinition("def2","s"); Parse parse = new AssignParseType().apply(touch.get()); assertParse(parse.findDefinitionByShorthand("def1").get().get(0, SHORTHAND_COLUMN), valid(4, DEFINITION)); assertParse(parse.findDefinitionByShorthand("def2").get().get(0, SHORTHAND_COLUMN), valid(4, DEFINITION)); } @Test public void unusedDefinitionParsedAsMainBody() { ObservableTouch touch = buildSingleCellTouch(buildPlainBobMinor(), null); Parse parse = new AssignParseType().apply(touch.get()); assertParse(parse.findDefinitionByShorthand("def1").get().get(0, DEFINITION_COLUMN), valid(CALL), unparsed()); } @Test public void definitionUsedInMainBodyAreaParsedAsMainBody() { ObservableTouch touch = buildSingleCellTouch(buildPlainBobMinor(), "def1 def2"); Parse parse = new AssignParseType().apply(touch.get()); assertParse(parse.findDefinitionByShorthand("def1").get().get(0, DEFINITION_COLUMN), valid(CALL), unparsed()); } @Test public void definitionUsedInSpiceAreaParsedAsSpice() { ObservableTouch touch = buildSingleCellTouch(buildPlainBobMinor(), "s"); touch.addCharacters(TOUCH_TABLE, 0,1,"def1 def2"); touch.setSpliced(true); Parse parse = new AssignParseType().apply(touch.get()); assertParse(parse.findDefinitionByShorthand("def1").get().get(0, DEFINITION_COLUMN), unparsed(), valid(SPLICE)); } @Test public void definitionUsedInMainAndSpiceAreaParsedAsMainBody() { ObservableTouch touch = buildSingleCellTouch(buildPlainBobMinor(), "def1"); touch.addCharacters(TOUCH_TABLE, 0,1,"def1"); touch.setSpliced(true); Parse parse = new AssignParseType().apply(touch.get()); assertParse(parse.findDefinitionByShorthand("def1").get().get(0, DEFINITION_COLUMN), valid(CALL), unparsed()); } @Test public void transativeDefinitionInMainBodyParsedAsMainBody() { ObservableTouch touch = buildSingleCellTouch(buildPlainBobMinor(), "def3"); touch.addDefinition("def3", "def2"); touch.addDefinition("def2", "def1"); Parse parse = new AssignParseType().apply(touch.get()); assertParse(parse.findDefinitionByShorthand("def3").get().get(0, DEFINITION_COLUMN), valid(4, DEFINITION)); assertParse(parse.findDefinitionByShorthand("def2").get().get(0, DEFINITION_COLUMN), valid(4, DEFINITION)); assertParse(parse.findDefinitionByShorthand("def1").get().get(0, DEFINITION_COLUMN), valid(CALL), unparsed()); } @Test public void transativeDefinitionInSplicedParsedAsSplice() { ObservableTouch touch = buildSingleCellTouch(buildPlainBobMinor(), "-"); touch.addCharacters(TableType.TOUCH_TABLE,0,1,"def3"); touch.addDefinition("def3", "def2"); touch.addDefinition("def2", "def1"); Parse parse = new AssignParseType().apply(touch.get()); assertParse(parse.findDefinitionByShorthand("def3").get().get(0, DEFINITION_COLUMN), valid(4, DEFINITION)); assertParse(parse.findDefinitionByShorthand("def2").get().get(0, DEFINITION_COLUMN), valid(4, DEFINITION)); assertParse(parse.findDefinitionByShorthand("def1").get().get(0, DEFINITION_COLUMN), unparsed(), valid(SPLICE)); } private NotationBody buildPlainBobMinor() { return NotationBuilder.getInstance() .setNumberOfWorkingBells(NumberOfBells.BELLS_6) .setName("Plain Bob") .setFoldedPalindromeNotationShorthand("x16x16x16", "12") .addCall("Bob", "-", "14", true) .addCall("Single", "s", "1234", false) .addCallInitiationRow(7) .addMethodCallingPosition("W", 7, 1) .addMethodCallingPosition("H", 7, 2) .setSpliceIdentifier("P") .build(); } private ObservableTouch buildSingleCellTouch(NotationBody notationBody, String characters) { ObservableTouch touch = new ObservableTouch(); touch.setNumberOfBells(notationBody.getNumberOfWorkingBells()); if (characters != null) { touch.addCharacters(TOUCH_TABLE, 0, 0, characters); } touch.addNotation(notationBody); touch.setTouchCheckingType(CheckingType.LEAD_BASED); touch.setSpliced(false); touch.addDefinition("def1", "-P"); return touch; } }
package org.cytoscape.browser.internal; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.GroupLayout.ParallelGroup; import javax.swing.GroupLayout.SequentialGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JToggleButton; import javax.swing.JToolBar; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import org.cytoscape.application.CyApplicationManager; import org.cytoscape.browser.internal.util.ColumnResizer; import org.cytoscape.equations.EquationCompiler; import org.cytoscape.model.CyColumn; import org.cytoscape.model.CyEdge; import org.cytoscape.model.CyIdentifiable; import org.cytoscape.model.CyNetwork; import org.cytoscape.model.CyNode; import org.cytoscape.model.CyTable; import org.cytoscape.model.subnetwork.CyRootNetwork; import org.cytoscape.model.subnetwork.CySubNetwork; import org.cytoscape.service.util.CyServiceRegistrar; import org.cytoscape.task.destroy.DeleteTableTaskFactory; import org.cytoscape.util.swing.CheckBoxJList; import org.cytoscape.work.swing.DialogTaskManager; /** * Toolbar for the Browser. All buttons related to this should be placed here. * */ public class AttributeBrowserToolBar extends JPanel implements PopupMenuListener { private static final long serialVersionUID = -508393701912596399L; private BrowserTable browserTable; private BrowserTableModel browserTableModel; private static final Dimension TOOLBAR_SIZE = new Dimension(500, 38); /* GUI components */ private JPopupMenu attributeSelectionPopupMenu; private JScrollPane jScrollPane; private JPopupMenu createColumnMenu; private JToolBar toolBar; private SequentialGroup hToolBarGroup; private ParallelGroup vToolBarGroup; private JButton selectButton; private CheckBoxJList attributeList; private JList attrDeletionList; private JButton createNewAttributeButton; private JButton deleteAttributeButton; private JButton deleteTableButton; private JButton selectAllAttributesButton; private JButton unselectAllAttributesButton; private JButton formulaBuilderButton; // private JButton mapGlobalTableButton; // private final MapGlobalToLocalTableTaskFactory mapGlobalTableTaskFactoryService; private final JComboBox tableChooser; private AttributeListModel attrListModel; private final EquationCompiler compiler; private final DeleteTableTaskFactory deleteTableTaskFactory; private final DialogTaskManager guiTaskMgr; private final JButton selectionModeButton; private final List<JComponent> components; private final Class<? extends CyIdentifiable> objType; private final CyApplicationManager appMgr; public AttributeBrowserToolBar(final CyServiceRegistrar serviceRegistrar, final EquationCompiler compiler, final DeleteTableTaskFactory deleteTableTaskFactory, final DialogTaskManager guiTaskMgr, final JComboBox tableChooser, final Class<? extends CyIdentifiable> objType, final CyApplicationManager appMgr) {//, final MapGlobalToLocalTableTaskFactory mapGlobalTableTaskFactoryService) { this(serviceRegistrar, compiler, deleteTableTaskFactory, guiTaskMgr, tableChooser, new JButton(), objType, appMgr);//, mapGlobalTableTaskFactoryService); this.selectionModeButton.setVisible(false); } public AttributeBrowserToolBar(final CyServiceRegistrar serviceRegistrar, final EquationCompiler compiler, final DeleteTableTaskFactory deleteTableTaskFactory, final DialogTaskManager guiTaskMgr, final JComboBox tableChooser, final JButton selectionModeButton, final Class<? extends CyIdentifiable> objType, final CyApplicationManager appMgr) {// , final MapGlobalToLocalTableTaskFactory mapGlobalTableTaskFactoryService) { this.compiler = compiler; this.selectionModeButton = selectionModeButton; this.appMgr = appMgr; // this.mapGlobalTableTaskFactoryService = mapGlobalTableTaskFactoryService; this.components = new ArrayList<JComponent>(); this.tableChooser = tableChooser; this.deleteTableTaskFactory = deleteTableTaskFactory; this.guiTaskMgr = guiTaskMgr; this.attrListModel = new AttributeListModel(null); this.objType = objType; serviceRegistrar.registerAllServices(attrListModel, new Properties()); selectionModeButton.setEnabled(false); initializeGUI(); } public void setBrowserTable(final BrowserTable browserTable) { this.browserTable = browserTable; if (browserTable != null) { browserTableModel = (BrowserTableModel) browserTable.getModel(); } else { browserTableModel = null; } attrListModel.setBrowserTableModel(browserTableModel); updateEnableState(); } @Override public void popupMenuCanceled(PopupMenuEvent e) { // TODO Auto-generated method stub } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { // Update actual table try { if (attributeList != null) { final Object[] selectedValues = attributeList.getSelectedValues(); final Set<String> visibleAttributes = new HashSet<String>(); for (final Object selectedValue : selectedValues) visibleAttributes.add((String)selectedValue); browserTable.setVisibleAttributeNames(visibleAttributes); } } catch (Exception ex) { attributeList.clearSelection(); } } @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { // Do nothing } public void updateEnableState() { for (final JComponent comp : components) { boolean enabled = browserTableModel != null; if (comp == deleteTableButton /*|| comp == mapGlobalTableButton*/) enabled &= objType == null; comp.setEnabled(enabled); } } protected void addComponent(final JComponent component, final ComponentPlacement placement) { hToolBarGroup.addPreferredGap(placement).addComponent(component); vToolBarGroup.addComponent(component, Alignment.CENTER, GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE); components.add(component); } private void initializeGUI() { setLayout(new BorderLayout()); add(getToolBar(), BorderLayout.CENTER); getAttributeSelectionPopupMenu(); getJPopupMenu(); // Add buttons if (selectionModeButton != null) addComponent(selectionModeButton, ComponentPlacement.RELATED); addComponent(getSelectButton(), ComponentPlacement.UNRELATED); addComponent(getSelectAllButton(), ComponentPlacement.RELATED); addComponent(getUnselectAllButton(), ComponentPlacement.RELATED); addComponent(getNewButton(), ComponentPlacement.UNRELATED); addComponent(getDeleteButton(), ComponentPlacement.RELATED); addComponent(getDeleteTableButton(), ComponentPlacement.RELATED); addComponent(getFunctionBuilderButton(), ComponentPlacement.UNRELATED); // addComponent(getMapGlobalTableButton(). ComponentPlacement.UNRELATED); if (tableChooser != null) addComponent(tableChooser, ComponentPlacement.UNRELATED); } public String getToBeDeletedAttribute() { return attrDeletionList.getSelectedValue().toString(); } /** * This method initializes jPopupMenu * * @return javax.swing.JPopupMenu */ private JPopupMenu getAttributeSelectionPopupMenu() { if (attributeSelectionPopupMenu == null) { attributeSelectionPopupMenu = new JPopupMenu(); attributeSelectionPopupMenu.add(getJScrollPane()); attributeSelectionPopupMenu.addPopupMenuListener(this); } return attributeSelectionPopupMenu; } /** * This method initializes jScrollPane * * @return javax.swing.JScrollPane */ private JScrollPane getJScrollPane() { if (jScrollPane == null) { jScrollPane = new JScrollPane(); jScrollPane.setPreferredSize(new Dimension(250, 200)); jScrollPane.setViewportView(getSelectedAttributeList()); } return jScrollPane; } /** * This method initializes jPopupMenu * * @return javax.swing.JPopupMenu */ private JPopupMenu getJPopupMenu() { if (createColumnMenu == null) { createColumnMenu = new JPopupMenu(); //final JMenu column = new JMenu("New Column"); final JMenu columnRegular = new JMenu("New Single Column"); final JMenu columnList = new JMenu("New List Column"); columnRegular.add(getJMenuItemIntegerAttribute(false)); columnRegular.add(getJMenuItemLongIntegerAttribute(false)); columnRegular.add(getJMenuItemStringAttribute(false)); columnRegular.add(getJMenuItemFloatingPointAttribute(false)); columnRegular.add(getJMenuItemBooleanAttribute(false)); columnList.add(getJMenuItemIntegerListAttribute(false)); columnList.add(getJMenuItemLongIntegerListAttribute(false)); columnList.add(getJMenuItemStringListAttribute(false)); columnList.add(getJMenuItemFloatingPointListAttribute(false)); columnList.add(getJMenuItemBooleanListAttribute(false)); //column.add(columnRegular); //column.add(columnList); createColumnMenu.add(columnRegular); createColumnMenu.add(columnList); /* // This is not valid for Global Table. if (objType != null) { final JMenu shared = new JMenu("New Shared Column"); final JMenu sharedRegular = new JMenu("Single"); final JMenu sharedList = new JMenu("List"); sharedRegular.add(getJMenuItemIntegerAttribute(true)); sharedRegular.add(getJMenuItemLongIntegerAttribute(true)); sharedRegular.add(getJMenuItemStringAttribute(true)); sharedRegular.add(getJMenuItemFloatingPointAttribute(true)); sharedRegular.add(getJMenuItemBooleanAttribute(true)); sharedList.add(getJMenuItemIntegerListAttribute(true)); sharedList.add(getJMenuItemLongIntegerListAttribute(true)); sharedList.add(getJMenuItemStringListAttribute(true)); sharedList.add(getJMenuItemFloatingPointListAttribute(true)); sharedList.add(getJMenuItemBooleanListAttribute(true)); shared.add(sharedRegular); shared.add(sharedList); createColumnMenu.add(shared); } */ } return createColumnMenu; } /** * This method initializes jMenuItemStringAttribute * * @return javax.swing.JMenuItem */ private JMenuItem getJMenuItemStringAttribute(final boolean isShared) { final JMenuItem jMenuItemStringAttribute = new JMenuItem(); jMenuItemStringAttribute.setText("String"); jMenuItemStringAttribute.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createNewAttribute("String", isShared); } }); return jMenuItemStringAttribute; } /** * This method initializes jMenuItemIntegerAttribute * * @return javax.swing.JMenuItem */ private JMenuItem getJMenuItemIntegerAttribute(final boolean isShared) { final JMenuItem jMenuItemIntegerAttribute = new JMenuItem(); jMenuItemIntegerAttribute.setText("Integer"); jMenuItemIntegerAttribute.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createNewAttribute("Integer", isShared); } }); return jMenuItemIntegerAttribute; } /** * This method initializes jMenuItemLongIntegerAttribute * * @return javax.swing.JMenuItem */ private JMenuItem getJMenuItemLongIntegerAttribute(final boolean isShared) { final JMenuItem jMenuItemLongIntegerAttribute = new JMenuItem(); jMenuItemLongIntegerAttribute.setText("Long Integer"); jMenuItemLongIntegerAttribute.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createNewAttribute("Long Integer", isShared); } }); return jMenuItemLongIntegerAttribute; } /** * This method initializes jMenuItemFloatingPointAttribute * * @return javax.swing.JMenuItem */ private JMenuItem getJMenuItemFloatingPointAttribute(final boolean isShared) { final JMenuItem jMenuItemFloatingPointAttribute = new JMenuItem(); jMenuItemFloatingPointAttribute.setText("Floating Point"); jMenuItemFloatingPointAttribute.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createNewAttribute("Floating Point", isShared); } }); return jMenuItemFloatingPointAttribute; } /** * This method initializes jMenuItemBooleanAttribute * * @return javax.swing.JMenuItem */ private JMenuItem getJMenuItemBooleanAttribute(final boolean isShared) { final JMenuItem jMenuItemBooleanAttribute = new JMenuItem(); jMenuItemBooleanAttribute.setText("Boolean"); jMenuItemBooleanAttribute.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createNewAttribute("Boolean", isShared); } }); return jMenuItemBooleanAttribute; } /** * This method initializes jMenuItemStringListAttribute * * @return javax.swing.JMenuItem */ private JMenuItem getJMenuItemStringListAttribute(final boolean isShared) { final JMenuItem jMenuItemStringListAttribute = new JMenuItem(); jMenuItemStringListAttribute.setText("String"); jMenuItemStringListAttribute.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createNewAttribute("String List", isShared); } }); return jMenuItemStringListAttribute; } /** * This method initializes jMenuItemIntegerListAttribute * * @return javax.swing.JMenuItem */ private JMenuItem getJMenuItemIntegerListAttribute(final boolean isShared) { final JMenuItem jMenuItemIntegerListAttribute = new JMenuItem(); jMenuItemIntegerListAttribute.setText("Integer"); jMenuItemIntegerListAttribute.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createNewAttribute("Integer List", isShared); } }); return jMenuItemIntegerListAttribute; } /** * This method initializes jMenuItemLongIntegerListAttribute * * @return javax.swing.JMenuItem */ private JMenuItem getJMenuItemLongIntegerListAttribute(final boolean isShared) { final JMenuItem jMenuItemLongIntegerListAttribute = new JMenuItem(); jMenuItemLongIntegerListAttribute.setText("Long Integer"); jMenuItemLongIntegerListAttribute.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createNewAttribute("Integer List", isShared); } }); return jMenuItemLongIntegerListAttribute; } /** * This method initializes jMenuItemFloatingPointListAttribute * * @return javax.swing.JMenuItem */ private JMenuItem getJMenuItemFloatingPointListAttribute(final boolean isShared) { final JMenuItem jMenuItemFloatingPointListAttribute = new JMenuItem(); jMenuItemFloatingPointListAttribute.setText("Floating Point"); jMenuItemFloatingPointListAttribute.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createNewAttribute("Floating Point List", isShared); } }); return jMenuItemFloatingPointListAttribute; } /** * This method initializes jMenuItemBooleanListAttribute * * @return javax.swing.JMenuItem */ private JMenuItem getJMenuItemBooleanListAttribute(final boolean isShared) { final JMenuItem jMenuItemBooleanListAttribute = new JMenuItem(); jMenuItemBooleanListAttribute.setText("Boolean"); jMenuItemBooleanListAttribute.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createNewAttribute("Boolean List", isShared); } }); return jMenuItemBooleanListAttribute; } /** * This method initializes the toolBar * * @return javax.swing.JToolBar */ private JToolBar getToolBar() { if (toolBar == null) { toolBar = new JToolBar(); toolBar.setMargin(new Insets(0, 0, 3, 0)); toolBar.setPreferredSize(TOOLBAR_SIZE); toolBar.setSize(TOOLBAR_SIZE); toolBar.setFloatable(false); toolBar.setOrientation(JToolBar.HORIZONTAL); final GroupLayout buttonBarLayout = new GroupLayout(toolBar); toolBar.setLayout(buttonBarLayout); hToolBarGroup = buttonBarLayout.createSequentialGroup(); vToolBarGroup = buttonBarLayout.createParallelGroup(GroupLayout.Alignment.LEADING); // Layout information. buttonBarLayout.setHorizontalGroup(buttonBarLayout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(hToolBarGroup)); buttonBarLayout.setVerticalGroup(vToolBarGroup); } return toolBar; } /** * This method initializes jButton * * @return javax.swing.JButton */ private JButton getSelectButton() { if (selectButton == null) { selectButton = new JButton(); selectButton.setBorder(null); selectButton.setMargin(new Insets(0, 0, 0, 0)); selectButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/table-select-column-icon.png"))); selectButton.setToolTipText("Show Column"); selectButton.setBorder(null); selectButton.setEnabled(false); selectButton.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (browserTableModel == null) return; attributeList.setSelectedItems(browserTable.getVisibleAttributeNames()); attributeSelectionPopupMenu.show(e.getComponent(), e.getX(), e.getY()); } }); } return selectButton; } private JButton getFunctionBuilderButton() { if (formulaBuilderButton == null) { formulaBuilderButton = new JButton(); formulaBuilderButton.setBorder(null); formulaBuilderButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/fx.png"))); formulaBuilderButton.setToolTipText("Function Builder"); formulaBuilderButton.setMargin(new Insets(1, 1, 1, 1)); formulaBuilderButton.setBorder(null); formulaBuilderButton.setEnabled(false); final JFrame rootFrame = (JFrame) SwingUtilities.getRoot(this); formulaBuilderButton.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (browserTableModel == null) return; // Do not allow opening of the formula builder dialog // while a cell is being edited! if (browserTable.getCellEditor() != null) return; final int cellRow = browserTable.getSelectedRow(); final int cellColumn = browserTable.getSelectedColumn(); // Map the screen index of column to internal index of the table model String colName = browserTable.getColumnName(cellColumn); int colIndex = browserTableModel.mapColumnNameToColumnIndex(colName); if (cellRow == -1 || cellColumn == -1 || !browserTableModel.isCellEditable(cellRow, colIndex)) { JOptionPane.showMessageDialog(rootFrame, "Can't enter a formula w/o a selected cell.", "Information", JOptionPane.INFORMATION_MESSAGE); } else { final String attrName = getAttribName(cellRow, cellColumn); final Map<String, Class<?>> attribNameToTypeMap = new HashMap<String, Class<?>>(); final CyTable attrs = browserTableModel.getAttributes(); initAttribNameToTypeMap(attrs, attrName, attribNameToTypeMap); final FormulaBuilderDialog formulaBuilderDialog = new FormulaBuilderDialog(compiler, browserTable, rootFrame, attrName); formulaBuilderDialog.setLocationRelativeTo(rootFrame); formulaBuilderDialog.setVisible(true); } } private void initAttribNameToTypeMap(final CyTable attrs, final String attrName, final Map<String, Class<?>> attribNameToTypeMap) { for (final CyColumn column : attrs.getColumns()) attribNameToTypeMap.put(column.getName(), column.getType()); attribNameToTypeMap.remove(attrName); } }); } return formulaBuilderButton; } private String getAttribName(final int cellRow, final int cellColumn) { int colIndexModel = browserTable.convertColumnIndexToModel(cellColumn); return browserTableModel.getColumnName( colIndexModel); } private JButton getDeleteButton() { if (deleteAttributeButton == null) { deleteAttributeButton = new JButton(); deleteAttributeButton.setBorder(null); deleteAttributeButton.setMargin(new Insets(0, 0, 0, 0)); deleteAttributeButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/stock_delete.png"))); deleteAttributeButton.setToolTipText("Delete Column..."); deleteAttributeButton.setBorder(null); // Create pop-up window for deletion deleteAttributeButton.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (deleteAttributeButton.isEnabled()) removeAttribute(e); } }); deleteAttributeButton.setEnabled(false); } return deleteAttributeButton; } private JButton getDeleteTableButton() { if (deleteTableButton == null) { deleteTableButton = new JButton(); deleteTableButton.setBorder(null); deleteTableButton.setMargin(new Insets(0, 0, 0, 0)); deleteTableButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/table_delete.png"))); deleteTableButton.setToolTipText("Delete Table..."); deleteTableButton.setBorder(null); // Create pop-up window for deletion deleteTableButton.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (deleteTableButton.isEnabled()) removeTable(e); } }); deleteTableButton.setEnabled(false); } return deleteTableButton; } private JButton getSelectAllButton() { if (selectAllAttributesButton == null) { selectAllAttributesButton = new JButton(); selectAllAttributesButton.setBorder(null); selectAllAttributesButton.setMargin(new Insets(0, 0, 0, 0)); selectAllAttributesButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/select_all.png"))); selectAllAttributesButton.setToolTipText("Show All Columns"); selectAllAttributesButton.setBorder(null); selectAllAttributesButton.setEnabled(false); selectAllAttributesButton.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { try { final CyTable table = browserTableModel.getAttributes(); final Set<String> allAttrNames = new HashSet<String>(); for (final CyColumn column : table.getColumns()) allAttrNames.add(column.getName()); browserTable.setVisibleAttributeNames(allAttrNames); //ColumnResizer.adjustColumnPreferredWidths(browserTableModel.getTable()); } catch (Exception ex) { attributeList.clearSelection(); } } }); } return selectAllAttributesButton; } private JButton getUnselectAllButton() { if (unselectAllAttributesButton == null) { unselectAllAttributesButton = new JButton(); unselectAllAttributesButton.setBorder(null); unselectAllAttributesButton.setMargin(new Insets(0, 0, 0, 0)); unselectAllAttributesButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/unselect_all.png"))); unselectAllAttributesButton.setToolTipText("Hide All Columns"); unselectAllAttributesButton.setBorder(null); unselectAllAttributesButton.setEnabled(false); unselectAllAttributesButton.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { try { browserTable.setVisibleAttributeNames(new HashSet<String>()); } catch (Exception ex) { attributeList.clearSelection(); } } }); } return unselectAllAttributesButton; } private void removeAttribute(final MouseEvent e) { final String[] attrArray = getAttributeArray(); final JFrame frame = (JFrame)SwingUtilities.getRoot(this); final DeletionDialog dDialog = new DeletionDialog(frame, browserTableModel.getAttributes(), browserTable); dDialog.pack(); dDialog.setLocationRelativeTo(toolBar); dDialog.setVisible(true); } private void removeTable(final MouseEvent e) { final CyTable table = browserTableModel.getAttributes(); if (table.getMutability() == CyTable.Mutability.MUTABLE) { String title = "Please confirm this action"; String msg = "Are you sure you want to delete this table?"; int _confirmValue = JOptionPane.showConfirmDialog(this, msg, title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); // if user selects yes delete the table if (_confirmValue == JOptionPane.OK_OPTION) guiTaskMgr.execute(deleteTableTaskFactory.createTaskIterator(table)); } else if (table.getMutability() == CyTable.Mutability.PERMANENTLY_IMMUTABLE) { String title = "Error"; String msg = "Can not delete this table, it is PERMANENTLY_IMMUTABLE"; JOptionPane.showMessageDialog(this, msg, title, JOptionPane.ERROR_MESSAGE); } else if (table.getMutability() == CyTable.Mutability.IMMUTABLE_DUE_TO_VIRT_COLUMN_REFERENCES) { String title = "Error"; String msg = "Can not delete this table, it is IMMUTABLE_DUE_TO_VIRT_COLUMN_REFERENCES"; JOptionPane.showMessageDialog(this, msg, title, JOptionPane.ERROR_MESSAGE); } } private JList getSelectedAttributeList() { if (attributeList == null) { attributeList = new CheckBoxJList(); attributeList.setModel(attrListModel); attributeList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); attributeList.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { attributeSelectionPopupMenu.setVisible(false); } } }); } return attributeList; } private String[] getAttributeArray() { final CyTable attrs = browserTableModel.getAttributes(); final Collection<CyColumn> columns = attrs.getColumns(); final String[] attributeArray = new String[columns.size() - 1]; int index = 0; for (final CyColumn column : columns) { if (!column.isPrimaryKey()) attributeArray[index++] = column.getName(); } Arrays.sort(attributeArray); return attributeArray; } /** * This method initializes createNewAttributeButton * * @return javax.swing.JButton */ private JButton getNewButton() { if (createNewAttributeButton == null) { createNewAttributeButton = new JButton(); createNewAttributeButton.setBorder(null); createNewAttributeButton.setFont(new java.awt.Font("Dialog", java.awt.Font.PLAIN, 12)); createNewAttributeButton.setHorizontalTextPosition(SwingConstants.CENTER); createNewAttributeButton.setMargin(new Insets(0, 0, 0, 0)); createNewAttributeButton.setToolTipText("Create New Column"); createNewAttributeButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/stock_new.png"))); createNewAttributeButton.setBorder(null); createNewAttributeButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (browserTableModel != null) createColumnMenu.show(e.getComponent(), e.getX(), e.getY()); } }); createNewAttributeButton.setEnabled(false); } return createNewAttributeButton; } /* private JButton getMapGlobalTableButton() { if (mapGlobalTableButton == null) { mapGlobalTableButton = new JButton(); mapGlobalTableButton.setBorder(null); mapGlobalTableButton.setMargin(new Insets(0, 0, 0, 0)); mapGlobalTableButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/table_map.png"))); mapGlobalTableButton.setToolTipText("Link Table to Attributes"); mapGlobalTableButton.setBorder(null); mapGlobalTableButton.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (mapGlobalTableButton.isEnabled()) guiTaskManagerServiceRef.execute(mapGlobalTableTaskFactoryService.createTaskIterator( browserTableModel.getAttributes() )); } }); } mapGlobalTableButton.setEnabled(false); return mapGlobalTableButton; } */ private void createNewAttribute(final String type, boolean isShared) { final String[] existingAttrs = getAttributeArray(); String newAttribName = null; do { newAttribName = JOptionPane.showInputDialog(this, "Please enter new column name: ", "Create New " + type + " Column", JOptionPane.QUESTION_MESSAGE); if (newAttribName == null) return; if (Arrays.binarySearch(existingAttrs, newAttribName) >= 0) { JOptionPane.showMessageDialog(null, "Column " + newAttribName + " already exists.", "Error.", JOptionPane.ERROR_MESSAGE); newAttribName = null; } } while (newAttribName == null); final CyTable attrs; if(isShared) { final CyNetwork network = appMgr.getCurrentNetwork(); if(network instanceof CySubNetwork) { final CyRootNetwork rootNetwork = ((CySubNetwork) network).getRootNetwork(); CyTable sharedTable = null; if(this.objType == CyNode.class) sharedTable = rootNetwork.getSharedNodeTable(); else if(this.objType == CyEdge.class) sharedTable = rootNetwork.getSharedEdgeTable(); else if(this.objType == CyNetwork.class) sharedTable = rootNetwork.getSharedNetworkTable(); else { throw new IllegalStateException("Object type is not valid. This should not happen."); } attrs = sharedTable; } else { throw new IllegalArgumentException("This is not a CySubNetwork and there is no shared table."); } } else { attrs = browserTableModel.getAttributes(); } if (type.equals("String")) attrs.createColumn(newAttribName, String.class, false); else if (type.equals("Floating Point")) attrs.createColumn(newAttribName, Double.class, false); else if (type.equals("Integer")) attrs.createColumn(newAttribName, Integer.class, false); else if (type.equals("Long Integer")) attrs.createColumn(newAttribName, Long.class, false); else if (type.equals("Boolean")) attrs.createColumn(newAttribName, Boolean.class, false); else if (type.equals("String List")) attrs.createListColumn(newAttribName, String.class, false); else if (type.equals("Floating Point List")) attrs.createListColumn(newAttribName, Double.class, false); else if (type.equals("Integer List")) attrs.createListColumn(newAttribName, Integer.class, false); else if (type.equals("Long Integer List")) attrs.createListColumn(newAttribName, Long.class, false); else if (type.equals("Boolean List")) attrs.createListColumn(newAttribName, Boolean.class, false); else throw new IllegalArgumentException("unknown column type \"" + type + "\"."); } }
package it.unibz.inf.ontop.docker; import it.unibz.inf.ontop.injection.OntopSQLOWLAPIConfiguration; import it.unibz.inf.ontop.owlapi.OntopOWLFactory; import it.unibz.inf.ontop.owlapi.OntopOWLReasoner; import it.unibz.inf.ontop.owlapi.connection.OWLConnection; import it.unibz.inf.ontop.owlapi.connection.OWLStatement; import it.unibz.inf.ontop.owlapi.resultset.OWLBindingSet; import it.unibz.inf.ontop.owlapi.resultset.TupleOWLResultSet; import org.junit.Ignore; import org.junit.Test; import org.semanticweb.owlapi.io.ToStringRenderer; import org.semanticweb.owlapi.model.OWLObject; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.security.MessageDigest; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertTrue; /*** * Class to test if functions on Strings and Numerics in SPARQL are working properly. */ public abstract class AbstractBindTestWithFunctions { protected static Logger log = LoggerFactory.getLogger(AbstractBindTestWithFunctions.class); private final OntopOWLReasoner reasoner; private final OWLConnection conn; protected AbstractBindTestWithFunctions(OntopOWLReasoner reasoner) { this.reasoner = reasoner; this.conn = reasoner.getConnection(); } protected static OntopOWLReasoner createReasoner(String owlFile, String obdaFile, String propertiesFile) throws OWLOntologyCreationException { owlFile = AbstractBindTestWithFunctions.class.getResource(owlFile).toString(); obdaFile = AbstractBindTestWithFunctions.class.getResource(obdaFile).toString(); propertiesFile = AbstractBindTestWithFunctions.class.getResource(propertiesFile).toString(); OntopOWLFactory factory = OntopOWLFactory.defaultFactory(); OntopSQLOWLAPIConfiguration config = OntopSQLOWLAPIConfiguration.defaultBuilder() .nativeOntopMappingFile(obdaFile) .ontologyFile(owlFile) .propertyFile(propertiesFile) .enableTestMode() .build(); return factory.createReasoner(config); } public OntopOWLReasoner getReasoner() { return reasoner; } public OWLConnection getConnection() { return conn; } private void runTests(String query) throws Exception { // Creating a new instance of the reasoner // Now we are ready for querying OWLStatement st = conn.createStatement(); int i = 0; try { TupleOWLResultSet rs = st.executeSelectQuery(query); while (rs.hasNext()) { final OWLBindingSet bindingSet = rs.next(); OWLObject ind1 = bindingSet.getOWLObject("w"); System.out.println(ind1); i++; } assertTrue(i > 0); } catch (Exception e) { throw e; } } @Test public void testAndBind() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND((CONTAINS(?title,\"Semantic\") && CONTAINS(?title,\"Web\")) AS ?w)\n" + "}\n" + "ORDER BY ?w"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); checkReturnedValues(queryBind, expectedValues); } @Test public void testAndBindDistinct() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT DISTINCT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND((CONTAINS(?title,\"Semantic\") && CONTAINS(?title,\"Web\")) AS ?w)\n" + "}\n" + "ORDER BY ?w"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); checkReturnedValues(queryBind, expectedValues); } @Test public void testOrBind() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT DISTINCT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND((CONTAINS(?title,\"Semantic\") || CONTAINS(?title,\"Book\")) AS ?w)\n" + "}\n" + "ORDER BY ?w"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); checkReturnedValues(queryBind, expectedValues); } /* * Tests for numeric functions */ @Test public void testCeil() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (CEIL(?discount) AS ?w)\n" + "}"; checkReturnedValues(queryBind, getCeilExpectedValues()); } protected List<String> getCeilExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"1\"^^xsd:decimal"); expectedValues.add("\"1\"^^xsd:decimal"); expectedValues.add("\"1\"^^xsd:decimal"); expectedValues.add("\"1\"^^xsd:decimal"); return expectedValues; } @Test public void testFloor() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (FLOOR(?discount) AS ?w)\n" + "}"; checkReturnedValues(queryBind, getFloorExpectedValues()); } protected List<String> getFloorExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"0\"^^xsd:decimal"); expectedValues.add("\"0\"^^xsd:decimal"); expectedValues.add("\"0\"^^xsd:decimal"); expectedValues.add("\"0\"^^xsd:decimal"); return expectedValues; } @Test public void testRound() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (CONCAT(STR(ROUND(?discount)),', ',STR(ROUND(?p))) AS ?w)\n" + "}"; checkReturnedValues(queryBind, getRoundExpectedValues()); } protected List<String> getRoundExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"0.0, 43.0\"^^xsd:string"); expectedValues.add("\"0.0, 23.0\"^^xsd:string"); expectedValues.add("\"0.0, 34.0\"^^xsd:string"); expectedValues.add("\"0.0, 10.0\"^^xsd:string"); return expectedValues; } @Test public void testAbs() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (ABS((?p - ?discount*?p) - ?p) AS ?w)\n" + "}"; checkReturnedValues(queryBind, getAbsExpectedValues()); } protected List<String> getAbsExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"8.5\"^^xsd:decimal"); expectedValues.add("\"5.75\"^^xsd:decimal"); expectedValues.add("\"6.7\"^^xsd:decimal"); expectedValues.add("\"1.5\"^^xsd:decimal"); return expectedValues; } /* * Tests for hash functions. H2 supports only SHA256 algorithm. */ @Test public void testHashSHA256() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount.\n" + " ?x dc:title ?title .\n" + " FILTER (STRSTARTS(?title, \"The S\"))\n" + " BIND (SHA256(str(?title)) AS ?w)\n" + "}"; List<String> expectedValues = new ArrayList<>(); try{ MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest("The Semantic Web".getBytes("UTF-8")); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String hex = Integer.toHexString(0xff & hash[i]); if(hex.length() == 1) hexString.append('0'); hexString.append(hex); } expectedValues.add(String.format("\"%s\"^^xsd:string",hexString.toString())); } catch(Exception ex){ throw new RuntimeException(ex); } checkReturnedValues(queryBind, expectedValues); } @Ignore @Test public void testHashMd5() throws Exception { } @Ignore @Test public void testHashSHA1() throws Exception { } @Ignore @Test public void testHashSHA384() throws Exception { } @Ignore @Test public void testHashSHA512() throws Exception { } /* * Tests for functions on strings. */ @Test public void testStrLen() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (STRLEN(?title) AS ?w)\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"15\"^^xsd:integer"); expectedValues.add("\"16\"^^xsd:integer"); expectedValues.add("\"20\"^^xsd:integer"); expectedValues.add("\"44\"^^xsd:integer"); checkReturnedValues(queryBind, expectedValues); } //test substring with 2 parameters @Test public void testSubstr2() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (SUBSTR(?title, 3) AS ?w)\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"ARQL Tutorial\"@en"); // ROMAN (23 Dec 2015): now the language tag is handled correctly expectedValues.add("\"e Semantic Web\"@en"); expectedValues.add("\"ime and Punishment\"@en"); expectedValues.add("\"e Logic Book: Introduction, Second Edition\"@en"); checkReturnedValues(queryBind, expectedValues); } //test substring with 3 parameters @Test public void testSubstr3() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (SUBSTR(?title, 3, 6) AS ?w)\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"ARQL T\"@en"); // ROMAN (23 Dec 2015): now the language tag is handled correctly expectedValues.add("\"e Sema\"@en"); expectedValues.add("\"ime an\"@en"); expectedValues.add("\"e Logi\"@en"); checkReturnedValues(queryBind, expectedValues); } @Test public void testURIEncoding() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " FILTER (STRSTARTS(?title,\"The\"))\n" + " BIND (ENCODE_FOR_URI(?title) AS ?w)\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"The%20Semantic%20Web\"^^xsd:string"); expectedValues.add("\"The%20Logic%20Book%3A%20Introduction%2C%20Second%20Edition\"^^xsd:string"); checkReturnedValues(queryBind, expectedValues); } @Test public void testStrEnds() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND(?title AS ?w)\n" + " FILTER(STRENDS(?title,\"b\"))\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"The Semantic Web\"@en"); checkReturnedValues(queryBind, expectedValues); } @Test public void testStrStarts() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND(?title AS ?w)\n" + " FILTER(STRSTARTS(?title,\"The\"))\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"The Semantic Web\"@en"); expectedValues.add("\"The Logic Book: Introduction, Second Edition\"@en"); checkReturnedValues(queryBind, expectedValues); } @Test public void testStrSubstring() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND(SUBSTR(?title,1,STRLEN(?title)) AS ?w)\n" + " FILTER(STRSTARTS(?title,\"The\"))\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"The Semantic Web\"@en"); // ROMAN (23 Dec 2015): now the language tag is handled correctly expectedValues.add("\"The Logic Book: Introduction, Second Edition\"@en"); // ROMAN (23 Dec 2015): now the language tag is handled correctly checkReturnedValues(queryBind, expectedValues); } @Test public void testContainsBind() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND(CONTAINS(?title,\"Semantic\") AS ?w)\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); checkReturnedValues(queryBind, expectedValues); } @Test public void testContainsFilter() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND(?title AS ?w)\n" + " FILTER(CONTAINS(?title,\"Semantic\"))\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"The Semantic Web\"@en"); checkReturnedValues(queryBind, expectedValues); } @Test public void testBindWithUcase() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (UCASE(?title) AS ?v)\n" + " BIND (CONCAT(?title, \" \", ?v) AS ?w)\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"SPARQL Tutorial SPARQL TUTORIAL\"^^xsd:string"); expectedValues.add("\"The Semantic Web THE SEMANTIC WEB\"^^xsd:string"); expectedValues.add("\"Crime and Punishment CRIME AND PUNISHMENT\"^^xsd:string"); expectedValues.add("\"The Logic Book: Introduction, Second Edition " + "The Logic Book: Introduction, Second Edition\"".toUpperCase()+"^^xsd:string"); checkReturnedValues(queryBind, expectedValues); } @Test public void testBindWithLcase() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (LCASE(?title) AS ?v)\n" + " BIND (CONCAT(?title, \" \", ?v) AS ?w)\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"SPARQL Tutorial sparql tutorial\"^^xsd:string"); expectedValues.add("\"The Semantic Web the semantic web\"^^xsd:string"); expectedValues.add("\"Crime and Punishment crime and punishment\"^^xsd:string"); expectedValues.add("\"The Logic Book: Introduction, Second Edition " + "The Logic Book: Introduction, Second Edition\"".toLowerCase()+"^^xsd:string"); checkReturnedValues(queryBind, expectedValues); } @Test public void testBindWithBefore1() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (STRBEFORE(?title,\"ti\") AS ?w)\n" + "}"; checkReturnedValues(queryBind, getBindWithBefore1ExpectedValues()); } protected List<String> getBindWithBefore1ExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"\"^^xsd:string"); expectedValues.add("\"The Seman\"@en"); expectedValues.add("\"\"^^xsd:string"); expectedValues.add("\"The Logic Book: Introduc\"@en"); return expectedValues; } @Test public void testBindWithBefore2() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (STRBEFORE(?title,\"\") AS ?w)\n" + "}"; checkReturnedValues(queryBind, getBindWithBefore2ExpectedValues()); } protected List<String> getBindWithBefore2ExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"\"@en"); expectedValues.add("\"\"@en"); expectedValues.add("\"\"@en"); expectedValues.add("\"\"@en"); return expectedValues; } @Test public void testBindWithAfter1() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (STRAFTER(?title,\"The\") AS ?w)\n" + "}"; checkReturnedValues(queryBind, getBindWithAfter1ExpectedValues()); } protected List<String> getBindWithAfter1ExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"\"^^xsd:string"); expectedValues.add("\" Semantic Web\"@en"); expectedValues.add("\"\"^^xsd:string"); expectedValues.add("\" Logic Book: Introduction, Second Edition\"@en"); return expectedValues; } @Test public void testBindWithAfter2() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (STRAFTER(?title,\"\") AS ?w)\n" + "}"; checkReturnedValues(queryBind, getBindWithAfter2ExpectedValues()); } protected List<String> getBindWithAfter2ExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"SPARQL Tutorial\"@en"); expectedValues.add("\"The Semantic Web\"@en"); expectedValues.add("\"Crime and Punishment\"@en"); expectedValues.add("\"The Logic Book: Introduction, Second Edition\"@en"); return expectedValues; } /* * Tests for functions on date and time */ @Test public void testMonth() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " BIND (MONTH(?year) AS ?w)\n" + "}"; checkReturnedValues(queryBind, getMonthExpectedValues()); } protected List<String> getMonthExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"6\"^^xsd:integer"); expectedValues.add("\"12\"^^xsd:integer"); expectedValues.add("\"9\"^^xsd:integer"); expectedValues.add("\"11\"^^xsd:integer"); return expectedValues; } @Test public void testYear() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " BIND (YEAR(?year) AS ?w)\n" + "}"; checkReturnedValues(queryBind, getYearExpectedValues()); } protected List<String> getYearExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"2014\"^^xsd:integer"); expectedValues.add("\"2011\"^^xsd:integer"); expectedValues.add("\"2015\"^^xsd:integer"); expectedValues.add("\"1967\"^^xsd:integer"); return expectedValues; } @Test public void testDay() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " BIND (DAY(?year) AS ?w)\n" + "}"; checkReturnedValues(queryBind, getDayExpectedValues()); } protected List<String> getDayExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"5\"^^xsd:integer"); expectedValues.add("\"8\"^^xsd:integer"); expectedValues.add("\"21\"^^xsd:integer"); expectedValues.add("\"5\"^^xsd:integer"); return expectedValues; } @Test public void testMinutes() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " BIND (MINUTES(?year) AS ?w)\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"47\"^^xsd:integer"); expectedValues.add("\"30\"^^xsd:integer"); expectedValues.add("\"23\"^^xsd:integer"); expectedValues.add("\"50\"^^xsd:integer"); checkReturnedValues(queryBind, expectedValues); } @Test public void testHours() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " BIND (HOURS(?year) AS ?w)\n" + "}"; checkReturnedValues(queryBind, getHoursExpectedValues()); } protected List<String> getHoursExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"18\"^^xsd:integer"); expectedValues.add("\"12\"^^xsd:integer"); expectedValues.add("\"9\"^^xsd:integer"); expectedValues.add("\"7\"^^xsd:integer"); return expectedValues; } @Test public void testSeconds() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " BIND (SECONDS(?year) AS ?w)\n" + "}"; checkReturnedValues(queryBind, getSecondsExpectedValues()); } protected List<String> getSecondsExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"52\"^^xsd:decimal"); expectedValues.add("\"0\"^^xsd:decimal"); expectedValues.add("\"6\"^^xsd:decimal"); expectedValues.add("\"0\"^^xsd:decimal"); return expectedValues; } @Test public void testNow() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " BIND (NOW() AS ?w)\n" + "}"; runTests(queryBind); } @Test public void testUuid() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title (UUID() AS ?w) WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + "}"; runTests(queryBind); } @Test public void testStrUuid() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title (STRUUID() AS ?w) WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + "}"; runTests(queryBind); } @Test public void testRand() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title (RAND() AS ?w) WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + "}"; runTests(queryBind); } @Test public void testDivide() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x dc:title ?title .\n" + " BIND ((?p / 2) AS ?w)\n" + "}"; checkReturnedValues(queryBind, getDivideExpectedValues()); } protected List<String> getDivideExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"21.250000\"^^xsd:decimal"); expectedValues.add("\"11.500000\"^^xsd:decimal"); expectedValues.add("\"16.750000\"^^xsd:decimal"); expectedValues.add("\"5.000000\"^^xsd:decimal"); return expectedValues; } @Test public void testTZ() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title (TZ(?year) AS ?w) WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + "}"; checkReturnedValues(queryBind, getTZExpectedValues()); } protected List<String> getTZExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"08:00\"^^xsd:string"); expectedValues.add("\"01:00\"^^xsd:string"); expectedValues.add("\"00:00\"^^xsd:string"); expectedValues.add("\"01:00\"^^xsd:string"); return expectedValues; } @Test public void testBound() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (BOUND(?title) AS ?w) WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x ns:pubYear ?year .\n" + " OPTIONAL{ \n" + " ?x dc:title ?title .\n" + " FILTER (STRSTARTS(?title, \"T\"))\n" + " } \n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); checkReturnedValues(queryBind, expectedValues); } /** * Currently equalities between lang strings are treated as RDFTermEqual. * * Therefore != is always false or null (which corresponds to false under 2VL) * */ @Test public void testRDFTermEqual() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (CONCAT(?title,\" | \",?title2) AS ?w) WHERE \n" + "{ \n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?y ns:discount ?discount2 .\n" + " ?y dc:title ?title2 .\n" + " FILTER (?discount = ?discount2 && ?title != ?title2)\n" + " } ORDER BY ?title"; List<String> expectedValues = new ArrayList<>(); checkReturnedValues(queryBind, expectedValues); } @Test public void testStrEqual() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (CONCAT(?title,\" | \",?title2) AS ?w) WHERE \n" + "{ \n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?y ns:discount ?discount2 .\n" + " ?y dc:title ?title2 .\n" + " FILTER (?discount = ?discount2 && str(?title) != str(?title2))\n" + " } ORDER BY ?title"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"Crime and Punishment | SPARQL Tutorial\"^^xsd:string"); expectedValues.add("\"SPARQL Tutorial | Crime and Punishment\"^^xsd:string"); checkReturnedValues(queryBind, expectedValues); } @Test public void testSameTerm() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (CONCAT(?title,\" | \",?title2) AS ?w) WHERE \n" + "{ \n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?y ns:discount ?discount2 .\n" + " ?y dc:title ?title2 .\n" + " FILTER(sameTerm(?discount, ?discount2) && !sameTerm(?title, ?title2))\n" + " } ORDER BY ?title"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"Crime and Punishment | SPARQL Tutorial\"^^xsd:string"); expectedValues.add("\"SPARQL Tutorial | Crime and Punishment\"^^xsd:string"); checkReturnedValues(queryBind, expectedValues); } @Test public void testIsIRI() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (isIRI(?title) AS ?w) WHERE \n" + "{ ?x ns:price ?price .\n" + " ?x ns:discount ?discount .\n" + " ?x ns:pubYear ?year .\n" + " ?x dc:title ?title .\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); checkReturnedValues(queryBind, expectedValues); } @Test public void testIsBlank() throws Exception { //no example data } @Test public void testIsLiteral() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (isLiteral(?discount) AS ?w) WHERE \n" + "{ ?x ns:price ?price .\n" + " ?x ns:discount ?discount .\n" + " ?x ns:pubYear ?year .\n" + " ?x dc:title ?title .\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); checkReturnedValues(queryBind, expectedValues); } @Test public void testIsNumeric() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (isNumeric(?discount) AS ?w) WHERE \n" + "{ ?x ns:price ?price .\n" + " ?x ns:discount ?discount .\n" + " ?x ns:pubYear ?year .\n" + " ?x dc:title ?title .\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); checkReturnedValues(queryBind, expectedValues); } @Test public void testStr() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (str(?year) AS ?w) WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " ?x ns:discount ?discount .\n" + " } ORDER BY ?year "; checkReturnedValues(queryBind, getStrExpectedValues()); } protected List<String> getStrExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"1970-11-05T07:50:00.000000\"^^xsd:string"); expectedValues.add("\"2011-12-08T12:30:00.000000\"^^xsd:string"); expectedValues.add("\"2014-06-05T18:47:52.000000\"^^xsd:string"); expectedValues.add("\"2015-09-21T09:23:06.000000\"^^xsd:string"); return expectedValues; } @Test public void testLang() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (lang(?title) AS ?w) WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " ?x ns:discount ?discount .\n" + " } "; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"en\"^^xsd:string"); expectedValues.add("\"en\"^^xsd:string"); expectedValues.add("\"en\"^^xsd:string"); expectedValues.add("\"en\"^^xsd:string"); checkReturnedValues(queryBind, expectedValues); } //In SPARQL 1.0, the DATATYPE function was not defined for literals with a language tag @Test public void testDatatype() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (?discount AS ?w) WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " ?x ns:discount ?discount .\n" + " FILTER ( datatype(?discount) = xsd:decimal)\n" + " } "; checkReturnedValues(queryBind, getDatatypeExpectedValues()); } protected List<String> getDatatypeExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"0.20\"^^xsd:decimal"); expectedValues.add("\"0.25\"^^xsd:decimal"); expectedValues.add("\"0.20\"^^xsd:decimal"); expectedValues.add("\"0.15\"^^xsd:decimal"); return expectedValues; } @Test public void testConcat() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (CONCAT(?title,\" | \", ?description) AS ?w) WHERE \n" + "{ \n" + " ?x ns:price ?p .\n" + " ?x dc:title ?title .\n" + " ?x dc:description ?description .\n" + " ?x ns:pubYear ?year .\n" + " ?x ns:discount ?discount .\n" + " } ORDER BY ?title"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"Crime and Punishment | good\"^^xsd:string"); expectedValues.add("\"SPARQL Tutorial | good\"^^xsd:string"); expectedValues.add("\"The Logic Book: Introduction, Second Edition | good\"^^xsd:string"); expectedValues.add("\"The Semantic Web | bad\"^^xsd:string"); checkReturnedValues(queryBind, expectedValues); } @Test public void testLangMatches() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (BOUND(?title) AS ?w) WHERE \n" + "{ \n" + " ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " OPTIONAL{\n" + " ?x dc:title ?title .\n" + " FILTER(langMatches( lang(?title), \"EN\" )) \n" + " } } ORDER BY ?title"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); checkReturnedValues(queryBind, expectedValues); } @Test public void testREGEX() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (BOUND(?title) AS ?w) WHERE \n" + "{ \n" + " ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " OPTIONAL{\n" + " ?x dc:title ?title .\n" + " FILTER(REGEX( ?title, \"Semantic\" )) \n" + " } } ORDER BY ?title"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); checkReturnedValues(queryBind, expectedValues); } @Test public void testREPLACE() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?w WHERE \n" + "{ \n" + " ?x ns:price ?p .\n" + " ?x dc:title ?title .\n" + " ?x dc:description ?description .\n" + " ?x ns:pubYear ?year .\n" + " BIND(REPLACE(?title, \"Second\", \"First\") AS ?w) .\n" + " } ORDER BY ?title"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"Crime and Punishment\"@en"); expectedValues.add("\"SPARQL Tutorial\"@en"); expectedValues.add("\"The Logic Book: Introduction, First Edition\"@en"); expectedValues.add("\"The Semantic Web\"@en"); checkReturnedValues(queryBind, expectedValues); } private void checkReturnedValues(String query, List<String> expectedValues) throws Exception { // Now we are ready for querying OWLConnection conn = reasoner.getConnection(); OWLStatement st = conn.createStatement(); int i = 0; List<String> returnedValues = new ArrayList<>(); try { TupleOWLResultSet rs = st.executeSelectQuery(query); while (rs.hasNext()) { final OWLBindingSet bindingSet = rs.next(); OWLObject ind1 = bindingSet.getOWLObject("w"); // log.debug(ind1.toString()); if (ind1 != null) { String value = ToStringRenderer.getInstance().getRendering(ind1); returnedValues.add(value); System.out.println(value); } else { returnedValues.add(null); } i++; } } catch (Exception e) { throw e; } assertTrue(String.format("%s instead of \n %s", returnedValues.toString(), expectedValues.toString()), returnedValues.equals(expectedValues)); assertTrue(String.format("Wrong size: %d (expected %d)", i, expectedValues.size()), expectedValues.size() == i); } }
package org.cipres.treebase.domain.nexus.nexml; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.cipres.treebase.Constants; import org.cipres.treebase.dao.jdbc.ContinuousMatrixElementJDBC; import org.cipres.treebase.dao.jdbc.ContinuousMatrixJDBC; import org.cipres.treebase.dao.jdbc.DiscreteMatrixElementJDBC; import org.cipres.treebase.dao.jdbc.DiscreteMatrixJDBC; import org.cipres.treebase.dao.jdbc.MatrixColumnJDBC; import org.cipres.treebase.domain.matrix.CharSet; import org.cipres.treebase.domain.matrix.CharacterMatrix; import org.cipres.treebase.domain.matrix.ColumnRange; import org.cipres.treebase.domain.matrix.ContinuousChar; import org.cipres.treebase.domain.matrix.ContinuousMatrix; import org.cipres.treebase.domain.matrix.ContinuousMatrixElement; import org.cipres.treebase.domain.matrix.DiscreteChar; import org.cipres.treebase.domain.matrix.DiscreteCharState; import org.cipres.treebase.domain.matrix.DiscreteMatrix; import org.cipres.treebase.domain.matrix.DiscreteMatrixElement; import org.cipres.treebase.domain.matrix.Matrix; import org.cipres.treebase.domain.matrix.MatrixColumn; import org.cipres.treebase.domain.matrix.MatrixDataType; import org.cipres.treebase.domain.matrix.MatrixElement; import org.cipres.treebase.domain.matrix.MatrixRow; import org.cipres.treebase.domain.matrix.PhyloChar; import org.cipres.treebase.domain.matrix.RowSegment; import org.cipres.treebase.domain.matrix.StandardMatrix; import org.cipres.treebase.domain.matrix.StateSet; import org.cipres.treebase.domain.study.Study; import org.cipres.treebase.domain.taxon.TaxonLabelHome; import org.cipres.treebase.domain.taxon.TaxonLabelSet; import org.nexml.model.Annotatable; import org.nexml.model.CategoricalMatrix; import org.nexml.model.CharacterState; import org.nexml.model.CharacterStateSet; import org.nexml.model.Document; import org.nexml.model.MatrixCell; import org.nexml.model.MolecularMatrix; import org.nexml.model.OTUs; import org.nexml.model.OTU; import org.nexml.model.Subset; public class NexmlMatrixConverter extends NexmlObjectConverter { private static final int MAX_GRANULAR_NCHAR = 1000; private static final int MAX_GRANULAR_NTAX = 30; /** * * @param study * @param taxonLabelHome */ public NexmlMatrixConverter(Study study,TaxonLabelHome taxonLabelHome,Document document) { super(study,taxonLabelHome,document); } /** * * @param xmlMatrix * @return */ public Matrix fromXmlToTreeBase(CategoricalMatrix xmlMatrix) { DiscreteMatrix tbMatrix = new DiscreteMatrix(); DiscreteMatrixJDBC matrixJDBC = new DiscreteMatrixJDBC(tbMatrix, xmlMatrix, this); List<MatrixColumnJDBC> columnJDBCs = new ArrayList<MatrixColumnJDBC>(); long[] colIds = matrixJDBC.getColIDs(); long[] rowIds = matrixJDBC.getRowIDs(); List<DiscreteMatrixElementJDBC> elements = new ArrayList<DiscreteMatrixElementJDBC>(); int colIndex = 0; for ( org.nexml.model.Character xmlCharacter : xmlMatrix.getCharacters() ) { String charName = xmlCharacter.getLabel(); DiscreteChar tbChar = new DiscreteChar(); tbChar.setDescription(charName); MatrixColumnJDBC aColumnJDBC = new MatrixColumnJDBC(); aColumnJDBC.setPhyloChar(tbChar); columnJDBCs.add(aColumnJDBC); int rowIndex = 0; for ( OTU xmlOTU : xmlMatrix.getOTUs().getAllOTUs() ) { @SuppressWarnings("unused") MatrixCell<CharacterState> xmlCell = xmlMatrix.getCell(xmlOTU, xmlCharacter); DiscreteMatrixElementJDBC element = new DiscreteMatrixElementJDBC(); //element.setValue(xmlCell.getValue()); // XXX nested stateset lookup song & dance here element.setElementOrder(colIndex); element.setMatrixRowID(rowIds[rowIndex]); element.setMatrixColID(colIds[colIndex]); elements.add(element); rowIndex++; } colIndex++; } DiscreteMatrixElementJDBC.batchDiscreteElements(elements, getTaxonLabelHome().getConnection()); return tbMatrix; } /** * * @param xmlMatrix * @return */ public Matrix fromXmlToTreeBase(org.nexml.model.ContinuousMatrix xmlMatrix) { ContinuousMatrix tbMatrix = new ContinuousMatrix(); ContinuousMatrixJDBC matrixJDBC = new ContinuousMatrixJDBC(tbMatrix, xmlMatrix, this); List<MatrixColumnJDBC> columnJDBCs = new ArrayList<MatrixColumnJDBC>(); long[] colIds = matrixJDBC.getColIDs(); long[] rowIds = matrixJDBC.getRowIDs(); List<ContinuousMatrixElementJDBC> elements = new ArrayList<ContinuousMatrixElementJDBC>(); int colIndex = 0; for ( org.nexml.model.Character xmlCharacter : xmlMatrix.getCharacters() ) { String charName = xmlCharacter.getLabel(); ContinuousChar tbChar = new ContinuousChar(); tbChar.setDescription(charName); MatrixColumnJDBC aColumnJDBC = new MatrixColumnJDBC(); aColumnJDBC.setPhyloChar(tbChar); columnJDBCs.add(aColumnJDBC); int rowIndex = 0; for ( OTU xmlOTU : xmlMatrix.getOTUs().getAllOTUs() ) { MatrixCell<Double> xmlCell = xmlMatrix.getCell(xmlOTU, xmlCharacter); ContinuousMatrixElementJDBC element = new ContinuousMatrixElementJDBC(); element.setValue(xmlCell.getValue()); element.setElementOrder(colIndex); element.setMatrixRowID(rowIds[rowIndex]); element.setMatrixColID(colIds[colIndex]); elements.add(element); rowIndex++; } colIndex++; } ContinuousMatrixElementJDBC.batchContinuousElements(elements, getTaxonLabelHome().getConnection()); return tbMatrix; } /** * * @param xmlMatrix * @return */ public Matrix fromXmlToTreeBase(org.nexml.model.Matrix<?> xmlMatrix) { OTUs xmlOTUs = xmlMatrix.getOTUs(); Matrix tbMatrix = null; TaxonLabelSet tbTaxa = null; Long tbTaxonLabelSetID = readTreeBaseID((Annotatable) xmlOTUs); if ( null != tbTaxonLabelSetID ) { tbTaxa = getTaxonLabelHome() .findPersistedObjectByID(TaxonLabelSet.class, tbTaxonLabelSetID); } if ( xmlMatrix instanceof CategoricalMatrix ) { tbMatrix = fromXmlToTreeBase((CategoricalMatrix) xmlMatrix); } else if ( xmlMatrix instanceof org.nexml.model.ContinuousMatrix ) { tbMatrix = fromXmlToTreeBase((org.nexml.model.ContinuousMatrix) xmlMatrix); } if ( null != tbMatrix ) { attachTreeBaseID((Annotatable) xmlMatrix, tbMatrix,Matrix.class); if ( null != tbTaxa ) { tbMatrix.setTaxa(tbTaxa); } tbMatrix.setStudy(getStudy()); tbMatrix.setTitle(xmlMatrix.getLabel()); tbMatrix.setPublished(false); } return tbMatrix; } /** * Creates and populates characters (i.e. columns) with their annotations, * and state sets, with their annotations * * @param tbMatrix * @return an xml matrix with empty rows */ public CategoricalMatrix fromTreeBaseToXml(StandardMatrix tbMatrix) { OTUs xmlOTUs = getOTUsById(tbMatrix.getTaxa().getId()); CategoricalMatrix xmlMatrix = getDocument().createCategoricalMatrix(xmlOTUs); // attach base uri and history note getDocument().addAnnotationValue("skos:historyNote", Constants.SKOSURI, "Mapped from TreeBASE schema using NexmlMatrixConverter $Rev$"); xmlMatrix.setBaseURI(mMatrixBaseURI); List<List<DiscreteCharState>> tbStateLabels = tbMatrix.getStateLabels(); List<MatrixColumn> tbColumns = tbMatrix.getColumnsReadOnly(); for ( int i = 0; i < tbColumns.size(); i++ ) { CharacterStateSet xmlStateSet = xmlMatrix.createCharacterStateSet(); for ( DiscreteCharState tbState : tbStateLabels.get(i) ) { CharacterState xmlState = xmlStateSet.createCharacterState(tbState.getSymbol().toString()); if ( null != tbState.getDescription() ) { xmlState.setLabel(tbState.getDescription()); } attachTreeBaseID((Annotatable)xmlState,tbState,DiscreteCharState.class); } org.nexml.model.Character xmlCharacter = xmlMatrix.createCharacter(xmlStateSet); PhyloChar tbCharacter = tbColumns.get(i).getCharacter(); if ( null != tbCharacter.getDescription() ) { xmlCharacter.setLabel(tbCharacter.getDescription()); } attachTreeBaseID((Annotatable)xmlCharacter,tbColumns.get(i),MatrixColumn.class); } return xmlMatrix; } /** * Creates and populates characters (i.e. columns) with their annotations, * and state sets, with their annotations * * @param tbMatrix * @return an xml matrix with empty rows */ public MolecularMatrix fromTreeBaseToXml(DiscreteMatrix tbMatrix) { OTUs xmlOTUs = getOTUsById(tbMatrix.getTaxa().getId()); String tbDataType = tbMatrix.getDataType().getDescription(); MolecularMatrix xmlMatrix = null; CharacterStateSet xmlStateSet = null; // create the matrix and constant state set if ( tbDataType.equals(MatrixDataType.MATRIX_DATATYPE_DNA) ) { xmlMatrix = getDocument().createMolecularMatrix(xmlOTUs, MolecularMatrix.DNA); xmlStateSet = ((MolecularMatrix)xmlMatrix).getDNACharacterStateSet(); } else if ( tbDataType.equals(MatrixDataType.MATRIX_DATATYPE_RNA) ) { xmlMatrix = getDocument().createMolecularMatrix(xmlOTUs, MolecularMatrix.RNA); xmlStateSet = ((MolecularMatrix)xmlMatrix).getRNACharacterStateSet(); } else if ( tbDataType.equals(MatrixDataType.MATRIX_DATATYPE_PROTEIN) ) { xmlMatrix = getDocument().createMolecularMatrix(xmlOTUs, MolecularMatrix.Protein); xmlStateSet = ((MolecularMatrix)xmlMatrix).getProteinCharacterStateSet(); } // attach base uri and history note xmlMatrix.setBaseURI(mMatrixBaseURI); getDocument().addAnnotationValue("skos:historyNote", Constants.SKOSURI, "Mapped from TreeBASE schema using NexmlMatrixConverter $Rev$"); // lookup the equivalent state in tb and attach identifiers for(StateSet tbStateSet : tbMatrix.getStateSets() ) { for (DiscreteCharState tbState : tbStateSet.getStates() ) { String tbSymbol = tbState.getSymbol().toString().toUpperCase(); CharacterState xmlState = xmlStateSet.lookupCharacterStateBySymbol(tbSymbol); if ( null == xmlState ) { xmlState = xmlStateSet.createCharacterState(tbSymbol); } attachTreeBaseID((Annotatable)xmlState,tbState,DiscreteCharState.class); } } // create columns and attach identifiers for ( MatrixColumn tbColumn : tbMatrix.getColumnsReadOnly() ) { org.nexml.model.Character xmlCharacter = xmlMatrix.createCharacter(xmlStateSet); attachTreeBaseID((Annotatable)xmlCharacter,tbColumn,MatrixColumn.class); } return xmlMatrix; } /** * Creates and populates characters (i.e. columns) with their annotations, * and state sets, with their annotations * * @param tbMatrix * @return an xml matrix with empty rows */ public org.nexml.model.ContinuousMatrix fromTreeBaseToXml(ContinuousMatrix tbMatrix) { OTUs xmlOTUs = getOTUsById(tbMatrix.getTaxa().getId()); org.nexml.model.ContinuousMatrix xmlMatrix = getDocument().createContinuousMatrix(xmlOTUs); // attach base uri and history note xmlMatrix.setBaseURI(mMatrixBaseURI); getDocument().addAnnotationValue("skos:historyNote", Constants.SKOSURI, "Mapped from TreeBASE schema using NexmlMatrixConverter $Rev$"); for ( MatrixColumn tbColumn : tbMatrix.getColumnsReadOnly() ) { org.nexml.model.Character xmlCharacter = xmlMatrix.createCharacter(); PhyloChar tbCharacter = tbColumn.getCharacter(); if ( null != tbCharacter.getDescription() ) { xmlCharacter.setLabel(tbCharacter.getDescription()); ((Annotatable)xmlCharacter).addAnnotationValue("dcterms:description", Constants.DCTermsURI, tbCharacter.getDescription()); } attachTreeBaseID((Annotatable)xmlCharacter,tbColumn,MatrixColumn.class); //coerce the tbMatrix into a character matrix to get its character sets CharacterMatrix tbCharacterMatrix = (CharacterMatrix)tbMatrix; Set<CharSet> tbCharSets = tbCharacterMatrix.getCharSets(); for ( CharSet tbCharSet : tbCharSets ) { Collection<ColumnRange> tbColumnRanges = tbCharSet.getColumns(tbCharacterMatrix); for ( ColumnRange tbColumnRange : tbColumnRanges ) { // these are the beginning and end of the range int tbStart = tbColumnRange.getStartColIndex(); int tbStop = tbColumnRange.getEndColIndex(); // increment from beginning to end. This number is probably either null, for a // contiguous range, or perhaps 3 for codon positions int tbInc = 1; // create the equivalent nexml character set Subset nexSubset = xmlMatrix.createSubset(tbCharSet.getLabel()); // assign character objects to the subset. Here we get the full list List<org.nexml.model.Character> nexCharacters = xmlMatrix.getCharacters(); // now we iterate over the coordinates and assign the nexml characters to the set for ( int i = tbStart; i <= tbStop; i += tbInc ) { nexSubset.addThing(nexCharacters.get(i)); } } } } return xmlMatrix; } // XXX doesn't handle the following data types: // public static final String MATRIX_DATATYPE_NUCLEOTIDE = "Nucleotide"; // public static final String MATRIX_DATATYPE_DISTANCE = "Distance"; // public static final String MATRIX_DATATYPE_MIXED = "Mixed"; @SuppressWarnings("unchecked") public org.nexml.model.Matrix<?> fromTreeBaseToXml(CharacterMatrix tbMatrix) { org.nexml.model.Matrix<?> xmlMatrix = null; if ( tbMatrix instanceof DiscreteMatrix ) { if ( tbMatrix.getDataType().getDescription().equals(MatrixDataType.MATRIX_DATATYPE_STANDARD) ) { xmlMatrix = fromTreeBaseToXml((StandardMatrix) tbMatrix); } else { xmlMatrix = fromTreeBaseToXml((DiscreteMatrix) tbMatrix); } populateXmlMatrix((org.nexml.model.Matrix<CharacterState>)xmlMatrix,(DiscreteMatrix)tbMatrix); } else if ( tbMatrix instanceof ContinuousMatrix ) { xmlMatrix = fromTreeBaseToXml((ContinuousMatrix) tbMatrix); populateXmlMatrix((org.nexml.model.ContinuousMatrix)xmlMatrix,(ContinuousMatrix)tbMatrix); } xmlMatrix.setLabel(tbMatrix.getTitle()); attachTreeBaseID((Annotatable)xmlMatrix, tbMatrix,Matrix.class); String tb1MatrixID = tbMatrix.getTB1MatrixID(); if ( null != tb1MatrixID ) { ((Annotatable)xmlMatrix).addAnnotationValue("tb:identifier.matrix.tb1", Constants.TBTermsURI, tb1MatrixID); } Set<CharSet> tbCharSets = tbMatrix.getCharSets(); for ( CharSet tbCharSet : tbCharSets ) { Collection<ColumnRange> tbColumnRanges = tbCharSet.getColumns(tbMatrix); for ( ColumnRange tbColumnRange : tbColumnRanges ) { // these are the beginning and end of the range int tbStart = tbColumnRange.getStartColIndex(); int tbStop = tbColumnRange.getEndColIndex(); // increment from beginning to end. This number is probably either null, for a // contiguous range, or perhaps 3 for codon positions int tbInc = 1; // create the equivalent nexml character set Subset nexSubset = xmlMatrix.createSubset(tbCharSet.getLabel()); // assign character objects to the subset. Here we get the full list List<org.nexml.model.Character> nexCharacters = xmlMatrix.getCharacters(); // now we iterate over the coordinates and assign the nexml characters to the set for ( int i = tbStart; i <= tbStop; i += tbInc ) { nexSubset.addThing(nexCharacters.get(i)); } } } return xmlMatrix; } /** * * @param xmlMatrix * @param tbMatrix * @param xmlOTUs * @param stateSet */ private void populateXmlMatrix( org.nexml.model.Matrix<CharacterState> xmlMatrix, DiscreteMatrix tbMatrix) { OTUs xmlOTUs = xmlMatrix.getOTUs(); List<org.nexml.model.Character> characterList = xmlMatrix.getCharacters(); for ( MatrixRow tbRow : tbMatrix.getRowsReadOnly() ) { Set<RowSegment> tbSegments = tbRow.getSegmentsReadOnly(); OTU xmlOTU = getOTUById(xmlOTUs, tbRow.getTaxonLabel().getId()); int charIndex = 0; if ( characterList.size() <= MAX_GRANULAR_NCHAR && xmlOTUs.getAllOTUs().size() <= MAX_GRANULAR_NTAX ) { for ( MatrixElement tbCell : tbRow.getElements() ) { org.nexml.model.Character xmlCharacter = characterList.get(charIndex); MatrixCell<CharacterState> xmlCell = xmlMatrix.getCell(xmlOTU, xmlCharacter); DiscreteCharState tbState = ((DiscreteMatrixElement)tbCell).getCharState(); String tbSymbolString = ( null == tbState ) ? "?" : tbState.getSymbol().toString(); CharacterState xmlState = xmlCharacter.getCharacterStateSet().lookupCharacterStateBySymbol(tbSymbolString); xmlCell.setValue(xmlState); attachTreeBaseID((Annotatable)xmlCell,tbCell,DiscreteMatrixElement.class); for ( RowSegment tbSegment : tbSegments ) { if ( tbSegment.getStartIndex() <= charIndex && charIndex <= tbSegment.getEndIndex() ) { //declare variables for row-segment annotations String title = tbSegment.getTitle(); String institutionCode = tbSegment.getSpecimenLabel().getInstAcronym(); String collectionCode = tbSegment.getSpecimenLabel().getCollectionCode(); String catalogNumber = tbSegment.getSpecimenLabel().getCatalogNumber(); String accessionNumber = tbSegment.getSpecimenLabel().getGenBankAccession(); String otherAccessionNumber = tbSegment.getSpecimenLabel().getOtherAccession(); String dateSampled = tbSegment.getSpecimenLabel().getSampleDateString(); String scientificName = tbSegment.getSpecimenTaxonLabelAsString(); String collector = tbSegment.getSpecimenLabel().getCollector(); Double latitude = tbSegment.getSpecimenLabel().getLatitude(); Double longitude = tbSegment.getSpecimenLabel().getLongitude(); Double elevation = tbSegment.getSpecimenLabel().getElevation(); String country = tbSegment.getSpecimenLabel().getCountry(); String state = tbSegment.getSpecimenLabel().getState(); String locality = tbSegment.getSpecimenLabel().getLocality(); String notes = tbSegment.getSpecimenLabel().getNotes(); //if the value is not null, output the xmlOTU annotation. //DwC refers to the Darwin Core term vocabulary for the associated annotation if (null != title){ //output name identifying the data set from which the record was derived ((Annotatable)xmlCell).addAnnotationValue("DwC:datasetName", Constants.DwCURI, title); } if ( null != institutionCode ) { //output name or acronym of institution that has custody of information referred to in record ((Annotatable)xmlCell).addAnnotationValue("DwC:institutionCode", Constants.DwCURI, institutionCode); } if ( null != collectionCode ) { //output name or code that identifies collection or data set from which record was derived ((Annotatable)xmlCell).addAnnotationValue ("DwC:collectionCode", Constants.DwCURI, collectionCode); } if ( null != catalogNumber ){ //output unique (usually) identifier for the record within data set or collection ((Annotatable)xmlCell).addAnnotationValue("DwC:catalogNumber", Constants.DwCURI, catalogNumber); } if ( null != accessionNumber) { //output a list of genetic sequence information associated with occurrence ((Annotatable)xmlCell).addAnnotationValue("DwC:associatedSequences", Constants.DwCURI, accessionNumber); } if ( null != otherAccessionNumber ) { //list of previous or alternate fully catalog numbers (i.e. Genbank) or human-used identifiers ((Annotatable)xmlCell).addAnnotationValue("DwC:otherCatalogNumbers", Constants.DwCURI, otherAccessionNumber); } if ( null != dateSampled ) { //output date sampled in ISO 8601 format ((Annotatable)xmlCell).addAnnotationValue("DwC:eventDate", Constants.DwCURI, dateSampled); } if ( null != scientificName ) { //output full scientific name ((Annotatable)xmlCell).addAnnotationValue("DwC:scientificName", Constants.DwCURI, scientificName); } if ( null != collector ) { //output names of people associated with recording of original occurrence ((Annotatable)xmlCell).addAnnotationValue("DwC:recordedBy", Constants.DwCURI, collector); } if ( null != latitude ) { //output geographic latitude in decimal degrees using geodeticDatum spatial reference system ((Annotatable)xmlCell).addAnnotationValue("DwC:decimalLatitude", Constants.DwCURI, latitude); } if ( null != longitude ) { //output geographic longitude in decimal degrees using geodeticDatum spatial reference system ((Annotatable)xmlCell).addAnnotationValue("DwC:decimalLongitude", Constants.DwCURI, longitude); } if ( null != elevation ) { //there are two different Darwin Core terms for elevation depending on elevation value //outputs geographic elevation of sample if ( elevation >= 0) { //above local surface in meters ((Annotatable)xmlCell).addAnnotationValue("DwC:verbatimElevation", Constants.DwCURI, elevation); } else { //below local surface in meters ((Annotatable)xmlCell).addAnnotationValue("DwC:verbatimDepth", Constants.DwCURI, elevation); } } if ( null != country ) { //output country in which location occurs ((Annotatable)xmlCell).addAnnotationValue("DwC:country", Constants.DwCURI, country); } if ( null != state ) { //output name of next smaller administrative region than country (i.e. state, province, region) ((Annotatable)xmlCell).addAnnotationValue ("DwC:stateProvince", Constants.DwCURI, state); } if ( null != locality) { //output brief description of sample location ((Annotatable)xmlCell).addAnnotationValue("DwC:locality", Constants.DwCURI, locality); } if ( null != notes ) { //output any additional information about specimen ((Annotatable)xmlCell).addAnnotationValue("DwC:occurenceRemarks", Constants.DwCURI, notes); } } } charIndex++; } } else { String seq = tbRow.buildElementAsString(); if ( tbMatrix.getDataType().getDescription().equals(MatrixDataType.MATRIX_DATATYPE_STANDARD) ) { StringBuilder sb = new StringBuilder(); for ( int i = 0; i < seq.length(); i++ ) { sb.append(seq.charAt(i)); if ( i < seq.length() - 1 ) { sb.append(' '); } } } xmlMatrix.setSeq(seq,xmlOTU); } for ( RowSegment tbSegment : tbSegments ) { //declare variables for row-segment annotations String title = tbSegment.getTitle(); String institutionCode = tbSegment.getSpecimenLabel().getInstAcronym(); String collectionCode = tbSegment.getSpecimenLabel().getCollectionCode(); String catalogNumber = tbSegment.getSpecimenLabel().getCatalogNumber(); String accessionNumber = tbSegment.getSpecimenLabel().getGenBankAccession(); String otherAccessionNumber = tbSegment.getSpecimenLabel().getOtherAccession(); String dateSampled = tbSegment.getSpecimenLabel().getSampleDateString(); String scientificName = tbSegment.getSpecimenTaxonLabelAsString(); String collector = tbSegment.getSpecimenLabel().getCollector(); Double latitude = tbSegment.getSpecimenLabel().getLatitude(); Double longitude = tbSegment.getSpecimenLabel().getLongitude(); Double elevation = tbSegment.getSpecimenLabel().getElevation(); String country = tbSegment.getSpecimenLabel().getCountry(); String state = tbSegment.getSpecimenLabel().getState(); String locality = tbSegment.getSpecimenLabel().getLocality(); String notes = tbSegment.getSpecimenLabel().getNotes(); //if the value is not null, output the xmlOTU annotation. //DwC refers to the Darwin Core term vocabulary for the associated annotation if (null != title){ //output name identifying the data set from which the record was derived xmlOTU.addAnnotationValue("DwC:datasetName", Constants.DwCURI, title); } if ( null != institutionCode ) { //output name or acronym of institution that has custody of information referred to in record xmlOTU.addAnnotationValue("DwC:institutionCode", Constants.DwCURI, institutionCode); } if ( null != collectionCode ) { //output name or code that identifies collection or data set from which record was derived xmlOTU.addAnnotationValue ("DwC:collectionCode", Constants.DwCURI, collectionCode); } if ( null != catalogNumber ){ //output unique (usually) identifier for the record within data set or collection xmlOTU.addAnnotationValue("DwC:catalogNumber", Constants.DwCURI, catalogNumber); } if ( null != accessionNumber) { //output a list of genetic sequence information associated with occurrence xmlOTU.addAnnotationValue("DwC:associatedSequences", Constants.DwCURI, accessionNumber); } if ( null != otherAccessionNumber ) { //list of previous or alternate fully catalog numbers (i.e. Genbank) or human-used identifiers xmlOTU.addAnnotationValue("DwC:otherCatalogNumbers", Constants.DwCURI, otherAccessionNumber); } if ( null != dateSampled ) { //output date sampled in ISO 8601 format xmlOTU.addAnnotationValue("DwC:eventDate", Constants.DwCURI, dateSampled); } if ( null != scientificName ) { //output full scientific name xmlOTU.addAnnotationValue("DwC:scientificName", Constants.DwCURI, scientificName); } if ( null != collector ) { //output names of people associated with recording of original occurrence xmlOTU.addAnnotationValue("DwC:recordedBy", Constants.DwCURI, collector); } if ( null != latitude ) { //output geographic latitude in decimal degrees using geodeticDatum spatial reference system xmlOTU.addAnnotationValue("DwC:decimalLatitude", Constants.DwCURI, latitude); } if ( null != longitude ) { //output geographic longitude in decimal degrees using geodeticDatum spatial reference system xmlOTU.addAnnotationValue("DwC:decimalLongitude", Constants.DwCURI, longitude); } if ( null != elevation ) { //there are two different Darwin Core terms for elevation depending on elevation value //outputs geographic elevation of sample if ( elevation >= 0) { //above local surface in meters xmlOTU.addAnnotationValue("DwC:verbatimElevation", Constants.DwCURI, elevation); } else { //below local surface in meters xmlOTU.addAnnotationValue("DwC:verbatimDepth", Constants.DwCURI, elevation); } } if ( null != country ) { //output country in which location occurs xmlOTU.addAnnotationValue("DwC:country", Constants.DwCURI, country); } if ( null != state ) { //output name of next smaller administrative region than country (i.e. state, province, region) xmlOTU.addAnnotationValue ("DwC:stateProvince", Constants.DwCURI, state); } if ( null != locality) { //output brief description of sample location xmlOTU.addAnnotationValue("DwC:locality", Constants.DwCURI, locality); } if ( null != notes ) { //output any additional information about specimen xmlOTU.addAnnotationValue("DwC:occurenceRemarks", Constants.DwCURI, notes); } } } } /** * * @param xmlMatrix * @param tbMatrix */ private void populateXmlMatrix(org.nexml.model.ContinuousMatrix xmlMatrix, ContinuousMatrix tbMatrix) { List<org.nexml.model.Character> characterList = xmlMatrix.getCharacters(); OTUs xmlOTUs = xmlMatrix.getOTUs(); for ( MatrixRow tbRow : tbMatrix.getRowsReadOnly() ) { List<MatrixElement> elements = tbRow.getElements(); OTU xmlOTU = getOTUById(xmlOTUs, tbRow.getTaxonLabel().getId()); if ( characterList.size() <= MAX_GRANULAR_NCHAR && xmlOTUs.getAllOTUs().size() <= MAX_GRANULAR_NTAX ) { for ( int elementIndex = 0; elementIndex < tbMatrix.getnChar(); elementIndex++ ) { ContinuousMatrixElement tbCell = (ContinuousMatrixElement)elements.get(elementIndex); MatrixCell<Double> xmlCell = xmlMatrix.getCell(xmlOTU, characterList.get(elementIndex)); xmlCell.setValue(tbCell.getValue()); attachTreeBaseID((Annotatable)xmlCell,tbCell,DiscreteMatrixElement.class); } } else { String seq = tbRow.buildElementAsString(); xmlMatrix.setSeq(seq,xmlOTU); } Set<RowSegment> tbSegments = tbRow.getSegmentsReadOnly(); for ( RowSegment tbSegment : tbSegments ) { //declare variables for row-segment annotations String title = tbSegment.getTitle(); String institutionCode = tbSegment.getSpecimenLabel().getInstAcronym(); String collectionCode = tbSegment.getSpecimenLabel().getCollectionCode(); String catalogNumber = tbSegment.getSpecimenLabel().getCatalogNumber(); String accessionNumber = tbSegment.getSpecimenLabel().getGenBankAccession(); String otherAccessionNumber = tbSegment.getSpecimenLabel().getOtherAccession(); String dateSampled = tbSegment.getSpecimenLabel().getSampleDateString(); String scientificName = tbSegment.getSpecimenTaxonLabelAsString(); String collector = tbSegment.getSpecimenLabel().getCollector(); Double latitude = tbSegment.getSpecimenLabel().getLatitude(); Double longitude = tbSegment.getSpecimenLabel().getLongitude(); Double elevation = tbSegment.getSpecimenLabel().getElevation(); String country = tbSegment.getSpecimenLabel().getCountry(); String state = tbSegment.getSpecimenLabel().getState(); String locality = tbSegment.getSpecimenLabel().getLocality(); String notes = tbSegment.getSpecimenLabel().getNotes(); //if the value is not null, output the xmlOTU annotation. //DwC refers to the Darwin Core term vocabulary for the associated annotation if (null != title){ //output name identifying the data set from which the record was derived xmlOTU.addAnnotationValue("DwC:datasetName", Constants.DwCURI, title); } if ( null != institutionCode ) { //output name or acronym of institution that has custody of information referred to in record xmlOTU.addAnnotationValue("DwC:institutionCode", Constants.DwCURI, institutionCode); } if ( null != collectionCode ) { //output name or code that identifies collection or data set from which record was derived xmlOTU.addAnnotationValue ("DwC:collectionCode", Constants.DwCURI, collectionCode); } if ( null != catalogNumber ){ //output unique (usually) identifier for the record within data set or collection xmlOTU.addAnnotationValue("DwC:catalogNumber", Constants.DwCURI, catalogNumber); } if ( null != accessionNumber) { //output a list of genetic sequence information associated with occurrence xmlOTU.addAnnotationValue("DwC:associatedSequences", Constants.DwCURI, accessionNumber); } if ( null != otherAccessionNumber ) { //list of previous or alternate fully catalog numbers (i.e. Genbank) or human-used identifiers xmlOTU.addAnnotationValue("DwC:otherCatalogNumbers", Constants.DwCURI, otherAccessionNumber); } if ( null != dateSampled ) { //output date sampled in ISO 8601 format xmlOTU.addAnnotationValue("DwC:eventDate", Constants.DwCURI, dateSampled); } if ( null != scientificName ) { //output full scientific name xmlOTU.addAnnotationValue("DwC:scientificName", Constants.DwCURI, scientificName); } if ( null != collector ) { //output names of people associated with recording of original occurrence xmlOTU.addAnnotationValue("DwC:recordedBy", Constants.DwCURI, collector); } if ( null != latitude ) { //output geographic latitude in decimal degrees using geodeticDatum spatial reference system xmlOTU.addAnnotationValue("DwC:decimalLatitude", Constants.DwCURI, latitude); } if ( null != longitude ) { //output geographic longitude in decimal degrees using geodeticDatum spatial reference system xmlOTU.addAnnotationValue("DwC:decimalLongitude", Constants.DwCURI, longitude); } if ( null != elevation ) { //there are two different Darwin Core terms for elevation depending on elevation value //outputs geographic elevation of sample if ( elevation >= 0) { //above local surface in meters xmlOTU.addAnnotationValue("DwC:verbatimElevation", Constants.DwCURI, elevation); } else { //below local surface in meters xmlOTU.addAnnotationValue("DwC:verbatimDepth", Constants.DwCURI, elevation); } } if ( null != country ) { //output country in which location occurs xmlOTU.addAnnotationValue("DwC:country", Constants.DwCURI, country); } if ( null != state ) { //output name of next smaller administrative region than country (i.e. state, province, region) xmlOTU.addAnnotationValue ("DwC:stateProvince", Constants.DwCURI, state); } if ( null != locality) { //output brief description of sample location xmlOTU.addAnnotationValue("DwC:locality", Constants.DwCURI, locality); } if ( null != notes ) { //output any additional information about specimen xmlOTU.addAnnotationValue("DwC:occurenceRemarks", Constants.DwCURI, notes); } } } } }
package it.unitn.ing.rista.diffr; import java.util.*; import static java.lang.System.*; import static java.util.Collections.sort; import java.io.*; import java.awt.*; import java.util.concurrent.TimeUnit; import com.radiographema.MaudText; import it.unitn.ing.rista.diffr.AtomSite; import it.unitn.ing.rista.diffr.instrument.DefaultInstrument; import it.unitn.ing.rista.io.cif.*; import it.unitn.ing.rista.util.*; import it.unitn.ing.rista.awt.*; import it.unitn.ing.rista.interfaces.Peak; public class DataFileSet extends XRDcat { protected static String[] diclistc = new String[]{ "_pd_meas_datetime_initiated", "_pd_meas_info_author_name", "_riet_meas_datafile_format", "_pd_proc_ls_background_function", "_pd_proc_ls_profile_function", "_pd_proc_ls_peak_cutoff", "_pd_proc_2theta_range_min", "_pd_proc_2theta_range_max", "_pd_proc_2theta_range_inc", "_diffrn_ambient_pressure", "_diffrn_ambient_temperature", "_riet_lorentz_restricted", "_riet_par_background_interpolated", "_riet_par_background_interpolation_range", "_riet_meas_dataset_compute", "_riet_meas_datafile_replace", "_riet_meas_dataset_random_texture", "_maud_background_add_automatic", "_maud_interpolated_background_iterations", "_pd_proc_ls_datafile_weight", "_riet_meas_dataset_no_strain", "_riet_meas_dataset_omogeneous", "_riet_chebyshev_polynomial_background", "_riet_par_background_exp_shift", "_riet_par_background_exp_thermal_shift", "_pd_spec_orientation_omega", "_pd_spec_orientation_chi", "_pd_spec_orientation_phi", "_pd_meas_orientation_omega_offset", "_pd_meas_orientation_chi_offset", "_pd_meas_orientation_phi_offset", "_pd_meas_orientation_eta_offset", "_riet_par_spec_displac_x", "_riet_par_spec_displac_y", "_riet_par_spec_displac_z", "_riet_par_background_pol", "_riet_par_background_chi", "_riet_par_background_eta", "_riet_intensity_extraction", "_riet_position_extraction", "_reflectivity_model_type", "_diffrn_measurement_device", "_fluorescence_model_type", "_diffraction_model_type", "_pd_proc_info_excluded_regions", "_riet_par_background_peak_id", "_riet_meas_datafile_name", "_original_diffraction_image"}; protected static String[] diclistcrm = new String[]{ "_pd_meas_datetime_initiated", "_pd_meas_info_author_name", "_riet_meas_datafile_format", "_pd_proc_ls_background_function", "_pd_proc_ls_profile_function", "_pd_proc_ls_peak_cutoff", "_pd_proc_2theta_range_min", "_pd_proc_2theta_range_max", "_pd_proc_2theta_range_inc", "_diffrn_ambient_pressure", "_diffrn_ambient_temperature", "_riet_lorentz_restricted", "_riet_par_background_interpolated", "_riet_par_background_interpolation_range", "_riet_meas_dataset_compute", "_riet_meas_datafile_replace", "_riet_meas_dataset_random_texture", "_maud_background_add_automatic", "number of iteration for background interpolation", "_pd_proc_ls_datafile_weight", "_riet_meas_dataset_no_strain", "_riet_meas_dataset_omogeneous", "use Chebyshev polynomial for background", /* "_pd_meas_orientation_omega_offset", "_pd_meas_orientation_chi_offset", "_pd_meas_orientation_phi_offset", "_pd_meas_orientation_eta_offset",*/ "_riet_par_background_exp_shift", "_riet_par_background_exp_thermal_shift", "Additional sample omega", "Additional sample chi", "Additional sample phi", "omega disalignement", "chi disalignement", "phi disalignement", "eta disalignement", "x sample displacement", "y sample displacement", "z sample displacement", "background polynomial coeff ", "chi background coeff ", "eta background coeff", "_riet_intensity_extraction", "_riet_position_extraction", "_reflectivity_model_type", "_diffrn_measurement_device", "_fluorescence_model_type", "_diffraction_model_type", "_pd_proc_info_excluded_regions", "_riet_par_background_peak_id", "_riet_meas_datafile_name", "_original_diffraction_image"}; protected static String[] classlistc = new String[]{"superclass:it.unitn.ing.rista.diffr.Region", "superclass:it.unitn.ing.rista.diffr.BkgPeak", "superclass:it.unitn.ing.rista.diffr.DiffrDataFile", "superclass:it.unitn.ing.rista.diffr.DiffractionImageDatafile"/*, "superclass:it.unitn.ing.rista.diffr.CustomAddition"*/ }; public static String[] classlistcs = new String[]{"superclass:it.unitn.ing.rista.diffr.IntensityExtractor", "superclass:it.unitn.ing.rista.diffr.PositionExtractor", "superclass:it.unitn.ing.rista.diffr.Reflectivity", "superclass:it.unitn.ing.rista.diffr.Instrument", "superclass:it.unitn.ing.rista.diffr.Fluorescence", "superclass:it.unitn.ing.rista.diffr.Diffraction"}; public static String[] peakFunctionClass = new String[]{"PseudoVoigt"}; public static boolean[] needDist = new boolean[]{false}; public static int nFunction = 1; public static final int instrumentID = 0; int activedatanumber; private int[] datafileindex; Vector<Peak> thepeaklist = new Vector<Peak>(0, 1); int theindex = -1; public boolean omogeneousDataset = MaudPreferences.getBoolean("background_experimental.dataset_omogeneous", true); public boolean omogeneous = omogeneousDataset; public static final int omogeneousID = 21; int interpolatedPoints = 5; public final static int bkgExpShift = 0; public final static int bkgExpThermalShift = 1; public final static int sampleOmegaID = 2; public final static int sampleChiID = 3; public final static int samplePhiID = 4; public final static int disalignementOmegaID = 5; public final static int displacementxID = 9; public boolean isBackgroundExperimental = false; public static final int minRangeID = 6; public static final int maxRangeID = 7; public static final int lorentzRestrictedID = 11; public static final int backgroundInterpolatedID = 12; public static final int interpolatedPointsID = 13; public static final int enabledID = 14; public boolean enabled = true; public static final int replaceID = 15; public boolean replaceDatafile = false; public static final int automaticPolynomialBackgroundID = 17; public boolean automaticPolynomialBackground = false; public static final int randomTextureID = 16; public boolean randomTexture = false; public boolean noStrain = false; boolean hasNegative2theta = false; double[] sample_angles = new double[3]; double[] disalignement_angles = new double[4]; double[] displacement_errors = new double[3]; public static int interpolationIterationsID = 18; protected int interpolationIterations; static final int datasetWeightFieldID = 19; static final int noStrainID = 20; final static int useChebyshevPolynomialsID = 22; boolean useChebyshevPolynomials = false; double datasetWeight = 1.0; boolean[] needRestore = null; Vector overallVector = null; private Map<Phase, double[][]> phaseStructureFactors = new Hashtable<Phase, double[][]>(); private Map<Phase, double[][][][]> phaseScatFactors = new Hashtable<Phase, double[][][][]>(); public DataFileSet(XRDcat afile, String alabel) { super(afile, alabel); initXRD(); identifier = "dataset"; } public DataFileSet(XRDcat afile) { this(afile, "DataFileSet_x"); } public DataFileSet() { identifier = "dataset"; IDlabel = "dataset"; description = "select this to use a dataset"; } @Override public void initConstant() { Nstring = 23; Nstringloop = 0; Nparameter = 12; Nparameterloop = 3; Nsubordinate = classlistcs.length; Nsubordinateloop = classlistc.length; } @Override public void initDictionary() { arraycopy(diclistc, 0, diclist, 0, totsubordinateloop); arraycopy(diclistcrm, 0, diclistRealMeaning, 0, totsubordinateloop); arraycopy(classlistc, 0, classlist, 0, totsubordinateloop - totsubordinate); arraycopy(classlistcs, 0, classlists, 0, totsubordinate - totparameterloop); } @Override public void initParameters() { super.initParameters(); setLorentzRestricted("true"); setBackgroundInterpolated("false"); setEnabled("true"); setOmogeneous(omogeneous); setReplaceDatafile(MaudPreferences.getPref("datafile.replaceOnAdd", "false")); setAutomaticPolynomialBackground(MaudPreferences.getPref("datafile.addOwnBackgroundPolynomial", "false")); setInterpolatedPoints(MaudPreferences.getInteger("backgroundSubtraction.interpolatedPointsInterval", 150)); setPeakCutoff(MaudPreferences.getPref("pseudoVoigt.defaultPeakCutoff", "30")); setMaxRange("0"); setMinRange("0"); setIntensityExtractor("Le Bail"); setPositionExtractor("none pe"); setInstrument(DefaultInstrument.modelID); setDiffraction("Basic diffraction"); setReflectivity("none reflectivity"); setFluorescence("none fluorescence"); stringField[0] = "Date/time meas"; // to avoid the notify staff setRandomTexture("false"); setNoStrain("false"); useChebyshevPolynomials(false); setBackgroundInterpolationIterations(MaudPreferences.getInteger("backgroundSubtraction.iterations", 10)); setString(datasetWeightFieldID, "1.0"); for (int i = 0; i < Nparameter; i++) parameterField[i] = new Parameter(this, getParameterString(i), 0); } @Override public String toDataString() { return "dataset_" + toXRDcatString(); } /* public void setLabel(String alabel) { setDataFileSetID(alabel); }*/ double[] backgroundChi, backgroundEta, backgroundPol; // todo: background for 2theta and energy int nchibckgpar, netabckgpar, npolbckgpar; // Vector bkgDatafiles = new Vector(0, 1); public void checkConsistencyForVersion(double version) { if (version < 1.821) { if (getFluorescenceMethod().startsWith("none") && getReflectivityMethod().startsWith("none")) setDiffraction("Basic diffraction"); } } @Override public void updateParametertoDoubleBuffering(boolean firstLoading) { if (getFilePar().isLoadingFile() || !isAbilitatetoRefresh) return; super.updateParametertoDoubleBuffering(false); // setRadiation(); // System.out.println("Refreshing angles!"); sample_angles[0] = getParameterValue(sampleOmegaID); // omega sample_angles[1] = getParameterValue(sampleChiID); // chi sample_angles[2] = getParameterValue(samplePhiID); // phi for (int i = 0; i < 4; i++) disalignement_angles[i] = getParameterValue(disalignementOmegaID + i); for (int i = 0; i < 3; i++) displacement_errors[i] = getParameterValue(displacementxID + i); backgroundChi = getParameterLoopVector(chiBackgroundID); backgroundEta = getParameterLoopVector(etaBackgroundID); backgroundPol = getParameterLoopVector(backgroundID); nchibckgpar = numberOfLoopParameters[chiBackgroundID]; netabckgpar = numberOfLoopParameters[etaBackgroundID]; npolbckgpar = numberOfLoopParameters[backgroundID]; } @Override public void updateStringtoDoubleBuffering(boolean firstLoading) { if (getFilePar().isLoadingFile() || !isAbilitatetoRefresh) return; boolean refreshBackgroundInterpolation = false; if (interpolatedPoints != Integer.valueOf(getInterpolatedPoints())) { interpolatedPoints = Integer.valueOf(getInterpolatedPoints()); refreshBackgroundInterpolation = true; } if (interpolationIterations != Integer.valueOf(getInterpolationIterations())) { interpolationIterations = Integer.valueOf(getInterpolationIterations()); refreshBackgroundInterpolation = true; } if (refreshBackgroundInterpolation) { removeManualInterpolation(false); } isBackgroundExperimental = false; int alldatafilenumber = datafilesnumber(); for (int i = 0; i < alldatafilenumber; i++) { DiffrDataFile bdatafile = getDataFile(i); if (bdatafile.getAsBackgroundPermission()) isBackgroundExperimental = true; } enabled = isEnabled(); replaceDatafile = mustReplace(); automaticPolynomialBackground = isAutomaticPolynomialBackground(); randomTexture = hasRandomTexture(); noStrain = hasNoStrain(); useChebyshevPolynomials = useChebyshevPolynomialsString().equalsIgnoreCase("true"); datasetWeight = Double.parseDouble(getString(datasetWeightFieldID)); } public double[] dataForPlot = null; public double[] getDataForPlot() { return dataForPlot; } public double[] datafitForPlot = null; public double[] getDatafitForPlot() { return datafitForPlot; } public double[] backgroundForPlot = null; public double[] getBackgroundForPlot() { return backgroundForPlot; } public double[][] dataphaseForPlot = null; public double[][] getDataphaseForPlot() { return dataphaseForPlot; } static public double[][] getSummedExperimentalComputedData(DiffrDataFile[] datafile, int mode) { if (datafile == null || datafile.length == 0) return null; int ylength = datafile.length; double stepX = 1.0E10; double xmin = 1.0E10, xmax = -1.0E10; // minimum maximum range for (int is1 = 0; is1 < ylength; is1++) { int xlength = datafile[is1].finalindex - datafile[is1].startingindex - 1; double x1 = datafile[is1].getXDataForPlot(datafile[is1].startingindex, mode); double x2 = datafile[is1].getXDataForPlot(datafile[is1].finalindex - 1, mode); double lstepX = Math.abs((x2 - x1) / xlength); if (lstepX < stepX) stepX = lstepX; if (xmin > x1) xmin = x1; if (xmax < x2) xmax = x2; if (xmin > x2) xmin = x2; if (xmax < x1) xmax = x1; } int np = (int) Math.abs((xmax - xmin) / stepX) + 1; double[][] dataToExport = new double[3][np]; if (np > 0) { for (int is1 = 0; is1 < np; is1++) { dataToExport[0][is1] = xmin + is1 * stepX; int total = 0; int totalFit = 0; // data for (int sn = 0; sn < ylength; sn++) { double xstartmin = datafile[sn].getXDataForPlot(datafile[sn].startingindex, mode); double xendmax = datafile[sn].getXDataForPlot(datafile[sn].finalindex - 1, mode); if (xendmax < datafile[sn].getXDataForPlot(datafile[sn].startingindex, mode)) xendmax = datafile[sn].getXDataForPlot(datafile[sn].startingindex, mode); if (xstartmin > datafile[sn].getXDataForPlot(datafile[sn].finalindex - 1, mode)) xstartmin = datafile[sn].getXDataForPlot(datafile[sn].finalindex - 1, mode); if (dataToExport[0][is1] >= xstartmin && dataToExport[0][is1] <= xendmax) { double value = datafile[sn].getInterpolatedYForSummation(dataToExport[0][is1]); double valuec = datafile[sn].getInterpolatedFitForSummation(dataToExport[0][is1]); if (!Double.isNaN(value)) { dataToExport[1][is1] += value; total++; } if (!Double.isNaN(valuec)) { dataToExport[2][is1] += valuec; totalFit++; } } } if (total > 0) dataToExport[1][is1] /= total; if (totalFit > 0) dataToExport[2][is1] /= totalFit; } } return dataToExport; } public void updateDataForPlot() { dataForPlot = null; datafitForPlot = null; backgroundForPlot = null; dataphaseForPlot = null; DiffrDataFile[] datafile = getActiveDataFiles(); if (datafile == null || datafile.length == 0) return; int ylength = datafile.length; int startingIndex = datafile[0].startingindex; int finalIndex = datafile[0].finalindex; double xmin = 1.0E10, xmax = 0.0; double stepX = 1.0E10; int mode = PlotDataFile.checkScaleModeX(); // minimum maximum range for (int is1 = 0; is1 < ylength; is1++) { int xlength = datafile[is1].finalindex - datafile[is1].startingindex - 1; double x1 = datafile[is1].getXDataForPlot(datafile[is1].startingindex, mode); double x2 = datafile[is1].getXDataForPlot(datafile[is1].finalindex - 1, mode); double lstepX = Math.abs((x2 - x1) / xlength); if (lstepX < stepX) stepX = lstepX; if (xmin > x1) xmin = x1; if (xmax < x2) xmax = x2; if (xmin > x2) xmin = x2; if (xmax < x1) xmax = x1; } int np = (int) Math.abs((xmax - xmin) / stepX) + 1; if (np > 0) { dataForPlot = new double[2 * np]; if (datafile[0].hasfit()/* || peaksLocated todo ripristinare */) { datafitForPlot = new double[2 * np]; } for (int is1 = 0; is1 < np; is1++) { int is2 = is1 * 2; dataForPlot[is2] = xmin + is1 * stepX; int total = 0; int totalFit = 0; // data for (int sn = 0; sn < ylength; sn++) { double xstartmin = datafile[sn].getXDataForPlot(datafile[sn].startingindex, mode); double xendmax = datafile[sn].getXDataForPlot(datafile[sn].finalindex - 1, mode); if (xendmax < datafile[sn].getXDataForPlot(datafile[sn].startingindex, mode)) xendmax = datafile[sn].getXDataForPlot(datafile[sn].startingindex, mode); if (xstartmin > datafile[sn].getXDataForPlot(datafile[sn].finalindex - 1, mode)) xstartmin = datafile[sn].getXDataForPlot(datafile[sn].finalindex - 1, mode); if (dataForPlot[is2] >= xstartmin && dataForPlot[is2] <= xendmax) { double value = datafile[sn].getInterpolatedYSqrtIntensity(dataForPlot[is2], 2, mode); if (!Double.isNaN(value)) { dataForPlot[is2 + 1] += value; total++; } } } if (total > 0) dataForPlot[is2 + 1] /= total; // fit if (datafile[0].hasfit()) { datafitForPlot[is2] = dataForPlot[is2]; for (int sn = 0; sn < ylength; sn++) { double xstartmin = datafile[sn].getXDataForPlot(datafile[sn].startingindex, mode); double xendmax = datafile[sn].getXDataForPlot(datafile[sn].finalindex - 1, mode); if (xendmax < datafile[sn].getXDataForPlot(datafile[sn].startingindex, mode)) xendmax = datafile[sn].getXDataForPlot(datafile[sn].startingindex, mode); if (xstartmin > datafile[sn].getXDataForPlot(datafile[sn].finalindex - 1, mode)) xstartmin = datafile[sn].getXDataForPlot(datafile[sn].finalindex - 1, mode); if (datafitForPlot[is2] >= xstartmin && datafitForPlot[is2] <= xendmax) { double value = datafile[sn].getInterpolatedFitSqrtIntensity(datafitForPlot[is2], 2, mode); if (!Double.isNaN(value)) { datafitForPlot[is2 + 1] += value; totalFit++; } } } if (totalFit > 0) datafitForPlot[is2 + 1] /= totalFit; } } // Phases fit if (datafitForPlot != null) { int numberphases = getFilePar().getActiveSample().phasesNumber(); dataphaseForPlot = new double[numberphases][2 * np]; for (int s = 0; s < numberphases; s++) { Phase phase = getFilePar().getActiveSample().getPhase(s); if (phase.plotFit()) { int j; for (int i = j = 0; i < np; i++, j += 2) { int totalFit = 0; for (int sn = 0; sn < ylength; sn++) { double xstartmin = datafile[sn].getXDataForPlot(datafile[sn].startingindex, mode); double xendmax = datafile[sn].getXDataForPlot(datafile[sn].finalindex - 1, mode); if (xendmax < datafile[sn].getXDataForPlot(datafile[sn].startingindex, mode)) xendmax = datafile[sn].getXDataForPlot(datafile[sn].startingindex, mode); if (xstartmin > datafile[sn].getXDataForPlot(datafile[sn].finalindex - 1, mode)) xstartmin = datafile[sn].getXDataForPlot(datafile[sn].finalindex - 1, mode); if (datafitForPlot[j] >= xstartmin && datafitForPlot[j] <= xendmax) { double value = datafile[sn].getInterpolatedFitSqrtIntensity(datafitForPlot[j], 2, mode, s); if (!Double.isNaN(value)) { dataphaseForPlot[s][j + 1] += value; totalFit++; } } } if (totalFit > 0) dataphaseForPlot[s][j + 1] /= totalFit; dataphaseForPlot[s][j] = datafitForPlot[j]; } } } // Background backgroundForPlot = new double[2 * np]; int j; for (int i = j = 0; i < np; i++, j += 2) { int totalFit = 0; for (int sn = 0; sn < ylength; sn++) { double xstartmin = datafile[sn].getXDataForPlot(datafile[sn].startingindex, mode); double xendmax = datafile[sn].getXDataForPlot(datafile[sn].finalindex - 1, mode); if (xendmax < datafile[sn].getXDataForPlot(datafile[sn].startingindex, mode)) xendmax = datafile[sn].getXDataForPlot(datafile[sn].startingindex, mode); if (xstartmin > datafile[sn].getXDataForPlot(datafile[sn].finalindex - 1, mode)) xstartmin = datafile[sn].getXDataForPlot(datafile[sn].finalindex - 1, mode); if (datafitForPlot[j] >= xstartmin && datafitForPlot[j] <= xendmax) { double value = datafile[sn].getInterpolatedBkgFitSqrtIntensity(datafitForPlot[j], 2, mode); if (!Double.isNaN(value)) { backgroundForPlot[j + 1] += value; totalFit++; } } } if (totalFit > 0) backgroundForPlot[j + 1] /= totalFit; backgroundForPlot[j] = datafitForPlot[j]; } } } } public double getDatasetWeight() { return datasetWeight; } public String getDatasetWeightString() { return getString(datasetWeightFieldID); } public void setDatasetWeight(String value) { setString(datasetWeightFieldID, value); } public void setGroupCount(int groupCount) { int alldatafilenumber = datafilesnumber(); for (int i = 0; i < alldatafilenumber; i++) { DiffrDataFile bdatafile = getDataFile(i); bdatafile.setGroupCount(groupCount); } } public String getGroupCount() { if (datafilesnumber() > 0) { return (getDataFile(0)).getGroupCount(); } else return "1"; } public String getDataFileSetID() { return getString(0); } public void setDataFileSetID(String astring) { super.setString(0, astring); } public int getInstrumentID() { return 3; } public void setInstrument(String value) { // System.out.println("Setting Instrument (in dataset):" + value); if (subordinateField[getInstrumentID()] == null || !value.equals((subordinateField[getInstrumentID()]).identifier)) setsubordinateField(getInstrumentID(), value); } public void setInstrument(int number) { setInstrument(getsubordIdentifier(getInstrumentID(), number)); } public void setInstrument(XRDcat inst) { inst.setParent(this); setsubordinateField(getInstrumentID(), inst); inst.setLabel("Diffraction Instrument"); } public void setNewInstrument(int number) { setsubordinateField(getInstrumentID(), getsubordIdentifier(getInstrumentID(), number)); } public Instrument getInstrument() { if (subordinateField[getInstrumentID()] == null) { // System.out.println("Inizialize new Instrument (in dataset)"); setInstrument(0); getInstrument().initializeAsNew(); } return (Instrument) subordinateField[getInstrumentID()]; } public void loadInstrument(String filename, Frame aframe) { CIFParser instrumentParser = new CIFParser(filename, aframe, this, "Instrument"); Object[] ainstrument = instrumentParser.getMainCat(); if (ainstrument != null && ainstrument[0] != null) { getFilePar().loadingFile = true; subordinateField[getInstrumentID()] = (XRDcat) ainstrument[0]; getFilePar().loadingFile = false; notifyUpObjectChanged(this, Constants.OBJECT_ADDED); refreshAll(true); } } @Override public int setField(String cif, String astring, String astringerror, String min, String max, boolean free, String refName, String refBound, String constant, String ratio, String expression, boolean autoTrace, boolean positive) { int index1 = super.setField(cif, astring, astringerror, min, max, free, refName, refBound, constant, ratio, expression, autoTrace, positive); if (cif.equalsIgnoreCase("_diffrn_measurement_device")) { // check if old parameter file containing instruments if (FilePar.instruments != null && FilePar.instruments.size() > 0) { for (int i = 0; i < FilePar.instruments.size(); i++) { Instrument inst = (Instrument) FilePar.instruments.elementAt(i); if (inst.getLabel().equalsIgnoreCase(astring)) { setInstrument(inst); return index1; } } } } return index1; } public Parameter getomega() { return parameterField[sampleOmegaID]; } public Parameter getchi() { return parameterField[sampleChiID]; } public Parameter getphi() { return parameterField[samplePhiID]; } public ListVector getDataFileList() { return subordinateloopField[2]; } public ListVector getDataImageList() { return subordinateloopField[3]; } public boolean askForRange = false; public DiffrDataFile[] addDataFileforName(String filename, boolean browsing) { askForRange = browsing; if (replaceDatafile()) removeAllFiles(); // Vector<DiffrDataFile> listActualDatafiles = new Vector<DiffrDataFile>(datafilesnumber()); // for (int i = 0; i < datafilesnumber(); i++) // listActualDatafiles.add(getDataFile(i)); int actualNumber = datafilesnumber(); // listActualDatafiles.size(); addDatafiles(filename); int datafilesAddedNumber = datafilesnumber() - actualNumber; DiffrDataFile[] succeed = new DiffrDataFile[datafilesAddedNumber]; for (int i = actualNumber; i < datafilesnumber(); i++) succeed[i - actualNumber] = getDataFile(i); askForRange = false; return succeed; } public XRDcat[] addDatafiles(String alabel) { try { XRDcat obj = (XRDcat) factory(this, alabel, filterClass(classlist[2], alabel)); addsubordinateloopField(2, obj); } catch (CannotCreateXRDcat e) { e.printStackTrace(); } catch (PrototypeNotFound ex) { ex.printStackTrace(); } return null; } public void addDatafilesFromScript(String filename) { Constants.refreshTreePermitted = false; if (filename != null) { String[] folderandname = Misc.getFolderandName(filename); BufferedReader reader = Misc.getReader(filename); if (reader != null) { try { String token; StringTokenizer st; String linedata = reader.readLine(); Vector cifItems = new Vector(0, 1); int pivot = 0; while (!linedata.toLowerCase().startsWith("loop_")) linedata = reader.readLine(); linedata = reader.readLine(); while (linedata.startsWith("_")) { st = new StringTokenizer(linedata, "' ,\t\r\n"); while (st.hasMoreTokens()) { token = st.nextToken(); cifItems.addElement(token); if (token.equalsIgnoreCase("_riet_meas_datafile_name")) pivot = cifItems.size(); } linedata = reader.readLine(); } int maxindex = cifItems.size(); int index = 0; DiffrDataFile datafile[] = null; String[] listItems = new String[maxindex]; while ((linedata != null)) { st = new StringTokenizer(linedata, "' ,\t\r\n"); while (st.hasMoreTokens()) { token = st.nextToken(); index++; if (index == pivot) { datafile = addDataFileforName(folderandname[0] + token, false); // System.out.println(datafile); } else if (index > 0) { listItems[index - 1] = token; } if (index == maxindex) { index = 0; if (datafile != null) for (int i = 0; i < maxindex; i++) if (i != pivot - 1) { for (int ij = 0; ij < datafile.length; ij++) datafile[ij].setField((String) cifItems.elementAt(i), listItems[i], "0", "0", "0", false, null, null, null, null, null, false, false); // System.out.println(datafile); // System.out.println((String) cifItems.elementAt(i) + listItems[i]); } } } linedata = reader.readLine(); } } catch (IOException e) { System.out.println("Error loading cif file!"); } try { reader.close(); } catch (IOException e) { e.printStackTrace(); // LogSystem.printStackTrace(e); } } } Constants.refreshTreePermitted = true; notifyUpObjectChanged(this, 0); } public void checkOwnPolynomial() { for (int i = 0; i < datafilesnumber(); i++) { getDataFile(i).checkOwnPolynomial(); } } public void removeSelectedDataFile() { Constants.refreshTreePermitted = false; removeselSubLField(2); Constants.refreshTreePermitted = true; notifyUpObjectChanged(this, 0); } public void disableByAngles(int angleNumber, double startingAngle, double finalAngle) { Constants.refreshTreePermitted = false; double angle; Vector datafiles = getSelectedDatafiles(); int numberDatafiles = datafiles.size(); for (int i = 0; i < numberDatafiles; i++) { DiffrDataFile diffrDatafile = (DiffrDataFile) datafiles.elementAt(i); angle = diffrDatafile.getAngleValue(angleNumber); if (angle < finalAngle && angle > startingAngle) disable(diffrDatafile); } Constants.refreshTreePermitted = true; notifyUpObjectChanged(this, 0); } public void disableByAngles(int angleNumber, double startingAngle, double finalAngle, double everyAngle) { Constants.refreshTreePermitted = false; double angle; Vector datafiles = getSelectedDatafiles(); int numberDatafiles = datafiles.size(); for (double angleIncremented = startingAngle; angleIncremented < finalAngle; angleIncremented += everyAngle) { for (int i = 0; i < numberDatafiles; i++) { DiffrDataFile diffrDatafile = (DiffrDataFile) datafiles.elementAt(i); angle = diffrDatafile.getAngleValue(angleNumber); if (Math.abs(angle - angleIncremented) < Math.abs(everyAngle/1000)) disable(diffrDatafile); } } Constants.refreshTreePermitted = true; notifyUpObjectChanged(this, 0); } public void groupByAngles(int angleNumber, double startingAngle, double finalAngle, double everyAngle) { // todo Constants.refreshTreePermitted = false; double angle; Vector datafiles = getSelectedDatafiles(); int numberDatafiles = datafiles.size(); for (double angleIncremented = startingAngle; angleIncremented < finalAngle; angleIncremented += everyAngle) { for (int i = 0; i < numberDatafiles; i++) { DiffrDataFile diffrDatafile = (DiffrDataFile) datafiles.elementAt(i); angle = diffrDatafile.getAngleValue(angleNumber); if (Math.abs(angle - angleIncremented) < Math.abs(everyAngle/1000)) disable(diffrDatafile); } } Constants.refreshTreePermitted = true; notifyUpObjectChanged(this, 0); } public void generateByAngles(double[] startingAngle, double[] finalAngle, double[] everyAngle) { Constants.refreshTreePermitted = false; Vector datafiles = getSelectedDatafiles(); int numberDatafiles = datafiles.size(); for (int i = 0; i < numberDatafiles; i++) { double[] angles = new double[startingAngle.length]; DiffrDataFile diffrDatafile = (DiffrDataFile) datafiles.elementAt(i); double[] originalAngles = new double[startingAngle.length]; for (int j = 0; j < startingAngle.length; j++) originalAngles[j] = diffrDatafile.getAngleValue(j); generateOutputForAngles(diffrDatafile, 0, startingAngle.length, startingAngle, finalAngle, everyAngle); for (int j = 0; j < startingAngle.length; j++) diffrDatafile.setAngleValue(j, originalAngles[j]); } Constants.refreshTreePermitted = true; notifyUpObjectChanged(this, 0); } public void generateOutputForAngles(DiffrDataFile diffrDatafile, int angleNumber, int angleMax, double[] start, double[] end, double[] step) { if (angleNumber == angleMax) { return; } for (double angle = start[angleNumber]; angle <= end[angleNumber]; angle += step[angleNumber]) { diffrDatafile.setAngleValue(angleNumber, angle); // System.out.println("Generating: " + angleNumber + " " + angleMax + " " + diffrDatafile.getAngleValue(0) + " " + diffrDatafile.getAngleValue(1) + " " + diffrDatafile.getAngleValue(2) + " " + diffrDatafile.getAngleValue(3)); diffrDatafile.fittingFileOutput(false, angleMax); generateOutputForAngles(diffrDatafile, angleNumber + 1, angleMax, start, end, step); } diffrDatafile.setAngleValue(angleNumber, start[angleNumber]); } private void disable(DiffrDataFile diffrDatafile) { diffrDatafile.setCompute(false); } private void enable(DiffrDataFile diffrDatafile) { diffrDatafile.setCompute(true); } public void removeEvery(int number) { Constants.refreshTreePermitted = false; Vector datafiles = getSelectedDatafiles(); int numberDatafiles = datafiles.size(); int index = 1; for (int i = 0; i < numberDatafiles; i++, index++) { DiffrDataFile diffrDatafile = (DiffrDataFile) datafiles.elementAt(i); if (index == number) { disable(diffrDatafile); index = 0; } } Constants.refreshTreePermitted = true; notifyUpObjectChanged(this, 0); } public void removeDatafilesWithTotalLessThan(double number) { Constants.refreshTreePermitted = false; Vector datafiles = getSelectedDatafiles(); int numberDatafiles = datafiles.size(); for (int i = 0; i < numberDatafiles; i++) { DiffrDataFile diffrDatafile = (DiffrDataFile) datafiles.elementAt(i); double total = diffrDatafile.getTotalIntensity(); if (total < number) disable(diffrDatafile); } Constants.refreshTreePermitted = true; notifyUpObjectChanged(this, 0); } public void enableEvery(int number) { Constants.refreshTreePermitted = false; Vector datafiles = getSelectedDatafiles(); int numberDatafiles = datafiles.size(); int index = 1; for (int i = 0; i < numberDatafiles; i++, index++) { DiffrDataFile diffrDatafile = (DiffrDataFile) datafiles.elementAt(i); if (index == number) { enable(diffrDatafile); index = 0; } else disable(diffrDatafile); } Constants.refreshTreePermitted = true; notifyUpObjectChanged(this, 0); } public void groupEvery(int number) { // todo Constants.refreshTreePermitted = false; Vector datafiles = getSelectedDatafiles(); int numberDatafiles = datafiles.size(); int index = 1; Vector<DiffrDataFile> groupOfDatafiles = new Vector<DiffrDataFile>(number); for (int i = 0; i < numberDatafiles; i++, index++) { DiffrDataFile diffrDatafile = (DiffrDataFile) datafiles.elementAt(i); diffrDatafile.updateParametertoDoubleBuffering(false); diffrDatafile.updateStringtoDoubleBuffering(false); groupOfDatafiles.add(diffrDatafile); if (index == number) { groupAndRemove(groupOfDatafiles); index = 0; } } Constants.refreshTreePermitted = true; notifyUpObjectChanged(this, 0); } private void groupAndRemove(Vector<DiffrDataFile> groupOfDatafiles) { if (groupOfDatafiles == null) // paranoid check return; if (groupOfDatafiles.size() > 1) { DiffrDataFile primaryDatafile = groupOfDatafiles.firstElement(); groupOfDatafiles.removeElementAt(0); primaryDatafile.addAndMean(groupOfDatafiles); getFilePar().setStoreSpectraOption(true); primaryDatafile.setLabel(primaryDatafile.getLabel() + "_grouped"); for (int j = 0; j < groupOfDatafiles.size(); j++) removeDatafile(groupOfDatafiles.elementAt(j)); groupOfDatafiles.removeAllElements(); } else if (groupOfDatafiles.size() == 1) groupOfDatafiles.removeAllElements(); } public void removeDataFile(int index) { removeSubLField(2, index); } public void removeImageFile(int index) { removeSubLField(3, index); } public DiffrDataFile getSelectedDataFile() { return (DiffrDataFile) subordinateloopField[2].selectedElement(); } public DiffrDataFile getDataFile(int index) { return (DiffrDataFile) subordinateloopField[2].elementAt(index); } public DiffractionImageDatafile getDiffractionImage(int index) { return (DiffractionImageDatafile) subordinateloopField[3].elementAt(index); } public DiffrDataFile getActiveDataFile(int index) { return getDataFile(datafileindex[index]); } public Vector getSelectedDatafiles() { return subordinateloopField[2].selectedElements(); } public DiffrDataFile[] getSelectedDataFiles() { Vector datafiles = getSelectedDatafiles(); int numberDatafiles = datafiles.size(); DiffrDataFile[] diffrDatafiles = new DiffrDataFile[numberDatafiles]; for (int i = 0; i < numberDatafiles; i++) { diffrDatafiles[i] = (DiffrDataFile) datafiles.elementAt(i); } return diffrDatafiles; } public void removeAllDisabledFiles() { Constants.refreshTreePermitted = false; int datafilenumber = datafilesnumber(); for (int i = datafilenumber; i > 0; i DiffrDataFile tmpdatafile = getDataFile(i - 1); if (!tmpdatafile.getComputePermission()) removeDataFile(i - 1); } Constants.refreshTreePermitted = true; notifyUpObjectChanged(this, 0); // updateStringtoDoubleBuffering(); } public void removeAllFiles() { Constants.refreshTreePermitted = false; int datafilenumber = datafilesnumber(); for (int i = datafilenumber; i > 0; i // DiffrDataFile tmpdatafile = (DiffrDataFile) getDataFile(i-1); removeDataFile(i - 1); } Constants.refreshTreePermitted = true; notifyUpObjectChanged(this, 0); // updateStringtoDoubleBuffering(); } public void setStatusAllFiles(boolean status) { int datafilenumber = datafilesnumber(); for (int i = datafilenumber; i > 0; i DiffrDataFile tmpdatafile = getDataFile(i - 1); tmpdatafile.setCompute(status); } // updateStringtoDoubleBuffering(); } public void setStatusAllSelectedFiles(boolean status) { Vector datafiles = getSelectedDatafiles(); if (datafiles == null) { (new AttentionD(new Frame(), "No item from the list selected!")).setVisible(true); return; } int datafilenumber = datafiles.size(); for (int i = 0; i < datafilenumber; i++) { DiffrDataFile tmpdatafile = (DiffrDataFile) datafiles.elementAt(i); tmpdatafile.setCompute(status); } } public void setFittingOutputAllSelectedFiles(boolean status) { Vector datafiles = getSelectedDatafiles(); if (datafiles == null) { (new AttentionD(new Frame(), "No item from the list selected!")).setVisible(true); return; } int datafilenumber = datafiles.size(); for (int i = 0; i < datafilenumber; i++) { DiffrDataFile tmpdatafile = (DiffrDataFile) datafiles.elementAt(i); tmpdatafile.setGeneratePlotfile(status); } } public void setAsBkgAllSelectedFiles(boolean status) { Vector datafiles = getSelectedDatafiles(); if (datafiles == null) { (new AttentionD(new Frame(), "No item from the list selected!")).setVisible(true); return; } int datafilenumber = datafiles.size(); for (int i = 0; i < datafilenumber; i++) { DiffrDataFile tmpdatafile = (DiffrDataFile) datafiles.elementAt(i); tmpdatafile.setAsBackground(status); } } public void setNewAngles(int[] mult, double[] offset) { Vector datafiles = getSelectedDatafiles(); if (datafiles == null) { (new AttentionD(new Frame(), "No item from the list selected!")).setVisible(true); return; } int datafilenumber = datafiles.size(); for (int i = 0; i < datafilenumber; i++) { DiffrDataFile tmpdatafile = (DiffrDataFile) datafiles.elementAt(i); tmpdatafile.setNewAngles(mult, offset); } } public void setIndex(int index) { theindex = index; } public void refreshIndices(Phase phase) { int numberOfReflections = phase.gethklNumber(); double[][] structureFactors = phaseStructureFactors.get(phase); if (structureFactors == null) { structureFactors = new double[4][numberOfReflections]; phaseStructureFactors.put(phase, structureFactors); // System.out.println("Resetting structure factors"); resetStructureFactors(phase); } else if (structureFactors[0].length != numberOfReflections) { // System.out.println("Problem here, to be implemented"); // System.out.println("Updating structure factors"); double[][] newStructureFactors = new double[4][numberOfReflections]; updateStructureFactorsFromTo(phase, structureFactors, newStructureFactors); phaseStructureFactors.remove(phase); phaseStructureFactors.put(phase, newStructureFactors); // resetStructureFactors(phase); } reloadScatteringFactors(phase); /* double[][][][] scatFactors = phaseScatFactors.get(phase); int linesCount = 1; // todo, should be this in the end: getInstrument().getRadiationType().getLinesCount(); if (scatFactors == null) { scatFactors = new double[numberOfReflections][linesCount][phase.getFullAtomList().size()][2]; phaseScatFactors.put(phase, scatFactors); reloadScatteringFactors(phase); } else if (scatFactors.length != numberOfReflections || (scatFactors.length > 0 && scatFactors[0].length != linesCount) || (scatFactors.length > 0 && scatFactors[0].length > 0 && scatFactors[0][0].length != phase.getFullAtomList().size()) || resetScatFactors) { phaseScatFactors.remove(phase); scatFactors = new double[numberOfReflections][linesCount][phase.getFullAtomList().size()][2]; phaseScatFactors.put(phase, scatFactors); reloadScatteringFactors(phase); }*/ for (int i = 0; i < activedatafilesnumber(); i++) { getActiveDataFile(i).refreshIndices(phase); } } private void updateStructureFactorsFromTo(Phase phase, double[][] structureFactors, double[][] newStructureFactors) { int numberOfReflections = phase.gethklNumber(); for (int i = 0; i < numberOfReflections; i++) { Reflection refl = phase.getReflex(i); int reflID = Reflection.getUniqueIdFor(refl.getH(), refl.getK(), refl.getL()); boolean stop = false; int incr = 0; int index = i; if (index < structureFactors[3].length && reflID == structureFactors[3][index]) stop = true; while (!stop) { index = i + incr; boolean outOfRange = true; if (index < structureFactors[3].length) { outOfRange = false; if (reflID == structureFactors[3][index]) stop = true; } index = i - incr; if (index >= 0 && index < structureFactors[3].length) { outOfRange = false; if (reflID == structureFactors[3][index]) stop = true; } if (outOfRange && incr > 10) { stop = true; index = -1; } incr++; } if (index >=0) { for (int j = 0; j < 4; j++) { newStructureFactors[j][i] = structureFactors[j][index]; } } else { newStructureFactors[0][i] = Constants.STARTING_STRUCTURE_FACTOR * Constants.STARTING_STRUCTURE_FACTOR; newStructureFactors[1][i] = -1.0; newStructureFactors[2][i] = 0.0; newStructureFactors[3][i] = reflID; } } } static boolean checkHKL = true; private void resetStructureFactors(Phase phase) { double[][] structureFactors = getStructureFactors(phase); if (structureFactors != null && structureFactors.length != 0) { // System.out.println("resetting exp structure factors"); int phaseIndex = getSample().getPhaseIndex(phase); if (needRestore != null && phaseIndex < needRestore.length && needRestore[phaseIndex]) { // System.out.println("Loading structure factors"); for (int i1 = 0; i1 < structureFactors[0].length; i1++) { structureFactors[0][i1] = Constants.STARTING_STRUCTURE_FACTOR * Constants.STARTING_STRUCTURE_FACTOR; structureFactors[1][i1] = -1.0; structureFactors[2][i1] = 0.0; Reflection refl = phase.getReflex(i1); structureFactors[3][i1] = Reflection.getUniqueIdFor(refl.getH(), refl.getK(), refl.getL()); } int h = -1, k = -1, l = -1; if (phaseIndex >= 0) { Vector[] tmpVector = (Vector[]) overallVector.elementAt(phaseIndex); int hklNumber = Math.min(tmpVector[0].size(), phase.gethklNumber()); for (int j = 0; j < hklNumber; j++) { boolean check = true; int index = j; Reflection refl = phase.getReflectionVector().elementAt(j); if (checkHKL) { h = (int) ((double[]) tmpVector[0].elementAt(j))[0]; if (refl.getH() != h) check = false; k = (int) ((double[]) tmpVector[1].elementAt(j))[0]; if (refl.getK() != k) check = false; l = (int) ((double[]) tmpVector[2].elementAt(j))[0]; if (refl.getL() != l) check = false; } if (!check) { int delta = 1; while (!check && ((j - delta) >= 0 || (j + delta) < hklNumber)) { if ((j - delta) >= 0) { check = true; index = j - delta; h = (int) ((double[]) tmpVector[0].elementAt(index))[0]; if (refl.getH() != h) check = false; k = (int) ((double[]) tmpVector[1].elementAt(index))[0]; if (refl.getK() != k) check = false; l = (int) ((double[]) tmpVector[2].elementAt(index))[0]; if (refl.getL() != l) check = false; } if (!check && (j + delta) < hklNumber) { check = true; index = j + delta; h = (int) ((double[]) tmpVector[0].elementAt(index))[0]; if (refl.getH() != h) check = false; k = (int) ((double[]) tmpVector[1].elementAt(index))[0]; if (refl.getK() != k) check = false; l = (int) ((double[]) tmpVector[2].elementAt(index))[0]; if (refl.getL() != l) check = false; } delta++; } } if (check) { if (j < tmpVector[3].size()) structureFactors[0][j] = ((double[]) tmpVector[3].elementAt(index))[0]; if (j < tmpVector[4].size()) structureFactors[1][j] = ((double[]) tmpVector[4].elementAt(index))[0]; if (j < tmpVector[5].size()) structureFactors[2][j] = ((double[]) tmpVector[5].elementAt(index))[0]; structureFactors[3][j] = Reflection.getUniqueIdFor(refl.getH(), refl.getK(), refl.getL()); } else out.println("Reflection: " + h + "," + k + "," + l + " not corresponding on loading structure factors"); } } needRestore[phaseIndex] = false; } else { for (int i1 = 0; i1 < structureFactors[0].length; i1++) { structureFactors[0][i1] = Constants.STARTING_STRUCTURE_FACTOR * Constants.STARTING_STRUCTURE_FACTOR; structureFactors[1][i1] = -1.0; structureFactors[2][i1] = 0.0; Reflection refl = phase.getReflectionVector().elementAt(i1); structureFactors[3][i1] = Reflection.getUniqueIdFor(refl.getH(), refl.getK(), refl.getL()); } } } } public void storeComputedStructureFactors(Phase phase, double[] fhkl) { double[][] structureFactors = phaseStructureFactors.get(phase); arraycopy(fhkl, 0, structureFactors[1], 0, structureFactors[0].length); } public void storeExperimentalStructureFactors(Phase phase, double[] fhkl) { double[][] structureFactors = phaseStructureFactors.get(phase); arraycopy(fhkl, 0, structureFactors[0], 0, structureFactors[0].length); } public void storeComputedOverExperimentalStructureFactors() { Sample sample = getSample(); for (int i = 0; i < sample.numberOfPhases; i++) storeComputedOverExperimentalStructureFactors(sample.getPhase(i)); } public void storeComputedOverExperimentalStructureFactors(Phase phase) { double[][] structureFactors = phaseStructureFactors.get(phase); arraycopy(structureFactors[1], 0, structureFactors[0], 0, structureFactors[0].length); } public void storeExperimentalOverComputedStructureFactors() { Sample sample = getSample(); for (int i = 0; i < sample.numberOfPhases; i++) storeExperimentalOverComputedStructureFactors(sample.getPhase(i)); } public void storeExperimentalOverComputedStructureFactors(Phase phase) { double[][] structureFactors = phaseStructureFactors.get(phase); arraycopy(structureFactors[0], 0, structureFactors[1], 0, structureFactors[0].length); } public double[][] getStructureFactors(Phase phase) { return phaseStructureFactors.get(phase); } public void reloadScatteringFactors(Phase phase) { Vector<AtomSite> atoms = phase.getFullAtomList(); int atomsNumber = atoms.size(); int numberofpeaks = phase.gethklNumber() + 1; int linesCount = 1; // todo, should be this in the end: getInstrument().getRadiationType().getLinesCount(); double[][][][] scatFactors = phaseScatFactors.get(phase); if (scatFactors == null) { scatFactors = new double[numberofpeaks][linesCount][atomsNumber][2]; phaseScatFactors.put(phase, scatFactors); } else if (scatFactors.length != numberofpeaks || (scatFactors.length > 0 && scatFactors[0].length != linesCount) || (scatFactors.length > 0 && scatFactors[0].length > 0 && scatFactors[0][0].length != atomsNumber)) { phaseScatFactors.remove(phase); scatFactors = new double[numberofpeaks][linesCount][atomsNumber][2]; phaseScatFactors.put(phase, scatFactors); } double[] fu = new double[2]; // boolean isXray = !rad1.isElectron() && !rad1.isNeutron(); for (int j = 0; j < linesCount; j++) { Radiation rad1 = getInstrument().getRadiationType().getRadiation(j); // double lambda = getInstrument().getRadiationType().getRadiationWavelength(j); // double energyInKeV = Constants.ENERGY_LAMBDA / lambda * 0.001; fu[0] = 0; fu[1] = 0; for (int ato = 0; ato < atomsNumber; ato++) { AtomSite atom = atoms.elementAt(ato); double[] scatteringFactors = atom.scatfactor(0, rad1); scatFactors[0][j][ato][0] = scatteringFactors[0] + fu[0]; scatFactors[0][j][ato][1] = scatteringFactors[1] + fu[1]; for (int kj = 1; kj < numberofpeaks; kj++) { Reflection refl = phase.getReflex(kj - 1); scatteringFactors = atom.scatfactor(refl.d_space, rad1); scatFactors[kj][j][ato][0] = scatteringFactors[0] + fu[0]; scatFactors[kj][j][ato][1] = scatteringFactors[1] + fu[1]; } } } } public double[][][][] getScatteringFactor(Phase phase) { return phaseScatFactors.get(phase); } public void removingPhase(Phase phase) { phaseScatFactors.remove(phase); phaseStructureFactors.remove(phase); for (int i = 0; i < datafilesnumber(); i++) getDataFile(i).removingPhase(phase); } public void writeCustomObject(BufferedWriter out) { Sample asample = getFilePar().getActiveSample(); if (getFilePar().compactSavingStructureFactors()) // we do not save the structure factors in compact saving return; try { out.newLine(); out.write("#custom_object_" + "Fhkl"); out.newLine(); for (int i = 0; i < asample.phasesNumber(); i++) { Phase phase = asample.getPhase(i); String blockID = "phase_" + phase.toXRDcatString(); CIFDataBlock.writeBlockDecl(out, blockID, this); out.newLine(); out.write(CIFdictionary.loopDecl); out.newLine(); out.write(CIFdictionary.refln_h + " "); out.write(CIFdictionary.refln_k + " "); out.write(CIFdictionary.refln_l + " "); out.write(CIFdictionary.refln_FsquaredMeas + " "); out.write(CIFdictionary.refln_FsquaredCalc + " "); out.write(CIFdictionary.refln_FsquaredEsd + " "); out.newLine(); // String waveS = Fmt.format(wave[i]); int numberReflections = phase.gethklNumber(); double[][] structureFactors = phaseStructureFactors.get(phase); if (structureFactors != null) { for (int j = 0; j < numberReflections && j < structureFactors[0].length; j++) { Reflection refl = phase.getReflex(j); out.write(refl.getH() + " " + refl.getK() + " " + refl.getL() + " " + Fmt.format(structureFactors[0][j]) + " " + Fmt.format(structureFactors[1][j]) + " " + Fmt.format(structureFactors[2][j])); out.newLine(); } out.newLine(); } } out.newLine(); out.write("#end_custom_object_" + "Fhkl"); out.newLine(); out.newLine(); } catch (IOException ioe) { System.out.println("Error in writing the structure factors for " + toXRDcatString()); ioe.printStackTrace(); try { out.newLine(); out.write("#end_custom_object_" + "Fhkl"); out.newLine(); out.newLine(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } } public void readCustomObject(CIFtoken ciffile) { // to be override by subclasses // the default read and do nothing int newtoken, tokentype; // XRDcat theobj = null; boolean endofInput = false; int hklindex = 0, phaseindex = 0, cifentry = 0, tmpVindex = 0; int[] cifindex = new int[6]; Vector cifVector = new Vector(0, 1); Vector[] tmpVector = null; overallVector = new Vector(0, 1); boolean newLoop = false; boolean startLoop = false; int maxCIFentries = 6; try { do { tokentype = ciffile.nextToken(); switch (tokentype) { case CIFtoken.TT_DATA: case CIFtoken.TT_PHASE: if (tmpVector != null) { overallVector.addElement(tmpVector); } // phaseindex++; tmpVindex = 0; tmpVector = null; cifVector = new Vector(0, 1); cifentry = 0; newLoop = false; break; case CIFtoken.TT_CIFE: // CIF item cifVector.addElement(ciffile.thestring); break; case CIFtoken.TT_LOOP: // start the loop for the values here newLoop = true; startLoop = true; break; case CIFtoken.TT_NUMBER: if (!newLoop) break; if (startLoop) { cifindex = new int[cifVector.size()]; tmpVindex = 0; for (int i = 0; i < cifVector.size(); i++) { String thecife = (String) cifVector.elementAt(i); if (thecife.equalsIgnoreCase(CIFdictionary.refln_h)) { cifindex[i] = 0; tmpVindex++; } else if (thecife.equalsIgnoreCase(CIFdictionary.refln_k)) { cifindex[i] = 1; tmpVindex++; } else if (thecife.equalsIgnoreCase(CIFdictionary.refln_l)) { cifindex[i] = 2; tmpVindex++; } else if (thecife.equalsIgnoreCase(CIFdictionary.refln_FsquaredMeas)) { cifindex[i] = 3; tmpVindex++; } else if (thecife.equalsIgnoreCase(CIFdictionary.refln_FsquaredCalc)) { cifindex[i] = 4; tmpVindex++; } else if (thecife.equalsIgnoreCase(CIFdictionary.refln_FsquaredEsd)) { cifindex[i] = 5; tmpVindex++; }else cifindex[i] = -1; } startLoop = false; cifVector.removeAllElements(); } if (tmpVector == null) { tmpVector = new Vector[maxCIFentries]; for (int i = 0; i < maxCIFentries; i++) tmpVector[i] = new Vector(0, 10); } if (cifindex[cifentry] >= 0) { double[] value = new double[1]; value[0] = ciffile.thevalue; tmpVector[cifindex[cifentry]].addElement(value); } cifentry++; if (cifentry == tmpVindex) cifentry = 0; break; case CIFtoken.TT_CUSTOM_END: if (tmpVector != null) { overallVector.addElement(tmpVector); } endofInput = true; break; default: { } } } while (tokentype != CIFtoken.TT_EOF && !endofInput); // System.out.println("Custom object loaded!"); if (overallVector.size() > 0) { needRestore = new boolean[overallVector.size()]; for (int i = 0; i < overallVector.size(); i++) needRestore[i] = true; } else needRestore = null; // notLoaded = false; } catch (IOException ioe) { out.println("IO exception in custom object for " + toXRDcatString()); } /* if (theobj != null) theobj.readall(ciffile);*/ } public void SumDatafileOutput(Frame aframe) { int datanumber = 0; double[] xcoord = null; double[] intensity = null; String filename = Utility.openFileDialog(aframe, "Save summed datafile as (CIF file)", FileDialog.SAVE, getFilePar().getDirectory(), null, "put a name (with extension).cif"); if (filename == null) return; String[] folderAndName = Misc.getFolderandName(filename); String folder = folderAndName[0]; filename = folderAndName[1]; if (!filename.endsWith(".cif")) filename += ".cif"; // int numberOfFilesTotal = 0; DiffrDataFile[] datafiles = getSelectedDataFiles(); if (datafiles == null) { (new AttentionD(new Frame(), "No item from the list selected!")).setVisible(true); return; } double[][] dataToExport = DataFileSet.getSummedExperimentalComputedData(datafiles, 0); int ylength = datafiles.length; BufferedWriter output = Misc.getWriter(folder, filename); try { double[] meanAngles = new double[DiffrDataFile.maxAngleNumber]; for (int ib = 0; ib < DiffrDataFile.maxAngleNumber; ib++) meanAngles[ib] = 0; boolean energyDispersive = false; for (int i = 0; i < ylength; i++) { if (datafiles[i].energyDispersive) energyDispersive = true; double[] tilt = datafiles[i].getTiltingAngle(); // if (i == 0) firstTilt = tilt; for (int ib = 0; ib < DiffrDataFile.maxAngleNumber; ib++) meanAngles[ib] += tilt[ib] / ylength; } if (energyDispersive) output.write("_pd_meas_scan_method disp"); output.newLine(); output.write("_pd_meas_number_of_points " + Integer.toString(dataToExport[0].length)); output.newLine(); /* if (tmpdatafile.originalNotCalibrated) { output.write("_riet_meas_datafile_calibrated false"); output.newLine(); }*/ output.newLine(); for (int ib = 0; ib < DiffrDataFile.maxAngleNumber; ib++) { // if (verifySameAngles[ib]) { output.write(DiffrDataFile.diclistc[ib + 1] + ' '); output.write(Fmt.format(meanAngles[ib])); output.newLine(); } output.write(DiffrDataFile.diclistc[7] + ' '); output.write(datafiles[0].getString(7)); output.newLine(); output.newLine(); output.write("loop_"); output.newLine(); output.write(datafiles[0].getCIFXcoord()); output.newLine(); output.write(DiffrDataFile.intensityCalcCIFstring); output.newLine(); for (int i = 0; i < dataToExport[0].length; i++) { output.write(' ' + Fmt.format(dataToExport[0][i]) + ' ' + Fmt.format(dataToExport[1][i])); output.newLine(); } } catch (Exception io) { } try { output.flush(); output.close(); } catch (IOException io) { } } public void sumDatafileOutput(Frame aframe, int selectedIndex, double angle_range) { int datanumber = 0; double[] xcoord = null; double[] intensity = null; double angleRange = Math.abs(2 * angle_range); String filename = Utility.openFileDialog(aframe, "Save summed datafile as (.esg extension mandatory)", FileDialog.SAVE, getFilePar().getDirectory(), null, "put a name (with extension).esg"); if (filename == null) return; String[] folderAndName = Misc.getFolderandName(filename); String folder = folderAndName[0]; filename = folderAndName[1]; DiffrDataFile tmpdatafile = null; Vector datafiles = getSelectedDatafiles(); int datafilenumber = datafiles.size(); if (datafilenumber == 0) { (new AttentionD(new Frame(), "No selected items in the list")).setVisible(true); return; } Vector<DiffrDataFile> datafileOrdered = new Vector<>(datafilenumber, 10); for (int i = 0; i < datafilenumber; i++) { tmpdatafile = (DiffrDataFile) datafiles.elementAt(i); datafileOrdered.add(tmpdatafile); } Collections.sort(datafileOrdered, new AngleComparator(selectedIndex)); Vector<Vector<DiffrDataFile>> datafileTable = new Vector<>(); double startingAngle = datafileOrdered.elementAt(0).getTiltingAngle()[selectedIndex]; double maxAngle = datafileOrdered.elementAt(datafilenumber - 1).getTiltingAngle()[selectedIndex]; double angle = startingAngle; int index = 0; int groupIndex = 0; while (angle < maxAngle && index < datafilenumber) { double nextAngle = angle + angleRange; boolean nextGroup = false; Vector<DiffrDataFile> datalist = new Vector<>(); while (index < datafilenumber && !nextGroup) { double actualAngle = datafileOrdered.elementAt(index).getTiltingAngle()[selectedIndex]; // System.out.println(index + " " + angle + " " + nextAngle + " " + actualAngle); if (actualAngle >= angle && actualAngle <= nextAngle) { datalist.add(datafileOrdered.elementAt(index++)); } else { nextGroup = true; } } if (datalist.size() > 0) datafileTable.add(datalist); angle = nextAngle; } BufferedWriter output = Misc.getWriter(folder, filename); int groupfilenumber = datafileTable.size(); for (int ij = 0; ij < groupfilenumber; ij++) { Vector<DiffrDataFile> datalist = datafileTable.elementAt(ij); try { boolean first = true; boolean energyDispersive = false; boolean useCountTimeToScale = false; datafilenumber = datalist.size(); double[] meanAngle = new double[DiffrDataFile.maxAngleNumber]; double countingTime = 0; for (int k = 0; k < DiffrDataFile.maxAngleNumber; k++) meanAngle[k] = 0; for (int j = 0; j < datafilenumber; j++) { for (int k = 0; k < DiffrDataFile.maxAngleNumber; k++) meanAngle[k] += datalist.elementAt(j).getTiltingAngle()[k]; if (datalist.elementAt(j).useCountTimeToScale()) useCountTimeToScale = true; countingTime += datalist.elementAt(j).getCountTimeValue(); } for (int k = 0; k < DiffrDataFile.maxAngleNumber; k++) meanAngle[k] /= datafilenumber; for (int i = 0; i < datafilenumber; i++) { tmpdatafile = datalist.elementAt(i); if (tmpdatafile.energyDispersive) energyDispersive = true; if (first) { first = false; datanumber = tmpdatafile.finalindex - tmpdatafile.startingindex; xcoord = new double[datanumber]; intensity = new double[datanumber]; for (int j = tmpdatafile.startingindex; j < tmpdatafile.finalindex; j++) { xcoord[j - tmpdatafile.startingindex] = tmpdatafile.getXDataOriginal(j); intensity[j - tmpdatafile.startingindex] = tmpdatafile.getYData(j); } } else { for (int j = tmpdatafile.startingindex; j < tmpdatafile.finalindex; j++) { intensity[j - tmpdatafile.startingindex] += tmpdatafile.getYData(j); } } } for (int j = tmpdatafile.startingindex; j < tmpdatafile.finalindex; j++) { intensity[j - tmpdatafile.startingindex] /= countingTime; } output.write("_pd_block_id " + tmpdatafile.toString()); output.newLine(); output.newLine(); output.write("_pd_meas_number_of_points " + Integer.toString(datanumber)); output.newLine(); output.write("_riet_meas_datafile_calibrated false"); output.newLine(); output.write(DiffrDataFile.diclistc[DiffrDataFile.countingTimeValueID] + " "); output.write(Fmt.format(1)); useCountTimeToScale = false; output.newLine(); if (energyDispersive) { output.write(DiffrDataFile.pd_meas_scan_method + " disp"); output.newLine(); } if (useCountTimeToScale) { output.write(DiffrDataFile.diclistc[DiffrDataFile.useCountTimeToScaleID] + " true"); output.newLine(); } output.newLine(); for (int ib = 0; ib < DiffrDataFile.maxAngleNumber; ib++) { output.write(DiffrDataFile.diclistc[ib + 1] + ' '); output.write(Fmt.format(meanAngle[ib])); output.newLine(); } // output.write(DiffrDataFile.diclistc[7] + ' '); // output.write(tmpdatafile.getString(7)); // output.newLine(); output.newLine(); output.write("loop_"); output.newLine(); if (energyDispersive) { output.write(DiffrDataFile.pd_meas_counts_total); output.newLine(); for (int i = 0; i < datanumber; i++) { output.write(Fmt.format(intensity[i])); output.newLine(); } output.newLine(); } else { output.write(tmpdatafile.getCIFXcoord()); output.newLine(); output.write(DiffrDataFile.intensityCalcCIFstring); output.newLine(); for (int i = 0; i < datanumber; i++) { output.write(' ' + Fmt.format(xcoord[i]) + ' ' + Fmt.format(intensity[i])); output.newLine(); } output.newLine(); } } catch (IOException ignored) { } // datalist.removeAllElements(); // datalist = null; } try { output.flush(); output.close(); } catch (IOException ignored) { } datafileTable.removeAllElements(); datafileOrdered.removeAllElements(); // datafileTable = null; } public void SumDatafileOutput(Frame aframe, boolean[] sameAngle, double[] angle, boolean nativeFormat) { int datanumber = 0; double[] xcoord = null; double[] intensity = null; double[] angleRange = MoreMath.abs(angle); String filenameTemplate = "put a name (with extension).cif"; if (nativeFormat) filenameTemplate = "put a name with proper extension"; String filename = Utility.openFileDialog(aframe, "Save summed datafile as ", FileDialog.SAVE, getFilePar().getDirectory(), null, filenameTemplate); if (filename == null) return; String[] folderAndName = Misc.getFolderandName(filename); String folder = folderAndName[0]; filename = folderAndName[1]; if (!nativeFormat && filename.endsWith(".cif")) filename = filename.substring(0, filename.length() - 4); DiffrDataFile tmpdatafile = null; int datafilenumber = datafilesnumber(); if (datafilenumber == 0) { (new AttentionD(new Frame(), "No items in the list")).setVisible(true); return; } Vector<double[]> angles = new Vector<>(10, 10); Vector<Vector<DiffrDataFile>> datafileTable = new Vector<>(10, 10); int check; // boolean[] alreadyPickedUp = new boolean[datafilenumber]; // for (int i = 0; i < datafilenumber; i++) // alreadyPickedUp[i] = false; for (int i = 0; i < datafilenumber; i++) { tmpdatafile = getDataFile(i); if (tmpdatafile.getComputePermission()) { double[] tilt = tmpdatafile.getTiltingAngle(); check = getAnglesPosition(angles, tilt, sameAngle, angleRange); if (check == -1) { angles.addElement(tilt); Vector<DiffrDataFile> datalist = new Vector<>(0, 1); datalist.addElement(tmpdatafile); datafileTable.addElement(datalist); } else { Vector<DiffrDataFile> datalist = datafileTable.elementAt(check); datalist.addElement(tmpdatafile); } } } int groupfilenumber = datafileTable.size(); StringBuilder groupfilename = new StringBuilder(""); groupfilename.append(filename); groupfilename.append("Group.cif"); BufferedWriter groupoutput = null; try { groupoutput = Misc.getWriter(folder, groupfilename.toString()); groupoutput.write("loop_"); groupoutput.newLine(); groupoutput.write(diclistc[totsubordinate + 2]); groupoutput.newLine(); } catch (IOException ignored) { } boolean[] verifySameAngles = new boolean[sameAngle.length]; double[] meanAngles = new double[angle.length]; for (int ij = 0; ij < groupfilenumber; ij++) { Vector<DiffrDataFile> datalist = datafileTable.elementAt(ij); StringBuilder newfilename = new StringBuilder(""); newfilename.append(filename); BufferedWriter output = null; try { boolean first = true; boolean energyDispersive = false; datafilenumber = datalist.size(); for (int ib = 0; ib < sameAngle.length; ib++) verifySameAngles[ib] = true; double[] firstTilt = null; int bank = 0; int bankFirst = 0; for (int i = 0; i < datafilenumber; i++) { tmpdatafile = datalist.elementAt(i); if (tmpdatafile.energyDispersive) energyDispersive = true; double[] tilt = tmpdatafile.getTiltingAngle(); bank = tmpdatafile.getBankNumber(); if (i == 0) { firstTilt = tilt; arraycopy(tilt, 0, meanAngles, 0, sameAngle.length); bankFirst = bank; } int ib; for (ib = 0; ib < sameAngle.length - 1; ib++) if (!(tilt[ib] >= firstTilt[ib] - angleRange[ib] && tilt[ib] <= firstTilt[ib] + angleRange[ib])) verifySameAngles[ib] = false; if (bank != bankFirst) verifySameAngles[ib] = false; if (first) { for (int j = 0; j < sameAngle.length - 1; j++) if (sameAngle[j]) newfilename.append('_').append(Integer.toString((int) tilt[j])); if (nativeFormat) newfilename.append(tmpdatafile.identifier); else newfilename.append(".cif"); groupoutput.write(" '" + newfilename + '\''); groupoutput.newLine(); first = false; output = Misc.getWriter(folder, newfilename.toString()); datanumber = tmpdatafile.finalindex - tmpdatafile.startingindex; xcoord = new double[datanumber]; intensity = new double[datanumber]; for (int j = tmpdatafile.startingindex; j < tmpdatafile.finalindex; j++) { xcoord[j - tmpdatafile.startingindex] = tmpdatafile.getXDataForCalibration(j); intensity[j - tmpdatafile.startingindex] = tmpdatafile.getYData(j); } } else { for (int kj = 0; kj < sameAngle.length; kj++) meanAngles[kj] += tilt[kj]; for (int j = tmpdatafile.startingindex; j < tmpdatafile.finalindex; j++) { intensity[j - tmpdatafile.startingindex] += tmpdatafile.getYData(j); } } } output.write("_pd_meas_number_of_points " + Integer.toString(datanumber)); output.newLine(); output.write("_riet_meas_datafile_calibrated false"); output.newLine(); if (energyDispersive) { output.write("_pd_meas_scan_method disp"); output.newLine(); } output.newLine(); for (int ib = 0; ib < sameAngle.length; ib++) { if (verifySameAngles[ib]) { output.write(DiffrDataFile.diclistc[ib + 1] + ' '); output.write(Fmt.format(meanAngles[ib] / datafilenumber)); output.newLine(); } } output.write(DiffrDataFile.diclistc[7] + ' '); output.write(tmpdatafile.getString(7)); output.newLine(); output.newLine(); output.write("loop_"); output.newLine(); output.write(tmpdatafile.getCIFXcoord()); output.newLine(); output.write(DiffrDataFile.intensityCalcCIFstring); output.newLine(); for (int i = 0; i < datanumber; i++) { output.write(' ' + Fmt.format(xcoord[i]) + ' ' + Fmt.format(intensity[i] / datafilenumber)); output.newLine(); } } catch (IOException ignored) { } try { output.flush(); output.close(); } catch (IOException ignored) { } datalist.removeAllElements(); // datalist = null; } try { groupoutput.flush(); groupoutput.close(); } catch (IOException ignored) { } datafileTable.removeAllElements(); // datafileTable = null; } private boolean checkAngle(double v, double v1, double v2) { return v >= v1 - v2 && v <= v1 + v2; } public int getAnglesPosition(Vector<double[]> angles, double[] tilt, boolean[] sameAngle, double[] rangeAngles) { int size = angles.size(); double[] angle; for (int i = 0; i < size; i++) { angle = angles.elementAt(i); boolean check = true; for (int j = 0; j < sameAngle.length; j++) if (sameAngle[j] && !checkAngle(tilt[j], angle[j], rangeAngles[j])) check = false; if (check) return i; } return size - 1; } public void mergeReflectivityDatafile(Frame aframe) { int datanumber; // double[] xcoord = null; // double[] intensity = null; String filename = Utility.openFileDialog(aframe, "Save merge reflectivity datafile as (*.cif)", FileDialog.SAVE, getFilePar().getDirectory(), null, "put a name.cif"); if (filename == null) return; String[] folderAndName = Misc.getFolderandName(filename); String folder = folderAndName[0]; filename = folderAndName[1]; if (!filename.endsWith(".cif")) filename += ".cif"; // int numberOfFilesTotal = 0; Vector datafiles = getSelectedDatafiles(); if (datafiles == null || datafiles.size() <= 1) { (new AttentionD(new Frame(), "No more than 1 item from the list selected!")).setVisible(true); return; } int datafilenumber = datafiles.size(); BufferedWriter output = Misc.getWriter(folder, filename); try { // check order DiffrDataFile datafile; int datafound = 0; double startingangle = 200.0; int actualdata = 0; for (int i = 0; i < datafilenumber; i++) { datafile = (DiffrDataFile) datafiles.elementAt(i); double angle = datafile.getXData(datafile.startingindex); if (angle < startingangle) { actualdata = i; startingangle = angle; } } Misc.swapVectorElements(datafiles, 0, actualdata); datafound++; while (datafound < datafilenumber) { double actualangle = 200.0; actualdata = datafound; for (int i = datafound; i < datafilenumber; i++) { datafile = (DiffrDataFile) datafiles.elementAt(i); double angle = datafile.getXData(datafile.startingindex); if (angle < actualangle) { actualdata = i; actualangle = angle; } } Misc.swapVectorElements(datafiles, datafound++, actualdata); } // finish ordering // check overlapping datafile = (DiffrDataFile) datafiles.elementAt(0); double angle1 = datafile.getXData(datafile.finalindex - 1); for (int i = 1; i < datafilenumber; i++) { datafile = (DiffrDataFile) datafiles.elementAt(i); double angle2 = datafile.getXData(datafile.startingindex); if (datafile.measurementstep == 0.0) datafile.measurementstep = Math.abs(datafile.getXData(datafile.startingindex + 1) - angle2); double angletocheck; if (i == 1) angletocheck = angle1 + 0.000001; else angletocheck = angle1 + datafile.measurementstep + 0.000001; if (angle2 > angletocheck) { (new AttentionD(new Frame(), "Improper alignement or overlapping of data!")).setVisible(true); return; } angle1 = datafile.getXData(datafile.finalindex - 1); } // merging files datafile = (DiffrDataFile) datafiles.elementAt(0); startingangle = datafile.getXData(datafile.startingindex); DiffrDataFile datafile2 = (DiffrDataFile) datafiles.elementAt(datafilenumber - 1); Vector<double[]> data = new Vector<double[]>(0, 100); // computing attenuator factor double attenuatorfactor = 1.0; int index2 = 0; for (int i = 1; i < datafilenumber; i++) { datafile = (DiffrDataFile) datafiles.elementAt(i - 1); datafile2 = (DiffrDataFile) datafiles.elementAt(i); double attenuatorfactor1 = 0.0; double attenuatorfactor2 = 0.0; int dataindex = datafile.startingindex; double startingAngle2 = datafile2.getXData(datafile2.startingindex); double actualAngle = datafile.getXData(dataindex); while (actualAngle < startingAngle2 - 0.000001) { double[] xdata = new double[2]; xdata[0] = actualAngle; xdata[1] = datafile.getYData(dataindex) * attenuatorfactor; data.addElement(xdata); actualAngle = datafile.getXData(++dataindex); // wgt.addItem(datafile.getWeight(index++)); } int pauseIndex = dataindex; index2 = datafile2.startingindex; while (dataindex < datafile.finalindex) { attenuatorfactor1 += datafile.getYData(dataindex++) * attenuatorfactor; attenuatorfactor2 += datafile2.getYData(index2++); } double newattenuatorfactor = attenuatorfactor1 / attenuatorfactor2; dataindex = pauseIndex; index2 = datafile2.startingindex; while (dataindex < datafile.finalindex) { double[] xdata = new double[2]; xdata[1] = (datafile.getYData(dataindex) * attenuatorfactor + datafile2.getYData(index2) * newattenuatorfactor) / 2.0; if (datafile.getXData(dataindex) != datafile2.getXData(index2)) out.println("Different: " + datafile.getXData(dataindex) + ' ' + datafile2.getXData(index2)); xdata[0] = (datafile.getXData(dataindex++) + datafile2.getXData(index2++)) / 2.0; data.addElement(xdata); } attenuatorfactor = newattenuatorfactor; } while (index2 < datafile2.finalindex) { double[] xdata = new double[2]; xdata[0] = datafile2.getXData(index2); xdata[1] = datafile2.getYData(index2) * attenuatorfactor; data.addElement(xdata); index2++; // wgt.addItem(datafile2.getWeight(index2++)); } datanumber = data.size(); output.write("_pd_meas_number_of_points " + Integer.toString(datanumber)); output.newLine(); datafile = (DiffrDataFile) datafiles.elementAt(0); output.write("_riet_meas_datafile_calibrated false"); output.newLine(); output.newLine(); double[] tilt = datafile.getTiltingAngle(); for (int ib = 0; ib < tilt.length; ib++) { output.write(DiffrDataFile.diclistc[ib + 1] + ' '); output.write(Fmt.format(tilt[ib])); output.newLine(); } output.newLine(); output.write("loop_"); output.newLine(); output.write(datafile.getCIFXcoord()); output.newLine(); output.write(DiffrDataFile.intensityCalcCIFstring); output.newLine(); for (int i = 0; i < datanumber; i++) { double[] xdata = data.elementAt(i); output.write(' ' + Fmt.format(xdata[0]) + ' ' + Fmt.format(xdata[1])); output.newLine(); } } catch (IOException ignored) { } try { output.flush(); output.close(); } catch (IOException ignored) { } } public void addAdditionalBackgroundToSelected() { DiffrDataFile[] datafiles = getSelectedDataFiles(); if (datafiles != null) for (DiffrDataFile datafile : datafiles) datafile.addBackgroundParameter(); } public void removeAdditionalBackgroundToSelected() { DiffrDataFile[] datafiles = getSelectedDataFiles(); if (datafiles != null) for (DiffrDataFile datafile : datafiles) datafile.removeAllBackgroundParameters(); } public void addAdditionalShiftToSelected() { DiffrDataFile[] datafiles = getSelectedDataFiles(); if (datafiles != null) for (DiffrDataFile datafile : datafiles) datafile.addShiftParameter(); } public void removeAdditionalShiftToSelected() { DiffrDataFile[] datafiles = getSelectedDataFiles(); if (datafiles != null) for (DiffrDataFile datafile : datafiles) datafile.removeAllShiftParameters(); } /** * Bound all parameters of selected spectra to the first selected. */ public void boundSelectedSpectra() { DiffrDataFile[] datafiles = getSelectedDataFiles(); if (datafiles != null) for (int i = 1; i < datafiles.length; i++) datafiles[i].setEqualTo(datafiles[0], true); } public void addAdditionalBackgroundToAll() { int datafilenumber = datafilesnumber(); for (int i = 0; i < datafilenumber; i++) getDataFile(i).addBackgroundParameter(); } public void removeDatafile(DiffrDataFile datafile) { int datafilenumber = datafilesnumber(); for (int i = 0; i < datafilenumber; i++) { DiffrDataFile tmpdatafile = getDataFile(i); if (tmpdatafile == datafile) { removeDataFile(i); i = datafilenumber; } } // updateStringtoDoubleBuffering(); } public Sample getSample() { return (Sample) getParent(); } public double[] getAdditionalSampleAngles() { return sample_angles; } public double[] getDisalignementAngles() { return disalignement_angles; } public double[] getDisplacementErrors() { return displacement_errors; } int actualIndex; public int getDataFileSetIndex() { return actualIndex; } public void setDataFileSetIndex(int value) { actualIndex = value; } public String getMinRange() { return getString(minRangeID); } public void setMinRange(String value) { setString(minRangeID, value); } public String getMaxRange() { return getString(maxRangeID); } public void setMaxRange(String value) { setString(maxRangeID, value); } public double getMinRangeD() { return Double.valueOf(getMinRange()); } public double getMaxRangeD() { return Double.valueOf(getMaxRange()); } public void setLorentzRestricted(String avalue) { setString(lorentzRestrictedID, avalue); } public void setLorentzRestricted(boolean avalue) { if (avalue) setLorentzRestricted("true"); else setLorentzRestricted("false"); } public String getLorentzRestricted() { return getString(lorentzRestrictedID); } public boolean isLorentzRestricted() { return getLorentzRestricted().equals("true"); } public void setEnabled(String avalue) { setString(enabledID, avalue); } public void setEnabled(boolean avalue) { if (avalue) setEnabled("true"); else setEnabled("false"); enabled = isEnabled(); Sample asample = (Sample) getParent(); asample.checkActiveDataSets(); // todo only temporarly, fix in the computation asample.refreshDataIndices(); // System.out.println(toXRDcatString() + " enabled"); } public String getEnabled() { return getString(enabledID); } public boolean isEnabled() { return getEnabled().equals("true"); } public boolean enabled() { return enabled; } public void setOmogeneous(String avalue) { setString(omogeneousID, avalue); } public void setOmogeneous(boolean avalue) { if (avalue) setOmogeneous("true"); else setOmogeneous("false"); omogeneous = isOmogeneous(); } public String getOmogeneous() { return getString(omogeneousID); } public boolean isOmogeneous() { return getOmogeneous().equals("true"); } public boolean omogeneous() { return omogeneous; } public String getRandomTexture() { return getString(randomTextureID); } public boolean hasRandomTexture() { return getRandomTexture().equals("true"); } public void setRandomTexture(String avalue) { setString(randomTextureID, avalue); } public void setRandomTexture(boolean avalue) { if (avalue) setRandomTexture("true"); else setRandomTexture("false"); randomTexture = hasRandomTexture(); Sample asample = (Sample) getParent(); resetForRandomTexture(); // System.out.println(toXRDcatString() + " enabled"); } private void resetForRandomTexture() { int phasesnumber = getSample().phasesNumber(); for (int j = 0; j < phasesnumber; j++) { Phase phase = getSample().getPhase(j); for (int i = 0; i < activedatafilesnumber(); i++) getActiveDataFile(i).resetForRandomTexture(phase); } } public String getNoStrain() { return getString(noStrainID); } public boolean hasNoStrain() { return getNoStrain().equals("true"); } public void setNoStrain(String avalue) { setString(noStrainID, avalue); } public void setNoStrain(boolean avalue) { if (avalue) setNoStrain("true"); else setNoStrain("false"); noStrain = hasNoStrain(); Sample asample = (Sample) getParent(); resetForNoStrain(); // System.out.println(toXRDcatString() + " enabled"); } private void resetForNoStrain() { int phasesnumber = getSample().phasesNumber(); for (int j = 0; j < phasesnumber; j++) { Phase phase = getSample().getPhase(j); for (int i = 0; i < activedatafilesnumber(); i++) getActiveDataFile(i).resetForNoStrain(phase); } } public void useChebyshevPolynomials(boolean value) { if (value) setString(useChebyshevPolynomialsID, "true"); else setString(useChebyshevPolynomialsID, "false"); } public String useChebyshevPolynomialsString() { return getString(useChebyshevPolynomialsID); } public boolean useChebyshevPolynomials() { return useChebyshevPolynomials; } public void setReplaceDatafile(boolean b) { if (b) setReplaceDatafile("true"); else setReplaceDatafile("false"); replaceDatafile = mustReplace(); } public void setReplaceDatafile(String avalue) { setString(replaceID, avalue); } public boolean replaceDatafile() { return replaceDatafile; } public String getReplaceDatafile() { return getString(replaceID); } public boolean mustReplace() { return getReplaceDatafile().equals("true"); } public void setAutomaticPolynomialBackground(boolean b) { if (b) setAutomaticPolynomialBackground("true"); else setAutomaticPolynomialBackground("false"); automaticPolynomialBackground = isAutomaticPolynomialBackground(); } public void setAutomaticPolynomialBackground(String avalue) { setString(automaticPolynomialBackgroundID, avalue); } public boolean automaticPolynomialBackground() { return automaticPolynomialBackground; } public String getAutomaticPolynomialBackground() { return getString(automaticPolynomialBackgroundID); } public boolean isAutomaticPolynomialBackground() { return getAutomaticPolynomialBackground().equals("true"); } public void setBackgroundInterpolated(String avalue) { setString(backgroundInterpolatedID, avalue); } public void setBackgroundInterpolated(boolean avalue) { if (avalue) setBackgroundInterpolated("true"); else setBackgroundInterpolated("false"); } public String getBackgroundInterpolated() { return getString(backgroundInterpolatedID); } public boolean isBackgroundInterpolated() { return getBackgroundInterpolated().equals("true"); } public void setInterpolatedPoints(int avalue) { setInterpolatedPoints(Integer.toString(avalue)); } public void setInterpolatedPoints(String avalue) { setString(interpolatedPointsID, avalue); // interpolatedPoints = Integer.valueOf(getInterpolatedPoints()); } public String getInterpolatedPoints() { return getString(interpolatedPointsID); } public int getInterpolatedPointsValue() { return interpolatedPoints; } public void setBackgroundInterpolationIterations(int integer) { setBackgroundInterpolationIterations(Integer.toString(integer)); } public void setBackgroundInterpolationIterations(String integer) { setString(interpolationIterationsID, integer); } public int getInterpolationIterationsValue() { return interpolationIterations; } public String getInterpolationIterations() { return getString(interpolationIterationsID); } public void removeManualInterpolation(boolean forceRemove) { for (int i = 0; i < datafilesnumber(); i++) { if (forceRemove || !getDataFile(i).getManualBkgInterpolation()) getDataFile(i).removeManualInterpolation(); } } public void checkManualInterpolation() { for (int i = 0; i < datafilesnumber(); i++) { this.getDataFile(i).checkManualInterpolation(); } } public int datafilesnumber() { return numberofelementSubL(2); } public int activedatafilesnumber() { return activedatanumber; } public static final int backgroundID = 0; public int numbercoefbackg() { return numberofelementPL(backgroundID); } public void addBackgroudCoeff() { int numb = numbercoefbackg(); String parameterString = getParameterString(backgroundID, numb); double minmax = -10000.0 / (numb + 1) / (numb + 1) / (numb + 1); addparameterloopField(backgroundID, new Parameter(this, parameterString, 0, ParameterPreferences.getDouble(parameterString + ".min", -minmax), ParameterPreferences.getDouble(parameterString + ".max", minmax))); } public void removeAllBackgroundCoeff() { removeAllPLField(backgroundID); } public Parameter getbackgcoef(int index) { return (Parameter) parameterloopField[backgroundID].elementAt(index); } public static final int chiBackgroundID = 1; public int numbercoefbackgChi() { return numberofelementPL(chiBackgroundID); } public Parameter getbackgcoefChi(int index) { return (Parameter) parameterloopField[chiBackgroundID].elementAt(index); } public static final int etaBackgroundID = 2; public int numbercoefbackgEta() { return numberofelementPL(etaBackgroundID); } public Parameter getbackgcoefEta(int index) { return (Parameter) parameterloopField[etaBackgroundID].elementAt(index); } public int backgpeaksnumber() { return numberofelementSubL(1); } public ListVector getBkgPeakList() { return subordinateloopField[1]; } public void addBkgPeak(BkgPeak peak) { getBkgPeakList().addItem(peak); } public BkgPeak getBkgPeak(int index) { return (BkgPeak) subordinateloopField[1].elementAt(index); } public int excludedRegionsNumber() { return numberofelementSubL(0); } public Region getExcludedRegion(int index) { return (Region) subordinateloopField[0].elementAt(index); } public void setPeakFunction(String value) { setString(4, value); } public String getPeakFunction() { return getString(4); } public void setPeakCutoff(String value) { setString(5, value); } public String getPeakCutoff() { return getString(5); } public double getPeakCutoffD() { return Double.valueOf(getPeakCutoff()); } public boolean hasSimilarRadiationTo(DataFileSet adataset) { RadiationType radtypeThis = getInstrument().getRadiationType(); RadiationType radtypeOther = adataset.getInstrument().getRadiationType(); return radtypeThis.isSimilarTo(radtypeOther); } int numberOfData; public int computeDataNumber() { numberOfData = 0; int datafilenumber = activedatafilesnumber(); for (int i = 0; i < datafilenumber; i++) { DiffrDataFile adfile = getActiveDataFile(i); numberOfData += adfile.computeDataNumber(); } return numberOfData; } public int getNumberOfData() { return numberOfData; } @Override public boolean isActive(XRDcat obj) { return isEnabled() && super.isActive(obj); } public double[] getData() { int dnumber = 0; double dta[] = new double[getNumberOfData()]; int datafilenumber = activedatafilesnumber(); for (int i = 0; i < datafilenumber; i++) { DiffrDataFile adfile = getActiveDataFile(i); int apnumber = adfile.getNumberOfData(); double adta[] = adfile.getDataForStatistic(); arraycopy(adta, 0, dta, dnumber, apnumber); dnumber += apnumber; } return dta; } public double[] getWeight() { int dnumber = 0; double dta[] = new double[getNumberOfData()]; int datafilenumber = activedatafilesnumber(); double sumDataWeighted = 1.0; FilePar afilepar = getFilePar(); for (int i = 0; i < datafilenumber; i++) { DiffrDataFile adfile = getActiveDataFile(i); switch (afilepar.getMinimizeQuantitySwitch()) { case 0: sumDataWeighted = 1.0; break; case 1: sumDataWeighted = Math.sqrt(adfile.getDataWeightSum()); break; } int apnumber = adfile.getNumberOfData(); double adta[] = adfile.getWeight(); for (int j = 0; j < apnumber; j++) dta[dnumber + j] = adta[j] / sumDataWeighted; dnumber += apnumber; } return dta; } public double[] getFit() { int dnumber = 0; double dta[] = new double[getNumberOfData()]; int datafilenumber = activedatafilesnumber(); for (int i = 0; i < datafilenumber; i++) { DiffrDataFile adfile = getActiveDataFile(i); int apnumber = adfile.getNumberOfData(); double adta[] = adfile.getFitForStatistic(); arraycopy(adta, 0, dta, dnumber, apnumber); dnumber += apnumber; } return dta; } public DiffrDataFile[] getActiveDataFiles() { int datafilenumber = activedatafilesnumber(); if (datafilenumber == 0) return null; // System.out.println(toXRDcatString() + " " + datafilenumber); DiffrDataFile[] adfile = new DiffrDataFile[datafilenumber]; for (int i = 0; i < datafilenumber; i++) { adfile[i] = getActiveDataFile(i); } return adfile; } public void multiPlot(Frame aframe) { int datafilenumber = activedatafilesnumber(); final Frame newFrame = aframe; final DiffrDataFile[] adfile = new DiffrDataFile[datafilenumber]; for (int i = 0; i < datafilenumber; i++) { adfile[i] = getActiveDataFile(i); } final String label = DataFileSet.this.toXRDcatString(); (new PersistentThread() { @Override public void executeJob() { if (adfile.length > 1) (new MultiPlotFitting(newFrame, adfile, label)).setVisible(true); else if (adfile.length > 0) (new PlotFitting(newFrame, adfile)).setVisible(true); else (new PlotFitting(newFrame, null)).setVisible(true); } }).start(); } String yTitle = null; String yUnit = null; public void multiPlot2D(Frame aframe) { int datafilenumber = activedatafilesnumber(); yTitle = null; yUnit = null; boolean angleAxis = MaudPreferences.getBoolean("multiplot2D.use2Theta", false); if (angleAxis) { yTitle = "2Theta"; yUnit = "degrees"; } final Frame newFrame = aframe; final DiffrDataFile[] adfile = new DiffrDataFile[datafilenumber]; for (int i = 0; i < datafilenumber; i++) { adfile[i] = getActiveDataFile(i); } final String label = DataFileSet.this.toXRDcatString(); (new PersistentThread() { @Override public void executeJob() { new MultiPlotFitting2D(newFrame, adfile, label, yTitle, yUnit); } }).start(); } public void plot2DandExportPng(String plotOutput2DFileName) { int datafilenumber = activedatafilesnumber(); yTitle = null; yUnit = null; boolean angleAxis = MaudPreferences.getBoolean("multiplot2D.use2Theta", false); if (angleAxis) { yTitle = "2Theta"; yUnit = "degrees"; } final DiffrDataFile[] adfile = new DiffrDataFile[datafilenumber]; for (int i = 0; i < datafilenumber; i++) { adfile[i] = getActiveDataFile(i); } final String label = DataFileSet.this.toXRDcatString(); MultiPlotFitting2D plot = new MultiPlotFitting2D(null, adfile, label, yTitle, yUnit); (new PersistentThread() { @Override public void executeJob() { int index = MaudText.addNewThread(); try { TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } Component comp = plot.fullGraphPanel; if (comp != null) { Rectangle rect = comp.getBounds(); Image fileImage = plot.createImage(rect.width, rect.height); Graphics g = fileImage.getGraphics(); //write to the image g.clearRect(0, 0, comp.getWidth(), comp.getHeight()); comp.paint(g); // write it out in the format you want String dst = plotOutput2DFileName + label + ".png"; Misc.deleteFile(dst); BeartexPFPlot.savePic(fileImage, "png", dst, comp); boolean fileSaved = false; while (!fileSaved) { fileSaved = Misc.checkForFile(dst); try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } //dispose of the graphics content g.dispose(); plot.setVisible(false); plot.dispose(); MaudText.removeThread(index); } } }).start(); } public void plotAndExportPng(String plotOutputFileName) { int datafilenumber = activedatafilesnumber(); final DiffrDataFile[] adfile = new DiffrDataFile[datafilenumber]; for (int i = 0; i < datafilenumber; i++) { adfile[i] = getActiveDataFile(i); } final String label = DataFileSet.this.toXRDcatString(); PlotFitting plot = new PlotFitting(null, adfile, false); plot.setSize(plot.defaultFrameW, plot.defaultFrameH); plot.setVisible(true); (new PersistentThread() { @Override public void executeJob() { int index = MaudText.addNewThread(); try { TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } Component comp = plot.thePlotPanel.getComponentToPrint(); if (comp != null) { Rectangle rect = comp.getBounds(); Image fileImage = plot.createImage(rect.width, rect.height); Graphics g = fileImage.getGraphics(); //write to the image g.clearRect(0, 0, comp.getWidth(), comp.getHeight()); comp.paint(g); // write it out in the format you want String dst = plotOutputFileName + label + ".png"; Misc.deleteFile(dst); BeartexPFPlot.savePic(fileImage, "png", dst, comp); boolean fileSaved = false; while (!fileSaved) { fileSaved = Misc.checkForFile(dst); try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } //dispose of the graphics content g.dispose(); plot.setVisible(false); plot.dispose(); MaudText.removeThread(index); } } }).start(); } public void polarPlot2D(Frame aframe) { final Frame newFrame = aframe; (new PersistentThread() { @Override public void executeJob() { int zoom = MaudPreferences.getInteger("polarPlotData2D.zoom", 4); int gridPoints = MaudPreferences.getInteger("polarPlotData2D.gridPoints", 201); new PolarPlotData2D(newFrame, DataFileSet.this, gridPoints, zoom, 0, false, Constants.PI / 2, false, 512); } }).start(); } public double[][] getPolarPlotData() { int numberExpPoints = 0; int datafilenumber = activedatafilesnumber(); final DiffrDataFile[] adfile = new DiffrDataFile[datafilenumber]; for (int i = 0; i < datafilenumber; i++) { adfile[i] = getActiveDataFile(i); numberExpPoints += adfile[i].getNumberOfData(); } boolean experimental = MaudPreferences.getBoolean("polarPlotData2D.experimental", true); if(numberExpPoints <= 0) return null; double[][] expTFAndAngles = new double[3][numberExpPoints]; int index = 0; for (int i = 0; i < datafilenumber; i++) { double[][] texture_angles = adfile[i].getTextureAnglesAndIntensityNoBkg(experimental); for (int j = 0; j < adfile[i].getNumberOfData(); j++) { expTFAndAngles[0][index] = texture_angles[0][j]; expTFAndAngles[1][index] = texture_angles[1][j]; expTFAndAngles[2][index++] = texture_angles[2][j]; } double[] textAngl = adfile[i].getTiltingAngle(); int j = index - adfile[i].getNumberOfData(); /* System.out.println(i + " " + textAngl[0] + " " + textAngl[1] + " " + textAngl[2] + " " + textAngl[3]); System.out.println(i + " " + expTFAndAngles[0][j] + " " + expTFAndAngles[0][index - 1] + " " + expTFAndAngles[1][j] + " " + expTFAndAngles[1][index - 1] + " " + expTFAndAngles[2][j] + " " + expTFAndAngles[2][index - 1]);*/ } return expTFAndAngles; } public void differencePlot2D(Frame aframe) { int datafilenumber = activedatafilesnumber(); yTitle = null; yUnit = null; boolean angleAxis = MaudPreferences.getBoolean("multiplot2D.use2Theta", false); if (angleAxis) { yTitle = "2Theta"; yUnit = "degrees"; } final Frame newFrame = aframe; final DiffrDataFile[] adfile = new DiffrDataFile[datafilenumber]; for (int i = 0; i < datafilenumber; i++) { adfile[i] = getActiveDataFile(i); } final String label = DataFileSet.this.toXRDcatString(); (new PersistentThread() { @Override public void executeJob() { new DifferencePlot2D(newFrame, adfile, label, yTitle, yUnit); } }).start(); } public void sectionPlot2D(Frame aframe) { final Frame newFrame = aframe; int datafilenumber = activedatafilesnumber(); final DiffrDataFile[] adfile = new DiffrDataFile[datafilenumber]; for (int i = 0; i < datafilenumber; i++) { adfile[i] = getActiveDataFile(i); } final String label = DataFileSet.this.toXRDcatString(); (new PersistentThread() { @Override public void executeJob() { new SectionPlotData2D(newFrame, adfile, label).setVisible(true); } }).start(); } // DiffrDataFile adatafile[]; int minindex[]; int maxindex[]; @Override public void notifyParameterChanged(Parameter source) { FilePar filepar = getFilePar(); if (filepar != null && !filepar.isLoadingFile() && isAbilitatetoRefresh) { for (int i = 0; i < sampleOmegaID; i++) if (source == parameterField[i]) { notifyParameterChanged(source, Constants.THERMAL_SHIFT_CHANGED); return; } for (int i = sampleOmegaID; i < sampleOmegaID + 3; i++) if (source == parameterField[i]) { notifyParameterChanged(source, Constants.SAMPLE_ORIENTATION_CHANGED); notifyParameterChanged(source, Constants.ERROR_POSITION_CHANGED); return; } for (int i = displacementxID; i < displacementxID + 3; i++) if (source == parameterField[i]) { notifyParameterChanged(source, Constants.ERROR_POSITION_CHANGED); return; } for (int i = disalignementOmegaID; i < disalignementOmegaID + 4; i++) if (source == parameterField[i]) { notifyParameterChanged(source, Constants.TEXTURE_CHANGED); return; } for (int i = 0; i < Nparameterloop; i++) { for (int j = 0; j < numberofelementPL(i); j++) { Parameter apar = (Parameter) parameterloopField[i].elementAt(j); if (apar == source) { notifyParameterChanged(source, Constants.BKG_PARAMETER_CHANGED); return; } } } } super.notifyParameterChanged(source); } // todo: check notification up and down after moving instrument @Override public void refreshForNotificationUp(XRDcat source, int reason) { refreshComputation = true; // if (source instanceof DiffrDataFile) // System.out.println("Notification received from " + source + " , reason " + reason); // boolean isFromInstrument = source instanceof Instrument; if (reason == Constants.ANGULAR_CALIBRATION) { refreshComputation = true; int datafilenumber = datafilesnumber(); for (int i = 0; i < datafilenumber; i++) { getDataFile(i).setCalibrated(false); getDataFile(i).refreshBkgComputation = true; getDataFile(i).refreshSpectraComputation = true; } reason = 0; } else if (reason == Constants.INTENSITY_CALIBRATION) { refreshComputation = true; int datafilenumber = datafilesnumber(); for (int i = 0; i < datafilenumber; i++) { getDataFile(i).setIntensityUncalibrated(); getDataFile(i).refreshBkgComputation = true; getDataFile(i).refreshSpectraComputation = true; } reason = 0; } else if (reason == Constants.BKG_FILE_CHANGED) { int datafilenumber = datafilesnumber(); for (int i = 0; i < datafilenumber; i++) { getDataFile(i).refreshBkgComputation = true; } reason = 0; } else if (reason == Constants.TEXTURE_CHANGED) { refreshComputation = true; int datafilenumber = datafilesnumber(); for (int i = 0; i < datafilenumber; i++) { getDataFile(i).refreshBkgComputation = true; getDataFile(i).refreshSpectraComputation = true; } } if (source == this || source instanceof BkgPeak) { int datafilenumber = datafilesnumber(); // System.out.println("Setting all bckg changed"); if (reason == Constants.BKG_PARAMETER_CHANGED) for (int i = 0; i < datafilenumber; i++) { getDataFile(i).refreshBkgComputation = true; getDataFile(i).refreshSpectraComputation = true; } } else { XRDcat sourceDatafile = source; while (sourceDatafile != null && (!(sourceDatafile instanceof FilePar) && !(sourceDatafile instanceof DiffrDataFile))) sourceDatafile = sourceDatafile.getParent(); if (sourceDatafile instanceof DiffrDataFile) { int datafilenumber = datafilesnumber(); for (int i = 0; i < datafilenumber; i++) { if (getDataFile(i) == sourceDatafile) { if (reason == Constants.BKG_PARAMETER_CHANGED) { getDataFile(i).refreshBkgComputation = true; getDataFile(i).refreshSpectraComputation = true; // System.out.println("refreshing bkg "+sourceDatafile.toXRDcatString()); } else { // System.out.println("Setting parameter changed, " + sourceDatafile); if (isBackgroundInterpolated()) getDataFile(i).refreshBkgComputation = true; } } } } else { int datafilenumber = datafilesnumber(); for (int i = 0; i < datafilenumber; i++) { if (isBackgroundInterpolated()) getDataFile(i).refreshBkgComputation = true; getDataFile(i).refreshSpectraComputation = true; } } } } @Override public void refreshForNotificationDown(XRDcat source, int reason) { boolean isFromDataset = source instanceof DataFileSet; XRDcat sourceparent = source; if (!isFromDataset) { while (sourceparent != null && !(sourceparent instanceof FilePar)) { sourceparent = sourceparent.getParent(); if (sourceparent instanceof DataFileSet) { isFromDataset = true; break; } } } if (isFromDataset) return; refreshComputation = true; // we need to compute all probably int datafilenumber = datafilesnumber(); for (int i = 0; i < datafilenumber; i++) { if (isBackgroundInterpolated()) getDataFile(i).refreshBkgComputation = true; getDataFile(i).refreshSpectraComputation = true; } } @Override public void setRefreshAllStatus() { super.setRefreshAllStatus(); } int numberofpeak; BkgPeak[] abkgPeak; @Override public void update(boolean firstLoading) { super.update(firstLoading); activedatanumber = 0; int datafilenumber = datafilesnumber(); // setRadiation(); for (int i = 0; i < datafilenumber; i++) if (getDataFile(i).getComputePermission()) activedatanumber++; // System.out.println("Refresh active datafiles!"); datafileindex = new int[activedatanumber]; activedatanumber = 0; for (int i = 0; i < datafilenumber; i++) if (getDataFile(i).getComputePermission()) { datafileindex[activedatanumber] = i; activedatanumber++; } numberofpeak = backgpeaksnumber(); abkgPeak = new BkgPeak[numberofpeak]; for (int k = 0; k < numberofpeak; k++) { abkgPeak[k] = getBkgPeak(k); // abkgPeak[k].preparecomputing(); } } public double[] getTotalIntensityForActiveSpectra() { update(false); double[] total = new double[activedatanumber]; for (int i = 0; i < activedatanumber; i++) total[i] = getActiveDataFile(i).getTotalIntensity(); return total; } public double[] getCoordinateForActiveSpectra(int coord) { update(false); double[] total = new double[activedatanumber]; for (int i = 0; i < activedatanumber; i++) { double angle = getActiveDataFile(i).getAngleValue(coord); if (angle > -9999999) total[i] = angle; else total[i] = i; } return total; } public double[] getTotalIntensityForSelectedSpectra() { update(false); Vector datafiles = getSelectedDatafiles(); int numberDatafiles = datafiles.size(); double[] total = new double[numberDatafiles]; for (int i = 0; i < numberDatafiles; i++) total[i] = ((DiffrDataFile) datafiles.elementAt(i)).getTotalIntensity(); return total; } public double[] getCoordinateForSelectedSpectra(int coord) { update(false); Vector datafiles = getSelectedDatafiles(); int numberDatafiles = datafiles.size(); double[] total = new double[numberDatafiles]; for (int i = 0; i < numberDatafiles; i++) { double angle = ((DiffrDataFile) datafiles.elementAt(i)).getAngleValue(coord); if (angle > -9999999) total[i] = angle; else total[i] = i; } return total; } public void forceRangeCut() { double drange0 = getMinRangeD(); double drange1 = getMaxRangeD(); int datafilenumber = datafilesnumber(); for (int i = 0; i < datafilenumber; i++) { DiffrDataFile adatafile1 = getDataFile(i); adatafile1.checkIncreasingX(); int minindex1 = adatafile1.getMinIndexforValue(drange0, drange1); int maxindex1 = adatafile1.getMaxIndexforValue(drange0, drange1); if ((maxindex1 - minindex1) < 4) adatafile1.setCompute(false); else adatafile1.setMinMaxIndices(minindex1, maxindex1); } } double drange_final[] = new double[2]; public DiffrDataFile getBackgroundDataFile(DiffrDataFile requestingDataFile) { int banknumber = requestingDataFile.getBankNumber(); int alldatafilenumber = datafilesnumber(); for (int i = 0; i < alldatafilenumber; i++) { DiffrDataFile bdatafile = getDataFile(i); if (bdatafile.getAsBackgroundPermission() && bdatafile.getBankNumber() == banknumber) return bdatafile; } return null; } public boolean isBackgroundExperimental() { return isBackgroundExperimental; } public void setRefreshComputation(boolean value) { refreshComputation = false; int datafilenumber = activedatafilesnumber(); for (int i = 0; i < datafilenumber; i++) getActiveDataFile(i).refreshSpectraComputation = false; } public void finalOutput(OutputStream out) throws IOException { double[] indexes = getRefinementIndexes(); printLine(out, "DataSet " + toXRDcatString() + " :"); printLine(out, "DataSet Rwp: " + Fmt.format(indexes[0])); printLine(out, "DataSet Rp: " + Fmt.format(indexes[4])); printLine(out, "DataSet Rwpnb (no background): " + Fmt.format(indexes[1])); printLine(out, "DataSet Rwpnb1 (no bkg rescaled): " + Fmt.format(indexes[2])); printLine(out, "DataSet Rwpnb2 (no bkg rescaled^2): " + Fmt.format(indexes[3])); printLine(out, "DataSet Rpnb (no background): " + Fmt.format(indexes[5])); printLine(out, "DataSet Rpnb1 (no bkg rescaled): " + Fmt.format(indexes[6])); printLine(out, "DataSet Rpnb2 (no bkg rescaled^2): " + Fmt.format(indexes[7])); newLine(out); printLine(out, "Refinement final output indices for single spectra:"); int datafilenumber = activedatafilesnumber(); for (int i = 0; i < datafilenumber; i++) getActiveDataFile(i).finalOutput(out); out.flush(); } boolean indexesComputed = false; double[] refinementIndexes = new double[18]; public double[] getRefinementIndexes() { // todo: add WSS if (!indexesComputed) { for (int j = 0; j < 18; j++) refinementIndexes[j] = 0.0; int datafilenumber = activedatafilesnumber(); for (int i = 0; i < datafilenumber; i++) { double[] refIndex = getActiveDataFile(i).getRefinementIndexes(); for (int j = 8; j < 18; j++) refinementIndexes[j] += refIndex[j]; } refinementIndexes[0] = MoreMath.sqrt(refinementIndexes[8] / refinementIndexes[14]); refinementIndexes[1] = MoreMath.sqrt(refinementIndexes[8] / refinementIndexes[15]); refinementIndexes[2] = MoreMath.sqrt(refinementIndexes[10] / refinementIndexes[15]); refinementIndexes[3] = MoreMath.sqrt(refinementIndexes[11] / refinementIndexes[15]); refinementIndexes[4] = refinementIndexes[9] / refinementIndexes[16]; refinementIndexes[5] = refinementIndexes[9] / refinementIndexes[17]; refinementIndexes[6] = refinementIndexes[12] / refinementIndexes[17]; refinementIndexes[7] = refinementIndexes[13] / refinementIndexes[17]; indexesComputed = true; } return refinementIndexes; } public void computeRange() { // preparing computation int datafilenumber = activedatafilesnumber(); // System.out.println(datafilenumber); // adatafile = new DiffrDataFile[datafilenumber]; // System.out.println(toXRDcatString() + " number of datafiles " + datafilenumber); minindex = new int[datafilenumber]; maxindex = new int[datafilenumber]; double[] drange = new double[2]; drange[0] = getMinRangeD(); drange[1] = getMaxRangeD(); // System.out.println(drange[0] + ", " + drange[1]); omogeneousDataset = true; drange_final[1] = -1.0E+10; drange_final[0] = 1.0E+10; for (int i = 0; i < datafilenumber; i++) { // adatafile[i] = getActiveDataFile(i); DiffrDataFile bdatafile = getActiveDataFile(i); bdatafile.calibrateX(); bdatafile.checkIncreasingX(); minindex[i] = bdatafile.getMinIndexforValue(drange[0], drange[1]); maxindex[i] = bdatafile.getMaxIndexforValue(drange[0], drange[1]); // System.out.println("Datafile #" + i + ": " + bdatafile + " , minmax " + minindex[i] + " " + maxindex[i]); bdatafile.setMinMaxIndices(minindex[i], maxindex[i]); if (i > 0) { if (minindex[0] != minindex[i]) omogeneousDataset = false; if (maxindex[0] != maxindex[i]) omogeneousDataset = false; } double[] arange = bdatafile.getRange(minindex[i], maxindex[i]); if (drange_final[0] > arange[0]) drange_final[0] = arange[0]; if (drange_final[1] < arange[1]) drange_final[1] = arange[1]; } // if (drange_final[0] < 0) // hasNegative2theta = true; getSample().setRange(drange_final); // preparing background datafiles if any for (int i = 0; i < datafilesnumber(); i++) { // adatafile[i] = getActiveDataFile(i); DiffrDataFile bdatafile = getDataFile(i); if (bdatafile.getAsBackgroundPermission()) { bdatafile.calibrateX(); // bdatafile.checkIncreasingX(); double drangeMin = drange_final[0]; double drangeMax = drange_final[1]; if (bdatafile.dspacingbase) { double newdrangeMin = drangeMin / (1.0 + getParameterValue(bkgExpThermalShift) * 1.0E-4) - getParameterValue(bkgExpShift); if (newdrangeMin < drangeMin) drangeMin = newdrangeMin; double newdrangeMax = drangeMax / (1.0 + getParameterValue(bkgExpThermalShift) * 1.0E-4) - getParameterValue(bkgExpShift); if (newdrangeMax > drangeMax) drangeMax = newdrangeMax; } else if (bdatafile.energyDispersive) { double newdrangeMin = drangeMin * (1.0 + getParameterValue(bkgExpThermalShift) * 1.0E-4) - getParameterValue(bkgExpShift); if (newdrangeMin < drangeMin) drangeMin = newdrangeMin; double newdrangeMax = drangeMax * (1.0 + getParameterValue(bkgExpThermalShift) * 1.0E-4) - getParameterValue(bkgExpShift); if (newdrangeMax > drangeMax) drangeMax = newdrangeMax; } else { double newdrangeMin = drangeMin / (1.0 + getParameterValue(bkgExpThermalShift) * 1.0E-4) - getParameterValue(bkgExpShift); if (newdrangeMin < drangeMin) drangeMin = newdrangeMin; double newdrangeMax = drangeMax / (1.0 + getParameterValue(bkgExpThermalShift) * 1.0E-4) - getParameterValue(bkgExpShift); if (newdrangeMax > drangeMax) drangeMax = newdrangeMax; } int minindex1 = bdatafile.getMinIndexforValue(drangeMin, drangeMax); int maxindex1 = bdatafile.getMaxIndexforValue(drangeMin, drangeMax); bdatafile.setMinMaxIndices(minindex1, maxindex1); bdatafile.computeSmoothSpectrum(getParameterValue(bkgExpShift), getParameterValue(bkgExpThermalShift), bdatafile); } } } public int getNumberOfBackgroundFiles() { int index = 0; for (int i = 0; i < datafilesnumber(); i++) { DiffrDataFile tmpDatafile = getDataFile(i); if (tmpDatafile.getAsBackgroundPermission()) { index++; } } return index; } public void refreshAll(boolean firstLoading) { FilePar filepar = getFilePar(); if (filepar != null && !filepar.isLoadingFile() && isAbilitatetoRefresh) { // System.out.println("Refreshing " + this.toXRDcatString()); refreshComputation = true; setRefreshAllStatus(); update(firstLoading); Object[] childrens = getObjectChildren(); int numberOfChildrens = childrens.length; for (int i = 0; i < numberOfChildrens; i++) { // System.out.println(this.toXRDcatString() + ": " + childrens[i].toXRDcatString()); ((XRDcat) childrens[i]).refreshAll(firstLoading); } } } public void computeBackground() { // preparing computation int datafilenumber = activedatafilesnumber(); // compute background // System.out.println("Compute background"); for (int i = 0; i < datafilenumber; i++) { DiffrDataFile tmpDatafile = getActiveDataFile(i); if (tmpDatafile.refreshBkgComputation) { // System.out.println("Refreshing backg: " + tmpDatafile.toXRDcatString()); // System.out.println("Min, max: " + minindex[i] + " " + maxindex[i]); // System.out.println("Max: " + tmpDatafile.twothetacalibrated.length); // System.out.println("Start-end: " + tmpDatafile.startingindex + " " + tmpDatafile.finalindex); tmpDatafile.resetBkg(); // tmpDatafile.computeBackground(minindex[i], maxindex[i]); tmpDatafile.computeBackground(tmpDatafile.startingindex, tmpDatafile.finalindex); double tbackgroundChi = 0.0; double[] chieta = tmpDatafile.getTiltingAngle(); if (nchibckgpar > 0) { for (int k = 0; k < nchibckgpar; k++) tbackgroundChi += backgroundChi[k] * MoreMath.pow(chieta[1], k + 1); } if (netabckgpar > 0) { for (int k = 0; k < netabckgpar; k++) tbackgroundChi += backgroundEta[k] * MoreMath.pow(chieta[3], k + 1); } // System.out.println("Next min, max: " + minindex[i] + " " + maxindex[i]); // for (int j = minindex[i]; j < maxindex[i]; j++) { for (int j = tmpDatafile.startingindex; j < tmpDatafile.finalindex; j++) { double thetaord = tmpDatafile.getXData(j); double background = tbackgroundChi; if (useChebyshevPolynomials()) { for (int k = 0; k < npolbckgpar; k++) background += backgroundPol[k] * ChebyshevPolynomial.getT(k, thetaord); } else { for (int k = 0; k < npolbckgpar; k++) background += backgroundPol[k] * Math.pow(thetaord, k); } for (int k = 0; k < numberofpeak; k++) background += abkgPeak[k].computeIntensity(thetaord, chieta[0], chieta[1], chieta[2], chieta[3]); background *= tmpDatafile.getIntensityCalibration(j); tmpDatafile.addtoBkgFit(j, background); } tmpDatafile.spectrumModified = true; } } // refreshBkgComputation = false; } public void exportExperimentalComputedData(BufferedWriter output) { int datafilenumber = activedatafilesnumber(); for (int i = 0; i < datafilenumber; i++) { DiffrDataFile tmpDatafile = getActiveDataFile(i); if (tmpDatafile != null) tmpDatafile.exportExperimentalComputedData(output,false); } } public void addPhasePeaks(Phase aphase, Sample asample, boolean lastDataset) { if (activedatafilesnumber() == 0) return; DiffrDataFile datafiletmp = this.getActiveDataFile(0); Instrument ainstrument = getInstrument(); // compute peaks int numberofradiation = ainstrument.getRadiationType().getLinesCount(); double[] wavelength = new double[numberofradiation]; double[] radweight = new double[numberofradiation]; for (int j = 0; j < numberofradiation; j++) { wavelength[j] = ainstrument.getRadiationType().getRadiationWavelength(j); radweight[j] = ainstrument.getRadiationType().getRadiationWeigth(j); // System.out.println("Rad: " + j + " " + wavelength[j] + " " + radweight[j]); } int numberofpeaks = aphase.gethklNumber(); // System.out.println("Dataset compute, phase " + aphase.getPhaseName() + ", number of peaks: " + numberofpeaks); // aphase.setReflectionNumber(numberofpeaks); // double Fhkl[] = // Radiation rad1 = radtype.getRadiation(0); // todo: Luca 23/06/2011 aphase.Fhklcompv(rad1.getRadiationIDNumber(), rad1.tubeNumber, this.getIndex(), lastDataset); double Rhkl; double intensity = ainstrument.getIntensityValue(); // boolean distribution = needDistribution(); // System.out.println("Adding peaks: " + numberofpeaks); for (int i = 0; i < numberofpeaks; i++) { double dspace = aphase.getDspacing(i); if (datafiletmp.dspacingbase || datafiletmp.energyDispersive || datafiletmp.computeposition(dspace, wavelength[0]) < 180.0) { // if (Fhkl != null) // aphase.getReflex(i).setStructureFactor(datasetNumber, Fhkl[i]); // double dspace = aphase.getDspacing(i); Rhkl = intensity; // * Fhkl[i]; Peak hklpeak = aphase.getActiveSizeStrain().createPeak(dspace, datafiletmp.dspacingbase, datafiletmp.energyDispersive, wavelength, radweight, aphase.getReflex(i), i); hklpeak.setIntensity(Rhkl); // hklpeak.setLayer(alayer); // hklpeak.setCrystMstrainDistribution(crystallite, microstrain, distx, distsize); // hklpeak.setCrystalliteMicrostrain(aphase.getCrystallite(i), aphase.getMicrostrainD(i)); thepeaklist.addElement(hklpeak); dspace = -dspace; if (datafiletmp.xInsideRange(datafiletmp.computeposition(dspace, wavelength[0]))) { hklpeak = aphase.getActiveSizeStrain().createPeak(dspace, datafiletmp.dspacingbase, datafiletmp.energyDispersive, wavelength, radweight, aphase.getReflex(i), i); hklpeak.setIntensity(Rhkl); // hklpeak.setLayer(alayer); // hklpeak.setCrystMstrainDistribution(crystallite, microstrain, distx, distsize); // hklpeak.setCrystalliteMicrostrain(aphase.getCrystallite(i), aphase.getMicrostrainD(i)); thepeaklist.addElement(hklpeak); } }// else // System.out.println("Not added : " + dspace + ", " + computeposition(dspace, wavelength[0])); } // System.out.println("adding peaks completed"); } public void computeSpectra(Sample asample) { indexesComputed = false; final Diffraction diffr = getDiffraction(); final Reflectivity refle = getReflectivity(); final Fluorescence fluo = getFluorescence(); int datafilenumber = activedatafilesnumber(); for (int k = 0; k < datafilenumber; k++) { DiffrDataFile datafile = getActiveDataFile(k); if (datafile.refreshSpectraComputation) datafile.resetPhasesFit(); } diffr.computeDiffraction(asample,this); refle.computeReflectivity(asample, this); fluo.computeFluorescence(asample, this); for (int k = 0; k < datafilenumber; k++) { DiffrDataFile datafile = getActiveDataFile(k); if (datafile.refreshSpectraComputation) { datafile.hasfit = true; datafile.spectrumModified = true; datafile.resetExperimentalBackground(); datafile.resetBackgroundInterpolated(); if (isBackgroundExperimental()) datafile.addExperimentalBackground(); if (isBackgroundInterpolated()) datafile.addInterpolatedBackgroundFromResiduals(); } } } public double meanAbsorptionScaleFactor = 1.0; public void setMeanAbsorption(double value) { meanAbsorptionScaleFactor = value; } public double getMeanAbsorption() { return meanAbsorptionScaleFactor; } public double getSampleAsymmetry(double x, double[] tilting_angles) { return getSample().getSampleAsymmetry(x, tilting_angles); } public double[] getTextureAngles(DiffrDataFile datafile, double[] tilting_angles, double twotheta) { return getInstrument().getTextureAngles(datafile, tilting_angles, getSample().getSampleAngles(), twotheta); } public double[][] getTextureAngles(DiffrDataFile datafile, double[] tilting_angles, double[] twotheta) { return getInstrument().getTextureAngles(datafile, tilting_angles, getSample().getSampleAngles(), twotheta); } public double[] getAlternateTextureAngles(DiffrDataFile datafile, double[] tilting_angles, double twotheta) { return getInstrument().getAlternateTextureAngles(datafile, tilting_angles, getSample().getSampleAngles(), twotheta); } public double getXshift() { return getSample().getXshift() + getDisplacementErrors()[0]; } public double getYshift() { return getSample().getYshift() + getDisplacementErrors()[1]; } public double getZshift() { return getSample().getZshift() + getDisplacementErrors()[2]; } public double getCorrectedPosition(Sample asample, double x, double[] tilting_angles, DiffrDataFile adatafile) { return getInstrument().getCorrectedPosition(asample, x, tilting_angles, adatafile); } public boolean extractIntensity() { return !getIntensityExtractorMethod().equalsIgnoreCase("none ie") && getFilePar().isTextureFactorsExtractionPermitted(); } public boolean isRandomTexture() { return !getIntensityExtractorMethod().equalsIgnoreCase("none ie"); } public boolean isTextureFactorsExtractionPermitted() { return extractIntensity(); // todo at the moment we just rely on the fact no texture extraction is in } public boolean extractPosition() { return !getPositionExtractorMethod().equalsIgnoreCase("none pe"); } boolean computed = false; int actualThread; int index; public void computeExpTextureFactor(Sample asample) { // FilePar aparFile = getFilePar(); final Sample theSample = asample; if (!isTextureFactorsExtractionPermitted()) return; int datafilenumber = activedatafilesnumber(); final ProgressFrame prF; if (!Constants.textonly && Constants.showProgressFrame) { // try { prF = new ProgressFrame(datafilenumber); // } catch (NullPointerException npe) { // System.out.println("Not able to create frame, MacOSX display sleep bug?"); } else prF = null; // printf("Extracting texture weights for dataset: " + toXRDcatString(), prF); computed = false; actualThread = 0; for (index = 0; index < datafilenumber;) { while (actualThread >= 1 /* Constants.maxNumberOfThreads*/) { try { Thread.sleep(Constants.timeToWaitThreadsEnding); } catch (InterruptedException ie) { } } int actualIndex1 = index; (new PersistentThread() { @Override public void executeJob() { actualThread++; DiffrDataFile datafile = getActiveDataFile(index++); if (datafile.computeExpTextureFactor(theSample)) computed = true; if (prF != null) prF.increaseProgressBarValue(); actualThread } }).start(); while (actualIndex1 == index) { try { Thread.sleep(Constants.timeToWaitThreadsStarting); } catch (InterruptedException ie) { } } } while (actualThread > 0) { try { Thread.sleep(Constants.timeToWaitThreadsEnding); } catch (InterruptedException ie) { } } if (prF != null) { prF.setVisible(false); prF.dispose(); } // prF = null; if (computed) refreshAll(false); } public void computeExpStrain(Sample asample) { FilePar aparFile = getFilePar(); if (!aparFile.isPositionExtractionPermitted()) return; int datafilenumber = activedatafilesnumber(); ProgressFrame prF = null; if (!Constants.textonly && Constants.showProgressFrame) try { prF = new ProgressFrame(datafilenumber); } catch (NullPointerException npe) { out.println("Not able to create frame, MacOSX display sleep bug?"); } printf("Extracting positions for dataset: " + toXRDcatString(), prF); boolean computed1 = false; for (int k = 0; k < datafilenumber; k++) { if (getActiveDataFile(k).computeExpStrain(asample)) computed1 = true; if (prF != null) prF.increaseProgressBarValue(); } if (prF != null) { prF.setVisible(false); prF.dispose(); } // prF = null; if (computed1) refreshAll(false); } public int getIntensityExtractorID() { return 0; } public void setIntensityExtractor(String value) { if (subordinateField[getIntensityExtractorID()] == null || !value.equals((subordinateField[getIntensityExtractorID()]).identifier)) setsubordinateField(getIntensityExtractorID(), value); } public void setIntensityExtractor(int number) { setIntensityExtractor(getsubordIdentifier(getIntensityExtractorID(), number)); } public IntensityExtractor getIntensityExtractor() { if (subordinateField[getIntensityExtractorID()] == null) setIntensityExtractor(0); return (IntensityExtractor) subordinateField[getIntensityExtractorID()]; } public String getIntensityExtractorMethod() { return getIntensityExtractor().identifier; } public int getPositionExtractorID() { return 1; } public void setPositionExtractor(String value) { if (subordinateField[getPositionExtractorID()] == null || !value.equals((subordinateField[getPositionExtractorID()]).identifier)) setsubordinateField(getPositionExtractorID(), value); } public void setPositionExtractor(int number) { setPositionExtractor(getsubordIdentifier(getPositionExtractorID(), number)); } public PositionExtractor getPositionExtractor() { if (subordinateField[getPositionExtractorID()] == null) setPositionExtractor(0); return (PositionExtractor) subordinateField[getPositionExtractorID()]; } public String getPositionExtractorMethod() { return getPositionExtractor().identifier; } public int getReflectivityID() { return 2; } public void setReflectivity(String value) { if (subordinateField[getReflectivityID()] == null || !value.equals((subordinateField[getReflectivityID()]).identifier)) setsubordinateField(getReflectivityID(), value); } public void setReflectivity(int number) { setReflectivity(getsubordIdentifier(getReflectivityID(), number)); } public Reflectivity getReflectivity() { if (subordinateField[getReflectivityID()] == null) setReflectivity(0); return (Reflectivity) subordinateField[getReflectivityID()]; } public String getReflectivityMethod() { return getReflectivity().identifier; } public boolean needReflectivityStatistic() { return getReflectivity().needReflectivityStatistic(); } public int getDiffractionID() { return 5; } public void setDiffraction(String value) { if (subordinateField[getDiffractionID()] == null || !value.equals((subordinateField[getDiffractionID()]).identifier)) setsubordinateField(getDiffractionID(), value); } public void setDiffraction(int number) { setFluorescence(getsubordIdentifier(getDiffractionID(), number)); } public Diffraction getDiffraction() { if (subordinateField[getDiffractionID()] == null) setDiffraction(0); return (Diffraction) subordinateField[getDiffractionID()]; } public String getDiffractionMethod() { return getDiffraction().identifier; } public int getFluorescenceID() { return 4; } public void setFluorescence(String value) { if (subordinateField[getFluorescenceID()] == null || !value.equals((subordinateField[getFluorescenceID()]).identifier)) setsubordinateField(getFluorescenceID(), value); } public void setFluorescence(int number) { setFluorescence(getsubordIdentifier(getFluorescenceID(), number)); } public Fluorescence getFluorescence() { if (subordinateField[getFluorescenceID()] == null) setFluorescence(0); return (Fluorescence) subordinateField[getFluorescenceID()]; } public String getFluorescenceMethod() { return getFluorescence().identifier; } public boolean needFluorescenceStatistic() { return getFluorescence().needFluorescenceStatistic(); } public void fittingFileOutput(boolean addStatisticalError, boolean phaseOutput) { int datafilenumber = activedatafilesnumber(); for (int i = 0; i < datafilenumber; i++) { DiffrDataFile adtafile1 = getActiveDataFile(i); if (phaseOutput) adtafile1.fittingPhaseOutput(getSample(), addStatisticalError); else adtafile1.fittingFileOutput(addStatisticalError, 0); } } public void freeAllBackgroundParameters() { int numbercoef = numbercoefbackg(); for (int k = 0; k < numbercoef; k++) getbackgcoef(k).setRefinableCheckBound(); numbercoef = numbercoefbackgChi(); for (int k = 0; k < numbercoef; k++) getbackgcoefChi(k).setRefinableCheckBound(); numbercoef = numbercoefbackgEta(); for (int k = 0; k < numbercoef; k++) getbackgcoefEta(k).setRefinableCheckBound(); int numberofpeak1 = backgpeaksnumber(); for (int k = 0; k < numberofpeak1; k++) getBkgPeak(k).freeAllBackgroundParameters(); int datafilenumber = activedatafilesnumber(); for (int i = 0; i < datafilenumber; i++) { getActiveDataFile(i).freeAllBackgroundParameters(); } } public void boundMonitorsByBank() { int datafilenumber = activedatafilesnumber(); for (int i = 0; i < datafilenumber; i++) { DiffrDataFile adatafile1 = getActiveDataFile(i); int bankNumber = adatafile1.getBankNumber(); for (int j = 0; j < i; j++) { DiffrDataFile adatafile2 = getActiveDataFile(j); int bankNumber2 = adatafile2.getBankNumber(); if (bankNumber == bankNumber2) { adatafile1.setEqualTo(adatafile2, false); break; } } } } public void boundMonitorsByAngles(boolean[] useAngle) { int datafilenumber = activedatafilesnumber(); for (int i = 0; i < datafilenumber; i++) { DiffrDataFile adatafile1 = getActiveDataFile(i); double[] angles = adatafile1.getTiltingAngle(); for (int j = 0; j < i; j++) { DiffrDataFile adatafile2 = getActiveDataFile(j); double[] angles2 = adatafile2.getTiltingAngle(); boolean sameAngles = true; for (int k = 0; k < angles.length; k++) { if (useAngle[k] && angles[k] != angles2[k]) { sameAngles = false; break; } } if (sameAngles) { adatafile1.setEqualTo(adatafile2, false); break; } } } } public void freeAllScaleParameters() { getInstrument().freeAllScaleParameters(); } public boolean freeAllBasicParameters() { int datafilenumber = activedatafilesnumber(); for (int i = 0; i < datafilenumber; i++) getActiveDataFile(i).freeAllBasicParameters(); return getInstrument().freeAllBasicParameters(); } public void fixAllBackgroundParametersPreserveBound() { int numbercoef = numbercoefbackg(); for (int k = 0; k < numbercoef; k++) getbackgcoef(k).setNotRefinableCheckBound(); numbercoef = numbercoefbackgChi(); for (int k = 0; k < numbercoef; k++) getbackgcoefChi(k).setNotRefinableCheckBound(); numbercoef = numbercoefbackgEta(); for (int k = 0; k < numbercoef; k++) getbackgcoefEta(k).setNotRefinableCheckBound(); int numberofpeak1 = backgpeaksnumber(); for (int k = 0; k < numberofpeak1; k++) getBkgPeak(k).fixAllParametersPreserveBound(); for (int i = 0; i < activedatafilesnumber(); i++) getActiveDataFile(i).fixAllBackgroundParametersPreserveBound(); } public void freeAllCountMonitors() { for (int i = 0; i < activedatafilesnumber(); i++) getActiveDataFile(i).freeAllCountMonitors(); } public void freeAllShiftsParameters(boolean forceFree) { if (!getInstrument().refineAllZEROBankCoefficients(forceFree)) for (int i = 0; i < activedatafilesnumber(); i++) getActiveDataFile(i).freeThetaParameters(); } public void freeAllShiftsParameters() { for (int i = 0; i < activedatafilesnumber(); i++) getActiveDataFile(i).freeThetaParameters(); } public void refineAllXYSampleDisplacements() { for (int i = 0; i < activedatafilesnumber(); i++) getActiveDataFile(i).refineAllXYSampleDisplacements(); } public void fixAllCountMonitorsPreserveBound() { for (int i = 0; i < activedatafilesnumber(); i++) getActiveDataFile(i).fixAllCountMonitorsPreserveBound(); } @Override public void writeSubordinate(BufferedWriter out, String dicstring, XRDcat subordinate) { try { if (subordinate != null) { String name = subordinate.toXRDcatString(); if (subordinate instanceof DiffrDataFile) name = ((DiffrDataFile) subordinate).getNameRelativeToPar(); out.newLine(); out.write("#subordinateObject_" + name); out.newLine(); out.newLine(); out.write(dicstring + " '" + name + '\''); out.newLine(); out.newLine(); subordinate.writeParameters(out); out.newLine(); out.write("#end_subordinateObject_" + name); out.newLine(); out.newLine(); } } catch (IOException ioe) { System.out.println("Error in writing the subordinate object " + toXRDcatString()); } } public void sortPeakArray() { sort(thepeaklist, new dhklComparer()); } public void resetPeakArray() { thepeaklist = new Vector<Peak>(100, 100); } public Vector<Peak> getPeakList() { return thepeaklist; } public Peak getPeak(int i) { return thepeaklist.elementAt(i); } public int getNumberofPeaks() { return thepeaklist.size(); } @Override public void edit(Frame aframe) { (new DataD(aframe, this)).setVisible(true); } public void sortByBankNumber() { sort(getDataFileList(), new datafileBankComparer()); getDataFileList().updateList(); } public void sortByAngles(int[] order) { sort(getDataFileList(), new datafileAnglesComparer(order)); getDataFileList().updateList(); } public void sortByName() { sort(getDataFileList(), new datafileNameComparer()); getDataFileList().updateList(); } public void addAnglesToMeasurement(double[] angles) { int maxNumber = angles.length; int[] mult = new int[maxNumber]; double[] offset = new double[maxNumber]; for (int i = 0; i < maxNumber; i++) { mult[i] = 1; offset[i] = angles[i]; } for (int i = 0; i < datafilesnumber(); i++) { DiffrDataFile tmpdatafile = getDataFile(i); tmpdatafile.setNewAngles(mult, offset); } } public void changeBackgroundInterpolation() { int datafilenumber = datafilesnumber(); int maxrange = 0; int oldInterval = getInterpolatedPointsValue(); int newInterval = -1; for (int i = 0; i < datafilenumber; i++) { int range = Math.abs(getDataFile(i).finalindex - getDataFile(i).startingindex); if (newInterval == -1) newInterval = range / oldInterval; if (maxrange < range) { newInterval = range / oldInterval; maxrange = range; } } setInterpolatedPoints(newInterval); } public int getNumberOfTexturePoints(Phase aphase, int hklnumbersel) { int total = 0; for (int i = 0; i < activedatafilesnumber(); i++) { DiffrDataFile adatafile = getActiveDataFile(i); for (int j = 0; j < adatafile.positionsPerPattern; j++) { boolean goodPoint = adatafile.isInsideRange(adatafile.getPositions(aphase)[hklnumbersel][j][0]); // System.out.println(goodPoint); if (goodPoint) total++; } } return total; } public void useCountTimeAllSelectedFiles(boolean status) { Vector datafiles = getSelectedDatafiles(); if (datafiles == null) { (new AttentionD(new Frame(), "No item from the list selected!")).setVisible(true); return; } int datafilenumber = datafiles.size(); for (int i = 0; i < datafilenumber; i++) { DiffrDataFile tmpdatafile = (DiffrDataFile) datafiles.elementAt(i); tmpdatafile.useCountTimeToScale(status); } } public boolean isDiffraction() { if (getFluorescence().identifier.toLowerCase().startsWith("none") && getReflectivity().identifier.toLowerCase().startsWith("none")) return true; return false; } static class datafileAnglesComparer implements Comparator { int[] order; public datafileAnglesComparer(int[] order) { this.order = order; } public int compare(Object obj1, Object obj2) { double[] angles1 = ((DiffrDataFile) obj1).getTiltingAngle(); double[] angles2 = ((DiffrDataFile) obj2).getTiltingAngle(); // for (int ordervalue : order) { for (int ordervalue : order) { double diff = angles2[ordervalue] - angles1[ordervalue]; if (diff != 0.0) { if (diff > 0) return -1; return 1; } } return 0; } } class datafileNameComparer implements Comparator { public int compare(Object obj1, Object obj2) { String name1 = ((DiffrDataFile) obj1).getLabel(); String name2 = ((DiffrDataFile) obj2).getLabel(); int len1 = name1.length(); int len2 = name2.length(); int minLength = Math.min(len1, len2); for (int i = 0; i < minLength; i++) { int diff = name2.charAt(i) - name1.charAt(i); if (diff != 0.0) { if (diff > 0) return -1; return 1; } } int diff = len2 - len1; if (diff == 0.0) return 0; else if (diff > 0) return -1; return 1; } } static class datafileBankComparer implements Comparator { public int compare(Object obj1, Object obj2) { int bank1 = ((DiffrDataFile) obj1).getBankNumber(); int bank2 = ((DiffrDataFile) obj2).getBankNumber(); int diff = bank2 - bank1; if (diff == 0.0) return 0; else if (diff > 0) return -1; return 1; } } static class dhklComparer implements Comparator { public int compare(Object obj1, Object obj2) { Reflection refl1 = ((Peak) obj1).getReflex(); Reflection refl2 = ((Peak) obj2).getReflex(); double dspace1 = refl1.d_space; double dspace2 = refl2.d_space; double diff = dspace1 - dspace2; if (diff == 0.0) return 0; else if (diff > 0) return -1; return 1; } } class AngleComparator implements Comparator { public int selectedAngle = 0; AngleComparator(int index) { selectedAngle = index; } public int compare(Object obj1, Object obj2) { double dspace1 = ((DiffrDataFile) obj1).getTiltingAngle()[selectedAngle]; double dspace2 = ((DiffrDataFile) obj2).getTiltingAngle()[selectedAngle]; double diff = dspace1 - dspace2; if (diff == 0.0) return 0; else if (diff > 0) return 1; return -1; } } }
package com.beegman.webbee.block; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import javax.servlet.http.HttpServletResponse; import org.aldan3.util.Stream; import org.aldan3.util.inet.HttpUtils; import com.beegman.webbee.base.BaseBlock; import com.beegman.webbee.model.AppModel; /** This class take care of asynchronous storing attachments * * <p> How to manage post load and store<br> WebBee design intention to reduce * number of explicit intercepter methods and utilize OO principles, so if * any intercepter is required, then methods <code>storeAttachment</code> or <code>loadAttachment</code> * have to be overridden with adding intercepter code. * * * * * @author Dmitriy * */ public class Attach<A extends AppModel> extends BaseBlock<A> { protected String attachId; private boolean downloadRequest; @Override protected Object doControl() { downloadRequest = false; String fileName = getParameterValue("browsefile+filename", "", 0); String attachId = generateId(fileName); HashMap pageMap = (HashMap) getModel(); if (attachId != null) { //log("............Storing......." + fileName + " with " + attachId, null); try { storeAttachment(getObjectParameterValue("browsefile", null, 0, false), attachId); pageMap.put("id", attachId); pageMap.put("filename", extractFileName(fileName)); } catch (IOException e) { pageMap.put("error", 1); log("error", e); } } resp.setContentType("application/json; charset=UTF-8"); return pageMap; } private String extractFileName(String filePath) { int lsl = filePath.lastIndexOf('/'); int lbsl = filePath.lastIndexOf('\\'); if (lsl < lbsl) lsl = lbsl; if (lsl < 0) return filePath; return filePath.substring(lsl+1); } @Override protected Object getModel(){ //try { attachId = null; attachId = getId(); if (attachId == null) { try { resp.sendError(HttpServletResponse.SC_FORBIDDEN); } catch (IOException e) { log("",e); } return null; } if (attachId.length() > 0) { downloadRequest = true; resp.setContentType(getAttachContentType(attachId)); if (getParameterValue("download", 0, 0) == 1) resp.setHeader("Content-disposition", "attachment; filename=\"" + getName(attachId) + '"'); try { loadAttachment(attachId, resp.getOutputStream()); } catch (IOException e) { log("problem in download attachment", e); } return null; } downloadRequest = false; HashMap pageMap = new HashMap(); pageMap.put("divid", getParameterValue("divid", "??", 0)); pageMap.put("name", getParameterValue("name", "??", 0)); pageMap.put("target", getParameterValue("target", "??", 0)); pageMap.put("upload", getParameterValue("upload", 0, 0)); return pageMap;//}catch(Throwable t) {log("==>", t);} return null; } @Override protected String getSubmitPage() { return null; } @Override protected String getViewName() { if ("json".equals(getParameterValue("response", "", 0))) return "attach_json" + getConfigValue(CONFIG_VIEWEXT, VIEW_EXT); // getResourceName() return super.getViewName(); } @Override protected void visit() { } @Override protected boolean useLabels() { return false; } @Override protected String getCanvasView() { return null; } @Override protected boolean canCache() { return downloadRequest; } @Override protected long getLastModified() { try { return getAttachmentFile(attachId).lastModified(); } catch (IOException e) { log("", e); } return -1; } protected String generateId(String fileName) { // TODO not reliable, perhaps replace with UDDI return "" + (long) (10000000 * Math.random() / 1) + ext(fileName); } protected String getId() { return getParameterValue("id", "", 0); } protected String ext(String filename) { int ldp = filename.lastIndexOf('.'); if (ldp > 0) return filename.substring(ldp); return "."; } protected void storeAttachment(Object attachment, String id) throws IOException { File attachFile = getAttachmentFile(id); File attachFolder = attachFile.getParentFile(); if (attachFolder != null) attachFolder.mkdirs(); if (attachment instanceof byte[]) { FileOutputStream fos = new FileOutputStream(attachFile); try { fos.write((byte[]) attachment); fos.flush(); } finally { fos.close(); } } else if (attachment instanceof File) { Stream.copyFile((File) attachment, attachFile); } else if (attachment instanceof String) { FileWriter fw = new FileWriter(attachFile); try { fw.write((String) attachment); } finally { fw.close(); } } else log("Not implemented storing of " + attachment, null); } protected File getAttachmentFile(String id) throws IOException { return new File(getAttachmentRoot(), id.replaceAll("/", "_").replaceAll("\\\\", "_")); } protected File getAttachmentRoot() { return getAppModel().getAttachmentHome(); } protected boolean loadAttachment(String id, OutputStream os) throws IOException { InputStream is = null; try { File af = getAttachmentFile(id); long flen = af.length(); resp.setDateHeader("Last-modified", af.lastModified()); String range = req.getHeader("Range"); if (range != null) { long[] rr = HttpUtils.parseRangeHeader(range, flen); if (rr != null && rr[1] > 0) { if (rr[0] > rr[1] || rr[1] >= flen) { reportRangeError(flen); return false; } is = new FileInputStream(af); long sl = is.skip(rr[0]); if (rr[0] != sl) { reportRangeError(flen); return false; } long clen = rr[1]-rr[0]+1; resp.setHeader("content-length", String.valueOf(clen)); resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); resp.setHeader("Content-Range", HttpUtils.BYTES_UNIT + " " + rr[0] + '-' + rr[1] + '/' + flen); Stream.copyStream(is, os, clen); return rr[1] == (flen -1); } } resp.setHeader("content-length", String.valueOf(flen)); resp.setHeader("Accept-Ranges", HttpUtils.BYTES_UNIT); Stream.copyStream(is = new FileInputStream(getAttachmentFile(id)), os, 0); return true; } finally { // TODO consider possible masking of original exception if (is != null) is.close(); } } protected void reportRangeError(long flen) { resp.setHeader("Content-Range", HttpUtils.BYTES_UNIT + " */" + flen); resp.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); } protected String getAttachContentType(String id) { return frontController.getServletContext().getMimeType(id); } protected String getName(String id) { return id; } }
package com.sun.facelets.tag.ui; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.faces.component.UIComponentBase; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.servlet.http.HttpServletResponse; import com.sun.facelets.util.DevTools; import com.sun.facelets.util.FastWriter; /** * @author Jacob Hookom * @version $Id: UIDebug.java,v 1.5 2006-05-09 02:49:40 adamwiner Exp $ */ public final class UIDebug extends UIComponentBase { public final static String COMPONENT_TYPE = "facelets.ui.Debug"; public final static String COMPONENT_FAMILY = "facelets"; private static long nextId = System.currentTimeMillis(); private final static String KEY = "facelets.ui.DebugOutput"; public final static String DEFAULT_HOTKEY = "D"; private String hotkey = DEFAULT_HOTKEY; public UIDebug() { super(); this.setTransient(true); this.setRendered(true); this.setRendererType(null); } public String getFamily() { return COMPONENT_FAMILY; } public List getChildren() { return new ArrayList() { public boolean add(Object o) { throw new IllegalStateException("<ui:debug> does not support children"); } public void add(int index, Object o) { throw new IllegalStateException("<ui:debug> does not support children"); } }; } public void encodeBegin(FacesContext faces) throws IOException { String actionId = faces.getApplication().getViewHandler().getActionURL(faces, faces.getViewRoot().getViewId()); StringBuffer sb = new StringBuffer(512); sb.append("<script language=\"javascript\" type=\"text/javascript\">\n"); sb.append("//<![CDATA[\n"); sb.append("function faceletsDebug(URL) { day = new Date(); id = day.getTime(); eval(\"page\" + id + \" = window.open(URL, '\" + id + \"', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=800,height=600,left = 240,top = 212');\"); };"); sb.append("var faceletsOrigKeyup = document.onkeyup; document.onkeyup = function(e) { if (window.event) e = window.event; if (String.fromCharCode(e.keyCode) == '" + this.getHotkey() + "' & e.shiftKey & e.ctrlKey) faceletsDebug('"); sb.append(actionId); sb.append('?'); sb.append(KEY); sb.append('='); sb.append(writeDebugOutput(faces)); sb.append("'); else if (faceletsOrigKeyup) faceletsOrigKeyup(e); };\n"); sb.append(" sb.append("</script>\n"); ResponseWriter writer = faces.getResponseWriter(); writer.write(sb.toString()); } private static String writeDebugOutput(FacesContext faces) throws IOException { FastWriter fw = new FastWriter(); DevTools.debugHtml(fw, faces); Map session = faces.getExternalContext().getSessionMap(); Map debugs = (Map) session.get(KEY); if (debugs == null) { debugs = new LinkedHashMap() { protected boolean removeEldestEntry(Entry eldest) { return (this.size() > 5); } }; session.put(KEY, debugs); } String id = "" + nextId++; debugs.put(id, fw.toString()); return id; } private static String fetchDebugOutput(FacesContext faces, String id) { Map session = faces.getExternalContext().getSessionMap(); Map debugs = (Map) session.get(KEY); if (debugs != null) { return (String) debugs.get(id); } return null; } public static boolean debugRequest(FacesContext faces) { String id = (String) faces.getExternalContext().getRequestParameterMap().get(KEY); if (id != null) { Object resp = faces.getExternalContext().getResponse(); if (!faces.getResponseComplete() && resp instanceof HttpServletResponse) { try { HttpServletResponse httpResp = (HttpServletResponse) resp; String page = fetchDebugOutput(faces, id); if (page != null) { httpResp.setContentType("text/html"); httpResp.getWriter().write(page); } else { httpResp.setContentType("text/plain"); httpResp.getWriter().write("No Debug Output Available"); } httpResp.flushBuffer(); faces.responseComplete(); } catch (IOException e) { return false; } return true; } } return false; } public String getHotkey() { return this.hotkey; } public void setHotkey(String hotkey) { this.hotkey = (hotkey != null) ? hotkey.toUpperCase() : ""; } }
package krasa.formatter.utils; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.ReadonlyStatusHandler; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import krasa.formatter.eclipse.FileDoesNotExistsException; import krasa.formatter.exception.ParsingFailedException; import krasa.formatter.plugin.InvalidPropertyFile; import org.jetbrains.annotations.NotNull; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilderFactory; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * @author Vojtech Krasa */ public class FileUtils { private static final Logger LOG = Logger.getInstance(FileUtils.class.getName()); public static boolean isWritable(@NotNull VirtualFile file, @NotNull Project project) { return !ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(file).hasReadonlyFiles(); } public static boolean isWholeFile(int startOffset, int endOffset, String text) { return startOffset == 0 && endOffset == text.length(); } public static boolean isJavaScript(PsiFile psiFile) { FileType fileType = psiFile.getFileType(); return StdFileTypes.JS.equals(fileType) || "JavaScript".equals(fileType.getName()); } public static boolean isCpp(PsiFile psiFile) { String name = psiFile.getFileType().getName(); return name.equals("C++") || name.equals("C/C++") || name.equals("ObjectiveC") ; // CLion calls it ObjectiveC... wtf } public static boolean isJava(PsiFile psiFile) { return StdFileTypes.JAVA.equals(psiFile.getFileType()); } public static Properties readPropertiesFile(File file, Properties defaultConfig) { if (!file.exists()) { throw new FileDoesNotExistsException(file); } BufferedInputStream stream = null; final Properties formatterOptions; try { stream = new BufferedInputStream(new FileInputStream(file)); formatterOptions = new Properties(defaultConfig); formatterOptions.load(stream); } catch (IOException e) { throw new RuntimeException("config file read error", e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { /* ignore */ } } } return formatterOptions; } public static Properties readPropertiesFile(File file) { return readPropertiesFile(file, null); } public static Properties readXmlJavaSettingsFile(File file, Properties properties, String profile) { int defaultSize = properties.size(); if (!file.exists()) { throw new FileDoesNotExistsException(file); } if (profile == null) { throw new IllegalStateException("no profile selected, go to settings and select proper settings file"); } boolean profileFound = false; try { // load file profiles org.w3c.dom.Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file); doc.getDocumentElement().normalize(); NodeList profiles = doc.getElementsByTagName("profile"); if (profiles.getLength() == 0) { throw new IllegalStateException( "loading of profile settings failed, file does not contain any profiles"); } for (int temp = 0; temp < profiles.getLength(); temp++) { Node profileNode = profiles.item(temp); if (profileNode.getNodeType() == Node.ELEMENT_NODE) { Element profileElement = (Element) profileNode; String name = profileElement.getAttribute("name"); if (profile.equals(name)) { profileFound = true; NodeList childNodes = profileElement.getElementsByTagName("setting"); if (childNodes.getLength() == 0) { throw new IllegalStateException( "loading of profile settings failed, profile has no settings elements"); } for (int i = 0; i < childNodes.getLength(); i++) { Node item = childNodes.item(i); if (item.getNodeType() == Node.ELEMENT_NODE) { Element attributeItem = (Element) item; String id = attributeItem.getAttribute("id"); String value = attributeItem.getAttribute("value"); properties.setProperty(id.trim(), value.trim()); } } } } } } catch (Exception e) { LOG.error("file: " + file.getAbsolutePath() + ", profile: " + profile, e); throw new InvalidPropertyFile(e.getMessage(), e); } if (!profileFound) { throw new IllegalStateException("profile not found in the file " + file.getAbsolutePath()); } if (properties.size() == defaultSize) { throw new IllegalStateException("no properties loaded, something is broken, file:" + file.getAbsolutePath()); } return properties; } public static List<String> getProfileNamesFromConfigXML(File file) throws ParsingFailedException { List<String> profileNames = new ArrayList<String>(); if (file.exists()) { try { // load file profiles // delete eclipse dependency to fix java.lang.ClassCastException: // org.apache.xerces.jaxp.DocumentBuilderFactoryImpl cannot be cast to // javax.xml.parsers.DocumentBuilderFactory org.w3c.dom.Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("profile"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String name = eElement.getAttribute("name"); profileNames.add(name); } } } catch (Exception e) { LOG.info(e); throw new ParsingFailedException(e); } } else { LOG.info("not existing file"); } return profileNames; } }
package org.jdesktop.swingx; import java.awt.Color; import java.awt.Cursor; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Paint; import java.awt.Point; import java.awt.RenderingHints; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.awt.image.BufferedImageOp; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.List; import javax.imageio.ImageIO; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JList; import javax.swing.TransferHandler; import javax.swing.event.MouseInputAdapter; import org.jdesktop.swingx.color.ColorUtil; /** * a panel which shows an image centered. the user can drag an image into the panel * to display it. The view has built in actions for * scaling, * rotating, * opening a new image, and * cropping. * * has dashed rect and text indicating you should drag there. * * allows user to drag image within the panel, if allowed. shows move cursor * or hand cursor. * * allows to set a crop/ restriction rect, if allowed * * * JXImageView allows a user to drag photos into the well. If the user drags * more than one photo at a time the first photo will be loaded and shown in the well. * * JXImageView provides actions to do common image operations like rotation, opening * and saving, and zooming. * * @author joshy */ public class JXImageView extends JXPanel { // the image this view will show private Image image; // location to draw image. if null then draw in the center private Point2D imageLocation; private Paint checkerPaint; /** Creates a new instance of JXImageView */ public JXImageView() { MouseInputAdapter mia = new MoveHandler(); addMouseMotionListener(mia); addMouseListener(mia); this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); this.setTransferHandler(new DnDHandler()); checkerPaint = ColorUtil.getCheckerPaint(Color.white,new Color(250,250,250),50); } public Point2D getImageLocation() { return imageLocation; } public void setImageLocation(Point2D imageLocation) { this.imageLocation = imageLocation; } public Image getImage() { return image; } public void setImage(Image image) { this.image = image; setImageLocation(null); repaint(); } public void setImage(URL url) throws IOException { setImage(ImageIO.read(url)); } public void setImage(File file) throws IOException { setImage(ImageIO.read(file)); } // an action which will open a file chooser and load the selected image // if any. public Action getOpenAction() { Action action = new AbstractAction() { public void actionPerformed(ActionEvent actionEvent) { JFileChooser chooser = new JFileChooser(); chooser.showOpenDialog(JXImageView.this); File file = chooser.getSelectedFile(); if(file != null) { try { setImage(file); } catch (IOException ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); } } } }; action.putValue(Action.NAME,"Open"); return action; } // an action that will open a file chooser then save the current image to // the selected file, if any. public Action getSaveAction() { Action action = new AbstractAction() { public void actionPerformed(ActionEvent evt) { Image img = getImage(); BufferedImage dst = new BufferedImage( img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D)dst.getGraphics(); // smooth scaling g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g.drawImage(img,0,0,null); g.dispose(); JFileChooser chooser = new JFileChooser(); chooser.showSaveDialog(JXImageView.this); File file = chooser.getSelectedFile(); if(file != null) { try { ImageIO.write(dst,"png",file); } catch (IOException ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); } } } }; action.putValue(Action.NAME,"Save"); return action; } public Action getRotateClockwiseAction() { Action action = new AbstractAction() { public void actionPerformed(ActionEvent evt) { Image img = getImage(); BufferedImage src = new BufferedImage( img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); BufferedImage dst = new BufferedImage( img.getHeight(null), img.getWidth(null), BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D)src.getGraphics(); // smooth scaling g.drawImage(img,0,0,null); g.dispose(); AffineTransform trans = AffineTransform.getRotateInstance(Math.PI/2,0,0); trans.translate(0,-src.getHeight()); BufferedImageOp op = new AffineTransformOp(trans, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); Rectangle2D rect = op.getBounds2D(src); op.filter(src,dst); setImage(dst); } }; action.putValue(Action.NAME,"Rotate Clockwise"); return action; } public Action getRotateCounterClockwiseAction() { Action action = new AbstractAction() { public void actionPerformed(ActionEvent evt) { Image img = getImage(); BufferedImage src = new BufferedImage( img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); BufferedImage dst = new BufferedImage( img.getHeight(null), img.getWidth(null), BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D)src.getGraphics(); // smooth scaling g.drawImage(img,0,0,null); g.dispose(); AffineTransform trans = AffineTransform.getRotateInstance(-Math.PI/2,0,0); trans.translate(-src.getWidth(),0); BufferedImageOp op = new AffineTransformOp(trans, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); Rectangle2D rect = op.getBounds2D(src); op.filter(src,dst); setImage(dst); } }; action.putValue(Action.NAME, "Rotate CounterClockwise"); return action; } protected void paintComponent(Graphics g) { ((Graphics2D)g).setPaint(checkerPaint); //g.setColor(getBackground()); g.fillRect(0,0,getWidth(),getHeight()); if(getImage() != null) { if(getImageLocation() == null) { g.drawImage(getImage(), (getWidth()-getImage().getWidth(null))/2, (getHeight()-getImage().getHeight(null))/2, null); } else { g.drawImage(getImage(), (int)getImageLocation().getX(), (int)getImageLocation().getY(), null); } } } private class MoveHandler extends MouseInputAdapter { private Point prev = null; public void mousePressed(MouseEvent evt) { prev = evt.getPoint(); } public void mouseDragged(MouseEvent evt) { Point curr = evt.getPoint(); int offx = curr.x - prev.x; int offy = curr.y - prev.y; Point2D offset = getImageLocation(); if (offset == null) { if (image != null) { offset = new Point2D.Double((getWidth() - getImage().getWidth(null)) / 2, (getHeight() - getImage().getHeight(null)) / 2); } else { offset = new Point2D.Double(0, 0); } } offset = new Point2D.Double(offset.getX() + offx, offset.getY() + offy); setImageLocation(offset); prev = curr; repaint(); } public void mouseReleased(MouseEvent evt) { prev = null; } } private class DnDHandler extends TransferHandler { public boolean canImport(JComponent c, DataFlavor[] flavors) { for (int i = 0; i < flavors.length; i++) { if (DataFlavor.javaFileListFlavor.equals(flavors[i])) { return true; } } return false; } public boolean importData(JComponent comp, Transferable t) { if (canImport(comp, t.getTransferDataFlavors())) { try { List files = (List) t.getTransferData(DataFlavor.javaFileListFlavor); if (files.size() > 0) { File file = (File) files.get(0); BufferedImage img = ImageIO.read(file); setImage(img); return true; } } catch (Exception ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); } } return false; } } }
package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Container; import java.awt.Cursor; import java.awt.Dialog; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.Insets; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Robot; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowFocusListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractListModel; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JProgressBar; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.auth.DefaultUserNameStore; import org.jdesktop.swingx.auth.LoginAdapter; import org.jdesktop.swingx.auth.LoginEvent; import org.jdesktop.swingx.auth.LoginListener; import org.jdesktop.swingx.auth.LoginService; import org.jdesktop.swingx.auth.PasswordStore; import org.jdesktop.swingx.auth.UserNameStore; import org.jdesktop.swingx.painter.MattePainter; import org.jdesktop.swingx.plaf.LoginPaneAddon; import org.jdesktop.swingx.plaf.LoginPaneUI; import org.jdesktop.swingx.plaf.LookAndFeelAddons; import org.jdesktop.swingx.plaf.UIManagerExt; import org.jdesktop.swingx.util.WindowUtils; /** * <p>JXLoginPane is a JPanel that implements a Login dialog with * support for saving passwords supplied for future use in a secure * manner. It is intended to work with <strong>LoginService</strong> * and <strong>PasswordStore</strong> to implement the * authentication.</p> * * <p> In order to perform the authentication, <strong>JXLoginPane</strong> * calls the <code>authenticate</code> method of the <strong>LoginService * </strong>. In order to perform the persistence of the password, * <strong>JXLoginPane</strong> calls the put method of the * <strong>PasswordStore</strong> object that is supplied. If * the <strong>PasswordStore</strong> is <code>null</code>, then the password * is not saved. Similarly, if a <strong>PasswordStore</strong> is * supplied and the password is null, then the <strong>PasswordStore</strong> * will be queried for the password using the <code>get</code> method. * * @author Bino George * @author Shai Almog * @author rbair * @author Karl Schaefer * @author rah003 */ public class JXLoginPane extends JXImagePanel { /** * The Logger */ private static final Logger LOG = Logger.getLogger(JXLoginPane.class.getName()); /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = 3544949969896288564L; /** * UI Class ID */ public final static String uiClassID = "LoginPaneUI"; /** * Action key for an Action in the ActionMap that initiates the Login * procedure */ public static final String LOGIN_ACTION_COMMAND = "login"; /** * Action key for an Action in the ActionMap that cancels the Login * procedure */ public static final String CANCEL_LOGIN_ACTION_COMMAND = "cancel-login"; /** * The JXLoginPane can attempt to save certain user information such as * the username, password, or both to their respective stores. * This type specifies what type of save should be performed. */ public static enum SaveMode {NONE, USER_NAME, PASSWORD, BOTH} /** * Returns the status of the login process */ public enum Status {NOT_STARTED, IN_PROGRESS, FAILED, CANCELLED, SUCCEEDED} /** * Used as a prefix when pulling data out of UIManager for i18n */ private static String CLASS_NAME = JXLoginPane.class.getSimpleName(); /** * The current login status for this panel */ private Status status = Status.NOT_STARTED; /** * An optional banner at the top of the panel */ private JXImagePanel banner; /** * Text that should appear on the banner */ private String bannerText; /** * Custom label allowing the developer to display some message to the user */ private JLabel messageLabel; /** * Shows an error message such as "user name or password incorrect" or * "could not contact server" or something like that if something * goes wrong */ private JXLabel errorMessageLabel; /** * A Panel containing all of the input fields, check boxes, etc necessary * for the user to do their job. The items on this panel change whenever * the SaveMode changes, so this panel must be recreated at runtime if the * SaveMode changes. Thus, I must maintain this reference so I can remove * this panel from the content panel at runtime. */ private JXPanel loginPanel; /** * The panel on which the input fields, messageLabel, and errorMessageLabel * are placed. While the login thread is running, this panel is removed * from the dialog and replaced by the progressPanel */ private JXPanel contentPanel; /** * This is the area in which the name field is placed. That way it can toggle on the fly * between text field and a combo box depending on the situation, and have a simple * way to get the user name */ private NameComponent namePanel; /** * The password field presented allowing the user to enter their password */ private JPasswordField passwordField; /** * A combo box presenting the user with a list of servers to which they * may log in. This is an optional feature, which is only enabled if * the List of servers supplied to the JXLoginPane has a length greater * than 1. */ private JComboBox serverCombo; /** * Check box presented if a PasswordStore is used, allowing the user to decide whether to * save their password */ private JCheckBox saveCB; /** * Label displayed whenever caps lock is on. */ private JLabel capsOn; /** * A special panel that displays a progress bar and cancel button, and * which notify the user of the login process, and allow them to cancel * that process. */ private JXPanel progressPanel; /** * A JLabel on the progressPanel that is used for informing the user * of the status of the login procedure (logging in..., canceling login...) */ private JLabel progressMessageLabel; /** * The LoginService to use. This must be specified for the login dialog to operate. * If no LoginService is defined, a default login service is used that simply * allows all users access. This is useful for demos or prototypes where a proper login * server is not available. */ private LoginService loginService; /** * Optional: a PasswordStore to use for storing and retrieving passwords for a specific * user. */ private PasswordStore passwordStore; /** * Optional: a UserNameStore to use for storing user names and retrieving them */ private UserNameStore userNameStore; /** * A list of servers where each server is represented by a String. If the * list of Servers is greater than 1, then a combo box will be presented to * the user to choose from. If any servers are specified, the selected one * (or the only one if servers.size() == 1) will be passed to the LoginService */ private List<String> servers; /** * Whether to save password or username or both */ private SaveMode saveMode; /** * Tracks the cursor at the time that authentication was started, and restores to that * cursor after authentication ends, or is cancelled; */ private Cursor oldCursor; /** * The default login listener used by this panel. */ private LoginListener defaultLoginListener; private CapsOnTest capsOnTest = new CapsOnTest(); private boolean caps; private boolean isTestingCaps; private KeyEventDispatcher capsOnListener = new KeyEventDispatcher() { public boolean dispatchKeyEvent(KeyEvent e) { if (e.getID() != KeyEvent.KEY_PRESSED) { return false; } if (e.getKeyCode() == 20) { setCapsLock(!isCapsLockOn()); } return false; }}; /** * Caps lock detection support */ private boolean capsLockSupport = true; /** * Login/cancel control pane; */ private JXBtnPanel buttonPanel; /** * Window event listener responsible for triggering caps lock test on vindow activation and * focus changes. */ private CapsOnWinListener capsOnWinListener = new CapsOnWinListener(capsOnTest); private boolean initDone; /** * Creates a default JXLoginPane instance */ static { LookAndFeelAddons.contribute(new LoginPaneAddon()); } /** * Populates UIDefaults with the localizable Strings we will use * in the Login panel. */ private void reinitLocales(Locale l) { // PENDING: JW - use the locale given as parameter // as this probably (?) should be called before super.setLocale setBannerText(UIManagerExt.getString(CLASS_NAME + ".bannerString", getLocale())); banner.setImage(createLoginBanner()); // TODO: Can't change the error message since it might have been already changed by the user! //errorMessageLabel.setText(UIManager.getString(CLASS_NAME + ".errorMessage", getLocale())); progressMessageLabel.setText(UIManagerExt.getString(CLASS_NAME + ".pleaseWait", getLocale())); recreateLoginPanel(); Window w = SwingUtilities.getWindowAncestor(this); if (w instanceof JXLoginFrame) { JXLoginFrame f = (JXLoginFrame) w; f.setTitle(UIManagerExt.getString(CLASS_NAME + ".titleString", getLocale())); if (buttonPanel != null) { buttonPanel.getOk().setText(UIManagerExt.getString(CLASS_NAME + ".loginString", getLocale())); buttonPanel.getCancel().setText(UIManagerExt.getString(CLASS_NAME + ".cancelString", getLocale())); } } JLabel lbl = (JLabel) passwordField.getClientProperty("labeledBy"); if (lbl != null) { lbl.setText(UIManagerExt.getString(CLASS_NAME + ".passwordString", getLocale())); } lbl = (JLabel) namePanel.getComponent().getClientProperty("labeledBy"); if (lbl != null) { lbl.setText(UIManagerExt.getString(CLASS_NAME + ".nameString", getLocale())); } if (serverCombo != null) { lbl = (JLabel) serverCombo.getClientProperty("labeledBy"); if (lbl != null) { lbl.setText(UIManagerExt.getString(CLASS_NAME + ".serverString", getLocale())); } } saveCB.setText(UIManagerExt.getString(CLASS_NAME + ".rememberPasswordString", getLocale())); // by default, caps is initialized in off state - i.e. without warning. Setting to // whitespace preserves formatting of the panel. capsOn.setText(isCapsLockOn() ? UIManagerExt.getString(CLASS_NAME + ".capsOnWarning", getLocale()) : " "); getActionMap().get(LOGIN_ACTION_COMMAND).putValue(Action.NAME, UIManagerExt.getString(CLASS_NAME + ".loginString", getLocale())); getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND).putValue(Action.NAME, UIManagerExt.getString(CLASS_NAME + ".cancelString", getLocale())); } /** * Create a {@code JXLoginPane} that always accepts the user, never stores * passwords or user ids, and has no target servers. * <p> * This constructor should <i>NOT</i> be used in a real application. It is * provided for compliance to the bean specification and for use with visual * editors. */ public JXLoginPane() { this(null); } /** * Create a {@code JXLoginPane} with the specified {@code LoginService} * that does not store user ids or passwords and has no target servers. * * @param service * the {@code LoginService} to use for logging in */ public JXLoginPane(LoginService service) { this(service, null, null); } /** * Create a {@code JXLoginPane} with the specified {@code LoginService}, * {@code PasswordStore}, and {@code UserNameStore}, but without a server * list. * <p> * If you do not want to store passwords or user ids, those parameters can * be {@code null}. {@code SaveMode} is autoconfigured from passed in store * parameters. * * @param service * the {@code LoginService} to use for logging in * @param passwordStore * the {@code PasswordStore} to use for storing password * information * @param userStore * the {@code UserNameStore} to use for storing user information */ public JXLoginPane(LoginService service, PasswordStore passwordStore, UserNameStore userStore) { this(service, passwordStore, userStore, null); } /** * Create a {@code JXLoginPane} with the specified {@code LoginService}, * {@code PasswordStore}, {@code UserNameStore}, and server list. * <p> * If you do not want to store passwords or user ids, those parameters can * be {@code null}. {@code SaveMode} is autoconfigured from passed in store * parameters. * <p> * Setting the server list to {@code null} will unset all of the servers. * The server list is guaranteed to be non-{@code null}. * * @param service * the {@code LoginService} to use for logging in * @param passwordStore * the {@code PasswordStore} to use for storing password * information * @param userStore * the {@code UserNameStore} to use for storing user information * @param servers * a list of servers to authenticate against */ public JXLoginPane(LoginService service, PasswordStore passwordStore, UserNameStore userStore, List<String> servers) { setLoginService(service); setPasswordStore(passwordStore); setUserNameStore(userStore); setServers(servers); //create the login and cancel actions, and add them to the action map getActionMap().put(LOGIN_ACTION_COMMAND, createLoginAction()); getActionMap().put(CANCEL_LOGIN_ACTION_COMMAND, createCancelAction()); //initialize the save mode if (passwordStore != null && userStore != null) { saveMode = SaveMode.BOTH; } else if (passwordStore != null) { saveMode = SaveMode.PASSWORD; } else if (userStore != null) { saveMode = SaveMode.USER_NAME; } else { saveMode = SaveMode.NONE; } updateUI(); if (!initDone) { initComponents(); } updateUI(); } /** * Sets current state of the caps lock key as detected by the component. * @param b True when caps lock is turned on, false otherwise. */ private void setCapsLock(boolean b) { caps = b; capsOn.setText(caps ? UIManagerExt.getString(CLASS_NAME + ".capsOnWarning", getLocale()) : " "); } /** * Gets current state of the caps lock as seen by the login panel. The state seen by the login * panel and therefore returned by this method can be delayed in comparison to the real caps * lock state and displayed by the keyboard light. This is usually the case when component or * its text fields are not focused. * * @return True when caps lock is on, false otherwise. Returns always false when * <code>isCapsLockDetectionSupported()</code> returns false. */ public boolean isCapsLockOn() { return caps; } /** * Check current state of the caps lock state detection. Note that the value can change after * component have been made visible. Due to current problems in locking key state detection by * core java detection of the changes in caps lock can be always reliably determined. When * component can't guarantee reliable detection it will switch it off. This is usually the case * for unsigned applets and webstart invoked application. Since your users are going to pass * their password in the component you should always sign it when distributing application over * the network. * @return True if changes in caps lock state can be monitored by the component, false otherwise. */ public boolean isCapsLockDetectionSupported() { return capsLockSupport; } /** * {@inheritDoc} */ public LoginPaneUI getUI() { return (LoginPaneUI) super.getUI(); } /** * Sets the look and feel (L&F) object that renders this component. * * @param ui the LoginPaneUI L&F object * @see javax.swing.UIDefaults#getUI */ public void setUI(LoginPaneUI ui) { super.setUI(ui); } /** * Notification from the <code>UIManager</code> that the L&F has changed. * Replaces the current UI object with the latest version from the * <code>UIManager</code>. * * @see javax.swing.JComponent#updateUI */ public void updateUI() { if (!initDone) { // called by jpanel <init> when components are not ready yet. return; } setUI((LoginPaneUI) LookAndFeelAddons.getUI(this, LoginPaneUI.class)); } /** * Returns the name of the L&F class that renders this component. * * @return the string {@link #uiClassID} * @see javax.swing.JComponent#getUIClassID * @see javax.swing.UIDefaults#getUI */ public String getUIClassID() { return uiClassID; } /** * Recreates the login panel, and replaces the current one with the new one */ protected void recreateLoginPanel() { contentPanel.remove(loginPanel); loginPanel = createLoginPanel(); loginPanel.setBorder(BorderFactory.createEmptyBorder(0, 36, 7, 11)); contentPanel.add(loginPanel, 1); } /** * Creates and returns a new LoginPanel, based on the SaveMode state of * the login panel. Whenever the SaveMode changes, the panel is recreated. * I do this rather than hiding/showing components, due to a cleaner * implementation (no invisible components, components are not sharing * locations in the LayoutManager, etc). */ private JXPanel createLoginPanel() { JXPanel loginPanel = new JXPanel(); //create the NameComponent if (saveMode == SaveMode.NONE) { namePanel = new SimpleNamePanel(); } else { namePanel = new ComboNamePanel(userNameStore); } JLabel nameLabel = new JLabel(UIManagerExt.getString(CLASS_NAME + ".nameString", getLocale())); nameLabel.setLabelFor(namePanel.getComponent()); //create the password component passwordField = new JPasswordField("", 15); JLabel passwordLabel = new JLabel(UIManagerExt.getString(CLASS_NAME + ".passwordString", getLocale())); passwordLabel.setLabelFor(passwordField); //create the server combo box if necessary JLabel serverLabel = new JLabel(UIManagerExt.getString(CLASS_NAME + ".serverString", getLocale())); if (servers.size() > 1) { serverCombo = new JComboBox(servers.toArray()); serverLabel.setLabelFor(serverCombo); } else { serverCombo = null; } //create the save check box. By default, it is not selected saveCB = new JCheckBox(UIManagerExt.getString(CLASS_NAME + ".rememberPasswordString", getLocale())); saveCB.setIconTextGap(10); saveCB.setSelected(false); //TODO should get this from prefs!!! And, it should be based on the user //determine whether to show/hide the save check box based on the SaveMode saveCB.setVisible(saveMode == SaveMode.PASSWORD || saveMode == SaveMode.BOTH); capsOn = new JLabel(" "); // don't show by default. We perform test when login panel gets focus. int lShift = 3;// lShift is used to align all other components with the checkbox GridLayout grid = new GridLayout(2,1); grid.setVgap(5); JPanel fields = new JPanel(grid); fields.add(namePanel.getComponent()); fields.add(passwordField); loginPanel.setLayout(new GridBagLayout()); GridBagConstraints gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(4, lShift, 5, 11); loginPanel.add(nameLabel, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 1; gridBagConstraints.gridheight = 2; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.fill = GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 5, 0); loginPanel.add(fields, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(5, lShift, 5, 11); loginPanel.add(passwordLabel, gridBagConstraints); if (serverCombo != null) { gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(0, lShift, 5, 11); loginPanel.add(serverLabel, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 1; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 5, 0); loginPanel.add(serverCombo, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 4, 0); loginPanel.add(saveCB, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, lShift, 0, 11); loginPanel.add(capsOn, gridBagConstraints); } else { gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 4, 0); loginPanel.add(saveCB, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, lShift, 0, 11); loginPanel.add(capsOn, gridBagConstraints); } return loginPanel; } /** * This method adds functionality to support bidi languages within this * component */ public void setComponentOrientation(ComponentOrientation orient) { // this if is used to avoid needless creations of the image if(orient != super.getComponentOrientation()) { super.setComponentOrientation(orient); banner.setImage(createLoginBanner()); progressPanel.applyComponentOrientation(orient); } } /** * Create all of the UI components for the login panel */ private void initComponents() { //create the default banner banner = new JXImagePanel(); banner.setImage(createLoginBanner()); //create the default label messageLabel = new JLabel(" "); messageLabel.setOpaque(true); messageLabel.setFont(messageLabel.getFont().deriveFont(Font.BOLD)); //create the main components loginPanel = createLoginPanel(); //create the message and hyperlink and hide them errorMessageLabel = new JXLabel(UIManagerExt.getString(CLASS_NAME + ".errorMessage", getLocale())); errorMessageLabel.setIcon(UIManager.getIcon(CLASS_NAME + ".errorIcon", getLocale())); errorMessageLabel.setVerticalTextPosition(SwingConstants.TOP); errorMessageLabel.setLineWrap(true); errorMessageLabel.setPaintBorderInsets(false); errorMessageLabel.setBackgroundPainter(new MattePainter(UIManager.getColor(CLASS_NAME + ".errorBackground", getLocale()), true)); errorMessageLabel.setMaxLineSpan(320); errorMessageLabel.setVisible(false); //aggregate the optional message label, content, and error label into //the contentPanel contentPanel = new JXPanel(new VerticalLayout()); messageLabel.setBorder(BorderFactory.createEmptyBorder(12, 12, 7, 11)); contentPanel.add(messageLabel); loginPanel.setBorder(BorderFactory.createEmptyBorder(0, 36, 7, 11)); contentPanel.add(loginPanel); errorMessageLabel.setBorder(UIManager.getBorder(CLASS_NAME + ".errorBorder", getLocale())); contentPanel.add(errorMessageLabel); //create the progress panel progressPanel = new JXPanel(new GridBagLayout()); progressMessageLabel = new JLabel(UIManagerExt.getString(CLASS_NAME + ".pleaseWait", getLocale())); progressMessageLabel.setFont(UIManager.getFont(CLASS_NAME +".pleaseWaitFont", getLocale())); JProgressBar pb = new JProgressBar(); pb.setIndeterminate(true); JButton cancelButton = new JButton(getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND)); progressPanel.add(progressMessageLabel, new GridBagConstraints(0, 0, 2, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(12, 12, 11, 11), 0, 0)); progressPanel.add(pb, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 24, 11, 7), 0, 0)); progressPanel.add(cancelButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 11, 11), 0, 0)); //layout the panel setLayout(new BorderLayout()); add(banner, BorderLayout.NORTH); add(contentPanel, BorderLayout.CENTER); initDone = true; } /** * Create and return an image to use for the Banner. This may be overridden * to return any image you like */ protected Image createLoginBanner() { return getUI() == null ? null : getUI().getBanner(); } /** * Create and return an Action for logging in */ protected Action createLoginAction() { return new LoginAction(this); } /** * Create and return an Action for canceling login */ protected Action createCancelAction() { return new CancelAction(this); } //TODO need to fire property change events!!! /** * @return Returns the saveMode. */ public SaveMode getSaveMode() { return saveMode; } /** * The save mode indicates whether the "save" password is checked by default. This method * makes no difference if the passwordStore is null. * * @param saveMode The saveMode to set either SAVE_NONE, SAVE_PASSWORD or SAVE_USERNAME */ public void setSaveMode(SaveMode saveMode) { if (this.saveMode != saveMode) { SaveMode oldMode = getSaveMode(); this.saveMode = saveMode; recreateLoginPanel(); firePropertyChange("saveMode", oldMode, getSaveMode()); } } /** * @return the List of servers */ public List<String> getServers() { return Collections.unmodifiableList(servers); } /** * Sets the list of servers. See the servers field javadoc for more info */ public void setServers(List<String> servers) { //only at startup if (this.servers == null) { this.servers = servers == null ? new ArrayList<String>() : servers; } else if (this.servers != servers) { List<String> old = getServers(); this.servers = servers == null ? new ArrayList<String>() : servers; recreateLoginPanel(); firePropertyChange("servers", old, getServers()); } } private LoginListener getDefaultLoginListener() { if (defaultLoginListener == null) { defaultLoginListener = new LoginListenerImpl(); } return defaultLoginListener; } /** * Sets the {@code LoginService} for this panel. Setting the login service * to {@code null} will actually set the service to use * {@code NullLoginService}. * * @param service * the service to set. If {@code service == null}, then a * {@code NullLoginService} is used. */ public void setLoginService(LoginService service) { LoginService oldService = getLoginService(); LoginService newService = service == null ? new NullLoginService() : service; //newService is guaranteed to be nonnull if (!newService.equals(oldService)) { if (oldService != null) { oldService.removeLoginListener(getDefaultLoginListener()); } loginService = newService; this.loginService.addLoginListener(getDefaultLoginListener()); firePropertyChange("loginService", oldService, getLoginService()); } } /** * Gets the <strong>LoginService</strong> for this panel. * * @return service service */ public LoginService getLoginService() { return loginService; } /** * Sets the <strong>PasswordStore</strong> for this panel. * * @param store PasswordStore */ public void setPasswordStore(PasswordStore store) { PasswordStore oldStore = getPasswordStore(); PasswordStore newStore = store == null ? new NullPasswordStore() : store; //newStore is guaranteed to be nonnull if (!newStore.equals(oldStore)) { passwordStore = newStore; firePropertyChange("passwordStore", oldStore, getPasswordStore()); } } /** * Gets the {@code UserNameStore} for this panel. * * @return the {@code UserNameStore} */ public UserNameStore getUserNameStore() { return userNameStore; } /** * Sets the user name store for this panel. * @param store */ public void setUserNameStore(UserNameStore store) { UserNameStore oldStore = getUserNameStore(); UserNameStore newStore = store == null ? new DefaultUserNameStore() : store; //newStore is guaranteed to be nonnull if (!newStore.equals(oldStore)) { userNameStore = newStore; firePropertyChange("userNameStore", oldStore, getUserNameStore()); } } /** * Gets the <strong>PasswordStore</strong> for this panel. * * @return store PasswordStore */ public PasswordStore getPasswordStore() { return passwordStore; } /** * Sets the <strong>User name</strong> for this panel. * * @param username User name */ public void setUserName(String username) { if (namePanel != null) { namePanel.setUserName(username); } } /** * Gets the <strong>User name</strong> for this panel. * @return the user name */ public String getUserName() { return namePanel == null ? null : namePanel.getUserName(); } /** * Sets the <strong>Password</strong> for this panel. * * @param password Password */ public void setPassword(char[] password) { passwordField.setText(new String(password)); } /** * Gets the <strong>Password</strong> for this panel. * * @return password Password */ public char[] getPassword() { return passwordField.getPassword(); } /** * Return the image used as the banner */ public Image getBanner() { return banner.getImage(); } /** * Set the image to use for the banner. If the {@code img} is {@code null}, * then no image will be displayed. * * @param img * the image to display */ public void setBanner(Image img) { // we do not expose the ImagePanel, so we will produce property change // events here Image oldImage = getBanner(); if (oldImage != img) { banner.setImage(img); firePropertyChange("banner", oldImage, getBanner()); } } /** * Set the text to use when creating the banner. If a custom banner image is * specified, then this is ignored. If {@code text} is {@code null}, then * no text is displayed. * * @param text * the text to display */ public void setBannerText(String text) { if (text == null) { text = ""; } if (!text.equals(this.bannerText)) { String oldText = this.bannerText; this.bannerText = text; //fix the login banner banner.setImage(createLoginBanner()); firePropertyChange("bannerText", oldText, text); } } /** * Returns text used when creating the banner */ public String getBannerText() { return bannerText; } /** * Returns the custom message for this login panel */ public String getMessage() { return messageLabel.getText(); } /** * Sets a custom message for this login panel */ public void setMessage(String message) { messageLabel.setText(message); } /** * Returns the error message for this login panel */ public String getErrorMessage() { return errorMessageLabel.getText(); } /** * Sets the error message for this login panel */ public void setErrorMessage(String errorMessage) { errorMessageLabel.setText(errorMessage); } /** * Returns the panel's status */ public Status getStatus() { return status; } /** * Change the status */ protected void setStatus(Status newStatus) { if (status != newStatus) { Status oldStatus = status; status = newStatus; firePropertyChange("status", oldStatus, newStatus); } } public void setLocale(Locale l) { super.setLocale(l); reinitLocales(l); } /** * Initiates the login procedure. This method is called internally by * the LoginAction. This method handles cursor management, and actually * calling the LoginService's startAuthentication method. */ protected void startLogin() { oldCursor = getCursor(); try { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); progressMessageLabel.setText(UIManagerExt.getString(CLASS_NAME + ".pleaseWait", getLocale())); String name = getUserName(); char[] password = getPassword(); String server = servers.size() == 1 ? servers.get(0) : serverCombo == null ? null : (String)serverCombo.getSelectedItem(); loginService.startAuthentication(name, password, server); } catch(Exception ex) { //The status is set via the loginService listener, so no need to set //the status here. Just log the error. LOG.log(Level.WARNING, "Authentication exception while logging in", ex); } finally { setCursor(oldCursor); } } /** * Cancels the login procedure. Handles cursor management and interfacing * with the LoginService's cancelAuthentication method */ protected void cancelLogin() { progressMessageLabel.setText(UIManagerExt.getString(CLASS_NAME + ".cancelWait", getLocale())); getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND).setEnabled(false); loginService.cancelAuthentication(); setCursor(oldCursor); } /** * Puts the password into the password store. If password store is not set, method will do * nothing. */ protected void savePassword() { if (saveCB.isSelected() && (saveMode == SaveMode.BOTH || saveMode == SaveMode.PASSWORD) && passwordStore != null) { passwordStore.set(getUserName(),getLoginService().getServer(),getPassword()); } } public void removeNotify() { try { // TODO: keep it here until all ui stuff is moved to uidelegate. if (capsLockSupport) KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(capsOnListener); Container c = JXLoginPane.this; while (c.getParent() != null) { c = c.getParent(); } if (c instanceof Window) { Window w = (Window) c; w.removeWindowFocusListener(capsOnWinListener ); w.removeWindowListener(capsOnWinListener ); } } catch (Exception e) { // bail out probably in unsigned app distributed over web } super.removeNotify(); } public void addNotify() { try { KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher( capsOnListener); Container c = JXLoginPane.this; while (c.getParent() != null) { c = c.getParent(); } if (c instanceof Window) { Window w = (Window) c; w.addWindowFocusListener(capsOnWinListener ); w.addWindowListener(capsOnWinListener); } } catch (Exception e) { // probably unsigned app over web, disable capslock support and bail out capsLockSupport = false; } super.addNotify(); } /* For Login (initiated in LoginAction): 0) set the status 1) Immediately disable the login action 2) Immediately disable the close action (part of enclosing window) 3) initialize the progress pane a) enable the cancel login action b) set the message text 4) hide the content pane, show the progress pane When cancelling (initiated in CancelAction): 0) set the status 1) Disable the cancel login action 2) Change the message text on the progress pane When cancel finishes (handled in LoginListener): 0) set the status 1) hide the progress pane, show the content pane 2) enable the close action (part of enclosing window) 3) enable the login action When login fails (handled in LoginListener): 0) set the status 1) hide the progress pane, show the content pane 2) enable the close action (part of enclosing window) 3) enable the login action 4) Show the error message 5) resize the window (part of enclosing window) When login succeeds (handled in LoginListener): 0) set the status 1) close the dialog/frame (part of enclosing window) */ /** * Listener class to track state in the LoginService */ protected class LoginListenerImpl extends LoginAdapter { public void loginSucceeded(LoginEvent source) { //save the user names and passwords String userName = namePanel.getUserName(); savePassword(); if ((getSaveMode() == SaveMode.USER_NAME || getSaveMode() == SaveMode.BOTH) && userName != null && !userName.trim().equals("")) { userNameStore.addUserName(userName); userNameStore.saveUserNames(); } setStatus(Status.SUCCEEDED); } public void loginStarted(LoginEvent source) { getActionMap().get(LOGIN_ACTION_COMMAND).setEnabled(false); getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND).setEnabled(true); remove(contentPanel); add(progressPanel, BorderLayout.CENTER); revalidate(); repaint(); setStatus(Status.IN_PROGRESS); } public void loginFailed(LoginEvent source) { remove(progressPanel); add(contentPanel, BorderLayout.CENTER); getActionMap().get(LOGIN_ACTION_COMMAND).setEnabled(true); errorMessageLabel.setVisible(true); revalidate(); repaint(); setStatus(Status.FAILED); } public void loginCanceled(LoginEvent source) { remove(progressPanel); add(contentPanel, BorderLayout.CENTER); getActionMap().get(LOGIN_ACTION_COMMAND).setEnabled(true); errorMessageLabel.setVisible(false); revalidate(); repaint(); setStatus(Status.CANCELLED); } } /** * Action that initiates a login procedure. Delegates to JXLoginPane.startLogin */ private static final class LoginAction extends AbstractActionExt { private JXLoginPane panel; public LoginAction(JXLoginPane p) { super(UIManagerExt.getString(CLASS_NAME + ".loginString", p.getLocale()), LOGIN_ACTION_COMMAND); this.panel = p; } public void actionPerformed(ActionEvent e) { panel.startLogin(); } public void itemStateChanged(ItemEvent e) {} } /** * Action that cancels the login procedure. */ private static final class CancelAction extends AbstractActionExt { private JXLoginPane panel; public CancelAction(JXLoginPane p) { //TODO localize super(UIManagerExt.getString(CLASS_NAME + ".cancelLogin", p.getLocale()), CANCEL_LOGIN_ACTION_COMMAND); this.panel = p; this.setEnabled(false); } public void actionPerformed(ActionEvent e) { panel.cancelLogin(); } public void itemStateChanged(ItemEvent e) {} } /** * Simple login service that allows everybody to login. This is useful in demos and allows * us to avoid having to check for LoginService being null */ private static final class NullLoginService extends LoginService { public boolean authenticate(String name, char[] password, String server) throws Exception { return true; } public boolean equals(Object obj) { return obj instanceof NullLoginService; } public int hashCode() { return 7; } } /** * Simple PasswordStore that does not remember passwords */ private static final class NullPasswordStore extends PasswordStore { private static final char[] EMPTY = new char[0]; public boolean set(String username, String server, char[] password) { //null op return false; } public char[] get(String username, String server) { return EMPTY; } public boolean equals(Object obj) { return obj instanceof NullPasswordStore; } public int hashCode() { return 7; } } public static interface NameComponent { public String getUserName(); public void setUserName(String userName); public JComponent getComponent(); } /** * If a UserNameStore is not used, then this text field is presented allowing the user * to simply enter their user name */ public static final class SimpleNamePanel extends JTextField implements NameComponent { public SimpleNamePanel() { super("", 15); } public String getUserName() { return getText(); } public void setUserName(String userName) { setText(userName); } public JComponent getComponent() { return this; } } /** * If a UserNameStore is used, then this combo box is presented allowing the user * to select a previous login name, or type in a new login name */ public static final class ComboNamePanel extends JComboBox implements NameComponent { private UserNameStore userNameStore; public ComboNamePanel(UserNameStore userNameStore) { super(); this.userNameStore = userNameStore; setModel(new NameComboBoxModel()); setEditable(true); } public String getUserName() { Object item = getModel().getSelectedItem(); return item == null ? null : item.toString(); } public void setUserName(String userName) { getModel().setSelectedItem(userName); } public void setUserNames(String[] names) { setModel(new DefaultComboBoxModel(names)); } public JComponent getComponent() { return this; } private final class NameComboBoxModel extends AbstractListModel implements ComboBoxModel { private Object selectedItem; public void setSelectedItem(Object anItem) { selectedItem = anItem; fireContentsChanged(this, -1, -1); } public Object getSelectedItem() { return selectedItem; } public Object getElementAt(int index) { return userNameStore.getUserNames()[index]; } public int getSize() { return userNameStore.getUserNames().length; } } } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, LoginService svc) { return showLoginDialog(parent, svc, null, null); } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, LoginService svc, PasswordStore ps, UserNameStore us) { return showLoginDialog(parent, svc, ps, us, null); } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, LoginService svc, PasswordStore ps, UserNameStore us, List<String> servers) { JXLoginPane panel = new JXLoginPane(svc, ps, us, servers); return showLoginDialog(parent, panel); } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, JXLoginPane panel) { Window w = WindowUtils.findWindow(parent); JXLoginDialog dlg = null; if (w == null) { dlg = new JXLoginDialog((Frame)null, panel); } else if (w instanceof Dialog) { dlg = new JXLoginDialog((Dialog)w, panel); } else if (w instanceof Frame) { dlg = new JXLoginDialog((Frame)w, panel); } else { throw new AssertionError("Shouldn't be able to happen"); } dlg.setVisible(true); return dlg.getStatus(); } /** * Shows a login frame. A JFrame is not modal, and thus does not block */ public static JXLoginFrame showLoginFrame(LoginService svc) { return showLoginFrame(svc, null, null); } public static JXLoginFrame showLoginFrame(LoginService svc, PasswordStore ps, UserNameStore us) { return showLoginFrame(svc, ps, us, null); } public static JXLoginFrame showLoginFrame(LoginService svc, PasswordStore ps, UserNameStore us, List<String> servers) { JXLoginPane panel = new JXLoginPane(svc, ps, us, servers); return showLoginFrame(panel); } public static JXLoginFrame showLoginFrame(JXLoginPane panel) { return new JXLoginFrame(panel); } public static final class JXLoginDialog extends JDialog { private JXLoginPane panel; public JXLoginDialog(Frame parent, JXLoginPane p) { super(parent, true); init(p); } public JXLoginDialog(Dialog parent, JXLoginPane p) { super(parent, true); init(p); } protected void init(JXLoginPane p) { setTitle(UIManagerExt.getString(CLASS_NAME + ".titleString", getLocale())); this.panel = p; initWindow(this, panel); } public JXLoginPane.Status getStatus() { return panel.getStatus(); } } public static final class JXLoginFrame extends JFrame { private JXLoginPane panel; public JXLoginFrame(JXLoginPane p) { super(UIManagerExt.getString(CLASS_NAME + ".titleString", p.getLocale())); this.panel = p; initWindow(this, panel); } public JXLoginPane.Status getStatus() { return panel.getStatus(); } public JXLoginPane getPanel() { return panel; } } /** * Utility method for initializing a Window for displaying a LoginDialog. * This is particularly useful because the differences between JFrame and * JDialog are so minor. * * Note: This method is package private for use by JXLoginDialog (proper, * not JXLoginPane.JXLoginDialog). Change to private if JXLoginDialog is * removed. */ static void initWindow(final Window w, final JXLoginPane panel) { w.setLayout(new BorderLayout()); w.add(panel, BorderLayout.CENTER); JButton okButton = new JButton(panel.getActionMap().get(LOGIN_ACTION_COMMAND)); final JButton cancelButton = new JButton( UIManagerExt.getString(CLASS_NAME + ".cancelString", panel.getLocale())); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //change panel status to cancelled! panel.status = JXLoginPane.Status.CANCELLED; w.setVisible(false); w.dispose(); } }); panel.addPropertyChangeListener("status", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { JXLoginPane.Status status = (JXLoginPane.Status)evt.getNewValue(); switch (status) { case NOT_STARTED: break; case IN_PROGRESS: cancelButton.setEnabled(false); break; case CANCELLED: cancelButton.setEnabled(true); w.pack(); break; case FAILED: cancelButton.setEnabled(true); w.pack(); break; case SUCCEEDED: w.setVisible(false); w.dispose(); } for (PropertyChangeListener l : w.getPropertyChangeListeners("status")) { PropertyChangeEvent pce = new PropertyChangeEvent(w, "status", evt.getOldValue(), evt.getNewValue()); l.propertyChange(pce); } } }); // FIX for #663 - commented out two lines below. Not sure why they were here in a first place. // cancelButton.setText(UIManager.getString(CLASS_NAME + ".cancelString")); // okButton.setText(UIManager.getString(CLASS_NAME + ".loginString")); JXBtnPanel buttonPanel = new JXBtnPanel(okButton, cancelButton); panel.setButtonPanel(buttonPanel); JXPanel controls = new JXPanel(new FlowLayout(FlowLayout.RIGHT)); new BoxLayout(controls, BoxLayout.X_AXIS); controls.add(Box.createHorizontalGlue()); controls.add(buttonPanel); w.add(controls, BorderLayout.SOUTH); w.addWindowListener(new WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { panel.cancelLogin(); } }); if (w instanceof JFrame) { final JFrame f = (JFrame)w; f.getRootPane().setDefaultButton(okButton); f.setResizable(false); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); ActionListener closeAction = new ActionListener() { public void actionPerformed(ActionEvent e) { f.setVisible(false); f.dispose(); } }; f.getRootPane().registerKeyboardAction(closeAction, ks, JComponent.WHEN_IN_FOCUSED_WINDOW); } else if (w instanceof JDialog) { final JDialog d = (JDialog)w; d.getRootPane().setDefaultButton(okButton); d.setResizable(false); KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); ActionListener closeAction = new ActionListener() { public void actionPerformed(ActionEvent e) { d.setVisible(false); } }; d.getRootPane().registerKeyboardAction(closeAction, ks, JComponent.WHEN_IN_FOCUSED_WINDOW); } w.pack(); w.setLocation(WindowUtils.getPointForCentering(w)); } private void setButtonPanel(JXBtnPanel buttonPanel) { this.buttonPanel = buttonPanel; } private static class JXBtnPanel extends JXPanel { private JButton cancel; private JButton ok; public JXBtnPanel(JButton okButton, JButton cancelButton) { GridLayout layout = new GridLayout(1,2); layout.setHgap(5); setLayout(layout); this.ok = okButton; this.cancel = cancelButton; add(okButton); add(cancelButton); setBorder(new EmptyBorder(0,0,7,11)); } /** * @return the cancel */ public JButton getCancel() { return cancel; } /** * @return the ok */ public JButton getOk() { return ok; } } private class CapsOnTest { public void runTest() { boolean success = false; // TODO: check the progress from time to time //try { // java.awt.Toolkit.getDefaultToolkit().getLockingKeyState(java.awt.event.KeyEvent.VK_CAPS_LOCK); // System.out.println("GOTCHA"); //} catch (Exception ex) { //ex.printStackTrace(); //success = false; if (!success) { try { //Temporarily installed listener with auto-uninstall after test is finished. KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher( new KeyEventDispatcher() { public boolean dispatchKeyEvent(KeyEvent e) { if (e.getID() != KeyEvent.KEY_PRESSED) { return true; } if (isTestingCaps && e.getKeyCode() > 64 && e.getKeyCode() < 91) { setCapsLock (!e.isShiftDown() && Character.isUpperCase(e.getKeyChar())); } if (isTestingCaps && (e.getKeyCode() == KeyEvent.VK_BACK_SPACE)) { //uninstall isTestingCaps = false; KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(this); } return true; }}); Robot r = new Robot(); isTestingCaps = true; r.keyPress(65); r.keyRelease(65); r.keyPress(KeyEvent.VK_BACK_SPACE); r.keyRelease(KeyEvent.VK_BACK_SPACE); } catch (Exception e1) { // this can happen for example due to security reasons in unsigned applets // when we can't test caps lock state programatically bail out silently } } } } /** * Window event listener to invoke capslock test when login panel get activated. */ public static class CapsOnWinListener extends WindowAdapter implements WindowFocusListener { private CapsOnTest cot; private long stamp; public CapsOnWinListener(CapsOnTest cot) { this.cot = cot; } public void windowActivated(WindowEvent e) { cot.runTest(); stamp = System.currentTimeMillis(); } public void windowGainedFocus(WindowEvent e) { // repeat test only if more then 20ms passed between activation test and now. if (stamp + 20 < System.currentTimeMillis()) { cot.runTest(); } } public void windowLostFocus(WindowEvent e) { // ignore } } }
package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Container; import java.awt.Cursor; import java.awt.Dialog; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.Insets; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Robot; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowFocusListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractListModel; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JProgressBar; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.auth.DefaultUserNameStore; import org.jdesktop.swingx.auth.LoginAdapter; import org.jdesktop.swingx.auth.LoginEvent; import org.jdesktop.swingx.auth.LoginListener; import org.jdesktop.swingx.auth.LoginService; import org.jdesktop.swingx.auth.PasswordStore; import org.jdesktop.swingx.auth.UserNameStore; import org.jdesktop.swingx.painter.MattePainter; import org.jdesktop.swingx.plaf.LoginPaneAddon; import org.jdesktop.swingx.plaf.LoginPaneUI; import org.jdesktop.swingx.plaf.LookAndFeelAddons; import org.jdesktop.swingx.plaf.UIManagerExt; import org.jdesktop.swingx.util.WindowUtils; /** * <p>JXLoginPane is a specialized JPanel that implements a Login dialog with * support for saving passwords supplied for future use in a secure * manner. <strong>LoginService</strong> is invoked to perform authentication * and optional <strong>PasswordStore</strong> can be provided to store the user * login information.</p> * * <p> In order to perform the authentication, <strong>JXLoginPane</strong> * calls the <code>authenticate</code> method of the <strong>LoginService * </strong>. In order to perform the persistence of the password, * <strong>JXLoginPane</strong> calls the put method of the * <strong>PasswordStore</strong> object that is supplied. If * the <strong>PasswordStore</strong> is <code>null</code>, then the password * is not saved. Similarly, if a <strong>PasswordStore</strong> is * supplied and the password is null, then the <strong>PasswordStore</strong> * will be queried for the password using the <code>get</code> method. * * Example: * <code><pre> * final JXLoginPane panel = new JXLoginPane(new LoginService() { * public boolean authenticate(String name, char[] password, * String server) throws Exception { * // perform authentication and return true on success. * return false; * }}); * final JFrame frame = JXLoginPane.showLoginFrame(panel); * </pre></code> * * @author Bino George * @author Shai Almog * @author rbair * @author Karl Schaefer * @author rah003 */ public class JXLoginPane extends JXPanel { /** * The Logger */ private static final Logger LOG = Logger.getLogger(JXLoginPane.class.getName()); /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = 3544949969896288564L; /** * UI Class ID */ public final static String uiClassID = "LoginPaneUI"; /** * Action key for an Action in the ActionMap that initiates the Login * procedure */ public static final String LOGIN_ACTION_COMMAND = "login"; /** * Action key for an Action in the ActionMap that cancels the Login * procedure */ public static final String CANCEL_LOGIN_ACTION_COMMAND = "cancel-login"; /** * The JXLoginPane can attempt to save certain user information such as * the username, password, or both to their respective stores. * This type specifies what type of save should be performed. */ public static enum SaveMode {NONE, USER_NAME, PASSWORD, BOTH} /** * Returns the status of the login process */ public enum Status {NOT_STARTED, IN_PROGRESS, FAILED, CANCELLED, SUCCEEDED} /** * Used as a prefix when pulling data out of UIManager for i18n */ private static String CLASS_NAME = JXLoginPane.class.getSimpleName(); /** * The current login status for this panel */ private Status status = Status.NOT_STARTED; /** * An optional banner at the top of the panel */ private JXImagePanel banner; /** * Text that should appear on the banner */ private String bannerText; /** * Custom label allowing the developer to display some message to the user */ private JLabel messageLabel; /** * Shows an error message such as "user name or password incorrect" or * "could not contact server" or something like that if something * goes wrong */ private JXLabel errorMessageLabel; /** * A Panel containing all of the input fields, check boxes, etc necessary * for the user to do their job. The items on this panel change whenever * the SaveMode changes, so this panel must be recreated at runtime if the * SaveMode changes. Thus, I must maintain this reference so I can remove * this panel from the content panel at runtime. */ private JXPanel loginPanel; /** * The panel on which the input fields, messageLabel, and errorMessageLabel * are placed. While the login thread is running, this panel is removed * from the dialog and replaced by the progressPanel */ private JXPanel contentPanel; /** * This is the area in which the name field is placed. That way it can toggle on the fly * between text field and a combo box depending on the situation, and have a simple * way to get the user name */ private NameComponent namePanel; /** * The password field presented allowing the user to enter their password */ private JPasswordField passwordField; /** * A combo box presenting the user with a list of servers to which they * may log in. This is an optional feature, which is only enabled if * the List of servers supplied to the JXLoginPane has a length greater * than 1. */ private JComboBox serverCombo; /** * Check box presented if a PasswordStore is used, allowing the user to decide whether to * save their password */ private JCheckBox saveCB; /** * Label displayed whenever caps lock is on. */ private JLabel capsOn; /** * A special panel that displays a progress bar and cancel button, and * which notify the user of the login process, and allow them to cancel * that process. */ private JXPanel progressPanel; /** * A JLabel on the progressPanel that is used for informing the user * of the status of the login procedure (logging in..., canceling login...) */ private JLabel progressMessageLabel; /** * The LoginService to use. This must be specified for the login dialog to operate. * If no LoginService is defined, a default login service is used that simply * allows all users access. This is useful for demos or prototypes where a proper login * server is not available. */ private LoginService loginService; /** * Optional: a PasswordStore to use for storing and retrieving passwords for a specific * user. */ private PasswordStore passwordStore; /** * Optional: a UserNameStore to use for storing user names and retrieving them */ private UserNameStore userNameStore; /** * A list of servers where each server is represented by a String. If the * list of Servers is greater than 1, then a combo box will be presented to * the user to choose from. If any servers are specified, the selected one * (or the only one if servers.size() == 1) will be passed to the LoginService */ private List<String> servers; /** * Whether to save password or username or both */ private SaveMode saveMode; /** * Tracks the cursor at the time that authentication was started, and restores to that * cursor after authentication ends, or is cancelled; */ private Cursor oldCursor; /** * The default login listener used by this panel. */ private LoginListener defaultLoginListener; private CapsOnTest capsOnTest = new CapsOnTest(); private boolean caps; private boolean isTestingCaps; private KeyEventDispatcher capsOnListener = new KeyEventDispatcher() { public boolean dispatchKeyEvent(KeyEvent e) { if (e.getID() != KeyEvent.KEY_PRESSED) { return false; } if (e.getKeyCode() == 20) { setCapsLock(!isCapsLockOn()); } return false; }}; /** * Caps lock detection support */ private boolean capsLockSupport = true; /** * Login/cancel control pane; */ private JXBtnPanel buttonPanel; /** * Window event listener responsible for triggering caps lock test on vindow activation and * focus changes. */ private CapsOnWinListener capsOnWinListener = new CapsOnWinListener(capsOnTest); /** * Creates a default JXLoginPane instance */ static { LookAndFeelAddons.contribute(new LoginPaneAddon()); } /** * Populates UIDefaults with the localizable Strings we will use * in the Login panel. */ private void reinitLocales(Locale l) { // PENDING: JW - use the locale given as parameter // as this probably (?) should be called before super.setLocale setBannerText(UIManagerExt.getString(CLASS_NAME + ".bannerString", getLocale())); banner.setImage(createLoginBanner()); // TODO: Can't change the error message since it might have been already changed by the user! //errorMessageLabel.setText(UIManager.getString(CLASS_NAME + ".errorMessage", getLocale())); progressMessageLabel.setText(UIManagerExt.getString(CLASS_NAME + ".pleaseWait", getLocale())); recreateLoginPanel(); Window w = SwingUtilities.getWindowAncestor(this); if (w instanceof JXLoginFrame) { JXLoginFrame f = (JXLoginFrame) w; f.setTitle(UIManagerExt.getString(CLASS_NAME + ".titleString", getLocale())); if (buttonPanel != null) { buttonPanel.getOk().setText(UIManagerExt.getString(CLASS_NAME + ".loginString", getLocale())); buttonPanel.getCancel().setText(UIManagerExt.getString(CLASS_NAME + ".cancelString", getLocale())); } } JLabel lbl = (JLabel) passwordField.getClientProperty("labeledBy"); if (lbl != null) { lbl.setText(UIManagerExt.getString(CLASS_NAME + ".passwordString", getLocale())); } lbl = (JLabel) namePanel.getComponent().getClientProperty("labeledBy"); if (lbl != null) { lbl.setText(UIManagerExt.getString(CLASS_NAME + ".nameString", getLocale())); } if (serverCombo != null) { lbl = (JLabel) serverCombo.getClientProperty("labeledBy"); if (lbl != null) { lbl.setText(UIManagerExt.getString(CLASS_NAME + ".serverString", getLocale())); } } saveCB.setText(UIManagerExt.getString(CLASS_NAME + ".rememberPasswordString", getLocale())); // by default, caps is initialized in off state - i.e. without warning. Setting to // whitespace preserves formatting of the panel. capsOn.setText(isCapsLockOn() ? UIManagerExt.getString(CLASS_NAME + ".capsOnWarning", getLocale()) : " "); getActionMap().get(LOGIN_ACTION_COMMAND).putValue(Action.NAME, UIManagerExt.getString(CLASS_NAME + ".loginString", getLocale())); getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND).putValue(Action.NAME, UIManagerExt.getString(CLASS_NAME + ".cancelString", getLocale())); } /** * Create a {@code JXLoginPane} that always accepts the user, never stores * passwords or user ids, and has no target servers. * <p> * This constructor should <i>NOT</i> be used in a real application. It is * provided for compliance to the bean specification and for use with visual * editors. */ public JXLoginPane() { this(null); } /** * Create a {@code JXLoginPane} with the specified {@code LoginService} * that does not store user ids or passwords and has no target servers. * * @param service * the {@code LoginService} to use for logging in */ public JXLoginPane(LoginService service) { this(service, null, null); } /** * Create a {@code JXLoginPane} with the specified {@code LoginService}, * {@code PasswordStore}, and {@code UserNameStore}, but without a server * list. * <p> * If you do not want to store passwords or user ids, those parameters can * be {@code null}. {@code SaveMode} is autoconfigured from passed in store * parameters. * * @param service * the {@code LoginService} to use for logging in * @param passwordStore * the {@code PasswordStore} to use for storing password * information * @param userStore * the {@code UserNameStore} to use for storing user information */ public JXLoginPane(LoginService service, PasswordStore passwordStore, UserNameStore userStore) { this(service, passwordStore, userStore, null); } /** * Create a {@code JXLoginPane} with the specified {@code LoginService}, * {@code PasswordStore}, {@code UserNameStore}, and server list. * <p> * If you do not want to store passwords or user ids, those parameters can * be {@code null}. {@code SaveMode} is autoconfigured from passed in store * parameters. * <p> * Setting the server list to {@code null} will unset all of the servers. * The server list is guaranteed to be non-{@code null}. * * @param service * the {@code LoginService} to use for logging in * @param passwordStore * the {@code PasswordStore} to use for storing password * information * @param userStore * the {@code UserNameStore} to use for storing user information * @param servers * a list of servers to authenticate against */ public JXLoginPane(LoginService service, PasswordStore passwordStore, UserNameStore userStore, List<String> servers) { setLoginService(service); setPasswordStore(passwordStore); setUserNameStore(userStore); setServers(servers); //create the login and cancel actions, and add them to the action map getActionMap().put(LOGIN_ACTION_COMMAND, createLoginAction()); getActionMap().put(CANCEL_LOGIN_ACTION_COMMAND, createCancelAction()); //initialize the save mode if (passwordStore != null && userStore != null) { saveMode = SaveMode.BOTH; } else if (passwordStore != null) { saveMode = SaveMode.PASSWORD; } else if (userStore != null) { saveMode = SaveMode.USER_NAME; } else { saveMode = SaveMode.NONE; } // if (!initDone) { initComponents(); // updateUI(); } /** * Sets current state of the caps lock key as detected by the component. * @param b True when caps lock is turned on, false otherwise. */ private void setCapsLock(boolean b) { caps = b; capsOn.setText(caps ? UIManagerExt.getString(CLASS_NAME + ".capsOnWarning", getLocale()) : " "); } /** * Gets current state of the caps lock as seen by the login panel. The state seen by the login * panel and therefore returned by this method can be delayed in comparison to the real caps * lock state and displayed by the keyboard light. This is usually the case when component or * its text fields are not focused. * * @return True when caps lock is on, false otherwise. Returns always false when * <code>isCapsLockDetectionSupported()</code> returns false. */ public boolean isCapsLockOn() { return caps; } /** * Check current state of the caps lock state detection. Note that the value can change after * component have been made visible. Due to current problems in locking key state detection by * core java detection of the changes in caps lock can be always reliably determined. When * component can't guarantee reliable detection it will switch it off. This is usually the case * for unsigned applets and webstart invoked application. Since your users are going to pass * their password in the component you should always sign it when distributing application over * the network. * @return True if changes in caps lock state can be monitored by the component, false otherwise. */ public boolean isCapsLockDetectionSupported() { return capsLockSupport; } /** * {@inheritDoc} */ public LoginPaneUI getUI() { return (LoginPaneUI) super.getUI(); } /** * Sets the look and feel (L&F) object that renders this component. * * @param ui the LoginPaneUI L&F object * @see javax.swing.UIDefaults#getUI */ public void setUI(LoginPaneUI ui) { // initialized here due to implicit updateUI call from JPanel if (banner == null) { banner = new JXImagePanel(); } if (errorMessageLabel == null) { errorMessageLabel = new JXLabel(UIManagerExt.getString(CLASS_NAME + ".errorMessage", getLocale())); } super.setUI(ui); banner.setImage(createLoginBanner()); } /** * Notification from the <code>UIManager</code> that the L&F has changed. * Replaces the current UI object with the latest version from the * <code>UIManager</code>. * * @see javax.swing.JComponent#updateUI */ public void updateUI() { setUI((LoginPaneUI) LookAndFeelAddons.getUI(this, LoginPaneUI.class)); } /** * Returns the name of the L&F class that renders this component. * * @return the string {@link #uiClassID} * @see javax.swing.JComponent#getUIClassID * @see javax.swing.UIDefaults#getUI */ public String getUIClassID() { return uiClassID; } /** * Recreates the login panel, and replaces the current one with the new one */ protected void recreateLoginPanel() { contentPanel.remove(loginPanel); loginPanel = createLoginPanel(); loginPanel.setBorder(BorderFactory.createEmptyBorder(0, 36, 7, 11)); contentPanel.add(loginPanel, 1); } /** * Creates and returns a new LoginPanel, based on the SaveMode state of * the login panel. Whenever the SaveMode changes, the panel is recreated. * I do this rather than hiding/showing components, due to a cleaner * implementation (no invisible components, components are not sharing * locations in the LayoutManager, etc). */ private JXPanel createLoginPanel() { JXPanel loginPanel = new JXPanel(); //create the NameComponent if (saveMode == SaveMode.NONE) { namePanel = new SimpleNamePanel(); } else { namePanel = new ComboNamePanel(userNameStore); } JLabel nameLabel = new JLabel(UIManagerExt.getString(CLASS_NAME + ".nameString", getLocale())); nameLabel.setLabelFor(namePanel.getComponent()); //create the password component passwordField = new JPasswordField("", 15); JLabel passwordLabel = new JLabel(UIManagerExt.getString(CLASS_NAME + ".passwordString", getLocale())); passwordLabel.setLabelFor(passwordField); //create the server combo box if necessary JLabel serverLabel = new JLabel(UIManagerExt.getString(CLASS_NAME + ".serverString", getLocale())); if (servers.size() > 1) { serverCombo = new JComboBox(servers.toArray()); serverLabel.setLabelFor(serverCombo); } else { serverCombo = null; } //create the save check box. By default, it is not selected saveCB = new JCheckBox(UIManagerExt.getString(CLASS_NAME + ".rememberPasswordString", getLocale())); saveCB.setIconTextGap(10); saveCB.setSelected(false); //TODO should get this from prefs!!! And, it should be based on the user //determine whether to show/hide the save check box based on the SaveMode saveCB.setVisible(saveMode == SaveMode.PASSWORD || saveMode == SaveMode.BOTH); capsOn = new JLabel(" "); // don't show by default. We perform test when login panel gets focus. int lShift = 3;// lShift is used to align all other components with the checkbox GridLayout grid = new GridLayout(2,1); grid.setVgap(5); JPanel fields = new JPanel(grid); fields.add(namePanel.getComponent()); fields.add(passwordField); loginPanel.setLayout(new GridBagLayout()); GridBagConstraints gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(4, lShift, 5, 11); loginPanel.add(nameLabel, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 1; gridBagConstraints.gridheight = 2; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.fill = GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 5, 0); loginPanel.add(fields, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(5, lShift, 5, 11); loginPanel.add(passwordLabel, gridBagConstraints); if (serverCombo != null) { gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(0, lShift, 5, 11); loginPanel.add(serverLabel, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 1; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 5, 0); loginPanel.add(serverCombo, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 4, 0); loginPanel.add(saveCB, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, lShift, 0, 11); loginPanel.add(capsOn, gridBagConstraints); } else { gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 4, 0); loginPanel.add(saveCB, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, lShift, 0, 11); loginPanel.add(capsOn, gridBagConstraints); } return loginPanel; } /** * This method adds functionality to support bidi languages within this * component */ public void setComponentOrientation(ComponentOrientation orient) { // this if is used to avoid needless creations of the image if(orient != super.getComponentOrientation()) { super.setComponentOrientation(orient); banner.setImage(createLoginBanner()); progressPanel.applyComponentOrientation(orient); } } /** * Create all of the UI components for the login panel */ private void initComponents() { //create the default banner banner.setImage(createLoginBanner()); //create the default label messageLabel = new JLabel(" "); messageLabel.setOpaque(true); messageLabel.setFont(messageLabel.getFont().deriveFont(Font.BOLD)); //create the main components loginPanel = createLoginPanel(); //create the message and hyperlink and hide them errorMessageLabel.setIcon(UIManager.getIcon(CLASS_NAME + ".errorIcon", getLocale())); errorMessageLabel.setVerticalTextPosition(SwingConstants.TOP); errorMessageLabel.setLineWrap(true); errorMessageLabel.setPaintBorderInsets(false); errorMessageLabel.setBackgroundPainter(new MattePainter(UIManager.getColor(CLASS_NAME + ".errorBackground", getLocale()), true)); errorMessageLabel.setMaxLineSpan(320); errorMessageLabel.setVisible(false); //aggregate the optional message label, content, and error label into //the contentPanel contentPanel = new JXPanel(new VerticalLayout()); messageLabel.setBorder(BorderFactory.createEmptyBorder(12, 12, 7, 11)); contentPanel.add(messageLabel); loginPanel.setBorder(BorderFactory.createEmptyBorder(0, 36, 7, 11)); contentPanel.add(loginPanel); errorMessageLabel.setBorder(UIManager.getBorder(CLASS_NAME + ".errorBorder", getLocale())); contentPanel.add(errorMessageLabel); //create the progress panel progressPanel = new JXPanel(new GridBagLayout()); progressMessageLabel = new JLabel(UIManagerExt.getString(CLASS_NAME + ".pleaseWait", getLocale())); progressMessageLabel.setFont(UIManager.getFont(CLASS_NAME +".pleaseWaitFont", getLocale())); JProgressBar pb = new JProgressBar(); pb.setIndeterminate(true); JButton cancelButton = new JButton(getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND)); progressPanel.add(progressMessageLabel, new GridBagConstraints(0, 0, 2, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(12, 12, 11, 11), 0, 0)); progressPanel.add(pb, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 24, 11, 7), 0, 0)); progressPanel.add(cancelButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 11, 11), 0, 0)); //layout the panel setLayout(new BorderLayout()); add(banner, BorderLayout.NORTH); add(contentPanel, BorderLayout.CENTER); } /** * Create and return an image to use for the Banner. This may be overridden * to return any image you like */ protected Image createLoginBanner() { return getUI() == null ? null : getUI().getBanner(); } /** * Create and return an Action for logging in */ protected Action createLoginAction() { return new LoginAction(this); } /** * Create and return an Action for canceling login */ protected Action createCancelAction() { return new CancelAction(this); } //TODO need to fire property change events!!! /** * @return Returns the saveMode. */ public SaveMode getSaveMode() { return saveMode; } /** * The save mode indicates whether the "save" password is checked by default. This method * makes no difference if the passwordStore is null. * * @param saveMode The saveMode to set either SAVE_NONE, SAVE_PASSWORD or SAVE_USERNAME */ public void setSaveMode(SaveMode saveMode) { if (this.saveMode != saveMode) { SaveMode oldMode = getSaveMode(); this.saveMode = saveMode; recreateLoginPanel(); firePropertyChange("saveMode", oldMode, getSaveMode()); } } /** * @return the List of servers */ public List<String> getServers() { return Collections.unmodifiableList(servers); } /** * Sets the list of servers. See the servers field javadoc for more info */ public void setServers(List<String> servers) { //only at startup if (this.servers == null) { this.servers = servers == null ? new ArrayList<String>() : servers; } else if (this.servers != servers) { List<String> old = getServers(); this.servers = servers == null ? new ArrayList<String>() : servers; recreateLoginPanel(); firePropertyChange("servers", old, getServers()); } } private LoginListener getDefaultLoginListener() { if (defaultLoginListener == null) { defaultLoginListener = new LoginListenerImpl(); } return defaultLoginListener; } /** * Sets the {@code LoginService} for this panel. Setting the login service * to {@code null} will actually set the service to use * {@code NullLoginService}. * * @param service * the service to set. If {@code service == null}, then a * {@code NullLoginService} is used. */ public void setLoginService(LoginService service) { LoginService oldService = getLoginService(); LoginService newService = service == null ? new NullLoginService() : service; //newService is guaranteed to be nonnull if (!newService.equals(oldService)) { if (oldService != null) { oldService.removeLoginListener(getDefaultLoginListener()); } loginService = newService; this.loginService.addLoginListener(getDefaultLoginListener()); firePropertyChange("loginService", oldService, getLoginService()); } } /** * Gets the <strong>LoginService</strong> for this panel. * * @return service service */ public LoginService getLoginService() { return loginService; } /** * Sets the <strong>PasswordStore</strong> for this panel. * * @param store PasswordStore */ public void setPasswordStore(PasswordStore store) { PasswordStore oldStore = getPasswordStore(); PasswordStore newStore = store == null ? new NullPasswordStore() : store; //newStore is guaranteed to be nonnull if (!newStore.equals(oldStore)) { passwordStore = newStore; firePropertyChange("passwordStore", oldStore, getPasswordStore()); } } /** * Gets the {@code UserNameStore} for this panel. * * @return the {@code UserNameStore} */ public UserNameStore getUserNameStore() { return userNameStore; } /** * Sets the user name store for this panel. * @param store */ public void setUserNameStore(UserNameStore store) { UserNameStore oldStore = getUserNameStore(); UserNameStore newStore = store == null ? new DefaultUserNameStore() : store; //newStore is guaranteed to be nonnull if (!newStore.equals(oldStore)) { userNameStore = newStore; firePropertyChange("userNameStore", oldStore, getUserNameStore()); } } /** * Gets the <strong>PasswordStore</strong> for this panel. * * @return store PasswordStore */ public PasswordStore getPasswordStore() { return passwordStore; } /** * Sets the <strong>User name</strong> for this panel. * * @param username User name */ public void setUserName(String username) { if (namePanel != null) { namePanel.setUserName(username); } } /** * Gets the <strong>User name</strong> for this panel. * @return the user name */ public String getUserName() { return namePanel == null ? null : namePanel.getUserName(); } /** * Sets the <strong>Password</strong> for this panel. * * @param password Password */ public void setPassword(char[] password) { passwordField.setText(new String(password)); } /** * Gets the <strong>Password</strong> for this panel. * * @return password Password */ public char[] getPassword() { return passwordField.getPassword(); } /** * Return the image used as the banner */ public Image getBanner() { return banner.getImage(); } /** * Set the image to use for the banner. If the {@code img} is {@code null}, * then no image will be displayed. * * @param img * the image to display */ public void setBanner(Image img) { // we do not expose the ImagePanel, so we will produce property change // events here Image oldImage = getBanner(); if (oldImage != img) { banner.setImage(img); firePropertyChange("banner", oldImage, getBanner()); } } /** * Set the text to use when creating the banner. If a custom banner image is * specified, then this is ignored. If {@code text} is {@code null}, then * no text is displayed. * * @param text * the text to display */ public void setBannerText(String text) { if (text == null) { text = ""; } if (!text.equals(this.bannerText)) { String oldText = this.bannerText; this.bannerText = text; //fix the login banner this.banner.setImage(createLoginBanner()); firePropertyChange("bannerText", oldText, text); } } /** * Returns text used when creating the banner */ public String getBannerText() { return bannerText; } /** * Returns the custom message for this login panel */ public String getMessage() { return messageLabel.getText(); } /** * Sets a custom message for this login panel */ public void setMessage(String message) { messageLabel.setText(message); } /** * Returns the error message for this login panel */ public String getErrorMessage() { return errorMessageLabel.getText(); } /** * Sets the error message for this login panel */ public void setErrorMessage(String errorMessage) { errorMessageLabel.setText(errorMessage); } /** * Returns the panel's status */ public Status getStatus() { return status; } /** * Change the status */ protected void setStatus(Status newStatus) { if (status != newStatus) { Status oldStatus = status; status = newStatus; firePropertyChange("status", oldStatus, newStatus); } } public void setLocale(Locale l) { super.setLocale(l); reinitLocales(l); } /** * Initiates the login procedure. This method is called internally by * the LoginAction. This method handles cursor management, and actually * calling the LoginService's startAuthentication method. Method will return * immediately if asynchronous login is enabled or will block until * authentication finishes if <code>getSynchronous()</code> returns true. */ protected void startLogin() { oldCursor = getCursor(); try { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); progressMessageLabel.setText(UIManagerExt.getString(CLASS_NAME + ".pleaseWait", getLocale())); String name = getUserName(); char[] password = getPassword(); String server = servers.size() == 1 ? servers.get(0) : serverCombo == null ? null : (String)serverCombo.getSelectedItem(); loginService.startAuthentication(name, password, server); } catch(Exception ex) { //The status is set via the loginService listener, so no need to set //the status here. Just log the error. LOG.log(Level.WARNING, "Authentication exception while logging in", ex); } finally { setCursor(oldCursor); } } /** * Cancels the login procedure. Handles cursor management and interfacing * with the LoginService's cancelAuthentication method. Calling this method * has an effect only when authentication is still in progress (i.e. after * previous call to <code>startAuthentications()</code> and only when * authentication is performed asynchronously (<code>getSynchronous()</code> * returns false). */ protected void cancelLogin() { progressMessageLabel.setText(UIManagerExt.getString(CLASS_NAME + ".cancelWait", getLocale())); getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND).setEnabled(false); loginService.cancelAuthentication(); setCursor(oldCursor); } /** * Puts the password into the password store. If password store is not set, method will do * nothing. */ protected void savePassword() { if (saveCB.isSelected() && (saveMode == SaveMode.BOTH || saveMode == SaveMode.PASSWORD) && passwordStore != null) { passwordStore.set(getUserName(),getLoginService().getServer(),getPassword()); } } public void removeNotify() { try { // TODO: keep it here until all ui stuff is moved to uidelegate. if (capsLockSupport) KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(capsOnListener); Container c = JXLoginPane.this; while (c.getParent() != null) { c = c.getParent(); } if (c instanceof Window) { Window w = (Window) c; w.removeWindowFocusListener(capsOnWinListener ); w.removeWindowListener(capsOnWinListener ); } } catch (Exception e) { // bail out probably in unsigned app distributed over web } super.removeNotify(); } public void addNotify() { try { KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher( capsOnListener); Container c = JXLoginPane.this; while (c.getParent() != null) { c = c.getParent(); } if (c instanceof Window) { Window w = (Window) c; w.addWindowFocusListener(capsOnWinListener ); w.addWindowListener(capsOnWinListener); } } catch (Exception e) { // probably unsigned app over web, disable capslock support and bail out capsLockSupport = false; } super.addNotify(); } /* For Login (initiated in LoginAction): 0) set the status 1) Immediately disable the login action 2) Immediately disable the close action (part of enclosing window) 3) initialize the progress pane a) enable the cancel login action b) set the message text 4) hide the content pane, show the progress pane When cancelling (initiated in CancelAction): 0) set the status 1) Disable the cancel login action 2) Change the message text on the progress pane When cancel finishes (handled in LoginListener): 0) set the status 1) hide the progress pane, show the content pane 2) enable the close action (part of enclosing window) 3) enable the login action When login fails (handled in LoginListener): 0) set the status 1) hide the progress pane, show the content pane 2) enable the close action (part of enclosing window) 3) enable the login action 4) Show the error message 5) resize the window (part of enclosing window) When login succeeds (handled in LoginListener): 0) set the status 1) close the dialog/frame (part of enclosing window) */ /** * Listener class to track state in the LoginService */ protected class LoginListenerImpl extends LoginAdapter { public void loginSucceeded(LoginEvent source) { //save the user names and passwords String userName = namePanel.getUserName(); savePassword(); if ((getSaveMode() == SaveMode.USER_NAME || getSaveMode() == SaveMode.BOTH) && userName != null && !userName.trim().equals("")) { userNameStore.addUserName(userName); userNameStore.saveUserNames(); } setStatus(Status.SUCCEEDED); } public void loginStarted(LoginEvent source) { getActionMap().get(LOGIN_ACTION_COMMAND).setEnabled(false); getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND).setEnabled(true); remove(contentPanel); add(progressPanel, BorderLayout.CENTER); revalidate(); repaint(); setStatus(Status.IN_PROGRESS); } public void loginFailed(LoginEvent source) { remove(progressPanel); add(contentPanel, BorderLayout.CENTER); getActionMap().get(LOGIN_ACTION_COMMAND).setEnabled(true); errorMessageLabel.setVisible(true); revalidate(); repaint(); setStatus(Status.FAILED); } public void loginCanceled(LoginEvent source) { remove(progressPanel); add(contentPanel, BorderLayout.CENTER); getActionMap().get(LOGIN_ACTION_COMMAND).setEnabled(true); errorMessageLabel.setVisible(false); revalidate(); repaint(); setStatus(Status.CANCELLED); } } /** * Action that initiates a login procedure. Delegates to JXLoginPane.startLogin */ private static final class LoginAction extends AbstractActionExt { private JXLoginPane panel; public LoginAction(JXLoginPane p) { super(UIManagerExt.getString(CLASS_NAME + ".loginString", p.getLocale()), LOGIN_ACTION_COMMAND); this.panel = p; } public void actionPerformed(ActionEvent e) { panel.startLogin(); } public void itemStateChanged(ItemEvent e) {} } /** * Action that cancels the login procedure. */ private static final class CancelAction extends AbstractActionExt { private JXLoginPane panel; public CancelAction(JXLoginPane p) { //TODO localize super(UIManagerExt.getString(CLASS_NAME + ".cancelLogin", p.getLocale()), CANCEL_LOGIN_ACTION_COMMAND); this.panel = p; this.setEnabled(false); } public void actionPerformed(ActionEvent e) { panel.cancelLogin(); } public void itemStateChanged(ItemEvent e) {} } /** * Simple login service that allows everybody to login. This is useful in demos and allows * us to avoid having to check for LoginService being null */ private static final class NullLoginService extends LoginService { public boolean authenticate(String name, char[] password, String server) throws Exception { return true; } public boolean equals(Object obj) { return obj instanceof NullLoginService; } public int hashCode() { return 7; } } /** * Simple PasswordStore that does not remember passwords */ private static final class NullPasswordStore extends PasswordStore { private static final char[] EMPTY = new char[0]; public boolean set(String username, String server, char[] password) { //null op return false; } public char[] get(String username, String server) { return EMPTY; } public boolean equals(Object obj) { return obj instanceof NullPasswordStore; } public int hashCode() { return 7; } } public static interface NameComponent { public String getUserName(); public void setUserName(String userName); public JComponent getComponent(); } /** * If a UserNameStore is not used, then this text field is presented allowing the user * to simply enter their user name */ public static final class SimpleNamePanel extends JTextField implements NameComponent { public SimpleNamePanel() { super("", 15); } public String getUserName() { return getText(); } public void setUserName(String userName) { setText(userName); } public JComponent getComponent() { return this; } } /** * If a UserNameStore is used, then this combo box is presented allowing the user * to select a previous login name, or type in a new login name */ public static final class ComboNamePanel extends JComboBox implements NameComponent { private UserNameStore userNameStore; public ComboNamePanel(UserNameStore userNameStore) { super(); this.userNameStore = userNameStore; setModel(new NameComboBoxModel()); setEditable(true); } public String getUserName() { Object item = getModel().getSelectedItem(); return item == null ? null : item.toString(); } public void setUserName(String userName) { getModel().setSelectedItem(userName); } public void setUserNames(String[] names) { setModel(new DefaultComboBoxModel(names)); } public JComponent getComponent() { return this; } private final class NameComboBoxModel extends AbstractListModel implements ComboBoxModel { private Object selectedItem; public void setSelectedItem(Object anItem) { selectedItem = anItem; fireContentsChanged(this, -1, -1); } public Object getSelectedItem() { return selectedItem; } public Object getElementAt(int index) { return userNameStore.getUserNames()[index]; } public int getSize() { return userNameStore.getUserNames().length; } } } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, LoginService svc) { return showLoginDialog(parent, svc, null, null); } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, LoginService svc, PasswordStore ps, UserNameStore us) { return showLoginDialog(parent, svc, ps, us, null); } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, LoginService svc, PasswordStore ps, UserNameStore us, List<String> servers) { JXLoginPane panel = new JXLoginPane(svc, ps, us, servers); return showLoginDialog(parent, panel); } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, JXLoginPane panel) { Window w = WindowUtils.findWindow(parent); JXLoginDialog dlg = null; if (w == null) { dlg = new JXLoginDialog((Frame)null, panel); } else if (w instanceof Dialog) { dlg = new JXLoginDialog((Dialog)w, panel); } else if (w instanceof Frame) { dlg = new JXLoginDialog((Frame)w, panel); } else { throw new AssertionError("Shouldn't be able to happen"); } dlg.setVisible(true); return dlg.getStatus(); } /** * Shows a login frame. A JFrame is not modal, and thus does not block */ public static JXLoginFrame showLoginFrame(LoginService svc) { return showLoginFrame(svc, null, null); } public static JXLoginFrame showLoginFrame(LoginService svc, PasswordStore ps, UserNameStore us) { return showLoginFrame(svc, ps, us, null); } public static JXLoginFrame showLoginFrame(LoginService svc, PasswordStore ps, UserNameStore us, List<String> servers) { JXLoginPane panel = new JXLoginPane(svc, ps, us, servers); return showLoginFrame(panel); } public static JXLoginFrame showLoginFrame(JXLoginPane panel) { return new JXLoginFrame(panel); } public static final class JXLoginDialog extends JDialog { private JXLoginPane panel; public JXLoginDialog(Frame parent, JXLoginPane p) { super(parent, true); init(p); } public JXLoginDialog(Dialog parent, JXLoginPane p) { super(parent, true); init(p); } protected void init(JXLoginPane p) { setTitle(UIManagerExt.getString(CLASS_NAME + ".titleString", getLocale())); this.panel = p; initWindow(this, panel); } public JXLoginPane.Status getStatus() { return panel.getStatus(); } } public static final class JXLoginFrame extends JFrame { private JXLoginPane panel; public JXLoginFrame(JXLoginPane p) { super(UIManagerExt.getString(CLASS_NAME + ".titleString", p.getLocale())); this.panel = p; initWindow(this, panel); } public JXLoginPane.Status getStatus() { return panel.getStatus(); } public JXLoginPane getPanel() { return panel; } } /** * Utility method for initializing a Window for displaying a LoginDialog. * This is particularly useful because the differences between JFrame and * JDialog are so minor. * * Note: This method is package private for use by JXLoginDialog (proper, * not JXLoginPane.JXLoginDialog). Change to private if JXLoginDialog is * removed. */ static void initWindow(final Window w, final JXLoginPane panel) { w.setLayout(new BorderLayout()); w.add(panel, BorderLayout.CENTER); JButton okButton = new JButton(panel.getActionMap().get(LOGIN_ACTION_COMMAND)); final JButton cancelButton = new JButton( UIManagerExt.getString(CLASS_NAME + ".cancelString", panel.getLocale())); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //change panel status to cancelled! panel.status = JXLoginPane.Status.CANCELLED; w.setVisible(false); w.dispose(); } }); panel.addPropertyChangeListener("status", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { JXLoginPane.Status status = (JXLoginPane.Status)evt.getNewValue(); switch (status) { case NOT_STARTED: break; case IN_PROGRESS: cancelButton.setEnabled(false); break; case CANCELLED: cancelButton.setEnabled(true); w.pack(); break; case FAILED: cancelButton.setEnabled(true); w.pack(); break; case SUCCEEDED: w.setVisible(false); w.dispose(); } for (PropertyChangeListener l : w.getPropertyChangeListeners("status")) { PropertyChangeEvent pce = new PropertyChangeEvent(w, "status", evt.getOldValue(), evt.getNewValue()); l.propertyChange(pce); } } }); // FIX for #663 - commented out two lines below. Not sure why they were here in a first place. // cancelButton.setText(UIManager.getString(CLASS_NAME + ".cancelString")); // okButton.setText(UIManager.getString(CLASS_NAME + ".loginString")); JXBtnPanel buttonPanel = new JXBtnPanel(okButton, cancelButton); panel.setButtonPanel(buttonPanel); JXPanel controls = new JXPanel(new FlowLayout(FlowLayout.RIGHT)); new BoxLayout(controls, BoxLayout.X_AXIS); controls.add(Box.createHorizontalGlue()); controls.add(buttonPanel); w.add(controls, BorderLayout.SOUTH); w.addWindowListener(new WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { panel.cancelLogin(); } }); if (w instanceof JFrame) { final JFrame f = (JFrame)w; f.getRootPane().setDefaultButton(okButton); f.setResizable(false); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); ActionListener closeAction = new ActionListener() { public void actionPerformed(ActionEvent e) { f.setVisible(false); f.dispose(); } }; f.getRootPane().registerKeyboardAction(closeAction, ks, JComponent.WHEN_IN_FOCUSED_WINDOW); } else if (w instanceof JDialog) { final JDialog d = (JDialog)w; d.getRootPane().setDefaultButton(okButton); d.setResizable(false); KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); ActionListener closeAction = new ActionListener() { public void actionPerformed(ActionEvent e) { d.setVisible(false); } }; d.getRootPane().registerKeyboardAction(closeAction, ks, JComponent.WHEN_IN_FOCUSED_WINDOW); } w.pack(); w.setLocation(WindowUtils.getPointForCentering(w)); } private void setButtonPanel(JXBtnPanel buttonPanel) { this.buttonPanel = buttonPanel; } private static class JXBtnPanel extends JXPanel { private JButton cancel; private JButton ok; public JXBtnPanel(JButton okButton, JButton cancelButton) { GridLayout layout = new GridLayout(1,2); layout.setHgap(5); setLayout(layout); this.ok = okButton; this.cancel = cancelButton; add(okButton); add(cancelButton); setBorder(new EmptyBorder(0,0,7,11)); } /** * @return the cancel */ public JButton getCancel() { return cancel; } /** * @return the ok */ public JButton getOk() { return ok; } } private class CapsOnTest { KeyEventDispatcher ked; public void runTest() { boolean success = false; // TODO: check the progress from time to time //try { // java.awt.Toolkit.getDefaultToolkit().getLockingKeyState(java.awt.event.KeyEvent.VK_CAPS_LOCK); // System.out.println("GOTCHA"); //} catch (Exception ex) { //ex.printStackTrace(); //success = false; if (!success) { try { KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager(); // #swingx-697 // In some cases panel is not focused after the creation leaving bogus dispatcher in place. If found remove it. if (ked != null) { kfm.removeKeyEventDispatcher(ked); } // Temporarily installed listener with auto-uninstall after // test is finished. ked = new KeyEventDispatcher() { public boolean dispatchKeyEvent(KeyEvent e) { if (e.getID() != KeyEvent.KEY_PRESSED) { return true; } if (isTestingCaps && e.getKeyCode() > 64 && e.getKeyCode() < 91) { setCapsLock(!e.isShiftDown() && Character.isUpperCase(e.getKeyChar())); } if (isTestingCaps && (e.getKeyCode() == KeyEvent.VK_BACK_SPACE)) { // uninstall isTestingCaps = false; KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(this); if (ked == this) { ked = null; } } return true; } }; kfm.addKeyEventDispatcher(ked); Robot r = new Robot(); isTestingCaps = true; r.keyPress(65); r.keyRelease(65); r.keyPress(KeyEvent.VK_BACK_SPACE); r.keyRelease(KeyEvent.VK_BACK_SPACE); } catch (Exception e1) { // this can happen for example due to security reasons in unsigned applets // when we can't test caps lock state programatically bail out silently } } } } /** * Window event listener to invoke capslock test when login panel get activated. */ public static class CapsOnWinListener extends WindowAdapter implements WindowFocusListener { private CapsOnTest cot; private long stamp; public CapsOnWinListener(CapsOnTest cot) { this.cot = cot; } public void windowActivated(WindowEvent e) { cot.runTest(); stamp = System.currentTimeMillis(); } public void windowGainedFocus(WindowEvent e) { System.out.println("winFocusGained"); // repeat test only if more then 20ms passed between activation test and now. if (stamp + 20 < System.currentTimeMillis()) { cot.runTest(); } } public void windowLostFocus(WindowEvent e) { // ignore } } }
package org.smoothbuild.plugin.api; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; /** * Path within a project. */ public class Path { public static final char SEPARATOR_CHARACTER = '/'; public static final String SEPARATOR = new String(new char[] { SEPARATOR_CHARACTER }); private static final String ROOT_STRING = "."; private static final Path ROOT_PATH = new Path(ROOT_STRING); private final String value; public static Path path(String value) { checkIsValid(value); String canonicalValue = toCanonical(value); if (canonicalValue.equals(ROOT_STRING)) { return ROOT_PATH; } else { return new Path(canonicalValue); } } public static Path rootPath() { return ROOT_PATH; } private Path(String value) { this.value = value; } private static void checkIsValid(String value) { String message = validationError(value); if (message != null) { throw new IllegalArgumentException(message); } } public static String validationError(String path) { if (path.isEmpty()) { return "Empty paths are not allowed"; } if (path.startsWith("/")) { return "Path cannot start with slash character '/'. Only paths relative to project root dir are allowed"; } if (path.endsWith("/")) { return "Path cannot end with slash character '/'."; } if (path.contains(" return "Path cannot contain two slashes (//) in a row"; } if (path.contains("/./") || path.endsWith("/.")) { return "Path can contain '.' element only at the beginning (for example './mypath')."; } if (path.equals("..") || path.startsWith("../") || path.contains("/../") || path.endsWith("/..")) { return "Path cannot contain '..' element. Referencing files outside your project is a bad idea."; } return null; } private static String toCanonical(String path) { // remove './' prefix return path.startsWith("./") ? path.substring(2, path.length()) : path; } public String value() { return value; } public boolean isRoot() { return this == ROOT_PATH; } public Path parent() { if (this == ROOT_PATH) { throw new IllegalArgumentException("Cannot return parent of root path '.'"); } int index = value.lastIndexOf(SEPARATOR_CHARACTER); if (index == -1) { return ROOT_PATH; } else { return new Path(value.substring(0, index)); } } public Path append(Path path) { if (this == ROOT_PATH) { return path; } else if (path == ROOT_PATH) { return this; } else { return new Path(this.value + SEPARATOR + path.value); } } public ImmutableList<Path> toElements() { if (this == ROOT_PATH) { return ImmutableList.<Path> of(); } else { Builder<Path> builder = ImmutableList.builder(); for (String string : Splitter.on(SEPARATOR_CHARACTER).split(value)) { builder.add(new Path(string)); } return builder.build(); } } public Path firstElement() { if (this == ROOT_PATH) { throw new IllegalArgumentException("Cannot return first element of root path '.'"); } int index = value.indexOf(SEPARATOR_CHARACTER); if (index == -1) { return this; } else { return new Path(value.substring(0, index)); } } public Path lastElement() { if (this == ROOT_PATH) { throw new IllegalArgumentException("Cannot return last element of root path '.'"); } int index = value.lastIndexOf(SEPARATOR_CHARACTER); if (index == -1) { return this; } else { return new Path(value.substring(index + 1, value.length())); } } @Override public final boolean equals(Object object) { if (this == object) { return true; } if (object instanceof Path) { Path that = (Path) object; return this.value.equals(that.value); } return false; } @Override public final int hashCode() { return value.hashCode(); } @Override public String toString() { return "'" + value + "'"; } }
package ui; import game.Green; import game.Mustard; import game.Peacock; import game.Plum; import game.Scarlett; import game.White; import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; public class BoardFrame extends JFrame implements MouseListener,MouseMotionListener{ int mouseClickX; int mouseClickY; private static int windowHeight = 850; private int sidePanelWidth = 250; private final BoardCanvas canvas; private JPanel sidePanel; private JScrollPane textSP; private static JTextArea textOutput; private GridBagConstraints grid; private JButton accuseButton; private JButton endTurnButton; private JButton revealCardsButton; private JMenuBar menuBar; private JMenu menu; private JMenuItem menuItem; private JButton diceRollButton; public BoardFrame(){ super("CLUEDO"); canvas = new BoardCanvas(new Board()); setLayout(new BorderLayout()); setupComponents(); add(menuBar, BorderLayout.NORTH); add(canvas, BorderLayout.WEST); //Lays out board in center, adds the canvas add(sidePanel, BorderLayout.EAST); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setResizable(false); //prevents board from being resizable setVisible(true); addMouseListener(this); } /** * Method which sets up the main window components for the game */ private void setupComponents(){ // Setup grid grid = new GridBagConstraints(); // Setup JMenuBar // MenuBar menuBar = new JMenuBar(); // Menu menu = new JMenu("Menu"); menu.getAccessibleContext().setAccessibleDescription( "Menu Bar"); //create menuitems menuItem = startNewGame(); //add items menuBar.add(menu); menu.add(menuItem); // Setup sidepanel sidePanel = new JPanel(new GridBagLayout()); sidePanel.setSize(sidePanelWidth, windowHeight); sidePanel.setBackground(Color.gray); // Setup components for sidePanel // Text Area textOutput = new JTextArea(5, 25); textOutput.setEditable(false); textOutput.setText(" Welcome to Cluedo"); textSP = new JScrollPane(textOutput); accuseButton = newAccuseButton(); endTurnButton = newEndTurnButton(); revealCardsButton = newRevealCardsButton(); diceRollButton = newDiceRollButton(canvas); //Add components grid.gridwidth = 3; grid.gridx = 0; grid.gridy = 0; sidePanel.add(textSP, grid); grid.gridwidth = 1; grid.gridx = 0; grid.gridy = 2; sidePanel.add(accuseButton, grid); grid.gridx = 1; sidePanel.add(endTurnButton, grid); grid.gridx = 2; sidePanel.add(revealCardsButton, grid); grid.gridx = 1; grid.gridy = 3; sidePanel.add(diceRollButton, grid); } /** * Method which starts a new game with 2-6 players * @return JMenuItem stating asking how many players in the new game, then starting a new game */ private JMenuItem startNewGame(){ JMenuItem startNewGameItem = new JMenuItem("New Game"); startNewGameItem.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { Window mainWindow = SwingUtilities.windowForComponent(menuItem); JDialog title = new JDialog(mainWindow, "New Game"); title.setLocation(200,250); title.setModal(true); //Number of Players Panel JPanel numberPlayersPanel = new JPanel(); //Using Radio Buttons for Characters 2-6 players (Cant have one, 1 player would be pointless) final JRadioButton player2 = new JRadioButton("2 Players"); player2.setActionCommand("Play with 2 Players"); player2.setSelected(true); final JRadioButton player3 = new JRadioButton("3 Players"); player3.setActionCommand("Play with 3 Players"); player3.setSelected(true); final JRadioButton player4 = new JRadioButton("4 Players"); player4.setActionCommand("Play with 4 Players"); player4.setSelected(true); final JRadioButton player5 = new JRadioButton("5 Players"); player5.setActionCommand("Play with 5 Players"); player5.setSelected(true); final JRadioButton player6 = new JRadioButton("6 Players"); player6.setActionCommand("Play with 6 Players"); player6.setSelected(true); //Make a group for the buttons final ButtonGroup buttonGroup = new ButtonGroup(); buttonGroup.add(player2); buttonGroup.add(player3); buttonGroup.add(player4); buttonGroup.add(player5); buttonGroup.add(player6); //Submit button and logic for new game window JButton submitButton = new JButton("Submit"); submitButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { int players; if(player2.isSelected()){ players = 2; enterPlayerName(2); } else if(player3.isSelected()){ players = 3; enterPlayerName(3); } else if(player4.isSelected()){ players = 4; enterPlayerName(4); } else if(player5.isSelected()){ players = 5; enterPlayerName(5); } else{ players = 6; enterPlayerName(6); } //Now that number of players is established, set the player characters canvas.getGameBoard().addPlayer(0, new Scarlett()); if(players >= 2){ canvas.getGameBoard().addPlayer(1, new Mustard()); } if(players >= 3){ canvas.getGameBoard().addPlayer(2, new White()); } if(players >= 4){ canvas.getGameBoard().addPlayer(3, new Green()); } if(players >= 5){ canvas.getGameBoard().addPlayer(4, new Peacock()); } if(players >= 6){ canvas.getGameBoard().addPlayer(5, new Plum()); } } }); numberPlayersPanel.add(player2); numberPlayersPanel.add(player3); numberPlayersPanel.add(player4); numberPlayersPanel.add(player5); numberPlayersPanel.add(player6); numberPlayersPanel.add(submitButton); title.add(numberPlayersPanel); title.pack(); title.setVisible(true); } }); return startNewGameItem; } public BoardCanvas getCanvas(){ return canvas; } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub2 } @Override public void mousePressed(MouseEvent e) { canvas.selectPiece(e.getX(), e.getY()); System.out.println(e.getX()+":"+e.getY()); canvas.repaint(); } @Override public void mouseReleased(MouseEvent e) { canvas.setPiece(e.getX(), e.getY()); canvas.repaint(); } @Override public void mouseDragged(MouseEvent e) { canvas.movePiece(e.getX(), e.getY()); canvas.repaint(); } @Override public void mouseMoved(MouseEvent e) { } /** * Method that creates a button containing logic for the accusations * @return Button containing logic for accuse Window */ public static JButton newAccuseButton(){ final JButton button = new JButton(" Accuse "); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Window window = SwingUtilities.windowForComponent(button); final JDialog dialog = new JDialog(window, "Accuse"); dialog.setLocation(200, 350); dialog.setModal(true); JPanel cardsPanel = new JPanel(); //DropDowns String[] murderersList = { "Miss Scarlett", "Col. Mustard", "Mrs. White", "Reverand Green", "Mrs. Peacock", "Prof. Plum"}; final JComboBox<String> murderers = new JComboBox<String>(murderersList); String[] murderItemsList = { "Candlestick", "Dagger", "Lead Pipe", "Revolver", "Rope", "Spanner"}; final JComboBox<String> murderItems = new JComboBox<String>(murderItemsList); String[] murderRoomList = {"Kitchen", "Ball Room", "Conservatory", "Dining Room", "Billiard Room", "Library", "Lounge", "Hall", "Study"}; final JComboBox<String> murderRoom = new JComboBox<String>(murderRoomList); //Needs a check somewhere for whether the player is in a room final JButton submit = new JButton("Submit"); submit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { } }); //Could possibly add something to distinguish between accusing and checking within rooms? cardsPanel.add(murderers); cardsPanel.add(murderItems); cardsPanel.add(murderRoom); cardsPanel.add(submit); dialog.add(cardsPanel); dialog.pack(); dialog.setVisible(true); } }); return button; } /** * Method which creates "End Turn" Button with its logic (For ending players turn and passing to the next player), and returns it * * @return JButton containing logic for Ending turn */ public static JButton newEndTurnButton(){ final JButton button = new JButton(" End Turn "); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { } }); return button; } /** * Method which creates "Reveal Cards" Button with its logic (For hiding and revealing the players hand), and returns it * * @return JButton containing logic for Hiding and Revealing Cards */ public static JButton newRevealCardsButton(){ final JButton button = new JButton("Reveal Cards"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { } }); return button; } /** * Method which creates "Roll Dice" Button with its logic, and returns it * @param canvas * @return JButton containing logic for rolling dice */ public static JButton newDiceRollButton(final BoardCanvas canvas){ final JButton button = new JButton("Roll Dice"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) {canvas.getGameBoard().rollDice();} }); return button; } /** * Method which contains logic for setting up the players in the game * @param players - Int describing how many players are to be in the game */ public void enterPlayerName(int players){ if(players >=6){ Window player6Window = SwingUtilities.windowForComponent(menuItem); JDialog player6Name = new JDialog(player6Window, "Player 6: Enter Name"); player6Name.setLocation(200,250); player6Name.setModal(true); player6Name.pack(); player6Name.setVisible(true); } if(players >= 5){ Window player5Window = SwingUtilities.windowForComponent(menuItem); JDialog player5Name = new JDialog(player5Window, "Player 5: Enter Name"); player5Name.setLocation(200,250); player5Name.setModal(true); player5Name.pack(); player5Name.setVisible(true); } if(players >= 4){ Window player4Window = SwingUtilities.windowForComponent(menuItem); JDialog player4Name = new JDialog(player4Window, "Player 4: Enter Name"); player4Name.setLocation(200,250); player4Name.setModal(true); player4Name.pack(); player4Name.setVisible(true); } if(players >= 3){ Window player3Window = SwingUtilities.windowForComponent(menuItem); JDialog player3Name = new JDialog(player3Window, "Player 3: Enter Name"); player3Name.setLocation(200,250); player3Name.setModal(true); player3Name.pack(); player3Name.setVisible(true); } if(players >= 2){ Window player2Window = SwingUtilities.windowForComponent(menuItem); JDialog player2Name = new JDialog(player2Window, "Player 2: Enter Name"); player2Name.setLocation(200,250); player2Name.setModal(true); player2Name.pack(); player2Name.setVisible(true); } if(players >= 1){ Window player1Window = SwingUtilities.windowForComponent(menuItem); JDialog player1Name = new JDialog(player1Window, "Player 1: Enter Name"); player1Name.setLocation(200,250); player1Name.setModal(true); player1Name.pack(); player1Name.setVisible(true); } } }
package by.stub.database; import by.stub.client.StubbyResponse; import by.stub.client.StubbyResponseFactory; import by.stub.http.StubbyHttpTransport; import by.stub.utils.ObjectUtils; import by.stub.utils.ReflectionUtils; import by.stub.yaml.stubs.NotFoundStubResponse; import by.stub.yaml.stubs.RedirectStubResponse; import by.stub.yaml.stubs.StubHttpLifecycle; import by.stub.yaml.stubs.StubRequest; import by.stub.yaml.stubs.StubResponse; import by.stub.yaml.stubs.UnauthorizedStubResponse; import org.eclipse.jetty.http.HttpMethods; import java.io.File; import java.net.HttpURLConnection; 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; public class StubbedDataManager { private final File dataYaml; private final String dataYamlAbsolutePath; private final String dataYamlParentDirectory; private final List<StubHttpLifecycle> stubHttpLifecycles; public StubbedDataManager(final File dataYaml, final List<StubHttpLifecycle> stubHttpLifecycles) { this.dataYaml = dataYaml; this.dataYamlAbsolutePath = this.dataYaml.getAbsolutePath(); this.dataYamlParentDirectory = this.dataYaml.getParent(); this.stubHttpLifecycles = Collections.synchronizedList(stubHttpLifecycles); } public StubResponse findStubResponseFor(final StubRequest assertingRequest) { final StubHttpLifecycle assertingLifecycle = new StubHttpLifecycle(); assertingLifecycle.setRequest(assertingRequest); assertingLifecycle.setResponse(StubResponse.newStubResponse()); return identifyStubResponseType(assertingLifecycle); } private StubResponse identifyStubResponseType(final StubHttpLifecycle assertingLifecycle) { final StubHttpLifecycle matchedLifecycle = getMatchedStubHttpLifecycle(assertingLifecycle); if (ObjectUtils.isNull(matchedLifecycle)) { return new NotFoundStubResponse(); } final StubResponse stubResponse = matchedLifecycle.getResponse(); if (matchedLifecycle.isRestricted() && matchedLifecycle.hasNotAuthorized(assertingLifecycle)) { return new UnauthorizedStubResponse(); } if (stubResponse.hasHeaderLocation()) { return RedirectStubResponse.newRedirectStubResponse(stubResponse); } if (stubResponse.isRecordingRequired()) { try { final HttpURLConnection connection = new StubbyHttpTransport().constructHttpConnection(HttpMethods.GET, stubResponse.getBody()); try { connection.connect(); final StubbyResponse stubbyResponse = new StubbyResponseFactory(connection).construct(); ReflectionUtils.injectObjectFields(stubResponse, "body", stubbyResponse.getContent()); } finally { connection.disconnect(); } } catch (Exception e) { } } return stubResponse; } private synchronized StubHttpLifecycle getMatchedStubHttpLifecycle(final StubHttpLifecycle assertingLifecycle) { final int listIndex = stubHttpLifecycles.indexOf(assertingLifecycle); if (listIndex < 0) { return StubHttpLifecycle.NULL; } final StubHttpLifecycle foundStubHttpLifecycle = stubHttpLifecycles.get(listIndex); foundStubHttpLifecycle.setResourceId(listIndex); return foundStubHttpLifecycle; } public synchronized StubHttpLifecycle getMatchedStubHttpLifecycle(final int index) { if (!isStubHttpLifecycleExistsByIndex(index)) { return StubHttpLifecycle.NULL; } return stubHttpLifecycles.get(index); } public synchronized boolean resetStubHttpLifecycles(final List<StubHttpLifecycle> stubHttpLifecycles) { this.stubHttpLifecycles.clear(); final boolean added = this.stubHttpLifecycles.addAll(stubHttpLifecycles); if (added) { updateResourceIDHeaders(); } return added; } // Just a shallow copy that protects collection from modification, the points themselves are not copied public List<StubHttpLifecycle> getStubHttpLifecycles() { return new LinkedList<StubHttpLifecycle>(stubHttpLifecycles); } public File getDataYaml() { return dataYaml; } public synchronized Map<File, Long> getExternalFiles() { final Set<String> escrow = new HashSet<String>(); final Map<File, Long> externalFiles = new HashMap<File, Long>(); for (StubHttpLifecycle cycle : stubHttpLifecycles) { final File requestFile = cycle.getRequest().getRawFile(); if (ObjectUtils.isNotNull(requestFile) && !escrow.contains(requestFile.getName())) { escrow.add(requestFile.getName()); externalFiles.put(requestFile, requestFile.lastModified()); } final File responseFile = cycle.getResponse().getRawFile(); if (ObjectUtils.isNotNull(responseFile) && !escrow.contains(responseFile.getName())) { escrow.add(responseFile.getName()); externalFiles.put(responseFile, responseFile.lastModified()); } } return externalFiles; } public String getYamlAbsolutePath() { return dataYamlAbsolutePath; } public String getYamlParentDirectory() { return dataYamlParentDirectory; } public synchronized String getMarshalledYaml() { final StringBuilder builder = new StringBuilder(); for (final StubHttpLifecycle cycle : stubHttpLifecycles) { builder.append(cycle.getMarshalledYaml()).append("\n\n"); } return builder.toString(); } public synchronized String getMarshalledYamlByIndex(final int httpLifecycleIndex) { return stubHttpLifecycles.get(httpLifecycleIndex).getMarshalledYaml(); } public synchronized void updateStubHttpLifecycleByIndex(final int httpLifecycleIndex, final StubHttpLifecycle newStubHttpLifecycle) { deleteStubHttpLifecycleByIndex(httpLifecycleIndex); stubHttpLifecycles.add(httpLifecycleIndex, newStubHttpLifecycle); updateResourceIDHeaders(); } public synchronized boolean isStubHttpLifecycleExistsByIndex(final int httpLifecycleIndex) { return stubHttpLifecycles.size() - 1 >= httpLifecycleIndex; } public synchronized StubHttpLifecycle deleteStubHttpLifecycleByIndex(final int httpLifecycleIndex) { final StubHttpLifecycle removedLifecycle = stubHttpLifecycles.remove(httpLifecycleIndex); updateResourceIDHeaders(); return removedLifecycle; } private void updateResourceIDHeaders() { for (int index = 0; index < stubHttpLifecycles.size(); index++) { stubHttpLifecycles.get(index).setResourceId(index); } } }
package com.example.asm.resources; import android.content.Context; import android.os.Environment; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import java.util.Map; @SuppressWarnings("serial") class character implements Serializable { private static final long serialVersionUID = 1L; public final String char_name; public final String chronic_name; public String class_name; public String alignment; public String god; public final Map<String, Integer> phis_attr = new HashMap<>(); public final Map<String, Integer> soc_attr = new HashMap<>(); public final Map<String, Integer> men_attr = new HashMap<>(); private final Map<String, Integer> stored_phis_attr = new HashMap<>(); private final Map<String, Integer> stored_soc_attr = new HashMap<>(); private final Map<String, Integer> stored_men_attr = new HashMap<>(); public final Map<String, Integer> tal_abl = new HashMap<>(); public final Map<String, Integer> skl_abl = new HashMap<>(); public final Map<String, Integer> kng_abl = new HashMap<>(); private final Map<String, Integer> stored_tal_abl = new HashMap<>(); private final Map<String, Integer> stored_skl_abl = new HashMap<>(); private final Map<String, Integer> stored_kng_abl = new HashMap<>(); public final Map<String, Integer> bkg = new HashMap<>(); public final Map<String, Integer> sph = new HashMap<>(); public final Map<String, Integer> gft = new HashMap<>(); public final Map<String, Integer> dis = new HashMap<>(); private final Map<String, Integer> stored_bkg = new HashMap<>(); private final Map<String, Integer> stored_sph = new HashMap<>(); private final Map<String, Integer> stored_gft = new HashMap<>(); private final Map<String, Integer> stored_dis = new HashMap<>(); public final Map<String, Integer> sp_resources = new HashMap<>(); private Map<String, Integer> postponed_payments = new HashMap<>(); public Integer Generated; private String main_attr = "NULL"; private String scnd_attr = "NULL"; private String thrd_attr = "NULL"; private String main_abl = "NULL"; private String scnd_abl = "NULL"; private String thrd_abl = "NULL"; private final Integer attr_gen_limit; private final Integer abl_gen_limit; public Integer bkg_gen_points; public Integer cf_gen_points; private final Integer cf_gen_limit; public final Integer[] attr = new Integer[3]; public final Integer[] abl = new Integer[3]; public Integer free_points = 15; public character( String name, String chronic ) { char_name = name; chronic_name = chronic; class_name = "Воин"; alignment = "Законопослушный-Добрый"; god = "Акади"; Generated = 0; attr[0] = 7; attr[1] = 5; attr[2] = 3; abl[0] = 13; abl[1] = 9; abl[2] = 5; attr_gen_limit = 4; abl_gen_limit = 3; bkg_gen_points = 5; cf_gen_points = 5; cf_gen_limit = 3; phis_attr.put("strength", 1); phis_attr.put("dexterity", 1); phis_attr.put("stamina", 1); soc_attr.put("charisma", 1); soc_attr.put("manipulation", 1); soc_attr.put("appearance", 1); men_attr.put("perception", 1); men_attr.put("intelligence", 1); men_attr.put("wits", 1); tal_abl.put("alertness", 0); tal_abl.put("athletics", 0); tal_abl.put("brawl", 0); tal_abl.put("subterfuge", 0); tal_abl.put("ambidexter", 0); tal_abl.put("leadership", 0); tal_abl.put("intimidation", 0); tal_abl.put("persuasion", 0); tal_abl.put("streetwise", 0); tal_abl.put("enlightenment", 0); skl_abl.put("security", 0); skl_abl.put("craft", 0); skl_abl.put("blindfight", 0); skl_abl.put("etiquete", 0); skl_abl.put("firearms", 0); skl_abl.put("survival", 0); skl_abl.put("melee", 0); skl_abl.put("herbalism", 0); skl_abl.put("stealth", 0); skl_abl.put("concentration", 0); kng_abl.put("alchemistry", 0); kng_abl.put("logic", 0); kng_abl.put("investigation", 0); kng_abl.put("religion", 0); kng_abl.put("linguistics", 0); kng_abl.put("medecine", 0); kng_abl.put("occult", 0); kng_abl.put("politics", 0); kng_abl.put("science", 0); bkg.put("allies", 0); bkg.put("contacts", 0); bkg.put("fame", 0); bkg.put("resources", 0); bkg.put("dignity", 0); bkg.put("artifact", 0); sph.put("time", 0); sph.put("spirit", 0); sph.put("life", 0); sph.put("matter", 0); sph.put("prime", 0); sph.put("mind", 0); sph.put("connection", 0); sph.put("forces", 0); sph.put("entropy", 0); dis.put("animalism", 0); dis.put("auspex", 0); dis.put("celerity", 0); dis.put("chimerstry", 0); dis.put("daimoinon", 0); dis.put("dementation", 0); dis.put("dominate", 0); dis.put("fortitude", 0); dis.put("melpominee", 0); dis.put("obfuscate", 0); dis.put("obtenebration", 0); dis.put("potence", 0); dis.put("presence", 0); dis.put("protean", 0); dis.put("quietus", 0); dis.put("serpentis", 0); dis.put("temporis", 0); dis.put("thanatosis", 0); dis.put("vicissitude", 0); dis.put("alchemistry", 0); dis.put("conveyance", 0); dis.put("enchantment", 0); dis.put("healing", 0); dis.put("hellfire", 0); dis.put("weathercraft", 0); gft.put("common", 0); gft.put("monk", 0); gft.put("warlord", 0); gft.put("assassin", 0); gft.put("mageslayer", 0); gft.put("shapeshifter", 0); sp_resources.put("rage", 0); sp_resources.put("faith", 0); sp_resources.put("wp", 0); sp_resources.put("health", 0); sp_resources.put("perm_faith", 0); sp_resources.put("perm_wp", 0); } @SuppressWarnings("ConstantConditions") public Integer save_new_values(String group, String name, Integer number ) { String type; Integer prev_num; if (group.equals("attr")) { if ( Generated == 0 ) { if (number > attr_gen_limit) { number = attr_gen_limit; } } switch (name) { case "strength": case "dexterity": case "stamina": type = "phis"; prev_num = phis_attr.get(name); break; case "charisma": case "manipulation": case "appearance": type = "soc"; prev_num = soc_attr.get(name); break; default: type = "men"; prev_num = men_attr.get(name); break; } if ( main_attr.equals("NULL") || main_attr.equals(type) ) { main_attr = type; } else if ( scnd_attr.equals("NULL") || scnd_attr.equals(type) ) { scnd_attr = type; } else if ( thrd_attr.equals("NULL") || thrd_attr.equals(type) ) { thrd_attr = type; } if ( main_attr.equals(type) ) { if ( (number - prev_num) <= attr[0] ) { attr[0] -= (number - prev_num); } else { number = prev_num + attr[0]; attr[0] = 0; } switch (type) { case "phis": phis_attr.put(name, number); break; case "soc": soc_attr.put(name, number); break; case "men": men_attr.put(name, number); break; } } else if ( scnd_attr.equals(type) ) { if ( (number - prev_num) <= attr[1] ) { attr[1] -= (number - prev_num); } else { number = prev_num + attr[1]; attr[1] = 0; } switch (type) { case "phis": phis_attr.put(name, number); break; case "soc": soc_attr.put(name, number); break; case "men": men_attr.put(name, number); break; } } else if ( thrd_attr.equals(type) ) { if ( (number - prev_num) <= attr[2] ) { attr[2] -= (number - prev_num); } else { number = prev_num + attr[2]; attr[2] = 0; } switch (type) { case "phis": phis_attr.put(name, number); break; case "soc": soc_attr.put(name, number); break; case "men": men_attr.put(name, number); break; } } } if (group.equals("abl")) { if ( Generated == 0 ) { if (number > abl_gen_limit) { number = abl_gen_limit; } } Integer gen_points; if ( tal_abl.get(name) != null ) { prev_num = tal_abl.get(name); if ( number == 1 && prev_num == 1 ) { if ( !name.equals("enlightenment") && !class_name.equals("Маг") ) { number = 0; } } if (tal_abl.get( "gen_points" ) == null) { if (main_abl.equals("NULL")) { Integer postponed = postponed_payments.get("tal"); if ( postponed != null ) { abl[0] -= postponed; postponed_payments.remove("tal"); } tal_abl.put( "gen_points", abl[0] ); main_abl = "tal"; } else if (scnd_abl.equals("NULL")) { Integer postponed = postponed_payments.get("tal"); if ( postponed != null ) { abl[1] -= postponed; postponed_payments.remove("tal"); } tal_abl.put( "gen_points", abl[1] ); scnd_abl = "tal"; } else if (thrd_abl.equals("NULL")) { Integer postponed = postponed_payments.get("tal"); if ( postponed != null ) { abl[2] -= postponed; postponed_payments.remove("tal"); } tal_abl.put( "gen_points", abl[2] ); thrd_abl = "tal"; } } gen_points = tal_abl.get( "gen_points" ); if ( (number - prev_num) <= gen_points ) { gen_points -= (number - prev_num); } else { number = prev_num + gen_points; gen_points = 0; } tal_abl.put(name, number); tal_abl.put( "gen_points", gen_points ); if ( main_abl.equals("tal") ) { abl[0] = gen_points; } else if ( scnd_abl.equals("tal") ) { abl[1] = gen_points; } else if ( thrd_abl.equals("tal") ) { abl[2] = gen_points; } } if ( skl_abl.get(name) != null ) { prev_num = skl_abl.get(name); if ( number == 1 && prev_num == 1 ) { number = 0; } if (skl_abl.get( "gen_points" ) == null) { if (main_abl.equals("NULL")) { skl_abl.put( "gen_points", abl[0] ); main_abl = "skl"; } else if (scnd_abl.equals("NULL")) { skl_abl.put( "gen_points", abl[1] ); scnd_abl = "skl"; } else if (thrd_abl.equals("NULL")) { skl_abl.put( "gen_points", abl[2] ); thrd_abl = "skl"; } } gen_points = skl_abl.get( "gen_points" ); if ( (number - prev_num) <= gen_points ) { gen_points -= (number - prev_num); } else { number = prev_num + gen_points; gen_points = 0; } skl_abl.put(name, number); skl_abl.put( "gen_points", gen_points ); if ( main_abl.equals("skl") ) { abl[0] = gen_points; } else if ( scnd_abl.equals("skl") ) { abl[1] = gen_points; } else if ( thrd_abl.equals("skl") ) { abl[2] = gen_points; } } if ( kng_abl.get(name) != null ) { prev_num = kng_abl.get(name); if ( number == 1 && prev_num == 1 ) { if ( !name.equals("religion") && !class_name.equals("Жрец") ) { number = 0; } } if (kng_abl.get( "gen_points" ) == null) { if (main_abl.equals("NULL")) { Integer postponed = postponed_payments.get("kng"); if ( postponed != null ) { abl[2] -= postponed; postponed_payments.remove("kng"); } kng_abl.put( "gen_points", abl[0] ); main_abl = "kng"; } else if (scnd_abl.equals("NULL")) { Integer postponed = postponed_payments.get("kng"); if ( postponed != null ) { abl[2] -= postponed; postponed_payments.remove("kng"); } kng_abl.put( "gen_points", abl[1] ); scnd_abl = "kng"; } else if (thrd_abl.equals("NULL")) { Integer postponed = postponed_payments.get("kng"); if ( postponed != null ) { abl[2] -= postponed; postponed_payments.remove("kng"); } kng_abl.put( "gen_points", abl[2] ); thrd_abl = "kng"; } } gen_points = kng_abl.get( "gen_points" ); if ( (number - prev_num) <= gen_points ) { gen_points -= (number - prev_num); } else { number = prev_num + gen_points; gen_points = 0; } kng_abl.put(name, number); kng_abl.put( "gen_points", gen_points ); if ( main_abl.equals("kng") ) { abl[0] = gen_points; } else if ( scnd_abl.equals("kng") ) { abl[1] = gen_points; } else if ( thrd_abl.equals("kng") ) { abl[2] = gen_points; } } } if (group.equals("bkg")) { prev_num = bkg.get(name); if ( number == 1 && prev_num == 1 ) { number = 0; } if ( (number - prev_num) <= bkg_gen_points ) { bkg_gen_points -= (number - prev_num); } else { number = prev_num + bkg_gen_points; bkg_gen_points = 0; } bkg.put(name, number); } if (group.equals("sph")) { if ( Generated == 0 ) { if (number > cf_gen_limit) { number = cf_gen_limit; } } prev_num = sph.get(name); if ( number == 1 && prev_num == 1 ) { number = 0; } if ( (number - prev_num) <= cf_gen_points ) { cf_gen_points -= (number - prev_num); } else { number = prev_num + cf_gen_points; cf_gen_points = 0; } sph.put(name, number); } if (group.equals("dis")) { if ( Generated == 0 ) { if (number > cf_gen_limit) { number = cf_gen_limit; } } prev_num = dis.get(name); if ( number == 1 && prev_num == 1 ) { number = 0; } if ( (number - prev_num) <= cf_gen_points ) { cf_gen_points -= (number - prev_num); } else { number = prev_num + cf_gen_points; cf_gen_points = 0; } dis.put(name, number); } if (group.equals("gft")) { if ( Generated == 0 ) { if (number > cf_gen_limit) { number = cf_gen_limit; } } prev_num = gft.get(name); if ( number == 1 && prev_num == 1 ) { number = 0; } if ( (number - prev_num) <= cf_gen_points ) { cf_gen_points -= (number - prev_num); } else { number = prev_num + cf_gen_points; cf_gen_points = 0; } gft.put(name, number); } if (group.equals("button")) { return 1; } return number; } public boolean check_gen_points() { if ( Generated == 0 ) { Integer sum = 0; for (int e : attr) sum += e; for (int e : abl) sum += e; sum += bkg_gen_points; sum += cf_gen_points; if (sum > 0) { return true; } } return false; } public Integer save_fp_values( String group, String name, Integer number ) { Integer prev; Integer price; Integer diff; switch (group) { case "attr": price = 5; if (phis_attr.get(name) != null) { prev = phis_attr.get(name); diff = number - prev; if (number < stored_phis_attr.get(name)) { Integer st = prev - stored_phis_attr.get(name); diff = -st; number = stored_phis_attr.get(name); } if ((free_points - (price * diff)) >= 0) { free_points -= (price * diff); } else { Integer available = free_points / price; free_points -= available; number = prev + available; } phis_attr.put(name, number); } else if (soc_attr.get(name) != null) { prev = soc_attr.get(name); diff = number - prev; if (number < stored_soc_attr.get(name)) { Integer st = prev - stored_soc_attr.get(name); diff = -st; number = stored_soc_attr.get(name); } if ((free_points - (price * diff)) >= 0) { free_points -= (price * diff); } else { Integer available = free_points / price; free_points -= available; number = prev + available; } soc_attr.put(name, number); } else if (men_attr.get(name) != null) { prev = men_attr.get(name); diff = number - prev; if (number < stored_men_attr.get(name)) { Integer st = prev - stored_men_attr.get(name); diff = -st; number = stored_men_attr.get(name); } if ((free_points - (price * diff)) >= 0) { free_points -= (price * diff); } else { Integer available = free_points / price; free_points -= available; number = prev + available; } men_attr.put(name, number); } break; case "abl": price = 2; if (tal_abl.get(name) != null) { prev = tal_abl.get(name); if ( number == 1 && prev == 1 && stored_tal_abl.get(name) == 0 ) { number = 0; } diff = number - prev; if (number < stored_tal_abl.get(name)) { Integer st = prev - stored_tal_abl.get(name); diff = -st; number = stored_tal_abl.get(name); } if ((free_points - (price * diff)) >= 0) { free_points -= (price * diff); } else { Integer available = free_points / price; free_points -= available; number = prev + available; } tal_abl.put(name, number); } else if (skl_abl.get(name) != null) { prev = skl_abl.get(name); if ( number == 1 && prev == 1 && stored_skl_abl.get(name) == 0 ) { number = 0; } diff = number - prev; if (number < stored_skl_abl.get(name)) { Integer st = prev - stored_skl_abl.get(name); diff = -st; number = stored_skl_abl.get(name); } if ((free_points - (price * diff)) >= 0) { free_points -= (price * diff); } else { Integer available = free_points / price; free_points -= available; number = prev + available; } skl_abl.put(name, number); } else if (kng_abl.get(name) != null) { prev = kng_abl.get(name); if ( number == 1 && prev == 1 && stored_kng_abl.get(name) == 0 ) { number = 0; } diff = number - prev; if (number < stored_kng_abl.get(name)) { Integer st = prev - stored_kng_abl.get(name); diff = -st; number = stored_kng_abl.get(name); } if ((free_points - (price * diff)) >= 0) { free_points -= (price * diff); } else { Integer available = free_points / price; free_points -= available; number = prev + available; } kng_abl.put(name, number); } break; case "bkg": price = 1; prev = bkg.get(name); if ( number == 1 && prev == 1 && stored_bkg.get(name) == 0 ) { number = 0; } diff = number - prev; if (number < stored_bkg.get(name)) { Integer st = prev - stored_bkg.get(name); diff = -st; number = stored_bkg.get(name); } if ((free_points - (price * diff)) >= 0) { free_points -= (price * diff); } else { Integer available = free_points / price; free_points -= available; number = prev + available; } bkg.put(name, number); break; case "sph": price = 7; prev = sph.get(name); if ( number == 1 && prev == 1 && stored_sph.get(name) == 0 ) { number = 0; } diff = number - prev; if (number < stored_sph.get(name)) { Integer st = prev - stored_sph.get(name); diff = -st; number = stored_sph.get(name); } if ((free_points - (price * diff)) >= 0) { free_points -= (price * diff); } else { Integer available = free_points / price; free_points -= available; number = prev + available; } sph.put(name, number); break; case "dis": price = 7; prev = dis.get(name); if ( number == 1 && prev == 1 && stored_dis.get(name) == 0 ) { number = 0; } diff = number - prev; if (number < stored_dis.get(name)) { Integer st = prev - stored_dis.get(name); diff = -st; number = stored_dis.get(name); } if ((free_points - (price * diff)) >= 0) { free_points -= (price * diff); } else { Integer available = free_points / price; free_points -= available; number = prev + available; } dis.put(name, number); break; case "gft": price = 7; prev = gft.get(name); if ( number == 1 && prev == 1 && stored_gft.get(name) == 0 ) { number = 0; } diff = number - prev; if (number < stored_gft.get(name)) { Integer st = prev - stored_gft.get(name); diff = -st; number = stored_gft.get(name); } if ((free_points - (price * diff)) >= 0) { free_points -= (price * diff); } else { Integer available = free_points / price; free_points -= available; number = prev + available; } gft.put(name, number); break; case "button": if (! name.equals("wp")) { return 0; } price = 2; prev = sp_resources.get("perm_" + name); if ( number == 1 && prev == 1 && !class_name.equals("Маг") ) { number = 0; } diff = number - prev; if ((free_points - (price * diff)) >= 0) { free_points -= (price * diff); } else { Integer available = free_points / price; free_points -= available; number = prev + available; } sp_resources.put("perm_" + name, number); break; } return number; } public void store_values() { stored_phis_attr.putAll( phis_attr ); stored_soc_attr.putAll( soc_attr ); stored_men_attr.putAll( men_attr ); stored_tal_abl.putAll( tal_abl ); stored_skl_abl.putAll( skl_abl ); stored_kng_abl.putAll( kng_abl ); stored_bkg.putAll( bkg ); stored_sph.putAll( sph ); stored_dis.putAll( dis ); stored_gft.putAll( gft ); } private boolean isExternalStorageWritable() { String state = Environment.getExternalStorageState(); return Environment.MEDIA_MOUNTED.equals(state); } public void flush( Context context ) { String filename = char_name + " " + chronic_name; if ( isExternalStorageWritable() ){ FileOutputStream fos; try { fos = context.openFileOutput( filename, Context.MODE_PRIVATE); } catch ( FileNotFoundException e) { throw new RuntimeException( "Can't open file <" + filename + ">" ); } ObjectOutputStream os; try { os = new ObjectOutputStream(fos); os.writeObject(this); os.close(); fos.close(); } catch ( IOException e ) { throw new RuntimeException( "IO error <" + filename + ">" ); } } } public Integer get_health_pen() { Integer pen = 0; Integer health_val = sp_resources.get("health"); if ( 2 < health_val && health_val < 7 ) { pen = 1; } else if ( 6 < health_val && health_val < 11 ) { pen = 2; } else if ( 10 < health_val && health_val < 13 ) { pen = 5; } else if ( 12 < health_val && health_val <= 14 ) { pen = 10; } return pen; } public void return_m_point( String group ) { if ( group.equals("tal_abl") ) { if (postponed_payments.get("tal") == null) { Integer r_val = tal_abl.get("enlightenment"); Integer cur = tal_abl.get("gen_points"); cur += r_val; tal_abl.put("gen_points", cur); if (main_abl.equals("tal")) { abl[0] += r_val; } else if (scnd_abl.equals("tal")) { abl[1] += r_val; } else if (thrd_abl.equals("tal")) { abl[2] += r_val; } } else { postponed_payments.remove("tal"); } tal_abl.put("enlightenment", 0); } else if ( group.equals("kng_abl") ) { if (postponed_payments.get("kng") == null) { Integer r_val = kng_abl.get("religion"); Integer cur = kng_abl.get("gen_points"); cur += r_val; kng_abl.put("gen_points", cur); if (main_abl.equals("kng")) { abl[0] += r_val; } else if (scnd_abl.equals("kng")) { abl[1] += r_val; } else if (thrd_abl.equals("kng")) { abl[2] += r_val; } } else { postponed_payments.remove("kng"); } kng_abl.put("religion", 0); } } public void delay_charge( String name, Integer num ) { if ( name.equals("enlightenment") ) { tal_abl.put( name, num ); if ( main_abl.equals("tal") ) { abl[0] -= num; } else if ( scnd_abl.equals("tal") ) { abl[1] -= num; } else if ( thrd_abl.equals("tal") ) { abl[2] -= num; } else { postponed_payments.put( "tal", num ); } } else if ( name.equals("religion") ) { kng_abl.put( name, num ); if ( main_abl.equals("kng") ) { abl[0] -= num; } else if ( scnd_abl.equals("kng") ) { abl[1] -= num; } else if ( thrd_abl.equals("kng") ) { abl[2] -= num; } else { postponed_payments.put( "kng", num ); } } } }
package joshua.decoder.segment_file; import java.util.LinkedList; import java.util.List; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import joshua.corpus.Vocabulary; import joshua.decoder.ff.tm.Grammar; import joshua.decoder.JoshuaConfiguration; import joshua.lattice.Arc; import joshua.lattice.Lattice; import joshua.lattice.Node; import joshua.util.Regex; /** * This class represents a basic input sentence. A sentence is a sequence of UTF-8 characters * denoting a string of source language words. The sequence can optionally be wrapped in <seg * id="N">...</seg> tags, which are then used to set the sentence number (a 0-indexed ID). * * @author Matt Post <post@cs.jhu.edu> */ public class Sentence { private static final Logger logger = Logger.getLogger(Sentence.class.getName()); /* The sentence number. */ private int id = -1; /* * The source and target sides of the input sentence. Target sides are present when doing * alignment or forced decoding. */ protected String sentence; protected String target = null; protected String[] references = null; /* Lattice representation of the source sentence. */ protected Lattice<Integer> sourceLattice = null; private final List<ConstraintSpan> constraints; // Matches the opening and closing <seg> tags, e.g., // <seg id="72">this is a test input sentence</seg>. protected static final Pattern SEG_START = Pattern .compile("^\\s*<seg\\s+id=\"?(\\d+)\"?[^>]*>\\s*"); protected static final Pattern SEG_END = Pattern.compile("\\s*</seg\\s*>\\s*$"); /** * Constructor. Receives a string representing the input sentence. This string may be a * string-encoded lattice or a plain text string for decoding. * * @param inputSentence * @param id */ public Sentence(String inputSentence, int id) { inputSentence = Regex.spaces.replaceAll(inputSentence, " ").trim(); constraints = new LinkedList<ConstraintSpan>(); // Check if the sentence has SGML markings denoting the // sentence ID; if so, override the id passed in to the // constructor Matcher start = SEG_START.matcher(inputSentence); if (start.find()) { sentence = SEG_END.matcher(start.replaceFirst("")).replaceFirst(""); String idstr = start.group(1); this.id = Integer.parseInt(idstr); } else { if (inputSentence.indexOf(" ||| ") != -1) { String[] pieces = inputSentence.split("\\s?\\|{3}\\s?"); sentence = pieces[0]; target = pieces[1]; if (target.equals("")) target = null; if (pieces.length > 2) { references = new String[pieces.length - 2]; System.arraycopy(pieces, 2, references, 0, pieces.length - 2); } } else { sentence = inputSentence; } this.id = id; } adjustForLength(); } /** * Returns the length of the sentence. For lattices, the length is the shortest path through the * lattice. */ private int length() { return this.intLattice().getShortestDistance(); } /** * This function uses the supplied grammars to find OOVs in its input and create "detours" around * them by splitting the OOVs on internal word boundaries. The idea is to break apart noun * compounds in languages like German (such as the word "golfloch" = "golf" (golf) + "loch" (hole) * that artificially inflate the vocabulary with OOVs. * * @param grammars a list of grammars to consult to find in- and out-of-vocabulary items */ public void addOOVDetours(List<Grammar> grammars) { Lattice<Integer> lattice = this.intLattice(); Node<Integer> node = lattice.getNode(0); for (Arc<Integer> arc : node.getOutgoingArcs()) { int label = arc.getLabel(); boolean isOOV = true; for (Grammar grammar: grammars) { if (grammar.getTrieRoot().match(label) != null) { isOOV = false; break; } } /* If the word is an OOV, we now parse it at the character-level, with cells in the dynamic programming * chart recording whether each span represents a valid decomposition of in-vocabulary sequences of words. */ if (isOOV) { String word = Vocabulary.word(label); int[][] chart = new int[word.length()][word.length()]; for (int width = 1; width <= word.length(); width++) { for (int i = 0; i <= word.length() - width; i++) { int j = i + width; // TODO: finish this chart[i][j] = 1; } } } // Node<Integer> head = arc.getHead(); } } /** * If the input sentence is too long (not counting the <s> and </s> tokens), it is truncated to * the maximum length, specified with the "maxlen" parameter. * * Note that this code assumes the underlying representation is a sentence, and not a lattice. Its * behavior is undefined for lattices. */ private void adjustForLength() { Lattice<Integer> lattice = this.intLattice(); int size = lattice.size() - 2; // subtract off the start- and end-of-sentence tokens if (size > JoshuaConfiguration.maxlen) { logger.warning(String.format("* WARNING: sentence %d too long (%d), truncating to length %d", id(), size, JoshuaConfiguration.maxlen)); // Replace the input sentence (and target) String[] tokens = source().split("\\s+"); sentence = tokens[0]; for (int i = 1; i < JoshuaConfiguration.maxlen; i++) sentence += " " + tokens[i]; sourceLattice = null; if (target != null) { target = ""; } } } public boolean isEmpty() { return sentence.matches("^\\s*$"); } public int id() { return id; } public String source() { return sentence; } public String annotatedSource() { return Vocabulary.START_SYM + " " + sentence + " " + Vocabulary.STOP_SYM; } /** * If a target side was supplied with the sentence, this will be non-null. This is used when doing * synchronous parsing or constrained decoding. The input format is: * * Bill quiere ir a casa ||| Bill wants to go home * * If the parameter parse=true is set, parsing will be triggered, otherwise constrained decoding. * * @return */ public String target() { return target; } public String[] references() { return references; } public int[] intSentence() { return Vocabulary.addAll(annotatedSource()); } public List<ConstraintSpan> constraints() { return constraints; } public Lattice<Integer> intLattice() { if (this.sourceLattice == null) this.sourceLattice = Lattice.createIntLattice(intSentence()); return this.sourceLattice; } @Override public String toString() { StringBuilder sb = new StringBuilder(source()); if (target() != null) { sb.append(" ||| " + target()); } return sb.toString(); } }
package echode.api; import java.io.File; import java.io.PrintStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Scanner; import echode.Program; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.HashMap; import java.util.Map; public class Echode { Scanner scan; private String in; private List<Class> loaded = new ArrayList<>(); Class<?> c; boolean started = false; private PrintStream out; private Map<String, Map<String, ?>> vars = new HashMap<>(); /** * @param args * @throws ReflectiveOperationException */ public Echode(PrintStream out ) { this.out = out; } // welcome message public void intro() throws ReflectiveOperationException, MalformedURLException { out.println("Welcome to ECHODE version 0.3\nLoading echode.programs..."); load(); } private void load() throws ReflectiveOperationException, MalformedURLException { String currentDir = System.getProperty("user.dir"); //System.out.println(currentDir); File dir = new File(currentDir + "\\programs\\"); if (!dir.isDirectory()) { boolean mkdir = dir.mkdir(); if (!mkdir) { throw new RuntimeException("Making the directory failed."); } } URL url = new URL("file", currentDir, "programs/"); //out.println(dir); URL[] urls = new URL[1]; urls[0] = url; URLClassLoader loader = new URLClassLoader(urls); for (File f: dir.listFiles()) { out.println(f); if (f.getName().trim().endsWith(".class")) { String name = f.getName(); name = name.replaceAll(".class", ""); name = name.replace(dir.getAbsolutePath(), ""); name = name.replaceAll("/", "."); name = name.replaceAll("\\\\", "."); //out.println(); //out.println(name); Class c = loader.loadClass(name); for (Class<?> i:c.getInterfaces()) { if (i.equals(Program.class)) { loaded.add(c); out.println("Loaded " + c.getName()); } } } } } public void parse(String in2) throws ReflectiveOperationException { /** * Commented this out, in case needed. * * if (in2.equalsIgnoreCase("about")) { out.println( * "Echode version 0.2.2\nMade by Erik Konijn and Marks Polakovs"); } * else { if (in2.equalsIgnoreCase("kill")){ * out.println("Echode shut down successfully."); System.exit(0); * } else{ out.println("Not implemented yet."); } } **/ String[] result = in2.split(" "); switch (result[0]) { case "about": out .println("Echode version 0.3\nMade by Erik Konijn and Marks Polakovs"); break; case "kill": out.println("Echode shut down succesfully."); System.exit(0); break; //Help may be reimplemented at a later date case "version": out.println("0.3"); break; default: Class noparams[] = {}; for (Class c:loaded) { if(c.getName().equalsIgnoreCase(result[0])) { String[] argv = new String[result.length - 1]; for(int i = 0;i<result.length;i++) { if (!(i == 0)) { argv[i-1] = result[i]; } } c.getDeclaredMethod("run", PrintStream.class, String[].class) .invoke(c.getConstructors()[0].newInstance(noparams), out, argv); } } break; } } }
package kademlia.util.hashing; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * A class that is used to calculate the hash of strings. * * @author Joshua Kissoon * @since 20140405 */ public class HashCalculator { /** * Computes the SHA-1 Hash. * * @param toHash The string to hash * * @return byte[20] The hashed string * * @throws java.security.NoSuchAlgorithmException */ public static byte[] sha1Hash(String toHash) throws NoSuchAlgorithmException { /* Create a MessageDigest */ MessageDigest md = MessageDigest.getInstance("SHA-1"); /* Add password bytes to digest */ md.update(toHash.getBytes()); /* Get the hashed bytes */ return md.digest(); } /** * Computes the SHA-1 Hash using a Salt. * * @param toHash The string to hash * @param salt A salt used to blind the hash * * @return byte[20] The hashed string * * @throws java.security.NoSuchAlgorithmException */ public static byte[] sha1Hash(String toHash, String salt) throws NoSuchAlgorithmException { /* Create a MessageDigest */ MessageDigest md = MessageDigest.getInstance("SHA-1"); /* Add password bytes to digest */ md.update(toHash.getBytes()); /* Get the hashed bytes */ return md.digest(salt.getBytes()); } /** * Computes the MD5 Hash. * * @param toHash The string to hash * * @return byte[16] The hashed string * * @throws java.security.NoSuchAlgorithmException */ public static byte[] md5Hash(String toHash) throws NoSuchAlgorithmException { /* Create a MessageDigest */ MessageDigest md = MessageDigest.getInstance("MD5"); /* Add password bytes to digest */ md.update(toHash.getBytes()); /* Get the hashed bytes */ return md.digest(); } /** * Computes the MD5 Hash using a salt. * * @param toHash The string to hash * @param salt A salt used to blind the hash * * @return byte[16] The hashed string * * @throws java.security.NoSuchAlgorithmException */ public static byte[] md5Hash(String toHash, String salt) throws NoSuchAlgorithmException { /* Create a MessageDigest */ MessageDigest md = MessageDigest.getInstance("MD5"); /* Add password bytes to digest */ md.update(toHash.getBytes()); /* Get the hashed bytes */ return md.digest(salt.getBytes()); } }
package midmod; import midmod.json.Parser; import midmod.pal.Evaluator; import midmod.rules.RuleMap; import midmod.rules.actions.Action; import midmod.rules.actions.Actions; import midmod.rules.patterns.*; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.util.TraceClassVisitor; import javax.swing.*; import javax.swing.text.BadLocationException; import java.awt.event.KeyAdapter; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; import java.awt.event.KeyEvent; public class Main { private static int nativeActions; private static Action toNative(Object code) { ClassNode classNode = new ClassNode(Opcodes.ASM5); populateNativeCode(classNode, code); ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); classNode.accept(classWriter); ByteArrayOutputStream os = new ByteArrayOutputStream(); PrintWriter ps = new PrintWriter(os); classNode.accept(new TraceClassVisitor(new PrintWriter(System.out))); org.objectweb.asm.util.CheckClassAdapter.verify(new org.objectweb.asm.ClassReader(classWriter.toByteArray()), true, ps); byte[] bytes = classWriter.toByteArray(); String name = "NativeAction" + nativeActions++; try { return (Action)Class.forName(name, false, new SingleClassLoader(name, bytes)).newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } private static void populateNativeCode(ClassNode classNode, Object code) { if(code instanceof List) { List<Object> codeAsList = (List<Object>)code; // Dangerous String operator = (String)codeAsList.get(0); switch (operator) { case "+i": break; } } } public static void main(String[] args) throws IOException { RuleMap rules = new RuleMap(); boolean addBuiltins = true; if(addBuiltins) { rules.define( Patterns.conformsTo( Patterns.equalsObject("+"), Patterns.captureSingle(0, Patterns.is(String.class)), Patterns.captureSingle(1, Patterns.is(String.class)) ), (ruleMap, captures) -> (String) captures.get(0) + (String) captures.get(1) ); rules.define( Patterns.conformsTo( Patterns.equalsObject("toNative"), Patterns.captureSingle(0, Patterns.is(String.class)) ), (ruleMap, captures) -> toNative(captures.get(0)) ); rules.define( Patterns.conformsTo( Patterns.equalsObject("class"), Patterns.captureSingle(0, Patterns.is(String.class)) ), (ruleMap, captures) -> { try { return Class.forName((String) captures.get(0)); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; // Should be an error; how to handle errors? First class frames? Special case matching? } ); rules.define( Patterns.conformsTo( Patterns.equalsObject("invoke"), Patterns.captureSingle(0, Patterns.is(Class.class)), Patterns.captureSingle(1, Patterns.is(Object.class)), Patterns.captureSingle(2, Patterns.is(String.class)), Patterns.captureSingle(3, Patterns.is(List.class)), Patterns.captureSingle(4, Patterns.is(List.class)) ), (ruleMap, captures) -> { try { Class<?> klass = (Class<?>)captures.get(0); Object instance = captures.get(1); String methodName = (String)captures.get(2); List<Class<?>> parameterTypes = (List<Class<?>>)captures.get(3); List<Object> arguments = (List<Object>)captures.get(4); Class[] parameterTypesAsArray = parameterTypes.stream().toArray(s -> new Class[s]); Method method = klass.getMethod(methodName, parameterTypesAsArray); Object[] argumentsAsArray = (arguments).stream().toArray(s -> new Object[s]); return method.invoke(instance, argumentsAsArray); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; // Should be an error; how to handle errors? First class frames? } ); rules.defineBinary("+", Double.class, Double.class, (rhs, lhs) -> rhs + lhs); rules.defineBinary("+", Double.class, Integer.class, (rhs, lhs) -> rhs + lhs); rules.defineBinary("+", Integer.class, Double.class, (rhs, lhs) -> rhs + lhs); rules.defineBinary("+", Integer.class, Integer.class, (rhs, lhs) -> rhs + lhs); rules.defineBinary("-", Double.class, Double.class, (rhs, lhs) -> rhs - lhs); rules.defineBinary("-", Double.class, Integer.class, (rhs, lhs) -> rhs - lhs); rules.defineBinary("-", Integer.class, Double.class, (rhs, lhs) -> rhs - lhs); rules.defineBinary("-", Integer.class, Integer.class, (rhs, lhs) -> rhs - lhs); rules.defineBinary("*", Double.class, Double.class, (rhs, lhs) -> rhs * lhs); rules.defineBinary("*", Double.class, Integer.class, (rhs, lhs) -> rhs * lhs); rules.defineBinary("*", Integer.class, Double.class, (rhs, lhs) -> rhs * lhs); rules.defineBinary("*", Integer.class, Integer.class, (rhs, lhs) -> rhs * lhs); rules.defineBinary("/", Double.class, Double.class, (rhs, lhs) -> rhs / lhs); rules.defineBinary("/", Double.class, Integer.class, (rhs, lhs) -> rhs / lhs); rules.defineBinary("/", Integer.class, Double.class, (rhs, lhs) -> rhs / lhs); rules.defineBinary("/", Integer.class, Integer.class, (rhs, lhs) -> rhs / lhs); } new Thread(() -> { // Just some dummy source code for "warming up" the evaluator and parser String src = "{operator = \"+\", arg = \"MyString\"}"; try { new Evaluator(new RuleMap()).evaluate(src); } catch (IOException e) { e.printStackTrace(); } }).run(); Evaluator evaluator = new Evaluator(rules); JFrame frame = new JFrame(); JTextArea console = new JTextArea(); console.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if(e.isControlDown() && e.getKeyCode() == KeyEvent.VK_ENTER) { String sourceCode = console.getText(); int start = console.getSelectionStart(); int end = console.getSelectionEnd(); if(start == end) { start = 0; end = console.getDocument().getLength(); } try { sourceCode = console.getDocument().getText(start, end - start); } catch (BadLocationException e1) { e1.printStackTrace(); } try { Object result = evaluator.evaluate(new ByteArrayInputStream(sourceCode.getBytes())); String outputText = " " + result; console.getDocument().insertString(end, outputText, null); console.select(end + 1, end + outputText.length()); } catch (IOException e1) { e1.printStackTrace(); } catch (BadLocationException e1) { e1.printStackTrace(); } } } }); frame.getContentPane().add(console); frame.setSize(800, 600); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); if(1 != 2) return; """public class $@.name { $(@.fields >> (^.modifier >> ~0 "public" | ~1 "private") " " @.type " " @.name ) $(@.methods | (@.modifier >> ~0 "public" | ~1 "private") " " @.returnType " " @.name "(" ")" "{" @.body >> body "}" ) }""" /* From reference models, project applications Could some sort of "algebraic collection oriented script language" be used? body => ( is Binary ~.lhs | body ~ >> ( is Add " + " | is Sub " - " | is Mul " * " | is Div " / " | is Rem " % " ) ~.rhs | body ) */ MapCell globals = new MapCell(); /*JFrame frame = new JFrame(); JTextArea console = new JTextArea(); console.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if(e.isControlDown() && e.getKeyCode() == KeyEvent.VK_ENTER) { String sourceCode = console.getText(); int start = console.getSelectionStart(); int end = console.getSelectionEnd(); if(start == end) { start = 0; end = console.getDocument().getLength(); } try { sourceCode = console.getDocument().getText(start, end - start); } catch (BadLocationException e1) { e1.printStackTrace(); } try { Parser parser = new Parser(new ByteArrayInputStream(sourceCode.getBytes())); Object result = parser.execute(globals); console.getDocument().insertString(end, "\n=> " + result, null); } catch (IOException e1) { e1.printStackTrace(); } catch (BadLocationException e1) { e1.printStackTrace(); } } } }); frame.getContentPane().add(console); frame.setSize(800, 600); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true);*/ new Parser( "Composite = {}\n" + "Composite.X = \"someValue\"\n" + "Name = \"MyClass\"\n" + "FirstName = \"John\"\n" + "LastName = \"Johnson\"\n" ).execute(globals); MapCell dict1 = new MapCell(); MapCell dict1_1 = new MapCell(); dict1.put("Composite", dict1_1); dict1_1.put("X", "someValue"); MapCell dict2 = new MapCell(); //dict1.addListener(dict2); dict1.put("Name", "MyClass"); dict1.put("FirstName", "John"); dict1.put("LastName", "Johnson"); //dict1.addListener(Cells.get("Name").addListener(Cells.func((String x) -> x + "Extended").addListener(Cells.define("NameX").addListener(dict2)))); dict1.addListener(Cells.get("Composite").addListener(Cells.get("X").addListener(Cells.put("CX").addListener(dict2)))); FunctionMapCell environment = new FunctionMapCell(); environment .reduce("concat", Arrays.asList(dict1.withListener( Cells.get("FirstName")), Cells.constant(" "), dict1.withListener(Cells.get("LastName")) ) ).addListener(Cells.put("FullName").addListener(dict2)); Predicate<Object[]> allAreStrings = arguments -> Arrays.asList(arguments).stream().allMatch(x -> x instanceof String); environment.define("concat", allAreStrings, strings -> ((List<String>) (Object) Arrays.asList(strings)).stream().collect(Collectors.joining())); System.out.println("dict1:"); System.out.println(dict1); System.out.println("dict2:"); System.out.println(dict2); System.out.println("environment:"); System.out.println(environment); dict1.remove("Name"); environment.define("concat", allAreStrings, strings -> ((List<String>) (Object) Arrays.asList(strings)).stream().collect(Collectors.joining(":"))); //((DictionaryCell)dict1.get("Composite")).define("X", "SomeNewValue"); //dict1_1.define("X", "someValue2"); //Cells.reduce(dict1.withListener(Cells.get("FirstName")), dict1.withListener(Cells.get("LastName")), String.class, String.class, (x, y) -> x + " " + y).addListener(Cells.define("FullName").addListener(dict2)); dict1.put("Composite", dict1_1); //environment.define("concat", strings -> ((List<String>) (Object) Arrays.asList(strings)).stream().collect(Collectors.joining())); //environment.remove("concat"); System.out.println("dict1:"); System.out.println(dict1); System.out.println("dict2:"); System.out.println(dict2); System.out.println("environment:"); System.out.println(environment); } }
package matlabcontrol; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** * Contains important configuration information regarding the setup of MATLAB and matlabcontrol. * * @since 3.1.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ class Configuration { private Configuration() {} /** * If running on OS X. * * @return */ static boolean isOSX() { return getOperatingSystem().startsWith("Mac OS X"); } /** * If running on Windows. * * @return */ static boolean isWindows() { return getOperatingSystem().startsWith("Windows"); } /** * If running on Linux. * * @return */ static boolean isLinux() { return getOperatingSystem().startsWith("Linux"); } /** * Gets a string naming the operating system. * * @return */ static String getOperatingSystem() { return System.getProperty("os.name"); } /** * Returns the location or alias of MATLAB on an operating system specific basis. * <br><br> * For OS X this will be the location, for Windows or Linux this will be an alias. For any other operating system an * exception will be thrown. * * @return * @throws MatlabConnectionException thrown if the location of MATLAB cannot be determined on OS X, or the alias * cannot be determined because the operating system is not Windows or Linux */ static String getMatlabLocation() throws MatlabConnectionException { //Determine the location of MATLAB String matlabLoc; //OS X if (isOSX()) { matlabLoc = getOSXMatlabLocation(); } //Windows or Linux else if (isWindows() || isLinux()) { matlabLoc = "matlab"; } //Other unsupported operating system else { throw new MatlabConnectionException("MATLAB's location or alias can only be determined for OS X, " + "Windows, & Linux. For this operating system the location or alias must be specified " + "explicitly."); } return matlabLoc; } /** * Determines the location of the MATLAB executable on OS X. If multiple versions are found, the last one * encountered will be used. * * @return MATLAB's location on OS X * * @throws MatlabConnectionException if the location cannot be determined */ @SuppressFBWarnings(value = "DMI_HARDCODED_ABSOLUTE_FILENAME", justification = "OS X is very predictable") private static String getOSXMatlabLocation() throws MatlabConnectionException { //Search for MATLAB in the Applications directory String matlabName = null; String[] files = new File("/Applications/").list(); if (files != null) { for (String fileName : files) { if (fileName.startsWith("MATLAB")) { matlabName = fileName; } } } //If no installation is found if (matlabName == null) { throw new MatlabConnectionException("No installation of MATLAB on OS X can be found"); } //Build path to the executable location String matlabLocation = "/Applications/" + matlabName + "/bin/matlab"; //Check the path actually exists if (!new File(matlabLocation).exists()) { throw new MatlabConnectionException("An installation of MATLAB on OS X was found but the main " + "executable file was not found in the anticipated location: " + matlabLocation); } return matlabLocation; } /** * Converts the classpath into RMI's codebase format. The codebase format is a list of URL formatted strings * separated by spaces. As the application may be running in a different directory, paths are made absolute. * * @return codebase * @throws MatlabConnectionException */ static String getClassPathAsRMICodebase() throws MatlabConnectionException { try { StringBuilder codebaseBuilder = new StringBuilder(); String[] paths = System.getProperty("java.class.path", "").split(File.pathSeparator); for (int i = 0; i < paths.length; i++) { codebaseBuilder.append("file: codebaseBuilder.append(new File(paths[i]).getCanonicalFile().toURI().toURL().getPath()); if (i != paths.length - 1) { codebaseBuilder.append(" "); } } return codebaseBuilder.toString(); } catch (IOException e) { throw new MatlabConnectionException("Unable to resolve classpath entry", e); } } /** * Converts the classpath into individual canonical entries. * * @return * @throws MatlabConnectionException */ static String[] getClassPathAsCanonicalPaths() throws MatlabConnectionException { try { String[] paths = System.getProperty("java.class.path", "").split(File.pathSeparator); for (int i = 0; i < paths.length; i++) { paths[i] = new File(paths[i]).getCanonicalPath(); } return paths; } catch (IOException e) { throw new MatlabConnectionException("Unable to resolve classpath entry", e); } } /** * Determines the location of this code at runtime. Either it will be the directory or jar this .class file is in. * (That is, the .class file built from compiling this .java file.) Returned as a string so that it may be used by * MATLAB. * <br><br> * It may not be possible to determine the location of the code due to the class loader for this class. The class * loader will determine if a code source was set and the format of its location. Due to the problematic nature * of determining code location this method has been designed to throw exceptions with very detailed exceptions to * aid in improving this method further based on anticipated bug reports. * * @return * @throws MatlabConnectionException */ static String getSupportCodeLocation() throws MatlabConnectionException { //domain should never be null ProtectionDomain domain = Configuration.class.getProtectionDomain(); //codeSource can be null CodeSource codeSource = domain.getCodeSource(); if (codeSource != null) { //url can be null URL url = codeSource.getLocation(); if (url != null) { //Convert from url to absolute path try { //uri cannot be null, but this method can throw a URISyntaxException URI uri = url.toURI(); //path could be null String path = uri.getPath(); if (path != null) { try { File file = new File(path).getCanonicalFile(); if (file.exists()) { return file.getAbsolutePath(); } else { ClassLoader loader = Configuration.class.getClassLoader(); throw new MatlabConnectionException("Support code location was determined improperly." + " Location does not exist.\n" + "Location determined as: " + file.getAbsolutePath() + "\n" + "Path: " + path + "\n" + "URI Location: " + uri + "\n" + "URL Location: " + url + "\n" + "Code Source: " + codeSource + "\n" + "Protection Domain: " + domain + "\n" + "Class Loader: " + loader + (loader == null ? "" : "\nClass Loader Class: " + loader.getClass())); } } //Unable to resolve canconical path catch (IOException e) { ClassLoader loader = Configuration.class.getClassLoader(); throw new MatlabConnectionException("Support code location could not be determined. " + "Could not resolve canonical path.\n" + "Path: " + path + "\n" + "URI Location: " + uri + "\n" + "URL Location: " + url + "\n" + "Code Source: " + codeSource + "\n" + "Protection Domain: " + domain + "\n" + "Class Loader: " + loader + (loader == null ? "" : "\nClass Loader Class: " + loader.getClass()), e); } } //path was null else { ClassLoader loader = Configuration.class.getClassLoader(); throw new MatlabConnectionException("Support code location could not be determined. " + "Could not get path from URI location.\n" + "URI Location: " + uri + "\n" + "URL Location: " + url + "\n" + "Code Source: " + codeSource + "\n" + "Protection Domain: " + domain + "\n" + "Class Loader: " + loader + (loader == null ? "" : "\nClass Loader Class: " + loader.getClass())); } } //Unable to convert URL to URI catch (URISyntaxException e) { ClassLoader loader = Configuration.class.getClassLoader(); throw new MatlabConnectionException("Support code location could not be determined. " + "Could not convert from URL to URI location.\n" + "URL Location: " + url + "\n" + "Code Source: " + codeSource + "\n" + "Protection Domain: " + domain + "\n" + "Class Loader: " + loader + (loader == null ? "" : "\nClass Loader Class: " + loader.getClass()), e); } } //url was null else { ClassLoader loader = Configuration.class.getClassLoader(); throw new MatlabConnectionException("Support code location could not be determined. " + "Could not get URL from CodeSource.\n" + "Code Source: " + codeSource + "\n" + "Protection Domain: " + domain + "\n" + "Class Loader: " + loader + (loader == null ? "" : "\nClass Loader Class: " + loader.getClass())); } } //code source was null else { ClassLoader loader = Configuration.class.getClassLoader(); throw new MatlabConnectionException("Support code location could not be determined. " + "Could not get CodeSource from ProtectionDomain.\n" + "Protection Domain: " + domain + "\n" + "Class Loader: " + loader + (loader == null ? "" : "\nClass Loader Class: " + loader.getClass())); } } /** * Whether this code is running inside of MATLAB. * * @return */ static boolean isRunningInsideMatlab() { boolean available; try { //Load the class com.mathworks.jmi.Matlab and then calls its static method isMatlabAvailable() //All of this is done with reflection so that this class does not cause the class loader to attempt //to load JMI classes (and if not running inside of MATLAB - fail) Class<?> matlabClass = Class.forName("com.mathworks.jmi.Matlab"); Method isAvailableMethod = matlabClass.getMethod("isMatlabAvailable"); available = (Boolean) isAvailableMethod.invoke(null); } catch (Throwable t) { available = false; } return available; } }
package app.hongs.serv.matrix; import app.hongs.Cnst; import app.hongs.Core; import app.hongs.HongsException; import app.hongs.HongsExemption; import app.hongs.action.FormSet; import app.hongs.db.DB; import app.hongs.db.Model; import app.hongs.db.Table; import app.hongs.dh.search.SearchEntity; import app.hongs.util.Synt; import app.hongs.util.Tool; import java.io.File; import java.util.Collection; import java.util.LinkedHashMap; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.lucene.document.Document; /** * * @author Hongs */ public class Data extends SearchEntity { protected final String comf; protected final String conf; protected final String form; protected long time = 0; /** * * @param path * @param comf * @param conf * @param form */ public Data(String path, String comf, String conf, String form) { super(null, path, conf+"."+form); this.comf = comf; this.conf = conf; this.form = form; } /** * * @param conf * @param form */ public Data(String conf, String form) { this(conf.replaceFirst("^(centre|centra)/", ""), conf.replaceFirst("^(centre)/", "centra/"), conf, form); } /** * * Core * @param conf * @param form * @return */ public static Data getInstance(String conf, String form) { Data inst; Core core = Core.getInstance(); String name = Data.class.getName() +":"+ conf +":"+ form; if (core.containsKey(name)) { inst = (Data) core.got(name); } else { inst = new Data( conf, form); core.put ( name, inst); } return inst; } /** * * * * 0x1104 * @return */ @Override public Map getFields() { try { return super.getFields(); } catch (NullPointerException ex) { // Nothing todo } Map fields, fieldx; /** * centra/data * centre/data * * * */ try { if (! new File( Core.CONF_PATH + "/"+ conf + Cnst.FORM_EXT +".xml" ).exists()) { throw new HongsExemption(0x1104, "Data form conf '" + conf + "' is not exists") .setLocalizedOptions(conf); } fields = FormSet.getInstance(conf).getForm(form); if (! comf.equals(conf)) { if (! new File( Core.CONF_PATH + "/"+ comf + Cnst.FORM_EXT +".xml" ).exists()) { throw new HongsExemption(0x1104, "Data form conf '" + comf + "' is not exists") .setLocalizedOptions(comf); } fieldx = FormSet.getInstance(comf).getForm(form); fieldx = new LinkedHashMap(fieldx); fieldx.putAll( fields ); fields = fieldx; } } catch (HongsException ex) { throw ex.toExemption( ); } setFields(fields); return fields; } public String getFormId() { return Synt.declare(getParams().get("form_id"), form ); } public Model getModel() throws HongsException { String tn = Synt.declare(getParams().get("table.name"), "matrix.data"); if ("".equals(tn) || "none".equals(tn)) { return null; } return DB.getInstance("matrix").getModel(tn); } public Table getTable() throws HongsException { String tn = Synt.declare(getParams().get("table.name"), "matrix.data"); if ("".equals(tn) || "none".equals(tn)) { return null; } return DB.getInstance("matrix").getTable(tn); } /** * * @param rd * @return id,name(dispCols) * @throws HongsException */ @Override public Map create(Map rd) throws HongsException { long ct = System.currentTimeMillis() / 1000; rd.put("ctime" , ct); String id = Core.newIdentity(); save ( id , rd ); call ( id , "create", ct); Set<String> fs = getListable(); if (null != fs && ! fs.isEmpty( )) { Map sd = new LinkedHashMap( ); for(String fn : fs) { if ( ! fn.contains( "." )) { sd.put( fn, rd.get(fn) ); } } sd.put(Cnst.ID_KEY, id); return sd; } else { rd.put(Cnst.ID_KEY, id); return rd; } } /** * * @param rd * @return * @throws HongsException */ @Override public int update(Map rd) throws HongsException { long ct = System.currentTimeMillis() / 1000; rd.put("ctime" , ct); Set<String> ids = Synt.declare(rd.get(Cnst.ID_KEY), new HashSet()); permit (rd, ids , 0x1096); for(String id : ids) { save(id, rd ); call(id, "update", ct); } return ids.size(); } /** * * @param rd * @return * @throws HongsException */ @Override public int delete(Map rd) throws HongsException { long ct = System.currentTimeMillis() / 1000; rd.put("ctime" , ct); Set<String> ids = Synt.declare(rd.get(Cnst.ID_KEY), new HashSet()); permit (rd, ids , 0x1097); for(String id : ids) { drop(id, rd ); call(id, "delete", ct); } return ids.size(); } public void save(String id, Map rd) throws HongsException { Table table = getTable( ); String fid = getFormId(); String uid = (String) rd.get( "user_id" ); String where = "`id`=? AND `form_id`=? AND `etime`=?"; Object[] param = new String [ ] { id , fid , "0"}; long ctime = Synt.declare(rd.get("ctime"), 0L); if (0 == ctime) ctime = System.currentTimeMillis()/1000; Map dd = get( id ); if (! dd.isEmpty()) { if (table != null) { Map od = table.fetchCase() .filter( where, param) .select("ctime") .one(); if (! od.isEmpty( )) { if ( Synt.declare ( od.get("ctime"), 0L ) >= ctime ) { throw new HongsException(0x1100, ", "); } } } } else { if (table != null) { Map od = table.fetchCase() .filter( where, param) .select("ctime, data") .one(); if (! od.isEmpty( )) { if ( Synt.declare ( od.get("ctime"), 0L ) >= ctime ) { throw new HongsException(0x1100, ", "); } dd = (Map) app.hongs.util.Data.toObject(od.get("data").toString()); } } } int i = 0; Map<String,Map> fields = getFields(); for(String fn : fields.keySet()) { if ( "id". equals(fn)) { dd.put(fn , id); } else if (rd.containsKey(fn)) { Object fr = Synt.defoult(rd.get(fn), ""); Object fo = Synt.defoult(dd.get(fn), ""); dd.put(fn , fr); if (!equals(fr,fo) && !fn.equals("muid" ) && !fn.equals("mtime")) { i ++; } } } if (i == 0) { return; } dd.put("name", getName(dd)); dd.put("word", getWord(dd)); / if (table != null) { Map ud = new HashMap(); ud.put("etime", ctime); Map nd = new HashMap(); nd.put("ctime", ctime); nd.put("etime", 0 ); nd.put("id", id ); nd.put("form_id", fid); nd.put("user_id", uid); nd.put("memo", rd.get("memo")); nd.put("name", dd.get("name")); nd.put("data", app.hongs.util.Data.toString(dd)); table.update(ud, where, param); table.insert(nd); } / Document doc = new Document(); dd.put(Cnst.ID_KEY, id); docAdd(doc, dd); setDoc(id, doc); } public void drop(String id, Map rd) throws HongsException { Table table = getTable( ); String fid = getFormId(); String uid = (String) rd.get( "user_id" ); String where = "`id`=? AND `form_id`=? AND `etime`=?"; Object[] param = new String [ ] { id , fid , "0"}; long ctime = Synt.declare(rd.get("ctime"), 0L); if (0 == ctime) ctime = System.currentTimeMillis()/1000; if (table != null) { Map dd = table.fetchCase() .filter( where, param) .select("ctime, state, data, name") .one(); if (dd.isEmpty()) { throw new HongsException(0x1104, ""); } if ( Synt.declare ( dd.get("ctime"), 0L ) >= ctime ) { throw new HongsException(0x1100, ", "); } Map ud = new HashMap(); ud.put("etime", ctime); Map nd = new HashMap(); nd.put("ctime", ctime); nd.put("etime", 0 ); ud.put("state", 0 ); nd.put("id", id ); nd.put("form_id", fid); nd.put("user_id", uid); nd.put("memo", rd.get("memo")); nd.put("name", dd.get("name")); nd.put("data", dd.get("data")); table.update(ud, where, param); table.insert(nd); } / delDoc(id); } public void redo(String id, Map rd) throws HongsException { Table table = getTable( ); String fid = getFormId(); String uid = (String) rd.get( "user_id" ); String where = "`id`=? AND `form_id`=? AND `ctime`=?"; long rtime = Synt.declare(rd.get("rtime"), 0L); long ctime = Synt.declare(rd.get("ctime"), 0L); Object[] param = new Object [ ] { id, fid, rtime }; if (0 == ctime) ctime = System.currentTimeMillis()/1000; / if (table == null) { throw new HongsException(0x1100, ""); } Map dd = table.fetchCase() .filter( where, param) .select("etime, state, data, name") .one(); if (dd.isEmpty()) { throw new HongsException(0x1100, ""); } if (Synt.declare(dd.get("etime"), 0L) == 0L) { throw new HongsException(0x1100, ""); } / Map ud = new HashMap(); ud.put("etime", ctime); rd.put("ctime", ctime); rd.put("rtime", rtime); rd.put("etime", 0 ); rd.put("form_id", fid); rd.put("user_id", uid); rd.put("name" , dd.get("name")); rd.put("data" , dd.get("data")); where = "`id`=? AND `form_id`=? AND `etime`=?"; param = new Object[]{id, fid,0}; table.update(ud , where, param); table.insert(rd); / dd = (Map) app.hongs.util.Data.toObject(dd.get("data").toString()); Document doc = new Document( ); dd.put(Cnst.ID_KEY, id); docAdd(doc, dd); setDoc(id, doc); } public void call(String id, String act, long now) throws HongsException { String url = (String) getParams().get("callback"); if (url == null || "".equals(url)) { return; } String fid = getFormId(); url = Tool.inject(url,Synt.mapOf( "id" , id , "action", act, "entity", fid, "time" , now )); DataCaller.getInstance().add(url); } protected boolean equals(Object fo, Object fr) { return fo.equals(fr); } private Set<String> wdCols = null; private Set<String> nmCols = null; @Override public Set<String> getSrchable() { if (null != wdCols) { return wdCols; } Map fs = (Map) getFields().get("word"); if (fs != null && Synt.declare(fs.get("editable"), true)) { wdCols = Synt.setOf ( "word" ); } else { wdCols = getCaseNames("srchable"); wdCols.remove("word"); } return wdCols; } public Set<String> getNameable() { if (null != nmCols) { return nmCols; } Map fs = (Map) getFields().get("name"); if (fs != null && Synt.declare(fs.get("editable"), true)) { nmCols = Synt.setOf ( "name" ); } else { nmCols = getCaseNames("nameable"); nmCols.remove("name"); } return nmCols; } /** * * @param dd * @return * @throws HongsException */ protected String getWord(Map dd) throws HongsException { StringBuilder nn = new StringBuilder(); Set < String> ns = getSrchable( ); for ( String fn : ns ) { Object fv = dd.get(fn); if (fv == null) continue ; if (fv instanceof Collection) for (Object fw : (Collection) fv ) { nn.append(fw).append(' '); } else { nn.append(fv).append(' '); } } String nm = nn.toString().trim( ); if (! ns.contains("word") && ! ns.contains("id") ) { return dd.get("id") +" "+ nm ; } else { return nm; } } /** * * @param dd * @return * @throws HongsException */ protected String getName(Map dd) throws HongsException { StringBuilder nn = new StringBuilder(); Set < String> ns = getNameable( ); for ( String fn : ns ) { Object fv = dd.get(fn); if (fv == null) continue ; if (fv instanceof Collection) for (Object fw : (Collection) fv ) { nn.append(fw).append(' '); } else { nn.append(fv).append(' '); } } String nm = nn.toString().trim( ); if (! ns.contains("name") && 99 < nm.length( ) ) { return nm.substring(0, 99) + "..."; } else { return nm; } } }
package org.postgresql.test.jdbc2; import org.postgresql.test.TestUtil; import org.postgresql.util.PGobject; import org.postgresql.geometric.*; import junit.framework.TestCase; import org.postgresql.util.PSQLException; import java.sql.*; import java.util.ArrayList; import java.util.List; /* * Test case for geometric type I/O */ public class GeometricTest extends TestCase { private Connection con; public GeometricTest(String name) { super(name); } // Set up the fixture for this testcase: a connection to a database with // a table for this test. protected void setUp() throws Exception { con = TestUtil.openDB(); TestUtil.createTable(con, "testgeometric", "boxval box, circleval circle, lsegval lseg, pathval path, polygonval polygon, pointval point, lineval line"); } // Tear down the fixture for this test case. protected void tearDown() throws Exception { TestUtil.dropTable(con, "testgeometric"); TestUtil.closeDB(con); } private void checkReadWrite(PGobject obj, String column) throws Exception { PreparedStatement insert = con.prepareStatement("INSERT INTO testgeometric(" + column + ") VALUES (?)"); insert.setObject(1, obj); insert.executeUpdate(); insert.close(); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT " + column + " FROM testgeometric"); assertTrue(rs.next()); assertEquals(obj, rs.getObject(1)); rs.close(); stmt.executeUpdate("DELETE FROM testgeometric"); stmt.close(); } public void testPGbox() throws Exception { checkReadWrite(new PGbox(1.0, 2.0, 3.0, 4.0), "boxval"); checkReadWrite(new PGbox( -1.0, 2.0, 3.0, 4.0), "boxval"); checkReadWrite(new PGbox(1.0, -2.0, 3.0, 4.0), "boxval"); checkReadWrite(new PGbox(1.0, 2.0, -3.0, 4.0), "boxval"); checkReadWrite(new PGbox(1.0, 2.0, 3.0, -4.0), "boxval"); } public void testPGcircle() throws Exception { checkReadWrite(new PGcircle(1.0, 2.0, 3.0), "circleval"); checkReadWrite(new PGcircle( -1.0, 2.0, 3.0), "circleval"); checkReadWrite(new PGcircle(1.0, -2.0, 3.0), "circleval"); } public void testPGlseg() throws Exception { checkReadWrite(new PGlseg(1.0, 2.0, 3.0, 4.0), "lsegval"); checkReadWrite(new PGlseg( -1.0, 2.0, 3.0, 4.0), "lsegval"); checkReadWrite(new PGlseg(1.0, -2.0, 3.0, 4.0), "lsegval"); checkReadWrite(new PGlseg(1.0, 2.0, -3.0, 4.0), "lsegval"); checkReadWrite(new PGlseg(1.0, 2.0, 3.0, -4.0), "lsegval"); } public void testPGpath() throws Exception { PGpoint[] points = new PGpoint[] { new PGpoint(0.0, 0.0), new PGpoint(0.0, 5.0), new PGpoint(5.0, 5.0), new PGpoint(5.0, -5.0), new PGpoint( -5.0, -5.0), new PGpoint( -5.0, 5.0), }; checkReadWrite(new PGpath(points, true), "pathval"); checkReadWrite(new PGpath(points, false), "pathval"); } public void testPGpolygon() throws Exception { PGpoint[] points = new PGpoint[] { new PGpoint(0.0, 0.0), new PGpoint(0.0, 5.0), new PGpoint(5.0, 5.0), new PGpoint(5.0, -5.0), new PGpoint( -5.0, -5.0), new PGpoint( -5.0, 5.0), }; checkReadWrite(new PGpolygon(points), "polygonval"); } public void testPGline() throws Exception { final String columnName = "lineval"; // PostgreSQL versions older than 9.4 support creating columns with the LINE datatype, but // not actually writing to those columns. Only try to write if the version if at least 9.4 final boolean roundTripToDatabase = TestUtil.haveMinimumServerVersion(con, "9.4"); if (TestUtil.haveMinimumServerVersion(con, "9.4")) { // Apparently the driver requires public no-args constructor, and postgresql doesn't accept lines with A and B // coefficients both being zero... so assert a no-arg instantiated instance throws an exception. if (roundTripToDatabase) { try { checkReadWrite(new PGline(), columnName); fail("Expected a PGSQLException to be thrown"); } catch (PSQLException e) { assertTrue(e.getMessage().contains("A and B cannot both be zero")); } } // Generate a dataset for testing. List<PGline> linesToTest = new ArrayList<PGline>(); for (double i = 1; i <= 3; i += 0.25) { // Test the 3-arg constructor (coefficients+constant) linesToTest.add(new PGline(i, (0 - i), (1 / i))); linesToTest.add(new PGline("{" + i + "," + (0 - i) + "," + (1 / i) + "}")); // Test the 4-arg constructor (x/y coords of two points on the line) linesToTest.add(new PGline(i, (0 - i), (1 / i), (1 / i / i))); linesToTest.add(new PGline(i, (0 - i), i, (1 / i / i))); // tests vertical line // Test 2-arg constructor (2 PGpoints on the line); linesToTest.add(new PGline(new PGpoint(i, (0 - i)), new PGpoint((1 / i), (1 / i / i)))); linesToTest.add(new PGline(new PGpoint(i, (0 - i)), new PGpoint(i, (1 / i / i)))); // tests vertical line // Test 1-arg constructor (PGlseg on the line); linesToTest.add(new PGline(new PGlseg(i, (0 - i), (1 / i), (1 / i / i)))); linesToTest.add(new PGline(new PGlseg(i, (0 - i), i, (1 / i / i)))); linesToTest.add(new PGline(new PGlseg(new PGpoint(i, (0 - i)), new PGpoint((1 / i), (1 / i / i))))); linesToTest.add(new PGline(new PGlseg(new PGpoint(i, (0 - i)), new PGpoint(i, (1 / i / i))))); } // Include persistence an querying if the postgresql version supports it. if (roundTripToDatabase) { for (PGline testLine : linesToTest) { checkReadWrite(testLine, columnName); } } } } public void testPGpoint() throws Exception { checkReadWrite(new PGpoint(1.0, 2.0), "pointval"); } }
package br.com.caelum.iogi.reflection; import br.com.caelum.iogi.DependenciesInjector; import br.com.caelum.iogi.Instantiator; import br.com.caelum.iogi.parameters.Parameters; import br.com.caelum.iogi.util.Ints; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import java.util.Collection; import java.util.LinkedList; import java.util.List; public class Constructors { public static final Ordering<ClassConstructor> orderConstructorsBySize = new Ordering<ClassConstructor>() { public int compare(final ClassConstructor first, final ClassConstructor second) { return Ints.compare(first.size(), second.size()); } }; private final Collection<ClassConstructor> classConstructors; private final DependenciesInjector dependenciesInjector; public Constructors(final Collection<ClassConstructor> constructors, final DependenciesInjector dependenciesInjector) { this.classConstructors = constructors; this.dependenciesInjector = dependenciesInjector; } public FilledConstructors compatibleWith(final Parameters relevantParameters) { final LinkedList<ClassConstructor> compatible = new LinkedList<ClassConstructor>(); for (final ClassConstructor classConstructor : classConstructors) { if (classConstructor.canInstantiateOrInject(relevantParameters, dependenciesInjector)) compatible.add(classConstructor); } return new FilledConstructors(compatible, relevantParameters, dependenciesInjector); } public int size() { return classConstructors.size(); } public static class FilledConstructors { private final Collection<ClassConstructor> classConstructors; private final Parameters parameters; private final DependenciesInjector dependenciesInjector; public FilledConstructors(final Collection<ClassConstructor> classConstructors, final Parameters parameters, final DependenciesInjector dependenciesInjector) { this.classConstructors = classConstructors; this.parameters = parameters; this.dependenciesInjector = dependenciesInjector; } public FilledConstructor largest() { if (classConstructors.isEmpty()) { return FilledConstructor.nullFilledConstructor(); } final ClassConstructor largestConstructor = orderConstructorsBySize.max(classConstructors); return new FilledConstructor(largestConstructor, parameters, dependenciesInjector); } } public static class FilledConstructor { private static FilledConstructor nullFilledConstructor() { return new FilledConstructor(null,null, null) { @Override public NewObject instantiate(final Instantiator<Object> argumentInstantiator) { return NewObject.nullNewObject(); } }; } private final ClassConstructor constructor; private final Parameters parameters; private final DependenciesInjector dependenciesInjector; public FilledConstructor(final ClassConstructor constructor, final Parameters parameters, final DependenciesInjector dependenciesInjector) { this.constructor = constructor; this.parameters = parameters; this.dependenciesInjector = dependenciesInjector; } public NewObject instantiate(final Instantiator<Object> argumentInstantiator) { Object newObjectValue = constructor.construct(argumentValues(argumentInstantiator)); return new NewObject(argumentInstantiator, constructor, parameters, newObjectValue); } private List<Object> argumentValues(Instantiator<Object> argumentInstantiator) { final List<Object> argumentValues = Lists.newArrayList(); for (final Target<?> target : constructor.argumentTargets()) { argumentValues.add(argumentValue(argumentInstantiator, target)); } return argumentValues; } private Object argumentValue(Instantiator<Object> argumentInstantiator, Target<?> target) { if (needsDependency(target)) return dependenciesInjector.provide(target); else return argumentInstantiator.instantiate(target, parameters); } private boolean needsDependency(Target<?> target) { return targetsNeedingADependency().contains(target); } private Collection<Target<?>> targetsNeedingADependency() { return constructor.notFulfilledBy(parameters); } } }
package bzh.plealog.dbmirror.main; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import org.apache.commons.cli.CommandLine; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import bzh.plealog.dbmirror.fetcher.PFTPLoaderDescriptor; import bzh.plealog.dbmirror.fetcher.PFTPLoaderSystem; import bzh.plealog.dbmirror.util.conf.Configuration; import bzh.plealog.dbmirror.util.conf.DBMSAbstractConfig; import bzh.plealog.dbmirror.util.log.LoggerCentral; import bzh.plealog.dbmirror.util.mail.PMailer; /** * This is the class to use to start databank installation from the command * line. The program takes a single argument, a string, being a global * descriptor file name without its extension. That file is supposed to be * located within the conf directory of the application.<br> * <br> * The program may be configured using an environment variable: KDMS_CONF_DIR. * This variable should declare the absolute path to the configuration directory * of KDMS. If that variable is not declared, then the application locates the * configuration directory as a sub-directory (i.e. conf) of the directory * obtained from Java Preference user.dir variable.<br> * <br> * In addition, some parameters can be passed to the JVM for special * configuration purposes:<br> * -DKL_HOME=an_absolute_path ; the absolute path to the KDMS installation home * dir. If not set, use user.dir java property. -DKL_DEBUG=true ; if true, if * set, log will be in debug mode<br> * -DKL_WORKING_DIR=an_absolute_path ; if not set, log and working directories * are set to java.io.tmp<br> * -DKL_LOG_FILE=a_file_name ; if set, creates a log file with that name within * KL_WORKING_DIR<br> * <br> * * @author Patrick G. Durand */ public class CmdLineInstaller { public static final String ERR_DESC_MISSING = "Missing directives file. Processus aborted."; private static final String ERR1 = "File not found: "; private static final String ERR2 = "Unable to read file: "; private static final String ERR3 = "Unexpected error: "; private static final Log LOGGER = LogFactory .getLog(DBMSAbstractConfig.KDMS_ROOTLOG_CATEGORY + ".PMirror"); private void sendTerminationMail(PFTPLoaderDescriptor fDescriptor) { PMailer mailer; String host, port, sender, pswd, recp, val, desc; host = fDescriptor.getProperty(PFTPLoaderDescriptor.MAILER_HOST); if (host == null || host.length() == 0) return; sender = fDescriptor.getProperty(PFTPLoaderDescriptor.MAILER_SENDER); if (sender == null || sender.length() == 0) return; recp = fDescriptor.getProperty(PFTPLoaderDescriptor.MAILER_RECP); if (recp == null || recp.length() == 0) return; mailer = new PMailer(host, sender); port = fDescriptor.getProperty(PFTPLoaderDescriptor.MAILER_PORT); if (port != null && port.length() != 0) mailer.setSmtpPort(Integer.valueOf(port)); pswd = fDescriptor.getProperty(PFTPLoaderDescriptor.MAILER_PSWD); if (pswd != null && pswd.length() != 0) mailer.setPassword(pswd); val = fDescriptor.getProperty(PFTPLoaderDescriptor.MAILER_DEBUG); if (val != null && val.equals("true")) mailer.setDebug(true); desc = fDescriptor.getDescriptorName(); if (LoggerCentral.errorMsgEmitted()) { mailer.sendMail(recp, "[" + DBMSAbstractConfig.KDMS_ROOTLOG_CATEGORY + "] - processing " + desc + ": ERROR", "Processing of " + desc + " emitted warnings. Please check KDMS log files."); } else if (LoggerCentral.processAborted()) { mailer.sendMail(recp, "[" + DBMSAbstractConfig.KDMS_ROOTLOG_CATEGORY + "] - processing " + desc + ": STOP", "Processing of " + desc + " has been canceled. Please check KDMS log files."); } else { mailer.sendMail(recp, "[" + DBMSAbstractConfig.KDMS_ROOTLOG_CATEGORY + "] - processing " + desc + ": OK", "Processing of " + desc + " is successful. Databases are now in production."); } } private void dumpStarterMessage(){ Properties props = StarterUtils.getVersionProperties(); StringBuffer buf = new StringBuffer("\n"); buf.append(props.getProperty("prg.app.name")); buf.append(" "); buf.append(props.getProperty("prg.version")); buf.append(".\n"); System.out.println(buf.toString()); System.out.println("Log file is: "+DBMSAbstractConfig.getLogAppPath()+DBMSAbstractConfig.getLogAppFileName()); System.out.println(" check out this file to get processing details"); System.out.println("Job is now running..."); } private void startApplication(String descriptorName, PFTPLoaderDescriptor fDescCmd) { PFTPLoaderSystem lSystem; PFTPLoaderDescriptor fDesc; String descriptor; StarterUtils.configureApplication(null, DBMSAbstractConfig.KDMS_ROOTLOG_CATEGORY + "-" + descriptorName, true, false, true); dumpStarterMessage(); descriptor = descriptorName + DBMSAbstractConfig.FEXT_GD; try { LoggerCentral.reset(); fDesc = new PFTPLoaderDescriptor(descriptor); fDesc.load(new FileInputStream(DBMSAbstractConfig.getOSDepConfPath(Configuration.DESCRIPTOR) + descriptor), true); if (fDescCmd!=null){ fDesc.update(fDescCmd); } lSystem = new PFTPLoaderSystem(new PFTPLoaderDescriptor[] { fDesc }); lSystem.runProcessing(); // send email to administrator if needed sendTerminationMail(fDesc); } catch (FileNotFoundException e) { LoggerCentral.error(LOGGER, ERR1 + descriptor); } catch (IOException e) { LoggerCentral.error(LOGGER, ERR2 + descriptor); } catch (Exception e) { LoggerCentral.error(LOGGER, ERR3 + e); } if (LoggerCentral.errorMsgEmitted()){ System.out.println("Job done with status: FAILURE. Review log file"); } else{ System.out.println("Job done with status: SUCCESS"); } } /** * Expect either a single argument, such an argument and some options or * some options only.<br/><br/> * * First case: argument is the name of a global descriptor file. Such a file must have * the extension gd (stands for Global Descriptor) and must be located within the * OS-dependent conf path of the application. Pass the file name without its extension. * <br/><br/> * Second case: argument is same as above. One can also pass in some additional * options that will override declarations of the global descriptor. * <br/><br/> * Third case: use command-line options only to define what have to be installed. * <br/><br/> * Options are defined in CmdLineInstallerOptions utility class. Use -h or -help * option to get software command-line description. */ public static void main(String[] args) { // convert the array of strings into an appropriate object CommandLine cmd = CmdLineInstallerOptions.handleArguments(args); // nothing to do, exit! if (cmd==null){ return; } // do we have a global descriptor name? (first and second cases described above) String globalDesc = CmdLineInstallerOptions.getDescriptorName(cmd); globalDesc = (globalDesc==null?"CmdLine":globalDesc); // do we have options? (second and third cases described above) PFTPLoaderDescriptor fDescCmd = CmdLineInstallerOptions.getDescriptorFromOptions(cmd); //go, go, go... CmdLineInstaller mirror = new CmdLineInstaller(); mirror.startApplication(globalDesc, fDescCmd); } }
package edu.wustl.catissuecore.action; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import edu.wustl.catissuecore.actionForm.CreateSpecimenForm; import edu.wustl.catissuecore.applet.AppletConstants; import edu.wustl.catissuecore.applet.CopyPasteOperationValidatorModel; import edu.wustl.catissuecore.applet.model.MultipleSpecimenTableModel; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.util.XMLPropertyHandler; public class MultipleSpecimenCopyPasteAction extends BaseAppletAction { /** * This method is used to copy data from Selected components(comments,events,biohazards,external identifiers,derive) * It updates the the Buttons map maps * @param mapping * @param form * @param request * @param response * @return * @throws Exception - Exception */ public ActionForward copy(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Map formBeanMap = (HashMap) request.getSession().getAttribute(Constants.MULTIPLE_SPECIMEN_FORM_BEAN_MAP_KEY); Map specimenMap = (HashMap) request.getSession().getAttribute(Constants.MULTIPLE_SPECIMEN_MAP_KEY); Map eventsMap = (HashMap) request.getSession().getAttribute(Constants.MULTIPLE_SPECIMEN_EVENT_MAP_KEY); Map buttonsMap = new HashMap(); Map appletDataMap = (Map) request.getAttribute(Constants.INPUT_APPLET_DATA); CopyPasteOperationValidatorModel validatorModel = (CopyPasteOperationValidatorModel) appletDataMap.get(AppletConstants.VALIDATOR_MODEL); Map dataListsMap = new HashMap(); String columns = XMLPropertyHandler.getValue(Constants.MULTIPLE_SPECIMEN_COLUMNS_PER_PAGE); dataListsMap.put(Constants.MULTIPLE_SPECIMEN_COLUMNS_PER_PAGE ,columns); MultipleSpecimenTableModel multipleSpecimenTableModel = new MultipleSpecimenTableModel(0, dataListsMap); List selectedCopiedRows = validatorModel.getSelectedCopiedRows(); List selectedCopiedCols = validatorModel.getSelectedCopiedCols(); for (int j = 0; j < selectedCopiedCols.size(); j++) { int copiedColumn = ((Integer) selectedCopiedCols.get(j)).intValue(); for (int i = 0; i < selectedCopiedRows.size(); i++) { int copiedRow = ((Integer) selectedCopiedRows.get(i)).intValue(); if (copiedRow >= AppletConstants.SPECIMEN_COMMENTS_ROW_NO) { String key = copiedRow + AppletConstants.MULTIPLE_SPECIMEN_ROW_COLUMN_SEPARATOR + copiedColumn; Object value = null; if (copiedRow == AppletConstants.SPECIMEN_COMMENTS_ROW_NO || copiedRow == AppletConstants.SPECIMEN_BIOHAZARDS_ROW_NO || copiedRow == AppletConstants.SPECIMEN_EXTERNAL_IDENTIFIERS_ROW_NO) { value = specimenMap.get(multipleSpecimenTableModel.getKey(copiedRow, copiedColumn)); buttonsMap.put(key, value); String keyForCount = multipleSpecimenTableModel.getKey(copiedRow, copiedColumn) + Constants.APPEND_COUNT; buttonsMap.put(keyForCount, specimenMap.get(keyForCount)); } else if (copiedRow == AppletConstants.SPECIMEN_EVENTS_ROW_NO) { value = eventsMap.get(multipleSpecimenTableModel.getKey(copiedRow, copiedColumn)); buttonsMap.put(key, value); } else if (copiedRow == AppletConstants.SPECIMEN_DERIVE_ROW_NO) { value = formBeanMap.get(multipleSpecimenTableModel.getKey(copiedRow, copiedColumn)); buttonsMap.put(key, value); } } } } request.getSession().setAttribute(Constants.MULTIPLE_SPECIMEN_BUTTONS_MAP_KEY, buttonsMap); writeMapToResponse(response, null); return null; } /** * This method is used to paste data to Selected components(comments,events,biohazards,external identifiers,derive) * It updates the three maps * 1. Multiple Specimen map * 2. Multiple Specimen form bean map * 3. Multiple Specimen events map * * @param mapping * @param form * @param request * @param response * @return * @throws Exception - Exception */ public ActionForward paste(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Map formBeanMap = (HashMap) request.getSession().getAttribute(Constants.MULTIPLE_SPECIMEN_FORM_BEAN_MAP_KEY); Map specimenMap = (HashMap) request.getSession().getAttribute(Constants.MULTIPLE_SPECIMEN_MAP_KEY); Map eventsMap = (HashMap) request.getSession().getAttribute(Constants.MULTIPLE_SPECIMEN_EVENT_MAP_KEY); Map buttonsMap = (HashMap) request.getSession().getAttribute(Constants.MULTIPLE_SPECIMEN_BUTTONS_MAP_KEY); Map appletDataMap = (Map) request.getAttribute(Constants.INPUT_APPLET_DATA); CopyPasteOperationValidatorModel validatorModel = (CopyPasteOperationValidatorModel) appletDataMap.get(AppletConstants.VALIDATOR_MODEL); Map dataListsMap = new HashMap(); String columns = XMLPropertyHandler.getValue(Constants.MULTIPLE_SPECIMEN_COLUMNS_PER_PAGE); dataListsMap.put(Constants.MULTIPLE_SPECIMEN_COLUMNS_PER_PAGE ,columns); MultipleSpecimenTableModel multipleSpecimenTableModel = new MultipleSpecimenTableModel(0, dataListsMap); List selectedCopiedRows = validatorModel.getSelectedCopiedRows(); List selectedCopiedCols = validatorModel.getSelectedCopiedCols(); List selectedPastedRows = validatorModel.getSelectedPastedRows(); List selectedPastedCols = validatorModel.getSelectedPastedCols(); /** * Calculate all rows to be pasted in case user has selected a single row to be pasted */ if (selectedPastedRows.size() == 1) { int rowValue = ((Integer) selectedPastedRows.get(0)).intValue(); for (int i = 1; i < selectedCopiedRows.size(); i++) { selectedPastedRows.add(new Integer(rowValue + i)); } } /** * Calculate all columns to be pasted in case user has selected a single column to be pasted */ if (selectedPastedCols.size() == 1) { int rowValue = ((Integer) selectedPastedCols.get(0)).intValue(); for (int i = 1; i < selectedCopiedCols.size(); i++) { selectedPastedCols.add(new Integer(rowValue + i)); } } for (int j = 0; j < selectedCopiedCols.size(); j++) { int copiedColumn = ((Integer) selectedCopiedCols.get(j)).intValue(); int pastedColumn = ((Integer) selectedPastedCols.get(j)).intValue(); System.out.println("\n\npastedColumn : "+ pastedColumn); for (int i = 0; i < selectedCopiedRows.size(); i++) { int copiedRow = ((Integer) selectedCopiedRows.get(i)).intValue(); int pastedRow = ((Integer) selectedPastedRows.get(i)).intValue(); if (copiedRow >= AppletConstants.SPECIMEN_COMMENTS_ROW_NO) { /** * If columns selected to paste is 1 and multiple columns are copied, * increament the column count as per copied columns */ String key = copiedRow + AppletConstants.MULTIPLE_SPECIMEN_ROW_COLUMN_SEPARATOR + copiedColumn; Object value = null; if (copiedRow == AppletConstants.SPECIMEN_COMMENTS_ROW_NO || copiedRow == AppletConstants.SPECIMEN_BIOHAZARDS_ROW_NO || copiedRow == AppletConstants.SPECIMEN_EXTERNAL_IDENTIFIERS_ROW_NO) { value = buttonsMap.get(key); specimenMap.put(multipleSpecimenTableModel.getKey(pastedRow, pastedColumn), value); String keyForCount = multipleSpecimenTableModel.getKey(copiedRow, copiedColumn) + Constants.APPEND_COUNT; specimenMap.put(multipleSpecimenTableModel.getKey(pastedRow, pastedColumn) + Constants.APPEND_COUNT, buttonsMap.get(keyForCount)); } else if (copiedRow == AppletConstants.SPECIMEN_EVENTS_ROW_NO) { value = buttonsMap.get(key); eventsMap.put(multipleSpecimenTableModel.getKey(pastedRow, pastedColumn), value); } else if (copiedRow == AppletConstants.SPECIMEN_DERIVE_ROW_NO) { value = buttonsMap.get(key); ArrayList listOfFormBean = (ArrayList) value; ArrayList newList = new ArrayList(); if(listOfFormBean!=null) { for (int k = 0; k < listOfFormBean.size(); k++) { CreateSpecimenForm createForm = (CreateSpecimenForm) ((CreateSpecimenForm) listOfFormBean.get(k)).clone(); newList.add(createForm); } formBeanMap.put(multipleSpecimenTableModel.getKey(pastedRow, pastedColumn), newList); } } } } } request.getSession().setAttribute(Constants.MULTIPLE_SPECIMEN_FORM_BEAN_MAP_KEY, formBeanMap); request.getSession().setAttribute(Constants.MULTIPLE_SPECIMEN_MAP_KEY, specimenMap); request.getSession().setAttribute(Constants.MULTIPLE_SPECIMEN_EVENT_MAP_KEY, eventsMap); writeMapToResponse(response, null); return null; } }
package edu.wustl.query.util.listener; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.util.Properties; import javax.naming.InitialContext; import javax.servlet.ServletContextEvent; import javax.sql.DataSource; import edu.wustl.cab2b.server.path.PathFinder; import edu.wustl.common.util.XMLPropertyHandler; import edu.wustl.common.util.global.ApplicationProperties; import edu.wustl.common.util.logger.Logger; import edu.wustl.common.vocab.VocabularyException; import edu.wustl.common.vocab.utility.VocabUtil; import edu.wustl.query.util.filter.StrutsConfigReader; import edu.wustl.query.util.global.Constants; import edu.wustl.query.util.global.VIProperties; import edu.wustl.query.util.global.Variables; public class QueryServletContextListenerUtil { public static void initializeQuery(ServletContextEvent sce, String datasourceJNDIName) throws Exception { Logger.configDefaultLogger(sce.getServletContext()); Variables.applicationHome = sce.getServletContext().getRealPath(""); setGlobalVariable(); //Added by Baljeet....This method caches all the Meta data initEntityCache(datasourceJNDIName); // Added to create map of query actions which will be used by QueryRequestFilter to check authorization StrutsConfigReader.init(Variables.applicationHome+File.separator+Constants.WEB_INF_FOLDER_NAME+File.separator+Constants.AQ_STRUTS_CONFIG_FILE_NAME); } private static void initEntityCache(String datasourceJNDIName) { try { //Added for initializing PathFinder and EntityCache InitialContext ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup(datasourceJNDIName); Connection conn = ds.getConnection(); PathFinder.getInstance(conn); } catch (Exception e) { //logger.debug("Exception occured while initialising entity cache"); } } private static void setGlobalVariable() throws Exception { String path = System.getProperty("app.propertiesFile"); XMLPropertyHandler.init(path); File propetiesDirPath = new File(path); Variables.propertiesDirPath = propetiesDirPath.getParent(); Variables.applicationName = ApplicationProperties.getValue("app.name"); Variables.applicationVersion = ApplicationProperties.getValue("app.version"); int maximumTreeNodeLimit = Integer.parseInt(XMLPropertyHandler.getValue(Constants.MAXIMUM_TREE_NODE_LIMIT)); Variables.maximumTreeNodeLimit = maximumTreeNodeLimit; readProperties(); path = System.getProperty("app.propertiesFile"); //configure VI setVIProperties(); } private static void setVIProperties() throws VocabularyException { Properties vocabProperties = VocabUtil.getVocabProperties(); VIProperties.sourceVocabName = vocabProperties.getProperty("source.vocab.name"); VIProperties.sourceVocabVersion = vocabProperties.getProperty("source.vocab.version"); VIProperties.sourceVocabUrn = vocabProperties.getProperty("source.vocab.urn"); VIProperties.searchAlgorithm = vocabProperties.getProperty("match.algorithm"); VIProperties.maxPVsToShow = Integer.valueOf(vocabProperties.getProperty("pvs.to.show")); VIProperties.maxToReturnFromSearch = Integer.valueOf(vocabProperties.getProperty("max.to.return.from.search")); VIProperties.translationAssociation = vocabProperties.getProperty("vocab.translation.association.name"); VIProperties.medClassName = vocabProperties.getProperty("med.class.name"); } private static void readProperties() { File file = new File(Variables.applicationHome + System.getProperty("file.separator") + "WEB-INF" + System.getProperty("file.separator") + "classes" + System.getProperty("file.separator") + "query.properties"); if (file.exists()) { Properties queryProperties = new Properties(); try { queryProperties.load(new FileInputStream(file)); Variables.queryGeneratorClassName = queryProperties.getProperty("query.queryGeneratorClassName"); //Added to get AbstractQuery Implementer Class Name. Variables.abstractQueryClassName = queryProperties.getProperty("query.abstractQueryClassName"); Variables.abstractQueryManagerClassName = queryProperties.getProperty("query.abstractQueryManagerClassName"); Variables.abstractQueryUIManagerClassName = queryProperties.getProperty("query.abstractQueryUIManagerClassName"); Variables.abstractQueryITableManagerClassName = queryProperties.getProperty("query.abstractQueryITableManagerClassName"); Variables.viewIQueryGeneratorClassName = queryProperties.getProperty("query.viewIQueryGeneratorClassName"); Variables.recordsPerPageForSpreadSheet = Integer.parseInt(queryProperties.getProperty("spreadSheet.recordsPerPage")); Variables.recordsPerPageForTree = Integer.parseInt(queryProperties.getProperty("tree.recordsPerPage")); Variables.resultLimit = Integer.parseInt(queryProperties.getProperty("datasecurity.resultLimit")); Variables.exportDataThreadClassName = queryProperties.getProperty("query.exportDataThreadClassName"); Variables.dataQueryExecutionClassName = queryProperties.getProperty("query.dataQueryExecutionClassName"); Variables.properties = queryProperties; Variables.csmUtility = queryProperties.getProperty("query.csmUtility"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } }
package com.cafeform.algorithm; import java.util.*; import java.util.concurrent.LinkedBlockingDeque; /** * Another implementation of bredth first search. * Uses color and predecesser HashMap to check the status of each node * color : Back=Found, Gray=Found, but not child search, White=Not found * predeccessor : parent node * * @author kaizawa */ class BreadthFirstSearch2 extends SearchAlgorithm { LinkedBlockingDeque<Node> foundNodeQueue = new LinkedBlockingDeque<>(); HashSet<Node> foundNodeSet = new HashSet<>(); HashMap<Node, Node> predeccessorMap = new HashMap(); public BreadthFirstSearch2(List<Node> nodeList, Node startNode, Node goalNode) { super(nodeList, startNode, goalNode); } @Override public SearchResult doSearch() { predeccessorMap.put(startNode, null); foundNodeQueue.add(startNode); while(false == foundNodeQueue.isEmpty()){ Node currentNode = foundNodeQueue.poll(); if (currentNode == goalNode) { break; } else { for (Node child : (Set<Node>) currentNode.getChildrenMap().keySet()) { time.incrementAndGet(); //Check if it has already been found if(foundNodeSet.contains(child)){ // This node has ever been found. continue; } // Put child node to the gray queue. foundNodeQueue.add(child); // Set currentNode as parent of child node predeccessorMap.put(child, currentNode); // Set color of child node to GRAY foundNodeSet.add(child); } } } // Return path which found first return new SearchResult(getShortstPathFromGloal(), "BreadthFirstSearch2", time.get()); } public List<Node> getShortstPathFromGloal(){ ArrayList<Node> shortestPath = new ArrayList<>(); for(Node node = goalNode; null != node; node = predeccessorMap.get(node)){ shortestPath.add(0, node); } return shortestPath; } }
package com.chariotsolutions.nfc.plugin; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Stack; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.content.IntentFilter; import android.content.IntentFilter.MalformedMimeTypeException; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.nfc.tech.Ndef; import android.nfc.tech.NdefFormatable; import android.os.Parcelable; import android.util.Log; import com.phonegap.api.Plugin; import com.phonegap.api.PluginResult; import com.phonegap.api.PluginResult.Status; public class NdefPlugin extends Plugin { private static Stack<Intent> queuedIntents = new Stack<Intent>(); private static final String REGISTER_MIME_TYPE = "registerMimeType"; private static final String REGISTER_NDEF = "registerNdef"; private static final String REGISTER_NDEF_FORMATTABLE = "registerNdefFormattable"; private static final String WRITE_TAG = "writeTag"; private static final String P2P = "p2p"; private static final String NDEF = "ndef"; private static final String NDEF_MIME = "ndef-mime"; private static final String NDEF_UNFORMATTED = "ndef-unformatted"; private NdefMessage p2pMessage = null; private Intent currentIntent = null; private static String TAG = "NdefPlugin"; private PendingIntent pendingIntent = null; private List<IntentFilter> intentFilters = null; private ArrayList<String[]> techLists = null; @Override // TODO refactor this into multiple methods public PluginResult execute(String action, JSONArray data, String callbackId) { initialize(); if (action.equalsIgnoreCase(REGISTER_MIME_TYPE)) { try { intentFilters.add(addDataTypeToNewIntentFilter(data)); } catch (InstantiationException e) { Log.e(TAG, e.toString()); return new PluginResult(Status.ERROR); } enableNfc(); parseQueuedMessages(); return new PluginResult(Status.OK); } else if (action.equalsIgnoreCase(REGISTER_NDEF)) { addTechList(new String[] { Ndef.class.getName() }); enableNfc(); parseQueuedMessages(); return new PluginResult(Status.OK); } else if (action.equalsIgnoreCase(REGISTER_NDEF_FORMATTABLE)) { addTechList(new String[] { NdefFormatable.class.getName()}); enableNfc(); parseQueuedMessages(); return new PluginResult(Status.OK); } else if (action.equalsIgnoreCase(WRITE_TAG)) { Tag tag = null; if (currentIntent == null) { Log.e(TAG, "Failed to write tag, recieved null intent"); return new PluginResult(Status.ERROR); } else { tag = currentIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG); } try { NdefRecord[] records = jsonToNdefRecords(data.getString(0)); writeTag(new NdefMessage(records), tag); } catch (JSONException e) { Log.e(TAG, "error reading ndefMessage from JSON"); return new PluginResult(Status.ERROR); } return new PluginResult(Status.OK); } else if (action.equalsIgnoreCase(P2P)) { try { NdefRecord[] records = jsonToNdefRecords(data.getString(0)); this.p2pMessage = new NdefMessage(records); this.ctx.runOnUiThread(new Runnable() { public void run() { NfcAdapter.getDefaultAdapter(NdefPlugin.this.ctx).enableForegroundNdefPush(NdefPlugin.this.ctx, p2pMessage); } }); } catch (JSONException e) { Log.e(TAG, "error reading ndefMessage from JSON"); return new PluginResult(Status.ERROR); } return new PluginResult(Status.OK); } Log.d(TAG, "no result"); return new PluginResult(Status.NO_RESULT); } private void initialize() { if (pendingIntent == null) { Intent intent = new Intent(ctx, ctx.getClass()); intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); pendingIntent = PendingIntent.getActivity(ctx, 0, intent, 0); } if (techLists == null) { techLists = new ArrayList<String[]>(); } if (intentFilters == null) { intentFilters = new ArrayList<IntentFilter>(); } } private NdefRecord[] jsonToNdefRecords(String ndefMessageAsJSON) throws JSONException { JSONArray jsonRecords = new JSONArray(ndefMessageAsJSON); NdefRecord[] records = new NdefRecord[jsonRecords.length()]; for (int i = 0; i < jsonRecords.length(); i++) { JSONObject record = jsonRecords.getJSONObject(i); byte tnf = (byte) record.getInt("tnf"); byte[] type = jsonToByteArray(record.getJSONArray("type")); byte[] id = jsonToByteArray(record.getJSONArray("id")); byte[] payload = jsonToByteArray(record.getJSONArray("payload")); records[i] = new NdefRecord(tnf, type, id, payload); } return records; } private void addTechList(String[] list) { this.addTechFilter(); this.addToTechList(list); } private void parseQueuedMessages() { while(!queuedIntents.isEmpty()) { parseMessage(queuedIntents.pop()); } } private void addTechFilter() { intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED)); } private void addToTechList(String[] techs) { techLists.add(techs); } private void enableNfc() { try { this.ctx.runOnUiThread(new NfcRunnable(ctx, this.getPendingIntent(), this.getIntentFilters().toArray(new IntentFilter[this.getIntentFilters().size()]), techLists.toArray(new String[0][0]))); } catch ( Exception e ) { Log.e(TAG, e.toString()); } } private IntentFilter addDataTypeToNewIntentFilter(JSONArray data) throws InstantiationException { IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); String mimeType = null; try { mimeType = (String) data.getString(0); } catch (JSONException jsone) { Log.e(TAG, "No data type supplied"); throw new InstantiationException(); } // TODO make this less crap if (mimeType != null) { try { ndef.addDataType(mimeType.toString()); } catch (MalformedMimeTypeException e) { Log.e(TAG, e.toString()); throw new InstantiationException(); } } else { Log.e(TAG, "Data Type was null"); throw new InstantiationException(); } return ndef; } private PendingIntent getPendingIntent() { return pendingIntent; } private List<IntentFilter> getIntentFilters() { return intentFilters; } public void parseMessage(Intent intent) { String action = intent.getAction(); this.currentIntent = intent; if (action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) { Parcelable[] rawData = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); for (Parcelable message : rawData) { fireNdefEvent(NDEF_MIME, message); } } else if (action.equals(NfcAdapter.ACTION_TECH_DISCOVERED)) { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); for (String tagTech : tag.getTechList()) { if (tagTech.equalsIgnoreCase(NdefFormatable.class.getName())) { fireNdefEvent(NDEF_UNFORMATTED); return; } else if (tagTech.equalsIgnoreCase(Ndef.class.getName())) { for (Parcelable message : intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)) { fireNdefEvent(NDEF, message); } } } } } private void fireNdefEvent(String type) { JSONArray jsonData = new JSONArray(); fireNdefEvent(type, jsonData); } private void fireNdefEvent(String type, Parcelable parcelable) { JSONArray jsonData = messageToJSON((NdefMessage)parcelable); fireNdefEvent(type, jsonData); } private void fireNdefEvent(String type, JSONArray ndefMessage) { String command = "NdefPlugin.fireEvent('" + type + "', " + ndefMessage + ")"; this.sendJavascript(command); } private JSONArray messageToJSON(NdefMessage message) { List<JSONObject> list = new ArrayList<JSONObject>(); List<NdefRecord> records = Arrays.asList(message.getRecords()); for (NdefRecord r : records) { list.add(recordToJSON(r)); } return new JSONArray(list); } private JSONObject recordToJSON(NdefRecord record) { JSONObject json = new JSONObject(); try { json.put("tnf", record.getTnf()); json.put("type", byteArrayToJSON(record.getType())); json.put("id", byteArrayToJSON(record.getId())); json.put("payload", byteArrayToJSON(record.getPayload())); } catch (JSONException e) { //Not sure why this would happen, documentation is unclear. Log.e(TAG,"Failed to convert ndef record into json: " + record.toString(), e); } return json; } private JSONArray byteArrayToJSON(byte[] bytes) { JSONArray json = new JSONArray(); for (int i = 0; i < bytes.length; i++) { json.put(bytes[i]); } return json; } private byte[] jsonToByteArray(JSONArray json) throws JSONException { byte[] b = new byte[json.length()]; for (int i = 0; i < json.length(); i++) { b[i] = (byte)json.getInt(i); } return b; } private PluginResult writeTag(NdefMessage message, Tag tag) { Log.d(TAG, "writeTag"); int size = message.toByteArray().length; try { Ndef ndef = Ndef.get(tag); if (ndef != null) { ndef.connect(); if (!ndef.isWritable()) { Log.e(TAG, "Failed to write tag - read only"); return new PluginResult(Status.ERROR); } if (ndef.getMaxSize() < size) { Log.e(TAG, "Tag capacity is " + ndef.getMaxSize() + " bytes, message is " + size + " bytes."); return new PluginResult(Status.ERROR); } ndef.writeNdefMessage(message); return new PluginResult(Status.OK); } else { NdefFormatable format = NdefFormatable.get(tag); if (format != null) { try { format.connect(); format.format(message); Log.e(TAG, "Formatted tag and wrote message"); return new PluginResult(Status.OK); } catch (IOException e) { Log.e(TAG, "Failed to format tag."); return new PluginResult(Status.ERROR); } } else { Log.e(TAG, "Tag doesn't support NDEF."); return new PluginResult(Status.ERROR); } } } catch (Exception e) { Log.e(TAG, "Failed to write tag"); } return new PluginResult(Status.ERROR); } class NfcRunnable implements Runnable { private Activity activity = null; private PendingIntent pendingIntent = null; private IntentFilter[] intentFilters = null; private String[][] techLists = null; public NfcRunnable(Activity activity, PendingIntent pendingIntent, IntentFilter[] intentFilters, String[][] techLists) { this.techLists = techLists; this.activity = activity; this.pendingIntent = pendingIntent; this.intentFilters = intentFilters; } public void run() { Log.d(TAG, "starting NFC!"); NfcAdapter.getDefaultAdapter(activity).enableForegroundDispatch( activity, pendingIntent, intentFilters, techLists); } } class NfcPausable implements Runnable { private Activity activity; public NfcPausable(Activity activity) { this.activity = activity; } public void run() { Log.d(TAG, "Pausing NFC"); NfcAdapter.getDefaultAdapter(activity).disableForegroundDispatch(activity); NfcAdapter.getDefaultAdapter(activity).disableForegroundNdefPush(activity); } } public static void saveIntent(Intent intent) { queuedIntents.push(intent); } @Override public void onPause(boolean multitasking) { super.onPause(multitasking); this.ctx.runOnUiThread(new NfcPausable(ctx)); } @Override public void onResume(boolean multitasking) { super.onResume(multitasking); this.ctx.runOnUiThread(new NfcRunnable(ctx, this.getPendingIntent(), this.getIntentFilters().toArray(new IntentFilter[this.getIntentFilters().size()]), this.techLists.toArray(new String[0][0]))); Intent resumedIntent = ctx.getIntent(); if(NfcAdapter.ACTION_NDEF_DISCOVERED.equalsIgnoreCase(resumedIntent.getAction())) { parseMessage(resumedIntent); ctx.setIntent(new Intent()); } } @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); parseMessage(intent); Log.d(TAG, "new intent"); } }
package com.diguage.books.thinking.io; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; public class BufferToText { private static final int BSIZE = 1024; public static void main(String[] args) throws IOException { String fileName = Resource.BASE_PATH + "ioBuffer.txt"; FileChannel fc = new FileOutputStream(fileName).getChannel(); fc.write(ByteBuffer.wrap("Some Text".getBytes())); fc.close(); fc = new FileInputStream(fileName).getChannel(); ByteBuffer buffer = ByteBuffer.allocate(BSIZE); fc.read(buffer); buffer.flip(); System.out.println(buffer.asCharBuffer()); // Don't work buffer.rewind(); String encoding = System.getProperty("file.encoding"); System.out.println("Decoded using " + encoding + " : " + Charset.forName(encoding).decode(buffer)); fc.close(); fc = new FileOutputStream(fileName).getChannel(); fc.write(ByteBuffer.wrap("Hello, D".getBytes("UTF-16BE"))); fc.position(fc.size() - 2); fc.write(ByteBuffer.wrap("Hello, D".getBytes("UTF-16BE"))); fc.close(); fc = new FileInputStream(fileName).getChannel(); buffer.clear(); fc.read(buffer); buffer.flip(); System.out.println(buffer.asCharBuffer()); fc.close(); fc = new FileOutputStream(fileName).getChannel(); buffer = ByteBuffer.allocate(24); buffer.asCharBuffer().put("Some text"); fc.write(buffer); fc.close(); fc = new FileInputStream(fileName).getChannel(); buffer.clear(); fc.read(buffer); buffer.flip(); System.out.println(buffer.asCharBuffer()); fc.close(); } }
import java.io.*; import java.util.Scanner; /* Examples using the Scanner class * - by default uses whitespace as the delimiter */ public class JavaScanner { public static void main(String [] args) throws IOException { simpleRead(); simpleReadWithDelimiter(); simpleReadInts(); simpleReadLines(); } public static void simpleRead() throws IOException { Scanner s = null; try { //s = new Scanner(new File("one-number-per-line.txt")); s = new Scanner(new File("lorem-ipsum.txt")); while (s.hasNext()) { System.out.println(s.next()); } } finally { if (s != null) s.close(); } } public static void simpleReadWithDelimiter() throws IOException { Scanner s = null; try { s = new Scanner(new File("numbers.csv")); s.useDelimiter(","); while (s.hasNext()) { System.out.println(s.next()); } } finally { if (s != null) s.close(); } } public static void simpleReadInts() throws IOException { Scanner s = null; try { s = new Scanner(new File("example.txt")); while (s.hasNext()) { if (s.hasNextInt()) System.out.println(s.nextInt()); else s.next(); } } finally { if (s != null) s.close(); } } public static void simpleReadLines() throws IOException { Scanner s = null; try { s = new Scanner(new File("example.txt")); while (s.hasNextLine()) { System.out.println(s.nextLine()); } } finally { if (s != null) s.close(); } } }
package org.intermine.web.logic; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; import java.util.Properties; import junit.framework.TestCase; import org.intermine.metadata.Model; import org.intermine.pathquery.Path; import org.intermine.pathquery.PathException; import org.intermine.pathquery.PathQuery; import org.intermine.web.logic.config.WebConfig; import org.intermine.web.logic.session.SessionMethods; import org.intermine.web.struts.MockServletContext; import org.xml.sax.SAXException; public class WebUtilTest extends TestCase { MockServletContext context = new MockServletContext(); WebConfig config; Model model; public WebUtilTest(final String arg) throws FileNotFoundException, IOException, SAXException, ClassNotFoundException { super(arg); final Properties p = new Properties(); p.setProperty("web.config.classname.mappings", "CLASS_NAME_MAPPINGS"); p.setProperty("web.config.fieldname.mappings", "FIELD_NAME_MAPPINGS"); SessionMethods.setWebProperties(context, p); final InputStream is = getClass().getClassLoader().getResourceAsStream( "WebConfigTest.xml"); final InputStream classesIS = getClass().getClassLoader() .getResourceAsStream("testClassMappings.properties"); final InputStream fieldsIS = getClass().getClassLoader() .getResourceAsStream("testFieldMappings.properties"); context.addInputStream("/WEB-INF/webconfig-model.xml", is); context.addInputStream("/WEB-INF/CLASS_NAME_MAPPINGS", classesIS); context.addInputStream("/WEB-INF/FIELD_NAME_MAPPINGS", fieldsIS); model = Model.getInstanceByName("testmodel"); config = WebConfig.parse(context, model); } public void testFormatPath() throws PathException { Path p = new Path(model, "Employee.name"); String expected = "Angestellter > Name"; // Check class name labels assertEquals(expected, WebUtil.formatPath(p, config)); p = new Path(model, "Contractor.oldComs.vatNumber"); // Check reference and attribute labels expected = "Contractor > Companies they used to work for > VAT Number"; assertEquals(expected, WebUtil.formatPath(p, config)); p = new Path(model, "Contractor.personalAddress.address"); // Check default munging expected = "Contractor > Personal Address > Address"; assertEquals(expected, WebUtil.formatPath(p, config)); // Check path making expected = "Contractor > Companies they used to work for > VAT Number"; assertEquals(expected, WebUtil.formatPath( "Contractor.oldComs.vatNumber", model, config)); // Check path making, complete labelling expected = "Firma > Abteilungen > Angestellter"; assertEquals(expected, WebUtil.formatPath( "Company.departments.employees", model, config)); // Check composite attribute labelling p = new Path(model, "Employee.department.name"); expected = "Angestellter > Abteilung"; assertEquals(expected, WebUtil.formatPath(p, config)); // Check composite attribute labelling, from a reference. p = new Path(model, "Manager.department.employees.department.name"); expected = "Manager > Department > Angestellter > Abteilung"; assertEquals(expected, WebUtil.formatPath(p, config)); } public void testFormatField() throws PathException { Path p = new Path(model, "Employee.name"); String expected = "Name"; assertEquals(expected, WebUtil.formatField(p, config)); p = new Path(model, "Contractor.oldComs.vatNumber"); expected = "VAT Number"; assertEquals(expected, WebUtil.formatField(p, config)); p = new Path(model, "Contractor.personalAddress"); expected = "Personal Address"; assertEquals(expected, WebUtil.formatField(p, config)); } public void testFormatPathDescription() { final PathQuery pq = new PathQuery(model); pq.setDescription("Employee.department.company", "COMPANY"); pq.setDescription("Employee.department", "DEPARTMENT"); pq.setDescription("Employee", "EMPLOYEE"); assertEquals("EMPLOYEE", WebUtil.formatPathDescription("Employee", pq, config)); assertEquals("EMPLOYEE > Years Alive", WebUtil.formatPathDescription("Employee.age", pq, config)); assertEquals("EMPLOYEE > Address > Address", WebUtil.formatPathDescription("Employee.address.address", pq, config)); assertEquals("EMPLOYEE > Full Time", WebUtil.formatPathDescription("Employee.fullTime", pq, config)); assertEquals("DEPARTMENT", WebUtil.formatPathDescription( "Employee.department", pq, config)); } public void testCompositePathDescriptions() { final PathQuery pq = new PathQuery(model); pq.setDescription("Employee.department.company", "COMPANY"); pq.setDescription("Employee.department", "DEPARTMENT"); pq.setDescription("Employee.address", "RESIDENCE"); pq.setDescription("Employee", "EMPLOYEE"); assertEquals("RESIDENCE > Address", WebUtil.formatPathDescription( "Employee.address.address", pq, config)); // Obeys existing composite rules for attributes. assertEquals("DEPARTMENT", WebUtil.formatPathDescription( "Employee.department.name", pq, config)); assertEquals("DEPARTMENT > Manager > Name", WebUtil.formatPathDescription( "Employee.department.manager.name", pq, config)); assertEquals("COMPANY", WebUtil.formatPathDescription( "Employee.department.company", pq, config)); assertEquals("COMPANY > Abteilungen > Manager > Years Alive", WebUtil.formatPathDescription( "Employee.department.company.departments.manager.age", pq, config)); // Paths without any configuration are handled as per formatPath assertEquals("Contractor > Companies they used to work for > VAT Number", WebUtil.formatPathDescription("Contractor.oldComs.vatNumber", pq, config)); } /** * Check that formatted pathquery views take both the pathdescriptions and the webconfig into account. */ public void testFormatPathQueryView() { final PathQuery pq = new PathQuery(model); pq.setDescription("Employee.department.company", "COMPANY"); pq.setDescription("Employee.department", "DEPARTMENT"); pq.setDescription("Employee", "EMPLOYEE"); pq.addViews("Employee.name", "Employee.fullTime", "Employee.department.name", "Employee.department.company.contractors.oldComs.vatNumber"); final List<String> expected = Arrays.asList("EMPLOYEE > Name", "EMPLOYEE > Full Time", "DEPARTMENT", "COMPANY > Contractors > Companies they used to work for > VAT Number"); assertEquals(expected, WebUtil.formatPathQueryView(pq, config)); } }
package com.jayantkrish.jklol.cvsm.ccg; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.jayantkrish.jklol.ccg.SyntacticCategory; import com.jayantkrish.jklol.ccg.lambda.ApplicationExpression; import com.jayantkrish.jklol.ccg.lambda.ConstantExpression; import com.jayantkrish.jklol.ccg.lambda.Expression; import com.jayantkrish.jklol.ccg.lambda.LambdaExpression; import com.jayantkrish.jklol.cvsm.ccg.ConvertCncToCvsm.Span; import com.jayantkrish.jklol.util.Pair; public class CcgLfReader { private final List<CategoryPattern> patterns; private static final Set<String> twoArgumentFunctions = Sets.newHashSet("fa", "ba", "rp", "lp", "bc", "fc", "gbx", "bx", "conj", "funny", "ltc", "rtc"); private static final Set<String> oneArgumentFunctions = Sets.newHashSet("lex", "tr"); public CcgLfReader(List<CategoryPattern> patterns) { this.patterns = ImmutableList.copyOf(patterns); } public static CcgLfReader parseFrom(Iterable<String> patternStrings) { List<CategoryPattern> patterns = Lists.newArrayList(); for (String line : patternStrings) { patterns.add(SemTypePattern.parseFrom(line)); } return new CcgLfReader(patterns); } /** * Finds the lowest parse tree node in {@code ccgExpression} that * spans {@code spanStart} (inclusive) to {@code spanEnd} * (exclusive). The parse tree node must have an atomic type. * * @param ccgExpression * @param spanStart * @param spanEnd * @return */ public Expression findSpanningExpression(Expression ccgExpression, int spanStart, int spanEnd) { List<Expression> spanningExpression = Lists.newArrayList(); spanningExpression.add(null); findSpanningExpressionHelper(ccgExpression, spanStart, spanEnd, spanningExpression); return spanningExpression.get(0); } private static Pair<Integer, Integer> findSpanningExpressionHelper(Expression ccgExpression, int spanStart, int spanEnd, List<Expression> spanningExpression) { Preconditions.checkState(ccgExpression instanceof ApplicationExpression, "Illegal expression type: " + ccgExpression); ApplicationExpression app = (ApplicationExpression) ccgExpression; Pair<Integer, Integer> currentSpan = null; String name = ((ConstantExpression) app.getFunction()).getName(); List<Expression> arguments = app.getArguments(); int lastArg = arguments.size() - 1; if (name.equals("lf")) { int wordInd = Integer.parseInt(((ConstantExpression) arguments.get(1)).getName()) - 1; currentSpan = Pair.of(wordInd, wordInd + 1); } else if (twoArgumentFunctions.contains(name)) { Pair<Integer, Integer> leftSpan = findSpanningExpressionHelper(arguments.get(lastArg - 1), spanStart, spanEnd, spanningExpression); Pair<Integer, Integer> rightSpan = findSpanningExpressionHelper(arguments.get(lastArg), spanStart, spanEnd, spanningExpression); currentSpan = Pair.of(leftSpan.getLeft(), rightSpan.getRight()); } else if (oneArgumentFunctions.contains(name)) { currentSpan = findSpanningExpressionHelper(arguments.get(lastArg), spanStart, spanEnd, spanningExpression); } else { throw new IllegalArgumentException("Unknown function type: " + name); } SyntacticCategory syntax = getSyntacticCategory(ccgExpression); if (currentSpan.getLeft() <= spanStart && currentSpan.getRight() >= spanEnd && spanningExpression.get(0) == null && syntax.isAtomic()) { spanningExpression.set(0, ccgExpression); } return currentSpan; } public Pair<Integer, Integer> getExpressionSpan(Expression ccgExpression) { List<Expression> spanningExpression = Lists.newArrayList(); spanningExpression.add(null); return findSpanningExpressionHelper(ccgExpression, -1, -1, spanningExpression); } public Expression pruneModifiers(Expression ccgExpression, List<Span> mentionSpans) { ApplicationExpression app = (ApplicationExpression) ccgExpression; String name = ((ConstantExpression) app.getFunction()).getName(); List<Expression> arguments = app.getArguments(); int lastArg = arguments.size() - 1; if (name.equals("lf")) { return ccgExpression; } else if (oneArgumentFunctions.contains(name)) { List<Expression> newArguments = Lists.newArrayList(arguments); newArguments.set(lastArg, pruneModifiers(arguments.get(lastArg), mentionSpans)); return new ApplicationExpression(app.getFunction(), newArguments); } else if (name.equals("fa") || name.equals("ba")) { Expression left = arguments.get(lastArg - 1); Expression right = arguments.get(lastArg); SyntacticCategory syntax = null; Expression toSimplify = null; Pair<Integer, Integer> expressionSpan = null; if (name.equals("fa")) { syntax = getSyntacticCategory(left); expressionSpan = getExpressionSpan(left); toSimplify = right; } else { syntax = getSyntacticCategory(right); expressionSpan = getExpressionSpan(right); toSimplify = left; } if (!syntax.isAtomic() && (syntax.getArgument().isUnifiableWith(syntax.getReturn()) || syntax.isUnifiableWith(SyntacticCategory.parseFrom("NP[1]/N")))) { boolean noMentionInSpan = true; for (Span mentionSpan : mentionSpans) { if (!(mentionSpan.getEnd() <= expressionSpan.getLeft() || mentionSpan.getStart() >= expressionSpan.getRight())) { noMentionInSpan = false; } } if (noMentionInSpan) { return pruneModifiers(toSimplify, mentionSpans); } } } else if (name.equals("lp")) { return pruneModifiers(arguments.get(lastArg), mentionSpans); } else if (name.equals("rp")) { return pruneModifiers(arguments.get(lastArg - 1), mentionSpans); } if (twoArgumentFunctions.contains(name)) { Expression left = arguments.get(lastArg - 1); Expression right = arguments.get(lastArg); List<Expression> newArguments = Lists.newArrayList(arguments); newArguments.set(lastArg - 1, pruneModifiers(left, mentionSpans)); newArguments.set(lastArg, pruneModifiers(right, mentionSpans)); return new ApplicationExpression(app.getFunction(), newArguments); } else { throw new IllegalArgumentException("Unknown function type: " + name); } } public List<String> getWordsInCcgParse(Expression ccgParse, List<Expression> wordExpressions) { List<String> words = Lists.newArrayList(); getWordsInCcgParseHelper(ccgParse, wordExpressions, words); return words; } public void getWordsInCcgParseHelper(Expression ccgExpression, List<Expression> wordExpressions, List<String> words) { ApplicationExpression app = (ApplicationExpression) ccgExpression; String name = ((ConstantExpression) app.getFunction()).getName(); List<Expression> arguments = app.getArguments(); int lastArg = arguments.size() - 1; if (name.equals("lf")) { int wordInd = Integer.parseInt(((ConstantExpression) arguments.get(1)).getName()) - 1; ApplicationExpression wordExpression = (ApplicationExpression) wordExpressions.get(wordInd); words.add(((ConstantExpression) wordExpression.getArguments().get(2)).getName().replaceAll("^\"(.*)\"", "$1")); } else if (oneArgumentFunctions.contains(name)) { getWordsInCcgParseHelper(arguments.get(lastArg), wordExpressions, words); } else if (twoArgumentFunctions.contains(name)) { getWordsInCcgParseHelper(arguments.get(lastArg - 1), wordExpressions, words); getWordsInCcgParseHelper(arguments.get(lastArg), wordExpressions, words); } } private static SyntacticCategory getSyntacticCategory(Expression ccgExpression) { Preconditions.checkState(ccgExpression instanceof ApplicationExpression, "Illegal expression type: " + ccgExpression); ApplicationExpression app = (ApplicationExpression) ccgExpression; String name = ((ConstantExpression) app.getFunction()).getName(); List<Expression> arguments = app.getArguments(); int lastArg = arguments.size() - 1; String syntaxString = null; if (name.equals("lf")) { syntaxString = ((ConstantExpression) arguments.get(lastArg)).getName(); } else if (twoArgumentFunctions.contains(name)) { syntaxString = ((ConstantExpression) arguments.get(lastArg - 2)).getName(); } else if (oneArgumentFunctions.contains(name)) { syntaxString = ((ConstantExpression) arguments.get(lastArg - 1)).getName(); } else { throw new IllegalArgumentException("Unknown function type: " + name); } syntaxString = syntaxString.replaceAll("^\"(.*)\"$", "$1"); return SyntacticCategory.parseFrom(syntaxString); } public List<Expression> findAtomicSubexpressions(Expression ccgExpression) { List<Expression> subexpressions = Lists.newArrayList(); findAtomicSubexpressionsHelper(ccgExpression, subexpressions); return subexpressions; } private void findAtomicSubexpressionsHelper(Expression ccgExpression, List<Expression> accumulator) { SyntacticCategory syntax = getSyntacticCategory(ccgExpression); if (syntax.isAtomic()) { accumulator.add(ccgExpression); } ApplicationExpression app = (ApplicationExpression) ccgExpression; String name = ((ConstantExpression) app.getFunction()).getName(); List<Expression> arguments = app.getArguments(); int lastArg = arguments.size() - 1; if (name.equals("lf")) { // Base case: do nothing. } else if (twoArgumentFunctions.contains(name)) { findAtomicSubexpressionsHelper(arguments.get(lastArg - 1), accumulator); findAtomicSubexpressionsHelper(arguments.get(lastArg), accumulator); } else if (oneArgumentFunctions.contains(name)) { findAtomicSubexpressionsHelper(arguments.get(lastArg), accumulator); } else { throw new IllegalArgumentException("Unknown function type: " + name); } } public Expression parse(Expression ccgExpression, List<Expression> words) { int numWords = words.size(); List<Expression> wordExpressions = Lists.newArrayList(Collections.<Expression> nCopies(numWords, null)); for (Expression expression : words) { ApplicationExpression app = (ApplicationExpression) expression; String functionName = ((ConstantExpression) app.getFunction()).getName(); Preconditions.checkArgument(functionName.equals("w")); int wordNum = Integer.parseInt(((ConstantExpression) app.getArguments().get(1)).getName()); String word = ((ConstantExpression) app.getArguments().get(2)).getName().toLowerCase().replaceAll("\"", ""); SyntacticCategory wordSyntax = SyntacticCategory.parseFrom(((ConstantExpression) app.getArguments().get(7)).getName().replaceAll("\"", "")); wordExpressions.set(wordNum - 1, getExpressionForWord(word, wordSyntax)); } return recursivelyTransformCcgParse(ccgExpression, wordExpressions, words); } private Expression getExpressionForWord(String word, SyntacticCategory syntax) { for (CategoryPattern pattern : patterns) { if (pattern.matches(Arrays.<String> asList(word), syntax)) { return pattern.getLogicalForm(Arrays.<String> asList(word), syntax); } } return null; } private Expression recursivelyTransformCcgParse(Expression ccgExpression, List<Expression> wordExpressions, List<Expression> words) { Preconditions.checkState(ccgExpression instanceof ApplicationExpression, "Illegal expression type: " + ccgExpression); ApplicationExpression app = (ApplicationExpression) ccgExpression; String name = ((ConstantExpression) app.getFunction()).getName(); List<Expression> arguments = app.getArguments(); if (name.equals("lf")) { int wordInd = Integer.parseInt(((ConstantExpression) arguments.get(1)).getName()); Expression wordExpression = wordExpressions.get(wordInd - 1); if (wordExpression == null) { throw new LogicalFormConversionError("No lexicon template for word: " + words.get(wordInd - 1)); } return wordExpression; } else if (name.equals("lex")) { // Lex is a type-changing rule. Only rules which maintain the // same semantic type specification are supported. SyntacticCategory origCategory = SyntacticCategory.parseFrom(((ConstantExpression) arguments.get(0)).getName().replaceAll("\"", "")); SyntacticCategory newCategory = SyntacticCategory.parseFrom(((ConstantExpression) arguments.get(1)).getName().replaceAll("\"", "")); if (!SemTypePattern.hasSameSemanticType(origCategory, newCategory)) { throw new LogicalFormConversionError("Used type changing rule: " + origCategory + " to " + newCategory); } return recursivelyTransformCcgParse(arguments.get(2), wordExpressions, words); } else if (name.equals("fa")) { Expression left = recursivelyTransformCcgParse(arguments.get(1), wordExpressions, words); Expression right = recursivelyTransformCcgParse(arguments.get(2), wordExpressions, words); return new ApplicationExpression(left, Arrays.asList(right)); } else if (name.equals("ba")) { Expression left = recursivelyTransformCcgParse(arguments.get(1), wordExpressions, words); Expression right = recursivelyTransformCcgParse(arguments.get(2), wordExpressions, words); return new ApplicationExpression(right, Arrays.asList(left)); } else if (name.equals("rp")) { Preconditions.checkState(arguments.size() == 3, "rp arguments: " + arguments); return recursivelyTransformCcgParse(arguments.get(1), wordExpressions, words); } else if (name.equals("lp")) { Preconditions.checkState(arguments.size() == 3); return recursivelyTransformCcgParse(arguments.get(2), wordExpressions, words); } else if (name.equals("bx")) { Expression left = recursivelyTransformCcgParse(arguments.get(1), wordExpressions, words); Expression right = recursivelyTransformCcgParse(arguments.get(2), wordExpressions, words); SyntacticCategory function = getSyntacticCategory(arguments.get(2)); SyntacticCategory argument = getSyntacticCategory(arguments.get(1)); int depth = getCompositionDepth(function, argument); return buildCompositionExpression(left, right, depth); } throw new LogicalFormConversionError("Unknown function type: " + name); } private Expression buildCompositionExpression(Expression functionLogicalForm, Expression argumentLogicalForm, int numArgsToKeep) { // Composition. LambdaExpression functionAsLambda = (LambdaExpression) (functionLogicalForm.simplify()); LambdaExpression argumentAsLambda = (LambdaExpression) (argumentLogicalForm.simplify()); System.out.println("argument: " + argumentAsLambda); List<ConstantExpression> remainingArgs = argumentAsLambda.getArguments().subList(0, numArgsToKeep); List<ConstantExpression> remainingArgsRenamed = ConstantExpression.generateUniqueVariables(remainingArgs.size()); List<Expression> functionArguments = Lists.newArrayList(); functionArguments.add(new ApplicationExpression(argumentAsLambda, remainingArgsRenamed)); List<ConstantExpression> newFunctionArgs = ConstantExpression.generateUniqueVariables(functionAsLambda.getArguments().size() - 1); functionArguments.addAll(newFunctionArgs); Expression result = new ApplicationExpression(functionAsLambda, functionArguments); if (newFunctionArgs.size() > 0) { result = new LambdaExpression(newFunctionArgs, result); } result = new LambdaExpression(remainingArgsRenamed, result); return result; } private int getCompositionDepth(SyntacticCategory function, SyntacticCategory argument) { SyntacticCategory functionArgument = function.getArgument(); // Depth is the number of arguments of argument which must be passed in before // function can be applied to argument. int depth = 0; while (!functionArgument.isUnifiableWith(argument)) { depth++; argument = argument.getReturn(); } return depth; } public class LogicalFormConversionError extends RuntimeException { private static final long serialVersionUID = 1L; public LogicalFormConversionError(String cause) { super(cause); } } }
package advent; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Thirteen { public static List<Rule> rules; public static int bestScore = 0; public static List<String> bestOrder; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = null; Set<String> names = new HashSet<String>(); rules = new ArrayList<Rule>(); while((line = br.readLine()) != null) { if (line.isEmpty()) { break; } String[] split = line.split(" "); String startName = split[0]; String endName = split[10].substring(0, split[10].length()-1); String loseGain = split[2]; String amount = split[3]; int ruleAmount = Integer.parseInt(amount); if (loseGain.equals("lose")) { ruleAmount = -ruleAmount; } names.add(startName); names.add(endName); rules.add(new Rule(startName, endName, ruleAmount)); } List<String> namesLst = new ArrayList<String>(); namesLst.addAll(names); createOrders(namesLst, new ArrayList<String>()); // part 2 namesLst.add("self"); bestScore = 0; bestOrder = null; createOrders(namesLst, new ArrayList<String>()); } public static void createOrders(List<String> names, List<String> currOrder) { if (currOrder.size() == names.size()) { //System.out.println(currOrder); int score = 0; for(int i=1; i<currOrder.size(); i++) { score += adjust(currOrder.get(i), currOrder.get(i-1)); } score += adjust(currOrder.get(0), currOrder.get(currOrder.size()-1)); //System.out.println("DEBUG: " + score + " " + currOrder); if (score > bestScore) { bestScore = score; bestOrder = new ArrayList<String>(); bestOrder.addAll(currOrder); System.out.println("New Best: " + bestScore + " " + bestOrder); } } else { for(String name : names) { if (!currOrder.contains(name)) { currOrder.add(name); createOrders(names, currOrder); currOrder.remove(name); } } } } public static int adjust(String namea, String nameb) { int total = 0; for(Rule rule : rules) { if ( (rule.name1.equals(namea) && rule.name2.equals(nameb)) || (rule.name1.equals(nameb) && rule.name2.equals(namea))) { //System.out.println("DEBUG: applied " + rule); total += rule.amount; } } return total; } public static class Rule { final String name1; final String name2; final int amount; public Rule(String name1, String name2, int amount) { this.name1 = name1; this.name2 = name2; this.amount = amount; } @Override public String toString() { return "Rule [name1=" + name1 + ", name2=" + name2 + ", amount=" + amount + "]"; } } }
package com.jcwhatever.nucleus.utils; import com.jcwhatever.nucleus.regions.data.SyncLocation; import com.jcwhatever.nucleus.utils.extended.MaterialExt; import com.jcwhatever.nucleus.utils.text.TextUtils; import com.jcwhatever.nucleus.utils.validate.IValidator; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Entity; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.util.Vector; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Collection; import javax.annotation.Nullable; /** * Location utilities. */ public final class LocationUtils { private LocationUtils () {} // array to help convert yaw to block face private static final BlockFace[] YAW_FACES = new BlockFace[] { BlockFace.SOUTH, BlockFace.SOUTH_SOUTH_WEST, BlockFace.SOUTH_WEST, BlockFace.WEST_SOUTH_WEST, BlockFace.WEST, BlockFace.WEST_NORTH_WEST, BlockFace.NORTH_WEST, BlockFace.NORTH_NORTH_WEST, BlockFace.NORTH, BlockFace.NORTH_NORTH_EAST, BlockFace.NORTH_EAST, BlockFace.EAST_NORTH_EAST, BlockFace.EAST, BlockFace.EAST_SOUTH_EAST, BlockFace.SOUTH_EAST, BlockFace.SOUTH_SOUTH_EAST, BlockFace.SOUTH }; private static final Location CENTERED_LOCATION = new Location(null, 0, 0, 0); /** * Copy the values from a source {@link org.bukkit.Location} to a new * {@link org.bukkit.Location}. * * @param source The source location. * * @return The new location. */ public static Location copy(Location source) { PreCon.notNull(source); Location destination = new Location(null, 0, 0, 0); return copy(source, destination); } /** * Copy the values from a source {@link org.bukkit.Location} to a destination * {@link org.bukkit.Location}. * * @param source The source location. * @param destination The destination location. * * @return The destination location. */ public static Location copy(Location source, Location destination) { PreCon.notNull(source); PreCon.notNull(destination); destination.setWorld(source.getWorld()); destination.setX(source.getX()); destination.setY(source.getY()); destination.setZ(source.getZ()); destination.setYaw(source.getYaw()); destination.setPitch(source.getPitch()); return destination; } /** * Copy the values from a source {@link org.bukkit.Location} to a destination * {@link org.bukkit.util.Vector}. * * @param source The source location. * @param destination The destination vector. * * @return The destination vector. */ public static Vector copy(Location source, Vector destination) { PreCon.notNull(source); PreCon.notNull(destination); destination.setX(source.getX()); destination.setY(source.getY()); destination.setZ(source.getZ()); return destination; } /** * Copy the values from a source {@link org.bukkit.util.Vector} to a new * {@link org.bukkit.util.Vector}. * * @param source The source location. * * @return The new vector. */ public static Vector copy(Vector source) { PreCon.notNull(source); Vector vector = new Vector(0, 0, 0); return copy(source, vector); } /** * Copy the values from a source {@link org.bukkit.util.Vector} to a destination * {@link org.bukkit.util.Vector}. * * @param source The source location. * @param destination The destination vector. * * @return The destination vector. */ public static Vector copy(Vector source, Vector destination) { PreCon.notNull(source); PreCon.notNull(destination); destination.setX(source.getX()); destination.setY(source.getY()); destination.setZ(source.getZ()); return destination; } /** * Get a location centered on the X and Z axis of the block * represented by the provided location. * * @param location The location. * * @return A new {@link org.bukkit.Location} containing the result. */ public static Location getCenteredLocation(Location location) { PreCon.notNull(location); return getCenteredLocation(location, new Location(null, 0, 0, 0)); } /** * Get a location centered on the X and Z axis of the block * represented by the provided location. * * @param location The location. * @param output The location to put the results into. * * @return The output location. */ public static Location getCenteredLocation(Location location, Location output) { PreCon.notNull(location); output.setWorld(location.getWorld()); output.setX(location.getBlockX() + 0.5); output.setY(location.getY()); output.setZ(location.getBlockZ() + 0.5); output.setYaw(location.getYaw()); output.setPitch(location.getPitch()); return output; } /** * Teleport an entity to the location centered on the * X and Z axis. * * @param entity The entity to teleport. * @param location The teleport location. */ public static boolean teleportCentered(Entity entity, Location location) { PreCon.notNull(entity); PreCon.notNull(location); Location adjusted = getCenteredLocation(location, Bukkit.isPrimaryThread() ? CENTERED_LOCATION : new Location(null, 0, 0, 0)); return entity.teleport(adjusted, PlayerTeleportEvent.TeleportCause.PLUGIN); } /** * Convert a location into a block location (remove numbers to the right of the floating point value) * and remove the yaw and pitch values. * * @param location The location to convert. * * @return A new {@link org.bukkit.Location} containing the result. */ public static Location getBlockLocation(Location location) { PreCon.notNull(location); return getBlockLocation(location, new Location(null, 0, 0, 0)); } /** * Convert a location into a block location (remove numbers to the right of the floating point value) * and remove the yaw and pitch values. * * @param location The location to convert. * @param output The location to put the results into. * * @return The output location. */ public static Location getBlockLocation(Location location, Location output) { PreCon.notNull(location); output.setWorld(location.getWorld()); output.setX(location.getBlockX()); output.setY(location.getBlockY()); output.setZ(location.getBlockZ()); return output; } /** * Add values to the locations coordinates without changing the coordinates * in the provided location. * * @param location The location. * @param x The value to add to the X coordinates. * @param y The value to add to the Y coordinates. * @param z The value to add to the Z coordinates. * * @return A new {@link org.bukkit.Location} instance. */ public static Location add(Location location, double x, double y, double z) { return location.clone().add(x, y, z); } /** * Add values to the locations coordinates without changing the coordinates * in the provided location. * * @param location The location. * @param output The location to put the results into. * @param x The value to add to the X coordinates. * @param y The value to add to the Y coordinates. * @param z The value to add to the Z coordinates. * * @return The output location. */ public static Location add(Location location, Location output, double x, double y, double z) { return copy(location, output).add(x, y, z); } /** * Add noise to a location. Changes to another point within the specified * radius of the original location randomly. * * @param location The location. * @param radiusX The max radius on the X axis. * @param radiusY The max radius on the Y axis. * @param radiusZ The max radius on the Z axis. */ public static Location addNoise(Location location, double radiusX, double radiusY, double radiusZ) { PreCon.notNull(location); return addNoise(location, location.clone(), radiusX, radiusY, radiusZ); } /** * Add noise to a location. Changes to another point within the specified * radius of the original location randomly. * * @param location The location. * @param output The location to put the results into. * @param radiusX The max radius on the X axis. * @param radiusY The max radius on the Y axis. * @param radiusZ The max radius on the Z axis. * * @return The output location. */ public static Location addNoise(Location location, Location output, double radiusX, double radiusY, double radiusZ) { PreCon.notNull(location); PreCon.notNull(output); PreCon.positiveNumber(radiusX); PreCon.positiveNumber(radiusY); PreCon.positiveNumber(radiusZ); double noiseX = 0; double noiseY = 0; double noiseZ = 0; if (radiusX > 0) { noiseX = Rand.getDouble(radiusX * 2) - radiusX; } if (radiusY > 0) { noiseY = Rand.getDouble(radiusY * 2) - radiusY; } if (radiusZ > 0) { noiseZ = Rand.getDouble(radiusZ * 2) - radiusZ; } return output.add(noiseX, noiseY, noiseZ); } /** * Determine if 2 locations can be considered the same using the specified * precision. The precision is used as: location1 is about the same as location2 +/- precision. * * @param location1 The first location to compare. * @param location2 The second location to compare. * @param precision The precision. */ public static boolean isLocationMatch(Location location1, Location location2, double precision) { PreCon.notNull(location1); PreCon.notNull(location2); double xDelta = Math.abs(location1.getX() - location2.getX()); double zDelta = Math.abs(location1.getZ() - location2.getZ()); double yDelta = Math.abs(location1.getY() - location2.getY()); return xDelta <= precision && zDelta <= precision && yDelta <= precision; } /** * Parse a location from a formatted string. * <p> * Format of string : x,y,z * </p> * * @param world The world the location is for. * @param coordinates The string coordinates. * * @return A new {@link org.bukkit.Location} or null if a location could not be parsed. */ @Nullable public static Location parseSimpleLocation(World world, String coordinates) { return parseSimpleLocation(new Location(null, 0, 0, 0), world, coordinates); } /** * Parse a location from a formatted string. * <p> * Format of string : x,y,z * </p> * * @param output The location place the results in. * @param world The world the location is for. * @param coordinates The string coordinates. * * @return The output location or null if a location could not be parsed. */ @Nullable public static Location parseSimpleLocation(Location output, World world, String coordinates) { PreCon.notNull(output); PreCon.notNull(world); PreCon.notNull(coordinates); String[] parts = TextUtils.PATTERN_COMMA.split(coordinates); if (parts.length != 3) return null; double x = TextUtils.parseDouble(parts[0], Double.MAX_VALUE); double y = TextUtils.parseDouble(parts[1], Double.MAX_VALUE); double z = TextUtils.parseDouble(parts[2], Double.MAX_VALUE); if (x != Double.MAX_VALUE && y != Double.MAX_VALUE && z != Double.MAX_VALUE) { output.setWorld(world); output.setX(x); output.setY(y); output.setZ(z); return output; } return null; } /** * Parse a location from a formatted string. * <p> * Format of string: x,y,z,yawF,pitchF,worldName * </p> * * @param coordinates The string coordinates. * * @return A new {@link SyncLocation} or null if the string could not be parsed. */ @Nullable public static SyncLocation parseLocation(String coordinates) { PreCon.notNull(coordinates); SyncLocation location = new SyncLocation((World)null, 0, 0, 0); return parseLocation(coordinates, location); } /** * Parse a location from a formatted string. * <p> * Format of string: x,y,z,yawF,pitchF,worldName * </p> * * @param coordinates The string coordinates. * * @return A new {@link SyncLocation} or null if the string could not be parsed. */ @Nullable public static SyncLocation parseLocation(String coordinates, SyncLocation output) { PreCon.notNull(coordinates); String[] parts = TextUtils.PATTERN_COMMA.split(coordinates); if (parts.length != 6) return null; double x = TextUtils.parseDouble(parts[0], Double.MAX_VALUE); if (x == Double.MAX_VALUE) return null; double y = TextUtils.parseDouble(parts[1], Double.MAX_VALUE); if (y == Double.MAX_VALUE) return null; double z = TextUtils.parseDouble(parts[2], Double.MAX_VALUE); if (z == Double.MAX_VALUE) return null; float yaw = TextUtils.parseFloat(parts[3], Float.MAX_VALUE); if (yaw == Float.MAX_VALUE) return null; float pitch = TextUtils.parseFloat(parts[4], Float.MAX_VALUE); if (pitch == Float.MAX_VALUE) return null; output.setWorld(parts[5]); output.setX(x); output.setY(y); output.setZ(z); output.setYaw(yaw); output.setPitch(pitch); return output; } /** * Parse the world name from a from a location formatted string. * <p> * Format of string: x,y,z,yawF,pitchF,worldName * </p> * <p>Useful when the world the location is for is not loaded and * the name is needed.</p> * * @param coordinates The string coordinates. * * @return Null if the string could not be parsed. */ @Nullable public static String parseLocationWorldName(String coordinates) { PreCon.notNull(coordinates); String[] parts = TextUtils.PATTERN_COMMA.split(coordinates); if (parts.length != 6) return null; return parts[5]; } /** * Convert a location to a parsable string. * * @param location The location to convert. */ public static String locationToString(Location location) { PreCon.notNull(location); return String.valueOf(location.getX()) + ',' + location.getY() + ',' + location.getZ() + ',' + location.getYaw() + ',' + location.getPitch() + ',' + location.getWorld().getName(); } /** * Convert a location to a parsable string. * * @param location The location to convert. * @param floatingPointPlaces The number of places in the floating point values. */ public static String locationToString(Location location, int floatingPointPlaces) { PreCon.notNull(location); PreCon.positiveNumber(floatingPointPlaces); BigDecimal x = new BigDecimal(floatingPointPlaces == 0 ? location.getBlockX() : location.getX()) .setScale(floatingPointPlaces, RoundingMode.HALF_UP); BigDecimal y = new BigDecimal(floatingPointPlaces == 0 ? location.getBlockY() : location.getY()) .setScale(floatingPointPlaces, RoundingMode.HALF_UP); BigDecimal z = new BigDecimal(floatingPointPlaces == 0 ? location.getBlockZ() : location.getZ()) .setScale(floatingPointPlaces, RoundingMode.HALF_UP); BigDecimal yaw = new BigDecimal(location.getYaw()) .setScale(floatingPointPlaces, RoundingMode.HALF_UP); BigDecimal pitch = new BigDecimal(location.getPitch()) .setScale(floatingPointPlaces, RoundingMode.HALF_UP); return String.valueOf(x) + ',' + y + ',' + z + ',' + yaw + ',' + pitch + ',' + location.getWorld().getName(); } /** * Convert a locations yaw angle to a {@link org.bukkit.block.BlockFace}. * * @param location The location to convert. */ public static BlockFace getBlockFacingYaw(Location location) { PreCon.notNull(location); return getBlockFacingYaw(location.getYaw()); } /** * Convert a yaw angle to a {@link org.bukkit.block.BlockFace}. * * @param yaw The yaw angle to convert. */ public static BlockFace getBlockFacingYaw(float yaw) { yaw = yaw + 11.25f; yaw = yaw < 0 ? 360 - (Math.abs(yaw) % 360) : yaw % 360; int i = (int)(yaw / 22.5); return YAW_FACES[i]; } /** * Find a surface block (solid block that can be walked on) location below the provided * search location. * <p> * If the search location is a surface block, the search location * is returned. * </p> * * @param searchLoc The search location. * * @return A new {@link org.bukkit.Location} or null if the search reaches below 0 on the Y axis. */ @Nullable public static Location findSurfaceBelow(Location searchLoc) { return findSurfaceBelow(searchLoc, new Location(null, 0, 0, 0)); } /** * Find a surface block (solid block that can be walked on) location below the provided * search location. * <p> * If the search location is a surface block, the search location * is returned. * </p> * * @param searchLoc The search location. * * @return The output location or null if the search reaches below 0 on the Y axis. */ @Nullable public static Location findSurfaceBelow(Location searchLoc, Location output) { PreCon.notNull(searchLoc); getBlockLocation(searchLoc, output); if (!MaterialExt.isTransparent(output.getBlock().getType())) return searchLoc; output.add(0, -1, 0); Block current = searchLoc.getBlock(); while (!MaterialExt.isSurface(current.getType())) { output.add(0, -1, 0); current = output.getBlock(); if (output.getY() < 0) { return null; } } return output; } /** * Get the location closest to the specified player. * * @param sourceLocation The location source to search from. * @param locations The location candidates. */ @Nullable public static Location getClosestLocation(Location sourceLocation, Collection<Location> locations) { return getClosestLocation(sourceLocation, locations, null); } /** * Get the location closest to the specified player. * * @param sourceLocation The location source to search from. * @param locations The location candidates. * @param validator The validator used to determine if a location is a candidate. */ @Nullable public static Location getClosestLocation(Location sourceLocation, Collection<Location> locations, @Nullable IValidator<Location> validator) { PreCon.notNull(sourceLocation); PreCon.notNull(locations); Location closest = null; double closestDist = Double.MAX_VALUE; for (Location loc : locations) { if (validator != null && !validator.isValid(loc)) continue; double dist; if ((dist = sourceLocation.distanceSquared(loc)) < closestDist) { closest = loc; closestDist = dist; } } return closest; } /** * Rotate a location around an axis location. * * @param axis The axis location. * @param location The location to move. * @param rotationX The rotation around the X axis in degrees. * @param rotationY The rotation around the Y axis in degrees. * @param rotationZ The rotation around the Z axis in degrees. */ public static Location rotate(Location axis, Location location, double rotationX, double rotationY, double rotationZ) { PreCon.notNull(axis); PreCon.notNull(location); return rotate(axis, location, new Location(null, 0, 0, 0), rotationX, rotationY, rotationZ); } /** * Rotate a location around an axis location. * * @param axis The axis location. * @param location The location to move. * @param output The location to put results into. * @param rotationX The rotation around the X axis in degrees. * @param rotationY The rotation around the Y axis in degrees. * @param rotationZ The rotation around the Z axis in degrees. * * @return The output location. */ public static Location rotate(Location axis, Location location, Location output, double rotationX, double rotationY, double rotationZ) { PreCon.notNull(axis); PreCon.notNull(location); double x = location.getX(); double y = location.getY(); double z = location.getZ(); double centerX = axis.getX(); double centerY = axis.getY(); double centerZ = axis.getZ(); double translateX = x; double translateY = y; double translateZ = z; double yaw = location.getYaw(); // rotate on X axis if (Double.compare(rotationX, 0.0D) != 0) { double rotX = Math.toRadians(rotationX); translateY = rotateX(centerY, centerZ, y, z, rotX); translateZ = rotateZ(centerY, centerZ, y, z, rotX); } // rotate on Y axis if (Double.compare(rotationY, 0.0D) != 0) { double rotY = Math.toRadians(rotationY); translateX = rotateX(centerX, centerZ, x, z, rotY); translateZ = rotateZ(centerX, centerZ, x, z, rotY); yaw += rotationY; } // rotate on Z axis if (Double.compare(rotationZ, 0.0D) != 0) { double rotZ = Math.toRadians(rotationZ); translateX = rotateX(centerX, centerY, x, y, rotZ); translateY = rotateZ(centerX, centerY, x, y, rotZ); } output.setWorld(location.getWorld()); output.setX(translateX); output.setY(translateY); output.setZ(translateZ); output.setYaw((float) yaw); output.setPitch(location.getPitch()); return output; } private static double rotateX(double centerA, double centerB, double a, double b, double rotation) { return centerA + Math.cos(rotation) * (a - centerA) - Math.sin(rotation) * (b - centerB); } private static double rotateZ(double centerA, double centerB, double a, double b, double rotation) { return centerB + Math.sin(rotation) * (a - centerA) + Math.cos(rotation) * (b - centerB); } }
package trampoline; import java.util.ArrayList; public class Node { private Node lhs; private Node rhs; private Integer value; public Node(Integer value) { this.value = value; } private class SideAwareNode extends Node { final public String side; public SideAwareNode(Integer value, String side) { super(value); this.side = side; } public boolean isLhs () { return this.side.equals("lhs"); } public boolean isRhs () { return !isLhs(); } } public void printTree () { SideAwareNode next = innerPrintTree(); ArrayList<Integer> printList = new ArrayList<Integer>(); while (next != null) { if (next.isLhs()) { if (next.getValue() != null) { System.out.println(next.getValue()); } } else { if (next.getValue() != null) { System.out.println(next.getValue()); } } next = next.innerPrintTree(); /* while (next.isLhs()) { if (next.getValue() != null) { printList.add(next.getValue()); } next = next.innerPrintTree(); if (next == null) { break; } } if (next == null) { break; } while (next.isRhs()) { if (next.getValue() != null) { printList.add(next.getValue()); } next = next.innerPrintTree(); if (next == null) { break; } } */ } for (Integer val: printList) { System.out.println(val); } } public SideAwareNode innerPrintTree () { if (this.lhs != null) { return new SideAwareNode(lhs.getValue(), "lhs"); } if (this.rhs != null) { return new SideAwareNode(rhs.getValue(), "rhs"); } return null; } /** * find a node, returns null if not found * @param targetValue * @return */ public Node find (Integer targetValue) { Node found = this; Node lastFound = found; while (found != null) { found = found.innerFind(targetValue); lastFound = found; if (lastFound == null) { break; } if (lastFound.getValue().equals(targetValue)) { break; } } return lastFound; } /** * returns Node with given value, if not found returns null * @param targetValue * @return */ private Node innerFind (Integer targetValue) { if (this.getValue().equals(targetValue)) { return this; } if (this.getValue() > targetValue) { if (rhs == null) { return null; } return rhs; } else { if (lhs == null) { return null; } return lhs; } } /** * adds a node to the tree * * @param child */ public void add (Node child) { Node tempParent; Node lastParent = this; Node parent = innerAdd(child); while (parent != lastParent) { tempParent = parent; parent = tempParent.innerAdd(child); lastParent = tempParent; } } private Node innerAdd (Node n) { if (n.getValue() > getValue()) { if (lhs == null) { lhs = n; } else { return lhs; } } else { if (rhs == null) { rhs = n; } else { return rhs; } } return this; } public Integer getValue() { return value; } public void setValue(Integer value) { this.value = value; } }
package com.jme.scene.state; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import java.util.Collection; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import com.jme.math.Matrix3f; import com.jme.math.Matrix4f; import com.jme.math.Quaternion; import com.jme.math.Vector2f; import com.jme.math.Vector3f; import com.jme.renderer.ColorRGBA; import com.jme.scene.Geometry; import com.jme.util.export.InputCapsule; import com.jme.util.export.JMEExporter; import com.jme.util.export.JMEImporter; import com.jme.util.export.OutputCapsule; import com.jme.util.geom.BufferUtils; import com.jme.util.shader.ShaderVariable; import com.jme.util.shader.uniformtypes.ShaderVariableFloat; import com.jme.util.shader.uniformtypes.ShaderVariableFloat2; import com.jme.util.shader.uniformtypes.ShaderVariableFloat3; import com.jme.util.shader.uniformtypes.ShaderVariableFloat4; import com.jme.util.shader.uniformtypes.ShaderVariableInt; import com.jme.util.shader.uniformtypes.ShaderVariableInt2; import com.jme.util.shader.uniformtypes.ShaderVariableInt3; import com.jme.util.shader.uniformtypes.ShaderVariableInt4; import com.jme.util.shader.uniformtypes.ShaderVariableMatrix2; import com.jme.util.shader.uniformtypes.ShaderVariableMatrix3; import com.jme.util.shader.uniformtypes.ShaderVariableMatrix4; import com.jme.util.shader.uniformtypes.ShaderVariablePointerByte; import com.jme.util.shader.uniformtypes.ShaderVariablePointerFloat; import com.jme.util.shader.uniformtypes.ShaderVariablePointerInt; import com.jme.util.shader.uniformtypes.ShaderVariablePointerShort; /** * Implementation of the GL_ARB_shader_objects extension. * * @author Thomas Hourdel * @author Rikard Herlitz (MrCoder) */ public abstract class GLSLShaderObjectsState extends RenderState { private static final Logger logger = Logger .getLogger(GLSLShaderObjectsState.class.getName()); /** Storage for shader uniform values */ protected HashMap<String, ShaderVariable> shaderUniforms = new HashMap<String, ShaderVariable>(); /** Storage for shader attribute values */ protected HashMap<String, ShaderVariable> shaderAttributes = new HashMap<String, ShaderVariable>(); /** Optional logic for setting shadervariables based on the current geom */ protected GLSLShaderDataLogic shaderDataLogic; /** The Geometry this shader currently operates on during rendering */ protected Geometry geom; protected static boolean glslSupported = false; protected static boolean glslSupportedDetected = false; protected boolean needSendShader = false; protected String vertShader, fragShader; /** * Gets the currently loaded vertex shader. * @return */ public String getVertexShader() { return vertShader; } /** * Gets the currently loaded fragment shader. * @return */ public String getFragmentShader() { return fragShader; } /** * Gets all shader uniforms variables. * @return */ public Collection<ShaderVariable> getShaderUniforms() { return shaderUniforms.values(); } /** * Retrieves a shader uniform by name. * @param uniformName * @return */ public ShaderVariable getUniformByName(String uniformName) { return shaderUniforms.get(uniformName); } /** * Gets all shader attribute variables. * @return */ public Collection<ShaderVariable> getShaderAttributes() { return shaderAttributes.values(); } /** * Retrieves a shader attribute by name. * @param uniformName * @return */ public ShaderVariable getAttributeByName(String attributeName) { return shaderAttributes.get(attributeName); } /** * * @param geom */ public void setGeometry(Geometry geom) { this.geom = geom; } /** * Logic to handle setting geom-specific data to a shader before rendering * @param shaderDataLogic */ public void setShaderDataLogic(GLSLShaderDataLogic shaderDataLogic) { this.shaderDataLogic = shaderDataLogic; } /** * <code>isSupported</code> determines if the ARB_shader_objects extension * is supported by current graphics configuration. This will only be valid * if a renderer has been created. * * @return if ARB shader objects are supported */ public static boolean isSupported() { return glslSupported; } /** * Overide setting of glsl support. * * @param use */ public static void overrideSupport(boolean use) { glslSupported = use; } /** * Reset glsl support to driver-detected setting. */ public static void resetSupport() { glslSupported = glslSupportedDetected; } /** * Set an uniform value for this shader object. * * @param name uniform variable to change * @param value the new value */ public void setUniform(String name, boolean value) { ShaderVariableInt shaderUniform = getShaderUniform(name, ShaderVariableInt.class); shaderUniform.value1 = value ? 1 : 0; setNeedsRefresh(true); } /** * Set an uniform value for this shader object. * * @param name uniform variable to change * @param value the new value */ public void setUniform(String name, int value) { ShaderVariableInt shaderUniform = getShaderUniform(name, ShaderVariableInt.class); shaderUniform.value1 = value; setNeedsRefresh(true); } /** * Set an uniform value for this shader object. * * @param name uniform variable to change * @param value the new value */ public void setUniform(String name, float value) { ShaderVariableFloat shaderUniform = getShaderUniform(name, ShaderVariableFloat.class); shaderUniform.value1 = value; setNeedsRefresh(true); } /** * Set an uniform value for this shader object. * * @param name uniform variable to change * @param value1 the new value * @param value2 the new value */ public void setUniform(String name, boolean value1, boolean value2) { ShaderVariableInt2 shaderUniform = getShaderUniform(name, ShaderVariableInt2.class); shaderUniform.value1 = value1 ? 1 : 0; shaderUniform.value2 = value2 ? 1 : 0; setNeedsRefresh(true); } /** * Set an uniform value for this shader object. * * @param name uniform variable to change * @param value1 the new value * @param value2 the new value */ public void setUniform(String name, int value1, int value2) { ShaderVariableInt2 shaderUniform = getShaderUniform(name, ShaderVariableInt2.class); shaderUniform.value1 = value1; shaderUniform.value2 = value2; setNeedsRefresh(true); } /** * Set an uniform value for this shader object. * * @param name uniform variable to change * @param value1 the new value * @param value2 the new value */ public void setUniform(String name, float value1, float value2) { ShaderVariableFloat2 shaderUniform = getShaderUniform(name, ShaderVariableFloat2.class); shaderUniform.value1 = value1; shaderUniform.value2 = value2; setNeedsRefresh(true); } /** * Set an uniform value for this shader object. * * @param name uniform variable to change * @param value1 the new value * @param value2 the new value * @param value3 the new value */ public void setUniform(String name, boolean value1, boolean value2, boolean value3) { ShaderVariableInt3 shaderUniform = getShaderUniform(name, ShaderVariableInt3.class); shaderUniform.value1 = value1 ? 1 : 0; shaderUniform.value2 = value2 ? 1 : 0; shaderUniform.value3 = value3 ? 1 : 0; setNeedsRefresh(true); } /** * Set an uniform value for this shader object. * * @param name uniform variable to change * @param value1 the new value * @param value2 the new value * @param value3 the new value */ public void setUniform(String name, int value1, int value2, int value3) { ShaderVariableInt3 shaderUniform = getShaderUniform(name, ShaderVariableInt3.class); shaderUniform.value1 = value1; shaderUniform.value2 = value2; shaderUniform.value3 = value3; setNeedsRefresh(true); } /** * Set an uniform value for this shader object. * * @param name uniform variable to change * @param value1 the new value * @param value2 the new value * @param value3 the new value */ public void setUniform(String name, float value1, float value2, float value3) { ShaderVariableFloat3 shaderUniform = getShaderUniform(name, ShaderVariableFloat3.class); shaderUniform.value1 = value1; shaderUniform.value2 = value2; shaderUniform.value3 = value3; setNeedsRefresh(true); } /** * Set an uniform value for this shader object. * * @param name uniform variable to change * @param value1 the new value * @param value2 the new value * @param value3 the new value * @param value4 the new value */ public void setUniform(String name, boolean value1, boolean value2, boolean value3, boolean value4) { ShaderVariableInt4 shaderUniform = getShaderUniform(name, ShaderVariableInt4.class); shaderUniform.value1 = value1 ? 1 : 0; shaderUniform.value2 = value2 ? 1 : 0; shaderUniform.value3 = value3 ? 1 : 0; shaderUniform.value4 = value4 ? 1 : 0; setNeedsRefresh(true); } /** * Set an uniform value for this shader object. * * @param name uniform variable to change * @param value1 the new value * @param value2 the new value * @param value3 the new value * @param value4 the new value */ public void setUniform(String name, int value1, int value2, int value3, int value4) { ShaderVariableInt4 shaderUniform = getShaderUniform(name, ShaderVariableInt4.class); shaderUniform.value1 = value1; shaderUniform.value2 = value2; shaderUniform.value3 = value3; shaderUniform.value4 = value4; setNeedsRefresh(true); } /** * Set an uniform value for this shader object. * * @param name uniform variable to change * @param value1 the new value * @param value2 the new value * @param value3 the new value * @param value4 the new value */ public void setUniform(String name, float value1, float value2, float value3, float value4) { ShaderVariableFloat4 shaderUniform = getShaderUniform(name, ShaderVariableFloat4.class); shaderUniform.value1 = value1; shaderUniform.value2 = value2; shaderUniform.value3 = value3; shaderUniform.value4 = value4; setNeedsRefresh(true); } /** * Set an uniform value for this shader object. * * @param name uniform variable to change * @param value the new value */ public void setUniform(String name, Vector2f value) { ShaderVariableFloat2 shaderUniform = getShaderUniform(name, ShaderVariableFloat2.class); shaderUniform.value1 = value.x; shaderUniform.value2 = value.y; setNeedsRefresh(true); } /** * Set an uniform value for this shader object. * * @param name uniform variable to change * @param value the new value */ public void setUniform(String name, Vector3f value) { ShaderVariableFloat3 shaderUniform = getShaderUniform(name, ShaderVariableFloat3.class); shaderUniform.value1 = value.x; shaderUniform.value2 = value.y; shaderUniform.value3 = value.z; setNeedsRefresh(true); } /** * Set an uniform value for this shader object. * * @param name uniform variable to change * @param value the new value */ public void setUniform(String name, ColorRGBA value) { ShaderVariableFloat4 shaderUniform = getShaderUniform(name, ShaderVariableFloat4.class); shaderUniform.value1 = value.r; shaderUniform.value2 = value.g; shaderUniform.value3 = value.b; shaderUniform.value4 = value.a; setNeedsRefresh(true); } /** * Set an uniform value for this shader object. * * @param name uniform variable to change * @param value the new value */ public void setUniform(String name, Quaternion value) { ShaderVariableFloat4 shaderUniform = getShaderUniform(name, ShaderVariableFloat4.class); shaderUniform.value1 = value.x; shaderUniform.value2 = value.y; shaderUniform.value3 = value.z; shaderUniform.value4 = value.w; setNeedsRefresh(true); } /** * Set an uniform value for this shader object. * * @param name uniform variable to change * @param value the new value (a float buffer of size 4) * @param rowMajor true if is this in row major order */ public void setUniform(String name, float value[], boolean rowMajor) { if (value.length != 4) return; ShaderVariableMatrix2 shaderUniform = getShaderUniform(name, ShaderVariableMatrix2.class); shaderUniform.matrixBuffer.clear(); shaderUniform.matrixBuffer.put(value[0]); shaderUniform.matrixBuffer.put(value[1]); shaderUniform.matrixBuffer.put(value[2]); shaderUniform.matrixBuffer.put(value[3]); shaderUniform.rowMajor = rowMajor; setNeedsRefresh(true); } /** * Set an uniform value for this shader object. * * @param name uniform variable to change * @param value the new value * @param rowMajor true if is this in row major order */ public void setUniform(String name, Matrix3f value, boolean rowMajor) { ShaderVariableMatrix3 shaderUniform = getShaderUniform(name, ShaderVariableMatrix3.class); // prepare buffer for writing shaderUniform.matrixBuffer.rewind(); value.fillFloatBuffer(shaderUniform.matrixBuffer); // prepare buffer for reading shaderUniform.matrixBuffer.rewind(); shaderUniform.rowMajor = rowMajor; setNeedsRefresh(true); } /** * Set an uniform value for this shader object. * * @param name uniform variable to change * @param value the new value * @param rowMajor true if is this in row major order */ public void setUniform(String name, Matrix4f value, boolean rowMajor) { ShaderVariableMatrix4 shaderUniform = getShaderUniform(name, ShaderVariableMatrix4.class); // prepare buffer for writing shaderUniform.matrixBuffer.rewind(); value.fillFloatBuffer(shaderUniform.matrixBuffer); // prepare buffer for reading shaderUniform.matrixBuffer.rewind(); shaderUniform.rowMajor = rowMajor; setNeedsRefresh(true); } /** <code>clearUniforms</code> clears all uniform values from this state. */ public void clearUniforms() { shaderUniforms.clear(); } /** * Set an attribute pointer value for this shader object. * * @param name attribute variable to change * @param size Specifies the number of values for each element of the * generic vertex attribute array. Must be 1, 2, 3, or 4. * @param normalized Specifies whether fixed-point data values should be * normalized or converted directly as fixed-point values when they are * accessed. * @param stride Specifies the byte offset between consecutive attribute * values. If stride is 0 (the initial value), the attribute values are * understood to be tightly packed in the array. * @param data The actual data to use as attribute pointer */ public void setAttributePointer(String name, int size, boolean normalized, int stride, FloatBuffer data) { ShaderVariablePointerFloat shaderUniform = getShaderAttribute(name, ShaderVariablePointerFloat.class); shaderUniform.size = size; shaderUniform.normalized = normalized; shaderUniform.stride = stride; shaderUniform.data = data; setNeedsRefresh(true); } /** * Set an attribute pointer value for this shader object. * * @param name attribute variable to change * @param size Specifies the number of values for each element of the * generic vertex attribute array. Must be 1, 2, 3, or 4. * @param normalized Specifies whether fixed-point data values should be * normalized or converted directly as fixed-point values when they are * accessed. * @param unsigned Specifies wheter the data is signed or unsigned * @param stride Specifies the byte offset between consecutive attribute * values. If stride is 0 (the initial value), the attribute values are * understood to be tightly packed in the array. * @param data The actual data to use as attribute pointer */ public void setAttributePointer(String name, int size, boolean normalized, boolean unsigned, int stride, ByteBuffer data) { ShaderVariablePointerByte shaderUniform = getShaderAttribute(name, ShaderVariablePointerByte.class); shaderUniform.size = size; shaderUniform.normalized = normalized; shaderUniform.unsigned = unsigned; shaderUniform.stride = stride; shaderUniform.data = data; setNeedsRefresh(true); } /** * Set an attribute pointer value for this shader object. * * @param name attribute variable to change * @param size Specifies the number of values for each element of the * generic vertex attribute array. Must be 1, 2, 3, or 4. * @param normalized Specifies whether fixed-point data values should be * normalized or converted directly as fixed-point values when they are * accessed. * @param unsigned Specifies wheter the data is signed or unsigned * @param stride Specifies the byte offset between consecutive attribute * values. If stride is 0 (the initial value), the attribute values are * understood to be tightly packed in the array. * @param data The actual data to use as attribute pointer */ public void setAttributePointer(String name, int size, boolean normalized, boolean unsigned, int stride, IntBuffer data) { ShaderVariablePointerInt shaderUniform = getShaderAttribute(name, ShaderVariablePointerInt.class); shaderUniform.size = size; shaderUniform.normalized = normalized; shaderUniform.unsigned = unsigned; shaderUniform.stride = stride; shaderUniform.data = data; setNeedsRefresh(true); } /** * Set an attribute pointer value for this shader object. * * @param name attribute variable to change * @param size Specifies the number of values for each element of the * generic vertex attribute array. Must be 1, 2, 3, or 4. * @param normalized Specifies whether fixed-point data values should be * normalized or converted directly as fixed-point values when they are * accessed. * @param unsigned Specifies wheter the data is signed or unsigned * @param stride Specifies the byte offset between consecutive attribute * values. If stride is 0 (the initial value), the attribute values are * understood to be tightly packed in the array. * @param data The actual data to use as attribute pointer */ public void setAttributePointer(String name, int size, boolean normalized, boolean unsigned, int stride, ShortBuffer data) { ShaderVariablePointerShort shaderUniform = getShaderAttribute(name, ShaderVariablePointerShort.class); shaderUniform.size = size; shaderUniform.normalized = normalized; shaderUniform.unsigned = unsigned; shaderUniform.stride = stride; shaderUniform.data = data; setNeedsRefresh(true); } /** * <code>clearAttributes</code> clears all attribute values from this * state. */ public void clearAttributes() { shaderAttributes.clear(); } /** * @return RS_SHADER_OBJECTS * @see com.jme.scene.state.RenderState#getType() * @deprecated As of 2.0, use {@link RenderState#getStateType()} instead. */ public int getType() { return RS_GLSL_SHADER_OBJECTS; } /** * <code>getStateType</code> returns the type {@link RenderState.StateType#GLSLShaderObjects} * * @return {@link RenderState.StateType#GLSLShaderObjects} * @see com.jme.scene.state.RenderState#getStateType() */ public StateType getStateType() { return StateType.GLSLShaderObjects; } /** * Creates or retrieves a uniform shadervariable. * * @param name Name of the uniform shadervariable to retrieve or create * @param classz Class type of the shadervariable * @return */ private <T extends ShaderVariable> T getShaderUniform(String name, Class<T> classz) { T shaderVariable = getShaderVariable(name, classz, shaderUniforms); checkUniformSizeLimits(); return shaderVariable; } /** * Creates or retrieves a attribute shadervariable. * * @param name Name of the attribute shadervariable to retrieve or create * @param classz Class type of the shadervariable * @return */ private <T extends ShaderVariable> T getShaderAttribute(String name, Class<T> classz) { T shaderVariable = getShaderVariable(name, classz, shaderAttributes); checkAttributeSizeLimits(); return shaderVariable; } /** * @param name Name of the shadervariable to retrieve or create * @param classz Class type of the shadervariable * @param shaderVariableList List retrieve shadervariable from * @return */ @SuppressWarnings("unchecked") private <T extends ShaderVariable> T getShaderVariable(String name, Class<T> classz, HashMap<String, ShaderVariable> shaderVariableList) { ShaderVariable temp = shaderVariableList.get(name); if (temp != null) { temp.needsRefresh = true; return (T) temp; } try { T shaderUniform = classz.newInstance(); shaderUniform.name = name; shaderVariableList.put(name, shaderUniform); return shaderUniform; } catch (InstantiationException e) { logger.logp(Level.SEVERE, this.getClass().toString(), "getShaderVariable(name, classz, shaderVariableList)", "Exception", e); } catch (IllegalAccessException e) { logger.logp(Level.SEVERE, this.getClass().toString(), "getShaderVariable(name, classz, shaderVariableList)", "Exception", e); } return null; } /** * Check if we are keeping the size limits in terms of uniform locations * on the card. */ public void checkUniformSizeLimits() { // Implement in provider } /** * Check if we are keeping the size limits in terms of attribute locations * on the card. */ public void checkAttributeSizeLimits() { // Implement in provider } /** * Loads shader from URL * * @param url * @return */ private String load(URL url) { BufferedReader r = null; try { r = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); while (r.ready()) { buf.append(r.readLine()).append('\n'); } r.close(); return buf.toString(); } catch (IOException e) { logger.severe("Could not load shader program: " + e); logger.logp(Level.SEVERE, getClass().getName(), "load(URL)", "Exception", e); return null; } } /** * <code>load</code> loads the shader object from the specified file. The * program must be in ASCII format. The implementation must * convert the String into data compatible with the graphics library. * * @param vert text file containing the vertex shader object * @param frag text file containing the fragment shader object */ public void load(URL vert, URL frag){ vertShader = vert != null ? load(vert) : null; fragShader = frag != null ? load(frag) : null; needSendShader = true; } /** * <code>load</code> loads the shader object from the specified file. The * program must be in ASCII format. The implementation must * convert the String into data compatible with the graphics library. * * @param vert The input stream from which the vertex shader can be read * @param frag The input stream from which the fragment shader can be read */ public void load(InputStream vert, InputStream frag) { ByteBuffer vertexByteBuffer = vert != null ? load(vert) : null; ByteBuffer fragmentByteBuffer = frag != null ? load(frag) : null; sendToGL(vertexByteBuffer, fragmentByteBuffer); } /** * <code>load</code> loads the shader object from the specified string. The * program must be in ASCII format. We delegate the loading to each * implementation because we do not know in what format the underlying API * wants the data. * * @param vert string containing the vertex shader object * @param frag string containing the fragment shader object */ public void load(String vert, String frag){ vertShader = vert; fragShader = frag; needSendShader = true; } public void write(JMEExporter e) throws IOException { super.write(e); OutputCapsule capsule = e.getCapsule(this); capsule.writeStringSavableMap(shaderUniforms, "shaderUniforms", null); capsule.writeStringSavableMap(shaderAttributes, "shaderAttributes", null); } @SuppressWarnings ("unchecked") public void read(JMEImporter e) throws IOException { super.read(e); InputCapsule capsule = e.getCapsule(this); shaderUniforms = (HashMap<String, ShaderVariable>) capsule.readStringSavableMap("shaderUniforms", new HashMap<String, ShaderVariable>()); shaderAttributes = (HashMap<String, ShaderVariable>) capsule.readStringSavableMap("shaderAttributes", new HashMap<String, ShaderVariable>()); } public Class<? extends GLSLShaderObjectsState> getClassTag() { return GLSLShaderObjectsState.class; } /** * Loads the shader object. Use null for an empty vertex or empty fragment * shader. * * @param vertexByteBuffer vertex shader * @param fragmentByteBuffer fragment shader * @see com.jme.scene.state.GLSLShaderObjectsState#load(java.net.URL, *java.net.URL) */ protected abstract void sendToGL(ByteBuffer vertexByteBuffer, ByteBuffer fragmentByteBuffer); /** * Load an URL and grab content into a ByteBuffer. * * @param in The input stream to read * @return the loaded url */ protected ByteBuffer load(InputStream in) { DataInputStream dataStream = null; try { BufferedInputStream bufferedInputStream = new BufferedInputStream(in); dataStream = new DataInputStream(bufferedInputStream); byte shaderCode[] = new byte[bufferedInputStream.available()]; dataStream.readFully(shaderCode); bufferedInputStream.close(); dataStream.close(); ByteBuffer shaderByteBuffer = BufferUtils.createByteBuffer(shaderCode.length); shaderByteBuffer.put(shaderCode); shaderByteBuffer.rewind(); return shaderByteBuffer; } catch (Exception e) { logger.severe("Could not load shader object: " + e); logger.logp(Level.SEVERE, getClass().getName(), "load(URL)", "Exception", e); return null; } finally { // Ensure that the stream is closed, even if there is an exception. if (dataStream != null) { try { dataStream.close(); } catch (IOException closeFailure) { logger.log(Level.WARNING, "Failed to close the shader object", closeFailure); } } } } }
package com.mcmacker4.voidpixel.editor.util; import org.lwjgl.input.Mouse; import org.newdawn.slick.Color; import org.newdawn.slick.TrueTypeFont; import com.mcmacker4.voidpixel.editor.main.Game; public class Button { private String text; private int x, y; private final Color normalColor = Color.cyan; private final Color overColor = Color.blue; private TrueTypeFont font = FontLoader.MAIN_FONT; private int ID; private boolean center; public Button(String text, int x, int y, int ID) { this.text = text; this.x = x; this.y = y; this.ID = ID; } public void draw() { Color c; if(isMouseOver()) c = overColor; else c = normalColor; font.drawString(x, y, text, c); } public boolean isMouseOver() { float mx = Mouse.getX(); float my = Game.getHeight() - Mouse.getY(); return mx > x && mx < x + font.getWidth(text) && my > y && my < y + font.getHeight(); } public void centerHorizontal() { center = true; x = Game.getWidth() / 2 - font.getWidth(text) / 2; } public void setText(String s) { text = s; if(center) centerHorizontal(); } public String getText() { return text; } public int getID() { return ID; } public void setID(int ID) { this.ID = ID; } }
package com.mjoell.twitchchatcounter; public class TwitchConnect { private static IRCBot bot = new IRCBot(); public static void main() throws Exception { if(TwitchChatCounter.verbose) { bot.setVerbose(true); } else { bot.setVerbose(false); } bot.connect("irc.twitch.tv", 6667, TwitchChatCounter.password); System.out.println("Connected to irc.twitch.tv"); for(int i = 0; i < TwitchChatCounter.channels.length; i++) { bot.joinChannel("#" + TwitchChatCounter.channels[i]); System.out.println("Joined channel " + TwitchChatCounter.channels[i] + ". Waiting 4 seconds before joining next."); Thread.sleep(4000); } bot.joinChannel("#uberfacts"); System.out.println("Joined channel uberfacts. Waiting 4 seconds before joining next."); System.out.println("Joined all channels. Assuming you're not in verbose, this is the last you'll hear from us for a while."); } }
package blasd.apex.core.memory; import java.lang.instrument.Instrumentation; import java.lang.reflect.Array; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Objects; import java.util.concurrent.atomic.LongAdder; import java.util.function.IntPredicate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.ReflectionUtils; import com.google.common.base.CharMatcher; import com.google.common.base.Optional; import com.google.common.hash.BloomFilter; import com.google.common.hash.Funnels; import blasd.apex.core.agent.InstrumentationAgent; /** * This class helps reference-sharing * * @author Benoit Lacelle * */ public class ApexMemoryHelper implements IApexMemoryConstants { protected static final Logger LOGGER = LoggerFactory.getLogger(ApexMemoryHelper.class); protected ApexMemoryHelper() { // hidden } public static final int JVM_MEMORY_CHUNK = 8; public static final int JVM_BYTES_PER_CHAR = 2; public static final int JVM_STRING_HEADER = 45; public static long getStringMemory(CharSequence existingRef) { // Object Header int nbChars = existingRef.length(); // String are essentially char[], 8 for char long nbBits = (long) nbChars * JVM_BYTES_PER_CHAR + JVM_STRING_HEADER; return JVM_MEMORY_CHUNK * (nbBits / JVM_MEMORY_CHUNK); } /** * @deprecated renamed to deepSize */ @Deprecated public static long recursiveSize(Object object) { return deepSize(object); } /** * * @param object * the object to analyze * @return the number of bytes consumed by given objects, taking in account the references objects */ public static long deepSize(Object object) { return deepSizeWithBloomFilter(object, Integer.MAX_VALUE / 1024); } public static long recursiveSize(Object object, IntPredicate identityPredicate) { return deepSize(object, identityPredicate); } /** * * @param object * @param identityPredicate * a predicate returning true if it is the first encounter of given object. It may return false even if * an object has not been considered before, woult it be because the identity policy is not guaranteed * (e.g. we rely on a BloomFilter) or if we want to exclude some objects * @return Long.MAX_VALUE if the Instrumentation agent is not available. Else an estimation of the memory * consumption. */ public static long deepSize(Object object, IntPredicate identityPredicate) { if (object == null) { return 0L; } else { Optional<Instrumentation> instrumentation = InstrumentationAgent.getInstrumentation(); if (instrumentation.isPresent()) { LongAdder totalSize = new LongAdder(); deepSize(instrumentation.get(), identityPredicate, totalSize, object); return totalSize.sum(); } else { LOGGER.debug("Instrumentation is not available for {}", object); // We prefer to return MAX-VALUE to prevent the caller believing this object has no memory foot-print return Long.MAX_VALUE; } } } @Deprecated public static long recursiveSizeWithBloomFilter(Object object, long expectedObjectCardinality) { return deepSizeWithBloomFilter(object, expectedObjectCardinality); } public static long deepSizeWithBloomFilter(Object object, long expectedObjectCardinality) { BloomFilter<Integer> identities = BloomFilter.create(Funnels.integerFunnel(), expectedObjectCardinality); return recursiveSize(object, identities::put); } @Deprecated public static void recursiveSize(Instrumentation instrumentation, IntPredicate identities, LongAdder totalSize, Object object) { deepSize(instrumentation, identities, totalSize, object); } /** * * @param instrumentation * an {@link Instrumentation} able to provide the memory weight of given object * @param identities * an identityHashSet where to collect already handlded objects * @param totalSize * the LongAdder where to accumulate the memory * @param object * the object to analyse */ public static void deepSize(Instrumentation instrumentation, IntPredicate identities, LongAdder totalSize, Object object) { Objects.requireNonNull(instrumentation); if (object == null) { return; } else { // see FastHashCode in // -> Random value unrelated to memory address if (identities.test(System.identityHashCode(object))) { long currentSize = instrumentation.getObjectSize(object); totalSize.add(currentSize); if (object instanceof Object[]) { // For arrays, it would not work to iterate on its fields Arrays.stream((Object[]) object) .forEach(element -> recursiveSize(instrumentation, identities, totalSize, element)); } else { ReflectionUtils.doWithFields(object.getClass(), field -> recursiveSize(instrumentation, identities, totalSize, field.get(object)), field -> { if (Modifier.isStatic(field.getModifiers())) { // Do not add static fields in memory graph return false; } else if (field.getType().isPrimitive()) { // Primitive fields has already been captured by Instrumentation.getObjectSize return false; } else { // Ensure the field is accessible as we are going to read it ReflectionUtils.makeAccessible(field); return true; } }); } } } } public static long getDoubleMemory() { // Double are essentially a double in an Object long charArrayWeight = DOUBLE + OBJECT; return charArrayWeight; } public static long getObjectArrayMemory(Object[] asArray) { if (asArray == null) { return 0L; } long footprint = OBJECT; // The weight of the array footprint += OBJECT * asArray.length; return footprint; } public static long getObjectArrayMemory(Object asArray) { if (asArray == null) { return 0L; } Class<?> arrayClass = asArray.getClass(); if (!arrayClass.isArray()) { return 0L; } Class<?> elementClass = arrayClass.getComponentType(); // Object header long footprint = OBJECT; final long componentWeight; if (elementClass == int.class) { componentWeight = INT; } else if (elementClass == float.class) { componentWeight = FLOAT; } else { // Long, Double, Object componentWeight = OBJECT; } // The weight of the array footprint += componentWeight * Array.getLength(asArray); return footprint; } private static final long MASK = 0xFFFFFFFFL; private static final int SHIFT = 32; /** * It might be useful to have an long<->(int,int) packing guaranteeing both integers to be positive if the long is * positive */ public static final long positivePack(int i1, int i2) { long packed1 = (long) i1 << SHIFT; long packed2 = Integer.rotateLeft(i2, 1) & MASK; return Long.rotateRight(packed1 | packed2, 1); } public static final int positiveUnpack1(long packed) { // Move the higher bit as lower bit: if packed >= 0, we then are sure to have a 0 as first bit return (int) (Long.rotateLeft(packed, 1) >>> SHIFT); } public static final int positiveUnpack2(long packed) { // Move the higher bit as lower bit: if packed >= 0, we then are sure to have a 0 as first bit // Then, this 0 bit it put back as last bit: the integer is guaranteed to be positive return Integer.rotateRight((int) (Long.rotateLeft(packed, 1) & MASK), 1); } public static long memoryAsLong(String targetMax) { if (targetMax.isEmpty()) { throw new UnsupportedOperationException("Can not be empty"); } String digits; long multiplier; char lastChar = targetMax.charAt(targetMax.length() - 1); if (CharMatcher.javaDigit().matches(lastChar)) { multiplier = 1L; digits = targetMax; } else { if (lastChar == 'k' || lastChar == 'K') { multiplier = IApexMemoryConstants.KB; } else if (lastChar == 'm' || lastChar == 'M') { multiplier = IApexMemoryConstants.MB; } else if (lastChar == 'g' || lastChar == 'G') { multiplier = IApexMemoryConstants.GB; } else { throw new IllegalArgumentException( "Can not parse " + targetMax + ". It should end by a digit or one of 'k', 'm','g'"); } digits = targetMax.substring(0, targetMax.length() - 1).trim(); } // Something like "123,456" if (digits.length() >= 5 && digits.charAt(digits.length() - 4) == ',') { // Transform "123,456" to "123" ~ "456" digits = digits.substring(0, digits.length() - 4) + digits.substring(digits.length() - 3); } double parsedAsDouble = Double.parseDouble(digits); return (long) (parsedAsDouble * multiplier); } public static String memoryAsString(long bytes) { String string = ""; int unitsDone = 0; if (unitsDone < 2) { long gb = bytes / IApexMemoryConstants.GB; if (gb > 0) { unitsDone++; string += gb + "G"; bytes -= gb * IApexMemoryConstants.GB; } } if (unitsDone < 2) { long mb = bytes / IApexMemoryConstants.MB; if (mb > 0) { unitsDone++; string += mb + "M"; bytes -= mb * IApexMemoryConstants.MB; } } if (unitsDone < 2) { long kb = bytes / IApexMemoryConstants.KB; if (kb > 0) { unitsDone++; string += kb + "K"; bytes -= kb * IApexMemoryConstants.KB; } } if (unitsDone < 2) { if (bytes > 0) { string += bytes + "B"; } else { LOGGER.trace("No more bytes"); } } return string; } }
package com.opencms.workplace; import org.opencms.lock.CmsLock; import org.opencms.main.OpenCms; import org.opencms.security.CmsSecurityException; import org.opencms.staticexport.CmsLinkManager; import org.opencms.workplace.CmsWorkplaceAction; import com.opencms.core.CmsException; import com.opencms.core.I_CmsConstants; import com.opencms.core.I_CmsSession; import com.opencms.file.CmsFile; import com.opencms.file.CmsObject; import com.opencms.file.CmsRequestContext; import com.opencms.file.CmsResource; import com.opencms.flex.util.CmsStringSubstitution; import com.opencms.linkmanagement.CmsPageLinks; import com.opencms.template.A_CmsXmlContent; import com.opencms.template.CmsTemplateClassManager; import com.opencms.template.CmsXmlControlFile; import com.opencms.template.CmsXmlTemplate; import com.opencms.template.CmsXmlTemplateFile; import com.opencms.util.Encoder; import java.io.IOException; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Vector; import javax.servlet.http.HttpServletRequest; import org.w3c.dom.Element; public class CmsXmlTemplateEditor extends CmsWorkplaceDefault { protected void commitTemporaryFile(CmsObject cms, String originalFilename, String temporaryFilename, int tempProject, int curProject) throws CmsException { // set current project to tempfileproject cms.getRequestContext().setCurrentProject(tempProject); CmsFile tempFile = cms.readFile(temporaryFilename); Map minfos = cms.readProperties(temporaryFilename); // set current project cms.getRequestContext().setCurrentProject(curProject); CmsFile orgFile = cms.readFile(originalFilename); orgFile.setContents(tempFile.getContents()); cms.writeFile(orgFile); Iterator keys = minfos.keySet().iterator(); while(keys.hasNext()) { String keyName = (String)keys.next(); cms.writeProperty(originalFilename, keyName, (String)minfos.get(keyName)); } // don't forget to clear the cache. A_CmsXmlContent.clearFileCache(cms.getRequestContext().currentProject().getName()+":" + cms.getRequestContext().addSiteRoot(originalFilename)); } protected String createTemporaryFile(CmsObject cms, CmsResource file, int tempProject, int curProject) throws CmsException { String temporaryFilename = CmsResource.getPath(cms.readAbsolutePath(file)) + C_TEMP_PREFIX + file.getResourceName(); boolean ok = true; cms.getRequestContext().setCurrentProject(tempProject); try { cms.copyResource(cms.readAbsolutePath(file), temporaryFilename, false, true, I_CmsConstants.C_COPY_AS_NEW); // cms.chmod(temporaryFilename, 91); } catch (CmsException e) { if ((e.getType() == CmsException.C_FILE_EXISTS) || (e.getType() != CmsException.C_SQL_ERROR)) { try { // try to re-use the old temporary file cms.changeLockedInProject(tempProject, temporaryFilename); cms.lockResource(temporaryFilename, true); // cms.chmod(temporaryFilename, 91); } catch (Exception ex) { ok = false; } } else { throw e; } } String extendedTempFile = temporaryFilename; int loop = 0; while (!ok) { ok = true; extendedTempFile = temporaryFilename + loop; try { cms.copyResource(cms.readAbsolutePath(file), extendedTempFile); // cms.chmod(extendedTempFile, 91); } catch (CmsException e) { if ((e.getType() != CmsException.C_FILE_EXISTS) && (e.getType() != CmsException.C_SQL_ERROR)) { cms.getRequestContext().setCurrentProject(curProject); // This was not a file-exists-exception. // Very bad. We should not continue here since we may run // into an endless looooooooooooooooooooooooooooooooooop. throw e; } // temp file could not be created loop++; ok = false; } } cms.getRequestContext().setCurrentProject(curProject); // Oh how lucky we are! We have found a temporary file! temporaryFilename = extendedTempFile; return temporaryFilename; } /** * Gets the templates displayed in the template select box. * @param cms The CmsObject. * @param lang The langauge definitions. * @param names The names of the new rescources. * @param values The links that are connected with each resource. * @param parameters Hashtable of parameters (not used yet). * @return The vectors names and values are filled with the information found in the * workplace.ini. * @throws Throws CmsException if something goes wrong. */ public Integer getAvailableTemplates(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters) throws CmsException { Integer retValue = CmsHelperMastertemplates.getTemplates(cms, names, values, (String)parameters.get("template"), -1); if(retValue.intValue() != -1) { return retValue; } else { // no template found -> use the given one // first clean the vectors names.removeAllElements(); values.removeAllElements(); // now add the current template String name = (String)parameters.get("template"); try { // to read the title of this template name = cms.readProperty(name, C_PROPERTY_TITLE); } catch(CmsException exc) { // ignore this exception - the title for this template was not readable } names.add(name); values.add(parameters.get("template")); return new Integer(0); } } /** * Gets all views available in the workplace screen. * <P> * The given vectors <code>names</code> and <code>values</code> will * be filled with the appropriate information to be used for building * a select box. * <P> * <code>names</code> will contain language specific view descriptions * and <code>values</code> will contain the correspondig URL for each * of these views after returning from this method. * <P> * * @param cms CmsObject Object for accessing system resources. * @param lang reference to the currently valid language file * @param names Vector to be filled with the appropriate values in this method. * @param values Vector to be filled with the appropriate values in this method. * @param parameters Hashtable containing all user parameters <em>(not used here)</em>. * @return Index representing the user's current workplace view in the vectors. * @throws CmsException */ public Integer getBodys(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters) throws CmsException { I_CmsSession session = cms.getRequestContext().getSession(true); String currentBodySection = (String)parameters.get("body"); String bodyClassName = (String)parameters.get("bodyclass"); String tempBodyFilename = (String)session.getValue("te_tempbodyfile"); Object tempObj = CmsTemplateClassManager.getClassInstance(bodyClassName); CmsXmlTemplate bodyElementClassObject = (CmsXmlTemplate)tempObj; CmsXmlTemplateFile bodyTemplateFile = bodyElementClassObject.getOwnTemplateFile(cms, tempBodyFilename, C_BODY_ELEMENT, parameters, null); Vector allBodys = bodyTemplateFile.getAllSections(); int loop = 0; int currentBodySectionIndex = 0; int numBodys = allBodys.size(); for(int i = 0;i < numBodys;i++) { String bodyname = (String)allBodys.elementAt(i); String encodedBodyname = Encoder.escapeXml(bodyname); if(bodyname.equals(currentBodySection)) { currentBodySectionIndex = loop; } values.addElement(encodedBodyname); names.addElement(encodedBodyname); loop++; } return new Integer(currentBodySectionIndex); } /** * Gets the content of a defined section in a given template file and its subtemplates * with the given parameters. * * @see #getContent(CmsObject, String, String, Hashtable, String) * @param cms CmsObject Object for accessing system resources. * @param templateFile Filename of the template file. * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. */ public byte[] getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) throws CmsException { CmsRequestContext reqCont = cms.getRequestContext(); HttpServletRequest orgReq = (HttpServletRequest)reqCont.getRequest().getOriginalRequest(); I_CmsSession session = cms.getRequestContext().getSession(true); // get the temporary file projectid int tempProject = 0; try{ tempProject = Integer.parseInt(cms.getRegistry().getSystemValue("tempfileproject")); }catch(Exception e){ throw new CmsException("Can not read projectId of tempfileproject for creating temporary file for editing! "+e.toString()); } if(tempProject == 0){ throw new CmsException("Can not create temporary file for editing!"); } int curProject = cms.getRequestContext().currentProject().getId(); // Get the user's browser String browser = orgReq.getHeader("user-agent"); String hostName = orgReq.getScheme() + "://" + orgReq.getServerName() + ":" + orgReq.getServerPort(); // Get all URL parameters String content = (String)parameters.get(C_PARA_CONTENT); if(content == null){ // try to get the value from the session because we might come from errorpage content = (String)session.getValue(C_PARA_CONTENT); session.removeValue(C_PARA_CONTENT); } String body = (String)parameters.get("body"); if(body == null){ // try to get the value from the session because we might come from errorpage body = (String)session.getValue("body"); session.removeValue("body"); } String file = (String)parameters.get(C_PARA_RESOURCE); if(file == null){ // try to get the value from the session because we might come from errorpage file = (String)session.getValue(C_PARA_RESOURCE); session.removeValue(C_PARA_RESOURCE); } String editor = (String)parameters.get("editor"); if((editor == null) || "".equals(editor)){ // try to get the value from the session because we might come from errorpage editor = (String)session.getValue("editor"); if(editor != null){ parameters.put("editor", editor); } session.removeValue("editor"); } String title = (String)parameters.get(C_PARA_TITLE); if(title == null){ // try to get the value from the session because we might come from errorpage title = (String)session.getValue(C_PARA_TITLE); session.removeValue(C_PARA_TITLE); } String bodytitle = (String)parameters.get("bodytitle"); if(bodytitle == null){ // try to get the value from the session because we might come from errorpage bodytitle = (String)session.getValue("bodytitle"); session.removeValue("bodytitle"); } String layoutTemplateFilename = (String)parameters.get("template"); if(layoutTemplateFilename == null){ // try to get the value from the session because we might come from errorpage layoutTemplateFilename = (String)session.getValue("template"); session.removeValue("template"); } String layoutTemplatFilenameRelative = layoutTemplateFilename; layoutTemplateFilename = CmsLinkManager.getAbsoluteUri(layoutTemplateFilename, file); String bodyElementClassName = (String)parameters.get("bodyclass"); if(bodyElementClassName == null){ // try to get the value from the session because we might come from errorpage bodyElementClassName = (String)session.getValue("bodyclass"); session.removeValue("bodyclass"); } String bodyElementFilename = (String)parameters.get("bodyfile"); if(bodyElementFilename == null){ // try to get the value from the session because we might come from errorpage bodyElementFilename = (String)session.getValue("bodyfile"); session.removeValue("bodyfile"); } String action = (String)parameters.get(C_PARA_ACTION); String startView = (String)parameters.get("startview"); if((startView == null) || ("".equals(startView))){ // try to get the value from the session because we might come from errorpage startView = (String)session.getValue("startview"); session.removeValue("startview"); } // Get all session parameters String oldEdit = (String)session.getValue("te_oldedit"); String oldLayoutFilename = (String)session.getValue("te_oldlayout"); String oldTitle = (String)session.getValue("te_title"); String oldBody = (String)session.getValue("te_oldbody"); String oldBodytitle = (String)session.getValue("te_oldbodytitle"); String layoutTemplateClassName = (String)session.getValue("te_templateclass"); String tempPageFilename = (String)session.getValue("te_temppagefile"); String tempBodyFilename = (String)session.getValue("te_tempbodyfile"); String style = (String)session.getValue("te_stylesheet"); boolean existsContentParam = content != null; boolean existsFileParam = (file != null && (!"".equals(file))); boolean saveRequested = ((action != null) && (C_EDIT_ACTION_SAVE.equals(action) || C_EDIT_ACTION_SAVEEXIT.equals(action))); boolean exitRequested = ((action != null) && (C_EDIT_ACTION_EXIT.equals(action) || C_EDIT_ACTION_SAVEEXIT.equals(action))); boolean bodychangeRequested = ((oldBody != null) && (body != null) && (!(oldBody.equals(body)))); boolean templatechangeRequested = (oldLayoutFilename != null && layoutTemplateFilename != null && (!(oldLayoutFilename.equals(layoutTemplateFilename)))); boolean titlechangeRequested = (oldTitle != null && title != null && (!(oldTitle.equals(title)))); boolean newbodyRequested = ((action != null) && "newbody".equals(action)); boolean previewRequested = ((action != null) && "preview".equals(action)); boolean bodytitlechangeRequested = (oldBodytitle != null && bodytitle != null && (!(oldBodytitle.equals(bodytitle)))); String saveerror = ""; // Check if there is a file parameter in the request if(!existsFileParam) { throwException("No \"file\" parameter given. Don't know which file should be edited."); } // If there is no content parameter this seems to be // a new request of the page editor. // So we have to read all files and set some initial values. parameters.put("root.pagetype", cms.getResourceType(cms.readFileHeader(file).getType()).getResourceTypeName()); parameters.put("filename_for_relative_template", file); // Simple page support String templateProp = cms.readProperty(file, C_PROPERTY_TEMPLATE); boolean isSimplePage = (templateProp != null); // Check, if the selected page file is locked CmsResource pageFileResource = cms.readFileHeader(file); CmsLock lock = cms.getLock(file); if(lock.isNullLock()) { cms.lockResource(file); } if(!existsContentParam) { if (isSimplePage) { bodyElementClassName = C_XML_CONTROL_DEFAULT_CLASS; bodyElementFilename = file; layoutTemplateClassName = C_XML_CONTROL_DEFAULT_CLASS; layoutTemplateFilename = templateProp; layoutTemplatFilenameRelative = templateProp; } else { CmsXmlControlFile originalControlFile = new CmsXmlControlFile(cms, file); if(originalControlFile.isElementClassDefined(C_BODY_ELEMENT)) { bodyElementClassName = originalControlFile.getElementClass(C_BODY_ELEMENT); } if(originalControlFile.isElementTemplateDefined(C_BODY_ELEMENT)) { bodyElementFilename = originalControlFile.getElementTemplate(C_BODY_ELEMENT); bodyElementFilename = originalControlFile.validateBodyPath(cms, bodyElementFilename, cms.readFileHeader(file)); } if((bodyElementClassName == null) || (bodyElementFilename == null)) { // Either the template class or the template file // for the body element could not be determined. // BUG: Send error here } // The content file must be locked before editing //CmsResource contentFileResource = cms.readFileHeader(bodyElementFilename); lock = cms.getLock(bodyElementFilename); if(lock.isNullLock()) { cms.lockResource(bodyElementFilename); } // Now get the currently selected master template file layoutTemplateFilename = originalControlFile.getMasterTemplate(); layoutTemplatFilenameRelative = layoutTemplateFilename; layoutTemplateFilename = CmsLinkManager.getAbsoluteUri(layoutTemplateFilename, originalControlFile.getAbsoluteFilename()); layoutTemplateClassName = originalControlFile.getTemplateClass(); } int browserId; if(browser.indexOf("MSIE") > -1) { browserId = 0; }else { browserId = 1; } if(editor == null || "".equals(editor)) { if(startView == null || "".equals(startView)){ editor = C_SELECTBOX_EDITORVIEWS[C_SELECTBOX_EDITORVIEWS_DEFAULT[browserId]]; } else { editor = startView; } session.putValue("te_pageeditor", editor); parameters.put("editor", editor); } // And finally the document title title = cms.readProperty(file, C_PROPERTY_TITLE); if(title == null) { title = ""; } // We don't want the user to go on and create any temporary // files, if he has insufficient rights. Check this now. if (!cms.hasPermissions(file, I_CmsConstants.C_WRITE_ACCESS)) { throw new CmsSecurityException("Insufficient rights for editing the file " + file, CmsSecurityException.C_SECURITY_NO_PERMISSIONS); } if (!cms.hasPermissions(bodyElementFilename, I_CmsConstants.C_WRITE_ACCESS)) { throw new CmsSecurityException("Insufficient rights for editing the file " + bodyElementFilename, CmsSecurityException.C_SECURITY_NO_PERMISSIONS); } // Okay. All values are initialized. Now we can create // the temporary files. // if the parameter noactivex is set the temp file was already created, // so read the filename from the session String noactivex = (String)parameters.get("noactivex"); if(noactivex == null || "".equals(noactivex.trim())){ tempPageFilename = createTemporaryFile(cms, pageFileResource, tempProject, curProject); } else { tempPageFilename = (String)session.getValue("te_temppagefile"); } cms.getRequestContext().setCurrentProject(curProject); if (isSimplePage) { tempBodyFilename = tempPageFilename; } else { tempBodyFilename = C_VFS_PATH_BODIES.substring(0, C_VFS_PATH_BODIES.length()-1) + tempPageFilename; } session.putValue("te_temppagefile", tempPageFilename); session.putValue("te_tempbodyfile", tempBodyFilename); } // Get the XML parsed content of the layout file. // This can be done by calling the getOwnTemplateFile() method of the // layout's template class. // The content is needed to determine the HTML style of the body element. Object tempObj = null; CmsXmlTemplateFile layoutTemplateFile = null; if (isSimplePage) { StringBuffer layoutBuffer = new StringBuffer(512); layoutBuffer.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<xmltemplate>\n<stylesheet>"); layoutBuffer.append("none"); layoutBuffer.append("</stylesheet>\n<template><element name=\"jsptemplate\"/></template>\n<elementdef name=\"jsptemplate\">\n<class>com.opencms.flex.CmsJspTemplate</class>\n<template>"); layoutBuffer.append(templateFile); layoutBuffer.append("</template>\n</elementdef>\n</xmltemplate>\n"); layoutTemplateFile = new CmsXmlTemplateFile(cms, templateFile + C_XML_CONTROL_FILE_SUFFIX, layoutBuffer.toString()); } else { tempObj = CmsTemplateClassManager.getClassInstance(layoutTemplateClassName); CmsXmlTemplate layoutTemplateClassObject = (CmsXmlTemplate)tempObj; layoutTemplateFile = layoutTemplateClassObject.getOwnTemplateFile(cms, layoutTemplateFilename, null, parameters, null); } // Get the XML parsed content of the body file. // This can be done by calling the getOwnTemplateFile() method of the // body's template class. tempObj = CmsTemplateClassManager.getClassInstance(bodyElementClassName); CmsXmlTemplate bodyElementClassObject = (CmsXmlTemplate)tempObj; CmsXmlTemplateFile bodyTemplateFile = bodyElementClassObject.getOwnTemplateFile(cms, tempBodyFilename, C_BODY_ELEMENT, parameters, null); // Get the temporary page file object CmsXmlControlFile temporaryControlFile = null; if (! isSimplePage) temporaryControlFile = new CmsXmlControlFile(cms, tempPageFilename); if(!existsContentParam) { Vector allBodys = bodyTemplateFile.getAllSections(); if(allBodys == null || allBodys.size() == 0) { body = ""; }else { body = (String)allBodys.elementAt(0); } bodytitle = body.equals("(default)") ? "" : body; if (isSimplePage) { style = cms.readProperty(layoutTemplateFilename, C_PROPERTY_TEMPLATE); if (style != null) { style = hostName + OpenCms.getOpenCmsContext() + style; } else { style = ""; } } else { temporaryControlFile.setElementTemplSelector(C_BODY_ELEMENT, body); temporaryControlFile.setElementTemplate(C_BODY_ELEMENT, tempBodyFilename); // change the current project to temp file project cms.getRequestContext().setCurrentProject(tempProject); temporaryControlFile.write(); cms.getRequestContext().setCurrentProject(curProject); try { style = getStylesheet(cms, null, layoutTemplateFile, null); } catch (Exception e) { style = ""; } if(style != null && !"".equals(style)) { style = hostName + style; } } session.putValue("te_stylesheet", style); } else { // There exists a content parameter. // We have to check all possible changes requested by the user. if(titlechangeRequested) { // The user entered a new document title try { cms.getRequestContext().setCurrentProject(tempProject); cms.writeProperty(tempPageFilename, C_PROPERTY_TITLE, title); cms.getRequestContext().setCurrentProject(curProject); }catch(CmsException e) { cms.getRequestContext().setCurrentProject(curProject); if(OpenCms.isLogging(C_OPENCMS_INFO) ) { OpenCms.log(C_OPENCMS_INFO, getClassName() + "Could not write property " + C_PROPERTY_TITLE + " for file " + file + "."); OpenCms.log(C_OPENCMS_INFO, getClassName() + e); } } } if(templatechangeRequested) { // The user requested a change of the layout template if (isSimplePage) { cms.getRequestContext().setCurrentProject(tempProject); cms.writeProperty(tempPageFilename, C_PROPERTY_TEMPLATE, layoutTemplatFilenameRelative); cms.getRequestContext().setCurrentProject(curProject); style = cms.readProperty(layoutTemplateFilename, C_PROPERTY_TEMPLATE); if (style != null) { style = hostName + OpenCms.getOpenCmsContext() + style; } else { style = ""; } } else { temporaryControlFile.setMasterTemplate(layoutTemplatFilenameRelative ); try { style = getStylesheet(cms, null, layoutTemplateFile, null); }catch(Exception e) { style = ""; } if(style != null && !"".equals(style)) { style = hostName + style; } } session.putValue("te_stylesheet", style); } if(bodytitlechangeRequested) { // The user entered a new title for the current body if((!oldBody.equals("(default)")) && (!oldBody.equals("script"))) { if(bodytitle.toLowerCase().equals("script")) { bodytitle = "script"; } try { bodyTemplateFile.renameSection(oldBody, bodytitle); oldBody = bodytitle; if(!bodychangeRequested) { body = bodytitle; } }catch(Exception e) { bodytitle = oldBodytitle; } if(bodytitle.equals("script")) { session.putValue("te_pageeditor", editor); editor = C_SELECTBOX_EDITORVIEWS[1]; parameters.put("editor", editor); } }else { bodytitle = oldBodytitle; } } if(bodychangeRequested) { if (! isSimplePage) temporaryControlFile.setElementTemplSelector(C_BODY_ELEMENT, body); bodytitle = body.equals("(default)") ? "" : body; if(body.equals("script")) { // User wants to edit javascript code // Select text editor session.putValue("te_pageeditor", editor); editor = C_SELECTBOX_EDITORVIEWS[1]; parameters.put("editor", editor); }else { if(oldBody.equals("script")) { // User wants to switch back from javascript mode // Select old editor editor = (String)session.getValue("te_pageeditor"); parameters.put("editor", editor); } } } if(newbodyRequested) { body = C_BODY_ELEMENT + bodyTemplateFile.createNewSection(C_BODY_ELEMENT); bodytitle = body; if (! isSimplePage) { temporaryControlFile.setElementTemplSelector(C_BODY_ELEMENT, body); temporaryControlFile.setElementTemplate(C_BODY_ELEMENT, tempBodyFilename); } } // check for C_PROPERTY_RELATIVEROOT property (with directory search) String relativeRoot = cms.readProperty(file, C_PROPERTY_RELATIVEROOT, true); // save file contents to our temporary file. content = Encoder.unescape(content, Encoder.C_UTF8_ENCODING); if (! Encoder.C_UTF8_ENCODING.equalsIgnoreCase(cms.getRequestContext().getEncoding())) { content = Encoder.escapeNonAscii(content); } if((!exitRequested) || saveRequested) { bodyTemplateFile.setEditedTemplateContent(cms, content, oldBody, oldEdit.equals(C_SELECTBOX_EDITORVIEWS[0]), file, relativeRoot); } cms.getRequestContext().setCurrentProject(tempProject); bodyTemplateFile.write(); if (! isSimplePage) temporaryControlFile.write(); cms.getRequestContext().setCurrentProject(curProject); } // If the user requested a preview then send a redirect // to the temporary page file. if(previewRequested) { preview(tempPageFilename, reqCont); return "".getBytes(); } // If the user requested a "save" expilitly by pressing one of // the "save" buttons, copy all informations of the temporary // files to the original files. if(saveRequested) { try{ commitTemporaryFile(cms, bodyElementFilename, tempBodyFilename, tempProject, curProject); cms.getRequestContext().setCurrentProject(tempProject); title = cms.readProperty(tempPageFilename, C_PROPERTY_TITLE); cms.getRequestContext().setCurrentProject(curProject); if(title != null && !"".equals(title)) { cms.writeProperty(file, C_PROPERTY_TITLE, title); } if (! isSimplePage) { CmsXmlControlFile originalControlFile = new CmsXmlControlFile(cms, file); originalControlFile.setMasterTemplate(temporaryControlFile.getMasterTemplate()); originalControlFile.write(); } // here we care about the linkmanagement CmsPageLinks linkObject = cms.getPageLinks(file); cms.createLinkEntrys(linkObject.getResourceId(), linkObject.getLinkTargets()); } catch (CmsException e){ // there was an exception while the file should be saved // return to the editor and show the exception so the user can save the changes saveerror = e.getShortException(); if(content != null){ session.putValue(C_PARA_CONTENT, content); } if(body != null){ session.putValue("body", body); } if(file != null){ session.putValue(C_PARA_RESOURCE, file); } if(editor != null){ session.putValue("editor", editor); } if(title != null){ session.putValue(C_PARA_TITLE, title); } if(bodytitle != null){ session.putValue("bodytitle", bodytitle); } if(layoutTemplatFilenameRelative != null){ session.putValue("template", layoutTemplatFilenameRelative); } if(bodyElementClassName != null){ session.putValue("bodyclass", bodyElementClassName); } if(bodyElementFilename != null){ session.putValue("bodyfile", bodyElementFilename); } if(startView != null){ session.putValue("startview", startView); } } } // Check if we should leave th editor instead of start processing if(exitRequested && ((saveerror == null) || "".equals(saveerror))) { // First delete temporary files if (! isSimplePage) temporaryControlFile.removeFromFileCache(); bodyTemplateFile.removeFromFileCache(); // deleting the pagefile will delete the bodyfile too cms.getRequestContext().setCurrentProject(tempProject); cms.deleteResource(tempPageFilename, I_CmsConstants.C_DELETE_OPTION_IGNORE_VFS_LINKS); cms.getRequestContext().setCurrentProject(curProject); try { cms.getRequestContext().getResponse().sendCmsRedirect(CmsWorkplaceAction.getWorkplaceUri(cms)); }catch(IOException e) { throwException("Could not send redirect to workplace main screen.", e); } return null; } // Include the datablocks of the layout file into the body file. // So the "bodytag" and "style" data can be accessed by the body file. Element bodyTag = layoutTemplateFile.getBodyTag(); bodyTemplateFile.setBodyTag(bodyTag); // Load the body! content = bodyTemplateFile.getEditableTemplateContent(this, parameters, body, editor.equals(C_SELECTBOX_EDITORVIEWS[0]), style); // set the context & servlet path in editor content content = CmsStringSubstitution.substitute(content, C_MACRO_OPENCMS_CONTEXT + "/", OpenCms.getOpenCmsContext() + "/"); // escape content content = Encoder.escapeWBlanks(content, Encoder.C_UTF8_ENCODING); parameters.put(C_PARA_CONTENT, content); // put the body parameter so that the selectbox can set the correct current value parameters.put("body", body); parameters.put("bodyfile", bodyElementFilename); parameters.put("bodyclass", bodyElementClassName); parameters.put("template", layoutTemplateFilename); // remove all parameters that could be relevant for the // included editor. parameters.remove(C_PARA_RESOURCE); parameters.remove(C_PARA_ACTION); int numEditors = C_SELECTBOX_EDITORVIEWS.length; for(int i = 0;i < numEditors;i++) { if(editor.equals(C_SELECTBOX_EDITORVIEWS[i])) { parameters.put("editor._CLASS_", C_SELECTBOX_EDITORVIEWS_CLASSES[i]); parameters.put("editor._TEMPLATE_", C_VFS_PATH_DEFAULT_INTERNAL + C_SELECTBOX_EDITORVIEWS_TEMPLATES[i]); } } session.putValue("te_file", file); session.putValue("te_oldedit", editor); session.putValue("te_oldbody", body); session.putValue("te_oldbodytitle", bodytitle); session.putValue("te_oldlayout", layoutTemplateFilename); if(title != null) { session.putValue("te_title", title); }else { session.putValue("te_title", ""); } session.putValue("te_templateclass", layoutTemplateClassName); CmsXmlWpTemplateFile xmlTemplateDocument = (CmsXmlWpTemplateFile)getOwnTemplateFile(cms, templateFile, elementName, parameters, templateSelector); xmlTemplateDocument.setData("editor", editor); xmlTemplateDocument.setData("bodyfile", bodyElementFilename); xmlTemplateDocument.setData("bodyclass", bodyElementClassName); xmlTemplateDocument.setData("editorframe", (String)parameters.get("root.editorframe")); if (bodytitle != null) { xmlTemplateDocument.setData("bodytitle", bodytitle); } // Put the "file" datablock for processing in the template file. // It will be inserted in a hidden input field and given back when submitting. xmlTemplateDocument.setData(C_PARA_RESOURCE, file); if(!"".equals(saveerror)){ templateSelector = "errorsave"; xmlTemplateDocument.setData("errordetail", saveerror); xmlTemplateDocument.setData("errorlasturl", xmlTemplateDocument.getFilename()+".html"); } return startProcessing(cms, xmlTemplateDocument, elementName, parameters, templateSelector); } /** Gets all editor views available in the template editor screens. * <P> * The given vectors <code>names</code> and <code>values</code> will * be filled with the appropriate information to be used for building * a select box. * <P> * Used to build font select boxes in editors. * * @param cms CmsObject Object for accessing system resources. * @param lang reference to the currently valid language file * @param names Vector to be filled with the appropriate values in this method. * @param values Vector to be filled with the appropriate values in this method. * @param parameters Hashtable containing all user parameters <em>(not used here)</em>. * @return Index representing the user's current workplace view in the vectors. * @throws CmsException */ public Integer getEditorViews(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters) throws CmsException { Vector names2 = new Vector(); Vector values2 = new Vector(); getConstantSelectEntries(names2, values2, C_SELECTBOX_EDITORVIEWS, lang); int browserId; CmsRequestContext reqCont = cms.getRequestContext(); HttpServletRequest orgReq = (HttpServletRequest)reqCont.getRequest().getOriginalRequest(); String browser = orgReq.getHeader("user-agent"); if(browser.indexOf("MSIE") > -1) { browserId = 0; } else { browserId = 1; } int loop = 1; int allowedEditors = C_SELECTBOX_EDITORVIEWS_ALLOWED[browserId]; if(((String)parameters.get("body")).equals("script")) { allowedEditors = allowedEditors & 510; } for(int i = 0;i < names2.size();i++) { if((allowedEditors & loop) > 0) { values.addElement(values2.elementAt(i)); names.addElement(names2.elementAt(i)); } loop <<= 1; } int currentIndex = values.indexOf(parameters.get("editor")); return new Integer(currentIndex); } /** * Indicates if the results of this class are cacheable. * * @param cms CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. * @return <EM>true</EM> if cacheable, <EM>false</EM> otherwise. */ public boolean isCacheable(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) { return false; } protected void preview(String previewPath, CmsRequestContext reqCont) throws CmsException { String servletPath = reqCont.getRequest().getServletUrl(); try { reqCont.getResponse().sendCmsRedirect(previewPath); } catch(IOException e) { throwException("Could not send redirect preview file " + servletPath + previewPath, e); } } /** * User method to generate an URL for a preview. * The currently selected temporary file name will be considered. * <P> * In the editor template file, this method can be invoked by * <code>&lt;METHOD name="previewUrl"/&gt;</code>. * * @param cms CmsObject Object for accessing system resources. * @param tagcontent Unused in this special case of a user method. Can be ignored. * @param doc Reference to the A_CmsXmlContent object of the initiating XLM document <em>(not used here)</em>. * @param userObj Hashtable with parameters <em>(not used here)</em>. * @return String with the pics URL. * @throws CmsException */ public Object previewUrl(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObj) throws CmsException { String servletPath = cms.getRequestContext().getRequest().getServletUrl(); I_CmsSession session = cms.getRequestContext().getSession(true); String tempPath = (String)session.getValue("te_temppagefile"); String result = servletPath + tempPath; return result; } /** * Pre-Sets the value of the body title input field. * This method is directly called by the content definiton. * @param Cms The CmsObject. * @param lang The language file. * @param parameters User parameters. * @return Value that is pre-set into the title field. * @throws CmsExeption if something goes wrong. */ public String setBodyTitle(CmsObject cms, CmsXmlLanguageFile lang, Hashtable parameters) throws CmsException { I_CmsSession session = cms.getRequestContext().getSession(true); String title = (String)session.getValue("te_oldbodytitle"); return Encoder.escapeXml(title); } public Object getCharset(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObj) { // Try to find property on file and all parent folders String prop = null; try { I_CmsSession session = cms.getRequestContext().getSession(true); String file = (String)session.getValue("te_file"); prop = cms.readProperty(file, C_PROPERTY_CONTENT_ENCODING); while ((prop == null) && (! "".equals(file))) { file = file.substring(0, file.lastIndexOf("/")); prop = cms.readProperty(file + "/", C_PROPERTY_CONTENT_ENCODING); } } catch (Exception e) {} if (prop == null) prop = OpenCms.getDefaultEncoding(); return prop; } public Object setText(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObj) throws CmsException { Hashtable parameters = (Hashtable)userObj; String content = (String)parameters.get(C_PARA_CONTENT); boolean existsContentParam = (content != null && (!"".equals(content))); // Check the existance of the "file" parameter if(!existsContentParam) { String errorMessage = getClassName() + "No content found."; if(OpenCms.isLogging(C_OPENCMS_CRITICAL) ) { OpenCms.log(C_OPENCMS_CRITICAL, errorMessage); } content = ""; } // Escape the text for including it in HTML text return content; } /** * Pre-Sets the value of the title input field. * This method is directly called by the content definiton. * @param Cms The CmsObject. * @param lang The language file. * @param parameters User parameters. * @return Value that is pre-set into the title field. * @throws CmsExeption if something goes wrong. */ public String setTitle(CmsObject cms, CmsXmlLanguageFile lang, Hashtable parameters) throws CmsException { I_CmsSession session = cms.getRequestContext().getSession(true); String name = (String)session.getValue("te_title"); return Encoder.escapeXml(name); } }
package com.swijaya.galaxytorch; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.graphics.PixelFormat; import android.os.AsyncTask; import android.os.IBinder; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.WindowManager; import android.widget.LinearLayout; import android.widget.RemoteViews; import android.widget.Toast; public class GalaxyTorchService extends Service { private static final String TAG = GalaxyTorchService.class.getSimpleName(); private CameraDevice mCameraDevice; private LinearLayout mOverlay; private SurfaceView mSurfaceView; private SurfaceHolder mHolder; private final Lock mSurfaceLock = new ReentrantLock(); private final Condition mSurfaceHolderIsSet = mSurfaceLock.newCondition(); private static final int ONGOING_NOTIFICATION = 1; private enum WidgetState { OFF (R.drawable.widget_light), ON (R.drawable.wg_light_on), FOCUS (R.drawable.wg_light_focus); /** * The drawable resource associated with this widget state. */ private final int mDrawRes; private WidgetState(int drawRes) { mDrawRes = drawRes; } public int getDrawable() { return mDrawRes; } } private RemoteViews createWidgetWithState(WidgetState state) { Context ctx = getApplicationContext(); RemoteViews widgetViews = new RemoteViews(ctx.getPackageName(), R.layout.widget); widgetViews.setImageViewResource(R.id.widgetbutton, state.getDrawable()); switch (state) { case OFF: case ON: Log.v(TAG, "Renewing pending intent for widget"); // refresh the button's onClick pending intent // create an intent to launch GalaxyTorchWidgetHelperActivity Intent intent = new Intent(ctx, GalaxyTorchService.class); //intent.setAction(TORCH_TOGGLE_ACTION); PendingIntent pendingIntent = PendingIntent.getService(ctx, 0, intent, 0); widgetViews.setOnClickPendingIntent(R.id.widgetbutton, pendingIntent); break; default: // FOCUS; do nothing break; } return widgetViews; } @Override public IBinder onBind(Intent intent) { return null; } /** * This callback implementations should be called from a thread separate to * the task that needs to be done in onStart(). * * The reason is that the service's life cycle callback onStart() will need * to wait for the surface holder to be created, and these callbacks also * happen to be called by the system on the same GUI thread as the service's. * * @author santa * */ private class SurfaceKeeper implements SurfaceHolder.Callback { public void surfaceDestroyed(SurfaceHolder holder) { Log.v(TAG, "(overlay) surfaceDestroyed"); } public void surfaceCreated(SurfaceHolder holder) { Log.v(TAG, "(overlay) surfaceCreated"); if (mCameraDevice == null) { Log.w(TAG, "surfaceCreated: Camera device has not been instantiated"); return; } // atomically set the surface holder and start camera preview mSurfaceLock.lock(); try { mHolder = holder; mCameraDevice.setPreviewDisplayAndStartPreview(holder); mSurfaceHolderIsSet.signalAll(); } finally { mSurfaceLock.unlock(); } } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.v(TAG, "(overlay) surfaceChanged"); } } @SuppressWarnings("deprecation") @Override public void onCreate() { super.onCreate(); Log.v(TAG, "onCreate: service starting"); mCameraDevice = new CameraDevice(); mCameraDevice.acquireCamera(); createOverlay(); // this gives us the surface view the camera device needs SurfaceHolder holder = mSurfaceView.getHolder(); holder.addCallback(new SurfaceKeeper()); // deprecated holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } @Override public void onDestroy() { super.onDestroy(); Log.v(TAG, "onDestroy: service destroyed"); if (mCameraDevice.isFlashlightOn()) { Log.w(TAG, "Flashlight still on"); if (!mCameraDevice.toggleCameraLED(false, false)) { Log.e(TAG, "Cannot toggle camera LED"); } } //mCameraDevice.stopPreview(); // handled in surface callback mCameraDevice.releaseCamera(); mCameraDevice = null; // remove the overlay WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE); wm.removeView(mOverlay); mOverlay = null; mSurfaceView = null; } /** * A background task worker to toggle the torch on. * * We have to resort to using AsyncTask because onCreate() -> onStart() * and SurfaceHolder.Callback for the creation of the preview surface * defined in the former are all done within a single thread. * * As it happens, the service's two life cycle callbacks are most likely * to be called first before the SurfaceHolder's. This means that when * it comes time to toggle the camera's LED within onStart(), the surface * won't be ready. Putting locks around the surface holder won't work * without moving the one task in a separate thread. Hence, this * AsyncTask definition. * * @author santa * */ private class TorchToggleTask extends AsyncTask<Void, Void, Boolean> { private boolean mWasTorchOn; private AppWidgetManager mAppWidgetManager; private ComponentName mThisWidget; @Override protected void onPreExecute() { Log.v(TAG, "onPreExecute"); mWasTorchOn = mCameraDevice.isFlashlightOn(); Log.v(TAG, "Current torch state: " + (mWasTorchOn ? "on" : "off")); // set widget background(s) to its focused state (drawable) mAppWidgetManager = AppWidgetManager.getInstance(getApplicationContext()); mThisWidget = new ComponentName(getApplicationContext(), GalaxyTorchWidgetProvider.class); RemoteViews widget = createWidgetWithState(WidgetState.FOCUS); mAppWidgetManager.updateAppWidget(mThisWidget, widget); } @Override protected Boolean doInBackground(Void... params) { Log.v(TAG, "doInBackground"); mSurfaceLock.lock(); try { while (mHolder == null) { mSurfaceHolderIsSet.await(); } } catch (InterruptedException e) { Log.e(TAG, "InterruptedException: " + e.getLocalizedMessage()); return false; } finally { mSurfaceLock.unlock(); } // actually toggle the LED (in torch mode) return mCameraDevice.toggleCameraLED(!mWasTorchOn, false); } @Override protected void onPostExecute(Boolean result) { Log.v(TAG, "onPostExecute: " + result.toString()); if (!result) { Log.e(TAG, "Cannot toggle camera LED"); } // sanity check boolean isTorchOn = mCameraDevice.isFlashlightOn(); Log.v(TAG, "Current torch state should be " + (mWasTorchOn ? "off" : "on") + " and it is " + (isTorchOn ? "on" : "off")); assert (isTorchOn == !mWasTorchOn); if (isTorchOn == mWasTorchOn) { Log.e(TAG, "Current torch state after toggle did not change"); Toast toast = Toast.makeText(getApplicationContext(), R.string.err_cannot_toggle, Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.show(); // TODO: maybe try another strategy? } // set widget button(s) image to its appropriate state (drawable) RemoteViews widget = createWidgetWithState( isTorchOn ? WidgetState.ON : WidgetState.OFF); mAppWidgetManager.updateAppWidget(mThisWidget, widget); if (isTorchOn) { Log.v(TAG, "We toggled on. Creating an ongoing notification and start foreground service."); // we've turned on the torch; bring the service to foreground and // and notify user startForeground(ONGOING_NOTIFICATION, createToggleNotification()); } else { // after toggling off, kill this service Log.v(TAG, "We toggled off. Stopping service..."); //stopForeground(true); // stopSelf() would also remove notification stopSelf(); } } } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.v(TAG, "onStartCommand"); new TorchToggleTask().execute(); return super.onStartCommand(intent, flags, startId); } /** * Create a surface view overlay (for the camera's preview surface). */ private void createOverlay() { assert (mOverlay == null); WindowManager.LayoutParams params = new WindowManager.LayoutParams(1, 1, WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, // technically automatically set by FLAG_NOT_FOCUSABLE PixelFormat.TRANSLUCENT); params.gravity = Gravity.BOTTOM; LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); mOverlay = (LinearLayout) inflater.inflate(R.layout.overlay, null); mSurfaceView = (SurfaceView) mOverlay.findViewById(R.id.surfaceview); WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE); wm.addView(mOverlay, params); } /** * Create a status bar notification to tell the user that we are holding * the camera device's resources and setting its flashlight LED's torch * mode on. */ @SuppressWarnings("deprecation") private Notification createToggleNotification() { int icon = R.drawable.lightbulb_notify; CharSequence tickerText = getText(R.string.notify_toggle_on); long when = System.currentTimeMillis(); Context context = getApplicationContext(); CharSequence contentTitle = getText(R.string.notify_toggle_on); CharSequence contentText = getText(R.string.notify_toggle_on_ext); Intent notificationIntent = new Intent(this, GalaxyTorchService.class); PendingIntent pendingIntent = PendingIntent.getService(this, 0, notificationIntent, 0); Notification notification = new Notification(icon, tickerText, when); notification.setLatestEventInfo(context, contentTitle, contentText, pendingIntent); return notification; } }
package com.valkryst.VTerminal.printer; import com.valkryst.VTerminal.Panel; import com.valkryst.VTerminal.component.Screen; import lombok.Getter; import lombok.Setter; import java.awt.Point; import java.util.Objects; public class LinePrinter { /** The character to print the line with. */ @Getter @Setter private char printChar = ''; /** * Prints a line on the screen of a panel. * * @param panel * The panel. * * @param fromX * The x-axis (column) coordinate of the start point of the line. * * @param fromY * The y-axis (row) coordinate of the start point of the line. * * @param toX * The x-axis (column) coordinate of the end point of the line. * * @param toY * The y-axis (row) coordinate of the end point of the line. * * @throws NullPointerException * If the panel is null. */ public void print(final Panel panel, final int fromX, final int fromY, final int toX, final int toY) { Objects.requireNonNull(panel); print(panel.getScreen(), fromX, fromY, toX, toY); } /** * Prints a line on a screen. * * @param screen * The screen. * * @param fromX * The x-axis (column) coordinate of the start point of the line. * * @param fromY * The y-axis (row) coordinate of the start point of the line. * * @param toX * The x-axis (column) coordinate of the end point of the line. * * @param toY * The y-axis (row) coordinate of the end point of the line. * * @throws NullPointerException * If the panel is null. */ public void print(final Screen screen, int fromX, int fromY, final int toX, final int toY) { Objects.requireNonNull(screen); printLine(screen, fromX, fromY, toX, toY); } public void print(final Panel panel, final Point[] points) { Objects.requireNonNull(panel); Objects.requireNonNull(points); print(panel.getScreen(), points); } public void print(final Screen screen, final Point[] points) { Objects.requireNonNull(screen); Objects.requireNonNull(points); if (points.length < 2) { throw new IllegalArgumentException("A line requires at-least two points to be drawn."); } for (int i = 1 ; i < points.length ; i++) { final Point previous = points[i - 1]; final Point current = points[i]; print(screen, previous.x, previous.y, current.x, current.y); } } /** * Prints a line on a screen using the Bresenham algorithm. * * @param screen * The screen. * * @param fromX * The x-axis (column) coordinate of the start point of the line. * * @param fromY * The y-axis (row) coordinate of the start point of the line. * * @param toX * The x-axis (column) coordinate of the end point of the line. * * @param toY * The y-axis (row) coordinate of the end point of the line. * * @throws NullPointerException * If the screen is null. */ private void printLine(final Screen screen, int fromX, int fromY, final int toX, final int toY) { Objects.requireNonNull(screen); // delta of exact value and rounded value of the dependant variable int d = 0; int dy = Math.abs(toY - fromY); int dx = Math.abs(toX - fromX); int dy2 = (dy << 1); // slope scaling factors to avoid floating int dx2 = (dx << 1); // point int ix = fromX < toX ? 1 : -1; // increment direction int iy = fromY < toY ? 1 : -1; while (true) { screen.write(printChar, fromX, fromY); if (dy <= dx) { if (fromX == toX) { break; } fromX += ix; d += dy2; if (d > dx) { fromY += iy; d -= dx2; } } else { if (fromY == toY) { break; } fromY += iy; d += dx2; if (d > dy) { fromX += ix; d -= dy2; } } } } }
package beans; import app.ejb.UsuarioFacade; import app.entity.Mensaje; import app.entity.PeticionAmistad; import app.entity.Usuario; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.inject.Named; import javax.enterprise.context.Dependent; import javax.enterprise.context.RequestScoped; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.inject.Inject; /** * * @author user */ @Named(value = "notificacionesBean") @RequestScoped public class NotificacionesBean { /** * Creates a new instance of NotificacionesBean */ private List <Mensaje> listaMensajes; private List <PeticionAmistad> listaPeticiones; private boolean hayMensajesSinLeer; private boolean hayPeticionesDeAmistad; private Usuario u; @Inject SesionBean sesionBean; @EJB private UsuarioFacade uf; public NotificacionesBean() { } //public List <Mensaje> obtenerListaMensajes (Usuario u) { @PostConstruct public void init (){ this.u = sesionBean.obtenerUsuario(); if (listaMensajes == null) { List <Mensaje> mAux = new ArrayList<>(); for (Mensaje m : u.getMensajeCollection1()) { if (!m.getLeido()) { mAux.add(m); } } listaMensajes = mAux; if (listaMensajes.size()>0) { hayMensajesSinLeer = true; } else{ hayMensajesSinLeer = false; } } if (listaPeticiones == null) { List <PeticionAmistad> pAux = new ArrayList<>(); for (PeticionAmistad p: u.getPeticionAmistadCollection1()) { pAux.add(p); } listaPeticiones = pAux; if (listaPeticiones.size()>0) { this.hayPeticionesDeAmistad = true; } else{ this.hayPeticionesDeAmistad = false; } } } public List<PeticionAmistad> getListaPeticiones() { return listaPeticiones; } public void setListaPeticiones(List<PeticionAmistad> listaPeticiones) { this.listaPeticiones = listaPeticiones; } public void setHayMensajesSinLeer(boolean hayMensajesSinLeer) { this.hayMensajesSinLeer = hayMensajesSinLeer; } public void setHayPeticionesDeAmistad(boolean hayPeticionesDeAmistad) { this.hayPeticionesDeAmistad = hayPeticionesDeAmistad; } public void responder(Mensaje mensaje) throws IOException{ for(Mensaje m : u.getMensajeCollection1()){ if(m.getId().equals(mensaje.getId())){ m.setLeido(true); } } uf.edit(u); this.redirect(mensaje.getIdEmisor().getId()); } public void descartar(Mensaje mensaje) throws IOException{ for(Mensaje m : u.getMensajeCollection1()){ if(m.getId().equals(mensaje.getId())){ m.setLeido(true); } } uf.edit(u); this.redirectN(); } public String aceptar(PeticionAmistad peticion){ uf.aceptarPeticionAmistad(peticion.getUsuario().getId(), peticion.getUsuario1().getId()); u.getPeticionAmistadCollection1().remove(peticion); uf.edit(u); return "perfil"; } public void rechazar(PeticionAmistad peticion) throws IOException{ u.getPeticionAmistadCollection1().remove(peticion); uf.edit(u); this.redirectN(); } public List<Mensaje> getListaMensajes() { return listaMensajes; } public void setListaMensajes(List<Mensaje> listaMensajes) { this.listaMensajes = listaMensajes; } public void redirect(int id) throws IOException { ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); externalContext.redirect("perfil.jsf?id="+id); } public void redirectN() throws IOException { ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); externalContext.redirect("notificaciones.jsf"); } }
package com.jenjinstudios.core.util; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Hash { private static String getHashedString(String input) { String hashedString; try { //Convert the pass to an md5 hash string byte[] passBytes = input.getBytes("UTF-8"); MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] encryption = md.digest(passBytes); StringBuilder hexString = new StringBuilder(); for (byte anEncryption : encryption) { // Convert back to a string, making sure to include leading zeros. String hex = Integer.toHexString(0xff & anEncryption); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } hashedString = hexString.toString(); } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) { hashedString = null; } return hashedString; } public static String getHashedString(String input, String salt) { return getHashedString(salt + input); } }
package com.jme3.input.jogl; import com.jme3.cursors.plugins.JmeCursor; import com.jme3.input.MouseInput; import com.jme3.input.RawInputListener; import com.jme3.input.event.MouseButtonEvent; import com.jme3.input.event.MouseMotionEvent; import com.jogamp.common.nio.Buffers; import com.jogamp.newt.Display.PointerIcon; import com.jogamp.newt.event.MouseEvent; import com.jogamp.newt.event.MouseListener; import com.jogamp.newt.opengl.GLWindow; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.logging.Logger; import com.jogamp.nativewindow.util.Dimension; import com.jogamp.nativewindow.util.DimensionImmutable; import com.jogamp.nativewindow.util.PixelFormat; import com.jogamp.nativewindow.util.PixelRectangle; import com.jogamp.nativewindow.util.Point; import com.jogamp.newt.event.WindowAdapter; import com.jogamp.newt.event.WindowEvent; public class NewtMouseInput implements MouseInput, MouseListener { public static int WHEEL_AMP = 40; // arbitrary... Java's mouse wheel seems to report something a lot lower than lwjgl's private static final Logger logger = Logger.getLogger(NewtMouseInput.class.getName()); private boolean visible = true; private RawInputListener listener; private GLWindow component; private final ArrayList<MouseButtonEvent> eventQueue = new ArrayList<MouseButtonEvent>(); private final ArrayList<MouseButtonEvent> eventQueueCopy = new ArrayList<MouseButtonEvent>(); private int lastEventX; private int lastEventY; private int lastEventWheel; private int wheelPos; private Point location; private Point centerLocation; private Point centerLocationOnScreen; private Point lastKnownLocation; private boolean isRecentering; private boolean cursorMoved; private int eventsSinceRecenter; public NewtMouseInput() { location = new Point(); centerLocation = new Point(); centerLocationOnScreen = new Point(); lastKnownLocation = new Point(); } public void setInputSource(GLWindow comp) { if (component != null) { component.removeMouseListener(this); eventQueue.clear(); wheelPos = 0; isRecentering = false; eventsSinceRecenter = 0; lastEventX = 0; lastEventY = 0; lastEventWheel = 0; location = new Point(); centerLocation = new Point(); centerLocationOnScreen = new Point(); lastKnownLocation = new Point(); } component = comp; component.addMouseListener(this); component.addWindowListener(new WindowAdapter(){ @Override public void windowGainedFocus(WindowEvent e) { setCursorVisible(visible); } @Override public void windowLostFocus(WindowEvent e) { //without those lines, //on Linux (OpenBox) the mouse is not restored if invisible (eg via Alt-Tab) component.setPointerVisible(true); component.confinePointer(false); } }); } @Override public void initialize() { } @Override public void destroy() { } @Override public boolean isInitialized() { return true; } @Override public void setInputListener(RawInputListener listener) { this.listener = listener; } @Override public long getInputTimeNanos() { return System.nanoTime(); } @Override public void setCursorVisible(boolean visible) { lastKnownLocation.setX(0); lastKnownLocation.setY(0); this.visible = visible; component.setPointerVisible(visible); component.confinePointer(!visible); hack_confinePointer(); } private void hack_confinePointer() { if (component.hasFocus() && component.isPointerConfined() && !component.isPointerVisible()) { recenterMouse(component); } } @Override public void update() { if (!component.hasFocus()) return; if (cursorMoved) { int newX = location.getX(); int newY = location.getY(); int newWheel = wheelPos; // invert DY int actualX = lastKnownLocation.getX(); int actualY = component.getHeight() - lastKnownLocation.getY(); MouseMotionEvent evt = new MouseMotionEvent(actualX, actualY, newX - lastEventX, lastEventY - newY, wheelPos, lastEventWheel - wheelPos); listener.onMouseMotionEvent(evt); lastEventX = newX; lastEventY = newY; lastEventWheel = newWheel; cursorMoved = false; } synchronized (eventQueue) { eventQueueCopy.clear(); eventQueueCopy.addAll(eventQueue); eventQueue.clear(); } int size = eventQueueCopy.size(); for (int i = 0; i < size; i++) { listener.onMouseButtonEvent(eventQueueCopy.get(i)); } } @Override public int getButtonCount() { return 3; } @Override public void mouseClicked(MouseEvent awtEvt) { // MouseButtonEvent evt = new MouseButtonEvent(getJMEButtonIndex(arg0), false); // listener.onMouseButtonEvent(evt); } @Override public void mousePressed(MouseEvent newtEvt) { MouseButtonEvent evt = new MouseButtonEvent(getJMEButtonIndex(newtEvt), true, newtEvt.getX(), newtEvt.getY()); evt.setTime(newtEvt.getWhen()); synchronized (eventQueue) { eventQueue.add(evt); } } @Override public void mouseReleased(MouseEvent awtEvt) { MouseButtonEvent evt = new MouseButtonEvent(getJMEButtonIndex(awtEvt), false, awtEvt.getX(), awtEvt.getY()); evt.setTime(awtEvt.getWhen()); synchronized (eventQueue) { eventQueue.add(evt); } } @Override public void mouseEntered(MouseEvent awtEvt) { hack_confinePointer(); } @Override public void mouseExited(MouseEvent awtEvt) { hack_confinePointer(); } @Override public void mouseWheelMoved(MouseEvent awtEvt) { //FIXME not sure this is the right way to handle this case // [0] should be used when the shift key is down float dwheel = awtEvt.getRotation()[1]; wheelPos += dwheel * WHEEL_AMP; cursorMoved = true; } @Override public void mouseDragged(MouseEvent awtEvt) { mouseMoved(awtEvt); } @Override public void mouseMoved(MouseEvent awtEvt) { if (isRecentering) { // MHenze (cylab) Fix Issue 35: // As long as the MouseInput is in recentering mode, nothing is done until the mouse is entered in the component // by the events generated by the robot. If this happens, the last known location is resetted. if ((centerLocation.getX() == awtEvt.getX() && centerLocation.getY() == awtEvt.getY()) || eventsSinceRecenter++ == 5) { lastKnownLocation.setX(awtEvt.getX()); lastKnownLocation.setY(awtEvt.getY()); isRecentering = false; } } else { // MHenze (cylab) Fix Issue 35: // Compute the delta and absolute coordinates and recenter the mouse if necessary int dx = awtEvt.getX() - lastKnownLocation.getX(); int dy = awtEvt.getY() - lastKnownLocation.getY(); location.setX(location.getX() + dx); location.setY(location.getY() + dy); hack_confinePointer(); lastKnownLocation.setX(awtEvt.getX()); lastKnownLocation.setY(awtEvt.getY()); cursorMoved = true; } } // MHenze (cylab) Fix Issue 35: A method to generate recenter the mouse to allow the InputSystem to "grab" the mouse private void recenterMouse(final GLWindow component) { eventsSinceRecenter = 0; isRecentering = true; centerLocation.setX(component.getWidth() / 2); centerLocation.setY(component.getHeight() / 2); centerLocationOnScreen.setX(centerLocation.getX()); centerLocationOnScreen.setY(centerLocation.getY()); component.warpPointer(centerLocationOnScreen.getX(), centerLocationOnScreen.getY()); } private int getJMEButtonIndex(MouseEvent awtEvt) { int index; switch (awtEvt.getButton()) { default: case MouseEvent.BUTTON1: //left index = MouseInput.BUTTON_LEFT; break; case MouseEvent.BUTTON2: //middle index = MouseInput.BUTTON_MIDDLE; break; case MouseEvent.BUTTON3: //right index = MouseInput.BUTTON_RIGHT; break; case MouseEvent.BUTTON4: case MouseEvent.BUTTON5: case MouseEvent.BUTTON6: case MouseEvent.BUTTON7: case MouseEvent.BUTTON8: case MouseEvent.BUTTON9: //FIXME index = 0; break; } return index; } @Override public void setNativeCursor(JmeCursor cursor) { final ByteBuffer pixels = Buffers.copyIntBufferAsByteBuffer(cursor.getImagesData()); final DimensionImmutable size = new Dimension(cursor.getWidth(), cursor.getHeight()); final PixelFormat pixFormat = PixelFormat.RGBA8888; final PixelRectangle.GenericPixelRect rec = new PixelRectangle.GenericPixelRect(pixFormat, size, 0, true, pixels); final PointerIcon joglCursor = component.getScreen().getDisplay().createPointerIcon(rec, cursor.getXHotSpot(), cursor.getHeight() - cursor.getYHotSpot()); component.setPointerIcon(joglCursor); } }
package org.jetbrains.jps.incremental; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.io.FileUtil; import org.jetbrains.ether.dependencyView.Mappings; import org.jetbrains.jps.Module; import org.jetbrains.jps.ModuleChunk; import org.jetbrains.jps.incremental.storage.SourceToOutputMapping; import java.io.File; import java.io.IOException; import java.util.*; public abstract class Builder { private static final Key<Set<File>> ALL_AFFECTED_FILES_KEY = Key.create("_all_affected_files_"); private static final Key<Set<File>> ALL_COMPILED_FILES_KEY = Key.create("_all_compiled_files_"); public static enum ExitCode { OK, ABORT, ADDITIONAL_PASS_REQUIRED } public abstract String getName(); public abstract ExitCode build(CompileContext context, ModuleChunk chunk) throws ProjectBuildException; public abstract String getDescription(); public void cleanupResources(CompileContext context, ModuleChunk chunk) { ALL_AFFECTED_FILES_KEY.set(context, null); ALL_COMPILED_FILES_KEY.set(context, null); } /** * @param context * @param delta * @param chunk * @param filesToCompile files compiled in this round * @param successfullyCompiled * @return true if additional compilation pass is required, false otherwise * @throws Exception */ public final boolean updateMappings(CompileContext context, final Mappings delta, ModuleChunk chunk, Collection<File> filesToCompile, Collection<File> successfullyCompiled) throws Exception { try { boolean additionalPassRequired = false; final Set<String> removedPaths = getRemovedPaths(context); final Mappings globalMappings = context.getDataManager().getMappings(); //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (globalMappings) { if (!context.isProjectRebuild() && context.shouldDifferentiate(chunk, context.isCompilingTests())) { final Set<File> allCompiledFiles = getAllCompiledFilesContainer(context); final Set<File> allAffectedFiles = getAllAffectedFilesContainer(context); // mark as affected all files that were dirty before compilation allAffectedFiles.addAll(filesToCompile); // accumulate all successfully compiled in this round allCompiledFiles.addAll(successfullyCompiled); // unmark as affected all successfully compiled allAffectedFiles.removeAll(successfullyCompiled); final HashSet<File> affectedBeforeDif = new HashSet<File>(allAffectedFiles); final boolean incremental = globalMappings.differentiate( delta, removedPaths, successfullyCompiled, allCompiledFiles, allAffectedFiles ); if (incremental) { final Set<File> newlyAffectedFiles = new HashSet<File>(allAffectedFiles); newlyAffectedFiles.removeAll(affectedBeforeDif); newlyAffectedFiles.removeAll(allCompiledFiles); // the diff operation may have affected the class already compiled in thic compilation round if (!newlyAffectedFiles.isEmpty()) { for (File file : newlyAffectedFiles) { context.markDirty(file); } additionalPassRequired = context.isMake() && chunkContainsAffectedFiles(context, chunk, newlyAffectedFiles); } } else { additionalPassRequired = context.isMake(); context.markDirtyRecursively(chunk); } } globalMappings.integrate(delta, successfullyCompiled, removedPaths); } return additionalPassRequired; } catch(RuntimeException e) { final Throwable cause = e.getCause(); if (cause instanceof IOException) { throw ((IOException)cause); } throw e; } } // delete all class files that according to mappings correspond to given sources public static void deleteCorrespondingOutputFiles(CompileContext context, Map<File, Module> sources) throws Exception { if (!context.isProjectRebuild() && !sources.isEmpty()) { for (Map.Entry<File, Module> pair : sources.entrySet()) { final File file = pair.getKey(); final String srcPath = file.getPath(); final String moduleName = pair.getValue().getName().toLowerCase(Locale.US); final SourceToOutputMapping srcToOut = context.getDataManager().getSourceToOutputMap(moduleName, context.isCompilingTests()); final Collection<String> outputs = srcToOut.getState(srcPath); if (outputs != null) { for (String output : outputs) { FileUtil.delete(new File(output)); } srcToOut.remove(srcPath); } } } } private static boolean chunkContainsAffectedFiles(CompileContext context, ModuleChunk chunk, final Set<File> affected) throws Exception { final Set<Module> chunkModules = new HashSet<Module>(chunk.getModules()); if (!chunkModules.isEmpty()) { for (File file : affected) { final RootDescriptor moduleAndRoot = context.getModuleAndRoot(file); if (moduleAndRoot != null && chunkModules.contains(moduleAndRoot.module)) { return true; } } } return false; } private static Set<File> getAllAffectedFilesContainer(CompileContext context) { Set<File> allAffectedFiles = ALL_AFFECTED_FILES_KEY.get(context); if (allAffectedFiles == null) { allAffectedFiles = new HashSet<File>(); ALL_AFFECTED_FILES_KEY.set(context, allAffectedFiles); } return allAffectedFiles; } private static Set<File> getAllCompiledFilesContainer(CompileContext context) { Set<File> allCompiledFiles = ALL_COMPILED_FILES_KEY.get(context); if (allCompiledFiles == null) { allCompiledFiles = new HashSet<File>(); ALL_COMPILED_FILES_KEY.set(context, allCompiledFiles); } return allCompiledFiles; } private static Set<String> getRemovedPaths(CompileContext context) { final Set<String> removed = Paths.CHUNK_REMOVED_SOURCES_KEY.get(context); return removed != null? removed : Collections.<String>emptySet(); } }
package jshellsession; import java.io.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class JShellSession implements Closeable { private static final String END_MARKER = "[>>END<<]:"; private Lock mLock; private Condition mReachedEndMarkerCondition; private volatile boolean mReachedEndMarker; private Process mProcess; private BufferedWriter mWriter; private BufferedReader mStdOutReader; private BufferedReader mStdErrReader; private List<String> mStdOut; private List<String> mStdErr; private int mExitCode; private Set<Integer> mSuccessExitValues; private Thread mThreadStdOut; private Thread mThreadStdErr; private OnCommandOutputListener mOnCommandOutputListener; public JShellSession(Config config) throws IOException { mStdOut = new ArrayList<>(); mStdErr = new ArrayList<>(); mLock = new ReentrantLock(true); mReachedEndMarkerCondition = mLock.newCondition(); mReachedEndMarker = false; mExitCode = 0; mOnCommandOutputListener = null; mSuccessExitValues = new HashSet<>(config.mSuccessExitValues); mProcess = createProcess(config); mWriter = new BufferedWriter(new OutputStreamWriter(mProcess.getOutputStream())); mStdOutReader = new BufferedReader(new InputStreamReader(mProcess.getInputStream())); mStdErrReader = new BufferedReader(new InputStreamReader(mProcess.getErrorStream())); mThreadStdOut = new Thread(new Runnable() { @Override public void run() { processStdOutput(); } }); mThreadStdOut.start(); if (config.mRedirectErrorStream) { mThreadStdErr = null; } else { mThreadStdErr = new Thread(new Runnable() { @Override public void run() { processErrOutput(); } }); mThreadStdErr.start(); } } private Process createProcess(Config config) throws IOException { final ProcessBuilder processBuilder = new ProcessBuilder(config.mShellCommand); processBuilder.redirectErrorStream(config.mRedirectErrorStream); processBuilder.environment().putAll(config.mEnv); return processBuilder.start(); } public CommandResult run(String cmd) throws IOException { return run(cmd, 0); } private String validateCommand(String cmd) { return (cmd == null || cmd.trim().isEmpty()) ? ":" : cmd; } public static CommandResult quickRun(String cmd) throws IOException { return quickRun(Config.defaultConfig(), cmd); } public static CommandResult quickRun(Config config, String cmd) throws IOException { final JShellSession jShellSession = new JShellSession(config); try { return jShellSession.run(cmd); } finally { jShellSession.close(); } } public CommandResult run(String cmd, long timeout) throws IOException { mLock.lock(); mReachedEndMarker = false; try { if (mProcess == null) { throw new IllegalStateException("session has been closed"); } mStdOut.clear(); mStdErr.clear(); mWriter.write(String.format("%s; echo \"%s\"$?", validateCommand(cmd), END_MARKER)); mWriter.newLine(); mWriter.flush(); waitForEndMarker(timeout); return new CommandResult(mExitCode, mSuccessExitValues, mStdOut.toArray(new String[mStdOut.size()]), mStdErr.toArray(new String[mStdErr.size()])); } finally { mLock.unlock(); } } private void waitForEndMarker(long timeout) { if (timeout == 0) { while (!mReachedEndMarker) { try { mReachedEndMarkerCondition.await(); } catch (InterruptedException ignored) { } } } else { long nanos = TimeUnit.MILLISECONDS.toNanos(timeout); while (!mReachedEndMarker) { if (nanos <= 0L) { break; } try { nanos = mReachedEndMarkerCondition.awaitNanos(nanos); } catch (InterruptedException ignored) { } } } } private void processErrOutput() { try { for (String line = mStdErrReader.readLine(); line != null; line = mStdErrReader.readLine()) { line = line.replace('\0', ' ').trim(); mStdErr.add(line); if (mOnCommandOutputListener != null) { mOnCommandOutputListener.onNewErrOutLine(line); } } } catch (IOException ignored) { } } private void processStdOutput() { try { for (String line = mStdOutReader.readLine(); line != null; line = mStdOutReader.readLine()) { line = line.replace('\0', ' ').trim(); if (line.contains(END_MARKER)) { final int endMarkerIndex = line.indexOf(END_MARKER); if (!line.startsWith(END_MARKER)) { mStdOut.add(line.substring(0, endMarkerIndex).trim()); } mExitCode = Integer.parseInt(line.substring(endMarkerIndex + END_MARKER.length())); signal(); } else { mStdOut.add(line); if (mOnCommandOutputListener != null) { mOnCommandOutputListener.onNewStdOutLine(line); } } } } catch (IOException ignored) { } finally { if (mProcess != null) { try { mExitCode = mProcess.waitFor(); } catch (InterruptedException ignored) { } } signal(); } } private void signal() { mLock.lock(); try { mReachedEndMarker = true; mReachedEndMarkerCondition.signal(); } finally { mLock.unlock(); } } public boolean isRunning() { if (mProcess == null) { return false; } try { mProcess.exitValue(); return false; } catch (IllegalThreadStateException ignored) { return true; } } public void setOnCommandOutputListener(OnCommandOutputListener listener) { mOnCommandOutputListener = listener; } @Override public void close() { if (mProcess != null) { mProcess.destroy(); mProcess = null; mThreadStdOut.interrupt(); } if (mStdOutReader != null) { try { mStdOutReader.close(); } catch (IOException ignored) { } } if (mStdErrReader != null) { try { mStdErrReader.close(); } catch (IOException ignored) { } } if (mWriter != null) { try { mWriter.close(); } catch (IOException ignored) { } } try { mThreadStdOut.join(1000); } catch (InterruptedException ignored) { } if (mThreadStdErr != null) { try { mThreadStdErr.join(1000); } catch (InterruptedException ignored) { } } mOnCommandOutputListener = null; } }
package com.jayway.jsonpath; import com.fasterxml.jackson.databind.node.ArrayNode; import com.google.gson.JsonArray; import com.jayway.jsonpath.spi.json.GsonJsonProvider; import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider; import com.jayway.jsonpath.spi.json.JacksonJsonProvider; import com.jayway.jsonpath.spi.json.JsonOrgJsonProvider; import com.jayway.jsonpath.spi.json.JsonSmartJsonProvider; import com.jayway.jsonpath.spi.mapper.GsonMappingProvider; import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; import com.jayway.jsonpath.spi.mapper.JsonOrgMappingProvider; import com.jayway.jsonpath.spi.mapper.JsonSmartMappingProvider; import org.assertj.core.util.Lists; import org.junit.Test; import java.util.List; import static org.junit.Assert.assertEquals; public class ProviderInTest { private final String JSON = "[{\"foo\": \"bar\"}, {\"foo\": \"baz\"}]"; private final String EQUALS_FILTER = "$.[?(@.foo == %s)].foo"; private final String IN_FILTER = "$.[?(@.foo in [%s])].foo"; private final String DOUBLE_QUOTES = "\"bar\""; private final String DOUBLE_QUOTES_EQUALS_FILTER = String.format(EQUALS_FILTER, DOUBLE_QUOTES); private final String DOUBLE_QUOTES_IN_FILTER = String.format(IN_FILTER, DOUBLE_QUOTES); private final String SINGLE_QUOTES = "'bar'"; private final String SINGLE_QUOTES_EQUALS_FILTER = String.format(EQUALS_FILTER, SINGLE_QUOTES); private final String SINGLE_QUOTES_IN_FILTER = String.format(IN_FILTER, SINGLE_QUOTES); @Test public void testJsonPathQuotesJackson() throws Exception { final Configuration jackson = Configuration.builder().jsonProvider(new JacksonJsonProvider()).mappingProvider(new JacksonMappingProvider()).build(); final DocumentContext ctx = JsonPath.using(jackson).parse(JSON); final List<String> doubleQuoteEqualsResult = ctx.read(DOUBLE_QUOTES_EQUALS_FILTER); assertEquals(Lists.newArrayList("bar"), doubleQuoteEqualsResult); final List<String> singleQuoteEqualsResult = ctx.read(SINGLE_QUOTES_EQUALS_FILTER); assertEquals(doubleQuoteEqualsResult, singleQuoteEqualsResult); final List<String> doubleQuoteInResult = ctx.read(DOUBLE_QUOTES_IN_FILTER); assertEquals(doubleQuoteInResult, doubleQuoteEqualsResult); final List<String> singleQuoteInResult = ctx.read(SINGLE_QUOTES_IN_FILTER); assertEquals(doubleQuoteInResult, singleQuoteInResult); } @Test public void testJsonPathQuotesJacksonJsonNode() throws Exception { final Configuration jacksonJsonNode = Configuration.builder().jsonProvider(new JacksonJsonNodeJsonProvider()).mappingProvider(new JacksonMappingProvider()).build(); final DocumentContext ctx = JsonPath.using(jacksonJsonNode).parse(JSON); final ArrayNode doubleQuoteEqualsResult = ctx.read(DOUBLE_QUOTES_EQUALS_FILTER); assertEquals("bar", doubleQuoteEqualsResult.get(0).asText()); final ArrayNode singleQuoteEqualsResult = ctx.read(SINGLE_QUOTES_EQUALS_FILTER); assertEquals(doubleQuoteEqualsResult, singleQuoteEqualsResult); final ArrayNode doubleQuoteInResult = ctx.read(DOUBLE_QUOTES_IN_FILTER); assertEquals(doubleQuoteInResult, doubleQuoteEqualsResult); final ArrayNode singleQuoteInResult = ctx.read(SINGLE_QUOTES_IN_FILTER); assertEquals(doubleQuoteInResult, singleQuoteInResult); } @Test public void testJsonPathQuotesGson() throws Exception { final Configuration gson = Configuration.builder().jsonProvider(new GsonJsonProvider()).mappingProvider(new GsonMappingProvider()).build(); final DocumentContext ctx = JsonPath.using(gson).parse(JSON); final JsonArray doubleQuoteEqualsResult = ctx.read(DOUBLE_QUOTES_EQUALS_FILTER); assertEquals("bar", doubleQuoteEqualsResult.get(0).getAsString()); final JsonArray singleQuoteEqualsResult = ctx.read(SINGLE_QUOTES_EQUALS_FILTER); assertEquals(doubleQuoteEqualsResult, singleQuoteEqualsResult); final JsonArray doubleQuoteInResult = ctx.read(DOUBLE_QUOTES_IN_FILTER); assertEquals(doubleQuoteInResult, doubleQuoteEqualsResult); final JsonArray singleQuoteInResult = ctx.read(SINGLE_QUOTES_IN_FILTER); assertEquals(doubleQuoteInResult, singleQuoteInResult); } @Test public void testJsonPathQuotesJsonOrg() throws Exception { final Configuration jsonOrg = Configuration.builder().jsonProvider(new JsonOrgJsonProvider()).mappingProvider(new JsonOrgMappingProvider()).build(); final DocumentContext ctx = JsonPath.using(jsonOrg).parse(JSON); final org.json.JSONArray doubleQuoteEqualsResult = ctx.read(DOUBLE_QUOTES_EQUALS_FILTER); assertEquals("bar", doubleQuoteEqualsResult.get(0)); final org.json.JSONArray singleQuoteEqualsResult = ctx.read(SINGLE_QUOTES_EQUALS_FILTER); assertEquals(doubleQuoteEqualsResult.get(0), singleQuoteEqualsResult.get(0)); final org.json.JSONArray doubleQuoteInResult = ctx.read(DOUBLE_QUOTES_IN_FILTER); assertEquals(doubleQuoteInResult.get(0), doubleQuoteEqualsResult.get(0)); final org.json.JSONArray singleQuoteInResult = ctx.read(SINGLE_QUOTES_IN_FILTER); assertEquals(doubleQuoteInResult.get(0), singleQuoteInResult.get(0)); } @Test public void testJsonPathQuotesJsonSmart() throws Exception { final Configuration jsonSmart = Configuration.builder().jsonProvider(new JsonSmartJsonProvider()).mappingProvider(new JsonSmartMappingProvider()).build(); final DocumentContext ctx = JsonPath.using(jsonSmart).parse(JSON); final net.minidev.json.JSONArray doubleQuoteEqualsResult = ctx.read(DOUBLE_QUOTES_EQUALS_FILTER); assertEquals("bar", doubleQuoteEqualsResult.get(0)); final net.minidev.json.JSONArray singleQuoteEqualsResult = ctx.read(SINGLE_QUOTES_EQUALS_FILTER); assertEquals(doubleQuoteEqualsResult, singleQuoteEqualsResult); final net.minidev.json.JSONArray doubleQuoteInResult = ctx.read(DOUBLE_QUOTES_IN_FILTER); assertEquals(doubleQuoteInResult, doubleQuoteEqualsResult); final net.minidev.json.JSONArray singleQuoteInResult = ctx.read(SINGLE_QUOTES_IN_FILTER); assertEquals(doubleQuoteInResult, singleQuoteInResult); } }
package view; import java.io.IOException; //import javafx.scene.Parent; //import javafx.fxml.FXMLLoader; import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; /** * Main view (GUI) of uClear * * @author Wang Zhipeng * */ public class MainView extends Application { MainViewController mainViewControl; @Override public void start(Stage primaryStage) throws IOException { // Parent root = FXMLLoader.load(getClass().getResource("MainView.fxml")); mainViewControl = new MainViewController(); mainViewControl.setText("Enter Command here..."); mainViewControl.setDateLabel(); // Scene scene = new Scene(root, 434, 620); Scene scene = new Scene(mainViewControl); primaryStage.setWidth(450); primaryStage.setHeight(620); primaryStage.setTitle("uClear: Welcome!"); primaryStage.setScene(scene); scene.getStylesheets().add(MainView.class.getResource("MainView.css").toExternalForm()); primaryStage.show(); } public MainViewController getController() { return this.mainViewControl; } public static void main(String[] args) { launch(args); } }
import java.sql.*; import java.util.Scanner; import java.util.StringJoiner; import java.util.TimeZone; import java.util.Vector; import java.util.stream.StreamSupport; public class Main { public static String stringFill(String targetString,char filling, int repetition){ for (int j = 0; j < repetition; j++) { targetString += filling; } return targetString; } public static String formatString(Vector<String> vec){ String formatedString = "|"; int stringLen; int repetition; for (String i:vec) { if(i.length() >30){ i= i.substring(0, 29) + "."; } stringLen = i.length(); repetition = (30 - stringLen)/2; if((30 - stringLen) % 2 == 0){ formatedString = stringFill(formatedString,' ',repetition ); } else{ formatedString = stringFill(formatedString,' ',repetition + 1); } formatedString += i; formatedString = stringFill(formatedString,' ',repetition); formatedString += "|"; } return formatedString; } public static void main(String[] args) { Connection connexion= null; try { TimeZone timeZone = TimeZone.getTimeZone("Montreal"); TimeZone.setDefault(timeZone); Class.forName("oracle.jdbc.OracleDriver"); connexion = DriverManager.getConnection("jdbc:oracle:thin:@//ora-labos.labos.polymtl.ca:2001/labos", "INF3710-163-21","9WM6RV"); System.out.println("Connected!"); /* variables*/ Scanner scanner = new Scanner(System.in); //lire le stdin String matricule; String sigle; String cours; int choice; Statement makeJavaGreatAgain = connexion.createStatement(); ResultSet queryResults; String query; Vector<String> vecS = new Vector<>(); System.out.print("Entrer votre matricule \n~$> "); matricule = scanner.next(); boolean cont=true; while (cont) { System.out.print("\nChoisissez parmis les options suivantes :\n\t(1) Affichage du choix de cours courant\n\t(2) Suppression d'un cours\n\t(3) Ajout d'un cours\n\t(4) Validation\n\t(5) Quitter\n~$>"); choice = scanner.nextInt(); switch (choice) { //Affichage du choix de cours courrant case 1: query = "WITH T AS (SELECT DISTINCT C.TITRE,CT.RESPONSABLE,I.SIGLE,I.NUMSECT FROM COURS C,COURSTRIM CT,INSCRIPTION I WHERE C.SIGLE = I.SIGLE AND C.SIGLE = CT.SIGLE AND I.TRIM = '16-3' AND I.MATRICULE = " + matricule +" AND CT.TRIM = '16-3') select T.SIGLE, T.TITRE, T.NUMSECT, P.PRENOM, P.NOM FROM T LEFT JOIN PERSONNE P on (T.RESPONSABLE = P.NAS)"; queryResults = makeJavaGreatAgain.executeQuery(query); System.out.println("CHOIX DE COURS SESSION AUTOMNE 2016"); System.out.println(stringFill("",'-',125)); System.out.println("| SIGLE | TITRE | NUMERO DE SECTION | RESPONSABLE DU COURS |"); System.out.println(stringFill("",'-',125)); while (queryResults.next()) { vecS.add(queryResults.getString("sigle")); vecS.add(queryResults.getString("titre")); vecS.add(queryResults.getString("numsect")); vecS.add(queryResults.getString("prenom") + " " + queryResults.getString("nom")); System.out.println(formatString(vecS)); vecS.clear(); } System.out.println(" queryResults.close(); break; //Suppression d'un cours case 2: System.out.println("Vous avez choisi: Suppression d'un cours.\nVeuillez entrer le sigle du cours à retirer: \n~$>"); sigle = scanner.next(); query = "SELECT DISTINCT C.TITRE FROM COURS C WHERE C.SIGLE = '" + sigle + "'"; queryResults = makeJavaGreatAgain.executeQuery(query); if(queryResults.next()) { cours = sigle + ": " + queryResults.getString("TITRE"); } else { System.out.println(sigle + " n'est pas un sigle valide, la suppression de cours a été annulée. \n"); queryResults.close(); break; } query = "SELECT I.SIGLE FROM INSCRIPTION I WHERE I.TRIM = '16-3' AND I.MATRICULE = '" + matricule + "' AND I.SIGLE = '" + sigle + "'"; queryResults = makeJavaGreatAgain.executeQuery(query); if (queryResults.next()) { //Si on confirme, on supprime le cours de l'inscription System.out.println("Voulez-vous vraiment supprimer le cours? "+ cours +"\n\t(1) oui\n\t(2) non\n~$> "); choice = scanner.nextInt(); if(choice == 1) { query = "DELETE FROM INSCRIPTION I WHERE I.TRIM = '16-3' AND I.MATRICULE = '" + matricule + "' AND I.SIGLE = '" + sigle + "'"; makeJavaGreatAgain.executeQuery(query); System.out.println("Le cours " + cours + ", à été supprimé avec succès.\n"); } else{ System.out.println("Le cours " + cours + " n'a pas été supprimé.\n"); } } else { System.out.println("Le cours " + cours + " ne peut pas être supprimé, car il n'est pas dans votre choix de cours.\n"); } queryResults.close(); break; // Ajout d'un cours case 3: System.out.println("Vous avez choisi: Ajout d'un cours.\nVeuillez entrer le sigle du cours à ajouter. \n"+ "~$>"); sigle = scanner.next(); query = "SELECT DISTINCT C.TITRE FROM COURS C WHERE C.SIGLE = '" + sigle + "'"; queryResults = makeJavaGreatAgain.executeQuery(query); if(queryResults.next()) { cours = sigle + ": " + queryResults.getString("TITRE"); } else { System.out.println(sigle + " n'est pas un sigle valide, l'ajout de cours a été annulée \n"); queryResults.close(); break; } query = "SELECT LEPREREQUIS FROM PREREQUIS PR WHERE PR.SIGLE = '" + sigle + "' AND LEPREREQUIS NOT IN (SELECT SIGLE FROM INSCRIPTION I WHERE I.MATRICULE = '"+matricule+"' AND TRIM <> '16-3')"; queryResults = makeJavaGreatAgain.executeQuery(query); if(queryResults.next()){ System.out.println("Impossible d'ajouter le cours " + cours +", car il vous manque le(s) cours suivant(s):\t" ); do { System.out.println("\t"+ queryResults.getString("LEPREREQUIS")); } while(queryResults.next()); queryResults.close(); break; } //Ajouter le cours aux choix de cours break; // Validation case 4: connexion.commit(); break; // Quitter case 5: cont = false; break; } } makeJavaGreatAgain.close(); connexion.close(); } catch(ClassNotFoundException ex) { System.out.println("Pilote JDBC non trouvé" + ex.getMessage()); } catch(SQLException ex) { System.out.println("Connexion impossible" + ex.getMessage()); ex.printStackTrace(); } } } // Statement monSelect = maConnexion.createStatement(); ResultSet resSelect = monSelect.executeQuery // ("SELECT cid, cname, city FROM Customers");
package br.com.caelum.vraptor.interceptor; import static com.google.common.base.Objects.firstNonNull; import java.lang.reflect.Method; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; @ApplicationScoped public class InterceptorAcceptsExecutor { private final InterceptorMethodParametersResolver parameterResolver; private final StepInvoker invoker; /** * @deprecated CDI eyes only */ public InterceptorAcceptsExecutor() { this(null, null); } @Inject public InterceptorAcceptsExecutor( InterceptorMethodParametersResolver parameterResolver, StepInvoker invoker) { this.parameterResolver = parameterResolver; this.invoker = invoker; } public Boolean accepts(Object interceptor, Method method) { if(method != null) { Object[] params = parameterResolver.parametersFor(method); Object returnObject = invoker.tryToInvoke(interceptor, method, params); return firstNonNull((Boolean) returnObject, false); } return true; } }
package net.echinopsii.ariane.community.core.directory.wat; import net.echinopsii.ariane.community.core.portal.base.plugin.FaceletsResourceResolverService; import net.echinopsii.ariane.community.core.portal.base.plugin.FacesMBeanRegistry; import net.echinopsii.ariane.community.core.portal.base.model.MainMenuEntity; import net.echinopsii.ariane.community.core.portal.base.model.MenuEntityType; import net.echinopsii.ariane.community.core.portal.base.model.TreeMenuEntity; import net.echinopsii.ariane.community.core.portal.base.plugin.MainMenuEntityRegistry; import net.echinopsii.ariane.community.core.portal.base.plugin.RestResourceRegistry; import net.echinopsii.ariane.community.core.portal.base.plugin.TreeMenuRootsRegistry; import org.apache.felix.ipojo.annotations.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URL; import java.util.ArrayList; @Component @Provides(properties= {@StaticServiceProperty(name="targetArianeComponent", type="java.lang.String", value="Portal")}) @Instantiate public class DirectoryBootstrap implements FaceletsResourceResolverService { private static final Logger log = LoggerFactory.getLogger(DirectoryBootstrap.class); private static final String DIRECTORY_COMPONENT = "Ariane Directory Component"; protected static ArrayList<MainMenuEntity> directoryMainMenuEntityList = new ArrayList<MainMenuEntity>() ; protected static ArrayList<TreeMenuEntity> directoryTreeEntityList = new ArrayList<TreeMenuEntity>() ; private static String MAIN_MENU_DIRECTORY_CONTEXT; private static final int MAIN_MENU_DIR_RANK = 2; private static final String basePath = "/META-INF"; private static final String FACES_CONFIG_FILE_PATH = basePath + "/faces-config.xml"; private static final String REST_EP_FILE_PATH = basePath + "/rest.endpoints"; @Requires(from="ArianePortalFacesMBeanRegistry") private FacesMBeanRegistry portalPluginFacesMBeanRegistry = null; @Requires(from="DirectoryMenuRootsTreeRegistryImpl") private TreeMenuRootsRegistry treeMenuRootsRegistry = null; @Requires private MainMenuEntityRegistry mainMenuEntityRegistry = null; @Requires private RestResourceRegistry restResourceRegistry = null; @Bind public void bindRestResourceRegistry(RestResourceRegistry r) { log.debug("Bound to rest resource registry..."); restResourceRegistry = r; } @Unbind public void unbindRestResourceRegistry() { log.debug("Bound to rest resource registry..."); restResourceRegistry = null; } @Bind public void bindMainMenuEntityRegistry(MainMenuEntityRegistry r) { log.debug("Bound to main menu item registry..."); mainMenuEntityRegistry = r; } @Unbind public void unbindMainMenuEntityRegistry() { log.debug("Unbound from main menu item registry..."); mainMenuEntityRegistry = null; } @Bind(from="ArianePortalFacesMBeanRegistry") public void bindPortalPluginFacesMBeanRegistry(FacesMBeanRegistry r) { log.debug("Bound to portal plugin faces managed bean registry..."); portalPluginFacesMBeanRegistry = r; } @Unbind public void unbindPortalPluginFacesMBeanRegistry() { log.debug("Unbound from portal plugin faces managed bean registry..."); portalPluginFacesMBeanRegistry = null; } @Bind(from="DirectoryMenuRootsTreeRegistryImpl") public void bindTreeMenuRootsRegistry(TreeMenuRootsRegistry r) { log.debug("Bound to directory tree menu roots registry..."); treeMenuRootsRegistry = r; } @Unbind public void unbindTreeMenuRootsRegistry() { log.debug("Unbound from directory tree menu roots registry..."); treeMenuRootsRegistry = null; } @Validate public void validate() throws Exception { restResourceRegistry.registerPluginRestEndpoints(DirectoryBootstrap.class.getResource(REST_EP_FILE_PATH)); portalPluginFacesMBeanRegistry.registerPluginFacesMBeanConfig(DirectoryBootstrap.class.getResource(FACES_CONFIG_FILE_PATH)); MAIN_MENU_DIRECTORY_CONTEXT = portalPluginFacesMBeanRegistry.getRegisteredServletContext().getContextPath()+"/"; try { MainMenuEntity mainMenuEntity = new MainMenuEntity("directoriesMItem", "Directories", MAIN_MENU_DIRECTORY_CONTEXT + "views/directories/main.jsf", MenuEntityType.TYPE_MENU_ITEM, MAIN_MENU_DIR_RANK, "icon-directories-ariane"); mainMenuEntity.getDisplayRoles().add("ntwadmin"); mainMenuEntity.getDisplayRoles().add("sysadmin"); mainMenuEntity.getDisplayRoles().add("orgadmin"); mainMenuEntity.getDisplayRoles().add("ntwreviewer"); mainMenuEntity.getDisplayRoles().add("sysreviewer"); mainMenuEntity.getDisplayRoles().add("orgreviewer"); mainMenuEntity.getDisplayPermissions().add("dirComITiNtwDC:display"); mainMenuEntity.getDisplayPermissions().add("dirComITiNtwMarea:display"); mainMenuEntity.getDisplayPermissions().add("dirComITiNtwSubnet:display"); mainMenuEntity.getDisplayPermissions().add("dirComITiNtwIPAddress:display"); mainMenuEntity.getDisplayPermissions().add("dirComITiNtwNIC:display"); mainMenuEntity.getDisplayPermissions().add("dirComITiSysOsi:display"); mainMenuEntity.getDisplayPermissions().add("dirComITiSysOst:display"); mainMenuEntity.getDisplayPermissions().add("dirComOrgApp:display"); mainMenuEntity.getDisplayPermissions().add("dirComOrgCompany:display"); mainMenuEntity.getDisplayPermissions().add("dirComOrgEnvironment:display"); mainMenuEntity.getDisplayPermissions().add("dirComOrgTeam:display"); directoryMainMenuEntityList.add(mainMenuEntity); mainMenuEntityRegistry.registerMainLeftMenuEntity(mainMenuEntity); treeMenuRootsRegistry.setLinkedMainMenuEntity(mainMenuEntity); log.debug("{} has registered its main menu items", new Object[]{DIRECTORY_COMPONENT}); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } try { TreeMenuEntity commonRootTreeMenuEntity = new TreeMenuEntity().setId("commonsDir").setValue("Common").setType(MenuEntityType.TYPE_MENU_SUBMENU). addDisplayRole("ntwadmin").addDisplayRole("sysadmin").addDisplayRole("orgadmin"). addDisplayRole("ntwreviewer").addDisplayRole("sysreviewer").addDisplayRole("orgreviewer"). addDisplayPermission("dirComITiNtwDC:display").addDisplayPermission("dirComITiNtwRarea:display"). addDisplayPermission("dirComITiNtwSubnet:display").addDisplayPermission("dirComITiNtwIPAddress:display"). addDisplayPermission("dirComITiNtwNIC:display").addDisplayPermission("dirComITiSysOsi:display"). addDisplayPermission("dirComITiSysOst:display").addDisplayPermission("dirComOrgApp:display"). addDisplayPermission("dirComOrgCompany:display").addDisplayPermission("dirComOrgEnvironment:display"). addDisplayPermission("dirComOrgTeam:display"); directoryTreeEntityList.add(commonRootTreeMenuEntity); treeMenuRootsRegistry.registerTreeMenuRootEntity(commonRootTreeMenuEntity); TreeMenuEntity organisationalTreeMenuEntity = new TreeMenuEntity().setId("commonsOrgDir").setValue("Organisation"). setType(MenuEntityType.TYPE_MENU_SUBMENU). setParentTreeMenuEntity(commonRootTreeMenuEntity). addDisplayRole("orgadmin").addDisplayRole("orgreviewer"). addDisplayPermission("dirComOrgApp:display").addDisplayPermission("dirComOrgCompany:display"). addDisplayPermission("dirComOrgEnvironment:display").addDisplayPermission("dirComOrgTeam:display"); commonRootTreeMenuEntity.addChildTreeMenuEntity(organisationalTreeMenuEntity); organisationalTreeMenuEntity.addChildTreeMenuEntity(new TreeMenuEntity().setId("applicationTreeID").setValue("Application").setParentTreeMenuEntity(organisationalTreeMenuEntity).setIcon("arianeico-appplications-ariane"). setType(MenuEntityType.TYPE_MENU_ITEM).setContextAddress(MAIN_MENU_DIRECTORY_CONTEXT + "views/directories/application.jsf"). setDescription("Your IT applications definitions"). addDisplayRole("orgadmin").addDisplayRole("orgreviewer").addDisplayPermission("dirComOrgApp:display")). addChildTreeMenuEntity(new TreeMenuEntity().setId("teamTreeID").setValue("Team").setParentTreeMenuEntity(organisationalTreeMenuEntity).setIcon("icon-group"). setType(MenuEntityType.TYPE_MENU_ITEM).setContextAddress(MAIN_MENU_DIRECTORY_CONTEXT + "views/directories/team.jsf"). setDescription("Your teams (ops, devs, ...) definitions"). addDisplayRole("orgreviewer").addDisplayRole("orgadmin").addDisplayPermission("dirComOrgTeam:display")). addChildTreeMenuEntity(new TreeMenuEntity().setId("companyTreeID").setValue("Company").setParentTreeMenuEntity(organisationalTreeMenuEntity).setIcon("icon-building"). setType(MenuEntityType.TYPE_MENU_ITEM).setContextAddress(MAIN_MENU_DIRECTORY_CONTEXT + "views/directories/company.jsf"). setDescription("Definition of companies involved in your IT system (yours included)"). addDisplayRole("orgreviewer").addDisplayRole("orgadmin").addDisplayPermission("dirComOrgCompany:display")). addChildTreeMenuEntity(new TreeMenuEntity().setId("environmentTreeID").setValue("Environment").setParentTreeMenuEntity(organisationalTreeMenuEntity).setIcon("icon-tag"). setType(MenuEntityType.TYPE_MENU_ITEM).setContextAddress(MAIN_MENU_DIRECTORY_CONTEXT + "views/directories/environment.jsf"). setDescription("Your IT environment (development, homologation, QA, production ...)"). addDisplayRole("orgreviewer").addDisplayRole("orgadmin").addDisplayPermission("dirComOrgEnvironment:display")); TreeMenuEntity technicalTreeMenuEntity = new TreeMenuEntity().setId("commonsTechDir").setValue("IT infrastructure"). setType(MenuEntityType.TYPE_MENU_SUBMENU). setParentTreeMenuEntity(commonRootTreeMenuEntity). addDisplayRole("ntwadmin").addDisplayRole("sysadmin"). addDisplayRole("ntwreviewer").addDisplayRole("sysreviewer").addDisplayPermission("dirComITiNtwSubnet:display").addDisplayPermission("dirComITiNtwIPAddress:display"). addDisplayPermission("dirComITiNtwDC:display").addDisplayPermission("dirComITiNtwRarea:display"); commonRootTreeMenuEntity.addChildTreeMenuEntity(technicalTreeMenuEntity); TreeMenuEntity networkTreeMenuEntity = new TreeMenuEntity().setId("commontNtwDir").setValue("Network"). setType(MenuEntityType.TYPE_MENU_SUBMENU). setParentTreeMenuEntity(technicalTreeMenuEntity). addDisplayRole("ntwreviewer").addDisplayRole("ntwadmin"). addDisplayPermission("dirComITiNtwDC:display").addDisplayPermission("dirComITiNtwRarea:display"); technicalTreeMenuEntity.addChildTreeMenuEntity(networkTreeMenuEntity); networkTreeMenuEntity.addChildTreeMenuEntity(new TreeMenuEntity().setId("datacenterTreeID").setValue("Datacenter").setParentTreeMenuEntity(networkTreeMenuEntity).setIcon("arianeico-datacenter-ariane"). setType(MenuEntityType.TYPE_MENU_ITEM).setContextAddress(MAIN_MENU_DIRECTORY_CONTEXT + "views/directories/datacenter.jsf"). setDescription("Your datacenters definitions").addDisplayRole("ntwreviewer").addDisplayRole("ntwadmin"). addDisplayPermission("dirComITiNtwDC:display")). addChildTreeMenuEntity(new TreeMenuEntity().setId("subnetTreeID").setValue("Subnet").setParentTreeMenuEntity(networkTreeMenuEntity).setIcon("arianeico-subnet-ariane"). setType(MenuEntityType.TYPE_MENU_ITEM).setContextAddress(MAIN_MENU_DIRECTORY_CONTEXT + "views/directories/subnet.jsf"). setDescription("Your subnets definitions").addDisplayRole("ntwreviewer").addDisplayRole("ntwadmin"). addDisplayPermission("dirComITiNtwSubnet:display")). addChildTreeMenuEntity(new TreeMenuEntity().setId("multicastAreaTreeID").setValue("Routing Area").setParentTreeMenuEntity(networkTreeMenuEntity).setIcon("arianeico-routingarea-ariane"). setType(MenuEntityType.TYPE_MENU_ITEM).setContextAddress(MAIN_MENU_DIRECTORY_CONTEXT + "views/directories/routingArea.jsf"). setDescription("Your routing areas definitions").addDisplayRole("ntwreviewer").addDisplayRole("ntwadmin"). addDisplayPermission("dirComITiNtwRarea:display")). addChildTreeMenuEntity(new TreeMenuEntity().setId("ipAddressTreeID").setValue("IP Address").setParentTreeMenuEntity(networkTreeMenuEntity).setIcon("icon-ellipsis-horizontal"). setType(MenuEntityType.TYPE_MENU_ITEM).setContextAddress(MAIN_MENU_DIRECTORY_CONTEXT + "views/directories/ipAddress.jsf"). setDescription("Your IP Addresses definitions").addDisplayRole("ntwreviewer").addDisplayRole("ntwadmin"). addDisplayPermission("dirComITiNtwIPAddress:display")). addChildTreeMenuEntity(new TreeMenuEntity().setId("nicTreeID").setValue("NIC").setParentTreeMenuEntity(networkTreeMenuEntity).setIcon("icon-external-link"). setType(MenuEntityType.TYPE_MENU_ITEM).setContextAddress(MAIN_MENU_DIRECTORY_CONTEXT + "views/directories/nic.jsf"). setDescription("Your Network interface card definitions").addDisplayRole("ntwreviewer").addDisplayRole("ntwadmin"). addDisplayPermission("dirComITiNtwNIC:display")); TreeMenuEntity systemTreeMenuEntity = new TreeMenuEntity().setId("commonSysDir").setValue("System"). setType(MenuEntityType.TYPE_MENU_SUBMENU). setParentTreeMenuEntity(technicalTreeMenuEntity). addDisplayRole("sysreviewer").addDisplayRole("sysadmin").addDisplayPermission("dirComITiSysOsi:display"). addDisplayPermission("dirComITiSysOst:display"); technicalTreeMenuEntity.addChildTreeMenuEntity(systemTreeMenuEntity); systemTreeMenuEntity.addChildTreeMenuEntity(new TreeMenuEntity().setId("OSInstanceTreeID").setValue("OS Instance").setParentTreeMenuEntity(systemTreeMenuEntity).setIcon("arianeico-os-instances-ariane"). setType(MenuEntityType.TYPE_MENU_ITEM).setContextAddress(MAIN_MENU_DIRECTORY_CONTEXT + "views/directories/OSInstance.jsf"). setDescription("Your OS instances definitions").addDisplayRole("sysreviewer").addDisplayRole("sysadmin"). addDisplayPermission("dirComITiSysOsi:display")). addChildTreeMenuEntity(new TreeMenuEntity().setId("OSTypeTreeID").setValue("OS Type").setParentTreeMenuEntity(systemTreeMenuEntity).setIcon("icon-tag"). setType(MenuEntityType.TYPE_MENU_ITEM).setContextAddress(MAIN_MENU_DIRECTORY_CONTEXT + "views/directories/OSType.jsf"). setDescription("Your OS types definitions").addDisplayRole("sysreviewer").addDisplayRole("sysadmin"). addDisplayPermission("dirComITiSysOst:display")). addChildTreeMenuEntity(new TreeMenuEntity().setId("SysIPAddressTreeID").setValue("IP Address").setParentTreeMenuEntity(systemTreeMenuEntity).setIcon("icon-ellipsis-horizontal"). setType(MenuEntityType.TYPE_MENU_ITEM).setContextAddress(MAIN_MENU_DIRECTORY_CONTEXT + "views/directories/ipAddress.jsf"). setDescription("Your IP Addresses definitions").addDisplayRole("sysreviewer").addDisplayRole("sysadmin"). addDisplayPermission("dirComITiNtwIPAddress:display")). addChildTreeMenuEntity(new TreeMenuEntity().setId("SysNICTreeID").setValue("NIC").setParentTreeMenuEntity(systemTreeMenuEntity).setIcon("icon-external-link"). setType(MenuEntityType.TYPE_MENU_ITEM).setContextAddress(MAIN_MENU_DIRECTORY_CONTEXT + "views/directories/nic.jsf"). setDescription("Your Network interface card definitions").addDisplayRole("sysreviewer").addDisplayRole("sysadmin"). addDisplayPermission("dirComITiSysNIC:display")); log.debug("{} has registered its commons directory items", new Object[]{DIRECTORY_COMPONENT}); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } log.info("{} is started", new Object[]{DIRECTORY_COMPONENT}); } @Invalidate public void invalidate() throws Exception { if (mainMenuEntityRegistry!=null) { for(MainMenuEntity entity : directoryMainMenuEntityList) { mainMenuEntityRegistry.unregisterMainLeftMenuEntity(entity); } } directoryMainMenuEntityList.clear(); if (treeMenuRootsRegistry!=null) { for(TreeMenuEntity entity : directoryTreeEntityList) { treeMenuRootsRegistry.unregisterTreeMenuRootEntity(entity); } } directoryTreeEntityList.clear(); restResourceRegistry.unregisterPluginRestEndpoints(DirectoryBootstrap.class.getResource(REST_EP_FILE_PATH)); log.info("{} is stopped", new Object[]{DIRECTORY_COMPONENT}); } @Override public URL resolveURL(String path) { log.debug("Resolve {} from directory wat...", new Object[]{path}); return DirectoryBootstrap.class.getResource(basePath + path); } }
package org.weasis.dicom.viewer2d; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseWheelEvent; import java.util.ArrayList; import javax.swing.BoundedRangeModel; import javax.swing.event.ChangeEvent; import org.noos.xing.mydoggy.Content; import org.osgi.service.prefs.Preferences; import org.weasis.core.api.gui.util.ActionState; import org.weasis.core.api.gui.util.ActionW; import org.weasis.core.api.gui.util.ComboItemListener; import org.weasis.core.api.gui.util.GuiExecutor; import org.weasis.core.api.gui.util.SliderChangeListener; import org.weasis.core.api.gui.util.SliderCineListener; import org.weasis.core.api.gui.util.SliderCineListener.TIME; import org.weasis.core.api.gui.util.ToggleButtonListener; import org.weasis.core.api.image.GridBagLayoutModel; import org.weasis.core.api.image.op.ByteLut; import org.weasis.core.api.image.util.KernelData; import org.weasis.core.api.media.data.ImageElement; import org.weasis.core.api.media.data.MediaElement; import org.weasis.core.api.media.data.MediaSeries; import org.weasis.core.api.media.data.MediaSeries.MEDIA_POSITION; import org.weasis.core.api.media.data.Series; import org.weasis.core.api.media.data.TagW; import org.weasis.core.api.service.BundlePreferences; import org.weasis.core.ui.docking.PluginTool; import org.weasis.core.ui.docking.UIManager; import org.weasis.core.ui.editor.SeriesViewerEvent; import org.weasis.core.ui.editor.SeriesViewerEvent.EVENT; import org.weasis.core.ui.editor.image.DefaultView2d; import org.weasis.core.ui.editor.image.ImageViewerEventManager; import org.weasis.core.ui.editor.image.ImageViewerPlugin; import org.weasis.core.ui.editor.image.MeasureToolBar; import org.weasis.core.ui.editor.image.PannerListener; import org.weasis.core.ui.editor.image.SynchView; import org.weasis.core.ui.editor.image.SynchView.Mode; import org.weasis.core.ui.graphic.Graphic; import org.weasis.core.ui.graphic.model.AbstractLayer; import org.weasis.core.ui.graphic.model.GraphicsListener; import org.weasis.core.ui.graphic.model.Tools; import org.weasis.dicom.codec.DicomImageElement; import org.weasis.dicom.codec.SortSeriesStack; import org.weasis.dicom.codec.display.LutManager; import org.weasis.dicom.codec.display.PresetWindowLevel; import org.weasis.dicom.codec.display.ViewingProtocols; import org.weasis.dicom.codec.geometry.ImageOrientation; import org.weasis.dicom.viewer2d.internal.Activator; /** * The event processing center for this application. This class responses for loading data sets, processing the events * from the utility menu that includes changing the operation scope, the layout, window/level, rotation angle, zoom * factor, starting/stoping the cining-loop and etc. * */ public class EventManager extends ImageViewerEventManager<DicomImageElement> implements ActionListener { private static ActionW[] keyEventActions = { ActionW.ZOOM, ActionW.SCROLL_SERIES, ActionW.ROTATION, ActionW.WINLEVEL, ActionW.PAN, ActionW.MEASURE, ActionW.CONTEXTMENU }; /** The single instance of this singleton class. */ private static EventManager instance; private final SliderCineListener moveTroughSliceAction; private final SliderChangeListener windowAction; private final SliderChangeListener levelAction; private final SliderChangeListener rotateAction; private final SliderChangeListener zoomAction; private final SliderChangeListener lensZoomAction; private final ToggleButtonListener flipAction; private final ToggleButtonListener inverseLutAction; private final ToggleButtonListener inverseStackAction; private final ToggleButtonListener showLensAction; private final ToggleButtonListener imageOverlayAction; private final ToggleButtonListener drawOnceAction; private final ComboItemListener presetAction; private final ComboItemListener lutAction; private final ComboItemListener filterAction; private final ComboItemListener sortStackAction; private final ComboItemListener viewingProtocolAction; private final ComboItemListener layoutAction; private final ComboItemListener synchAction; private final ComboItemListener measureAction; private final PannerListener panAction; public final static ArrayList<SynchView> SYNCH_LIST = new ArrayList<SynchView>(); static { SYNCH_LIST.add(SynchView.NONE); SYNCH_LIST.add(SynchView.DEFAULT_STACK); SYNCH_LIST.add(SynchView.DEFAULT_TILE); } /** * Return the single instance of this class. This method guarantees the singleton property of this class. */ public static synchronized EventManager getInstance() { if (instance == null) { instance = new EventManager(); } return instance; } /** * The default private constructor to guarantee the singleton property of this class. */ private EventManager() { iniAction(moveTroughSliceAction = getMoveTroughSliceAction(20, TIME.second, 0.1)); iniAction(windowAction = newWindowAction()); iniAction(levelAction = newLevelAction()); iniAction(rotateAction = newRotateAction()); iniAction(zoomAction = newZoomAction()); iniAction(flipAction = newFlipAction()); iniAction(inverseLutAction = newInverseLutAction()); iniAction(inverseStackAction = newInverseStackAction()); iniAction(showLensAction = newLensAction()); iniAction(lensZoomAction = newLensZoomAction()); iniAction(imageOverlayAction = newImageOverlayAction()); iniAction(drawOnceAction = newDrawOnlyOnceAction()); iniAction(presetAction = newPresetAction()); iniAction(lutAction = newLutAction()); iniAction(filterAction = newFilterAction()); iniAction(sortStackAction = newSortStackAction()); iniAction(viewingProtocolAction = newViewingProtocolAction()); iniAction(layoutAction = newLayoutAction(View2dContainer.MODELS)); iniAction(synchAction = newSynchAction(SYNCH_LIST.toArray(new SynchView[SYNCH_LIST.size()]))); iniAction(measureAction = newMeasurementAction(MeasureToolBar.graphicList.toArray(new Graphic[MeasureToolBar.graphicList.size()]))); iniAction(panAction = newPanAction()); Preferences prefs = Activator.PREFERENCES.getDefaultPreferences(); zoomSetting.applyPreferences(prefs); viewSetting.applyPreferences(prefs); mouseActions.applyPreferences(prefs); if (prefs != null) { Preferences prefNode = prefs.node("mouse.sensivity"); //$NON-NLS-1$ windowAction.setMouseSensivity(prefNode.getDouble(windowAction.getActionW().cmd(), 1.25)); levelAction.setMouseSensivity(prefNode.getDouble(levelAction.getActionW().cmd(), 1.25)); moveTroughSliceAction.setMouseSensivity(prefNode.getDouble(moveTroughSliceAction.getActionW().cmd(), 0.1)); rotateAction.setMouseSensivity(prefNode.getDouble(rotateAction.getActionW().cmd(), 0.25)); zoomAction.setMouseSensivity(prefNode.getDouble(zoomAction.getActionW().cmd(), 0.1)); } initializeParameters(); } private void iniAction(ActionState action) { actions.put(action.getActionW(), action); } private void initializeParameters() { enableActions(false); windowAction.getModel().addChangeListener(presetAction); levelAction.getModel().addChangeListener(presetAction); } private ComboItemListener newFilterAction() { return new ComboItemListener(ActionW.FILTER, KernelData.ALL_FILTERS) { @Override public void itemStateChanged(Object object) { if (object instanceof KernelData) { firePropertyChange(action.cmd(), null, object); } } }; } @Override protected SliderCineListener getMoveTroughSliceAction(int speed, TIME time, double mouseSensivity) { return new SliderCineListener(ActionW.SCROLL_SERIES, 1, 2, 1, speed, time, mouseSensivity) { protected CineThread currentCine; @Override public void stateChanged(BoundedRangeModel model) { int index = model.getValue() - 1; Series series = null; ImageElement image = null; if (selectedView2dContainer != null) { DefaultView2d selectedImagePane = selectedView2dContainer.getSelectedImagePane(); if (selectedImagePane.getSeries() instanceof Series) { series = (Series) selectedImagePane.getSeries(); MediaElement media = series.getMedia(index); if (media instanceof ImageElement) { image = (ImageElement) media; if (image != null) { int min = (int) image.getMinValue(); int max = (int) image.getMaxValue(); if (min == 0 && max == 0) { // media.getImage() will load the image to determine the min and the max value image.getImage(); min = (int) image.getMinValue(); max = (int) image.getMaxValue(); } if (PresetWindowLevel.DEFAULT.equals(presetAction.getSelectedItem())) { windowAction.getModel().removeChangeListener(presetAction); levelAction.getModel().removeChangeListener(presetAction); windowAction.setMinMaxValueWithoutTriggerAction(0, (max - min), (int) image.getDefaultWindow()); levelAction.setMinMaxValueWithoutTriggerAction(min, max, (int) image.getDefaultLevel()); windowAction.getModel().addChangeListener(presetAction); levelAction.getModel().addChangeListener(presetAction); } else if (PresetWindowLevel.AUTO.equals(presetAction.getSelectedItem())) { windowAction.getModel().removeChangeListener(presetAction); levelAction.getModel().removeChangeListener(presetAction); windowAction.setMinMaxValueWithoutTriggerAction(0, max - min, max - min); levelAction.setMinMaxValueWithoutTriggerAction(min, max, (max - min) / 2 + min); windowAction.getModel().addChangeListener(presetAction); levelAction.getModel().addChangeListener(presetAction); } } } } } Number location = index; GridBagLayoutModel layout = (GridBagLayoutModel) layoutAction.getSelectedItem(); ActionState synch = getAction(ActionW.SYNCH); if (image != null && View2dFactory.getViewTypeNumber(layout, DefaultView2d.class) > 1 && synch instanceof ComboItemListener) { SynchView synchview = (SynchView) ((ComboItemListener) synch).getSelectedItem(); if (synchview.isActionEnable(ActionW.SCROLL_SERIES)) { double[] val = (double[]) image.getTagValue(TagW.SlicePosition); if (val != null) { location = val[0] + val[1] + val[2]; } } else { final ArrayList<DefaultView2d<DicomImageElement>> panes = selectedView2dContainer.getImagePanels(); for (DefaultView2d<DicomImageElement> p : panes) { Boolean cutlines = (Boolean) p.getActionValue(ActionW.SYNCH_CROSSLINE.cmd()); if (cutlines != null && cutlines) { double[] val = (double[]) image.getTagValue(TagW.SlicePosition); if (val != null) { location = val[0] + val[1] + val[2]; } else return; // Do not throw event because break; } } } } // Model contains display value, value-1 is the index value of a sequence firePropertyChange(action.cmd(), null, location); if (image != null) { fireSeriesViewerListeners(new SeriesViewerEvent(selectedView2dContainer, series, image, EVENT.SELECT)); } } @Override public void setSpeed(int speed) { super.setSpeed(speed); if (currentCine != null) { currentCine.iniSpeed(); } } /** Create a thread to cine the images. */ class CineThread extends Thread { private volatile int iteration; private volatile int wait; private volatile int currentCineRate; private volatile long start; private volatile boolean cining = true; @Override public void run() { iniSpeed(); // Create a robot to monitor the paint // Robot robot = null; // try { // robot = new java.awt.Robot(); // catch (Exception e) { while (cining) { GuiExecutor.instance().execute(new Runnable() { @Override public void run() { if (cining) { int frameIndex = getValue() + 1; frameIndex = frameIndex > getMax() ? 0 : frameIndex; setValue(frameIndex); } } }); iteration++; // Wait until the paint is finished // robot.waitForIdle(); // adjust the delay time based on the current performance long elapsed = (System.currentTimeMillis() - start) / 1000; if (elapsed > 0) { currentCineRate = (int) (iteration / elapsed); // System.out.println("fps:" + fps); if (currentCineRate < getSpeed()) { wait } else { wait++; } if (wait < 0) { wait = 0; } } // wait if (wait > 0) { try { Thread.sleep(wait); } catch (Exception e) { } } } } public void iniSpeed() { iteration = 0; currentCineRate = getSpeed(); wait = 1000 / currentCineRate; start = System.currentTimeMillis(); } public int getCurrentCineRate() { return currentCineRate; } } /** Start the cining. */ @Override public synchronized void start() { if (currentCine != null) { stop(); } if (getMax() - getMin() > 0) { currentCine = new CineThread(); currentCine.start(); } } /** Stop the cining. */ @Override public synchronized void stop() { CineThread moribund = currentCine; currentCine = null; if (moribund != null) { moribund.cining = false; moribund.interrupt(); } } @Override public void mouseWheelMoved(MouseWheelEvent e) { setValue(getValue() + e.getWheelRotation()); } @Override public int getCurrentCineRate() { if (currentCine != null) return currentCine.getCurrentCineRate(); return 0; } }; } private ComboItemListener newPresetAction() { return new ComboItemListener(ActionW.PRESET, PresetWindowLevel.getPresetCollection("UNKOWN")) { //$NON-NLS-1$ @Override public void itemStateChanged(Object object) { if (object instanceof PresetWindowLevel) { windowAction.getModel().removeChangeListener(this); levelAction.getModel().removeChangeListener(this); ImageElement img = null; if (selectedView2dContainer != null) { img = selectedView2dContainer.getSelectedImagePane().getImage(); } if (img == null) return; PresetWindowLevel preset = (PresetWindowLevel) object; if (preset.equals(PresetWindowLevel.DEFAULT)) { windowAction.setValue((int) img.getDefaultWindow()); levelAction.setValue((int) img.getDefaultLevel()); } else if (preset.equals(PresetWindowLevel.AUTO)) { int min = (int) img.getMinValue(); int max = (int) img.getMaxValue(); windowAction.setValue(max - min); levelAction.setValue((max - min) / 2 + min); } else if (!preset.equals(PresetWindowLevel.CUSTOM)) { windowAction.setValue((int) preset.getWindow()); levelAction.setValue((int) preset.getLevel()); } firePropertyChange(action.cmd(), null, preset); windowAction.getModel().addChangeListener(this); levelAction.getModel().addChangeListener(this); } } @Override public void stateChanged(ChangeEvent evt) { model.removeListDataListener(this); model.setSelectedItem(PresetWindowLevel.CUSTOM); model.addListDataListener(this); firePropertyChange(action.cmd(), null, PresetWindowLevel.CUSTOM); } }; } private ComboItemListener newLutAction() { return new ComboItemListener(ActionW.LUT, LutManager.getLutCollection()) { @Override public void itemStateChanged(Object object) { if (object instanceof ByteLut) { // customPreset = false; firePropertyChange(action.cmd(), null, object); } } }; } private ToggleButtonListener newImageOverlayAction() { return new ToggleButtonListener(ActionW.IMAGE_OVERLAY, true) { @Override public void actionPerformed(boolean selected) { firePropertyChange(action.cmd(), null, selected); } }; } private ComboItemListener newSortStackAction() { return new ComboItemListener(ActionW.SORTSTACK, SortSeriesStack.getValues()) { @Override public void itemStateChanged(Object object) { firePropertyChange(action.cmd(), null, object); } }; } private ComboItemListener newViewingProtocolAction() { return new ComboItemListener(ActionW.VIEWINGPROTOCOL, ViewingProtocols.getValues()) { @Override public void itemStateChanged(Object object) { firePropertyChange(action.cmd(), null, object); } }; } @Override protected ToggleButtonListener newInverseStackAction() { return new ToggleButtonListener(ActionW.INVERSESTACK, false) { @Override public void actionPerformed(boolean selected) { firePropertyChange(action.cmd(), null, selected); } }; } @Override public ActionW getActionFromkeyEvent(int keyEvent) { if (keyEvent != 0) { for (ActionW a : keyEventActions) { if (a.getKeyCode() == keyEvent) return a; } } return null; } @Override public void setSelectedView2dContainer(ImageViewerPlugin<DicomImageElement> selectedView2dContainer) { if (this.selectedView2dContainer != null) { this.selectedView2dContainer.setMouseActions(null); this.selectedView2dContainer.setDrawActions(null); moveTroughSliceAction.stop(); } this.selectedView2dContainer = selectedView2dContainer; if (selectedView2dContainer != null) { synchAction.setSelectedItemWithoutTriggerAction(selectedView2dContainer.getSynchView()); layoutAction.setSelectedItemWithoutTriggerAction(selectedView2dContainer.getLayoutModel()); updateComponentsListener(selectedView2dContainer.getSelectedImagePane()); selectedView2dContainer.setMouseActions(mouseActions); Graphic graphic = null; ActionState action = getAction(ActionW.DRAW_MEASURE); if (action instanceof ComboItemListener) { graphic = (Graphic) ((ComboItemListener) action).getSelectedItem(); } selectedView2dContainer.setDrawActions(graphic); } } /** process the action events. */ @Override public void actionPerformed(ActionEvent evt) { String command = evt.getActionCommand(); if (command.equals(ActionW.CINESTART.cmd())) { // turn cining on. moveTroughSliceAction.start(); } else if (command.equals(ActionW.CINESTOP.cmd())) { // turn cine off. moveTroughSliceAction.stop(); } } public void resetAllActions() { firePropertyChange(ActionW.ZOOM.cmd(), null, 0.0); if (selectedView2dContainer != null) { DefaultView2d viewPane = selectedView2dContainer.getSelectedImagePane(); if (viewPane != null) { viewPane.center(); } } presetAction.setSelectedItem(PresetWindowLevel.DEFAULT); flipAction.setSelected(false); rotateAction.setValue(0); inverseLutAction.setSelected(false); lutAction.setSelectedItem(ByteLut.defaultLUT); filterAction.setSelectedItem(KernelData.NONE); } public void reset(ResetTools action) { if (ResetTools.All.equals(action)) { resetAllActions(); } else if (ResetTools.Zoom.equals(action)) { // Pass the value 0.0 (convention: best fit zoom value) directly to the property change, otherwise the // value is adjusted by the BoundedRangeModel firePropertyChange(ActionW.ZOOM.cmd(), null, 0.0); } else if (ResetTools.Rotation.equals(action)) { rotateAction.setValue(0); } else if (ResetTools.WindowLevel.equals(action)) { presetAction.setSelectedItem(PresetWindowLevel.DEFAULT); } else if (ResetTools.Pan.equals(action)) { if (selectedView2dContainer != null) { DefaultView2d viewPane = selectedView2dContainer.getSelectedImagePane(); if (viewPane != null) { viewPane.center(); } } } } @Override public synchronized boolean updateComponentsListener(DefaultView2d<DicomImageElement> defaultView2d) { if (defaultView2d == null) return false; Content selectedContent = UIManager.toolWindowManager.getContentManager().getSelectedContent(); if (selectedContent == null || selectedContent.getComponent() != selectedView2dContainer) return false; if (selectedView2dContainer == null || defaultView2d != selectedView2dContainer.getSelectedImagePane()) return false; // System.out.println(v.getId() + ": udpate"); // selectedView2dContainer.setSelectedImagePane(v); clearAllPropertyChangeListeners(); if (defaultView2d.getSourceImage() == null) { enableActions(false); return false; } if (!enabledAction) { enableActions(true); } ImageElement image = defaultView2d.getImage(); MediaSeries<DicomImageElement> series = defaultView2d.getSeries(); windowAction.setMinMaxValueWithoutTriggerAction(0, (int) (image.getMaxValue() - image.getMinValue()), ((Float) defaultView2d.getActionValue(ActionW.WINDOW.cmd())).intValue()); levelAction.setMinMaxValueWithoutTriggerAction((int) image.getMinValue(), (int) image.getMaxValue(), ((Float) defaultView2d.getActionValue(ActionW.LEVEL.cmd())).intValue()); rotateAction.setValueWithoutTriggerAction((Integer) defaultView2d.getActionValue(ActionW.ROTATION.cmd())); flipAction.setSelectedWithoutTriggerAction((Boolean) defaultView2d.getActionValue(ActionW.FLIP.cmd())); zoomAction.setValueWithoutTriggerAction(viewScaleToSliderValue(Math.abs((Double) defaultView2d .getActionValue(ActionW.ZOOM.cmd())))); showLensAction.setSelectedWithoutTriggerAction((Boolean) defaultView2d.getActionValue(ActionW.LENS.cmd())); Double lensZoom = (Double) defaultView2d.getLensActionValue(ActionW.ZOOM.cmd()); if (lensZoom != null) { lensZoomAction.setValueWithoutTriggerAction(viewScaleToSliderValue(Math.abs(lensZoom))); } PresetWindowLevel[] presets = PresetWindowLevel.getPresetCollection((String) series.getTagValue(TagW.Modality)); presetAction.setDataList(presets); presetAction.setSelectedItemWithoutTriggerAction(defaultView2d.getActionValue(ActionW.PRESET.cmd())); moveTroughSliceAction.setMinMaxValue(1, series.size(), defaultView2d.getFrameIndex() + 1); Integer speed = (Integer) series.getTagValue(TagW.CineRate); if (speed != null) { moveTroughSliceAction.setSpeed(speed); } lutAction.setSelectedItemWithoutTriggerAction(defaultView2d.getActionValue(ActionW.LUT.cmd())); inverseLutAction.setSelectedWithoutTriggerAction((Boolean) defaultView2d.getActionValue(ActionW.INVERSELUT .cmd())); filterAction.setSelectedItemWithoutTriggerAction(defaultView2d.getActionValue(ActionW.FILTER.cmd())); imageOverlayAction.setSelectedWithoutTriggerAction((Boolean) defaultView2d.getActionValue(ActionW.IMAGE_OVERLAY .cmd())); sortStackAction.setSelectedItemWithoutTriggerAction(defaultView2d.getActionValue(ActionW.SORTSTACK.cmd())); viewingProtocolAction.setSelectedItemWithoutTriggerAction(defaultView2d.getActionValue(ActionW.VIEWINGPROTOCOL .cmd())); inverseStackAction.setSelectedWithoutTriggerAction((Boolean) defaultView2d.getActionValue(ActionW.INVERSESTACK .cmd())); // register all actions for the selected view and for the other views register according to synchview. updateAllListeners(selectedView2dContainer, (SynchView) synchAction.getSelectedItem()); for (PluginTool p : selectedView2dContainer.getToolPanel()) { if (p instanceof GraphicsListener) { defaultView2d.getLayerModel().addGraphicSelectionListener((GraphicsListener) p); } } return true; } @Override protected boolean isCompatible(MediaSeries<DicomImageElement> series1, MediaSeries<DicomImageElement> series2) { // Have the two series the same image plane orientation return ImageOrientation.hasSameOrientation(series1, series2); } @Override public void updateAllListeners(ImageViewerPlugin<DicomImageElement> viewerPlugin, SynchView synchView) { clearAllPropertyChangeListeners(); if (viewerPlugin != null) { DefaultView2d<DicomImageElement> viewPane = viewerPlugin.getSelectedImagePane(); // if (viewPane == null || viewPane.getSeries() == null) { if (viewPane == null) return; MediaSeries<DicomImageElement> series = viewPane.getSeries(); if (series != null) { addPropertyChangeListeners(viewPane); final ArrayList<DefaultView2d<DicomImageElement>> panes = viewerPlugin.getImagePanels(); panes.remove(viewPane); viewPane.setActionsInView(ActionW.SYNCH_CROSSLINE.cmd(), false); if (SynchView.NONE.equals(synchView)) { for (int i = 0; i < panes.size(); i++) { DefaultView2d<DicomImageElement> pane = panes.get(i); AbstractLayer layer = pane.getLayerModel().getLayer(Tools.CROSSLINES.getId()); if (layer != null) { layer.deleteAllGraphic(); } MediaSeries<DicomImageElement> s = pane.getSeries(); String fruid = (String) series.getTagValue(TagW.FrameOfReferenceUID); if (s != null && fruid != null) { if (fruid.equals(s.getTagValue(TagW.FrameOfReferenceUID))) { if (!ImageOrientation.hasSameOrientation(series, s)) { pane.setActionsInView(ActionW.SYNCH_CROSSLINE.cmd(), true); propertySupport.addPropertyChangeListener(ActionW.SCROLL_SERIES.cmd(), pane); } // Force to draw crosslines without changing the slice position moveTroughSliceAction.stateChanged(moveTroughSliceAction.getModel()); } } } } else { // TODO if Pan is activated than rotation is required if (Mode.Stack.equals(synchView.getMode())) { boolean hasLink = false; String fruid = (String) series.getTagValue(TagW.FrameOfReferenceUID); DicomImageElement img = series.getMedia(MEDIA_POSITION.MIDDLE); double[] val = img == null ? null : (double[]) img.getTagValue(TagW.SlicePosition); for (int i = 0; i < panes.size(); i++) { DefaultView2d<DicomImageElement> pane = panes.get(i); AbstractLayer layer = pane.getLayerModel().getLayer(Tools.CROSSLINES.getId()); if (layer != null) { layer.deleteAllGraphic(); } MediaSeries<DicomImageElement> s = pane.getSeries(); if (s != null && fruid != null && val != null) { if (fruid.equals(s.getTagValue(TagW.FrameOfReferenceUID))) { if (ImageOrientation.hasSameOrientation(series, s)) { hasLink = true; pane.setActionsInView(ActionW.SYNCH_LINK.cmd(), true); pane.setActionsInView(ActionW.SYNCH_CROSSLINE.cmd(), false); if (hasSameSizeAndSpatialCalibration(series, s)) { // If the image has the same reference and the same spatial calibration, all // the actions are synchronized addPropertyChangeListeners(pane, synchView); } else { propertySupport .addPropertyChangeListener(ActionW.SCROLL_SERIES.cmd(), pane); } } else { pane.setActionsInView(ActionW.SYNCH_LINK.cmd(), false); pane.setActionsInView(ActionW.SYNCH_CROSSLINE.cmd(), true); propertySupport.addPropertyChangeListener(ActionW.SCROLL_SERIES.cmd(), pane); } } } } viewPane.setActionsInView(ActionW.SYNCH_LINK.cmd(), hasLink); // Force to draw crosslines without changing the slice position moveTroughSliceAction.stateChanged(moveTroughSliceAction.getModel()); } else if (Mode.Tile.equals(synchView.getMode())) { for (int i = 0; i < panes.size(); i++) { DefaultView2d<DicomImageElement> pane = panes.get(i); pane.setActionsInView(ActionW.SYNCH_LINK.cmd(), true); pane.setActionsInView(ActionW.SYNCH_CROSSLINE.cmd(), false); addPropertyChangeListeners(pane, synchView); } } } } } } public static boolean hasSameSizeAndSpatialCalibration(MediaSeries<DicomImageElement> series1, MediaSeries<DicomImageElement> series2) { // Test if the two series has the same orientation if (series1 != null && series2 != null) { DicomImageElement image1 = series1.getMedia(MEDIA_POSITION.MIDDLE); DicomImageElement image2 = series2.getMedia(MEDIA_POSITION.MIDDLE); if (image1 != null && image2 != null) return image1.hasSameSizeAndSpatialCalibration(image2); } return false; } public void savePreferences() { Preferences prefs = Activator.PREFERENCES.getDefaultPreferences(); // Default view viewSetting.savePreferences(prefs); // Mouse buttons preferences mouseActions.savePreferences(prefs); if (prefs != null) { // Mouse sensitivity Preferences prefNode = prefs.node("mouse.sensivity"); //$NON-NLS-1$ BundlePreferences.putDoublePreferences(prefNode, windowAction.getActionW().cmd(), windowAction.getMouseSensivity()); BundlePreferences.putDoublePreferences(prefNode, levelAction.getActionW().cmd(), levelAction.getMouseSensivity()); BundlePreferences.putDoublePreferences(prefNode, moveTroughSliceAction.getActionW().cmd(), moveTroughSliceAction.getMouseSensivity()); BundlePreferences.putDoublePreferences(prefNode, rotateAction.getActionW().cmd(), rotateAction.getMouseSensivity()); BundlePreferences.putDoublePreferences(prefNode, zoomAction.getActionW().cmd(), zoomAction.getMouseSensivity()); } } }
/* High level API */ package org.xbill.DNS; import java.util.*; import java.io.*; import java.net.*; /** * High level API for mapping queries to DNS Records. Caching is used * when possible to reduce the number of DNS requests, and a Resolver * is used to perform the queries. A search path can be set or determined * by FindServer, which allows lookups of unqualified names. * @see Resolver * @see FindServer * * @author Brian Wellington */ public final class dns { private static Resolver res; private static Cache cache; private static Name [] searchPath; private static boolean searchPathSet; private static boolean initialized; /* Otherwise the class could be instantiated */ private dns() {} synchronized private static void initialize() { if (initialized) return; if (res == null) { try { setResolver(new ExtendedResolver()); } catch (UnknownHostException uhe) { System.out.println("Failed to initialize resolver"); System.exit(-1); } } if (!searchPathSet) searchPath = FindServer.searchPath(); if (cache == null) cache = new Cache(); } static boolean matchType(short type1, short type2) { return (type1 == Type.ANY || type2 == Type.ANY || type1 == type2); } /** * Converts an InetAddress into the corresponding domain name * (127.0.0.1 -> 1.0.0.127.IN-ADDR.ARPA.) * @return A String containing the domain name. */ public static String inaddrString(InetAddress addr) { byte [] address = addr.getAddress(); StringBuffer sb = new StringBuffer(); for (int i = 3; i >= 0; i sb.append(address[i] & 0xFF); sb.append("."); } sb.append("IN-ADDR.ARPA."); return sb.toString(); } /** * Converts an String containing an IP address in dotted quad form into the * corresponding domain name. * ex. 127.0.0.1 -> 1.0.0.127.IN-ADDR.ARPA. * @return A String containing the domain name. */ public static String inaddrString(String s) { InetAddress address; try { address = InetAddress.getByName(s); } catch (UnknownHostException e) { return null; } return inaddrString(address); } /** * Sets the Resolver to be used by functions in the dns class */ public static synchronized void setResolver(Resolver _res) { res = _res; } /** * Obtains the Resolver used by functions in the dns class. This can be used * to set Resolver properties. */ public static synchronized Resolver getResolver() { initialize(); return res; } /** * Specifies the domains which will be appended to unqualified names before * beginning the lookup process. If this is not set, FindServer will be used. * @see FindServer */ public static synchronized void setSearchPath(String [] domains) { if (domains == null || domains.length == 0) searchPath = null; else { searchPath = new Name[domains.length]; for (int i = 0; i < domains.length; i++) searchPath[i] = new Name(domains[i]); } searchPathSet = true; } /** * Obtains the Cache used by functions in the dns class. This can be used * to perform more specific queries and/or remove elements. */ public static synchronized Cache getCache() { initialize(); return cache; } private static Record [] lookup(Name name, short type, short dclass, byte cred, boolean querysent) { Record [] answers; int answerCount = 0, n = 0; Enumeration e; /*System.out.println("lookup of " + name + " " + Type.string(type));*/ SetResponse cached = cache.lookupRecords(name, type, dclass, cred); /*System.out.println(cached);*/ if (cached.isSuccessful()) { RRset [] rrsets = cached.answers(); answerCount = 0; for (int i = 0; i < rrsets.length; i++) answerCount += rrsets[i].size(); answers = new Record[answerCount]; for (int i = 0; i < rrsets.length; i++) { e = rrsets[i].rrs(); while (e.hasMoreElements()) { Record r = (Record)e.nextElement(); answers[n++] = r; } } } else if (cached.isNegative()) { return null; } else if (querysent) { return null; } else { Record question = Record.newRecord(name, type, dclass); Message query = Message.newQuery(question); Message response; try { response = res.send(query); } catch (Exception ex) { return null; } short rcode = response.getHeader().getRcode(); if (rcode == Rcode.NOERROR || rcode == Rcode.NXDOMAIN) cache.addMessage(response); if (rcode != Rcode.NOERROR) return null; return lookup(name, type, dclass, cred, true); } return answers; } /** * Finds records with the given name, type, and class with a certain credibility * @param namestr The name of the desired records * @param type The type of the desired records * @param dclass The class of the desired records * @param cred The minimum credibility of the desired records * @see Credibility * @return The matching records, or null if none are found */ public static Record [] getRecords(String namestr, short type, short dclass, byte cred) { Record [] answers = null; Name name = new Name(namestr); if (!Type.isRR(type) && type != Type.ANY) return null; initialize(); if (searchPath == null || name.isQualified()) answers = lookup(name, type, dclass, cred, false); else { for (int i = 0; i < searchPath.length; i++) { answers = lookup(new Name(namestr, searchPath[i]), type, dclass, cred, false); if (answers != null) break; } } return answers; } /** * Finds credible records with the given name, type, and class * @param namestr The name of the desired records * @param type The type of the desired records * @param dclass The class of the desired records * @return The matching records, or null if none are found */ public static Record [] getRecords(String namestr, short type, short dclass) { return getRecords(namestr, type, dclass, Credibility.NONAUTH_ANSWER); } /** * Finds any records with the given name, type, and class * @param namestr The name of the desired records * @param type The type of the desired records * @param dclass The class of the desired records * @return The matching records, or null if none are found */ public static Record [] getAnyRecords(String namestr, short type, short dclass) { return getRecords(namestr, type, dclass, Credibility.AUTH_ADDITIONAL); } /** * Finds credible records with the given name and type in class IN * @param namestr The name of the desired records * @param type The type of the desired records * @return The matching records, or null if none are found */ public static Record [] getRecords(String name, short type) { return getRecords(name, type, DClass.IN, Credibility.NONAUTH_ANSWER); } /** * Finds any records with the given name and type in class IN * @param namestr The name of the desired records * @param type The type of the desired records * @return The matching records, or null if none are found */ public static Record [] getAnyRecords(String name, short type) { return getRecords(name, type, DClass.IN, Credibility.AUTH_ADDITIONAL); } /** * Finds credible records for the given dotted quad address and type in class IN * @param addr The dotted quad address of the desired records * @param type The type of the desired records * @return The matching records, or null if none are found */ public static Record [] getRecordsByAddress(String addr, short type) { String name = inaddrString(addr); return getRecords(name, type, DClass.IN, Credibility.NONAUTH_ANSWER); } /** * Finds any records for the given dotted quad address and type in class IN * @param addr The dotted quad address of the desired records * @param type The type of the desired records * @return The matching records, or null if none are found */ public static Record [] getAnyRecordsByAddress(String addr, short type) { String name = inaddrString(addr); return getRecords(name, type, DClass.IN, Credibility.AUTH_ADDITIONAL); } }
package ed.lang.ruby; import java.lang.ref.WeakReference; import java.io.*; import java.util.*; import org.jruby.*; import org.jruby.ast.Node; import org.jruby.internal.runtime.GlobalVariables; import org.jruby.internal.runtime.methods.JavaMethod; import org.jruby.runtime.*; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.util.KCode; import static org.jruby.runtime.Visibility.PUBLIC; import ed.appserver.AppContext; import ed.appserver.JSFileLibrary; import ed.appserver.adapter.cgi.EnvMap; import ed.js.JSFunction; import ed.js.engine.Scope; import static ed.lang.ruby.RubyObjectWrapper.toRuby; import static ed.lang.ruby.RubyObjectWrapper.isCallableJSFunction; class RuntimeEnvironment { public static final String XGEN_MODULE_NAME = "XGen"; public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; static final Map<AppContext, WeakReference<Ruby>> runtimes = new WeakHashMap<AppContext, WeakReference<Ruby>>(); static final Map<String, Long> _localFileLastModTimes = new HashMap<String, Long>(); static final Ruby PARSE_RUNTIME = Ruby.newInstance(); static final boolean DEBUG = Boolean.getBoolean("DEBUG.RB"); static final boolean SKIP_REQUIRED_LIBS = Boolean.getBoolean("DEBUG.RB.SKIP.REQ.LIBS"); /** Scope top-level functions to avoid loading. */ static final Collection<String> DO_NOT_LOAD_FUNCS; // TODO for now, we just add the local site dir to the load path static final String[] BUILTIN_JS_FILE_LIBRARIES = {"local" /* , "core", "external" */}; static final RubyInstanceConfig config = new RubyInstanceConfig(); static { /* Don't pre-load XGen::Mongo::Base. It used to require /core/js/sql, * which isn't on the path this early in the game. Since Base was the * only thing that we pre-loaded here, I've commented this out. * Uncomment and re-add xgen.rb if there's anything we always want * required. */ // if (!SKIP_REQUIRED_LIBS) // config.requiredLibraries().add("xgen"); DO_NOT_LOAD_FUNCS = new ArrayList<String>(); DO_NOT_LOAD_FUNCS.add("print"); DO_NOT_LOAD_FUNCS.add("sleep"); DO_NOT_LOAD_FUNCS.add("fork"); DO_NOT_LOAD_FUNCS.add("eval"); DO_NOT_LOAD_FUNCS.add("exit"); for (int i = 0; i < RubyJSFunctionWrapper.IGNORE_JS_CLASSES.length; ++i) DO_NOT_LOAD_FUNCS.add(RubyJSFunctionWrapper.IGNORE_JS_CLASSES[i]); } /** Determines what major version of Ruby to compile: 1.8 (false) or YARV/1.9 (true). **/ public static final boolean YARV_COMPILE = false; protected Ruby runtime; /** * Creates Ruby classes and XGen module methods from any new JavaScript * classes and functions found in the top level of <var>scope</var>. * Called immediately after loading a file using a JSFileLibrary. */ public static void createNewClassesAndXGenMethods(Scope scope, Ruby runtime) { RubyModule xgen = runtime.getOrCreateModule(XGEN_MODULE_NAME); Set<String> alreadySeen = new HashSet<String>(); Scope s = scope; while (s != null) { for (String key : s.keySet()) { if (alreadySeen.contains(key) || DO_NOT_LOAD_FUNCS.contains(key)) continue; final Object obj = s.get(key); if (isCallableJSFunction(obj)) { if (DEBUG) System.err.println("adding top-level method " + key); alreadySeen.add(key); /* Creates method and attaches to the module. Also creates a new Ruby class if appropriate. */ RubyObjectWrapper.createRubyMethod(scope, runtime, (JSFunction)obj, key, xgen, null); } } s = s.getParent(); } } public static synchronized Ruby getRuntimeInstance(AppContext ac) { if (ac == null) return Ruby.newInstance(config); WeakReference<Ruby> ref = null; ref = runtimes.get(ac); if (ref == null) { Ruby runtime = Ruby.newInstance(config); runtimes.put(ac, ref = new WeakReference<Ruby>(runtime)); } return ref.get(); } public static synchronized void forgetRuntimeInstance(AppContext ac) { if (ac != null) { WeakReference<Ruby> ref = runtimes.remove(ac); if (ref != null) { Ruby runtime = ref.get(); Loader.removeLoadedFiles(runtime); } } } RuntimeEnvironment(Ruby runtime) { this.runtime = runtime; } public synchronized Ruby getRuntime(Scope s) { return s == null ? getRuntime((AppContext)null) : getRuntime((AppContext)s.get("__instance__")); } public synchronized Ruby getRuntime(AppContext ac) { if (runtime == null) runtime = getRuntimeInstance(ac); return runtime; } void forgetRuntime(Scope s) { runtime = null; if (s != null) forgetRuntimeInstance((AppContext)s.get("__instance__")); } void commonSetup(Scope s, InputStream stdin, OutputStream stdout) { resetOnFileChange(s); addJSFileLibrariesToPath(s); Ruby runtime = getRuntime(s); runtime.setGlobalVariables(new ScopeGlobalVariables(s, runtime)); exposeScopeFunctions(s); patchRequireAndLoad(s); setIO(stdin, stdout); /* Create class objects. */ RubyDBCursorWrapper.getDBCursorClass(runtime); RubyJSArrayWrapper.getJSArrayClass(runtime); RubyJSFileLibraryWrapper.getJSFileLibraryClass(runtime); RubyJSFunctionWrapper.getJSFunctionClass(runtime); RubyJSObjectWrapper.getJSObjectClass(runtime); RubyObjectIdWrapper.getObjectIdClass(runtime); } IRubyObject commonRun(Node node, Scope s) { /* See the second part of JRuby's Ruby.executeScript(String, String). */ Ruby runtime = getRuntime(s); ThreadContext context = runtime.getCurrentContext(); String oldFile = context.getFile(); int oldLine = context.getLine(); try { context.setFileAndLine(node.getPosition().getFile(), node.getPosition().getStartLine()); return runtime.runNormally(node, YARV_COMPILE); } finally { context.setFile(oldFile); context.setLine(oldLine); } } Node parse(String script, String filePath) { /* See the first part of JRuby's Ruby.executeScript(String, String). */ byte[] bytes; try { bytes = script.getBytes(KCode.NONE.getKCode()); } catch (UnsupportedEncodingException e) { bytes = script.getBytes(); } return RuntimeEnvironment.PARSE_RUNTIME.parseFile(new ByteArrayInputStream(bytes), filePath, null); } void addCGIEnv(Scope s, EnvMap env) { Ruby runtime = getRuntime(s); ThreadContext context = runtime.getCurrentContext(); RubyHash envHash = (RubyHash)runtime.getObject().fastGetConstant("ENV"); for (String key : env.keySet()) envHash.op_aset(context, runtime.newString(key), runtime.newString(env.get(key).toString())); } void addJSFileLibrariesToPath(Scope s) { Ruby runtime = getRuntime(s); RubyArray loadPath = (RubyArray)runtime.getLoadService().getLoadPath(); for (String libName : BUILTIN_JS_FILE_LIBRARIES) { Object val = s.get(libName); if (!(val instanceof JSFileLibrary)) continue; File root = ((JSFileLibrary)val).getRoot(); RubyString rubyRoot = runtime.newString(root.getPath().replace('\\', '/')); if (loadPath.include_p(runtime.getCurrentContext(), rubyRoot).isFalse()) { if (DEBUG) System.err.println("adding file library " + val.toString() + " root " + rubyRoot); loadPath.append(rubyRoot); } } } /** * Creates the $scope global object and sets up the XGen module with * top-level functions defined in the scope. */ void exposeScopeFunctions(Scope scope) { Ruby runtime = getRuntime(scope); runtime.getGlobalVariables().set("$scope", toRuby(scope, runtime, scope)); /* Creates a module named XGen, includes it in the Object class (just * like Kernel), and adds all top-level JavaScript methods to the * module. */ RubyModule xgen = runtime.getOrCreateModule(XGEN_MODULE_NAME); runtime.getObject().includeModule(xgen); createNewClassesAndXGenMethods(scope, runtime); } void patchRequireAndLoad(final Scope scope) { RubyModule kernel = getRuntime(scope).getKernel(); kernel.addMethod("require", new JavaMethod(kernel, PUBLIC) { public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule module, String name, IRubyObject[] args, Block block) { return new Loader(scope).require(context, self, module, name, args, block); } }); kernel.addMethod("load", new JavaMethod(kernel, PUBLIC) { public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule module, String name, IRubyObject[] args, Block block) { return new Loader(scope).load(context, self, module, name, args, block); } }); } /** * Set Ruby's $stdin, $stdout, STDIN, and STDOUT so that reading and * writing go to the right place. */ protected void setIO(InputStream stdin, OutputStream stdout) { GlobalVariables gvars = runtime.getGlobalVariables(); /* Ignore warnings about redefining STDIN and STDOUT by sending * $stderr to a dummy output stream. */ IRubyObject oldStderr = gvars.get("$stderr"); gvars.set("$stderr", new RubyIO(runtime, new ByteArrayOutputStream())); if (stdin != null) { RubyIO rstdin = new RubyIO(runtime, stdin); runtime.getObject().setConstant("STDIN", rstdin); gvars.set("$stdin", rstdin); } if (stdout != null) { RubyIO rstdout = new RubyIO(runtime, stdout); runtime.getObject().setConstant("STDOUT", rstdout); gvars.set("$stdout", rstdout); } gvars.set("$stderr", oldStderr); } /** * Resets runtime if any local file changed. This is a simple, dumb, * stupid way of making sure that files are re-required if they changed. * <p> * What we really want is a way to find out which file is really required * by "require 'foo'" so we can check at the time of the require instead * of up front for all files. There is no way to find 'foo' now without a * change to JRuby (which I'm working on). */ private void resetOnFileChange(Scope s) { return; /* This code is commented out for now because when run against an app * with 1,000 froze Rails files, calling anyLocalFileChanged for * every request is too slow. */ // if (anyLocalFileChanged(s)) { // if (DEBUG) // System.err.println("new file or file mod time changed; resetting Ruby runtime"); // forgetRuntime(s); } /* This code is commented out for now because when run against an app with * 1,000 froze Rails files, doing this for every request is too slow. */ // private boolean anyLocalFileChanged(Scope s) { // return false; // if (s == null) // return false; // JSFileLibrary lib = (JSFileLibrary)s.get("local"); // if (lib == null) // return false; // synchronized (localFileLastModTimes) { // return anyLocalFileChanged(lib.getRoot(), false); // private boolean anyLocalFileChanged(File dir, boolean changed) { // for (File f : dir.listFiles()) { // if (f.isDirectory()) // changed = anyLocalFileChanged(f, changed); // else { // String path = f.getPath(); // Long newModTime = new Long(f.lastModified()); // Long oldModTime = localFileLastModTimes.get(path); // if (oldModTime == null || !oldModTime.equals(newModTime)) { // changed = true; // localFileLastModTimes.put(path, newModTime); // return changed; }
package Application; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import org.springframework.stereotype.Controller; //import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.heroku.sdk.jdbc.DatabaseUrl; import Logic.CombatLogic; import Logic.MarketLogic; import Models.Player; import dataTransfer.LoginData; import dataTransfer.LoginValidation; import dataTransfer.RegisterData; //import Models.RegisterUserCredentials; import dataTransfer.ValidationCodes; import dto.CombatObject; import dto.MarketObject; @Controller public class HomeController { @RequestMapping("/") public String home() { return "index"; } @RequestMapping("/loginPage") public String loginPage() { return "users/login"; } @RequestMapping("/townPage") public String townPage() { return "town"; } @RequestMapping("/registerPage") public String registerPage() { return "users/register"; } @RequestMapping("/worldPage") public String worldPage() { return "world"; } @RequestMapping("/battlePage") public String battlePage() { return "battle"; } @RequestMapping(value = "/login", method = RequestMethod.POST) public @ResponseBody LoginValidation loginGet(@RequestBody LoginData data) { LoginValidation code = new LoginValidation(); try { Connection connection = DatabaseUrl.extract().getConnection(); Statement stmtCount = connection.createStatement(); Statement stmtUser = connection.createStatement(); Statement stmtUserCharacter = connection.createStatement(); Statement stmtCharacter = connection.createStatement(); ResultSet user = stmtCount.executeQuery("SELECT count(*) FROM Users WHERE username = '" + data.userName + "' AND password = '" + data.password + "'"); while (user.next()) { if(user.getInt(1) == 0) { code.IncorrectUsernameOrPassword = true; } } if(!code.IncorrectUsernameOrPassword) { ResultSet userInfo = stmtUser.executeQuery("SELECT * FROM Users WHERE username = '" + data.userName + "' AND password = '" + data.password + "'"); while (userInfo.next()) { code.playerData.setUserId(userInfo.getInt(1)); } ResultSet userCharacterInfo = stmtUserCharacter.executeQuery("SELECT * FROM userCharacters WHERE userid = '" + code.playerData.getUserId() + "'"); while (userInfo.next()) { if(userInfo.getInt(1) == code.playerData.getUserId()) { code.playerData.setCharacterID(userCharacterInfo.getInt(2)); } } ResultSet characterInfo = stmtCharacter.executeQuery("SELECT * FROM Characters WHERE characterid = '" + code.playerData.getCharacterID() + "'"); code.playerData.setCurrentHealth(characterInfo.getInt(2)); while (userInfo.next()) { if(userInfo.getInt(1) == code.playerData.getCharacterID()) { code.playerData.setCharacterName(characterInfo.getString(2)); code.playerData.setCurrentHealth(characterInfo.getInt(3)); code.playerData.setMaxHealth(characterInfo.getInt(4)); code.playerData.setAttack(characterInfo.getInt(5)); code.playerData.setHealItems(characterInfo.getInt(6)); code.playerData.setMoney(characterInfo.getInt(7)); code.playerData.setTown(characterInfo.getString(8)); } } } } catch (Exception e) { code.databaseError = true; } return code; // return new ResponseEntity<String>(HttpStatus.ACCEPTED); } @RequestMapping(value = "/register", method = RequestMethod.POST) public @ResponseBody ValidationCodes registerTransfer(@RequestBody RegisterData data) { ValidationCodes code = new ValidationCodes(); try { if(data.userName.isEmpty()) { code.UsernameEmpty = true; } if(data.email.isEmpty()) { code.EmailEmpty = true; } if(data.password.isEmpty() || data.confirmPassword.isEmpty()) { code.PasswordMismatch = true; } if(!code.UsernameEmpty && !code.EmailEmpty && !code.PasswordMismatch) { Connection connection = DatabaseUrl.extract().getConnection(); Statement stmtUser = connection.createStatement(); Statement stmtEmail = connection.createStatement(); Statement stmtInsert = connection.createStatement(); Statement stmtCharacterCreate = connection.createStatement(); Statement stmtUserData = connection.createStatement(); Statement stmtCharacterData = connection.createStatement(); Statement stmtCharacterRelate = connection.createStatement(); ResultSet userName = stmtUser.executeQuery("SELECT count(*) FROM Users WHERE username = '" + data.userName + "'"); ResultSet email = stmtEmail.executeQuery("SELECT count(*) FROM Users WHERE email = '" + data.email + "'"); while (userName.next()) { if(userName.getInt(1) != 0) { code.UsernameTaken = true; } } while (email.next()) { if(email.getInt(1) != 0) { code.EmailTaken = true; } } String newPassword = data.password; String newConfirmPassword = data.confirmPassword; if(!newPassword.equals(newConfirmPassword)) { code.PasswordMismatch = true; } if(!code.UsernameTaken && !code.EmailTaken && !code.PasswordMismatch) { stmtInsert.execute("Insert into Users (username, email, password) values ('" + data.userName + "','" + data.email + "','" + data.password + "')"); stmtCharacterCreate.execute("Insert into Characters (charactername, attack, maxhealth, currenthealth) values ('" + data.userName + "', 10, 10, 10)"); ResultSet userData = stmtUserData.executeQuery("SELECT userID FROM users WHERE username = '" + data.userName + "'"); ResultSet characterData = stmtCharacterData.executeQuery("SELECT characterID FROM Characters WHERE charactername = '" + data.userName + "'"); int userID = -1; int characterID = -1; while (userData.next()) { userID = userData.getInt(1); } while (characterData.next()) { characterID = characterData.getInt(1); } stmtCharacterRelate.execute("Insert into userCharacters (userid, characterid) values (" + userID + ", " + characterID + ")"); } } } catch (Exception e) { code.databaseError = true; } return code; } // @RequestMapping(value = "/validate", method = RequestMethod.POST) // public String registerPost(@ModelAttribute("registerUserCredentials") RegisterUserCredentials userCredentials, BindingResult result) { // try { // URI dbUri = new URI("postgres://fghhopulwiaynq:OfvO_N_KLpwGqwbOZY7wEwKfL_@ec2-54-221-201-165.compute-1.amazonaws.com:5432/df02650vnkne80"); // String dbusername = dbUri.getUserInfo().split(":")[0]; // String dbpassword = dbUri.getUserInfo().split(":")[1]; // String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath(); // System.out.println(userCredentials.getUserName()); // System.out.println(userCredentials.getEmail()); // System.out.println(userCredentials.getPassword()); // System.out.println(userCredentials.getConfirmPassword()); // //"Select * from Users // return "redirect:login"; // } catch (Exception e) { // return registerTransfer(); // @ModelAttribute("registerUserCredentials") // public RegisterUserCredentials getRegisterUserCredentials() { // return new RegisterUserCredentials(); @RequestMapping(value = "/buy/Attack", method = RequestMethod.POST) public @ResponseBody MarketObject increaseAttack(@RequestBody MarketObject data) { data = MarketLogic.buyAttack(data); try { Connection connection = DatabaseUrl.extract().getConnection(); Statement stmtUser = connection.createStatement(); stmtUser.execute("UPDATE Characters SET zeni = '" + data.getPlayer().getMoney() + "' WHERE characterid = '" + data.getPlayer().getCharacterID() + "'"); stmtUser.execute("UPDATE Characters SET attack = '" + data.getPlayer().getAttack() + "' WHERE characterid = '" + data.getPlayer().getCharacterID() + "'"); } catch (Exception e) { System.out.println(e); } return data; } @RequestMapping(value = "/buy/Health", method = RequestMethod.POST) public @ResponseBody MarketObject increaseHealth(@RequestBody MarketObject data) { data = MarketLogic.buyHealth(data); try { Connection connection = DatabaseUrl.extract().getConnection(); Statement stmtUser = connection.createStatement(); stmtUser.execute("UPDATE Characters SET zeni = '" + data.getPlayer().getMoney() + "' WHERE characterid = '" + data.getPlayer().getCharacterID() + "'"); stmtUser.execute("UPDATE Characters SET currenthealth = '" + data.getPlayer().getCurrentHealth() + "' WHERE characterid = '" + data.getPlayer().getCharacterID() + "'"); stmtUser.execute("UPDATE Characters SET maxhealth = '" + data.getPlayer().getMaxHealth() + "' WHERE characterid = '" + data.getPlayer().getCharacterID() + "'"); } catch (Exception e) { System.out.println(e); } return data; } @RequestMapping(value = "/buy/Potion", method = RequestMethod.POST) public @ResponseBody MarketObject addPotions(@RequestBody MarketObject data) { data = MarketLogic.buyPotion(data); try { Connection connection = DatabaseUrl.extract().getConnection(); Statement stmtUser = connection.createStatement(); stmtUser.execute("UPDATE Characters SET zeni = '" + data.getPlayer().getMoney() + "' WHERE characterid = '" + data.getPlayer().getCharacterID() + "'"); stmtUser.execute("UPDATE Characters SET healItems = '" + data.getPlayer().getHealItems() + "' WHERE characterid = '" + data.getPlayer().getCharacterID() + "'"); } catch (Exception e) { System.out.println(e); } return data; } @RequestMapping(value = "/combat/pve/Attack", method = RequestMethod.POST) public @ResponseBody CombatObject increaseAttack(@RequestBody CombatObject data) { data = CombatLogic.playerAttack(data); if(data.getThePlayer().getCurrentHealth() > 0 && data.getTheEnemy().getHealth() <= 0) { data = CombatLogic.survivingPlayer(data); } else { data = CombatLogic.enemyAttack(data); } if(data.getThePlayer().getCurrentHealth() <= 0) { data = CombatLogic.dieingPlayer(data); } try { Connection connection = DatabaseUrl.extract().getConnection(); Statement stmtUser = connection.createStatement(); stmtUser.execute("UPDATE Characters SET currenthealth = '" + data.getThePlayer().getCurrentHealth() + "' WHERE characterid = '" + data.getThePlayer().getCharacterID() + "'"); stmtUser.execute("UPDATE Characters SET zeni = '" + data.getThePlayer().getMoney() + "' WHERE characterid = '" + data.getThePlayer().getCharacterID() + "'"); } catch (Exception e) { System.out.println(e); } return data; } @RequestMapping(value = "/combat/pve/Heal", method = RequestMethod.POST) public @ResponseBody CombatObject increaseHealth(@RequestBody CombatObject data) { data = CombatLogic.healPlayer(data); if(data.getThePlayer().getCurrentHealth() > 0 && data.getTheEnemy().getHealth() <= 0) { data = CombatLogic.survivingPlayer(data); } else { data = CombatLogic.enemyAttack(data); } if(data.getThePlayer().getCurrentHealth() <= 0) { data = CombatLogic.dieingPlayer(data); } try { Connection connection = DatabaseUrl.extract().getConnection(); Statement stmtUser = connection.createStatement(); //Table that relates characters to users: usercharacters //Columns: characterid chactername health attack healingitems zeni //DataTypes: int string int int int int //ResultSet character = stmtUser.executeQuery("SELECT health FROM Characters WHERE characterid = '" + data.getThePlayer().getCharacterID() + "'"); stmtUser.execute("UPDATE Characters SET currenthealth = '" + data.getThePlayer().getCurrentHealth() + "' WHERE characterid = '" + data.getThePlayer().getCharacterID() + "'"); stmtUser.execute("UPDATE Characters SET healthitems = '" + data.getThePlayer().getHealItems() + "' WHERE characterid = '" + data.getThePlayer().getCharacterID() + "'"); stmtUser.execute("UPDATE Characters SET zeni = '" + data.getThePlayer().getMoney() + "' WHERE characterid = '" + data.getThePlayer().getCharacterID() + "'"); //while(character.next()) //int health = character.getInt(1); } catch (Exception e) { System.out.println(e); } return data; } @RequestMapping(value = "/combat/pve", method = RequestMethod.POST) public @ResponseBody CombatObject startCombat(@RequestBody Player data) { CombatObject combat = new CombatObject(data, CombatLogic.createEnemy(data)); try { Connection connection = DatabaseUrl.extract().getConnection(); Statement stmtUser = connection.createStatement(); stmtUser.execute("UPDATE Characters SET town = '" + data.getTown() + "' WHERE characterid = '" + data.getCharacterID() + "'"); } catch (Exception e) { System.out.println(e); } return combat; } }
package VASSAL.tools.io; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilterInputStream; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.zip.CRC32; import java.util.zip.CheckedOutputStream; import java.util.zip.Checksum; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import VASSAL.tools.IteratorUtils; import org.apache.commons.io.FileUtils; import VASSAL.Info; import VASSAL.tools.concurrent.CountingReadWriteLock; /** * @author Joel Uckelman * @since 3.2.0 */ public class ZipArchive implements FileArchive { private final File archiveFile; private ZipFile zipFile; private boolean modified = false; private boolean closed = true; private static class Entry { public ZipEntry ze; public File file; public Entry(ZipEntry ze, File file) { this.ze = ze; this.file = file; } @Override public String toString() { return getClass().getName() + "[file=\"" + file + "\", ze=\"" + ze + "\"]"; } } private final Map<String,Entry> entries = new HashMap<>(); private final ReadWriteLock rwl = new CountingReadWriteLock(); private final Lock r = rwl.readLock(); private final Lock w = rwl.writeLock(); /** * Opens a ZIP archive. * * @param path the name of the archive * @throws IOException */ public ZipArchive(String path) throws IOException { this(path, false); } /** * Opens a ZIP archive. * * @param file the name of the archive * @throws IOException */ public ZipArchive(File file) throws IOException { this(file, false); } /** * Opens a ZIP archive. * * @param path the name of the archive * @param truncate if <code>true</code>, truncate the archive file on open * @throws IOException */ public ZipArchive(String path, boolean truncate) throws IOException { this(new File(path), truncate); } /** * Opens a ZIP archive. * * @param file the name of the archive * @param truncate if <code>true</code>, truncate the archive file on open * @throws IOException */ public ZipArchive(File file, boolean truncate) throws IOException { if (file == null) throw new IllegalArgumentException(); this.archiveFile = file; if (truncate) { archiveFile.delete(); } } /** * Copies a ZIP archive. * * @param src the name of the source archive * @param dst the name of the destination archive * @throws IOException */ public ZipArchive(FileArchive src, String dst) throws IOException { this(src, new File(dst)); } /** * Copies a ZIP archive. * * @param src the name of the source archive * @param dst the name of the destination archive * @throws IOException */ public ZipArchive(FileArchive src, File dst) throws IOException { this(dst, true); final byte[] buf = new byte[8192]; // copy each entry to the new archive for (String name : src.getFiles()) { try (InputStream in = src.getInputStream(name); OutputStream out = getOutputStream(name)) { IOUtils.copy(in, out, buf); } } flush(); } /** {@inheritDoc} */ @Override public String getName() { return archiveFile.getPath(); } /** {@inheritDoc} */ @Override public File getFile() { return archiveFile; } /** {@inheritDoc} */ @Override public boolean isClosed() { return closed; } /** {@inheritDoc} */ @Override public boolean isModified() { return modified; } /** * {@inheritDoc} * * <b>Note:</b> It is impeative the that calling code ensures that this * stream is eventually closed, since the returned stream holds a read * lock on the archive. */ @Override public InputStream getInputStream(String path) throws IOException { r.lock(); try { openIfClosed(); final Entry e = entries.get(path); if (e == null) { throw new FileNotFoundException(path + " not in archive"); } InputStream in = null; if (e.file != null) { in = new FileInputStream(e.file); } else if (zipFile != null) { // NB: Undocumented, but ZipFile.getInputStream can return null! in = zipFile.getInputStream(e.ze); } if (in == null) { throw new FileNotFoundException(path + " not in archive"); } return new ZipArchiveInputStream(in); } catch (IOException ex) { r.unlock(); throw ex; } } /** * {@inheritDoc} * * <b>Note:</b> It is imperative the that calling code ensures that this * stream is eventually closed, since the returned stream holds a write * lock on the archive. */ @Override public OutputStream getOutputStream(String path) throws IOException { return getOutputStream(path, true); } /** * Gets an {@link OutputStream} to write to the given file. * * <b>Note:</b> It is imperative the that calling code ensures that this * stream is eventually closed, since the returned stream holds a write * lock on the archive. * * @param path the path to the file in the archive * @param compress whether to compress the file * @return an <code>OutputStream</code> for the requested file * @throws IOException */ public OutputStream getOutputStream(String path, boolean compress) throws IOException { w.lock(); try { openIfClosed(); modified = true; // set up new ZipEntry final ZipEntry ze = new ZipEntry(path); ze.setMethod(compress ? ZipEntry.DEFLATED : ZipEntry.STORED); // create new temp file final File tf = File.createTempFile("zip", ".tmp", Info.getTempDir()); // set up new Entry final Entry e = new Entry(ze, tf); final Entry old = entries.put(path, e); // clean up old temp file if (old != null && old.file != null) { old.file.delete(); } return new ZipArchiveOutputStream( new FileOutputStream(e.file), new CRC32(), e.ze ); } catch (IOException ex) { w.unlock(); throw ex; } } /** {@inheritDoc} */ @Override public void add(String path, String extPath) throws IOException { add(path, new File(extPath)); } /** {@inheritDoc} */ @Override public void add(String path, File extPath) throws IOException { try (FileInputStream in = new FileInputStream(extPath)) { add(path, in); } } /** {@inheritDoc} */ @Override public void add(String path, byte[] bytes) throws IOException { add(path, new ByteArrayInputStream(bytes)); } /** {@inheritDoc} */ @Override public void add(String path, InputStream in) throws IOException { try (OutputStream out = getOutputStream(path)) { IOUtils.copy(in, out); } } /** {@inheritDoc} */ @Override public boolean remove(String path) throws IOException { w.lock(); try { openIfClosed(); final Entry e = entries.remove(path); if (e != null) { modified = true; if (e.file != null) { e.file.delete(); } } return e != null; } finally { w.unlock(); } } /** {@inheritDoc} */ @Override public void revert() throws IOException { w.lock(); try { if (!modified) { return; } // delete all temporary files for (Entry e : entries.values()) { if (e != null && e.file != null) { e.file.delete(); } } modified = false; } finally { w.unlock(); } } /** {@inheritDoc} */ @Override public void flush() throws IOException { w.lock(); try { if (modified) { writeToDisk(); } } finally { w.unlock(); } } /** {@inheritDoc} */ @Override public void close() throws IOException { w.lock(); try { if (closed) { return; } else if (modified) { writeToDisk(); } else if (zipFile != null) { zipFile.close(); zipFile = null; closed = true; entries.clear(); } } finally { w.unlock(); } } private void writeToDisk() throws IOException { // write all files to a temporary zip archive final File tmpFile = File.createTempFile("tmp", ".zip", archiveFile.getParentFile()); try (OutputStream fout = new FileOutputStream(tmpFile); OutputStream bout = new BufferedOutputStream(fout); ZipOutputStream out = new ZipOutputStream(bout)) { out.setLevel(9); final byte[] buf = new byte[8192]; if (zipFile != null) { zipFile.close(); zipFile = null; // copy unmodified file into the temp archive try (InputStream fin = new FileInputStream(archiveFile); InputStream bin = new BufferedInputStream(fin); ZipInputStream in = new ZipInputStream(bin)) { ZipEntry ze = null; while ((ze = in.getNextEntry()) != null) { // skip modified or removed entries final Entry e = entries.get(ze.getName()); if (e == null || e.file != null) continue; // We can't reuse entries for compressed files because there's // no way to reset all fields to acceptable values. if (ze.getMethod() == ZipEntry.DEFLATED) { final ZipEntry nze = new ZipEntry(ze.getName()); nze.setTime(ze.getTime()); ze = nze; } out.putNextEntry(ze); IOUtils.copy(in, out, buf); entries.remove(ze.getName()); } } } for (Entry e : entries.values()) { // skip removed or unmodified files if (e == null || e.file == null) continue; // write new or modified file into the temp archive try (FileInputStream in = new FileInputStream(e.file)) { e.ze.setTime(e.file.lastModified()); out.putNextEntry(e.ze); IOUtils.copy(in, out, buf); } } } // Replace old archive with temp archive. try { FileUtils.forceDelete(archiveFile); FileUtils.moveFile(tmpFile, archiveFile); } catch (IOException e) { final String fmt = "Unable to overwrite %s: %s Data written to %s instead."; throw new IOException( String.format(fmt, archiveFile.getAbsolutePath(), e.getMessage(), tmpFile.getAbsolutePath()), e); } // Delete all temporary files for (Entry e : entries.values()) { if (e != null && e.file != null) { e.file.delete(); } } closed = true; modified = false; entries.clear(); } /** {@inheritDoc} */ @Override public boolean contains(String path) throws IOException { r.lock(); try { openIfClosed(); return entries.containsKey(path); } finally { r.unlock(); } } /** {@inheritDoc} */ @Override public long getSize(String path) throws IOException { r.lock(); try { openIfClosed(); final Entry e = entries.get(path); if (e == null) { throw new FileNotFoundException(path + " not in archive"); } return e.file == null ? e.ze.getSize() : e.file.length(); } finally { r.unlock(); } } /** {@inheritDoc} */ @Override public long getMTime(String path) throws IOException { r.lock(); try { openIfClosed(); final Entry e = entries.get(path); if (e == null) { throw new FileNotFoundException(path + " not in archive"); } return e.file == null ? e.ze.getTime() : e.file.lastModified(); } finally { r.unlock(); } } /** {@inheritDoc} */ @Override public List<String> getFiles() throws IOException { r.lock(); try { openIfClosed(); return new ArrayList<>(entries.keySet()); } finally { r.unlock(); } } /** {@inheritDoc} */ @Override public List<String> getFiles(String root) throws IOException { if (root.length() == 0) { return getFiles(); } r.lock(); try { openIfClosed(); // FIXME: directories need not have entries in the ZipFile! // if (!entries.containsKey(root)) // throw new FileNotFoundException(root + " not in archive"); root += '/'; final ArrayList<String> names = new ArrayList<>(); for (String n : entries.keySet()) { if (n.startsWith(root)) { names.add(n); } } return names; } finally { r.unlock(); } } /** Rebuilds the {@link Entry}s from our underlying {@link ZipFile}. */ private synchronized void readEntries() throws IOException { entries.clear(); if (archiveFile.exists() && archiveFile.length() > 0) { zipFile = new ZipFile(archiveFile); for (ZipEntry e : IteratorUtils.iterate(zipFile.entries().asIterator())) { entries.put(e.getName(), new Entry(e, null)); } } } /** Opens the archive if it is closed. */ private synchronized void openIfClosed() throws IOException { if (closed) { readEntries(); modified = false; closed = false; } } /** An {@link InputStream} which releases the read lock on close. */ private class ZipArchiveInputStream extends FilterInputStream { public ZipArchiveInputStream(InputStream in) { super(in); if (in == null) { throw new NullPointerException("in == null"); } } private boolean closed = false; @Override public void close() throws IOException { if (closed) { return; } try { super.close(); } finally { r.unlock(); closed = true; } } } /** * An {@link OutputStream} which calculates a checksum, counts bytes * written, and releases the write lock on close. */ private class ZipArchiveOutputStream extends CheckedOutputStream { private ZipEntry entry; private long count = 0; public ZipArchiveOutputStream(OutputStream out, Checksum cksum, ZipEntry e) { super(out, cksum); if (out == null) { throw new NullPointerException("out == null"); } if (cksum == null) { throw new NullPointerException("cksum == null"); } if (e == null) { throw new NullPointerException("e == null"); } entry = e; } @Override public void write(byte[] bytes, int off, int len) throws IOException { super.write(bytes, off, len); count += len; } @Override public void write(int b) throws IOException { super.write(b); ++count; } @Override public void flush() throws IOException { super.flush(); entry.setSize(count); entry.setCrc(getChecksum().getValue()); } private boolean closed = false; @Override public void close() throws IOException { if (closed) { return; } try { super.close(); } finally { w.unlock(); closed = true; } } } public static void main(String[] args) throws IOException { final ZipArchive archive = new ZipArchive("test.zip"); // write test archive.add("NOTES", "NOTES"); archive.add("README.txt", "README.txt"); archive.flush(); // read test try (InputStream in = archive.getInputStream("NOTES")) { IOUtils.copy(in, System.out); } archive.close(); } }
package brooklyn.cli; import groovy.lang.GroovyClassLoader; import groovy.lang.GroovyShell; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import javax.inject.Inject; import org.iq80.cli.Cli; import org.iq80.cli.Cli.CliBuilder; import org.iq80.cli.Command; import org.iq80.cli.Help; import org.iq80.cli.Option; import org.iq80.cli.OptionType; import org.iq80.cli.ParseException; import brooklyn.entity.basic.AbstractApplication; import brooklyn.entity.basic.Entities; import brooklyn.launcher.BrooklynLauncher; import brooklyn.location.Location; import brooklyn.location.basic.LocationRegistry; import brooklyn.util.ResourceUtils; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import com.google.common.base.Objects.ToStringHelper; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; public class Main { public static void main(String...args) { Cli<BrooklynCommand> parser = getCli(); try { BrooklynCommand command = parser.parse(args); command.call(); } catch (ParseException pe) { System.err.println("Parse error: " + pe.getMessage()); StringBuilder parseErrorHelp = new StringBuilder(); Help.help(parser.getMetadata(), ImmutableList.of("brooklyn"),parseErrorHelp); System.err.println(parseErrorHelp); System.exit(1); } catch (Exception e) { System.err.println("Execution error: " + e.getMessage()); e.printStackTrace(); } } public static abstract class BrooklynCommand implements Callable<Void> { @Inject public Help help; @Option(type = OptionType.GLOBAL, name = { "-v", "--verbose" }, description = "Verbose mode") public boolean verbose = false; @Option(type = OptionType.GLOBAL, name = { "-q", "--quiet" }, description = "Quiet mode") public boolean quiet = false; public ToStringHelper string() { return Objects.toStringHelper(getClass()) .add("verbose", verbose) .add("quiet", quiet); } public String toString() { return string().toString(); } } @Command(name = "help", description = "Display help information about brooklyn") public static class HelpCommand extends BrooklynCommand { @Override public Void call() throws Exception { return help.call(); } } @Command(name = "launch", description = "Starts a brooklyn application. Note that a BROOKLYN_CLASSPATH environment variable needs to be set up beforehand to point to the user application classpath.") public static class LaunchCommand extends BrooklynCommand { @Option(name = { "-a", "--app" }, required = true, title = "application class or file", description = "The Application to start. For example my.AppName or file://my/AppName.groovy or classpath://my/AppName.groovy") public String app; @Beta @Option(name = { "-s", "--script" }, title = "script URI", description = "EXPERIMENTAL. URI for a Groovy script to parse and load. This script will run before starting the app.") public String script = null; @Option(name = { "-l", "--location", "--locations" }, title = "location list", description = "Specifies the locations where the application will be launched.") public Collection<String> locations = Arrays.asList("localhost"); @Option(name = { "-p", "--port" }, title = "port number", description = "Specifies the port to be used by the Brooklyn Management Console.") public int port = 8081; @Option(name = { "-nc", "--noConsole" }, description = "Whether to start the web console") public boolean noConsole = false; @Option(name = { "-ns", "--noShutdownOnExit" }, description = "Whether to stop the application when the JVM exits") public boolean noShutdownOnExit = false; @Override public Void call() throws Exception { if (verbose) { System.out.println("Launching brooklyn app: "+app+" in "+Iterables.toString(locations)); } ResourceUtils utils = new ResourceUtils(this); ClassLoader parent = utils.getLoader(); GroovyClassLoader loader = new GroovyClassLoader(parent); // Get an instance of the brooklyn app AbstractApplication application = loadApplicationFromClasspathOrParse(utils, loader, app); //First, run a setup script if the user has provided one if (script != null) { String content = utils.getResourceAsString(script); GroovyShell shell = new GroovyShell(loader); shell.evaluate(content); } // Figure out the brooklyn location(s) where to launch the application List<Location> brooklynLocations = new LocationRegistry().getLocationsById(locations); // Start the application BrooklynLauncher.manage(application, port, !noShutdownOnExit, !noConsole); application.start(brooklynLocations); if (verbose) { Entities.dumpInfo(application); } // Block forever so that Brooklyn doesn't exit (until someone does cntrl-c or kill) waitUntilInterrupted(); return null; } private void waitUntilInterrupted() { synchronized (this) { while (true) { try { wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; // exit gracefully } } } } /** * Helper method that gets an instance of a brooklyn application */ @VisibleForTesting AbstractApplication loadApplicationFromClasspathOrParse(ResourceUtils utils, GroovyClassLoader loader, String app) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { Class<?> appClass; try { appClass = loader.loadClass(app, true, false); } catch (ClassNotFoundException cnfe) { // Not a class on the classpath String content = utils.getResourceAsString(app); appClass = loader.parseClass(content); } Constructor<?> constructor = appClass.getConstructor(); return (AbstractApplication) constructor.newInstance(); } @Override public ToStringHelper string() { return super.string() .add("app", app) .add("script", script) .add("location", locations) .add("port", port) .add("noConsole",noConsole) .add("noShutdwonOnExit",noShutdownOnExit); } } public static Cli<BrooklynCommand> getCli() { @SuppressWarnings({ "unchecked" }) CliBuilder<BrooklynCommand> builder = Cli.buildCli("brooklyn", BrooklynCommand.class) .withDescription("Brooklyn Management Service") .withDefaultCommand(HelpCommand.class) .withCommands( HelpCommand.class, LaunchCommand.class ); return builder.build(); } }
package ai.pathfinder.core; import java.util.ArrayList; import java.util.List; import java.util.Set; public class Problem { private Node initialNode; private Node goalNode; private Set<Node> wall; private int nodeSize; public Problem(Node initialNode, Node goalNode, Set<Node> wall, int nodeSize) { this.initialNode = initialNode; this.goalNode = goalNode; this.wall = wall; this.nodeSize = nodeSize; } public Node getInitialNode() { return initialNode; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Start: ").append(initialNode.toString()).append("\n") .append("Goal: ").append(goalNode.toString()).append("\n"); return sb.toString(); } public Action[] getActions(Node node) { List<Action> actions = new ArrayList<Action>(); int x = node.getX(); int y = node.getY(); if (!wall.contains(new Node(x + nodeSize, y))) actions.add(Action.LEFT); if (!wall.contains(new Node(x, y + nodeSize))) actions.add(Action.DOWN); if (!wall.contains(new Node(x - nodeSize, y))) actions.add(Action.RIGHT); if (!wall.contains(new Node(x, y - nodeSize))) actions.add(Action.UP); return actions.toArray(new Action[] {}); } public Node getResult(Node node, Action action) { switch (action) { case LEFT: return new Node(node.getX() + nodeSize, node.getY(), node, action); case DOWN: return new Node(node.getX(), node.getY() + nodeSize, node, action); case RIGHT: return new Node(node.getX() - nodeSize, node.getY(), node, action); case UP: return new Node(node.getX(), node.getY() - nodeSize, node, action); default: return null; } } public boolean isGoal(Node node) { return goalNode.equals(node); } }
package com.fsck.k9.message; import java.io.IOException; import java.io.OutputStream; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.fsck.k9.K9; import com.fsck.k9.activity.compose.ComposeCryptoStatus; import com.fsck.k9.mail.Body; import com.fsck.k9.mail.BodyPart; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.internet.BinaryTempFileBody; import com.fsck.k9.mail.internet.MimeBodyPart; import com.fsck.k9.mail.internet.MimeHeader; import com.fsck.k9.mail.internet.MimeMessage; import com.fsck.k9.mail.internet.MimeMessageHelper; import com.fsck.k9.mail.internet.MimeMultipart; import com.fsck.k9.mail.internet.TextBody; import com.fsck.k9.mailstore.BinaryMemoryBody; import org.apache.james.mime4j.util.MimeUtil; import org.openintents.openpgp.OpenPgpError; import org.openintents.openpgp.util.OpenPgpApi; import org.openintents.openpgp.util.OpenPgpApi.OpenPgpDataSource; public class PgpMessageBuilder extends MessageBuilder { public static final int REQUEST_USER_INTERACTION = 1; private OpenPgpApi openPgpApi; private MimeMessage currentProcessedMimeMessage; private ComposeCryptoStatus cryptoStatus; private boolean opportunisticSkipEncryption; private boolean opportunisticSecondPass; public PgpMessageBuilder(Context context) { super(context); } public void setOpenPgpApi(OpenPgpApi openPgpApi) { this.openPgpApi = openPgpApi; } @Override protected void buildMessageInternal() { try { currentProcessedMimeMessage = build(); } catch (MessagingException me) { queueMessageBuildException(me); return; } startOrContinueBuildMessage(null); } @Override public void buildMessageOnActivityResult(int requestCode, Intent userInteractionResult) { startOrContinueBuildMessage(userInteractionResult); } private void startOrContinueBuildMessage(@Nullable Intent pgpApiIntent) { try { boolean shouldSign = cryptoStatus.isSigningEnabled(); boolean shouldEncrypt = cryptoStatus.isEncryptionEnabled() && !opportunisticSkipEncryption; boolean isPgpInlineMode = cryptoStatus.isPgpInlineModeEnabled(); if (!shouldSign && !shouldEncrypt) { return; } if (pgpApiIntent == null) { pgpApiIntent = buildOpenPgpApiIntent(shouldSign, shouldEncrypt, isPgpInlineMode); } PendingIntent returnedPendingIntent = launchOpenPgpApiIntent(pgpApiIntent, shouldEncrypt || isPgpInlineMode, isPgpInlineMode); if (returnedPendingIntent != null) { queueMessageBuildPendingIntent(returnedPendingIntent, REQUEST_USER_INTERACTION); return; } if (opportunisticSkipEncryption && !opportunisticSecondPass) { opportunisticSecondPass = true; startOrContinueBuildMessage(null); return; } queueMessageBuildSuccess(currentProcessedMimeMessage); } catch (MessagingException me) { queueMessageBuildException(me); } } @NonNull private Intent buildOpenPgpApiIntent(boolean shouldSign, boolean shouldEncrypt, boolean isPgpInlineMode) throws MessagingException { Intent pgpApiIntent; if (shouldEncrypt) { if (!shouldSign) { throw new IllegalStateException("encrypt-only is not supported at this point and should never happen!"); } // pgpApiIntent = new Intent(shouldSign ? OpenPgpApi.ACTION_SIGN_AND_ENCRYPT : OpenPgpApi.ACTION_ENCRYPT); pgpApiIntent = new Intent(OpenPgpApi.ACTION_SIGN_AND_ENCRYPT); long[] encryptKeyIds = cryptoStatus.getEncryptKeyIds(); if (encryptKeyIds != null) { pgpApiIntent.putExtra(OpenPgpApi.EXTRA_KEY_IDS, encryptKeyIds); } if(!isDraft()) { String[] encryptRecipientAddresses = cryptoStatus.getRecipientAddresses(); boolean hasRecipientAddresses = encryptRecipientAddresses != null && encryptRecipientAddresses.length > 0; if (!hasRecipientAddresses) { throw new MessagingException("encryption is enabled, but no encryption key specified!"); } pgpApiIntent.putExtra(OpenPgpApi.EXTRA_USER_IDS, encryptRecipientAddresses); pgpApiIntent.putExtra(OpenPgpApi.EXTRA_ENCRYPT_OPPORTUNISTIC, cryptoStatus.isEncryptionOpportunistic()); } } else { pgpApiIntent = new Intent(isPgpInlineMode ? OpenPgpApi.ACTION_SIGN : OpenPgpApi.ACTION_DETACHED_SIGN); } if (shouldSign) { pgpApiIntent.putExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, cryptoStatus.getSigningKeyId()); } pgpApiIntent.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true); return pgpApiIntent; } private PendingIntent launchOpenPgpApiIntent(@NonNull Intent openPgpIntent, boolean captureOutputPart, boolean writeBodyContentOnly) throws MessagingException { final MimeBodyPart bodyPart = currentProcessedMimeMessage.toBodyPart(); String[] contentType = currentProcessedMimeMessage.getHeader(MimeHeader.HEADER_CONTENT_TYPE); if (contentType.length > 0) { bodyPart.setHeader(MimeHeader.HEADER_CONTENT_TYPE, contentType[0]); } bodyPart.setUsing7bitTransport(); OpenPgpDataSource dataSource = createOpenPgpDataSourceFromBodyPart(bodyPart, writeBodyContentOnly); BinaryTempFileBody pgpResultTempBody = null; OutputStream outputStream = null; if (captureOutputPart) { try { pgpResultTempBody = new BinaryTempFileBody(MimeUtil.ENC_7BIT); outputStream = pgpResultTempBody.getOutputStream(); } catch (IOException e) { throw new MessagingException("could not allocate temp file for storage!", e); } } Intent result = openPgpApi.executeApi(openPgpIntent, dataSource, outputStream); switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) { case OpenPgpApi.RESULT_CODE_SUCCESS: mimeBuildMessage(result, bodyPart, pgpResultTempBody); return null; case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED: PendingIntent returnedPendingIntent = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT); if (returnedPendingIntent == null) { throw new MessagingException("openpgp api needs user interaction, but returned no pendingintent!"); } return returnedPendingIntent; case OpenPgpApi.RESULT_CODE_ERROR: OpenPgpError error = result.getParcelableExtra(OpenPgpApi.RESULT_ERROR); if (error == null) { throw new MessagingException("internal openpgp api error"); } boolean isOpportunisticError = error.getErrorId() == OpenPgpError.OPPORTUNISTIC_MISSING_KEYS; if (isOpportunisticError) { skipEncryptingMessage(); return null; } throw new MessagingException(error.getMessage()); } throw new IllegalStateException("unreachable code segment reached - this is a bug"); } @NonNull private OpenPgpDataSource createOpenPgpDataSourceFromBodyPart(final MimeBodyPart bodyPart, final boolean writeBodyContentOnly) throws MessagingException { return new OpenPgpDataSource() { @Override public void writeTo(OutputStream os) throws IOException { try { if (writeBodyContentOnly) { bodyPart.getBody().writeTo(os); } else { bodyPart.writeTo(os); } } catch (MessagingException e) { throw new IOException(e); } } }; } private void mimeBuildMessage( @NonNull Intent result, @NonNull MimeBodyPart bodyPart, @Nullable BinaryTempFileBody pgpResultTempBody) throws MessagingException { if (pgpResultTempBody == null) { boolean shouldHaveResultPart = cryptoStatus.isPgpInlineModeEnabled() || (cryptoStatus.isEncryptionEnabled() && !opportunisticSkipEncryption); if (shouldHaveResultPart) { throw new AssertionError("encryption or pgp/inline is enabled, but no output part - this is a bug!"); } mimeBuildSignedMessage(bodyPart, result); return; } if (cryptoStatus.isPgpInlineModeEnabled()) { mimeBuildInlineMessage(pgpResultTempBody); return; } mimeBuildEncryptedMessage(pgpResultTempBody); } private void mimeBuildSignedMessage(@NonNull BodyPart signedBodyPart, Intent result) throws MessagingException { if (!cryptoStatus.isEncryptionEnabled()) { throw new IllegalStateException("call to mimeBuildSignedMessage while signing isn't enabled!"); } byte[] signedData = result.getByteArrayExtra(OpenPgpApi.RESULT_DETACHED_SIGNATURE); if (signedData == null) { throw new MessagingException("didn't find expected RESULT_DETACHED_SIGNATURE in api call result"); } MimeMultipart multipartSigned = new MimeMultipart(); multipartSigned.setSubType("signed"); multipartSigned.addBodyPart(signedBodyPart); multipartSigned.addBodyPart( new MimeBodyPart(new BinaryMemoryBody(signedData, MimeUtil.ENC_7BIT), "application/pgp-signature")); MimeMessageHelper.setBody(currentProcessedMimeMessage, multipartSigned); String contentType = String.format( "multipart/signed; boundary=\"%s\";\r\n protocol=\"application/pgp-signature\"", multipartSigned.getBoundary()); if (result.hasExtra(OpenPgpApi.RESULT_SIGNATURE_MICALG)) { String micAlgParameter = result.getStringExtra(OpenPgpApi.RESULT_SIGNATURE_MICALG); contentType += String.format("; micalg=\"%s\"", micAlgParameter); } else { Log.e(K9.LOG_TAG, "missing micalg parameter for pgp multipart/signed!"); } currentProcessedMimeMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, contentType); } private void mimeBuildEncryptedMessage(@NonNull Body encryptedBodyPart) throws MessagingException { if (!cryptoStatus.isEncryptionEnabled()) { throw new IllegalStateException("call to mimeBuildEncryptedMessage while encryption isn't enabled!"); } MimeMultipart multipartEncrypted = new MimeMultipart(); multipartEncrypted.setSubType("encrypted"); multipartEncrypted.addBodyPart(new MimeBodyPart(new TextBody("Version: 1"), "application/pgp-encrypted")); multipartEncrypted.addBodyPart(new MimeBodyPart(encryptedBodyPart, "application/octet-stream")); MimeMessageHelper.setBody(currentProcessedMimeMessage, multipartEncrypted); String contentType = String.format( "multipart/encrypted; boundary=\"%s\";\r\n protocol=\"application/pgp-encrypted\"", multipartEncrypted.getBoundary()); currentProcessedMimeMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, contentType); } private void mimeBuildInlineMessage(@NonNull Body inlineBodyPart) throws MessagingException { if (!cryptoStatus.isPgpInlineModeEnabled()) { throw new IllegalStateException("call to mimeBuildInlineMessage while pgp/inline isn't enabled!"); } MimeMessageHelper.setBody(currentProcessedMimeMessage, inlineBodyPart); } private void skipEncryptingMessage() throws MessagingException { if (!cryptoStatus.isEncryptionOpportunistic()) { throw new AssertionError("Got opportunistic error, but encryption wasn't supposed to be opportunistic!"); } opportunisticSkipEncryption = true; } public void setCryptoStatus(ComposeCryptoStatus cryptoStatus) { this.cryptoStatus = cryptoStatus; } }
package br.com.dbsoft.util; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.sql.Date; import java.util.Arrays; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.log4j.Logger; import br.com.dbsoft.core.DBSSDK.APP_SERVER_PROPERTY; public class DBSFile { private static Logger wLogger = Logger.getLogger(DBSFile.class); public static class FILE_EXTENSION{ public static final String PDF = ".pdf"; public static final String HTML = ".html"; public static final String XML = ".xml"; public static final String XLS = ".xls"; public static final String JASPER= ".jasper"; public static final String JRXML = ".jrxml"; public static final String ZIP = ".zip"; public static final String DOC = ".doc"; public static final String RAR = ".rar"; public static final String TXT = ".txt"; public static final String CSV = ".csv"; } public static class CONTENT_TYPE{ public static final String PDF = "application/pdf"; public static final String XML = "application/xml"; public static final String XLS = "application/excel"; } public static enum SORT_BY{ NAME, SIZE, MODIFIED_DATA } public static enum SORT_ORDER{ ASCENDING, DESCENDING } public static String getFileNameJASPER(String pReportFileName){ return pvGetFileNameWithExtention(pReportFileName, FILE_EXTENSION.JASPER); } public static String getFileNameJRXML(String pReportFileName){ return pvGetFileNameWithExtention(pReportFileName, FILE_EXTENSION.JRXML); } public static String getFileNamePDF(String pReportFileName){ return pvGetFileNameWithExtention(pReportFileName, FILE_EXTENSION.PDF); } public static String getFileNameXML(String pReportFileName){ return pvGetFileNameWithExtention(pReportFileName, FILE_EXTENSION.XML); } public static String getFileNameXLS(String pReportFileName){ return pvGetFileNameWithExtention(pReportFileName, FILE_EXTENSION.XLS); } public static String getFileNameHTML(String pReportFileName){ return pvGetFileNameWithExtention(pReportFileName, FILE_EXTENSION.HTML); } public static String getFileNameZIP(String pReportFileName){ return pvGetFileNameWithExtention(pReportFileName, FILE_EXTENSION.ZIP); } public static String getFileNameDOC(String pReportFileName){ return pvGetFileNameWithExtention(pReportFileName, FILE_EXTENSION.DOC); } public static String getFileNameRAR(String pReportFileName){ return pvGetFileNameWithExtention(pReportFileName, FILE_EXTENSION.RAR); } public static Boolean isEqual(String pFilePathA, String pFilePathB){ File xFileA = new File(pFilePathA); File xFileB = new File(pFilePathA); if (xFileA.exists() && xFileB.exists()){ if (xFileA.lastModified() == xFileB.lastModified() && xFileA.length() == xFileB.length()){ return true; } } return false; } public static Boolean isEqualDate(String pFilePathA, String pFilePathB){ File xFileA = new File(pFilePathA); File xFileB = new File(pFilePathB); if (xFileA.exists() && xFileB.exists()){ if (xFileA.lastModified() == xFileB.lastModified()){ return true; } } return false; } public static Boolean setLastModifiedDate(String pFilePath, Date pDateTime){ return setLastModifiedDate(pFilePath, pDateTime); } public static Boolean setLastModifiedDate(String pFilePath, long pDateTime){ File xFileA = new File(pFilePath); if (xFileA.exists()){ xFileA.setLastModified(pDateTime); } return false; } public static Boolean copyLastModifiedData(String pFilePathFrom, String pFilePathTo){ File xFileA = new File(pFilePathFrom); File xFileB = new File(pFilePathTo); if (xFileA.exists() && xFileB.exists()){ if (xFileA.lastModified() != xFileB.lastModified()){ xFileB.setLastModified(xFileA.lastModified()); } } return false; } public static File unzipFile(String pZipFileName) { return unzipFile(pZipFileName, null); } public static File unzipFile(String pZipFileName, String pDestinationFolder) { @SuppressWarnings("rawtypes") Enumeration xZipFileElements; ZipFile xZipFile = null; ZipEntry xZipFileObject = null; if (pZipFileName == null){ return null; } File xFile = new File(pZipFileName); if (pDestinationFolder == null){ pDestinationFolder = xFile.getParent(); if (pDestinationFolder == null){ wLogger.error("Pasta destino para descompatar " + pZipFileName + " não foi encontrada."); return null; } } if (xFile.exists() && xFile.canRead()) { pDestinationFolder = DBSFile.getPathFromFolderName(pDestinationFolder); try { xZipFile = new ZipFile(pZipFileName); xZipFileElements = xZipFile.entries(); while (xZipFileElements.hasMoreElements()) { xZipFileObject = (ZipEntry) xZipFileElements.nextElement(); pvCopyInputStream(xZipFile.getInputStream(xZipFileObject), new BufferedOutputStream(new FileOutputStream(pDestinationFolder + xZipFileObject.getName()))); xFile = new File(pDestinationFolder + xZipFileObject.getName()); xFile.setLastModified(xZipFileObject.getTime()); } } catch (IOException e) { wLogger.error("Erro ao descompactar arquivo " + pZipFileName, e); return null; }finally{ try { if (xZipFile!=null){ xZipFile.close(); } } catch (IOException e) { wLogger.error("Erro ao descompactar:close", e); } } // xFile = new File(pDestinationFolder + xZipFileObject.getName()); } else { pZipFileName = null; wLogger.error("unZip: não é possível ler arquivo " + pZipFileName + "."); } return xFile; } public static boolean zipFile(String pZipFileName, String... pFileNames){ String[] xFileName = pFileNames; if (!DBSFile.exists(xFileName[0])) { return false; } try (FileSystem xZipFileSystem = pvCreateZipFileSystem(pZipFileName, true)) { final Path xRoot = xZipFileSystem.getPath("/"); for (String xFilename : pFileNames) { final Path xSourcePath = Paths.get(xFilename); if (!Files.isDirectory(xSourcePath)) { final Path XDestinationPath = xZipFileSystem.getPath( xRoot.toString(), xSourcePath.toString()); final Path xParentPath = XDestinationPath.getFileName(); if (Files.notExists(xParentPath)) { //System.out.printf("Compress File %s\n", xParentPath); Files.copy(xSourcePath, xParentPath, StandardCopyOption.COPY_ATTRIBUTES); return true; } } else { Files.walkFileTree(xSourcePath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile( Path pFileSource, BasicFileAttributes pAttrs) throws IOException { final Path xFileDestination = xZipFileSystem .getPath(xRoot.toString(), pFileSource.toString()); Files.copy(pFileSource, xFileDestination, StandardCopyOption.REPLACE_EXISTING); return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory( Path dir, BasicFileAttributes attrs) throws IOException { final Path xDirToCreate = xZipFileSystem .getPath(xRoot.toString(), dir.toString()); System.out.println(xDirToCreate .getFileName()); if (Files.notExists(xDirToCreate .getFileName())) { System.out.printf( "Creating directory %s\n", xDirToCreate); Files.createDirectories(xDirToCreate); } return FileVisitResult.CONTINUE; } }); } } return true; } catch (Exception e) { wLogger.error(e); return false; } } /* // byte[] xReadBuffer = new byte[xFilename.length]; // // try { // ZipOutputStream xOutputZip = new ZipOutputStream( // new FileOutputStream(pDestinationFile)); // // for (int i = 0; i < xFilename.length; i++) { // FileInputStream xInput = new FileInputStream(pSourceFile); // xOutputZip.putNextEntry(new ZipEntry(pSourceFile)); // int xFileLength; // while ((xFileLength = xInput.read(xReadBuffer)) > 0) { // xOutputZip.write(xReadBuffer, 0, xFileLength); // } // // xOutputZip.closeEntry(); // xInput.close(); // } // // xOutputZip.close(); // return true; // } catch (IOException e) { // return false; // } // }*/ @SuppressWarnings("resource") public static boolean download(String pSourceURL, String pDestinationPath) { try { URL xWebSite = new URL(pSourceURL); ReadableByteChannel xByteChannel = Channels.newChannel(xWebSite .openStream()); FileOutputStream xOutputStream; xOutputStream = new FileOutputStream(pDestinationPath); xOutputStream.getChannel().transferFrom(xByteChannel, 0, 1 << 24); return true; } catch (IOException e) { wLogger.error(e); return false; } } public static boolean upload(String pDestionationURL, String pSourceFile) { if (!DBSFile.exists(pSourceFile)) { return false; } StringBuffer xStringBuffer = new StringBuffer(pDestionationURL); BufferedInputStream xBufferedInput = null; BufferedOutputStream xBufferedOutput = null; try { URL xUrl = new URL(xStringBuffer.toString()); URLConnection xUrlconnection = xUrl.openConnection(); xBufferedOutput = new BufferedOutputStream( xUrlconnection.getOutputStream()); xBufferedInput = new BufferedInputStream(new FileInputStream( pSourceFile)); int xI; while ((xI = xBufferedInput.read()) != -1) { xBufferedOutput.write(xI); } xBufferedInput.close(); xBufferedOutput.close(); return true; } catch (Exception e) { wLogger.error(e); return false; } } public static boolean move(String pOld, String pNew) { if (!DBSFile.exists(pOld)) { return false; } File xOldFile = new File(pOld); File xNewFile = new File(pNew); if (xOldFile.exists() && !xNewFile.exists()){ return xOldFile.renameTo(xNewFile); }else{ wLogger.error("Move não pode ser executado, por destino já existir."); return false; } } public static boolean copy(String pSourceFile, String pFileCopied) { if (!DBSFile.exists(pSourceFile)) { return false; } Path xPathSourceFile = Paths.get(pSourceFile); Path xPathFileCopied = Paths.get(pFileCopied); try { Files.copy(xPathSourceFile, xPathFileCopied, REPLACE_EXISTING, COPY_ATTRIBUTES); return true; } catch (IOException e) { wLogger.error(e); return false; } } public static boolean delete(String pFile) { if (!DBSFile.exists(pFile)) { return false; } File xFileToDelete = new File(pFile); boolean xIsOk = xFileToDelete.delete(); if (xIsOk) { //System.out.println("Arquivo deletado"); return true; } else { return false; } } /** * Retorna se arquivo existe. * @param pFile path completo do arquivo. * @return */ public static boolean exists(String pFile) { boolean xExists = false; if (pFile==null){ return false; } try{ File xFile = new File(pFile); xExists = xFile.exists(); }catch(Exception e){ xExists = false; wLogger.error(e); } return xExists; } public static boolean mkDir(String pPath){ if (pPath == null){ return false; } try{ if (!exists(pPath)){ File xFile = new File(pPath); return xFile.mkdirs(); }else{ return true; } }catch(Exception e){ wLogger.error(e); return false; } } public static boolean mkDir(File pFile){ if (pFile == null){ return false; } try{ if (pFile.getParent() != null){ return mkDir(pFile.getParent()); }else{ wLogger.error("Diretório a ser criado não foi informado."); return false; } }catch(Exception e){ wLogger.error(e); return false; } } public static Date getFileDateModified(String pFile){ if (pFile == null){ return null; } try{ File xFile = new File(pFile); return DBSDate.toDate(xFile.lastModified()); }catch(Exception e){ wLogger.error(e); return null; } } public static String getPathFromFileName(String pFileName){ return pvGetPath(pFileName, true); } public static String getPathFromFolderName(String pFolderName){ return pvGetPath(pFolderName, false); } public static String getServerPath(){ return System.getProperty(APP_SERVER_PROPERTY.PATH.JBOSS); } public static String getFileNameFromPath(String pPath){ if (pPath == null){return "";} int xI = pPath.lastIndexOf("/"); if (xI == -1){ return pPath; }else{ return DBSString.getSubString(pPath, xI + 2, pPath.length()); } } public static File[] getFilesFromPath(String pPath){ return getFilesFromPath(pPath, SORT_BY.NAME, SORT_ORDER.ASCENDING); } public static File[] getFilesFromPath(String pPath, SORT_BY pSortBy, SORT_ORDER pSortOrder){ if (pPath == null){return null;} try{ pPath = getPathFromFolderName(pPath); File xFile = new File(pPath); File[] xFiles = null; if (!xFile.exists()){ System.out.println("Caminho " + pPath + " inexistente."); wLogger.error("Caminho " + pPath + " inexistente."); return null; } if (!xFile.isDirectory()){ System.out.println("Caminho " + pPath + " não é um pasta."); wLogger.error("Caminho " + pPath + " não é um pasta."); return null; } xFiles = xFile.listFiles(); if (pSortBy == SORT_BY.MODIFIED_DATA){ if (pSortOrder == SORT_ORDER.ASCENDING){ Arrays.sort(xFiles, new Comparator<File>(){ @Override public int compare(File pFile1, File pFile2){ return Long.valueOf(pFile1.lastModified()).compareTo(pFile2.lastModified()); } }); }else{ Arrays.sort(xFiles, new Comparator<File>(){ @Override public int compare(File pFile1, File pFile2){ return -Long.valueOf(pFile1.lastModified()).compareTo(pFile2.lastModified()); } }); } }else if (pSortBy == SORT_BY.NAME){ if (pSortOrder == SORT_ORDER.ASCENDING){ Arrays.sort(xFiles, new Comparator<File>(){ @Override public int compare(File pFile1, File pFile2){ return String.CASE_INSENSITIVE_ORDER.compare(pFile1.getName(), pFile2.getName()); } }); }else{ Arrays.sort(xFiles, new Comparator<File>(){ @Override public int compare(File pFile1, File pFile2){ return -String.CASE_INSENSITIVE_ORDER.compare(pFile1.getName(), pFile2.getName()); } }); } }else if (pSortBy == SORT_BY.SIZE){ if (pSortOrder == SORT_ORDER.ASCENDING){ Arrays.sort(xFiles, new Comparator<File>(){ @Override public int compare(File pFile1, File pFile2){ return Long.valueOf(pFile1.length()).compareTo(pFile2.length()); } }); }else{ Arrays.sort(xFiles, new Comparator<File>(){ @Override public int compare(File pFile1, File pFile2){ return -Long.valueOf(pFile1.length()).compareTo(pFile2.length()); } }); } } return xFiles; }catch(Exception e){ wLogger.error(e); return null; } } public static void displayFiles(File[] files) { for (File file : files) { System.out.printf("File: %-20s Last Modified:" + new Date(file.lastModified()) + " size:" + file.length() + "\n", file.getName()); } } // Private private static String pvGetPath(String pName, boolean pHasFile){ if (pName != null){ try { URI xURI = new URI(pName).normalize(); String xHost = ""; String xPath = xURI.getPath(); //Procotolo if (xURI.getScheme()!=null){ xHost = xURI.getScheme() + ":"; } //Servidor if (xURI.getHost()!=null){ xHost += "//" + xURI.getHost(); } //Inclui barra inicial if (xURI.getHost()==null && !xPath.startsWith("/")){ xPath = "/" + xPath; } if (pHasFile){ if (!xPath.endsWith("/")){ File xFile = new File(xPath); xPath = DBSObject.getNotNull(xFile.getParent(),""); } } //Inclui barra final if (!xPath.endsWith("/")){ xPath += "/"; } return xHost + xPath; } catch (URISyntaxException e) { wLogger.error(e); return ""; } } return ""; } private static FileSystem pvCreateZipFileSystem(String pZipFilename, boolean pCreate) throws IOException { final Path xPath = Paths.get(pZipFilename); final URI xUri = URI.create("jar:file:" + xPath.toUri().getPath()); final Map<String, String> xEnv = new HashMap<>(); if (pCreate) { xEnv.put("create", "true"); } return FileSystems.newFileSystem(xUri, xEnv); } private static final void pvCopyInputStream(InputStream pInputStream, OutputStream pOutputStream) throws IOException { byte[] xBuffer = new byte[1024]; int xFileLentgh; while ((xFileLentgh = pInputStream.read(xBuffer)) >= 0) { pOutputStream.write(xBuffer, 0, xFileLentgh); } pInputStream.close(); pOutputStream.close(); } private static String pvGetFileNameWithExtention(String pFileName, String pExtension){ return pFileName + pExtension; } }
package org.jboss.as.weld.deployment.processors; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Set; import org.jboss.as.ee.component.ComponentDescription; import org.jboss.as.ee.component.EEModuleDescription; import org.jboss.as.ee.weld.WeldDeploymentMarker; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.weld.WeldLogger; import org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl; import org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl.BeanArchiveType; import org.jboss.as.weld.deployment.ExplicitBeanArchiveMetadata; import org.jboss.as.weld.deployment.ExplicitBeanArchiveMetadataContainer; import org.jboss.as.weld.deployment.PropertyReplacingBeansXmlParser; import org.jboss.as.weld.deployment.UrlScanner; import org.jboss.as.weld.deployment.WeldAttachments; import org.jboss.as.weld.services.bootstrap.WeldJaxwsInjectionServices; import org.jboss.as.weld.services.bootstrap.WeldJpaInjectionServices; import org.jboss.modules.DependencySpec; import org.jboss.modules.Module; import org.jboss.modules.ModuleDependencySpec; import org.jboss.modules.ModuleLoadException; import org.jboss.modules.ModuleLoader; import org.jboss.modules.Resource; import org.jboss.weld.bootstrap.spi.BeansXml; import org.jboss.weld.injection.spi.JaxwsInjectionServices; import org.jboss.weld.injection.spi.JpaInjectionServices; import org.jboss.weld.xml.BeansXmlParser; /** * Deployment processor that builds bean archives from external deployments. * <p/> * This is only run at the top level, as multiple sub deployments can reference the same * beans.xml information, so we have to iterate through all bean deployment archives in this processor, to prevent * beans.xml from being potentially parsed twice. * <p/> * * @author Stuart Douglas * @author Jozef Hartinger */ public class ExternalBeanArchiveProcessor implements DeploymentUnitProcessor { private static final String META_INF_BEANS_XML = "META-INF/beans.xml"; @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (!WeldDeploymentMarker.isPartOfWeldDeployment(deploymentUnit)) { return; } if (deploymentUnit.getParent() != null) { return; } final Set<String> componentClassNames = new HashSet<>(); final String beanArchiveIdPrefix = deploymentUnit.getName() + ".external."; final List<DeploymentUnit> deploymentUnits = new ArrayList<DeploymentUnit>(); deploymentUnits.add(deploymentUnit); deploymentUnits.addAll(deploymentUnit.getAttachmentList(Attachments.SUB_DEPLOYMENTS)); PropertyReplacingBeansXmlParser parser = new PropertyReplacingBeansXmlParser(deploymentUnit); final HashSet<URL> existing = new HashSet<URL>(); for (DeploymentUnit deployment : deploymentUnits) { try { final ExplicitBeanArchiveMetadataContainer weldDeploymentMetadata = deployment.getAttachment(ExplicitBeanArchiveMetadataContainer.ATTACHMENT_KEY); if (weldDeploymentMetadata != null) { for (ExplicitBeanArchiveMetadata md : weldDeploymentMetadata.getBeanArchiveMetadata().values()) { existing.add(md.getBeansXmlFile().toURL()); if (md.getAdditionalBeansXmlFile() != null) { existing.add(md.getAdditionalBeansXmlFile().toURL()); } } } } catch (MalformedURLException e) { throw new DeploymentUnitProcessingException(e); } EEModuleDescription moduleDesc = deployment.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION); if(moduleDesc != null) { for(ComponentDescription component : moduleDesc.getComponentDescriptions()) { componentClassNames.add(component.getComponentClassName()); } } } for (DeploymentUnit deployment : deploymentUnits) { final Module module = deployment.getAttachment(Attachments.MODULE); if (module == null) { return; } for (DependencySpec dep : module.getDependencies()) { final Module dependency = loadModuleDependency(dep); if (dependency == null) { continue; } URL url = findExportedLocalBeansXml(dependency); if (url != null && !existing.contains(url)) { if (url.toString().contains("jsf-impl-2.2")) { continue; } /* * Workaround for resteasy-cdi bundling beans.xml */ if (url.toString().contains("resteasy-cdi")) { continue; } WeldLogger.DEPLOYMENT_LOGGER.debugf("Found external beans.xml: %s", url.toString()); final BeansXml beansXml = parseBeansXml(url, parser, deploymentUnit); final UrlScanner urlScanner = new UrlScanner(); final List<String> discoveredClasses = new ArrayList<String>(); if(!urlScanner.handleBeansXml(url, discoveredClasses)) { continue; } discoveredClasses.removeAll(componentClassNames); final BeanDeploymentArchiveImpl bda = new BeanDeploymentArchiveImpl(new HashSet<String>(discoveredClasses), beansXml, dependency, beanArchiveIdPrefix + url.toExternalForm(), BeanArchiveType.EXTERNAL); WeldLogger.DEPLOYMENT_LOGGER.beanArchiveDiscovered(bda); final JpaInjectionServices jpaInjectionServices = new WeldJpaInjectionServices(deploymentUnit); final JaxwsInjectionServices jaxwsInjectionServices = new WeldJaxwsInjectionServices(deploymentUnit); bda.getServices().add(JpaInjectionServices.class, jpaInjectionServices); bda.getServices().add(JaxwsInjectionServices.class, jaxwsInjectionServices); deploymentUnit.addToAttachmentList(WeldAttachments.ADDITIONAL_BEAN_DEPLOYMENT_MODULES, bda); // make sure that if this beans.xml is seen by some other module, it is not processed twice existing.add(url); } } } } private URL findExportedLocalBeansXml(Module dependencyModule) { Enumeration<URL> exported = dependencyModule.getExportedResources(META_INF_BEANS_XML); if (exported.hasMoreElements()) { Set<URL> exportedSet = new HashSet<>(Collections.list(exported)); Collection<Resource> locals = dependencyModule.getClassLoader().loadResourceLocal(META_INF_BEANS_XML); if (!locals.isEmpty()) { URL local = locals.iterator().next().getURL(); if (exportedSet.contains(local)) { return local; } } } return null; } private Module loadModuleDependency(DependencySpec dep) { if (dep instanceof ModuleDependencySpec) { ModuleDependencySpec dependency = (ModuleDependencySpec) dep; final ModuleLoader loader = dependency.getModuleLoader(); if (loader != null) { try { return dependency.getModuleLoader().loadModule(dependency.getIdentifier()); } catch (ModuleLoadException e) { return null; } } } return null; } @Override public void undeploy(DeploymentUnit context) { } private BeansXml parseBeansXml(URL beansXmlFile, BeansXmlParser parser, final DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException { return parser.parse(beansXmlFile); } }
package ch.lambdaj.group; import java.util.*; public class LeafGroup<T> implements Group<T> { private List<T> list; private Map<String, Object> headMap = new TreeMap<String, Object>(); @SuppressWarnings("unchecked") LeafGroup(Map<String, Object> map, String childrenNodeName) { headMap = new TreeMap<String, Object>(map); list = (List<T>)headMap.remove(childrenNodeName); } public List<T> find(String key) { return list; } public List<T> find(Object key) { return find(key.toString()); } public List<T> findAll() { return list; } public Group<T> findGroup(String key) { return this; } public Group<T> findGroup(Object key) { return findGroup(key.toString()); } public List<Group<T>> subgroups() { return new ArrayList<Group<T>>(); } public int getSize() { return list.size(); } public boolean isLeaf() { return true; } public Set<String> keySet() { return new HashSet<String>(); } public String getHeadValue(String key) { Object value = headMap.get(key); return value == null ? "" : value.toString(); } public Set<String> getHeads() { return headMap.keySet(); } }
package com.intellij.ui; import com.intellij.util.ui.UIUtil; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Collection; import org.jetbrains.annotations.NonNls; public class CollapsiblePanel extends JPanel { private final JButton myToggleCollapseButton; private final JComponent myContent; private boolean myIsCollapsed; private final Collection<CollapsingListener> myListeners = new ArrayList<CollapsingListener>(); private boolean myIsInitialized = false; private final Icon myExpandIcon; private final Icon myCollapseIcon; private Label myTitleLabel; public static final KeyStroke LEFT_KEY_STROKE = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0); public static final KeyStroke RIGHT_KEY_STROKE = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0); @NonNls public static final String EXPAND = "expand"; @NonNls public static final String COLLAPSE = "collapse"; public CollapsiblePanel(JComponent content, boolean collapseButtonAtLeft, boolean isCollapsed, Icon collapseIcon, Icon expandIcon, String title) { super(new GridBagLayout()); myContent = content; setBackground(content.getBackground()); myExpandIcon = expandIcon; myCollapseIcon = collapseIcon; final Dimension buttonDimension = getButtonDimension(); myToggleCollapseButton = new JButton(); myToggleCollapseButton.setOpaque(false); myToggleCollapseButton.setBorderPainted(false); myToggleCollapseButton.setBackground(content.getBackground()); myToggleCollapseButton.setSize(buttonDimension); myToggleCollapseButton.setPreferredSize(buttonDimension); myToggleCollapseButton.setMinimumSize(buttonDimension); myToggleCollapseButton.setMaximumSize(buttonDimension); myToggleCollapseButton.setFocusable(true); myToggleCollapseButton.getActionMap().put(COLLAPSE, new AbstractAction() { public void actionPerformed(ActionEvent e) { collapse(); } }); myToggleCollapseButton.getActionMap().put(EXPAND, new AbstractAction() { public void actionPerformed(ActionEvent e) { expand(); } }); myToggleCollapseButton.getInputMap().put(LEFT_KEY_STROKE, COLLAPSE); myToggleCollapseButton.getInputMap().put(RIGHT_KEY_STROKE, EXPAND); final int iconAnchor = collapseButtonAtLeft ? GridBagConstraints.WEST : GridBagConstraints.EAST; add(myToggleCollapseButton, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, iconAnchor, GridBagConstraints.NONE, new Insets(-5, collapseButtonAtLeft ? 0 : -5, 0, collapseButtonAtLeft ? -5 : 0), 0, 0)); if (title != null) { myTitleLabel = new Label(title); myTitleLabel.setFont(UIUtil.getLabelFont().deriveFont(Font.BOLD)); myTitleLabel.setBackground(content.getBackground()); add(myTitleLabel, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(-5, -3, 0, -3), 0, 0)); } myToggleCollapseButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setCollapsed(!myIsCollapsed); } }); setCollapsed(isCollapsed); } private Dimension getButtonDimension() { if (myExpandIcon == null) { return new Dimension(7, 7); } else { return new Dimension(myExpandIcon.getIconWidth(), myExpandIcon.getIconHeight()); } } public CollapsiblePanel(JComponent content, boolean collapseButtonAtLeft) { this(content, collapseButtonAtLeft, false, null, null, null); } protected void setCollapsed(boolean collapse) { try { if (collapse) { if (myIsInitialized) remove(myContent); } else { add(myContent, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); } myIsCollapsed = collapse; Icon icon = getIcon(); if (icon != null){ myToggleCollapseButton.setIcon(icon); myToggleCollapseButton.setBorder(null); myToggleCollapseButton.setBorderPainted(false); myToggleCollapseButton.setToolTipText(getToggleButtonToolTipText()); } if (collapse) { setFocused(true); setSelected(true); } else { myContent.requestFocusInWindow(); } notifyListners(); revalidate(); repaint(); } finally { myIsInitialized = true; } } private String getToggleButtonToolTipText() { if (myIsCollapsed) { return UIBundle.message("collapsible.panel.collapsed.state.tooltip.text"); } else { return UIBundle.message("collapsible.panel.expanded.state.tooltip.text"); } } private Icon getIcon() { if (myIsCollapsed) { return myExpandIcon; } else { return myCollapseIcon; } } private void notifyListners() { CollapsingListener[] listeners = myListeners.toArray(new CollapsingListener[myListeners.size()]); for (CollapsingListener listener : listeners) { listener.onCollapsingChanged(this, isCollapsed()); } } public void addCollapsingListener(CollapsingListener listener) { myListeners.add(listener); } public void removeCollapsingListener(CollapsingListener listener) { myListeners.remove(listener); } public boolean isCollapsed() { return myIsCollapsed; } public void expand() { if (myIsCollapsed) { setCollapsed(false); } } public void collapse() { if (!myIsCollapsed) { setCollapsed(true); } } public void setFocused(boolean focused) { myToggleCollapseButton.requestFocusInWindow(); } public void setSelected(boolean selected) { myToggleCollapseButton.setSelected(selected); } public ActionMap getCollapsibleActionMap(){ return myToggleCollapseButton.getActionMap(); } public InputMap getCollapsibleInputMap(){ return myToggleCollapseButton.getInputMap(); } protected void paintComponent(Graphics g) { updatePanel(); super.paintComponent(g); } private void updatePanel() { if (paintAsSelected()) { setBackground(UIUtil.getTableSelectionBackground()); } else { setBackground(myContent.getBackground()); } } protected void paintChildren(Graphics g) { if (myTitleLabel != null) { updateTitle(); } updateToggleButton(); super.paintChildren(g); } private void updateToggleButton() { if (paintAsSelected()) { myToggleCollapseButton.setBackground(UIUtil.getTableSelectionBackground()); } else { myToggleCollapseButton.setBackground(myContent.getBackground()); } } private void updateTitle() { if (paintAsSelected()) { myTitleLabel.setForeground(UIUtil.getTableSelectionForeground()); myTitleLabel.setBackground(UIUtil.getTableSelectionBackground()); } else { myTitleLabel.setForeground(UIUtil.getLabelForeground()); myTitleLabel.setBackground(myContent.getBackground()); } } private boolean paintAsSelected() { return myToggleCollapseButton.hasFocus() && isCollapsed(); } }