proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/apiimpl/GraphContextMenu.java
GraphContextMenu
createMenuItemFromGraphContextMenuItem
class GraphContextMenu { private final VizConfig config; private final AbstractEngine engine; private final DataBridge dataBridge; public GraphContextMenu() { config = VizController.getInstance().getVizConfig(); engine = VizController.getInstance().getEngine(); dataBridge = VizController.getInstance().getDataBridge(); } public JPopupMenu getMenu() { GraphContextMenuItem[] items = getGraphContextMenuItems(); final List<NodeModel> selectedNodeModels = engine.getSelectedNodes(); Node[] selectedNodes = new Node[selectedNodeModels.size()]; int i = 0; for (NodeModel nm : selectedNodeModels) { selectedNodes[i++] = nm.getNode(); } final Graph graph = dataBridge.getGraph(); JPopupMenu contextMenu = new JPopupMenu(); //Add items ordered: Integer lastItemType = null; for (GraphContextMenuItem item : items) { item.setup(graph, selectedNodes); if (lastItemType == null) { lastItemType = item.getType(); } if (lastItemType != item.getType()) { contextMenu.addSeparator(); } lastItemType = item.getType(); if (item.isAvailable()) { contextMenu.add(createMenuItemFromGraphContextMenuItem(item, graph, selectedNodes)); } } return contextMenu; } /** * <p> * Prepares an array with one new instance of every GraphContextMenuItem and * returns it.</p> * <p> * It also returns the items ordered first by type and then by position.</p> * * @return Array of all GraphContextMenuItem implementations */ public GraphContextMenuItem[] getGraphContextMenuItems() { ArrayList<GraphContextMenuItem> items = new ArrayList<>(); items.addAll(Lookup.getDefault().lookupAll(GraphContextMenuItem.class)); sortItems(items); return items.toArray(new GraphContextMenuItem[0]); } public JMenuItem createMenuItemFromGraphContextMenuItem(final GraphContextMenuItem item, final Graph graph, final Node[] nodes) {<FILL_FUNCTION_BODY>} private void sortItems(ArrayList<? extends GraphContextMenuItem> m) { Collections.sort(m, new Comparator<GraphContextMenuItem>() { @Override public int compare(GraphContextMenuItem o1, GraphContextMenuItem o2) { //Order by type, position. if (o1.getType() == o2.getType()) { return o1.getPosition() - o2.getPosition(); } else { return o1.getType() - o2.getType(); } } }); } }
ContextMenuItemManipulator[] subItems = item.getSubItems(); if (subItems != null && item.canExecute()) { JMenu subMenu = new JMenu(); subMenu.setText(item.getName()); if (item.getDescription() != null && !item.getDescription().isEmpty()) { subMenu.setToolTipText(item.getDescription()); } subMenu.setIcon(item.getIcon()); Integer lastItemType = null; for (ContextMenuItemManipulator subItem : subItems) { ((GraphContextMenuItem) subItem).setup(graph, nodes); if (lastItemType == null) { lastItemType = subItem.getType(); } if (lastItemType != subItem.getType()) { subMenu.addSeparator(); } lastItemType = subItem.getType(); if (subItem.isAvailable()) { subMenu.add(createMenuItemFromGraphContextMenuItem((GraphContextMenuItem) subItem, graph, nodes)); } } if (item.getMnemonicKey() != null) { subMenu.setMnemonic(item.getMnemonicKey());//Mnemonic for opening a sub menu } return subMenu; } else { JMenuItem menuItem = new JMenuItem(); menuItem.setText(item.getName()); if (item.getDescription() != null && !item.getDescription().isEmpty()) { menuItem.setToolTipText(item.getDescription()); } menuItem.setIcon(item.getIcon()); if (item.canExecute()) { menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { new Thread() { @Override public void run() { DataLaboratoryHelper.getDefault().executeManipulator(item); } }.start(); } }); } else { menuItem.setEnabled(false); } if (item.getMnemonicKey() != null) { menuItem.setMnemonic(item.getMnemonicKey());//Mnemonic for executing the action menuItem.setAccelerator(KeyStroke.getKeyStroke(item.getMnemonicKey(), KeyEvent.CTRL_DOWN_MASK));//And the same key mnemonic + ctrl for executing the action (and as a help display for the user!). } return menuItem; }
729
641
1,370
<no_super_class>
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/apiimpl/contextmenuitems/CopyOrMoveToWorkspace.java
CopyOrMoveToWorkspace
getSubItems
class CopyOrMoveToWorkspace extends BasicItem implements NodesManipulator { @Override public void execute() { } @Override public void setup(Node[] nodes, Node clickedNode) { this.nodes = nodes; } @Override public ContextMenuItemManipulator[] getSubItems() {<FILL_FUNCTION_BODY>} @Override public boolean canExecute() { return nodes.length > 0; } @Override public int getType() { return 200; } @Override public Icon getIcon() { return null; } protected abstract boolean isCopy(); }
if (nodes != null) { int i = 0; ArrayList<GraphContextMenuItem> subItems = new ArrayList<>(); if (canExecute()) { subItems.add(new CopyOrMoveToWorkspaceSubItem(null, true, 0, 0, isCopy()));//New workspace ProjectController projectController = Lookup.getDefault().lookup(ProjectController.class); for (final Workspace w : projectController.getCurrentProject().getLookup() .lookup(WorkspaceProvider.class).getWorkspaces()) { GraphContextMenuItem item = new CopyOrMoveToWorkspaceSubItem(w, w != projectController.getCurrentWorkspace(), 1, i, isCopy()); subItems.add(item); i++; } return subItems.toArray(new ContextMenuItemManipulator[0]); } else { return null; } } else { return null; }
178
241
419
<methods>public non-sealed void <init>() ,public java.lang.String getDescription() ,public java.lang.Integer getMnemonicKey() ,public org.gephi.datalab.spi.ContextMenuItemManipulator[] getSubItems() ,public org.gephi.datalab.spi.ManipulatorUI getUI() ,public boolean isAvailable() ,public void setup(Node[], Node) ,public void setup(Graph, Node[]) <variables>protected Graph graph,protected Node[] nodes
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/apiimpl/contextmenuitems/CopyOrMoveToWorkspaceSubItem.java
CopyOrMoveToWorkspaceSubItem
copyToWorkspace
class CopyOrMoveToWorkspaceSubItem extends BasicItem implements NodesManipulator { private final Workspace workspace; private final boolean canExecute; private final int type; private final int position; private final boolean copy; /** * Constructor with copy or move settings * * @param workspace Workspace to copy or move, or null to use new workspace * @param canExecute canExecute * @param type type * @param position position * @param copy True to copy, false to move */ public CopyOrMoveToWorkspaceSubItem(Workspace workspace, boolean canExecute, int type, int position, boolean copy) { this.workspace = workspace; this.canExecute = canExecute; this.type = type; this.position = position; this.copy = copy; } @Override public void setup(Node[] nodes, Node clickedNode) { this.nodes = nodes; } @Override public void execute() { if (copy) { copyToWorkspace(workspace); } else { moveToWorkspace(workspace); } } @Override public String getName() { if (workspace != null) { return workspace.getLookup().lookup(WorkspaceInformation.class).getName(); } else { return NbBundle.getMessage(CopyOrMoveToWorkspaceSubItem.class, copy ? "GraphContextMenu_CopyToWorkspace_NewWorkspace" : "GraphContextMenu_MoveToWorkspace_NewWorkspace"); } } @Override public boolean canExecute() { return canExecute; } @Override public int getType() { return type; } @Override public int getPosition() { return position; } @Override public Icon getIcon() { return null; } public boolean copyToWorkspace(Workspace workspace) {<FILL_FUNCTION_BODY>} public void moveToWorkspace(Workspace workspace) { if (copyToWorkspace(workspace)) { delete(); } } public void delete() { Graph g = Lookup.getDefault().lookup(GraphController.class).getGraphModel().getGraph(); g.removeAllNodes(Arrays.asList(nodes)); } }
ProjectController projectController = Lookup.getDefault().lookup(ProjectController.class); GraphController graphController = Lookup.getDefault().lookup(GraphController.class); Workspace currentWorkspace = projectController.getCurrentWorkspace(); GraphModel currentGraphModel = graphController.getGraphModel(currentWorkspace); GraphModel targetGraphModel; if (workspace == null) { workspace = projectController.newWorkspace(currentWorkspace.getProject()); targetGraphModel = graphController.getGraphModel(workspace); targetGraphModel.setConfiguration(currentGraphModel.getConfiguration()); targetGraphModel.setTimeFormat(currentGraphModel.getTimeFormat()); targetGraphModel.setTimeZone(currentGraphModel.getTimeZone()); } else { targetGraphModel = graphController.getGraphModel(workspace); } currentGraphModel.getGraph().readLock(); try { targetGraphModel.bridge().copyNodes(nodes); Graph targetGraph = targetGraphModel.getGraph(); Graph visibleCurrentGraph = currentGraphModel.getGraphVisible(); List<Edge> edgesToRemove = new ArrayList<>(); for (Edge edge : targetGraph.getEdges()) { if (!visibleCurrentGraph.hasEdge(edge.getId())) { edgesToRemove.add(edge); } } if (!edgesToRemove.isEmpty()) { targetGraph.removeAllEdges(edgesToRemove); } return true; } catch (Exception e) { String error = NbBundle.getMessage(CopyOrMoveToWorkspace.class, "GraphContextMenu_CopyOrMoveToWorkspace_ConfigurationNotCompatible"); String title = NbBundle.getMessage(CopyOrMoveToWorkspace.class, "GraphContextMenu_CopyOrMoveToWorkspace_ConfigurationNotCompatible_Title"); JOptionPane.showMessageDialog(null, error, title, JOptionPane.ERROR_MESSAGE); return false; } finally { currentGraphModel.getGraph().readUnlockAll(); }
618
511
1,129
<methods>public non-sealed void <init>() ,public java.lang.String getDescription() ,public java.lang.Integer getMnemonicKey() ,public org.gephi.datalab.spi.ContextMenuItemManipulator[] getSubItems() ,public org.gephi.datalab.spi.ManipulatorUI getUI() ,public boolean isAvailable() ,public void setup(Node[], Node) ,public void setup(Graph, Node[]) <variables>protected Graph graph,protected Node[] nodes
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/apiimpl/contextmenuitems/Delete.java
Delete
execute
class Delete extends BasicItem { @Override public void execute() {<FILL_FUNCTION_BODY>} @Override public String getName() { return NbBundle.getMessage(Delete.class, "GraphContextMenu_Delete"); } @Override public boolean canExecute() { return nodes.length > 0; } @Override public int getType() { return 200; } @Override public int getPosition() { return 0; } @Override public Icon getIcon() { return ImageUtilities.loadImageIcon("VisualizationImpl/delete.png", false); } @Override public Integer getMnemonicKey() { return KeyEvent.VK_D; } }
NotifyDescriptor.Confirmation notifyDescriptor = new NotifyDescriptor.Confirmation( NbBundle.getMessage(Delete.class, "GraphContextMenu.Delete.message"), NbBundle.getMessage(Delete.class, "GraphContextMenu.Delete.message.title"), NotifyDescriptor.YES_NO_OPTION); if (DialogDisplayer.getDefault().notify(notifyDescriptor).equals(NotifyDescriptor.YES_OPTION)) { GraphElementsController gec = Lookup.getDefault().lookup(GraphElementsController.class); gec.deleteNodes(nodes); }
209
145
354
<methods>public non-sealed void <init>() ,public java.lang.String getDescription() ,public java.lang.Integer getMnemonicKey() ,public org.gephi.datalab.spi.ContextMenuItemManipulator[] getSubItems() ,public org.gephi.datalab.spi.ManipulatorUI getUI() ,public boolean isAvailable() ,public void setup(Node[], Node) ,public void setup(Graph, Node[]) <variables>protected Graph graph,protected Node[] nodes
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/apiimpl/contextmenuitems/Free.java
Free
canExecute
class Free extends BasicItem { @Override public void execute() { GraphElementsController gec = Lookup.getDefault().lookup(GraphElementsController.class); gec.setNodesFixed(nodes, false); } @Override public String getName() { return NbBundle.getMessage(Free.class, "GraphContextMenu_Free"); } @Override public boolean canExecute() {<FILL_FUNCTION_BODY>} @Override public int getType() { return 300; } @Override public int getPosition() { return 100; } @Override public Icon getIcon() { return ImageUtilities.loadImageIcon("VisualizationImpl/free.png", false); } @Override public Integer getMnemonicKey() { return KeyEvent.VK_F; } }
GraphElementsController gec = Lookup.getDefault().lookup(GraphElementsController.class); for (Node n : nodes) { if (gec.isNodeFixed(n)) { return true; } } return false;
238
66
304
<methods>public non-sealed void <init>() ,public java.lang.String getDescription() ,public java.lang.Integer getMnemonicKey() ,public org.gephi.datalab.spi.ContextMenuItemManipulator[] getSubItems() ,public org.gephi.datalab.spi.ManipulatorUI getUI() ,public boolean isAvailable() ,public void setup(Node[], Node) ,public void setup(Graph, Node[]) <variables>protected Graph graph,protected Node[] nodes
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/apiimpl/contextmenuitems/SelectInDataLaboratory.java
SelectInDataLaboratory
setup
class SelectInDataLaboratory extends BasicItem { private DataTablesController dtc; @Override public void setup(Graph graph, Node[] nodes) {<FILL_FUNCTION_BODY>} @Override public void execute() { dtc.setNodeTableSelection(nodes); dtc.selectNodesTable(); } @Override public String getName() { return NbBundle.getMessage(SelectInDataLaboratory.class, "GraphContextMenu_SelectInDataLaboratory"); } @Override public boolean isAvailable() { return true; } @Override public boolean canExecute() { return nodes.length >= 1 && dtc.isDataTablesReady(); } @Override public int getType() { return 400; } @Override public int getPosition() { return 100; } @Override public Icon getIcon() { return ImageUtilities.loadImageIcon("VisualizationImpl/table-select.png", false); } @Override public Integer getMnemonicKey() { return KeyEvent.VK_L; } }
this.nodes = nodes; dtc = Lookup.getDefault().lookup(DataTablesController.class); if (!dtc.isDataTablesReady()) { dtc.prepareDataTables(); }
312
59
371
<methods>public non-sealed void <init>() ,public java.lang.String getDescription() ,public java.lang.Integer getMnemonicKey() ,public org.gephi.datalab.spi.ContextMenuItemManipulator[] getSubItems() ,public org.gephi.datalab.spi.ManipulatorUI getUI() ,public boolean isAvailable() ,public void setup(Node[], Node) ,public void setup(Graph, Node[]) <variables>protected Graph graph,protected Node[] nodes
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/apiimpl/contextmenuitems/Settle.java
Settle
canExecute
class Settle extends BasicItem { @Override public void execute() { GraphElementsController gec = Lookup.getDefault().lookup(GraphElementsController.class); gec.setNodesFixed(nodes, true); } @Override public String getName() { return NbBundle.getMessage(Settle.class, "GraphContextMenu_Settle"); } @Override public boolean canExecute() {<FILL_FUNCTION_BODY>} @Override public int getType() { return 300; } @Override public int getPosition() { return 0; } @Override public Icon getIcon() { return ImageUtilities.loadImageIcon("VisualizationImpl/settle.png", false); } @Override public Integer getMnemonicKey() { return KeyEvent.VK_B; } }
GraphElementsController gec = Lookup.getDefault().lookup(GraphElementsController.class); for (Node n : nodes) { if (!gec.isNodeFixed(n)) { return true; } } return false;
240
66
306
<methods>public non-sealed void <init>() ,public java.lang.String getDescription() ,public java.lang.Integer getMnemonicKey() ,public org.gephi.datalab.spi.ContextMenuItemManipulator[] getSubItems() ,public org.gephi.datalab.spi.ManipulatorUI getUI() ,public boolean isAvailable() ,public void setup(Node[], Node) ,public void setup(Graph, Node[]) <variables>protected Graph graph,protected Node[] nodes
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/component/ActionsToolbar.java
ActionsToolbar
actionPerformed
class ActionsToolbar extends JToolBar { //Settings private Color color = new Color(0.6f, 0.6f, 0.6f); private float size = 10.0f; public ActionsToolbar() { initDesign(); initContent(); } private void initContent() { //Center on graph final JButton centerOnGraphButton = new JButton(); centerOnGraphButton.setToolTipText(NbBundle.getMessage(VizBarController.class, "ActionsToolbar.centerOnGraph")); centerOnGraphButton.setIcon( ImageUtilities.loadImageIcon("VisualizationImpl/centerOnGraph.png", false)); centerOnGraphButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { VizController.getInstance().getGraphIO().centerOnGraph(); } }); add(centerOnGraphButton); //Center on zero /*final JButton centerOnZeroButton = new JButton(); centerOnZeroButton.setToolTipText(NbBundle.getMessage(VizBarController.class, "ActionsToolbar.centerOnZero")); centerOnZeroButton.setIcon(ImageUtilities.loadImageIcon("VisualizationImpl/centerOnZero.png", false)); centerOnZeroButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { VizController.getInstance().getGraphIO().centerOnZero(); } }); add(centerOnZeroButton);*/ //Reset colors final JColorButton resetColorButton = new JColorButton(color, true, false); resetColorButton.setToolTipText(NbBundle.getMessage(ActionsToolbar.class, "ActionsToolbar.resetColors")); resetColorButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) {<FILL_FUNCTION_BODY>} }); add(resetColorButton); //Reset sizes //Reset label colors final JButton resetLabelColorButton = new JButton(); resetLabelColorButton.setIcon(ImageUtilities.loadImageIcon("VisualizationImpl/resetLabelColor.png", false)); resetLabelColorButton .setToolTipText(NbBundle.getMessage(ActionsToolbar.class, "ActionsToolbar.resetLabelColors")); resetLabelColorButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { GraphController gc = Lookup.getDefault().lookup(GraphController.class); GraphModel gm = gc.getGraphModel(); Graph graph = gm.getGraphVisible(); for (Node n : graph.getNodes().toArray()) { n.getTextProperties().setColor(Color.BLACK); n.getTextProperties().setAlpha(0f); } for (Edge e : graph.getEdges().toArray()) { e.getTextProperties().setColor(Color.BLACK); e.getTextProperties().setAlpha(0f); } } }); add(resetLabelColorButton); //Reset label visible final JButton resetLabelVisibleButton = new JButton(); resetLabelVisibleButton.setIcon(ImageUtilities.loadImageIcon("VisualizationImpl/resetLabelVisible.png", false)); resetLabelVisibleButton .setToolTipText(NbBundle.getMessage(ActionsToolbar.class, "ActionsToolbar.resetLabelVisible")); resetLabelVisibleButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { GraphController gc = Lookup.getDefault().lookup(GraphController.class); GraphModel gm = gc.getGraphModel(); Graph graph = gm.getGraphVisible(); for (Node n : graph.getNodes()) { n.getTextProperties().setVisible(true); } for (Edge e : graph.getEdges()) { e.getTextProperties().setVisible(true); } } }); add(resetLabelVisibleButton); } private void initDesign() { setFloatable(false); setOrientation(JToolBar.VERTICAL); putClientProperty("JToolBar.isRollover", Boolean.TRUE); //NOI18N setBorder(BorderFactory.createEmptyBorder(0, 2, 15, 2)); setOpaque(true); } @Override public void setEnabled(final boolean enabled) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { for (Component c : getComponents()) { c.setEnabled(enabled); } } }); } @Override public Component add(Component comp) { if (comp instanceof JButton) { UIUtils.fixButtonUI((JButton) comp); } return super.add(comp); } }
color = resetColorButton.getColor(); GraphController gc = Lookup.getDefault().lookup(GraphController.class); GraphModel gm = gc.getGraphModel(); Graph graph = gm.getGraphVisible(); for (Node n : graph.getNodes()) { n.setR(color.getRed() / 255f); n.setG(color.getGreen() / 255f); n.setB(color.getBlue() / 255f); n.setAlpha(1f); } for (Edge e : graph.getEdges()) { e.setR(color.getRed() / 255f); e.setG(color.getGreen() / 255f); e.setB(color.getBlue() / 255f); e.setAlpha(0f); }
1,252
230
1,482
<methods>public void <init>() ,public void <init>(int) ,public void <init>(java.lang.String) ,public void <init>(java.lang.String, int) ,public javax.swing.JButton add(javax.swing.Action) ,public void addSeparator() ,public void addSeparator(java.awt.Dimension) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public java.awt.Component getComponentAtIndex(int) ,public int getComponentIndex(java.awt.Component) ,public java.awt.Insets getMargin() ,public int getOrientation() ,public javax.swing.plaf.ToolBarUI getUI() ,public java.lang.String getUIClassID() ,public boolean isBorderPainted() ,public boolean isFloatable() ,public boolean isRollover() ,public void setBorderPainted(boolean) ,public void setFloatable(boolean) ,public void setLayout(java.awt.LayoutManager) ,public void setMargin(java.awt.Insets) ,public void setOrientation(int) ,public void setRollover(boolean) ,public void setUI(javax.swing.plaf.ToolBarUI) ,public void updateUI() <variables>private boolean floatable,private java.awt.Insets margin,private int orientation,private boolean paintBorder,private static final java.lang.String uiClassID
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/component/CollapsePanel.java
CollapsePanel
initComponents
class CollapsePanel extends javax.swing.JPanel { private boolean extended; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonPanel; private javax.swing.JButton extendButton; // End of variables declaration//GEN-END:variables /** * Creates new form CollapsePanel */ public CollapsePanel() { initComponents(); } public void init(JComponent topBar, final JComponent extendedPanel, boolean extended) { add(topBar, BorderLayout.CENTER); add(extendedPanel, BorderLayout.SOUTH); this.extended = extended; if (extended) { extendButton.setIcon(ImageUtilities.loadImageIcon("VisualizationImpl/arrowDown.png", false)); // NOI18N extendButton.setRolloverIcon(ImageUtilities.loadImageIcon("VisualizationImpl/arrowDown_rollover.png", false)); // NOI18N } else { extendButton.setIcon(ImageUtilities.loadImageIcon("VisualizationImpl/arrowUp.png", false)); // NOI18N extendButton.setRolloverIcon( ImageUtilities.loadImageIcon("VisualizationImpl/arrowUp_rollover.png", false)); // NOI18N } extendButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean ext = CollapsePanel.this.extended; ext = !ext; CollapsePanel.this.extended = ext; if (ext) { extendButton.setIcon(ImageUtilities.loadImageIcon("VisualizationImpl/arrowDown.png", false)); // NOI18N extendButton.setRolloverIcon(ImageUtilities.loadImageIcon("VisualizationImpl/arrowDown_rollover.png", false)); // NOI18N } else { extendButton.setIcon(ImageUtilities.loadImageIcon("VisualizationImpl/arrowUp.png", false)); // NOI18N extendButton.setRolloverIcon(ImageUtilities.loadImageIcon("VisualizationImpl/arrowUp_rollover.png", false)); // NOI18N } extendedPanel.setVisible(ext); // Workaround for JOGL bug 1274 (VizController.getInstance().getDrawable()).reinitWindow(); } }); if (!extended) { extendedPanel.setVisible(extended); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() {<FILL_FUNCTION_BODY>}// </editor-fold>//GEN-END:initComponents }
buttonPanel = new javax.swing.JPanel(); extendButton = new javax.swing.JButton(); setOpaque(true); setLayout(new java.awt.BorderLayout()); buttonPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 0, 3)); extendButton.setToolTipText( org.openide.util.NbBundle.getMessage(CollapsePanel.class, "CollapsePanel.extendButton.text")); // NOI18N extendButton.setAlignmentY(0.0F); extendButton.setBorderPainted(false); extendButton.setContentAreaFilled(false); extendButton.setFocusable(false); buttonPanel.add(extendButton); add(buttonPanel, java.awt.BorderLayout.EAST);
763
214
977
<methods>public void <init>() ,public void <init>(java.awt.LayoutManager) ,public void <init>(boolean) ,public void <init>(java.awt.LayoutManager, boolean) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public javax.swing.plaf.PanelUI getUI() ,public java.lang.String getUIClassID() ,public void setUI(javax.swing.plaf.PanelUI) ,public void updateUI() <variables>private static final java.lang.String uiClassID
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/component/NodeSettingsPanel.java
NodeSettingsPanel
initComponents
class NodeSettingsPanel extends javax.swing.JPanel { /** * Creates new form NodeSettingsPanel */ public NodeSettingsPanel() { initComponents(); } public void setup() { VizModel vizModel = VizController.getInstance().getVizModel(); } public void setEnable(boolean enable) { } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() {<FILL_FUNCTION_BODY>}// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables // End of variables declaration//GEN-END:variables }
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 581, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 74, Short.MAX_VALUE) );
257
144
401
<methods>public void <init>() ,public void <init>(java.awt.LayoutManager) ,public void <init>(boolean) ,public void <init>(java.awt.LayoutManager, boolean) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public javax.swing.plaf.PanelUI getUI() ,public java.lang.String getUIClassID() ,public void setUI(javax.swing.plaf.PanelUI) ,public void updateUI() <variables>private static final java.lang.String uiClassID
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/component/SelectionToolbar.java
SelectionToolbar
initContent
class SelectionToolbar extends JToolBar { private final ButtonGroup buttonGroup; public SelectionToolbar() { initDesign(); buttonGroup = new ButtonGroup(); initContent(); } private void initContent() {<FILL_FUNCTION_BODY>} private void initDesign() { setFloatable(false); setOrientation(JToolBar.VERTICAL); putClientProperty("JToolBar.isRollover", Boolean.TRUE); //NOI18N setOpaque(true); setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 2)); } @Override public void setEnabled(final boolean enabled) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { for (Component c : getComponents()) { c.setEnabled(enabled); } } }); } @Override public Component add(Component comp) { if (comp instanceof JButton) { UIUtils.fixButtonUI((JButton) comp); } if (comp instanceof AbstractButton) { buttonGroup.add((AbstractButton) comp); } return super.add(comp); } }
//Mouse final JToggleButton mouseButton = new JToggleButton(ImageUtilities.loadImageIcon("VisualizationImpl/mouse.png", false)); mouseButton.setToolTipText(NbBundle.getMessage(SelectionToolbar.class, "SelectionToolbar.mouse.tooltip")); mouseButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (mouseButton.isSelected()) { VizController.getInstance().getSelectionManager().setDirectMouseSelection(); } } }); mouseButton.setFocusPainted(false); add(mouseButton); Icon icon = ImageUtilities.loadImageIcon("VisualizationImpl/rectangle.png", false); //Rectangle final JToggleButton rectangleButton = new JToggleButton(icon); rectangleButton .setToolTipText(NbBundle.getMessage(SelectionToolbar.class, "SelectionToolbar.rectangle.tooltip")); rectangleButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (rectangleButton.isSelected()) { VizController.getInstance().getSelectionManager().setRectangleSelection(); } } }); rectangleButton.setFocusPainted(false); add(rectangleButton); //Drag final JToggleButton dragButton = new JToggleButton(ImageUtilities.loadImageIcon("VisualizationImpl/hand.png", false)); dragButton.setToolTipText(NbBundle.getMessage(SelectionToolbar.class, "SelectionToolbar.drag.tooltip")); dragButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (dragButton.isSelected()) { VizController.getInstance().getSelectionManager().setDraggingMouseSelection(); } } }); dragButton.setFocusPainted(false); add(dragButton); addSeparator(); buttonGroup .setSelected(rectangleButton.getModel(), VizController.getInstance().getVizConfig().isRectangleSelection()); buttonGroup .setSelected(mouseButton.getModel(), !VizController.getInstance().getVizConfig().isRectangleSelection()); buttonGroup.setSelected(dragButton.getModel(), VizController.getInstance().getVizConfig().isDraggingEnable()); //Init events VizController.getInstance().getSelectionManager().addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { SelectionManager selectionManager = VizController.getInstance().getSelectionManager(); if (selectionManager.isBlocked()) { buttonGroup.clearSelection(); } else if (!selectionManager.isSelectionEnabled()) { buttonGroup.clearSelection(); } else if (selectionManager.isDirectMouseSelection()) { if (!buttonGroup.isSelected(mouseButton.getModel())) { buttonGroup.setSelected(mouseButton.getModel(), true); } } else if (selectionManager.isRectangleSelection()) { if (!buttonGroup.isSelected(rectangleButton.getModel())) { buttonGroup.setSelected(rectangleButton.getModel(), true); } } else if (selectionManager.isDraggingEnabled()) { if (!buttonGroup.isSelected(dragButton.getModel())) { buttonGroup.setSelected(dragButton.getModel(), true); } } } });
326
878
1,204
<methods>public void <init>() ,public void <init>(int) ,public void <init>(java.lang.String) ,public void <init>(java.lang.String, int) ,public javax.swing.JButton add(javax.swing.Action) ,public void addSeparator() ,public void addSeparator(java.awt.Dimension) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public java.awt.Component getComponentAtIndex(int) ,public int getComponentIndex(java.awt.Component) ,public java.awt.Insets getMargin() ,public int getOrientation() ,public javax.swing.plaf.ToolBarUI getUI() ,public java.lang.String getUIClassID() ,public boolean isBorderPainted() ,public boolean isFloatable() ,public boolean isRollover() ,public void setBorderPainted(boolean) ,public void setFloatable(boolean) ,public void setLayout(java.awt.LayoutManager) ,public void setMargin(java.awt.Insets) ,public void setOrientation(int) ,public void setRollover(boolean) ,public void setUI(javax.swing.plaf.ToolBarUI) ,public void updateUI() <variables>private boolean floatable,private java.awt.Insets margin,private int orientation,private boolean paintBorder,private static final java.lang.String uiClassID
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/component/VizExtendedBar.java
VizExtendedBar
initComponents
class VizExtendedBar extends javax.swing.JPanel { // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JSeparator separator; private javax.swing.JTabbedPane tabbedPane; // End of variables declaration//GEN-END:variables /** * Creates new form VizExtendedBar */ public VizExtendedBar(VizToolbarGroup[] groups) { initComponents(); for (VizToolbarGroup g : groups) { if (g.hasExtended()) { JComponent c = g.getExtendedComponent(); if (c != null) { tabbedPane.addTab(g.getName(), c); } } } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() {<FILL_FUNCTION_BODY>}// </editor-fold>//GEN-END:initComponents }
separator = new javax.swing.JSeparator(); tabbedPane = new javax.swing.JTabbedPane(); setOpaque(true); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(separator, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE) .addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(separator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE)) );
325
328
653
<methods>public void <init>() ,public void <init>(java.awt.LayoutManager) ,public void <init>(boolean) ,public void <init>(java.awt.LayoutManager, boolean) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public javax.swing.plaf.PanelUI getUI() ,public java.lang.String getUIClassID() ,public void setUI(javax.swing.plaf.PanelUI) ,public void updateUI() <variables>private static final java.lang.String uiClassID
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/component/VizToolbar.java
VizToolbar
setEnable
class VizToolbar extends JToolBar { public VizToolbar(VizToolbarGroup[] groups) { initDesign(); for (VizToolbarGroup g : groups) { addSeparator(); for (JComponent c : g.getToolbarComponents()) { add(c); } } } private void initDesign() { setFloatable(false); putClientProperty("JToolBar.isRollover", Boolean.TRUE); //NOI18N setBorder(BorderFactory.createEmptyBorder(2, 0, 4, 0)); setOpaque(true); } public void setEnable(final boolean enabled) {<FILL_FUNCTION_BODY>} @Override public Component add(Component comp) { if (comp instanceof JButton) { UIUtils.fixButtonUI((JButton) comp); } return super.add(comp); } }
SwingUtilities.invokeLater(new Runnable() { @Override public void run() { for (Component c : getComponents()) { c.setEnabled(enabled); } } });
246
62
308
<methods>public void <init>() ,public void <init>(int) ,public void <init>(java.lang.String) ,public void <init>(java.lang.String, int) ,public javax.swing.JButton add(javax.swing.Action) ,public void addSeparator() ,public void addSeparator(java.awt.Dimension) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public java.awt.Component getComponentAtIndex(int) ,public int getComponentIndex(java.awt.Component) ,public java.awt.Insets getMargin() ,public int getOrientation() ,public javax.swing.plaf.ToolBarUI getUI() ,public java.lang.String getUIClassID() ,public boolean isBorderPainted() ,public boolean isFloatable() ,public boolean isRollover() ,public void setBorderPainted(boolean) ,public void setFloatable(boolean) ,public void setLayout(java.awt.LayoutManager) ,public void setMargin(java.awt.Insets) ,public void setOrientation(int) ,public void setRollover(boolean) ,public void setUI(javax.swing.plaf.ToolBarUI) ,public void updateUI() <variables>private boolean floatable,private java.awt.Insets margin,private int orientation,private boolean paintBorder,private static final java.lang.String uiClassID
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/model/edge/EdgeModeler.java
EdgeModeler
initModel
class EdgeModeler extends Modeler { public EdgeModeler(CompatibilityEngine engine) { super(engine); } public EdgeModel initModel(Edge edge, NodeModel sourceModel, NodeModel targetModelImpl) {<FILL_FUNCTION_BODY>} @Override public void beforeDisplay(GL2 gl, GLU glu) { gl.glBegin(GL2.GL_TRIANGLES); } @Override public void afterDisplay(GL2 gl, GLU glu) { gl.glEnd(); } @Override public void chooseModel(Model obj) { throw new UnsupportedOperationException("Not supported."); } @Override public int initDisplayLists(GL2 gl, GLU glu, GLUquadric quadric, int ptr) { return ptr; } public boolean isLod() { return false; } public boolean isSelectable() { return true; } public boolean isClickable() { return false; } public boolean isOnlyAutoSelect() { return true; } }
EdgeModel edgeModel; if (edge.isSelfLoop()) { edgeModel = new SelfLoopModel(edge, sourceModel); } else { edgeModel = new Edge2dModel(edge, sourceModel, targetModelImpl); } return edgeModel;
292
72
364
<methods>public void <init>(org.gephi.visualization.opengl.CompatibilityEngine) ,public abstract void afterDisplay(GL2, GLU) ,public abstract void beforeDisplay(GL2, GLU) ,public abstract void chooseModel(org.gephi.visualization.model.Model) ,public abstract int initDisplayLists(GL2, GLU, GLUquadric, int) ,public boolean isEnabled() ,public void setEnabled(boolean) <variables>protected final non-sealed org.gephi.visualization.apiimpl.VizConfig config,protected final non-sealed org.gephi.visualization.VizController controller,protected final non-sealed org.gephi.visualization.apiimpl.GraphDrawable drawable,protected boolean enabled,protected final non-sealed org.gephi.visualization.opengl.CompatibilityEngine engine
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/model/node/NodeDiskModel.java
NodeDiskModel
display
class NodeDiskModel extends NodeModel { public int modelType; public int modelBorderType; public NodeDiskModel(Node node) { super(node); } @Override public void display(GL2 gl, GLU glu, VizModel vizModel) {<FILL_FUNCTION_BODY>} @Override public boolean selectionTest(Vecf distanceFromMouse, float selectionSize) { return distanceFromMouse.get(2) - selectionSize < node.size(); } @Override public float getCollisionDistance(double angle) { return node.size(); } }
boolean selec = selected; boolean neighbor = false; highlight = false; if (vizModel.isAutoSelectNeighbor() && mark && !selec) { selec = true; highlight = true; neighbor = true; } mark = false; gl.glPushMatrix(); float size = node.size() * 2; gl.glTranslatef(node.x(), node.y(), node.z()); gl.glScalef(size, size, 1f); if (!selec) { if (vizModel.getConfig().isLightenNonSelected()) { float[] lightColor = vizModel.getBackgroundColorComponents(); float lightColorFactor = vizModel.getConfig().getLightenNonSelectedFactor(); float r = node.r(); float g = node.g(); float b = node.b(); gl.glColor3f(r + (lightColor[0] - r) * lightColorFactor, g + (lightColor[1] - g) * lightColorFactor, b + (lightColor[2] - b) * lightColorFactor); gl.glCallList(modelType); if (modelBorderType != 0) { float rborder = 0.498f * r; float gborder = 0.498f * g; float bborder = 0.498f * b; gl.glColor3f(rborder + (lightColor[0] - rborder) * lightColorFactor, gborder + (lightColor[1] - gborder) * lightColorFactor, bborder + (lightColor[2] - bborder) * lightColorFactor); gl.glCallList(modelBorderType); } } else { float r = node.r(); float g = node.g(); float b = node.b(); gl.glColor3f(r, g, b); gl.glCallList(modelType); if (modelBorderType != 0) { float rborder = 0.498f * r; float gborder = 0.498f * g; float bborder = 0.498f * b; gl.glColor3f(rborder, gborder, bborder); gl.glCallList(modelBorderType); } } } else { float r; float g; float b; float rborder; float gborder; float bborder; if (vizModel.isUniColorSelected()) { if (neighbor) { r = vizModel.getConfig().getUniColorSelectedNeigborColor()[0]; g = vizModel.getConfig().getUniColorSelectedNeigborColor()[1]; b = vizModel.getConfig().getUniColorSelectedNeigborColor()[2]; } else { r = vizModel.getConfig().getUniColorSelectedColor()[0]; g = vizModel.getConfig().getUniColorSelectedColor()[1]; b = vizModel.getConfig().getUniColorSelectedColor()[2]; } rborder = 0.498f * r; gborder = 0.498f * g; bborder = 0.498f * b; } else { rborder = node.r(); gborder = node.g(); bborder = node.b(); r = Math.min(1, 0.5f * rborder + 0.5f); g = Math.min(1, 0.5f * gborder + 0.5f); b = Math.min(1, 0.5f * bborder + 0.5f); } gl.glColor3f(r, g, b); gl.glCallList(modelType); if (modelBorderType != 0) { gl.glColor3f(rborder, gborder, bborder); gl.glCallList(modelBorderType); } } gl.glPopMatrix();
162
1,032
1,194
<methods>public void <init>(Node) ,public void addEdge(org.gephi.visualization.model.edge.EdgeModel) ,public float getCameraDistance() ,public abstract float getCollisionDistance(double) ,public float[] getDragDistanceFromMouse() ,public org.gephi.visualization.model.edge.EdgeModel[] getEdges() ,public ElementProperties getElementProperties() ,public Node getNode() ,public org.gephi.visualization.octree.Octant getOctant() ,public int getOctantId() ,public java.lang.String getText() ,public float getTextAlpha() ,public float getTextB() ,public float getTextG() ,public float getTextHeight() ,public float getTextR() ,public float getTextSize() ,public float getTextWidth() ,public float getX() ,public float getY() ,public boolean hasCustomTextColor() ,public boolean isHighlight() ,public boolean isInOctreeLeaf(org.gephi.visualization.octree.Octant) ,public boolean isSelected() ,public boolean isTextVisible() ,public int octreePosition(float, float, float, float) ,public void removeEdge(org.gephi.visualization.model.edge.EdgeModel) ,public abstract boolean selectionTest(org.gephi.lib.gleem.linalg.Vecf, float) ,public void setCameraDistance(float) ,public void setOctant(org.gephi.visualization.octree.Octant) ,public void setOctantId(int) ,public void setSelected(boolean) ,public void setText(java.lang.String) <variables>protected static final long ONEOVERPHI,protected float cameraDistance,protected float[] dragDistance,protected int edgeLength,protected org.gephi.visualization.model.edge.EdgeModel[] edges,protected boolean highlight,public boolean mark,public int markTime,protected final non-sealed Node node,protected org.gephi.visualization.octree.Octant octant,protected int octantId,protected boolean selected
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/model/node/NodeModel.java
NodeModel
octreePosition
class NodeModel implements Model, TextModel { protected static final long ONEOVERPHI = 106039; protected final Node node; public int markTime; public boolean mark; protected float cameraDistance; protected float[] dragDistance; //Octant protected Octant octant; protected int octantId; //Flags protected boolean selected; protected boolean highlight; //Edges protected EdgeModel[] edges; protected int edgeLength; public NodeModel(Node node) { this.node = node; //Default dragDistance = new float[2]; selected = false; mark = false; markTime = 0; //Edges edges = new EdgeModel[0]; } public int octreePosition(float centerX, float centerY, float centerZ, float size) {<FILL_FUNCTION_BODY>} public boolean isInOctreeLeaf(Octant leaf) { // float radius = node.size() / 2f; if (Math.abs(node.x() - leaf.getPosX()) > (leaf.getSize() / 2) || Math.abs(node.y() - leaf.getPosY()) > (leaf.getSize() / 2) || Math.abs(node.z() - leaf.getPosZ()) > (leaf.getSize() / 2)) { return false; } return true; } public abstract boolean selectionTest(Vecf distanceFromMouse, float selectionSize); public abstract float getCollisionDistance(double angle); public Node getNode() { return node; } public float getCameraDistance() { return cameraDistance; } public void setCameraDistance(float cameraDistance) { this.cameraDistance = cameraDistance; } public float getX() { return node.x(); } public float getY() { return node.y(); } @Override public boolean isSelected() { return selected; } @Override public void setSelected(boolean selected) { this.selected = selected; } public boolean isHighlight() { return highlight; } public Octant getOctant() { return octant; } public void setOctant(Octant octant) { this.octant = octant; } public int getOctantId() { return octantId; } public void setOctantId(int octantId) { this.octantId = octantId; } @Override public boolean hasCustomTextColor() { return node.getTextProperties().getAlpha() > 0; } @Override public float getTextWidth() { return node.getTextProperties().getWidth(); } @Override public float getTextHeight() { return node.getTextProperties().getWidth(); } @Override public String getText() { return node.getTextProperties().getText(); } @Override public void setText(String text) { node.getTextProperties().setText(text); } @Override public float getTextSize() { return node.getTextProperties().getSize(); } @Override public float getTextR() { return node.getTextProperties().getR(); } @Override public float getTextG() { return node.getTextProperties().getG(); } @Override public float getTextB() { return node.getTextProperties().getB(); } @Override public float getTextAlpha() { return node.getTextProperties().getAlpha(); } @Override public boolean isTextVisible() { return node.getTextProperties().isVisible(); } @Override public ElementProperties getElementProperties() { return node; } public float[] getDragDistanceFromMouse() { return dragDistance; } public void addEdge(EdgeModel model) { int id = edgeLength++; growEdges(id); edges[id] = model; if (model.getSourceModel() == this) { model.setOctantSourceId(id); } else { model.setOctantTargetId(id); } } public void removeEdge(EdgeModel model) { int id; if (model.getSourceModel() == this) { id = model.getOctantSourceId(); } else { id = model.getOctantTargetId(); } edges[id] = null; } public EdgeModel[] getEdges() { return edges; } private void growEdges(final int index) { if (index >= edges.length) { final int newLength = (int) Math.min(Math.max((ONEOVERPHI * edges.length) >>> 16, index + 1), Integer.MAX_VALUE); final EdgeModel t[] = new EdgeModel[newLength]; System.arraycopy(edges, 0, t, 0, edges.length); edges = t; } } }
//float radius = obj.getRadius(); int index = 0; if (node.y() < centerY) { index += 4; } if (node.z() > centerZ) { index += 2; } if (node.x() < centerX) { index += 1; } return index;
1,339
95
1,434
<no_super_class>
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/model/node/NodeModeler.java
NodeModeler
chooseModel
class NodeModeler extends Modeler { public int SHAPE_DIAMOND; public int SHAPE_DISK16; public int SHAPE_DISK32; public int SHAPE_DISK64; public int BORDER16; public int BORDER32; public int BORDER64; public NodeModeler(CompatibilityEngine engine) { super(engine); } public NodeModel initModel(Node n) { NodeDiskModel obj = new NodeDiskModel((Node) n); obj.modelType = SHAPE_DISK64; obj.modelBorderType = BORDER64; chooseModel(obj); return obj; } @Override public void chooseModel(Model object3d) {<FILL_FUNCTION_BODY>} @Override public int initDisplayLists(GL2 gl, GLU glu, GLUquadric quadric, int ptr) { // Diamond display list SHAPE_DIAMOND = ptr + 1; gl.glNewList(SHAPE_DIAMOND, GL2.GL_COMPILE); glu.gluDisk(quadric, 0, 0.5, 4, 1); gl.glEndList(); //End //Disk16 SHAPE_DISK16 = SHAPE_DIAMOND + 1; gl.glNewList(SHAPE_DISK16, GL2.GL_COMPILE); glu.gluDisk(quadric, 0, 0.5, 6, 1); gl.glEndList(); //Fin //Disk32 SHAPE_DISK32 = SHAPE_DISK16 + 1; gl.glNewList(SHAPE_DISK32, GL2.GL_COMPILE); glu.gluDisk(quadric, 0, 0.5, 12, 2); gl.glEndList(); //Disk64 SHAPE_DISK64 = SHAPE_DISK32 + 1; gl.glNewList(SHAPE_DISK64, GL2.GL_COMPILE); glu.gluDisk(quadric, 0, 0.5, 32, 4); gl.glEndList(); //Border16 BORDER16 = SHAPE_DISK64 + 1; gl.glNewList(BORDER16, GL2.GL_COMPILE); glu.gluDisk(quadric, 0.42, 0.50, 24, 2); gl.glEndList(); //Border32 BORDER32 = BORDER16 + 1; gl.glNewList(BORDER32, GL2.GL_COMPILE); glu.gluDisk(quadric, 0.42, 0.50, 48, 2); gl.glEndList(); //Border32 BORDER64 = BORDER32 + 1; gl.glNewList(BORDER64, GL2.GL_COMPILE); glu.gluDisk(quadric, 0.42, 0.50, 96, 4); gl.glEndList(); return BORDER64; } @Override public void beforeDisplay(GL2 gl, GLU glu) { } @Override public void afterDisplay(GL2 gl, GLU glu) { } protected float cameraDistance(NodeModel object) { float[] cameraLocation = drawable.getCameraLocation(); double distance = Math.sqrt(Math.pow((double) object.getNode().x() - cameraLocation[0], 2d) + Math.pow((double) object.getNode().y() - cameraLocation[1], 2d) + Math.pow((double) object.getNode().z() - cameraLocation[2], 2d)); object.setCameraDistance((float) distance); return (float) distance; } public boolean isLod() { return true; } public boolean isSelectable() { return true; } public boolean isClickable() { return true; } public boolean isOnlyAutoSelect() { return false; } }
NodeDiskModel obj = (NodeDiskModel) object3d; if (config.isDisableLOD()) { obj.modelType = SHAPE_DISK64; obj.modelBorderType = BORDER64; return; } float distance = cameraDistance(obj) / (obj.getNode().size() * drawable.getGlobalScale()); if (distance > 600) { obj.modelType = SHAPE_DIAMOND; obj.modelBorderType = -1; } else if (distance > 50) { obj.modelType = SHAPE_DISK16; obj.modelBorderType = BORDER16; } else { obj.modelType = SHAPE_DISK32; obj.modelBorderType = BORDER32; }
1,134
212
1,346
<methods>public void <init>(org.gephi.visualization.opengl.CompatibilityEngine) ,public abstract void afterDisplay(GL2, GLU) ,public abstract void beforeDisplay(GL2, GLU) ,public abstract void chooseModel(org.gephi.visualization.model.Model) ,public abstract int initDisplayLists(GL2, GLU, GLUquadric, int) ,public boolean isEnabled() ,public void setEnabled(boolean) <variables>protected final non-sealed org.gephi.visualization.apiimpl.VizConfig config,protected final non-sealed org.gephi.visualization.VizController controller,protected final non-sealed org.gephi.visualization.apiimpl.GraphDrawable drawable,protected boolean enabled,protected final non-sealed org.gephi.visualization.opengl.CompatibilityEngine engine
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/octree/Octant.java
Octant
displayOctant
class Octant { //Static protected static final long ONEOVERPHI = 106039; protected static final float TRIM_THRESHOLD = 1000; protected static final float TRIM_RATIO = 0.3f; //LeafId protected int leafId = Octree.NULL_ID; //Coordinates protected float size; protected float posX; protected float posY; protected float posZ; protected int depth; //Children protected Octant[] children; //Stats protected int nodeCount = 0; //Data protected NodeModel[] nodes; protected int[] nodesGarbage; protected int nodesGarbageLength; protected int nodesLength; //Flags protected boolean visible; public Octant(int depth, float posX, float posY, float posZ, float size) { this.size = size; this.posX = posX; this.posY = posY; this.posZ = posZ; this.depth = depth; } protected void addNode(NodeModel nodeModel) { int id; if (nodesGarbageLength > 0) { id = removeGarbage(); } else { id = nodesLength++; growNodes(id); } nodes[id] = nodeModel; nodeCount++; nodeModel.setOctantId(id); } protected void removeNode(NodeModel nodeModel) { int id = nodeModel.getOctantId(); nodeModel.setOctantId(Octree.NULL_ID); nodes[id] = null; nodeCount--; addGarbage(id); trimNodes(); } protected void clear() { nodes = null; nodesGarbage = null; nodesLength = 0; nodesGarbage = null; nodesGarbageLength = 0; nodeCount = 0; } protected boolean isEmpty() { return nodeCount == 0; } public float getPosX() { return posX; } public float getPosY() { return posY; } public float getPosZ() { return posZ; } public float getSize() { return size; } protected void displayOctant(GL2 gl) {<FILL_FUNCTION_BODY>} protected void displayOctantInfo(GL2 gl, GLU glu) { GLUT glut = new GLUT(); float quantum = size / 2; float height = 15; gl.glPushMatrix(); gl.glTranslatef(posX - quantum, posY + quantum - height, posZ + quantum); gl.glScalef(0.1f, 0.1f, 0.1f); gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); glut.glutStrokeString(GLUT.STROKE_MONO_ROMAN, "ID: " + leafId); gl.glPopMatrix(); height += 15; gl.glPushMatrix(); gl.glTranslatef(posX - quantum, posY + quantum - height, posZ + quantum); gl.glScalef(0.1f, 0.1f, 0.1f); gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); glut.glutStrokeString(GLUT.STROKE_MONO_ROMAN, "objectsCount: " + nodeCount); gl.glPopMatrix(); } private void addGarbage(int index) { if (nodesGarbage == null) { nodesGarbage = new int[10]; } else if (nodesGarbageLength == nodesGarbage.length) { final int newLength = (int) Math .min(Math.max((ONEOVERPHI * nodesGarbage.length) >>> 16, nodesGarbageLength + 1), Integer.MAX_VALUE); final int t[] = new int[newLength]; System.arraycopy(nodesGarbage, 0, t, 0, nodesGarbage.length); nodesGarbage = t; } nodesGarbage[nodesGarbageLength++] = index; } private int removeGarbage() { return nodesGarbage[--nodesGarbageLength]; } private void growNodes(final int index) { if (nodes == null) { nodes = new NodeModel[10]; } else if (index >= nodes.length) { final int newLength = (int) Math.min(Math.max((ONEOVERPHI * nodes.length) >>> 16, index + 1), Integer.MAX_VALUE); final NodeModel t[] = new NodeModel[newLength]; System.arraycopy(nodes, 0, t, 0, nodes.length); nodes = t; } } private void trimNodes() { if (nodesLength >= TRIM_THRESHOLD && ((float) nodeCount) / nodesLength < TRIM_RATIO) { NodeModel t[] = new NodeModel[nodeCount]; if (nodeCount > 0) { int c = 0; for (int i = 0; i < nodes.length; i++) { NodeModel n = nodes[i]; if (n != null) { n.setOctantId(c); t[c++] = n; } } } nodesLength = t.length; nodes = t; nodesGarbage = null; nodesGarbageLength = 0; } } }
float quantum = size / 2; gl.glBegin(GL2.GL_QUAD_STRIP); gl.glVertex3f(posX + quantum, posY + quantum, posZ + quantum); gl.glVertex3f(posX + quantum, posY - quantum, posZ + quantum); gl.glVertex3f(posX + quantum, posY + quantum, posZ - quantum); gl.glVertex3f(posX + quantum, posY - quantum, posZ - quantum); gl.glVertex3f(posX - quantum, posY + quantum, posZ - quantum); gl.glVertex3f(posX - quantum, posY - quantum, posZ - quantum); gl.glVertex3f(posX - quantum, posY + quantum, posZ + quantum); gl.glVertex3f(posX - quantum, posY - quantum, posZ + quantum); gl.glVertex3f(posX + quantum, posY + quantum, posZ + quantum); gl.glVertex3f(posX + quantum, posY - quantum, posZ + quantum); gl.glEnd(); gl.glBegin(GL2.GL_QUADS); gl.glVertex3f(posX - quantum, posY + quantum, posZ - quantum); gl.glVertex3f(posX - quantum, posY + quantum, posZ + quantum); gl.glVertex3f(posX + quantum, posY + quantum, posZ + quantum); gl.glVertex3f(posX + quantum, posY + quantum, posZ - quantum); gl.glVertex3f(posX - quantum, posY - quantum, posZ + quantum); gl.glVertex3f(posX - quantum, posY - quantum, posZ - quantum); gl.glVertex3f(posX + quantum, posY - quantum, posZ - quantum); gl.glVertex3f(posX + quantum, posY - quantum, posZ + quantum); gl.glEnd();
1,488
495
1,983
<no_super_class>
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/octree/Octree.java
OctantIterator
hasNext
class OctantIterator implements Iterator<NodeModel> { private final boolean ignoreVisibility; private int leafId; private Octant octant; private int leavesLength; private NodeModel[] nodes; private int nodesId; private int nodesLength; private NodeModel pointer; public OctantIterator(boolean ignoreVisibility) { leavesLength = leaves.length; this.ignoreVisibility = ignoreVisibility; } @Override public boolean hasNext() {<FILL_FUNCTION_BODY>} @Override public NodeModel next() { return pointer; } public void reset() { leafId = 0; octant = null; leavesLength = leaves.length; nodes = null; nodesId = 0; nodesLength = 0; pointer = null; } @Override public void remove() { throw new UnsupportedOperationException("Not supported."); } }
pointer = null; while (pointer == null) { while (nodesId < nodesLength && pointer == null) { pointer = nodes[nodesId++]; } if (pointer == null) { octant = null; while (leafId < leavesLength && (octant == null || (!octant.visible && !ignoreVisibility))) { octant = leaves[leafId++]; } if (octant == null || (!octant.visible && !ignoreVisibility)) { return false; } nodes = octant.nodes; nodesId = 0; nodesLength = octant.nodesLength; } } return pointer != null;
248
174
422
<no_super_class>
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/opengl/AbstractEngine.java
EngineLifeCycle
setInited
class EngineLifeCycle { private boolean started; private boolean inited; private boolean requestAnimation; public void requestPauseAnimating() { if (inited) { stopAnimating(); } } public void requestResumeAnimating() { if (!started) { return; } if (inited) { startAnimating(); } else { requestAnimation = true; } } public void requestStartAnimating() { started = true; requestResumeAnimating(); } public void requestStopAnimating() { requestPauseAnimating(); started = false; } public void initEngine() { } public boolean isInited() { return inited; } public void setInited() {<FILL_FUNCTION_BODY>} }
if (!inited) { inited = true; if (requestAnimation) { //graphDrawable.display(); startAnimating(); requestAnimation = false; } } else { dataBridge.reset(); textManager.initArchitecture(); }
239
77
316
<no_super_class>
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/opengl/GraphicalConfiguration.java
GraphicalConfiguration
checkGeneralCompatibility
class GraphicalConfiguration { private static boolean messageDelivered = false; private final GLProfile profile = GLProfile.get(GLProfile.GL2); private final GLCapabilities caps = new GLCapabilities(profile); private final AbstractGraphicsDevice device = GLDrawableFactory.getFactory(profile).getDefaultDevice(); private boolean vboSupport = false; private boolean pBufferSupport = false; private String vendor = ""; private String renderer = ""; private String versionStr = ""; public void checkGeneralCompatibility(GL2 gl) {<FILL_FUNCTION_BODY>} public String getVendor() { return vendor; } public String getRenderer() { return renderer; } public String getVersionStr() { return versionStr; } public boolean isPBufferSupported() { return pBufferSupport; } public boolean isVboSupported() { return vboSupport; } public boolean isIntelVendor() { return vendor.toLowerCase().contains("intel"); } }
if (messageDelivered) { return; } try { //Vendor vendor = gl.glGetString(GL2.GL_VENDOR); renderer = gl.glGetString(GL2.GL_RENDERER); versionStr = gl.glGetString(GL2.GL_VERSION); String currentConfig = String .format(NbBundle.getMessage(GraphicalConfiguration.class, "graphicalConfiguration_currentConfig"), vendor, renderer, versionStr); // Check version. if (!gl.isExtensionAvailable("GL_VERSION_1_2")) { String err = String .format(NbBundle.getMessage(GraphicalConfiguration.class, "graphicalConfiguration_exception"), versionStr, currentConfig); throw new GraphicalConfigurationException(err); } //VBO boolean vboExtension = gl.isExtensionAvailable("GL_ARB_vertex_buffer_object"); boolean vboFunctions = gl.isFunctionAvailable("glGenBuffersARB") && gl.isFunctionAvailable("glBindBufferARB") && gl.isFunctionAvailable("glBufferDataARB") && gl.isFunctionAvailable("glDeleteBuffersARB"); vboSupport = vboExtension && vboFunctions; //Pbuffer pBufferSupport = GLDrawableFactory.getDesktopFactory().canCreateGLPbuffer(device, profile); } catch (final GraphicalConfigurationException e) { messageDelivered = true; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane .showMessageDialog(WindowManager.getDefault().getMainWindow(), e.getMessage(), "Configuration", JOptionPane.WARNING_MESSAGE); Exceptions.printStackTrace(e); } }); }
275
461
736
<no_super_class>
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/options/DefaultOptionsPanelController.java
DefaultOptionsPanelController
getPanel
class DefaultOptionsPanelController extends OptionsPanelController { private final PropertyChangeSupport pcs = new PropertyChangeSupport(this); private DefaultPanel panel; private boolean changed; @Override public void update() { getPanel().load(); changed = false; } @Override public void applyChanges() { getPanel().store(); changed = false; } @Override public void cancel() { // need not do anything special, if no changes have been persisted yet } @Override public boolean isValid() { return getPanel().valid(); } @Override public boolean isChanged() { return changed; } @Override public HelpCtx getHelpCtx() { return null; // new HelpCtx("...ID") if you have a help set } @Override public JComponent getComponent(Lookup masterLookup) { return getPanel(); } @Override public void addPropertyChangeListener(PropertyChangeListener l) { pcs.addPropertyChangeListener(l); } @Override public void removePropertyChangeListener(PropertyChangeListener l) { pcs.removePropertyChangeListener(l); } private DefaultPanel getPanel() {<FILL_FUNCTION_BODY>} void changed() { if (!changed) { changed = true; pcs.firePropertyChange(OptionsPanelController.PROP_CHANGED, false, true); } pcs.firePropertyChange(OptionsPanelController.PROP_VALID, null, null); } }
if (panel == null) { panel = new DefaultPanel(this); } return panel;
410
30
440
<no_super_class>
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/scheduler/AbstractAnimator.java
AbstractAnimator
run
class AbstractAnimator extends Thread { //Runnable protected final Runnable runnable; //Lock protected final Semaphore semaphore; //Flag protected boolean animating = true; public AbstractAnimator(Runnable runnable, Semaphore semaphore, String name) { super(name); this.semaphore = semaphore; this.runnable = runnable; setDaemon(true); } @Override public void run() {<FILL_FUNCTION_BODY>} public final void shutdown() { animating = false; synchronized (this) { notify(); } } public final boolean isAnimating() { return animating; } }
while (animating) { synchronized (this) { try { wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } runnable.run(); semaphore.release(); }
204
72
276
<methods>public void <init>() ,public void <init>(java.lang.Runnable) ,public void <init>(java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable) ,public void <init>(java.lang.ThreadGroup, java.lang.String) ,public void <init>(java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long, boolean) ,public static int activeCount() ,public final void checkAccess() ,public int countStackFrames() ,public static native java.lang.Thread currentThread() ,public static void dumpStack() ,public static int enumerate(java.lang.Thread[]) ,public static Map<java.lang.Thread,java.lang.StackTraceElement[]> getAllStackTraces() ,public java.lang.ClassLoader getContextClassLoader() ,public static java.lang.Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() ,public long getId() ,public final java.lang.String getName() ,public final int getPriority() ,public java.lang.StackTraceElement[] getStackTrace() ,public java.lang.Thread.State getState() ,public final java.lang.ThreadGroup getThreadGroup() ,public java.lang.Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() ,public static native boolean holdsLock(java.lang.Object) ,public void interrupt() ,public static boolean interrupted() ,public final boolean isAlive() ,public final boolean isDaemon() ,public boolean isInterrupted() ,public final void join() throws java.lang.InterruptedException,public final synchronized void join(long) throws java.lang.InterruptedException,public final synchronized void join(long, int) throws java.lang.InterruptedException,public static void onSpinWait() ,public final void resume() ,public void run() ,public void setContextClassLoader(java.lang.ClassLoader) ,public final void setDaemon(boolean) ,public static void setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public final synchronized void setName(java.lang.String) ,public final void setPriority(int) ,public void setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public static native void sleep(long) throws java.lang.InterruptedException,public static void sleep(long, int) throws java.lang.InterruptedException,public synchronized void start() ,public final void stop() ,public final void suspend() ,public java.lang.String toString() ,public static native void yield() <variables>private static final java.lang.StackTraceElement[] EMPTY_STACK_TRACE,public static final int MAX_PRIORITY,public static final int MIN_PRIORITY,public static final int NORM_PRIORITY,private volatile sun.nio.ch.Interruptible blocker,private final java.lang.Object blockerLock,private java.lang.ClassLoader contextClassLoader,private boolean daemon,private static volatile java.lang.Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler,private volatile long eetop,private java.lang.ThreadGroup group,java.lang.ThreadLocal.ThreadLocalMap inheritableThreadLocals,private java.security.AccessControlContext inheritedAccessControlContext,private volatile boolean interrupted,private volatile java.lang.String name,volatile java.lang.Object parkBlocker,private int priority,private final long stackSize,private boolean stillborn,private java.lang.Runnable target,private static int threadInitNumber,int threadLocalRandomProbe,int threadLocalRandomSecondarySeed,long threadLocalRandomSeed,java.lang.ThreadLocal.ThreadLocalMap threadLocals,private static long threadSeqNumber,private volatile int threadStatus,private final long tid,private volatile java.lang.Thread.UncaughtExceptionHandler uncaughtExceptionHandler
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/scheduler/BasicFPSAnimator.java
BasicFPSAnimator
run
class BasicFPSAnimator extends Thread { //Runnable protected final Runnable runnable; //Lock protected final Object worldLock; protected final Object lock = new Object(); //Fps protected long startTime; protected long delay; //Flag protected boolean animating = true; public BasicFPSAnimator(Runnable runnable, Object worldLock, String name, float fps) { super(name); this.worldLock = worldLock; this.runnable = runnable; setDaemon(true); setFps(fps); } @Override public void run() {<FILL_FUNCTION_BODY>} public final void setFps(float fps) { delay = (long) (1000.0f / fps); synchronized (this.lock) { startTime = 0; this.lock.notify(); } } public final void shutdown() { animating = false; } public final boolean isAnimating() { return animating; } }
while (animating) { startTime = System.currentTimeMillis(); //Execute synchronized (worldLock) { runnable.run(); } //End long timeout; while ((timeout = delay - System.currentTimeMillis() + startTime) > 0) { //Wait only if the time spent in display is inferior than delay //Otherwise the render loop acts as a 'as fast as you can' loop synchronized (this.lock) { try { this.lock.wait(timeout); } catch (InterruptedException ex) { } } } }
291
160
451
<methods>public void <init>() ,public void <init>(java.lang.Runnable) ,public void <init>(java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable) ,public void <init>(java.lang.ThreadGroup, java.lang.String) ,public void <init>(java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long, boolean) ,public static int activeCount() ,public final void checkAccess() ,public int countStackFrames() ,public static native java.lang.Thread currentThread() ,public static void dumpStack() ,public static int enumerate(java.lang.Thread[]) ,public static Map<java.lang.Thread,java.lang.StackTraceElement[]> getAllStackTraces() ,public java.lang.ClassLoader getContextClassLoader() ,public static java.lang.Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() ,public long getId() ,public final java.lang.String getName() ,public final int getPriority() ,public java.lang.StackTraceElement[] getStackTrace() ,public java.lang.Thread.State getState() ,public final java.lang.ThreadGroup getThreadGroup() ,public java.lang.Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() ,public static native boolean holdsLock(java.lang.Object) ,public void interrupt() ,public static boolean interrupted() ,public final boolean isAlive() ,public final boolean isDaemon() ,public boolean isInterrupted() ,public final void join() throws java.lang.InterruptedException,public final synchronized void join(long) throws java.lang.InterruptedException,public final synchronized void join(long, int) throws java.lang.InterruptedException,public static void onSpinWait() ,public final void resume() ,public void run() ,public void setContextClassLoader(java.lang.ClassLoader) ,public final void setDaemon(boolean) ,public static void setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public final synchronized void setName(java.lang.String) ,public final void setPriority(int) ,public void setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public static native void sleep(long) throws java.lang.InterruptedException,public static void sleep(long, int) throws java.lang.InterruptedException,public synchronized void start() ,public final void stop() ,public final void suspend() ,public java.lang.String toString() ,public static native void yield() <variables>private static final java.lang.StackTraceElement[] EMPTY_STACK_TRACE,public static final int MAX_PRIORITY,public static final int MIN_PRIORITY,public static final int NORM_PRIORITY,private volatile sun.nio.ch.Interruptible blocker,private final java.lang.Object blockerLock,private java.lang.ClassLoader contextClassLoader,private boolean daemon,private static volatile java.lang.Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler,private volatile long eetop,private java.lang.ThreadGroup group,java.lang.ThreadLocal.ThreadLocalMap inheritableThreadLocals,private java.security.AccessControlContext inheritedAccessControlContext,private volatile boolean interrupted,private volatile java.lang.String name,volatile java.lang.Object parkBlocker,private int priority,private final long stackSize,private boolean stillborn,private java.lang.Runnable target,private static int threadInitNumber,int threadLocalRandomProbe,int threadLocalRandomSecondarySeed,long threadLocalRandomSeed,java.lang.ThreadLocal.ThreadLocalMap threadLocals,private static long threadSeqNumber,private volatile int threadStatus,private final long tid,private volatile java.lang.Thread.UncaughtExceptionHandler uncaughtExceptionHandler
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/scheduler/CompatibilityScheduler.java
CompatibilityScheduler
initArchitecture
class CompatibilityScheduler implements Scheduler, VizArchitecture { private final float updateFpsLimit = 5f; private final Object worldLock = new Object(); //States AtomicBoolean animating = new AtomicBoolean(); AtomicBoolean cameraMoved = new AtomicBoolean(); AtomicBoolean mouseMoved = new AtomicBoolean(); AtomicBoolean startDrag = new AtomicBoolean(); AtomicBoolean drag = new AtomicBoolean(); AtomicBoolean stopDrag = new AtomicBoolean(); AtomicBoolean mouseClick = new AtomicBoolean(); //Architeture private GraphDrawable graphDrawable; private CompatibilityEngine engine; private VizConfig vizConfig; //Animators private BasicFPSAnimator displayAnimator; private BasicFPSAnimator updateAnimator; private float displayFpsLimit = 30f; @Override public void initArchitecture() {<FILL_FUNCTION_BODY>} @Override public synchronized void start() { if (displayAnimator != null) { displayAnimator.shutdown(); } if (updateAnimator != null) { updateAnimator.shutdown(); } displayAnimator = new BasicFPSAnimator(new Runnable() { @Override public void run() { graphDrawable.display(); } }, worldLock, "DisplayAnimator", displayFpsLimit); displayAnimator.start(); updateAnimator = new BasicFPSAnimator(new Runnable() { @Override public void run() { updateWorld(); } }, worldLock, "UpdateAnimator", updateFpsLimit); updateAnimator.start(); } @Override public synchronized void stop() { updateAnimator.shutdown(); displayAnimator.shutdown(); cameraMoved.set(false); mouseMoved.set(false); startDrag.set(false); drag.set(false); stopDrag.set(false); mouseClick.set(false); } @Override public boolean isAnimating() { return displayAnimator != null && displayAnimator.isAnimating(); } @Override public void display(GL2 gl, GLU glu) { //Boolean vals boolean execMouseClick = mouseClick.getAndSet(false); boolean execMouseMove = mouseMoved.getAndSet(false); boolean execDrag = drag.get() || startDrag.get() || stopDrag.get(); if (cameraMoved.getAndSet(false)) { graphDrawable.setCameraPosition(gl, glu); engine.getOctree().updateVisibleOctant(gl); //Objects iterators in octree are ready //Task MODEL - LOD engine.updateLOD(); } //Task SELECTED if (execMouseMove) { engine.mouseMove(); engine.updateSelection(gl, glu); } else if (execDrag) { //Drag if (stopDrag.getAndSet(false)) { engine.stopDrag(); } if (startDrag.getAndSet(false)) { engine.startDrag(); } if (drag.getAndSet(false)) { engine.mouseDrag(); } } //Task AFTERSELECTION if (execMouseClick) { engine.mouseClick(); } //Display engine.beforeDisplay(gl, glu); engine.display(gl, glu); engine.afterDisplay(gl, glu); } @Override public void updateWorld() { if (engine.updateWorld()) { cameraMoved.set(true); mouseMoved.set(true); } } @Override public void updatePosition() { // if (objectsMoved.getAndSet(false)) { // engine.updateObjectsPosition(); // cameraMoved.set(true); // } } @Override public void requireUpdateVisible() { cameraMoved.set(true); } @Override public void requireUpdateSelection() { mouseMoved.set(true); } @Override public void requireStartDrag() { startDrag.set(true); } @Override public void requireDrag() { drag.set(true); } @Override public void requireStopDrag() { stopDrag.set(true); } @Override public void requireMouseClick() { mouseClick.set(true); } @Override public float getFps() { return displayFpsLimit; } @Override public void setFps(float maxFps) { this.displayFpsLimit = maxFps; if (displayAnimator != null) { displayAnimator.setFps(maxFps); } } }
this.graphDrawable = VizController.getInstance().getDrawable(); this.engine = (CompatibilityEngine) VizController.getInstance().getEngine(); this.vizConfig = VizController.getInstance().getVizConfig();
1,298
60
1,358
<no_super_class>
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/screenshot/OffscreenCanvas.java
OffscreenCanvas
display
class OffscreenCanvas extends GLAbstractListener implements TileRendererBase.TileRendererListener { private final boolean transparentBackground; public OffscreenCanvas(int width, int height, boolean transparentBackground, int antialiasing) { super(); final GLProfile glp = GLProfile.get(GLProfile.GL2); final GLCapabilities caps = getCaps(); caps.setOnscreen(false); caps.setDoubleBuffered(false); if (antialiasing == 0) { caps.setSampleBuffers(false); } else { caps.setSampleBuffers(true); caps.setNumSamples(antialiasing); } final GLDrawableFactory factory = GLDrawableFactory.getFactory(glp); drawable = factory.createOffscreenAutoDrawable(null, caps, null, width, height); drawable.addGLEventListener(this); cameraLocation = vizController.getDrawable().getCameraLocation(); cameraTarget = vizController.getDrawable().getCameraTarget(); engine = VizController.getInstance().getEngine(); globalScale = VizController.getInstance().getDrawable().getGlobalScale(); this.transparentBackground = transparentBackground; } @Override protected GLAutoDrawable initDrawable() { return drawable; } @Override public void init(GLAutoDrawable drawable) { GL2 gl = drawable.getGL().getGL2(); initConfig(gl); engine.initDisplayLists(gl, GLU); TextManager textManager = VizController.getInstance().getTextManager(); textManager.reinitRenderers(); } @Override public void initConfig(GL2 gl) { super.initConfig(gl); gl.glClear(GL2.GL_COLOR_BUFFER_BIT); float[] backgroundColor = vizController.getVizModel().getBackgroundColorComponents(); gl.glClearColor(backgroundColor[0], backgroundColor[1], backgroundColor[2], transparentBackground ? 0f : 1f); } @Override public void display(GLAutoDrawable drawable) {<FILL_FUNCTION_BODY>} @Override protected void init(GL2 gl) { } @Override protected void render3DScene(GL2 gl, com.jogamp.opengl.glu.GLU glu) { } @Override protected void reshape3DScene(GL2 gl) { } @Override public void addTileRendererNotify(TileRendererBase trb) { } @Override public void removeTileRendererNotify(TileRendererBase trb) { } @Override public void reshapeTile(TileRendererBase tr, int tileX, int tileY, int tileWidth, int tileHeight, int imageWidth, int imageHeight) { GL2 gl = tr.getAttachedDrawable().getGL().getGL2(); double aspectRatio = (double) imageWidth / (double) imageHeight; // Compute overall frustum float left, right, bottom, top; top = (float) (nearDistance * Math.tan(viewField * 3.14159265 / 360.0)); bottom = -top; left = (float) (bottom * aspectRatio); right = (float) (top * aspectRatio); float w = right - left; float h = top - bottom; // Compute tiled frustum float l = left + tileX * w / imageWidth; float r = l + tileWidth * w / imageWidth; float b = bottom + tileY * h / imageHeight; float t = b + tileHeight * h / imageHeight; gl.glMatrixMode(GL2.GL_PROJECTION); gl.glLoadIdentity(); gl.glFrustum(l, r, b, t, nearDistance, farDistance); gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glLoadIdentity(); setCameraPosition(gl, GLU); } @Override public void startTileRendering(TileRendererBase trb) { } @Override public void endTileRendering(TileRendererBase trb) { } @Override public void reinitWindow() { } }
GL2 gl = drawable.getGL().getGL2(); gl.glClear(GL2.GL_COLOR_BUFFER_BIT); float[] backgroundColor = vizController.getVizModel().getBackgroundColorComponents(); gl.glClearColor(backgroundColor[0], backgroundColor[1], backgroundColor[2], transparentBackground ? 0f : 1f); engine.display(gl, GLU);
1,140
107
1,247
<methods>public void <init>() ,public void destroy() ,public void display(GLAutoDrawable) ,public void display() ,public void dispose(GLAutoDrawable) ,public float[] getCameraLocation() ,public float[] getCameraTarget() ,public org.gephi.lib.gleem.linalg.Vec3f getCameraVector() ,public double getDraggingMarkerX() ,public double getDraggingMarkerY() ,public GL2 getGL() ,public GLAutoDrawable getGLAutoDrawable() ,public float getGlobalScale() ,public synchronized java.awt.Component getGraphComponent() ,public org.gephi.visualization.opengl.GraphicalConfiguration getGraphicalConfiguration() ,public java.awt.Point getLocationOnScreen() ,public java.nio.FloatBuffer getModelMatrix() ,public java.nio.FloatBuffer getProjectionMatrix() ,public java.nio.IntBuffer getViewport() ,public int getViewportHeight() ,public int getViewportWidth() ,public void init(GLAutoDrawable) ,public void initArchitecture() ,public void initConfig(GL2) ,public void initMouseEvents() ,public boolean isDestroyed() ,public double[] myGluProject(float, float) ,public float[] myGluProject(float, float, float) ,public void refreshDraggingMarker() ,public void renderTestCube(GL2) ,public void reshape(GLAutoDrawable, int, int, int, int) ,public void setCameraLocation(float[]) ,public void setCameraPosition(GL2, GLU) ,public void setCameraTarget(float[]) ,public void setVizController(org.gephi.visualization.VizController) <variables>protected static final GLU GLU,private double aspectRatio,protected float[] cameraLocation,protected float[] cameraTarget,protected org.gephi.lib.gleem.linalg.Vec3f cameraVector,private boolean destroyed,protected double[] draggingMarker,protected GLAutoDrawable drawable,protected org.gephi.visualization.opengl.AbstractEngine engine,public final float farDistance,protected float fps,protected float fpsAvg,protected float fpsCount,protected float globalScale,protected java.awt.Component graphComponent,protected org.gephi.visualization.apiimpl.GraphIO graphIO,protected org.gephi.visualization.swing.GLAbstractListener.GraphMouseAdapter graphMouseAdapter,protected java.awt.event.MouseAdapter graphMouseAdapterCanvas,protected MouseAdapter graphMouseAdapterNewt,protected org.gephi.visualization.opengl.GraphicalConfiguration graphicalConfiguration,protected java.nio.FloatBuffer modelMatrix,public final float nearDistance,protected java.nio.FloatBuffer projMatrix,private volatile boolean resizing,private static float rotateFactor,protected org.gephi.visualization.apiimpl.Scheduler scheduler,private boolean showGLLog,private long startTime,public final float viewField,protected java.nio.IntBuffer viewport,protected org.gephi.visualization.VizController vizController,protected org.gephi.visualization.VizModel vizModel,protected GLWindow window
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/selection/Cylinder.java
Cylinder
drawArea
class Cylinder implements SelectionArea { //Variables private static final float[] RECT_POINT = {1, 1}; //Architecture private final GraphIO graphIO; private final GraphDrawable drawable; private final SelectionManager selectionManager; private final VizModel vizModel; private final float[] rectangle = new float[2]; public Cylinder() { graphIO = VizController.getInstance().getGraphIO(); drawable = VizController.getInstance().getDrawable(); selectionManager = VizController.getInstance().getSelectionManager(); vizModel = VizController.getInstance().getVizModel(); } @Override public float[] getSelectionAreaRectancle() { float diameter = selectionManager.getMouseSelectionDiameter(); if (diameter == 1) { //Point return RECT_POINT; } else { float size; if (selectionManager.isMouseSelectionZoomProportionnal()) { size = diameter * (float) Math.abs(drawable.getDraggingMarkerX()); } else { size = diameter; } rectangle[0] = size; rectangle[1] = size; return rectangle; } } @Override public float[] getSelectionAreaCenter() { return null; } @Override public boolean mouseTest(Vecf distanceFromMouse, NodeModel nodeModel) { float diameter = selectionManager.getMouseSelectionDiameter(); if (diameter == 1) { //Point return nodeModel.selectionTest(distanceFromMouse, 0); } else if (selectionManager.isMouseSelectionZoomProportionnal()) { return nodeModel.selectionTest(distanceFromMouse, diameter); } else { return nodeModel.selectionTest(distanceFromMouse, (float) (diameter / -drawable.getDraggingMarkerX())); } } @Override public void drawArea(GL2 gl, GLU glu) {<FILL_FUNCTION_BODY>} @Override public boolean isEnabled() { return selectionManager.isSelectionEnabled(); } @Override public boolean blockSelection() { return false; } }
float diameter = selectionManager.getMouseSelectionDiameter(); if (diameter == 1) { //Point } else { //Cylinder float radius; if (selectionManager.isMouseSelectionZoomProportionnal()) { radius = (float) (diameter * Math.abs(drawable.getDraggingMarkerX())); //Proportionnal } else { radius = diameter; //Constant } float[] mousePosition = graphIO.getMousePosition(); float vectorX, vectorY, vectorX1 = mousePosition[0], vectorY1 = mousePosition[1]; double angle; gl.glColor4f(0f, 0f, 0f, 0.2f); gl.glBegin(GL2.GL_TRIANGLES); for (int i = 0; i <= 360; i++) { angle = i / 57.29577957795135f; vectorX = mousePosition[0] + (radius * (float) Math.sin(angle)); vectorY = mousePosition[1] + (radius * (float) Math.cos(angle)); gl.glVertex2f(mousePosition[0], mousePosition[1]); gl.glVertex2f(vectorX1, vectorY1); gl.glVertex2f(vectorX, vectorY); vectorY1 = vectorY; vectorX1 = vectorX; } gl.glEnd(); }
568
375
943
<no_super_class>
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/selection/Rectangle.java
Rectangle
start
class Rectangle implements SelectionArea { private static final float[] POINT_RECT = {1, 1}; private final GraphDrawable drawable; private final VizConfig config; private final float[] color; private final float[] rectangle = new float[2]; private final float[] rectangle3d = new float[2]; private final float[] center = new float[2]; private final float[] rectangleSize = new float[2]; //Variables private float[] startPosition; private float[] startPosition3d; private boolean stop = true; private boolean blocking = true; private boolean ctrl = false; public Rectangle() { drawable = VizController.getInstance().getDrawable(); config = VizController.getInstance().getVizConfig(); color = config.getRectangleSelectionColor().getRGBComponents(null); } @Override public float[] getSelectionAreaRectancle() { if (stop) { return POINT_RECT; } rectangleSize[0] = Math.abs(rectangle[0] - startPosition[0]); rectangleSize[1] = Math.abs(rectangle[1] - startPosition[1]); if (rectangleSize[0] < 1f) { rectangleSize[0] = 1f; } if (rectangleSize[1] < 1f) { rectangleSize[1] = 1f; } return rectangleSize; } @Override public float[] getSelectionAreaCenter() { if (stop) { return null; } center[0] = -(rectangle[0] - startPosition[0]) / 2f; center[1] = -(rectangle[1] - startPosition[1]) / 2f; return center; } @Override public boolean mouseTest(Vecf distanceFromMouse, NodeModel nodeModel) { if (stop) { return nodeModel.selectionTest(distanceFromMouse, 0); } float x = nodeModel.getX(); float y = nodeModel.getY(); float rad = nodeModel.getNode().size(); boolean res = true; if (startPosition3d[0] > rectangle3d[0]) { if (x - rad > startPosition3d[0] || x + rad < rectangle3d[0]) { res = false; } } else if (x + rad < startPosition3d[0] || x - rad > rectangle3d[0]) { res = false; } if (startPosition3d[1] < rectangle3d[1]) { if (y + rad < startPosition3d[1] || y - rad > rectangle3d[1]) { res = false; } } else if (y - rad > startPosition3d[1] || y + rad < rectangle3d[1]) { res = false; } return res; } public void start(float[] mousePosition, float[] mousePosition3d) {<FILL_FUNCTION_BODY>} public void stop() { stop = true; blocking = true; } public void setMousePosition(float[] mousePosition, float[] mousePosition3d) { if (!stop) { rectangle[0] = mousePosition[0]; rectangle[1] = mousePosition[1]; rectangle3d[0] = mousePosition3d[0]; rectangle3d[1] = mousePosition3d[1]; } } @Override public boolean isEnabled() { return true; } @Override public boolean blockSelection() { return blocking; } public void setBlocking(boolean blocking) { this.blocking = blocking; } @Override public void drawArea(GL2 gl, GLU glu) { if (!stop) { float x = startPosition[0]; float y = startPosition[1]; float w = rectangle[0] - startPosition[0]; float h = rectangle[1] - startPosition[1]; gl.glMatrixMode(GL2.GL_PROJECTION); gl.glPushMatrix(); gl.glLoadIdentity(); glu.gluOrtho2D(0, drawable.getViewportWidth(), 0, drawable.getViewportHeight()); gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glPushMatrix(); gl.glLoadIdentity(); gl.glColor4f(color[0], color[1], color[2], color[3]); gl.glBegin(GL2.GL_QUADS); gl.glVertex3f(x + w, y, 0); gl.glVertex3f(x, y, 0); gl.glVertex3f(x, y + h, 0); gl.glVertex3f(x + w, y + h, 0); gl.glEnd(); gl.glColor4f(color[0], color[1], color[2], 1f); gl.glBegin(GL2.GL_LINE_LOOP); gl.glVertex3f(x + w, y, 0); gl.glVertex3f(x, y, 0); gl.glVertex3f(x, y + h, 0); gl.glVertex3f(x + w, y + h, 0); gl.glEnd(); gl.glPopMatrix(); gl.glMatrixMode(GL2.GL_PROJECTION); gl.glPopMatrix(); gl.glMatrixMode(GL2.GL_MODELVIEW); } else { startPosition = null; } } public boolean isStop() { return stop; } public boolean isCtrl() { return ctrl; } public void setCtrl(boolean ctrl) { this.ctrl = ctrl; } }
this.startPosition = Arrays.copyOf(mousePosition, 2); this.startPosition3d = Arrays.copyOf(mousePosition3d, 2); this.rectangle[0] = startPosition[0]; this.rectangle[1] = startPosition[1]; this.rectangle3d[0] = startPosition3d[0]; this.rectangle3d[1] = startPosition3d[1]; stop = false; blocking = false;
1,523
125
1,648
<no_super_class>
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/swing/GraphCanvas.java
GraphCanvas
render3DScene
class GraphCanvas extends GLAbstractListener { private final GLUT glut = new GLUT(); @Override protected GLAutoDrawable initDrawable() { GLCanvas glCanvas = new GLCanvas(getCaps()); // glCanvas.setMinimumSize(new Dimension(0, 0)); //Fix Canvas resize Issue graphComponent = glCanvas; return glCanvas; } @Override protected void init(GL2 gl) { globalScale = ((GLCanvas)drawable).getCurrentSurfaceScale(new float[2])[0]; engine.startDisplay(); } @Override protected void render3DScene(GL2 gl, GLU glu) {<FILL_FUNCTION_BODY>} @Override protected void reshape3DScene(GL2 gl) { } @Override public void reinitWindow() { if (UIUtils.isAquaLookAndFeel()) { // Only used when collapse panel is set visible // Workaround for JOGL bug 1274 Container c = graphComponent.getParent(); if (c != null) { c.remove(graphComponent); c.add(graphComponent, BorderLayout.CENTER); } } } }
if (vizController.getVizConfig().isShowFPS()) { gl.glPushMatrix(); gl.glLoadIdentity(); gl.glMatrixMode(GL2.GL_PROJECTION); gl.glPushMatrix(); gl.glLoadIdentity(); gl.glGetIntegerv(GL2.GL_VIEWPORT, viewport); glu.gluOrtho2D(0, viewport.get(2), viewport.get(3), 0); gl.glDepthFunc(GL2.GL_ALWAYS); gl.glColor3i(192, 192, 192); gl.glRasterPos2f(10, 15); String fpsRound = String.valueOf((int) fps); glut.glutBitmapString(GLUT.BITMAP_HELVETICA_10, fpsRound); gl.glDepthFunc(GL2.GL_LESS); gl.glPopMatrix(); gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glPopMatrix(); }
342
291
633
<methods>public void <init>() ,public void destroy() ,public void display(GLAutoDrawable) ,public void display() ,public void dispose(GLAutoDrawable) ,public float[] getCameraLocation() ,public float[] getCameraTarget() ,public org.gephi.lib.gleem.linalg.Vec3f getCameraVector() ,public double getDraggingMarkerX() ,public double getDraggingMarkerY() ,public GL2 getGL() ,public GLAutoDrawable getGLAutoDrawable() ,public float getGlobalScale() ,public synchronized java.awt.Component getGraphComponent() ,public org.gephi.visualization.opengl.GraphicalConfiguration getGraphicalConfiguration() ,public java.awt.Point getLocationOnScreen() ,public java.nio.FloatBuffer getModelMatrix() ,public java.nio.FloatBuffer getProjectionMatrix() ,public java.nio.IntBuffer getViewport() ,public int getViewportHeight() ,public int getViewportWidth() ,public void init(GLAutoDrawable) ,public void initArchitecture() ,public void initConfig(GL2) ,public void initMouseEvents() ,public boolean isDestroyed() ,public double[] myGluProject(float, float) ,public float[] myGluProject(float, float, float) ,public void refreshDraggingMarker() ,public void renderTestCube(GL2) ,public void reshape(GLAutoDrawable, int, int, int, int) ,public void setCameraLocation(float[]) ,public void setCameraPosition(GL2, GLU) ,public void setCameraTarget(float[]) ,public void setVizController(org.gephi.visualization.VizController) <variables>protected static final GLU GLU,private double aspectRatio,protected float[] cameraLocation,protected float[] cameraTarget,protected org.gephi.lib.gleem.linalg.Vec3f cameraVector,private boolean destroyed,protected double[] draggingMarker,protected GLAutoDrawable drawable,protected org.gephi.visualization.opengl.AbstractEngine engine,public final float farDistance,protected float fps,protected float fpsAvg,protected float fpsCount,protected float globalScale,protected java.awt.Component graphComponent,protected org.gephi.visualization.apiimpl.GraphIO graphIO,protected org.gephi.visualization.swing.GLAbstractListener.GraphMouseAdapter graphMouseAdapter,protected java.awt.event.MouseAdapter graphMouseAdapterCanvas,protected MouseAdapter graphMouseAdapterNewt,protected org.gephi.visualization.opengl.GraphicalConfiguration graphicalConfiguration,protected java.nio.FloatBuffer modelMatrix,public final float nearDistance,protected java.nio.FloatBuffer projMatrix,private volatile boolean resizing,private static float rotateFactor,protected org.gephi.visualization.apiimpl.Scheduler scheduler,private boolean showGLLog,private long startTime,public final float viewField,protected java.nio.IntBuffer viewport,protected org.gephi.visualization.VizController vizController,protected org.gephi.visualization.VizModel vizModel,protected GLWindow window
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/swing/NewtGraphCanvas.java
NewtGraphCanvas
render3DScene
class NewtGraphCanvas extends GLAbstractListener { private final GLUT glut = new GLUT(); private NewtCanvasAWT glCanvas; @Override protected GLAutoDrawable initDrawable() { GLWindow glWindow = GLWindow.create(getCaps()); // glWindow.setSurfaceScale(new float[]{ScalableSurface.AUTOMAX_PIXELSCALE, ScalableSurface.AUTOMAX_PIXELSCALE}); if (!Utilities.isMac()) { glCanvas = new HighDPIFixCanvas(glWindow); } else { glCanvas = new NewtCanvasAWT(glWindow); } // glCanvas.setFocusable(true); // glCanvas.setIgnoreRepaint(true); // glCanvas.setMinimumSize(new Dimension(0, 0)); //Fix Canvas resize Issue // glCanvas.setMinimumSize(new Dimension(0, 0)); //Fix Canvas resize Issue //Basic init graphComponent = (Component) glCanvas; window = glWindow; // graphComponent.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); return glWindow; } @Override protected void init(GL2 gl) { // globalScale = glWindow.getCurrentSurfaceScale(new float[2])[0]; globalScale = (float) glCanvas.getGraphicsConfiguration().getDefaultTransform().getScaleX(); engine.startDisplay(); } @Override public void reinitWindow() { if (UIUtils.isAquaLookAndFeel()) { // Only used when collapse panel is set visible // Workaround for JOGL bug 1274 // glCanvas.setNEWTChild(null); // glCanvas.setNEWTChild(glWindow); } else { // Fix issue when closing the collapse panel Container c = graphComponent.getParent(); if (c != null) { c.remove(graphComponent); c.add(graphComponent, BorderLayout.CENTER); } } } @Override protected void render3DScene(GL2 gl, GLU glu) {<FILL_FUNCTION_BODY>} @Override protected void reshape3DScene(GL2 gl) { } @Override public void destroy() { super.destroy(); glCanvas.getNEWTChild().destroy(); glCanvas = null; } public class HighDPIFixCanvas extends NewtCanvasAWT { public HighDPIFixCanvas(GLWindow glWindow) { super(glWindow); } @Override public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); return new Dimension(d.width, d.height); } @Override public int getWidth() { return (int) (super.getWidth() * getGlobalScale()); } @Override public int getHeight() { return (int) (super.getHeight() * getGlobalScale()); } } }
if (vizController.getVizConfig().isShowFPS()) { gl.glPushMatrix(); gl.glLoadIdentity(); gl.glMatrixMode(GL2.GL_PROJECTION); gl.glPushMatrix(); gl.glLoadIdentity(); gl.glGetIntegerv(GL2.GL_VIEWPORT, viewport); glu.gluOrtho2D(0, viewport.get(2), viewport.get(3), 0); gl.glDepthFunc(GL2.GL_ALWAYS); gl.glColor3i(192, 192, 192); gl.glRasterPos2f(10, 15 + (getGlobalScale() > 1f ? 8 : 0)); String fpsRound = String.valueOf((int) fps); if (getGlobalScale() > 1f) { glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, fpsRound); } else { glut.glutBitmapString(GLUT.BITMAP_HELVETICA_10, fpsRound); } gl.glDepthFunc(GL2.GL_LESS); gl.glPopMatrix(); gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glPopMatrix(); }
824
359
1,183
<methods>public void <init>() ,public void destroy() ,public void display(GLAutoDrawable) ,public void display() ,public void dispose(GLAutoDrawable) ,public float[] getCameraLocation() ,public float[] getCameraTarget() ,public org.gephi.lib.gleem.linalg.Vec3f getCameraVector() ,public double getDraggingMarkerX() ,public double getDraggingMarkerY() ,public GL2 getGL() ,public GLAutoDrawable getGLAutoDrawable() ,public float getGlobalScale() ,public synchronized java.awt.Component getGraphComponent() ,public org.gephi.visualization.opengl.GraphicalConfiguration getGraphicalConfiguration() ,public java.awt.Point getLocationOnScreen() ,public java.nio.FloatBuffer getModelMatrix() ,public java.nio.FloatBuffer getProjectionMatrix() ,public java.nio.IntBuffer getViewport() ,public int getViewportHeight() ,public int getViewportWidth() ,public void init(GLAutoDrawable) ,public void initArchitecture() ,public void initConfig(GL2) ,public void initMouseEvents() ,public boolean isDestroyed() ,public double[] myGluProject(float, float) ,public float[] myGluProject(float, float, float) ,public void refreshDraggingMarker() ,public void renderTestCube(GL2) ,public void reshape(GLAutoDrawable, int, int, int, int) ,public void setCameraLocation(float[]) ,public void setCameraPosition(GL2, GLU) ,public void setCameraTarget(float[]) ,public void setVizController(org.gephi.visualization.VizController) <variables>protected static final GLU GLU,private double aspectRatio,protected float[] cameraLocation,protected float[] cameraTarget,protected org.gephi.lib.gleem.linalg.Vec3f cameraVector,private boolean destroyed,protected double[] draggingMarker,protected GLAutoDrawable drawable,protected org.gephi.visualization.opengl.AbstractEngine engine,public final float farDistance,protected float fps,protected float fpsAvg,protected float fpsCount,protected float globalScale,protected java.awt.Component graphComponent,protected org.gephi.visualization.apiimpl.GraphIO graphIO,protected org.gephi.visualization.swing.GLAbstractListener.GraphMouseAdapter graphMouseAdapter,protected java.awt.event.MouseAdapter graphMouseAdapterCanvas,protected MouseAdapter graphMouseAdapterNewt,protected org.gephi.visualization.opengl.GraphicalConfiguration graphicalConfiguration,protected java.nio.FloatBuffer modelMatrix,public final float nearDistance,protected java.nio.FloatBuffer projMatrix,private volatile boolean resizing,private static float rotateFactor,protected org.gephi.visualization.apiimpl.Scheduler scheduler,private boolean showGLLog,private long startTime,public final float viewField,protected java.nio.IntBuffer viewport,protected org.gephi.visualization.VizController vizController,protected org.gephi.visualization.VizModel vizModel,protected GLWindow window
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/text/ObjectColorMode.java
ObjectColorMode
textColor
class ObjectColorMode implements ColorMode { private final VizConfig vizConfig; public ObjectColorMode() { this.vizConfig = VizController.getInstance().getVizConfig(); } @Override public void defaultEdgeColor(Renderer renderer) { } @Override public void defaultNodeColor(Renderer renderer) { } @Override public void textNodeColor(Renderer renderer, NodeModel nodeModel) { textColor(renderer, nodeModel, nodeModel.isSelected() || nodeModel.isHighlight()); } @Override public void textEdgeColor(Renderer renderer, EdgeModel edgeModel) { float[] cl = edgeModel.getColor(); renderer.setColor(cl[0], cl[1], cl[2], cl[3]); } protected void textColor(Renderer renderer, TextModel text, boolean selected) {<FILL_FUNCTION_BODY>} @Override public String getName() { return NbBundle.getMessage(ObjectColorMode.class, "ObjectColorMode.name"); } @Override public ImageIcon getIcon() { return ImageUtilities.loadImageIcon("VisualizationImpl/ObjectColorMode.png", false); } @Override public String toString() { return getName(); } }
if (vizConfig.isLightenNonSelected()) { if (!selected) { float lightColorFactor = 1 - vizConfig.getLightenNonSelectedFactor(); renderer.setColor(text.getElementProperties().r(), text.getElementProperties().g(), text.getElementProperties().b(), lightColorFactor); } else { renderer.setColor(text.getElementProperties().r(), text.getElementProperties().g(), text.getElementProperties().b(), 1); } } else { renderer.setColor(text.getElementProperties().r(), text.getElementProperties().g(), text.getElementProperties().b(), text.getElementProperties().alpha()); }
341
171
512
<no_super_class>
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/text/TextColorMode.java
TextColorMode
textColor
class TextColorMode implements ColorMode { private final VizConfig vizConfig; private float[] color; public TextColorMode() { this.vizConfig = VizController.getInstance().getVizConfig(); } @Override public void defaultNodeColor(Renderer renderer) { color = VizController.getInstance().getVizModel().getTextModel().nodeColor; } @Override public void defaultEdgeColor(Renderer renderer) { color = VizController.getInstance().getVizModel().getTextModel().edgeColor; } @Override public void textNodeColor(Renderer renderer, NodeModel nodeModel) { textColor(renderer, nodeModel, nodeModel.isSelected() || nodeModel.isHighlight()); } @Override public void textEdgeColor(Renderer renderer, EdgeModel edgeModel) { textColor(renderer, edgeModel, edgeModel.isSelected() || edgeModel.isAutoSelected()); } public void textColor(Renderer renderer, TextModel text, boolean selected) {<FILL_FUNCTION_BODY>} @Override public String getName() { return NbBundle.getMessage(TextColorMode.class, "TextColorMode.name"); } @Override public ImageIcon getIcon() { return ImageUtilities.loadImageIcon("VisualizationImpl/TextColorMode.png", false); } @Override public String toString() { return getName(); } }
if (text.hasCustomTextColor()) { if (vizConfig.isLightenNonSelected()) { if (!selected) { float lightColorFactor = 1 - vizConfig.getLightenNonSelectedFactor(); renderer.setColor(text.getTextR(), text.getTextG(), text.getTextB(), lightColorFactor); } else { renderer.setColor(text.getTextR(), text.getTextG(), text.getTextB(), 1); } } else { renderer.setColor(text.getTextR(), text.getTextG(), text.getTextB(), text.getTextAlpha()); } } else if (vizConfig.isLightenNonSelected()) { if (!selected) { float lightColorFactor = 1 - vizConfig.getLightenNonSelectedFactor(); renderer.setColor(color[0], color[1], color[2], lightColorFactor); } else { renderer.setColor(color[0], color[1], color[2], 1); } } else { renderer.setColor(color[0], color[1], color[2], 1); }
379
291
670
<no_super_class>
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/text/TextManager.java
Renderer3D
drawTextEdge
class Renderer3D implements Renderer { private TextRenderer renderer; @Override public void initRenderer(Font font) { renderer = new TextRenderer(font, antialised, fractionalMetrics, null, shouldUseMipmapGeneration()); } @Override public void reinitRenderer() { renderer = new TextRenderer(renderer.getFont(), antialised, fractionalMetrics, null, shouldUseMipmapGeneration()); } private boolean shouldUseMipmapGeneration() { boolean doMipmap = mipmap; if (drawable.getGraphicalConfiguration() != null && drawable.getGraphicalConfiguration().isIntelVendor()) { //Disable mipmap generation in intel GPUs. See https://github.com/gephi/gephi/issues/1494 (Some label characters fade away when zooming out) doMipmap = false; } return doMipmap; } @Override public void disposeRenderer() { renderer.flush(); renderer.dispose(); } @Override public Font getFont() { return renderer.getFont(); } @Override public void setFont(Font font) { initRenderer(font); } @Override public void beginRendering() { renderer.begin3DRendering(); float cameraLocation = drawable.getCameraLocation()[2]; if (cachedCameraLocationZ != cameraLocation && model.sizeMode == sizeModes[0]) { //Force refresh if camera location changed in fixed mode nodeRefresh = true; edgeRefresh = true; } cachedCameraLocationZ = cameraLocation; } @Override public void endRendering() { renderer.end3DRendering(); nodeRefresh = false; edgeRefresh = false; } @Override public void drawTextNode(NodeModel objectModel) { Node node = objectModel.getNode(); TextProperties textData = (TextProperties) node.getTextProperties(); if (textData != null) { String txt = textData.getText(); float width, height, posX, posY; if (txt == null || txt.isEmpty()) { return; } float sizeFactor = drawable.getGlobalScale() * textData.getSize() * model.sizeMode.getSizeFactor3d(model.nodeSizeFactor, objectModel); if (nodeRefresh || (objectModel.getTextWidth() == 0f && objectModel.getTextHeight() == 0f)) { Rectangle2D r = renderer.getBounds(txt); width = (float) (sizeFactor * r.getWidth()); height = (float) (sizeFactor * r.getHeight()); posX = node.x() + (float) width / -2f; posY = node.y() + (float) height / -2f; textData.setDimensions(width, height); } else { width = textData.getWidth(); height = textData.getHeight(); posX = node.x() + (float) width / -2f; posY = node.y() + (float) height / -2f; } model.colorMode.textNodeColor(this, objectModel); renderer.draw3D(txt, posX, posY, (float) node.z(), sizeFactor); } } @Override public void drawTextEdge(EdgeModel objectModel) {<FILL_FUNCTION_BODY>} @Override public void setColor(float r, float g, float b, float a) { renderer.setColor(r, g, b, a); } @Override public TextRenderer getJOGLRenderer() { return renderer; } }
Edge edge = objectModel.getEdge(); TextProperties textData = (TextProperties) edge.getTextProperties(); if (textData != null) { String txt = textData.getText(); float width, height, posX, posY; if (txt == null || txt.isEmpty()) { return; } float sizeFactor = drawable.getGlobalScale() * textData.getSize() * model.edgeSizeFactor; if (edgeRefresh || (objectModel.getTextWidth() == 0f && objectModel.getTextHeight() == 0f)) { Rectangle2D r = renderer.getBounds(txt); width = (float) (sizeFactor * r.getWidth()); height = (float) (sizeFactor * r.getHeight()); textData.setDimensions(width, height); } else { width = textData.getWidth(); height = textData.getHeight(); } model.colorMode.textEdgeColor(this, objectModel); float x, y; if (edge.isDirected()) { x = (objectModel.getSourceModel().getNode().x() + 2 * objectModel.getTargetModel().getNode().x()) / 3f; y = (objectModel.getSourceModel().getNode().y() + 2 * objectModel.getTargetModel().getNode().y()) / 3f; } else { x = (objectModel.getSourceModel().getNode().x() + objectModel.getTargetModel().getNode().x()) / 2f; y = (objectModel.getSourceModel().getNode().y() + objectModel.getTargetModel().getNode().y()) / 2f; } posX = x + (float) width / -2; posY = y + (float) height / -2; float posZ = 0; renderer.draw3D(txt, posX, posY, posZ, sizeFactor); }
989
495
1,484
<no_super_class>
gephi_gephi
gephi/modules/VisualizationImpl/src/main/java/org/gephi/visualization/text/UniqueColorMode.java
UniqueColorMode
textColor
class UniqueColorMode implements ColorMode { private final VizConfig vizConfig; private float[] color; public UniqueColorMode() { this.vizConfig = VizController.getInstance().getVizConfig(); } @Override public void defaultNodeColor(Renderer renderer) { color = VizController.getInstance().getVizModel().getTextModel().nodeColor; renderer.setColor(color[0], color[1], color[2], color[3]); } @Override public void defaultEdgeColor(Renderer renderer) { color = VizController.getInstance().getVizModel().getTextModel().edgeColor; renderer.setColor(color[0], color[1], color[2], color[3]); } @Override public void textNodeColor(Renderer renderer, NodeModel nodeModel) { textColor(renderer, nodeModel, nodeModel.isSelected() || nodeModel.isHighlight()); } @Override public void textEdgeColor(Renderer renderer, EdgeModel edgeModel) { textColor(renderer, edgeModel, edgeModel.isSelected() || edgeModel.isAutoSelected()); } public void textColor(Renderer renderer, TextModel text, boolean selected) {<FILL_FUNCTION_BODY>} @Override public String getName() { return NbBundle.getMessage(UniqueColorMode.class, "UniqueColorMode.name"); } @Override public ImageIcon getIcon() { return ImageUtilities.loadImageIcon("VisualizationImpl/UniqueColorMode.png", false); } @Override public String toString() { return getName(); } }
if (vizConfig.isLightenNonSelected()) { if (!selected) { float lightColorFactor = 1 - vizConfig.getLightenNonSelectedFactor(); renderer.setColor(color[0], color[1], color[2], lightColorFactor); } else { renderer.setColor(color[0], color[1], color[2], 1); } } else { renderer.setColor(color[0], color[1], color[2], 1); }
432
134
566
<no_super_class>
gephi_gephi
gephi/modules/WelcomeScreen/src/main/java/org/gephi/desktop/welcome/Installer.java
Installer
restored
class Installer extends ModuleInstall { @Override public void restored() {<FILL_FUNCTION_BODY>} }
if (NbPreferences.forModule(WelcomeTopComponent.class) .getBoolean(WelcomeTopComponent.STARTUP_PREF, Boolean.TRUE)) { WindowManager.getDefault().invokeWhenUIReady(new Runnable() { @Override public void run() { WelcomeTopComponent component = WelcomeTopComponent.getInstance(); JDialog dialog = new JDialog(WindowManager.getDefault().getMainWindow(), component.getName(), false); dialog.getContentPane().add(component); dialog.setBounds(212, 237, 679, 378); dialog.setVisible(true); } }); }
34
170
204
<no_super_class>
gephi_gephi
gephi/modules/WelcomeScreen/src/main/java/org/gephi/desktop/welcome/WelcomeAction.java
WelcomeAction
run
class WelcomeAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() {<FILL_FUNCTION_BODY>} }); } }
WelcomeTopComponent component = WelcomeTopComponent.getInstance(); JDialog dialog = new JDialog(WindowManager.getDefault().getMainWindow(), component.getName(), false); dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); dialog.getContentPane().add(component); dialog.setBounds(212, 237, 679, 378); dialog.setVisible(true);
74
113
187
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/Doc.java
Level
computeBroken
class Level extends Doc { private final Indent plusIndent; // The extra indent following breaks. private final List<Doc> docs = new ArrayList<>(); // The elements of the level. private Level(Indent plusIndent) { this.plusIndent = plusIndent; } /** * Factory method for {@code Level}s. * * @param plusIndent the extra indent inside the {@code Level} * @return the new {@code Level} */ static Level make(Indent plusIndent) { return new Level(plusIndent); } /** * Add a {@link Doc} to the {@code Level}. * * @param doc the {@link Doc} to add */ void add(Doc doc) { docs.add(doc); } @Override int computeWidth() { return getWidth(docs); } @Override String computeFlat() { StringBuilder builder = new StringBuilder(); for (Doc doc : docs) { builder.append(doc.getFlat()); } return builder.toString(); } @Override Range<Integer> computeRange() { Range<Integer> docRange = EMPTY_RANGE; for (Doc doc : docs) { docRange = union(docRange, doc.range()); } return docRange; } // State that needs to be preserved between calculating breaks and // writing output. // TODO(cushon): represent phases as separate immutable data. /** True if the entire {@link Level} fits on one line. */ boolean oneLine = false; /** * Groups of {@link Doc}s that are children of the current {@link Level}, separated by {@link * Break}s. */ List<List<Doc>> splits = new ArrayList<>(); /** {@link Break}s between {@link Doc}s in the current {@link Level}. */ List<Break> breaks = new ArrayList<>(); @Override public State computeBreaks(CommentsHelper commentsHelper, int maxWidth, State state) { int thisWidth = getWidth(); if (state.column + thisWidth <= maxWidth) { oneLine = true; return state.withColumn(state.column + thisWidth); } State broken = computeBroken( commentsHelper, maxWidth, new State(state.indent + plusIndent.eval(), state.column)); return state.withColumn(broken.column); } private static void splitByBreaks(List<Doc> docs, List<List<Doc>> splits, List<Break> breaks) { splits.clear(); breaks.clear(); splits.add(new ArrayList<>()); for (Doc doc : docs) { if (doc instanceof Break) { breaks.add((Break) doc); splits.add(new ArrayList<>()); } else { getLast(splits).add(doc); } } } /** Compute breaks for a {@link Level} that spans multiple lines. */ private State computeBroken(CommentsHelper commentsHelper, int maxWidth, State state) {<FILL_FUNCTION_BODY>} /** Lay out a Break-separated group of Docs in the current Level. */ private static State computeBreakAndSplit( CommentsHelper commentsHelper, int maxWidth, State state, Optional<Break> optBreakDoc, List<Doc> split) { int breakWidth = optBreakDoc.isPresent() ? optBreakDoc.get().getWidth() : 0; int splitWidth = getWidth(split); boolean shouldBreak = (optBreakDoc.isPresent() && optBreakDoc.get().fillMode == FillMode.UNIFIED) || state.mustBreak || state.column + breakWidth + splitWidth > maxWidth; if (optBreakDoc.isPresent()) { state = optBreakDoc.get().computeBreaks(state, state.lastIndent, shouldBreak); } boolean enoughRoom = state.column + splitWidth <= maxWidth; state = computeSplit(commentsHelper, maxWidth, split, state.withMustBreak(false)); if (!enoughRoom) { state = state.withMustBreak(true); // Break after, too. } return state; } private static State computeSplit( CommentsHelper commentsHelper, int maxWidth, List<Doc> docs, State state) { for (Doc doc : docs) { state = doc.computeBreaks(commentsHelper, maxWidth, state); } return state; } @Override public void write(Output output) { if (oneLine) { output.append(getFlat(), range()); // This is defined because width is finite. } else { writeFilled(output); } } private void writeFilled(Output output) { // Handle first split. for (Doc doc : splits.get(0)) { doc.write(output); } // Handle following breaks and split. for (int i = 0; i < breaks.size(); i++) { breaks.get(i).write(output); for (Doc doc : splits.get(i + 1)) { doc.write(output); } } } /** * Get the width of a sequence of {@link Doc}s. * * @param docs the {@link Doc}s * @return the width */ static int getWidth(List<Doc> docs) { int width = 0; for (Doc doc : docs) { width += doc.getWidth(); if (width >= MAX_LINE_WIDTH) { return MAX_LINE_WIDTH; // Paranoid overflow protection } } return width; } private static Range<Integer> union(Range<Integer> x, Range<Integer> y) { return x.isEmpty() ? y : y.isEmpty() ? x : x.span(y).canonical(INTEGERS); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("plusIndent", plusIndent) .add("docs", docs) .toString(); } }
splitByBreaks(docs, splits, breaks); state = computeBreakAndSplit( commentsHelper, maxWidth, state, /* optBreakDoc= */ Optional.empty(), splits.get(0)); // Handle following breaks and split. for (int i = 0; i < breaks.size(); i++) { state = computeBreakAndSplit( commentsHelper, maxWidth, state, Optional.of(breaks.get(i)), splits.get(i + 1)); } return state;
1,603
134
1,737
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/DocBuilder.java
DocBuilder
withOps
class DocBuilder { private final Doc.Level base = Doc.Level.make(Indent.Const.ZERO); private final ArrayDeque<Doc.Level> stack = new ArrayDeque<>(); /** * A possibly earlier {@link Doc.Level} for appending text, à la Philip Wadler. * * <p>Processing {@link Doc}s presents a subtle problem. Suppose we have a {@link Doc} for to an * assignment node, {@code a = b}, with an optional {@link Doc.Break} following the {@code =}. * Suppose we have 5 characters to write it, so that we think we don't need the break. * Unfortunately, this {@link Doc} lies in an expression statement {@link Doc} for the statement * {@code a = b;} and this statement does not fit in 3 characters. This is why many formatters * sometimes emit lines that are too long, or cheat by using a narrower line length to avoid such * problems. * * <p>One solution to this problem is not to decide whether a {@link Doc.Level} should be broken * until later (in this case, after the semicolon has been seen). A simpler approach is to rewrite * the {@link Doc} as here, so that the semicolon moves inside the inner {@link Doc}, and we can * decide whether to break that {@link Doc} without seeing later text. */ private Doc.Level appendLevel = base; /** Start to build a {@code DocBuilder}. */ public DocBuilder() { stack.addLast(base); } /** * Add a list of {@link Op}s to the {@link OpsBuilder}. * * @param ops the {@link Op}s * @return the {@link OpsBuilder} */ public DocBuilder withOps(List<Op> ops) {<FILL_FUNCTION_BODY>} /** * Open a new {@link Doc.Level}. * * @param plusIndent the extra indent for the {@link Doc.Level} */ void open(Indent plusIndent) { Doc.Level level = Doc.Level.make(plusIndent); stack.addLast(level); } /** Close the current {@link Doc.Level}. */ void close() { Doc.Level top = stack.removeLast(); stack.peekLast().add(top); } /** * Add a {@link Doc} to the current {@link Doc.Level}. * * @param doc the {@link Doc} */ void add(Doc doc) { appendLevel.add(doc); } /** * Add a {@link Doc.Break} to the current {@link Doc.Level}. * * @param breakDoc the {@link Doc.Break} */ void breakDoc(Doc.Break breakDoc) { appendLevel = stack.peekLast(); appendLevel.add(breakDoc); } /** * Return the {@link Doc}. * * @return the {@link Doc} */ public Doc build() { return base; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("base", base) .add("stack", stack) .add("appendLevel", appendLevel) .toString(); } }
for (Op op : ops) { op.add(this); // These operations call the operations below to build the doc. } return this;
848
42
890
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/FormatterDiagnostic.java
FormatterDiagnostic
toString
class FormatterDiagnostic { private final int lineNumber; private final String message; private final int column; public static FormatterDiagnostic create(String message) { return new FormatterDiagnostic(-1, -1, message); } public static FormatterDiagnostic create(int lineNumber, int column, String message) { checkArgument(lineNumber >= 0); checkArgument(column >= 0); checkNotNull(message); return new FormatterDiagnostic(lineNumber, column, message); } private FormatterDiagnostic(int lineNumber, int column, String message) { this.lineNumber = lineNumber; this.column = column; this.message = message; } /** * Returns the line number on which the error occurred, or {@code -1} if the error does not have a * line number. */ public int line() { return lineNumber; } /** * Returns the 0-indexed column number on which the error occurred, or {@code -1} if the error * does not have a column. */ public int column() { return column; } /** Returns a description of the problem that prevented formatting from succeeding. */ public String message() { return message; } public String toString() {<FILL_FUNCTION_BODY>} }
StringBuilder sb = new StringBuilder(); if (lineNumber >= 0) { sb.append(lineNumber).append(':'); } if (column >= 0) { // internal column numbers are 0-based, but diagnostics use 1-based indexing by convention sb.append(column + 1).append(':'); } if (lineNumber >= 0 || column >= 0) { sb.append(' '); } sb.append("error: ").append(message); return sb.toString();
349
135
484
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/Indent.java
If
toString
class If extends Indent { private final BreakTag condition; private final Indent thenIndent; private final Indent elseIndent; private If(BreakTag condition, Indent thenIndent, Indent elseIndent) { this.condition = condition; this.thenIndent = thenIndent; this.elseIndent = elseIndent; } public static If make(BreakTag condition, Indent thenIndent, Indent elseIndent) { return new If(condition, thenIndent, elseIndent); } @Override int eval() { return (condition.wasBreakTaken() ? thenIndent : elseIndent).eval(); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return MoreObjects.toStringHelper(this) .add("condition", condition) .add("thenIndent", thenIndent) .add("elseIndent", elseIndent) .toString();
202
54
256
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/InputOutput.java
InputOutput
computeRanges
class InputOutput { private ImmutableList<String> lines = ImmutableList.of(); protected static final Range<Integer> EMPTY_RANGE = Range.closedOpen(-1, -1); private static final DiscreteDomain<Integer> INTEGERS = DiscreteDomain.integers(); /** Set the lines. */ protected final void setLines(ImmutableList<String> lines) { this.lines = lines; } /** * Get the line count. * * @return the line count */ public final int getLineCount() { return lines.size(); } /** * Get a line. * * @param lineI the line number * @return the line */ public final String getLine(int lineI) { return lines.get(lineI); } /** The {@link Range}s of the tokens or comments lying on each line, in any part. */ protected final List<Range<Integer>> ranges = new ArrayList<>(); private static void addToRanges(List<Range<Integer>> ranges, int i, int k) { while (ranges.size() <= i) { ranges.add(EMPTY_RANGE); } Range<Integer> oldValue = ranges.get(i); ranges.set(i, Range.closedOpen(oldValue.isEmpty() ? k : oldValue.lowerEndpoint(), k + 1)); } protected final void computeRanges(List<? extends Input.Tok> toks) {<FILL_FUNCTION_BODY>} /** * Given an {@code InputOutput}, compute the map from tok indices to line ranges. * * @param put the {@code InputOutput} * @return the map from {@code com.google.googlejavaformat.java.JavaInput.Tok} indices to line * ranges in this {@code put} */ public static Map<Integer, Range<Integer>> makeKToIJ(InputOutput put) { Map<Integer, Range<Integer>> map = new HashMap<>(); int ijN = put.getLineCount(); for (int ij = 0; ij <= ijN; ij++) { Range<Integer> range = put.getRanges(ij).canonical(INTEGERS); for (int k = range.lowerEndpoint(); k < range.upperEndpoint(); k++) { if (map.containsKey(k)) { map.put(k, Range.closedOpen(map.get(k).lowerEndpoint(), ij + 1)); } else { map.put(k, Range.closedOpen(ij, ij + 1)); } } } return map; } /** * Get the {@link Range} of {@link Input.Tok}s lying in any part on a line. * * @param lineI the line number * @return the {@link Range} of {@link Input.Tok}s on the specified line */ public final Range<Integer> getRanges(int lineI) { return 0 <= lineI && lineI < ranges.size() ? ranges.get(lineI) : EMPTY_RANGE; } @Override public String toString() { return "InputOutput{" + "lines=" + lines + ", ranges=" + ranges + '}'; } }
int lineI = 0; for (Input.Tok tok : toks) { String txt = tok.getOriginalText(); int lineI0 = lineI; lineI += Newlines.count(txt); int k = tok.getIndex(); if (k >= 0) { for (int i = lineI0; i <= lineI; i++) { addToRanges(ranges, i, k); } } }
841
119
960
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/Newlines.java
LineOffsetIterator
next
class LineOffsetIterator implements Iterator<Integer> { private int curr = 0; private int idx = 0; private final String input; private LineOffsetIterator(String input) { this.input = input; } @Override public boolean hasNext() { return curr != -1; } @Override public Integer next() {<FILL_FUNCTION_BODY>} private void advance() { for (; idx < input.length(); idx++) { char c = input.charAt(idx); switch (c) { case '\r': if (idx + 1 < input.length() && input.charAt(idx + 1) == '\n') { idx++; } // falls through case '\n': idx++; curr = idx; return; default: break; } } curr = -1; } @Override public void remove() { throw new UnsupportedOperationException("remove"); } }
if (curr == -1) { throw new NoSuchElementException(); } int result = curr; advance(); return result;
273
43
316
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/Output.java
BreakTag
recordBroken
class BreakTag { Optional<Boolean> taken = Optional.empty(); public void recordBroken(boolean broken) {<FILL_FUNCTION_BODY>} public boolean wasBreakTaken() { return taken.orElse(false); } }
// TODO(cushon): enforce invariants. // Currently we rely on setting Breaks multiple times, e.g. when deciding // whether a Level should be flowed. Using separate data structures // instead of mutation or adding an explicit 'reset' step would allow // a useful invariant to be enforced here. taken = Optional.of(broken);
71
89
160
<methods>public non-sealed void <init>() ,public final java.lang.String getLine(int) ,public final int getLineCount() ,public final Range<java.lang.Integer> getRanges(int) ,public static Map<java.lang.Integer,Range<java.lang.Integer>> makeKToIJ(com.google.googlejavaformat.InputOutput) ,public java.lang.String toString() <variables>protected static final Range<java.lang.Integer> EMPTY_RANGE,private static final DiscreteDomain<java.lang.Integer> INTEGERS,private ImmutableList<java.lang.String> lines,protected final List<Range<java.lang.Integer>> ranges
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptions.java
Builder
build
class Builder { private final ImmutableList.Builder<String> files = ImmutableList.builder(); private final RangeSet<Integer> lines = TreeRangeSet.create(); private final ImmutableList.Builder<Integer> offsets = ImmutableList.builder(); private final ImmutableList.Builder<Integer> lengths = ImmutableList.builder(); private boolean inPlace = false; private boolean aosp = false; private boolean version = false; private boolean help = false; private boolean stdin = false; private boolean fixImportsOnly = false; private boolean sortImports = true; private boolean removeUnusedImports = true; private boolean dryRun = false; private boolean setExitIfChanged = false; private Optional<String> assumeFilename = Optional.empty(); private boolean reflowLongStrings = true; private boolean formatJavadoc = true; ImmutableList.Builder<String> filesBuilder() { return files; } Builder inPlace(boolean inPlace) { this.inPlace = inPlace; return this; } RangeSet<Integer> linesBuilder() { return lines; } Builder addOffset(Integer offset) { offsets.add(offset); return this; } Builder addLength(Integer length) { lengths.add(length); return this; } Builder aosp(boolean aosp) { this.aosp = aosp; return this; } Builder version(boolean version) { this.version = version; return this; } Builder help(boolean help) { this.help = help; return this; } Builder stdin(boolean stdin) { this.stdin = stdin; return this; } Builder fixImportsOnly(boolean fixImportsOnly) { this.fixImportsOnly = fixImportsOnly; return this; } Builder sortImports(boolean sortImports) { this.sortImports = sortImports; return this; } Builder removeUnusedImports(boolean removeUnusedImports) { this.removeUnusedImports = removeUnusedImports; return this; } Builder dryRun(boolean dryRun) { this.dryRun = dryRun; return this; } Builder setExitIfChanged(boolean setExitIfChanged) { this.setExitIfChanged = setExitIfChanged; return this; } Builder assumeFilename(String assumeFilename) { this.assumeFilename = Optional.of(assumeFilename); return this; } Builder reflowLongStrings(boolean reflowLongStrings) { this.reflowLongStrings = reflowLongStrings; return this; } Builder formatJavadoc(boolean formatJavadoc) { this.formatJavadoc = formatJavadoc; return this; } CommandLineOptions build() {<FILL_FUNCTION_BODY>} }
return new CommandLineOptions( files.build(), inPlace, ImmutableRangeSet.copyOf(lines), offsets.build(), lengths.build(), aosp, version, help, stdin, fixImportsOnly, sortImports, removeUnusedImports, dryRun, setExitIfChanged, assumeFilename, reflowLongStrings, formatJavadoc);
784
119
903
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java
CommandLineOptionsParser
parse
class CommandLineOptionsParser { private static final Splitter COMMA_SPLITTER = Splitter.on(','); private static final Splitter COLON_SPLITTER = Splitter.on(':'); private static final Splitter ARG_SPLITTER = Splitter.on(CharMatcher.breakingWhitespace()).omitEmptyStrings().trimResults(); /** Parses {@link CommandLineOptions}. */ static CommandLineOptions parse(Iterable<String> options) {<FILL_FUNCTION_BODY>} private static Integer parseInteger(Iterator<String> it, String flag, String value) { try { return Integer.valueOf(getValue(flag, it, value)); } catch (NumberFormatException e) { throw new IllegalArgumentException( String.format("invalid integer value for %s: %s", flag, value), e); } } private static String getValue(String flag, Iterator<String> it, String value) { if (value != null) { return value; } if (!it.hasNext()) { throw new IllegalArgumentException("required value was not provided for: " + flag); } return it.next(); } /** * Parse multiple --lines flags, like {"1:12,14,20:36", "40:45,50"}. Multiple ranges can be given * with multiple --lines flags or separated by commas. A single line can be set by a single * number. Line numbers are {@code 1}-based, but are converted to the {@code 0}-based numbering * used internally by google-java-format. */ private static void parseRangeSet(RangeSet<Integer> result, String ranges) { for (String range : COMMA_SPLITTER.split(ranges)) { result.add(parseRange(range)); } } /** * Parse a range, as in "1:12" or "42". Line numbers provided are {@code 1}-based, but are * converted here to {@code 0}-based. */ private static Range<Integer> parseRange(String arg) { List<String> args = COLON_SPLITTER.splitToList(arg); switch (args.size()) { case 1: int line = Integer.parseInt(args.get(0)) - 1; return Range.closedOpen(line, line + 1); case 2: int line0 = Integer.parseInt(args.get(0)) - 1; int line1 = Integer.parseInt(args.get(1)) - 1; return Range.closedOpen(line0, line1 + 1); default: throw new IllegalArgumentException(arg); } } /** * Pre-processes an argument list, expanding arguments of the form {@code @filename} by reading * the content of the file and appending whitespace-delimited options to {@code arguments}. */ private static void expandParamsFiles(Iterable<String> args, List<String> expanded) { for (String arg : args) { if (arg.isEmpty()) { continue; } if (!arg.startsWith("@")) { expanded.add(arg); } else if (arg.startsWith("@@")) { expanded.add(arg.substring(1)); } else { Path path = Paths.get(arg.substring(1)); try { String sequence = new String(Files.readAllBytes(path), UTF_8); expandParamsFiles(ARG_SPLITTER.split(sequence), expanded); } catch (IOException e) { throw new UncheckedIOException(path + ": could not read file: " + e.getMessage(), e); } } } } }
CommandLineOptions.Builder optionsBuilder = CommandLineOptions.builder(); List<String> expandedOptions = new ArrayList<>(); expandParamsFiles(options, expandedOptions); Iterator<String> it = expandedOptions.iterator(); while (it.hasNext()) { String option = it.next(); if (!option.startsWith("-")) { optionsBuilder.filesBuilder().add(option).addAll(it); break; } String flag; String value; int idx = option.indexOf('='); if (idx >= 0) { flag = option.substring(0, idx); value = option.substring(idx + 1); } else { flag = option; value = null; } // NOTE: update usage information in UsageException when new flags are added switch (flag) { case "-i": case "-r": case "-replace": case "--replace": optionsBuilder.inPlace(true); break; case "--lines": case "-lines": case "--line": case "-line": parseRangeSet(optionsBuilder.linesBuilder(), getValue(flag, it, value)); break; case "--offset": case "-offset": optionsBuilder.addOffset(parseInteger(it, flag, value)); break; case "--length": case "-length": optionsBuilder.addLength(parseInteger(it, flag, value)); break; case "--aosp": case "-aosp": case "-a": optionsBuilder.aosp(true); break; case "--version": case "-version": case "-v": optionsBuilder.version(true); break; case "--help": case "-help": case "-h": optionsBuilder.help(true); break; case "--fix-imports-only": optionsBuilder.fixImportsOnly(true); break; case "--skip-sorting-imports": optionsBuilder.sortImports(false); break; case "--skip-removing-unused-imports": optionsBuilder.removeUnusedImports(false); break; case "--skip-reflowing-long-strings": optionsBuilder.reflowLongStrings(false); break; case "--skip-javadoc-formatting": optionsBuilder.formatJavadoc(false); break; case "-": optionsBuilder.stdin(true); break; case "-n": case "--dry-run": optionsBuilder.dryRun(true); break; case "--set-exit-if-changed": optionsBuilder.setExitIfChanged(true); break; case "-assume-filename": case "--assume-filename": optionsBuilder.assumeFilename(getValue(flag, it, value)); break; default: throw new IllegalArgumentException("unexpected flag: " + flag); } } return optionsBuilder.build();
971
773
1,744
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/java/DimensionHelpers.java
TypeWithDims
extractDims
class TypeWithDims { final Tree node; final ImmutableList<List<AnnotationTree>> dims; public TypeWithDims(Tree node, ImmutableList<List<AnnotationTree>> dims) { this.node = node; this.dims = dims; } } enum SortedDims { YES, NO } /** Returns a (possibly re-ordered) {@link TypeWithDims} for the given type. */ static TypeWithDims extractDims(Tree node, SortedDims sorted) {<FILL_FUNCTION_BODY>
Deque<List<AnnotationTree>> builder = new ArrayDeque<>(); node = extractDims(builder, node); Iterable<List<AnnotationTree>> dims; if (sorted == SortedDims.YES) { dims = reorderBySourcePosition(builder); } else { dims = builder; } return new TypeWithDims(node, ImmutableList.copyOf(dims));
155
113
268
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/java/FormatFileCallable.java
Result
fixImports
class Result { abstract @Nullable Path path(); abstract String input(); abstract @Nullable String output(); boolean changed() { return !input().equals(output()); } abstract @Nullable FormatterException exception(); static Result create( @Nullable Path path, String input, @Nullable String output, @Nullable FormatterException exception) { return new AutoValue_FormatFileCallable_Result(path, input, output, exception); } } private final Path path; private final String input; private final CommandLineOptions parameters; private final JavaFormatterOptions options; public FormatFileCallable( CommandLineOptions parameters, Path path, String input, JavaFormatterOptions options) { this.path = path; this.input = input; this.parameters = parameters; this.options = options; } @Override public Result call() { try { if (parameters.fixImportsOnly()) { return Result.create(path, input, fixImports(input), /* exception= */ null); } Formatter formatter = new Formatter(options); String formatted = formatter.formatSource(input, characterRanges(input).asRanges()); formatted = fixImports(formatted); if (parameters.reflowLongStrings()) { formatted = StringWrapper.wrap(Formatter.MAX_LINE_LENGTH, formatted, formatter); } return Result.create(path, input, formatted, /* exception= */ null); } catch (FormatterException e) { return Result.create(path, input, /* output= */ null, e); } } private String fixImports(String input) throws FormatterException {<FILL_FUNCTION_BODY>
if (parameters.removeUnusedImports()) { input = RemoveUnusedImports.removeUnusedImports(input); } if (parameters.sortImports()) { input = ImportOrderer.reorderImports(input, options.style()); } return input;
446
76
522
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatTool.java
GoogleJavaFormatTool
run
class GoogleJavaFormatTool implements Tool { @Override public String name() { return "google-java-format"; } @Override public Set<SourceVersion> getSourceVersions() { return Arrays.stream(SourceVersion.values()).collect(toImmutableEnumSet()); } @Override public int run(InputStream in, OutputStream out, OutputStream err, String... args) {<FILL_FUNCTION_BODY>} }
PrintStream outStream = new PrintStream(out); PrintStream errStream = new PrintStream(err); try { return Main.main(in, outStream, errStream, args); } catch (RuntimeException e) { errStream.print(e.getMessage()); errStream.flush(); return 1; // pass non-zero value back indicating an error has happened }
117
99
216
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatToolProvider.java
GoogleJavaFormatToolProvider
run
class GoogleJavaFormatToolProvider implements ToolProvider { @Override public String name() { return "google-java-format"; } @Override public int run(PrintWriter out, PrintWriter err, String... args) {<FILL_FUNCTION_BODY>} }
try { return Main.main(System.in, out, err, args); } catch (RuntimeException e) { err.print(e.getMessage()); err.flush(); return 1; // pass non-zero value back indicating an error has happened }
73
71
144
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java
StringAndIndex
scanImported
class StringAndIndex { private final String string; private final int index; StringAndIndex(String string, int index) { this.string = string; this.index = index; } } /** * Scans the imported thing, the dot-separated name that comes after import [static] and before * the semicolon. We don't allow spaces inside the dot-separated name. Wildcard imports are * supported: if the input is {@code import java.util.*;} then the returned string will be {@code * java.util.*}. * * @param start the index of the start of the identifier. If the import is {@code import * java.util.List;} then this index points to the token {@code java}. * @return the parsed import ({@code java.util.List} in the example) and the index of the first * token after the imported thing ({@code ;} in the example). * @throws FormatterException if the imported name could not be parsed. */ private StringAndIndex scanImported(int start) throws FormatterException {<FILL_FUNCTION_BODY>
int i = start; StringBuilder imported = new StringBuilder(); // At the start of each iteration of this loop, i points to an identifier. // On exit from the loop, i points to a token after an identifier or after *. while (true) { Preconditions.checkState(isIdentifierToken(i)); imported.append(tokenAt(i)); i++; if (!tokenAt(i).equals(".")) { return new StringAndIndex(imported.toString(), i); } imported.append('.'); i++; if (tokenAt(i).equals("*")) { imported.append('*'); return new StringAndIndex(imported.toString(), i + 1); } else if (!isIdentifierToken(i)) { throw new FormatterException("Could not parse imported name, at: " + tokenAt(i)); } }
286
222
508
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/java/JavaCommentsHelper.java
JavaCommentsHelper
javadocShaped
class JavaCommentsHelper implements CommentsHelper { private final String lineSeparator; private final JavaFormatterOptions options; public JavaCommentsHelper(String lineSeparator, JavaFormatterOptions options) { this.lineSeparator = lineSeparator; this.options = options; } @Override public String rewrite(Tok tok, int maxWidth, int column0) { if (!tok.isComment()) { return tok.getOriginalText(); } String text = tok.getOriginalText(); if (tok.isJavadocComment() && options.formatJavadoc()) { text = JavadocFormatter.formatJavadoc(text, column0); } List<String> lines = new ArrayList<>(); Iterator<String> it = Newlines.lineIterator(text); while (it.hasNext()) { lines.add(CharMatcher.whitespace().trimTrailingFrom(it.next())); } if (tok.isSlashSlashComment()) { return indentLineComments(lines, column0); } return CommentsHelper.reformatParameterComment(tok) .orElseGet( () -> javadocShaped(lines) ? indentJavadoc(lines, column0) : preserveIndentation(lines, column0)); } // For non-javadoc-shaped block comments, shift the entire block to the correct // column, but do not adjust relative indentation. private String preserveIndentation(List<String> lines, int column0) { StringBuilder builder = new StringBuilder(); // find the leftmost non-whitespace character in all trailing lines int startCol = -1; for (int i = 1; i < lines.size(); i++) { int lineIdx = CharMatcher.whitespace().negate().indexIn(lines.get(i)); if (lineIdx >= 0 && (startCol == -1 || lineIdx < startCol)) { startCol = lineIdx; } } // output the first line at the current column builder.append(lines.get(0)); // output all trailing lines with plausible indentation for (int i = 1; i < lines.size(); ++i) { builder.append(lineSeparator).append(Strings.repeat(" ", column0)); // check that startCol is valid index, e.g. for blank lines if (lines.get(i).length() >= startCol) { builder.append(lines.get(i).substring(startCol)); } else { builder.append(lines.get(i)); } } return builder.toString(); } // Wraps and re-indents line comments. private String indentLineComments(List<String> lines, int column0) { lines = wrapLineComments(lines, column0); StringBuilder builder = new StringBuilder(); builder.append(lines.get(0).trim()); String indentString = Strings.repeat(" ", column0); for (int i = 1; i < lines.size(); ++i) { builder.append(lineSeparator).append(indentString).append(lines.get(i).trim()); } return builder.toString(); } // Preserve special `//noinspection` and `//$NON-NLS-x$` comments used by IDEs, which cannot // contain leading spaces. private static final Pattern LINE_COMMENT_MISSING_SPACE_PREFIX = Pattern.compile("^(//+)(?!noinspection|\\$NON-NLS-\\d+\\$)[^\\s/]"); private List<String> wrapLineComments(List<String> lines, int column0) { List<String> result = new ArrayList<>(); for (String line : lines) { // Add missing leading spaces to line comments: `//foo` -> `// foo`. Matcher matcher = LINE_COMMENT_MISSING_SPACE_PREFIX.matcher(line); if (matcher.find()) { int length = matcher.group(1).length(); line = Strings.repeat("/", length) + " " + line.substring(length); } if (line.startsWith("// MOE:")) { // don't wrap comments for https://github.com/google/MOE result.add(line); continue; } while (line.length() + column0 > Formatter.MAX_LINE_LENGTH) { int idx = Formatter.MAX_LINE_LENGTH - column0; // only break on whitespace characters, and ignore the leading `// ` while (idx >= 2 && !CharMatcher.whitespace().matches(line.charAt(idx))) { idx--; } if (idx <= 2) { break; } result.add(line.substring(0, idx)); line = "//" + line.substring(idx); } result.add(line); } return result; } // Remove leading whitespace (trailing was already removed), and re-indent. // Add a +1 indent before '*', and add the '*' if necessary. private String indentJavadoc(List<String> lines, int column0) { StringBuilder builder = new StringBuilder(); builder.append(lines.get(0).trim()); int indent = column0 + 1; String indentString = Strings.repeat(" ", indent); for (int i = 1; i < lines.size(); ++i) { builder.append(lineSeparator).append(indentString); String line = lines.get(i).trim(); if (!line.startsWith("*")) { builder.append("* "); } builder.append(line); } return builder.toString(); } // Returns true if the comment looks like javadoc private static boolean javadocShaped(List<String> lines) {<FILL_FUNCTION_BODY>} }
Iterator<String> it = lines.iterator(); if (!it.hasNext()) { return false; } String first = it.next().trim(); // if it's actually javadoc, we're done if (first.startsWith("/**")) { return true; } // if it's a block comment, check all trailing lines for '*' if (!first.startsWith("/*")) { return false; } while (it.hasNext()) { if (!it.next().trim().startsWith("*")) { return false; } } return true;
1,535
165
1,700
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/java/JavacTokens.java
RawTok
readAllTokens
class RawTok { private final String stringVal; private final TokenKind kind; private final int pos; private final int endPos; RawTok(String stringVal, TokenKind kind, int pos, int endPos) { checkElementIndex(pos, endPos, "pos"); checkArgument(pos < endPos, "expected pos (%s) < endPos (%s)", pos, endPos); this.stringVal = stringVal; this.kind = kind; this.pos = pos; this.endPos = endPos; } /** The token kind, or {@code null} for whitespace and comments. */ public TokenKind kind() { return kind; } /** The start position. */ public int pos() { return pos; } /** The end position. */ public int endPos() { return endPos; } /** The escaped string value of a literal, or {@code null} for other tokens. */ public String stringVal() { return stringVal; } } private static final TokenKind STRINGFRAGMENT = stream(TokenKind.values()) .filter(t -> t.name().contentEquals("STRINGFRAGMENT")) .findFirst() .orElse(null); static boolean isStringFragment(TokenKind kind) { return STRINGFRAGMENT != null && Objects.equals(kind, STRINGFRAGMENT); } private static ImmutableList<Token> readAllTokens( String source, Context context, Set<Integer> nonTerminalStringFragments) {<FILL_FUNCTION_BODY>
if (source == null) { return ImmutableList.of(); } ScannerFactory fac = ScannerFactory.instance(context); char[] buffer = (source + EOF_COMMENT).toCharArray(); Scanner scanner = new AccessibleScanner(fac, new CommentSavingTokenizer(fac, buffer, buffer.length)); List<Token> tokens = new ArrayList<>(); do { scanner.nextToken(); tokens.add(scanner.token()); } while (scanner.token().kind != TokenKind.EOF); for (int i = 0; i < tokens.size(); i++) { if (isStringFragment(tokens.get(i).kind)) { int start = i; while (isStringFragment(tokens.get(i).kind)) { i++; } for (int j = start; j < i - 1; j++) { nonTerminalStringFragments.add(tokens.get(j).pos); } } } // A string template is tokenized as a series of STRINGFRAGMENT tokens containing the string // literal values, followed by the tokens for the template arguments. For the formatter, we // want the stream of tokens to appear in order by their start position. if (Runtime.version().feature() >= 21) { Collections.sort(tokens, Comparator.comparingInt(t -> t.pos)); } return ImmutableList.copyOf(tokens);
420
381
801
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/java/ModifierOrderer.java
ModifierOrderer
asModifier
class ModifierOrderer { /** Reorders all modifiers in the given text to be in JLS order. */ static JavaInput reorderModifiers(String text) throws FormatterException { return reorderModifiers( new JavaInput(text), ImmutableList.of(Range.closedOpen(0, text.length()))); } /** * Reorders all modifiers in the given text and within the given character ranges to be in JLS * order. */ static JavaInput reorderModifiers(JavaInput javaInput, Collection<Range<Integer>> characterRanges) throws FormatterException { if (javaInput.getTokens().isEmpty()) { // There weren't any tokens, possible because of a lexing error. // Errors about invalid input will be reported later after parsing. return javaInput; } RangeSet<Integer> tokenRanges = javaInput.characterRangesToTokenRanges(characterRanges); Iterator<? extends Token> it = javaInput.getTokens().iterator(); TreeRangeMap<Integer, String> replacements = TreeRangeMap.create(); while (it.hasNext()) { Token token = it.next(); if (!tokenRanges.contains(token.getTok().getIndex())) { continue; } Modifier mod = asModifier(token); if (mod == null) { continue; } List<Token> modifierTokens = new ArrayList<>(); List<Modifier> mods = new ArrayList<>(); int begin = token.getTok().getPosition(); mods.add(mod); modifierTokens.add(token); int end = -1; while (it.hasNext()) { token = it.next(); mod = asModifier(token); if (mod == null) { break; } mods.add(mod); modifierTokens.add(token); end = token.getTok().getPosition() + token.getTok().length(); } if (!Ordering.natural().isOrdered(mods)) { Collections.sort(mods); StringBuilder replacement = new StringBuilder(); for (int i = 0; i < mods.size(); i++) { if (i > 0) { addTrivia(replacement, modifierTokens.get(i).getToksBefore()); } replacement.append(mods.get(i)); if (i < (modifierTokens.size() - 1)) { addTrivia(replacement, modifierTokens.get(i).getToksAfter()); } } replacements.put(Range.closedOpen(begin, end), replacement.toString()); } } return applyReplacements(javaInput, replacements); } private static void addTrivia(StringBuilder replacement, ImmutableList<? extends Tok> toks) { for (Tok tok : toks) { replacement.append(tok.getText()); } } /** * Returns the given token as a {@link javax.lang.model.element.Modifier}, or {@code null} if it * is not a modifier. */ private static Modifier asModifier(Token token) {<FILL_FUNCTION_BODY>} /** Applies replacements to the given string. */ private static JavaInput applyReplacements( JavaInput javaInput, TreeRangeMap<Integer, String> replacementMap) throws FormatterException { // process in descending order so the replacement ranges aren't perturbed if any replacements // differ in size from the input Map<Range<Integer>, String> ranges = replacementMap.asDescendingMapOfRanges(); if (ranges.isEmpty()) { return javaInput; } StringBuilder sb = new StringBuilder(javaInput.getText()); for (Entry<Range<Integer>, String> entry : ranges.entrySet()) { Range<Integer> range = entry.getKey(); sb.replace(range.lowerEndpoint(), range.upperEndpoint(), entry.getValue()); } return new JavaInput(sb.toString()); } }
TokenKind kind = ((JavaInput.Tok) token.getTok()).kind(); if (kind != null) { switch (kind) { case PUBLIC: return Modifier.PUBLIC; case PROTECTED: return Modifier.PROTECTED; case PRIVATE: return Modifier.PRIVATE; case ABSTRACT: return Modifier.ABSTRACT; case STATIC: return Modifier.STATIC; case DEFAULT: return Modifier.DEFAULT; case FINAL: return Modifier.FINAL; case TRANSIENT: return Modifier.TRANSIENT; case VOLATILE: return Modifier.VOLATILE; case SYNCHRONIZED: return Modifier.SYNCHRONIZED; case NATIVE: return Modifier.NATIVE; case STRICTFP: return Modifier.STRICTFP; default: // fall out } } switch (token.getTok().getText()) { case "non-sealed": return Modifier.valueOf("NON_SEALED"); case "sealed": return Modifier.valueOf("SEALED"); default: return null; }
1,049
335
1,384
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/java/RemoveUnusedImports.java
UnusedImportScanner
caseTreeGetLabels
class UnusedImportScanner extends TreePathScanner<Void, Void> { private final Set<String> usedNames = new LinkedHashSet<>(); private final Multimap<String, Range<Integer>> usedInJavadoc = HashMultimap.create(); final JavacTrees trees; final DocTreeScanner docTreeSymbolScanner; private UnusedImportScanner(JavacTrees trees) { this.trees = trees; docTreeSymbolScanner = new DocTreeScanner(); } /** Skip the imports themselves when checking for usage. */ @Override public Void visitImport(ImportTree importTree, Void usedSymbols) { return null; } @Override public Void visitIdentifier(IdentifierTree tree, Void unused) { if (tree == null) { return null; } usedNames.add(tree.getName().toString()); return null; } // TODO(cushon): remove this override when pattern matching in switch is no longer a preview // feature, and TreePathScanner visits CaseTree#getLabels instead of CaseTree#getExpressions @SuppressWarnings("unchecked") // reflection @Override public Void visitCase(CaseTree tree, Void unused) { if (CASE_TREE_GET_LABELS != null) { try { scan((List<? extends Tree>) CASE_TREE_GET_LABELS.invoke(tree), null); } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } } return super.visitCase(tree, null); } private static final Method CASE_TREE_GET_LABELS = caseTreeGetLabels(); private static Method caseTreeGetLabels() {<FILL_FUNCTION_BODY>} @Override public Void scan(Tree tree, Void unused) { if (tree == null) { return null; } scanJavadoc(); return super.scan(tree, unused); } private void scanJavadoc() { if (getCurrentPath() == null) { return; } DocCommentTree commentTree = trees.getDocCommentTree(getCurrentPath()); if (commentTree == null) { return; } docTreeSymbolScanner.scan(new DocTreePath(getCurrentPath(), commentTree), null); } // scan javadoc comments, checking for references to imported types class DocTreeScanner extends DocTreePathScanner<Void, Void> { @Override public Void visitIdentifier(com.sun.source.doctree.IdentifierTree node, Void aVoid) { return null; } @Override public Void visitReference(ReferenceTree referenceTree, Void unused) { DCReference reference = (DCReference) referenceTree; long basePos = reference .pos((DCTree.DCDocComment) getCurrentPath().getDocComment()) .getStartPosition(); // the position of trees inside the reference node aren't stored, but the qualifier's // start position is the beginning of the reference node if (reference.qualifierExpression != null) { new ReferenceScanner(basePos).scan(reference.qualifierExpression, null); } // Record uses inside method parameters. The javadoc tool doesn't use these, but // IntelliJ does. if (reference.paramTypes != null) { for (JCTree param : reference.paramTypes) { // TODO(cushon): get start positions for the parameters new ReferenceScanner(-1).scan(param, null); } } return null; } // scans the qualifier and parameters of a javadoc reference for possible type names private class ReferenceScanner extends TreeScanner<Void, Void> { private final long basePos; public ReferenceScanner(long basePos) { this.basePos = basePos; } @Override public Void visitIdentifier(IdentifierTree node, Void aVoid) { usedInJavadoc.put( node.getName().toString(), basePos != -1 ? Range.closedOpen((int) basePos, (int) basePos + node.getName().length()) : null); return super.visitIdentifier(node, aVoid); } } } }
try { return CaseTree.class.getMethod("getLabels"); } catch (NoSuchMethodException e) { return null; }
1,131
42
1,173
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/java/Replacement.java
Replacement
create
class Replacement { public static Replacement create(int startPosition, int endPosition, String replaceWith) {<FILL_FUNCTION_BODY>} private final Range<Integer> replaceRange; private final String replacementString; private Replacement(Range<Integer> replaceRange, String replacementString) { this.replaceRange = checkNotNull(replaceRange, "Null replaceRange"); this.replacementString = checkNotNull(replacementString, "Null replacementString"); } /** The range of characters in the original source to replace. */ public Range<Integer> getReplaceRange() { return replaceRange; } /** The string to replace the range of characters with. */ public String getReplacementString() { return replacementString; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof Replacement) { Replacement that = (Replacement) o; return replaceRange.equals(that.getReplaceRange()) && replacementString.equals(that.getReplacementString()); } return false; } @Override public int hashCode() { return Objects.hash(replaceRange, replacementString); } }
checkArgument(startPosition >= 0, "startPosition must be non-negative"); checkArgument(startPosition <= endPosition, "startPosition cannot be after endPosition"); return new Replacement(Range.closedOpen(startPosition, endPosition), replaceWith);
316
63
379
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/java/SnippetFormatter.java
SnippetWrapper
snippetWrapper
class SnippetWrapper { int offset; final StringBuilder contents = new StringBuilder(); public SnippetWrapper append(String str) { contents.append(str); return this; } public SnippetWrapper appendSource(String source) { this.offset = contents.length(); contents.append(source); return this; } public void closeBraces(int initialIndent) { for (int i = initialIndent; --i >= 0; ) { contents.append("\n").append(createIndentationString(i)).append("}"); } } } private static final int INDENTATION_SIZE = 2; private final Formatter formatter = new Formatter(); private static final CharMatcher NOT_WHITESPACE = CharMatcher.whitespace().negate(); public String createIndentationString(int indentationLevel) { Preconditions.checkArgument( indentationLevel >= 0, "Indentation level cannot be less than zero. Given: %s", indentationLevel); int spaces = indentationLevel * INDENTATION_SIZE; StringBuilder buf = new StringBuilder(spaces); for (int i = 0; i < spaces; i++) { buf.append(' '); } return buf.toString(); } private static Range<Integer> offsetRange(Range<Integer> range, int offset) { range = range.canonical(DiscreteDomain.integers()); return Range.closedOpen(range.lowerEndpoint() + offset, range.upperEndpoint() + offset); } private static List<Range<Integer>> offsetRanges(List<Range<Integer>> ranges, int offset) { List<Range<Integer>> result = new ArrayList<>(); for (Range<Integer> range : ranges) { result.add(offsetRange(range, offset)); } return result; } /** Runs the Google Java formatter on the given source, with only the given ranges specified. */ public ImmutableList<Replacement> format( SnippetKind kind, String source, List<Range<Integer>> ranges, int initialIndent, boolean includeComments) throws FormatterException { RangeSet<Integer> rangeSet = TreeRangeSet.create(); for (Range<Integer> range : ranges) { rangeSet.add(range); } if (includeComments) { if (kind != SnippetKind.COMPILATION_UNIT) { throw new IllegalArgumentException( "comment formatting is only supported for compilation units"); } return formatter.getFormatReplacements(source, ranges); } SnippetWrapper wrapper = snippetWrapper(kind, source, initialIndent); ranges = offsetRanges(ranges, wrapper.offset); String replacement = formatter.formatSource(wrapper.contents.toString(), ranges); replacement = replacement.substring( wrapper.offset, replacement.length() - (wrapper.contents.length() - wrapper.offset - source.length())); return toReplacements(source, replacement).stream() .filter(r -> rangeSet.encloses(r.getReplaceRange())) .collect(toImmutableList()); } /** * Generates {@code Replacement}s rewriting {@code source} to {@code replacement}, under the * assumption that they differ in whitespace alone. */ private static List<Replacement> toReplacements(String source, String replacement) { if (!NOT_WHITESPACE.retainFrom(source).equals(NOT_WHITESPACE.retainFrom(replacement))) { throw new IllegalArgumentException( "source = \"" + source + "\", replacement = \"" + replacement + "\""); } /* * In the past we seemed to have problems touching non-whitespace text in the formatter, even * just replacing some code with itself. Retrospective attempts to reproduce this have failed, * but this may be an issue for future changes. */ List<Replacement> replacements = new ArrayList<>(); int i = NOT_WHITESPACE.indexIn(source); int j = NOT_WHITESPACE.indexIn(replacement); if (i != 0 || j != 0) { replacements.add(Replacement.create(0, i, replacement.substring(0, j))); } while (i != -1 && j != -1) { int i2 = NOT_WHITESPACE.indexIn(source, i + 1); int j2 = NOT_WHITESPACE.indexIn(replacement, j + 1); if (i2 == -1 || j2 == -1) { break; } if ((i2 - i) != (j2 - j) || !source.substring(i + 1, i2).equals(replacement.substring(j + 1, j2))) { replacements.add(Replacement.create(i + 1, i2, replacement.substring(j + 1, j2))); } i = i2; j = j2; } return replacements; } private SnippetWrapper snippetWrapper(SnippetKind kind, String source, int initialIndent) {<FILL_FUNCTION_BODY>
/* * Synthesize a dummy class around the code snippet provided by Eclipse. The dummy class is * correctly formatted -- the blocks use correct indentation, etc. */ switch (kind) { case COMPILATION_UNIT: { SnippetWrapper wrapper = new SnippetWrapper(); for (int i = 1; i <= initialIndent; i++) { wrapper.append("class Dummy {\n").append(createIndentationString(i)); } wrapper.appendSource(source); wrapper.closeBraces(initialIndent); return wrapper; } case CLASS_BODY_DECLARATIONS: { SnippetWrapper wrapper = new SnippetWrapper(); for (int i = 1; i <= initialIndent; i++) { wrapper.append("class Dummy {\n").append(createIndentationString(i)); } wrapper.appendSource(source); wrapper.closeBraces(initialIndent); return wrapper; } case STATEMENTS: { SnippetWrapper wrapper = new SnippetWrapper(); wrapper.append("class Dummy {\n").append(createIndentationString(1)); for (int i = 2; i <= initialIndent; i++) { wrapper.append("{\n").append(createIndentationString(i)); } wrapper.appendSource(source); wrapper.closeBraces(initialIndent); return wrapper; } case EXPRESSION: { SnippetWrapper wrapper = new SnippetWrapper(); wrapper.append("class Dummy {\n").append(createIndentationString(1)); for (int i = 2; i <= initialIndent; i++) { wrapper.append("{\n").append(createIndentationString(i)); } wrapper.append("Object o = "); wrapper.appendSource(source); wrapper.append(";"); wrapper.closeBraces(initialIndent); return wrapper; } default: throw new IllegalArgumentException("Unknown snippet kind: " + kind); }
1,357
541
1,898
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java
LongStringsAndTextBlockScanner
wrapLongStrings
class LongStringsAndTextBlockScanner extends TreePathScanner<Void, Void> { private final List<TreePath> longStringLiterals; private final List<Tree> textBlocks; LongStringsAndTextBlockScanner(List<TreePath> longStringLiterals, List<Tree> textBlocks) { this.longStringLiterals = longStringLiterals; this.textBlocks = textBlocks; } @Override public Void visitLiteral(LiteralTree literalTree, Void aVoid) { if (literalTree.getKind() != Kind.STRING_LITERAL) { return null; } int pos = getStartPosition(literalTree); if (input.substring(pos, min(input.length(), pos + 3)).equals("\"\"\"")) { textBlocks.add(literalTree); return null; } Tree parent = getCurrentPath().getParentPath().getLeaf(); if (parent instanceof MemberSelectTree && ((MemberSelectTree) parent).getExpression().equals(literalTree)) { return null; } int endPosition = getEndPosition(unit, literalTree); int lineEnd = endPosition; while (Newlines.hasNewlineAt(input, lineEnd) == -1) { lineEnd++; } if (lineMap.getColumnNumber(lineEnd) - 1 <= columnLimit) { return null; } longStringLiterals.add(getCurrentPath()); return null; } } private void indentTextBlocks( TreeRangeMap<Integer, String> replacements, List<Tree> textBlocks) { for (Tree tree : textBlocks) { int startPosition = getStartPosition(tree); int endPosition = getEndPosition(unit, tree); String text = input.substring(startPosition, endPosition); // Find the source code of the text block with incidental whitespace removed. // The first line of the text block is always """, and it does not affect incidental // whitespace. ImmutableList<String> initialLines = text.lines().collect(toImmutableList()); String stripped = stripIndent(initialLines.stream().skip(1).collect(joining(separator))); ImmutableList<String> lines = stripped.lines().collect(toImmutableList()); int deindent = initialLines.get(1).stripTrailing().length() - lines.get(0).stripTrailing().length(); int startColumn = lineMap.getColumnNumber(startPosition); String prefix = (deindent == 0 || lines.stream().anyMatch(x -> x.length() + startColumn > columnLimit)) ? "" : " ".repeat(startColumn - 1); StringBuilder output = new StringBuilder("\"\"\""); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); String trimmed = line.stripLeading().stripTrailing(); output.append(separator); if (!trimmed.isEmpty()) { // Don't add incidental leading whitespace to empty lines output.append(prefix); } if (i == lines.size() - 1 && trimmed.equals("\"\"\"")) { // If the trailing line is just """, indenting is more than the prefix of incidental // whitespace has no effect, and results in a javac text-blocks warning that 'trailing // white space will be removed'. output.append("\"\"\""); } else { output.append(line); } } replacements.put(Range.closedOpen(startPosition, endPosition), output.toString()); } } private void wrapLongStrings( TreeRangeMap<Integer, String> replacements, List<TreePath> longStringLiterals) {<FILL_FUNCTION_BODY>
for (TreePath path : longStringLiterals) { // Find the outermost contiguous enclosing concatenation expression TreePath enclosing = path; while (enclosing.getParentPath().getLeaf().getKind() == Kind.PLUS) { enclosing = enclosing.getParentPath(); } // Is the literal being wrapped the first in a chain of concatenation expressions? // i.e. `ONE + TWO + THREE` // We need this information to handle continuation indents. AtomicBoolean first = new AtomicBoolean(false); // Finds the set of string literals in the concat expression that includes the one that // needs // to be wrapped. List<Tree> flat = flatten(input, unit, path, enclosing, first); // Zero-indexed start column int startColumn = lineMap.getColumnNumber(getStartPosition(flat.get(0))) - 1; // Handling leaving trailing non-string tokens at the end of the literal, // e.g. the trailing `);` in `foo("...");`. int end = getEndPosition(unit, getLast(flat)); int lineEnd = end; while (Newlines.hasNewlineAt(input, lineEnd) == -1) { lineEnd++; } int trailing = lineEnd - end; // Get the original source text of the string literals, excluding `"` and `+`. ImmutableList<String> components = stringComponents(input, unit, flat); replacements.put( Range.closedOpen(getStartPosition(flat.get(0)), getEndPosition(unit, getLast(flat))), reflow(separator, columnLimit, startColumn, trailing, components, first.get())); }
990
455
1,445
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/java/Trees.java
Trees
operatorName
class Trees { /** Returns the length of the source for the node. */ static int getLength(Tree tree, TreePath path) { return getEndPosition(tree, path) - getStartPosition(tree); } /** Returns the source start position of the node. */ static int getStartPosition(Tree expression) { return ((JCTree) expression).getStartPosition(); } /** Returns the source end position of the node. */ static int getEndPosition(Tree expression, TreePath path) { return ((JCTree) expression) .getEndPosition(((JCTree.JCCompilationUnit) path.getCompilationUnit()).endPositions); } /** Returns the source text for the node. */ static String getSourceForNode(Tree node, TreePath path) { CharSequence source; try { source = path.getCompilationUnit().getSourceFile().getCharContent(false); } catch (IOException e) { throw new IOError(e); } return source.subSequence(getStartPosition(node), getEndPosition(node, path)).toString(); } /** Returns the simple name of a (possibly qualified) method invocation expression. */ static Name getMethodName(MethodInvocationTree methodInvocation) { ExpressionTree select = methodInvocation.getMethodSelect(); return select instanceof MemberSelectTree ? ((MemberSelectTree) select).getIdentifier() : ((IdentifierTree) select).getName(); } /** Returns the receiver of a qualified method invocation expression, or {@code null}. */ static ExpressionTree getMethodReceiver(MethodInvocationTree methodInvocation) { ExpressionTree select = methodInvocation.getMethodSelect(); return select instanceof MemberSelectTree ? ((MemberSelectTree) select).getExpression() : null; } /** Returns the string name of an operator, including assignment and compound assignment. */ static String operatorName(ExpressionTree expression) {<FILL_FUNCTION_BODY>} /** Returns the precedence of an expression's operator. */ static int precedence(ExpressionTree expression) { return TreeInfo.opPrec(((JCTree) expression).getTag()); } /** * Returns the enclosing type declaration (class, enum, interface, or annotation) for the given * path. */ static ClassTree getEnclosingTypeDeclaration(TreePath path) { for (; path != null; path = path.getParentPath()) { switch (path.getLeaf().getKind()) { case CLASS: case ENUM: case INTERFACE: case ANNOTATED_TYPE: return (ClassTree) path.getLeaf(); default: break; } } throw new AssertionError(); } /** Skips a single parenthesized tree. */ static ExpressionTree skipParen(ExpressionTree node) { return ((ParenthesizedTree) node).getExpression(); } }
JCTree.Tag tag = ((JCTree) expression).getTag(); if (tag == JCTree.Tag.ASSIGN) { return "="; } boolean assignOp = expression instanceof CompoundAssignmentTree; if (assignOp) { tag = tag.noAssignOp(); } String name = new Pretty(/*writer*/ null, /*sourceOutput*/ true).operatorName(tag); return assignOp ? name + "=" : name;
740
122
862
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/java/TypeNameClassifier.java
TypeNameClassifier
from
class TypeNameClassifier { private TypeNameClassifier() {} /** A state machine for classifying qualified names. */ private enum TyParseState { /** The start state. */ START(false) { @Override public TyParseState next(JavaCaseFormat n) { switch (n) { case UPPERCASE: // if we see an UpperCamel later, assume this was a class // e.g. com.google.FOO.Bar return TyParseState.AMBIGUOUS; case LOWER_CAMEL: return TyParseState.REJECT; case LOWERCASE: // could be a package return TyParseState.START; case UPPER_CAMEL: return TyParseState.TYPE; } throw new AssertionError(); } }, /** The current prefix is a type. */ TYPE(true) { @Override public TyParseState next(JavaCaseFormat n) { switch (n) { case UPPERCASE: case LOWER_CAMEL: case LOWERCASE: return TyParseState.FIRST_STATIC_MEMBER; case UPPER_CAMEL: return TyParseState.TYPE; } throw new AssertionError(); } }, /** The current prefix is a type, followed by a single static member access. */ FIRST_STATIC_MEMBER(true) { @Override public TyParseState next(JavaCaseFormat n) { return TyParseState.REJECT; } }, /** Anything not represented by one of the other states. */ REJECT(false) { @Override public TyParseState next(JavaCaseFormat n) { return TyParseState.REJECT; } }, /** An ambiguous type prefix. */ AMBIGUOUS(false) { @Override public TyParseState next(JavaCaseFormat n) { switch (n) { case UPPERCASE: return AMBIGUOUS; case LOWER_CAMEL: case LOWERCASE: return TyParseState.REJECT; case UPPER_CAMEL: return TyParseState.TYPE; } throw new AssertionError(); } }; private final boolean isSingleUnit; TyParseState(boolean isSingleUnit) { this.isSingleUnit = isSingleUnit; } public boolean isSingleUnit() { return isSingleUnit; } /** Transition function. */ public abstract TyParseState next(JavaCaseFormat n); } /** * Returns the end index (inclusive) of the longest prefix that matches the naming conventions of * a type or static field access, or -1 if no such prefix was found. * * <p>Examples: * * <ul> * <li>ClassName * <li>ClassName.staticMemberName * <li>com.google.ClassName.InnerClass.staticMemberName * </ul> */ static Optional<Integer> typePrefixLength(List<String> nameParts) { TyParseState state = TyParseState.START; Optional<Integer> typeLength = Optional.empty(); for (int i = 0; i < nameParts.size(); i++) { state = state.next(JavaCaseFormat.from(nameParts.get(i))); if (state == TyParseState.REJECT) { break; } if (state.isSingleUnit()) { typeLength = Optional.of(i); } } return typeLength; } /** Case formats used in Java identifiers. */ public enum JavaCaseFormat { UPPERCASE, LOWERCASE, UPPER_CAMEL, LOWER_CAMEL; /** Classifies an identifier's case format. */ static JavaCaseFormat from(String name) {<FILL_FUNCTION_BODY>} } }
Verify.verify(!name.isEmpty()); boolean firstUppercase = false; boolean hasUppercase = false; boolean hasLowercase = false; boolean first = true; for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); if (!Character.isAlphabetic(c)) { continue; } if (first) { firstUppercase = Character.isUpperCase(c); first = false; } hasUppercase |= Character.isUpperCase(c); hasLowercase |= Character.isLowerCase(c); } if (firstUppercase) { return (hasLowercase || name.length() == 1) ? UPPER_CAMEL : UPPERCASE; } else { return hasUppercase ? LOWER_CAMEL : LOWERCASE; }
1,052
239
1,291
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/java/UsageException.java
UsageException
buildMessage
class UsageException extends Exception { private static final Joiner NEWLINE_JOINER = Joiner.on(System.lineSeparator()); private static final String[] DOCS_LINK = { "https://github.com/google/google-java-format", }; private static final String[] USAGE = { "", "Usage: google-java-format [options] file(s)", "", "Options:", " -i, -r, -replace, --replace", " Send formatted output back to files, not stdout.", " -", " Format stdin -> stdout", " --assume-filename, -assume-filename", " File name to use for diagnostics when formatting standard input (default is <stdin>).", " --aosp, -aosp, -a", " Use AOSP style instead of Google Style (4-space indentation).", " --fix-imports-only", " Fix import order and remove any unused imports, but do no other formatting.", " --skip-sorting-imports", " Do not fix the import order. Unused imports will still be removed.", " --skip-removing-unused-imports", " Do not remove unused imports. Imports will still be sorted.", " --skip-reflowing-long-strings", " Do not reflow string literals that exceed the column limit.", " --skip-javadoc-formatting", " Do not reformat javadoc.", " --dry-run, -n", " Prints the paths of the files whose contents would change if the formatter were run" + " normally.", " --set-exit-if-changed", " Return exit code 1 if there are any formatting changes.", " --lines, -lines, --line, -line", " Line range(s) to format, e.g. the first 5 lines are 1:5 (1-based; default is all).", " --offset, -offset", " Character offset to format (0-based; default is all).", " --length, -length", " Character length to format.", " --help, -help, -h", " Print this usage statement.", " --version, -version, -v", " Print the version.", " @<filename>", " Read options and filenames from file.", "", }; private static final String[] ADDITIONAL_USAGE = { "If -i is given with -, the result is sent to stdout.", "The --lines, --offset, and --length flags may be given more than once.", "The --offset and --length flags must be given an equal number of times.", "If --lines, --offset, or --length are given, only one file (or -) may be given." }; UsageException() { super(buildMessage(null)); } UsageException(String message) { super(buildMessage(checkNotNull(message))); } private static String buildMessage(String message) {<FILL_FUNCTION_BODY>} private static void appendLine(StringBuilder builder, String line) { builder.append(line).append(System.lineSeparator()); } private static void appendLines(StringBuilder builder, String[] lines) { NEWLINE_JOINER.appendTo(builder, lines).append(System.lineSeparator()); } }
StringBuilder builder = new StringBuilder(); if (message != null) { builder.append(message).append('\n'); } appendLines(builder, USAGE); appendLines(builder, ADDITIONAL_USAGE); appendLines(builder, new String[] {""}); appendLine(builder, Main.versionString()); appendLines(builder, DOCS_LINK); return builder.toString();
893
112
1,005
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/java/filer/FormattingJavaFileObject.java
FormattingJavaFileObject
openWriter
class FormattingJavaFileObject extends ForwardingJavaFileObject<JavaFileObject> { /** A rough estimate of the average file size: 80 chars per line, 500 lines. */ private static final int DEFAULT_FILE_SIZE = 80 * 500; private final Formatter formatter; private final Messager messager; /** * Create a new {@link FormattingJavaFileObject}. * * @param delegate {@link JavaFileObject} to decorate * @param messager to log messages with. */ FormattingJavaFileObject( JavaFileObject delegate, Formatter formatter, @Nullable Messager messager) { super(checkNotNull(delegate)); this.formatter = checkNotNull(formatter); this.messager = messager; } @Override public Writer openWriter() throws IOException {<FILL_FUNCTION_BODY>} }
final StringBuilder stringBuilder = new StringBuilder(DEFAULT_FILE_SIZE); return new Writer() { @Override public void write(char[] chars, int start, int end) throws IOException { stringBuilder.append(chars, start, end - start); } @Override public void write(String string) throws IOException { stringBuilder.append(string); } @Override public void flush() throws IOException {} @Override public void close() throws IOException { try { formatter.formatSource( CharSource.wrap(stringBuilder), new CharSink() { @Override public Writer openStream() throws IOException { return fileObject.openWriter(); } }); } catch (FormatterException e) { // An exception will happen when the code being formatted has an error. It's better to // log the exception and emit unformatted code so the developer can view the code which // caused a problem. try (Writer writer = fileObject.openWriter()) { writer.append(stringBuilder.toString()); } if (messager != null) { messager.printMessage(Diagnostic.Kind.NOTE, "Error formatting " + getName()); } } } };
233
324
557
<methods>public javax.lang.model.element.Modifier getAccessLevel() ,public javax.tools.JavaFileObject.Kind getKind() ,public javax.lang.model.element.NestingKind getNestingKind() ,public boolean isNameCompatible(java.lang.String, javax.tools.JavaFileObject.Kind) <variables>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/java/javadoc/CharStream.java
CharStream
readAndResetRecorded
class CharStream { String remaining; int toConsume; CharStream(String input) { this.remaining = checkNotNull(input); } boolean tryConsume(String expected) { if (!remaining.startsWith(expected)) { return false; } toConsume = expected.length(); return true; } /* * @param pattern the pattern to search for, which must be anchored to match only at position 0 */ boolean tryConsumeRegex(Pattern pattern) { Matcher matcher = pattern.matcher(remaining); if (!matcher.find()) { return false; } checkArgument(matcher.start() == 0); toConsume = matcher.end(); return true; } String readAndResetRecorded() {<FILL_FUNCTION_BODY>} boolean isExhausted() { return remaining.isEmpty(); } }
String result = remaining.substring(0, toConsume); remaining = remaining.substring(toConsume); toConsume = 0; // TODO(cpovirk): Set this to a bogus value here and in the constructor. return result;
248
66
314
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocFormatter.java
JavadocFormatter
render
class JavadocFormatter { static final int MAX_LINE_LENGTH = 100; /** * Formats the given Javadoc comment, which must start with ∕✱✱ and end with ✱∕. The output will * start and end with the same characters. */ public static String formatJavadoc(String input, int blockIndent) { ImmutableList<Token> tokens; try { tokens = lex(input); } catch (LexException e) { return input; } String result = render(tokens, blockIndent); return makeSingleLineIfPossible(blockIndent, result); } private static String render(List<Token> input, int blockIndent) {<FILL_FUNCTION_BODY>} /* * TODO(cpovirk): Is this really the right location for the standardize* methods? Maybe the lexer * should include them as part of its own postprocessing? Or even the writer could make sense. */ private static Token standardizeBrToken(Token token) { return standardize(token, STANDARD_BR_TOKEN); } private static Token standardizePToken(Token token) { return standardize(token, STANDARD_P_TOKEN); } private static Token standardize(Token token, Token standardToken) { return SIMPLE_TAG_PATTERN.matcher(token.getValue()).matches() ? standardToken : token; } private static final Token STANDARD_BR_TOKEN = new Token(BR_TAG, "<br>"); private static final Token STANDARD_P_TOKEN = new Token(PARAGRAPH_OPEN_TAG, "<p>"); private static final Pattern SIMPLE_TAG_PATTERN = compile("^<\\w+\\s*/?\\s*>", CASE_INSENSITIVE); private static final Pattern ONE_CONTENT_LINE_PATTERN = compile(" */[*][*]\n *[*] (.*)\n *[*]/"); /** * Returns the given string or a one-line version of it (e.g., "∕✱✱ Tests for foos. ✱∕") if it * fits on one line. */ private static String makeSingleLineIfPossible(int blockIndent, String input) { Matcher matcher = ONE_CONTENT_LINE_PATTERN.matcher(input); if (matcher.matches()) { String line = matcher.group(1); if (line.isEmpty()) { return "/** */"; } else if (oneLineJavadoc(line, blockIndent)) { return "/** " + line + " */"; } } return input; } private static boolean oneLineJavadoc(String line, int blockIndent) { int oneLinerContentLength = MAX_LINE_LENGTH - "/** */".length() - blockIndent; if (line.length() > oneLinerContentLength) { return false; } // If the javadoc contains only a tag, use multiple lines to encourage writing a summary // fragment, unless it's /* @hide */. if (line.startsWith("@") && !line.equals("@hide")) { return false; } return true; } private JavadocFormatter() {} }
JavadocWriter output = new JavadocWriter(blockIndent); for (Token token : input) { switch (token.getType()) { case BEGIN_JAVADOC: output.writeBeginJavadoc(); break; case END_JAVADOC: output.writeEndJavadoc(); return output.toString(); case FOOTER_JAVADOC_TAG_START: output.writeFooterJavadocTagStart(token); break; case LIST_OPEN_TAG: output.writeListOpen(token); break; case LIST_CLOSE_TAG: output.writeListClose(token); break; case LIST_ITEM_OPEN_TAG: output.writeListItemOpen(token); break; case HEADER_OPEN_TAG: output.writeHeaderOpen(token); break; case HEADER_CLOSE_TAG: output.writeHeaderClose(token); break; case PARAGRAPH_OPEN_TAG: output.writeParagraphOpen(standardizePToken(token)); break; case BLOCKQUOTE_OPEN_TAG: case BLOCKQUOTE_CLOSE_TAG: output.writeBlockquoteOpenOrClose(token); break; case PRE_OPEN_TAG: output.writePreOpen(token); break; case PRE_CLOSE_TAG: output.writePreClose(token); break; case CODE_OPEN_TAG: output.writeCodeOpen(token); break; case CODE_CLOSE_TAG: output.writeCodeClose(token); break; case TABLE_OPEN_TAG: output.writeTableOpen(token); break; case TABLE_CLOSE_TAG: output.writeTableClose(token); break; case MOE_BEGIN_STRIP_COMMENT: output.requestMoeBeginStripComment(token); break; case MOE_END_STRIP_COMMENT: output.writeMoeEndStripComment(token); break; case HTML_COMMENT: output.writeHtmlComment(token); break; case BR_TAG: output.writeBr(standardizeBrToken(token)); break; case WHITESPACE: output.requestWhitespace(); break; case FORCED_NEWLINE: output.writeLineBreakNoAutoIndent(); break; case LITERAL: output.writeLiteral(token); break; case PARAGRAPH_CLOSE_TAG: case LIST_ITEM_CLOSE_TAG: case OPTIONAL_LINE_BREAK: break; default: throw new AssertionError(token.getType()); } } throw new AssertionError();
886
750
1,636
<no_super_class>
google_google-java-format
google-java-format/core/src/main/java/com/google/googlejavaformat/java/javadoc/Token.java
Token
toString
class Token { /** * Javadoc token type. * * <p>The general idea is that every token that requires special handling (extra line breaks, * indentation, forcing or forbidding whitespace) from {@link JavadocWriter} gets its own type. * But I haven't been super careful about it, so I'd imagine that we could merge or remove some of * these if we wanted. (For example, PARAGRAPH_CLOSE_TAG and LIST_ITEM_CLOSE_TAG could share a * common IGNORABLE token type. But their corresponding OPEN tags exist, so I've kept the CLOSE * tags.) * * <p>Note, though, that tokens of the same type may still have been handled differently by {@link * JavadocLexer} when it created them. For example, LITERAL is used for both plain text and inline * tags, even though the two affect the lexer's state differently. */ enum Type { /** ∕✱✱ */ BEGIN_JAVADOC, /** ✱∕ */ END_JAVADOC, /** The {@code @foo} that begins a block Javadoc tag like {@code @throws}. */ FOOTER_JAVADOC_TAG_START, LIST_OPEN_TAG, LIST_CLOSE_TAG, LIST_ITEM_OPEN_TAG, LIST_ITEM_CLOSE_TAG, HEADER_OPEN_TAG, HEADER_CLOSE_TAG, PARAGRAPH_OPEN_TAG, PARAGRAPH_CLOSE_TAG, // TODO(cpovirk): Support <div> (probably identically to <blockquote>). BLOCKQUOTE_OPEN_TAG, BLOCKQUOTE_CLOSE_TAG, PRE_OPEN_TAG, PRE_CLOSE_TAG, CODE_OPEN_TAG, CODE_CLOSE_TAG, TABLE_OPEN_TAG, TABLE_CLOSE_TAG, /** {@code <!-- MOE:begin_intracomment_strip -->} */ MOE_BEGIN_STRIP_COMMENT, /** {@code <!-- MOE:end_intracomment_strip -->} */ MOE_END_STRIP_COMMENT, HTML_COMMENT, // TODO(cpovirk): Support <hr> (probably a blank line before and after). BR_TAG, /** * Whitespace that is not in a {@code <pre>} or {@code <table>} section. Whitespace includes * leading newlines, asterisks, and tabs and spaces. In the output, it is translated to newlines * (with leading spaces and asterisks) or spaces. */ WHITESPACE, /** * A newline in a {@code <pre>} or {@code <table>} section. We preserve user formatting in these * sections, including newlines. */ FORCED_NEWLINE, /** * Token that permits but does not force a line break. The way that we accomplish this is * somewhat indirect: As far as {@link JavadocWriter} is concerned, this token is meaningless. * But its mere existence prevents {@link JavadocLexer} from joining two {@link #LITERAL} tokens * that would otherwise be adjacent. Since this token is not real whitespace, the writer may end * up writing the literals together with no space between, just as if they'd been joined. * However, if they don't fit together on the line, the writer will write the first one, start a * new line, and write the second. Hence, the token acts as an optional line break. */ OPTIONAL_LINE_BREAK, /** * Anything else: {@code foo}, {@code <b>}, {@code {@code foo}} etc. {@link JavadocLexer} * sometimes creates adjacent literal tokens, which it then merges into a single, larger literal * token before returning its output. * * <p>This also includes whitespace in a {@code <pre>} or {@code <table>} section. We preserve * user formatting in these sections, including arbitrary numbers of spaces. By treating such * whitespace as a literal, we can merge it with adjacent literals, preventing us from * autowrapping inside these sections -- and doing so naively, to boot. The wrapped line would * have no indentation after "* " or, possibly worse, it might begin with an arbitrary amount of * whitespace that didn't fit on the previous line. Of course, by doing this, we're potentially * creating lines of more than 100 characters. But it seems fair to call in the humans to * resolve such problems. */ LITERAL, ; } private final Type type; private final String value; Token(Type type, String value) { this.type = type; this.value = value; } Type getType() { return type; } String getValue() { return value; } int length() { return value.length(); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "\n" + getType() + ": " + getValue();
1,359
21
1,380
<no_super_class>
google_gson
gson/extras/src/main/java/com/google/gson/extras/examples/rawcollections/RawCollectionsExample.java
Event
main
class Event { private String name; private String source; private Event(String name, String source) { this.name = name; this.source = source; } @Override public String toString() { return String.format("(name=%s, source=%s)", name, source); } } @SuppressWarnings({"unchecked", "rawtypes"}) public static void main(String[] args) {<FILL_FUNCTION_BODY>
Gson gson = new Gson(); Collection collection = new ArrayList(); collection.add("hello"); collection.add(5); collection.add(new Event("GREETINGS", "guest")); String json = gson.toJson(collection); System.out.println("Using Gson.toJson() on a raw collection: " + json); JsonArray array = JsonParser.parseString(json).getAsJsonArray(); String message = gson.fromJson(array.get(0), String.class); int number = gson.fromJson(array.get(1), int.class); Event event = gson.fromJson(array.get(2), Event.class); System.out.printf("Using Gson.fromJson() to get: %s, %d, %s", message, number, event);
131
208
339
<no_super_class>
google_gson
gson/extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java
Factory
write
class Factory implements TypeAdapterFactory, InstanceCreator<Object> { private final Map<Type, InstanceCreator<?>> instanceCreators; @SuppressWarnings("ThreadLocalUsage") private final ThreadLocal<Graph> graphThreadLocal = new ThreadLocal<>(); Factory(Map<Type, InstanceCreator<?>> instanceCreators) { this.instanceCreators = instanceCreators; } @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { if (!instanceCreators.containsKey(type.getType())) { return null; } final TypeAdapter<T> typeAdapter = gson.getDelegateAdapter(this, type); final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class); return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException {<FILL_FUNCTION_BODY>} @Override public T read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } /* * Again we have one of two cases: * 1. We've encountered the first known object in this graph. Read * the entire graph in as a map from names to their JsonElements. * Then convert the first JsonElement to its Java object. * 2. We've encountered another graph object in the course of #1. * Read in its name, then deserialize its value from the * JsonElement in our map. We need to do this lazily because we * don't know which TypeAdapter to use until a value is * encountered in the wild. */ String currentName = null; Graph graph = graphThreadLocal.get(); boolean readEntireGraph = false; if (graph == null) { graph = new Graph(new HashMap<Object, Element<?>>()); readEntireGraph = true; // read the entire tree into memory in.beginObject(); while (in.hasNext()) { String name = in.nextName(); if (currentName == null) { currentName = name; } JsonElement element = elementAdapter.read(in); graph.map.put(name, new Element<>(null, name, typeAdapter, element)); } in.endObject(); } else { currentName = in.nextString(); } if (readEntireGraph) { graphThreadLocal.set(graph); } try { @SuppressWarnings("unchecked") // graph.map guarantees consistency between value and T Element<T> element = (Element<T>) graph.map.get(currentName); // now that we know the typeAdapter for this name, go from JsonElement to 'T' if (element.value == null) { element.typeAdapter = typeAdapter; element.read(graph); } return element.value; } finally { if (readEntireGraph) { graphThreadLocal.remove(); } } } }; } /** * Hook for the graph adapter to get a reference to a deserialized value before that value is * fully populated. This is useful to deserialize values that directly or indirectly reference * themselves: we can hand out an instance before read() returns. * * <p>Gson should only ever call this method when we're expecting it to; that is only when we've * called back into Gson to deserialize a tree. */ @Override public Object createInstance(Type type) { Graph graph = graphThreadLocal.get(); if (graph == null || graph.nextCreate == null) { throw new IllegalStateException("Unexpected call to createInstance() for " + type); } InstanceCreator<?> creator = instanceCreators.get(type); Object result = creator.createInstance(type); graph.nextCreate.value = result; graph.nextCreate = null; return result; } }
if (value == null) { out.nullValue(); return; } Graph graph = graphThreadLocal.get(); boolean writeEntireGraph = false; /* * We have one of two cases: * 1. We've encountered the first known object in this graph. Write * out the graph, starting with that object. * 2. We've encountered another graph object in the course of #1. * Just write out this object's name. We'll circle back to writing * out the object's value as a part of #1. */ if (graph == null) { writeEntireGraph = true; graph = new Graph(new IdentityHashMap<Object, Element<?>>()); } @SuppressWarnings("unchecked") // graph.map guarantees consistency between value and T Element<T> element = (Element<T>) graph.map.get(value); if (element == null) { element = new Element<>(value, graph.nextName(), typeAdapter, null); graph.map.put(value, element); graph.queue.add(element); } if (writeEntireGraph) { graphThreadLocal.set(graph); try { out.beginObject(); Element<?> current; while ((current = graph.queue.poll()) != null) { out.name(current.id); current.write(out); } out.endObject(); } finally { graphThreadLocal.remove(); } } else { out.value(element.id); }
1,054
415
1,469
<no_super_class>
google_gson
gson/extras/src/main/java/com/google/gson/interceptors/InterceptorFactory.java
InterceptorFactory
create
class InterceptorFactory implements TypeAdapterFactory { @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {<FILL_FUNCTION_BODY>} static class InterceptorAdapter<T> extends TypeAdapter<T> { private final TypeAdapter<T> delegate; private final JsonPostDeserializer<T> postDeserializer; @SuppressWarnings("unchecked") // ? public InterceptorAdapter(TypeAdapter<T> delegate, Intercept intercept) { try { this.delegate = delegate; this.postDeserializer = intercept.postDeserialize().getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void write(JsonWriter out, T value) throws IOException { delegate.write(out, value); } @Override public T read(JsonReader in) throws IOException { T result = delegate.read(in); postDeserializer.postDeserialize(result); return result; } } }
Intercept intercept = type.getRawType().getAnnotation(Intercept.class); if (intercept == null) { return null; } TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); return new InterceptorAdapter<>(delegate, intercept);
289
80
369
<no_super_class>
google_gson
gson/extras/src/main/java/com/google/gson/typeadapters/PostConstructAdapterFactory.java
PostConstructAdapter
read
class PostConstructAdapter<T> extends TypeAdapter<T> { private final TypeAdapter<T> delegate; private final Method method; public PostConstructAdapter(TypeAdapter<T> delegate, Method method) { this.delegate = delegate; this.method = method; } @Override public T read(JsonReader in) throws IOException {<FILL_FUNCTION_BODY>} @Override public void write(JsonWriter out, T value) throws IOException { delegate.write(out, value); } }
T result = delegate.read(in); if (result != null) { try { method.invoke(result); } catch (IllegalAccessException e) { throw new AssertionError(e); } catch (InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } throw new RuntimeException(e.getCause()); } } return result;
140
125
265
<no_super_class>
google_gson
gson/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java
RuntimeTypeAdapterFactory
write
class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory { private final Class<?> baseType; private final String typeFieldName; private final Map<String, Class<?>> labelToSubtype = new LinkedHashMap<>(); private final Map<Class<?>, String> subtypeToLabel = new LinkedHashMap<>(); private final boolean maintainType; private boolean recognizeSubtypes; private RuntimeTypeAdapterFactory(Class<?> baseType, String typeFieldName, boolean maintainType) { if (typeFieldName == null || baseType == null) { throw new NullPointerException(); } this.baseType = baseType; this.typeFieldName = typeFieldName; this.maintainType = maintainType; } /** * Creates a new runtime type adapter using for {@code baseType} using {@code typeFieldName} as * the type field name. Type field names are case sensitive. * * @param maintainType true if the type field should be included in deserialized objects */ public static <T> RuntimeTypeAdapterFactory<T> of( Class<T> baseType, String typeFieldName, boolean maintainType) { return new RuntimeTypeAdapterFactory<>(baseType, typeFieldName, maintainType); } /** * Creates a new runtime type adapter using for {@code baseType} using {@code typeFieldName} as * the type field name. Type field names are case sensitive. */ public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType, String typeFieldName) { return new RuntimeTypeAdapterFactory<>(baseType, typeFieldName, false); } /** * Creates a new runtime type adapter for {@code baseType} using {@code "type"} as the type field * name. */ public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType) { return new RuntimeTypeAdapterFactory<>(baseType, "type", false); } /** * Ensures that this factory will handle not just the given {@code baseType}, but any subtype of * that type. */ @CanIgnoreReturnValue public RuntimeTypeAdapterFactory<T> recognizeSubtypes() { this.recognizeSubtypes = true; return this; } /** * Registers {@code type} identified by {@code label}. Labels are case sensitive. * * @throws IllegalArgumentException if either {@code type} or {@code label} have already been * registered on this type adapter. */ @CanIgnoreReturnValue public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type, String label) { if (type == null || label == null) { throw new NullPointerException(); } if (subtypeToLabel.containsKey(type) || labelToSubtype.containsKey(label)) { throw new IllegalArgumentException("types and labels must be unique"); } labelToSubtype.put(label, type); subtypeToLabel.put(type, label); return this; } /** * Registers {@code type} identified by its {@link Class#getSimpleName simple name}. Labels are * case sensitive. * * @throws IllegalArgumentException if either {@code type} or its simple name have already been * registered on this type adapter. */ @CanIgnoreReturnValue public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type) { return registerSubtype(type, type.getSimpleName()); } @Override public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (type == null) { return null; } Class<?> rawType = type.getRawType(); boolean handle = recognizeSubtypes ? baseType.isAssignableFrom(rawType) : baseType.equals(rawType); if (!handle) { return null; } final TypeAdapter<JsonElement> jsonElementAdapter = gson.getAdapter(JsonElement.class); final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<>(); final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<>(); for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) { TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue())); labelToDelegate.put(entry.getKey(), delegate); subtypeToDelegate.put(entry.getValue(), delegate); } return new TypeAdapter<R>() { @Override public R read(JsonReader in) throws IOException { JsonElement jsonElement = jsonElementAdapter.read(in); JsonElement labelJsonElement; if (maintainType) { labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName); } else { labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName); } if (labelJsonElement == null) { throw new JsonParseException( "cannot deserialize " + baseType + " because it does not define a field named " + typeFieldName); } String label = labelJsonElement.getAsString(); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label); if (delegate == null) { throw new JsonParseException( "cannot deserialize " + baseType + " subtype named " + label + "; did you forget to register a subtype?"); } return delegate.fromJsonTree(jsonElement); } @Override public void write(JsonWriter out, R value) throws IOException {<FILL_FUNCTION_BODY>} }.nullSafe(); } }
Class<?> srcType = value.getClass(); String label = subtypeToLabel.get(srcType); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType); if (delegate == null) { throw new JsonParseException( "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?"); } JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); if (maintainType) { jsonElementAdapter.write(out, jsonObject); return; } JsonObject clone = new JsonObject(); if (jsonObject.has(typeFieldName)) { throw new JsonParseException( "cannot serialize " + srcType.getName() + " because it already defines a field named " + typeFieldName); } clone.add(typeFieldName, new JsonPrimitive(label)); for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue()); } jsonElementAdapter.write(out, clone);
1,500
316
1,816
<no_super_class>
google_gson
gson/gson/src/main/java/com/google/gson/JsonParser.java
JsonParser
parseReader
class JsonParser { /** * @deprecated No need to instantiate this class, use the static methods instead. */ @Deprecated public JsonParser() {} /** * Parses the specified JSON string into a parse tree. An exception is thrown if the JSON string * has multiple top-level JSON elements, or if there is trailing data. * * <p>The JSON string is parsed in {@linkplain JsonReader#setStrictness(Strictness) lenient mode}. * * @param json JSON text * @return a parse tree of {@link JsonElement}s corresponding to the specified JSON * @throws JsonParseException if the specified text is not valid JSON * @since 2.8.6 */ public static JsonElement parseString(String json) throws JsonSyntaxException { return parseReader(new StringReader(json)); } /** * Parses the complete JSON string provided by the reader into a parse tree. An exception is * thrown if the JSON string has multiple top-level JSON elements, or if there is trailing data. * * <p>The JSON data is parsed in {@linkplain JsonReader#setStrictness(Strictness) lenient mode}. * * @param reader JSON text * @return a parse tree of {@link JsonElement}s corresponding to the specified JSON * @throws JsonParseException if there is an IOException or if the specified text is not valid * JSON * @since 2.8.6 */ public static JsonElement parseReader(Reader reader) throws JsonIOException, JsonSyntaxException { try { JsonReader jsonReader = new JsonReader(reader); JsonElement element = parseReader(jsonReader); if (!element.isJsonNull() && jsonReader.peek() != JsonToken.END_DOCUMENT) { throw new JsonSyntaxException("Did not consume the entire document."); } return element; } catch (MalformedJsonException e) { throw new JsonSyntaxException(e); } catch (IOException e) { throw new JsonIOException(e); } catch (NumberFormatException e) { throw new JsonSyntaxException(e); } } /** * Returns the next value from the JSON stream as a parse tree. Unlike the other {@code parse} * methods, no exception is thrown if the JSON data has multiple top-level JSON elements, or if * there is trailing data. * * <p>If the {@linkplain JsonReader#getStrictness() strictness of the reader} is {@link * Strictness#STRICT}, that strictness will be used for parsing. Otherwise the strictness will be * temporarily changed to {@link Strictness#LENIENT} and will be restored once this method * returns. * * @throws JsonParseException if there is an IOException or if the specified text is not valid * JSON * @since 2.8.6 */ public static JsonElement parseReader(JsonReader reader) throws JsonIOException, JsonSyntaxException {<FILL_FUNCTION_BODY>} /** * @deprecated Use {@link JsonParser#parseString} */ @Deprecated @InlineMe(replacement = "JsonParser.parseString(json)", imports = "com.google.gson.JsonParser") public JsonElement parse(String json) throws JsonSyntaxException { return parseString(json); } /** * @deprecated Use {@link JsonParser#parseReader(Reader)} */ @Deprecated @InlineMe(replacement = "JsonParser.parseReader(json)", imports = "com.google.gson.JsonParser") public JsonElement parse(Reader json) throws JsonIOException, JsonSyntaxException { return parseReader(json); } /** * @deprecated Use {@link JsonParser#parseReader(JsonReader)} */ @Deprecated @InlineMe(replacement = "JsonParser.parseReader(json)", imports = "com.google.gson.JsonParser") public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException { return parseReader(json); } }
Strictness strictness = reader.getStrictness(); if (strictness == Strictness.LEGACY_STRICT) { // For backward compatibility change to LENIENT if reader has default strictness LEGACY_STRICT reader.setStrictness(Strictness.LENIENT); } try { return Streams.parse(reader); } catch (StackOverflowError e) { throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e); } catch (OutOfMemoryError e) { throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e); } finally { reader.setStrictness(strictness); }
1,031
190
1,221
<no_super_class>
google_gson
gson/gson/src/main/java/com/google/gson/JsonStreamParser.java
JsonStreamParser
next
class JsonStreamParser implements Iterator<JsonElement> { private final JsonReader parser; private final Object lock; /** * @param json The string containing JSON elements concatenated to each other. * @since 1.4 */ public JsonStreamParser(String json) { this(new StringReader(json)); } /** * @param reader The data stream containing JSON elements concatenated to each other. * @since 1.4 */ public JsonStreamParser(Reader reader) { parser = new JsonReader(reader); parser.setStrictness(Strictness.LENIENT); lock = new Object(); } /** * Returns the next available {@link JsonElement} on the reader. Throws a {@link * NoSuchElementException} if no element is available. * * @return the next available {@code JsonElement} on the reader. * @throws JsonParseException if the incoming stream is malformed JSON. * @throws NoSuchElementException if no {@code JsonElement} is available. * @since 1.4 */ @Override public JsonElement next() throws JsonParseException {<FILL_FUNCTION_BODY>} /** * Returns true if a {@link JsonElement} is available on the input for consumption * * @return true if a {@link JsonElement} is available on the input, false otherwise * @throws JsonParseException if the incoming stream is malformed JSON. * @since 1.4 */ @Override public boolean hasNext() { synchronized (lock) { try { return parser.peek() != JsonToken.END_DOCUMENT; } catch (MalformedJsonException e) { throw new JsonSyntaxException(e); } catch (IOException e) { throw new JsonIOException(e); } } } /** * This optional {@link Iterator} method is not relevant for stream parsing and hence is not * implemented. * * @since 1.4 */ @Override public void remove() { throw new UnsupportedOperationException(); } }
if (!hasNext()) { throw new NoSuchElementException(); } try { return Streams.parse(parser); } catch (StackOverflowError e) { throw new JsonParseException("Failed parsing JSON source to Json", e); } catch (OutOfMemoryError e) { throw new JsonParseException("Failed parsing JSON source to Json", e); }
542
101
643
<no_super_class>
google_gson
gson/gson/src/main/java/com/google/gson/TypeAdapter.java
TypeAdapter
nullSafe
class TypeAdapter<T> { public TypeAdapter() {} /** * Writes one JSON value (an array, object, string, number, boolean or null) for {@code value}. * * @param value the Java object to write. May be null. */ public abstract void write(JsonWriter out, T value) throws IOException; /** * Converts {@code value} to a JSON document and writes it to {@code out}. * * <p>A {@link JsonWriter} with default configuration is used for writing the JSON data. To * customize this behavior, create a {@link JsonWriter}, configure it and then use {@link * #write(JsonWriter, Object)} instead. * * @param value the Java object to convert. May be {@code null}. * @since 2.2 */ public final void toJson(Writer out, T value) throws IOException { JsonWriter writer = new JsonWriter(out); write(writer, value); } /** * Converts {@code value} to a JSON document. * * <p>A {@link JsonWriter} with default configuration is used for writing the JSON data. To * customize this behavior, create a {@link JsonWriter}, configure it and then use {@link * #write(JsonWriter, Object)} instead. * * @throws JsonIOException wrapping {@code IOException}s thrown by {@link #write(JsonWriter, * Object)} * @param value the Java object to convert. May be {@code null}. * @since 2.2 */ public final String toJson(T value) { StringWriter stringWriter = new StringWriter(); try { toJson(stringWriter, value); } catch (IOException e) { throw new JsonIOException(e); } return stringWriter.toString(); } /** * Converts {@code value} to a JSON tree. * * @param value the Java object to convert. May be {@code null}. * @return the converted JSON tree. May be {@link JsonNull}. * @throws JsonIOException wrapping {@code IOException}s thrown by {@link #write(JsonWriter, * Object)} * @since 2.2 */ public final JsonElement toJsonTree(T value) { try { JsonTreeWriter jsonWriter = new JsonTreeWriter(); write(jsonWriter, value); return jsonWriter.get(); } catch (IOException e) { throw new JsonIOException(e); } } /** * Reads one JSON value (an array, object, string, number, boolean or null) and converts it to a * Java object. Returns the converted object. * * @return the converted Java object. May be {@code null}. */ public abstract T read(JsonReader in) throws IOException; /** * Converts the JSON document in {@code in} to a Java object. * * <p>A {@link JsonReader} with default configuration (that is with {@link * Strictness#LEGACY_STRICT} as strictness) is used for reading the JSON data. To customize this * behavior, create a {@link JsonReader}, configure it and then use {@link #read(JsonReader)} * instead. * * <p>No exception is thrown if the JSON data has multiple top-level JSON elements, or if there is * trailing data. * * @return the converted Java object. May be {@code null}. * @since 2.2 */ public final T fromJson(Reader in) throws IOException { JsonReader reader = new JsonReader(in); return read(reader); } /** * Converts the JSON document in {@code json} to a Java object. * * <p>A {@link JsonReader} with default configuration (that is with {@link * Strictness#LEGACY_STRICT} as strictness) is used for reading the JSON data. To customize this * behavior, create a {@link JsonReader}, configure it and then use {@link #read(JsonReader)} * instead. * * <p>No exception is thrown if the JSON data has multiple top-level JSON elements, or if there is * trailing data. * * @return the converted Java object. May be {@code null}. * @since 2.2 */ public final T fromJson(String json) throws IOException { return fromJson(new StringReader(json)); } /** * Converts {@code jsonTree} to a Java object. * * @param jsonTree the JSON element to convert. May be {@link JsonNull}. * @return the converted Java object. May be {@code null}. * @throws JsonIOException wrapping {@code IOException}s thrown by {@link #read(JsonReader)} * @since 2.2 */ public final T fromJsonTree(JsonElement jsonTree) { try { JsonReader jsonReader = new JsonTreeReader(jsonTree); return read(jsonReader); } catch (IOException e) { throw new JsonIOException(e); } } /** * This wrapper method is used to make a type adapter null tolerant. In general, a type adapter is * required to handle nulls in write and read methods. Here is how this is typically done:<br> * * <pre>{@code * Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class, * new TypeAdapter<Foo>() { * public Foo read(JsonReader in) throws IOException { * if (in.peek() == JsonToken.NULL) { * in.nextNull(); * return null; * } * // read a Foo from in and return it * } * public void write(JsonWriter out, Foo src) throws IOException { * if (src == null) { * out.nullValue(); * return; * } * // write src as JSON to out * } * }).create(); * }</pre> * * You can avoid this boilerplate handling of nulls by wrapping your type adapter with this * method. Here is how we will rewrite the above example: * * <pre>{@code * Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class, * new TypeAdapter<Foo>() { * public Foo read(JsonReader in) throws IOException { * // read a Foo from in and return it * } * public void write(JsonWriter out, Foo src) throws IOException { * // write src as JSON to out * } * }.nullSafe()).create(); * }</pre> * * Note that we didn't need to check for nulls in our type adapter after we used nullSafe. */ public final TypeAdapter<T> nullSafe() {<FILL_FUNCTION_BODY>} }
return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { if (value == null) { out.nullValue(); } else { TypeAdapter.this.write(out, value); } } @Override public T read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } return TypeAdapter.this.read(reader); } };
1,775
141
1,916
<no_super_class>
google_gson
gson/gson/src/main/java/com/google/gson/internal/$Gson$Preconditions.java
$Gson$Preconditions
checkNotNull
class $Gson$Preconditions { private $Gson$Preconditions() { throw new UnsupportedOperationException(); } /** * @deprecated This is an internal Gson method. Use {@link Objects#requireNonNull(Object)} * instead. */ // Only deprecated for now because external projects might be using this by accident @Deprecated public static <T> T checkNotNull(T obj) {<FILL_FUNCTION_BODY>} public static void checkArgument(boolean condition) { if (!condition) { throw new IllegalArgumentException(); } } }
if (obj == null) { throw new NullPointerException(); } return obj;
154
28
182
google_gson
gson/gson/src/main/java/com/google/gson/internal/Excluder.java
Excluder
create
class Excluder implements TypeAdapterFactory, Cloneable { private static final double IGNORE_VERSIONS = -1.0d; public static final Excluder DEFAULT = new Excluder(); private double version = IGNORE_VERSIONS; private int modifiers = Modifier.TRANSIENT | Modifier.STATIC; private boolean serializeInnerClasses = true; private boolean requireExpose; private List<ExclusionStrategy> serializationStrategies = Collections.emptyList(); private List<ExclusionStrategy> deserializationStrategies = Collections.emptyList(); @Override protected Excluder clone() { try { return (Excluder) super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(e); } } public Excluder withVersion(double ignoreVersionsAfter) { Excluder result = clone(); result.version = ignoreVersionsAfter; return result; } public Excluder withModifiers(int... modifiers) { Excluder result = clone(); result.modifiers = 0; for (int modifier : modifiers) { result.modifiers |= modifier; } return result; } public Excluder disableInnerClassSerialization() { Excluder result = clone(); result.serializeInnerClasses = false; return result; } public Excluder excludeFieldsWithoutExposeAnnotation() { Excluder result = clone(); result.requireExpose = true; return result; } public Excluder withExclusionStrategy( ExclusionStrategy exclusionStrategy, boolean serialization, boolean deserialization) { Excluder result = clone(); if (serialization) { result.serializationStrategies = new ArrayList<>(serializationStrategies); result.serializationStrategies.add(exclusionStrategy); } if (deserialization) { result.deserializationStrategies = new ArrayList<>(deserializationStrategies); result.deserializationStrategies.add(exclusionStrategy); } return result; } @Override public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {<FILL_FUNCTION_BODY>} public boolean excludeField(Field field, boolean serialize) { if ((modifiers & field.getModifiers()) != 0) { return true; } if (version != Excluder.IGNORE_VERSIONS && !isValidVersion(field.getAnnotation(Since.class), field.getAnnotation(Until.class))) { return true; } if (field.isSynthetic()) { return true; } if (requireExpose) { Expose annotation = field.getAnnotation(Expose.class); if (annotation == null || (serialize ? !annotation.serialize() : !annotation.deserialize())) { return true; } } if (excludeClass(field.getType(), serialize)) { return true; } List<ExclusionStrategy> list = serialize ? serializationStrategies : deserializationStrategies; if (!list.isEmpty()) { FieldAttributes fieldAttributes = new FieldAttributes(field); for (ExclusionStrategy exclusionStrategy : list) { if (exclusionStrategy.shouldSkipField(fieldAttributes)) { return true; } } } return false; } // public for unit tests; can otherwise be private public boolean excludeClass(Class<?> clazz, boolean serialize) { if (version != Excluder.IGNORE_VERSIONS && !isValidVersion(clazz.getAnnotation(Since.class), clazz.getAnnotation(Until.class))) { return true; } if (!serializeInnerClasses && isInnerClass(clazz)) { return true; } /* * Exclude anonymous and local classes because they can have synthetic fields capturing enclosing * values which makes serialization and deserialization unreliable. * Don't exclude anonymous enum subclasses because enum types have a built-in adapter. * * Exclude only for deserialization; for serialization allow because custom adapter might be * used; if no custom adapter exists reflection-based adapter otherwise excludes value. * * Cannot allow deserialization reliably here because some custom adapters like Collection adapter * fall back to creating instances using Unsafe, which would likely lead to runtime exceptions * for anonymous and local classes if they capture values. */ if (!serialize && !Enum.class.isAssignableFrom(clazz) && ReflectionHelper.isAnonymousOrNonStaticLocal(clazz)) { return true; } List<ExclusionStrategy> list = serialize ? serializationStrategies : deserializationStrategies; for (ExclusionStrategy exclusionStrategy : list) { if (exclusionStrategy.shouldSkipClass(clazz)) { return true; } } return false; } private static boolean isInnerClass(Class<?> clazz) { return clazz.isMemberClass() && !ReflectionHelper.isStatic(clazz); } private boolean isValidVersion(Since since, Until until) { return isValidSince(since) && isValidUntil(until); } private boolean isValidSince(Since annotation) { if (annotation != null) { double annotationVersion = annotation.value(); return version >= annotationVersion; } return true; } private boolean isValidUntil(Until annotation) { if (annotation != null) { double annotationVersion = annotation.value(); return version < annotationVersion; } return true; } }
Class<?> rawType = type.getRawType(); final boolean skipSerialize = excludeClass(rawType, true); final boolean skipDeserialize = excludeClass(rawType, false); if (!skipSerialize && !skipDeserialize) { return null; } return new TypeAdapter<T>() { /** * The delegate is lazily created because it may not be needed, and creating it may fail. * Field has to be {@code volatile} because {@link Gson} guarantees to be thread-safe. */ private volatile TypeAdapter<T> delegate; @Override public T read(JsonReader in) throws IOException { if (skipDeserialize) { in.skipValue(); return null; } return delegate().read(in); } @Override public void write(JsonWriter out, T value) throws IOException { if (skipSerialize) { out.nullValue(); return; } delegate().write(out, value); } private TypeAdapter<T> delegate() { // A race might lead to `delegate` being assigned by multiple threads but the last // assignment will stick TypeAdapter<T> d = delegate; return d != null ? d : (delegate = gson.getDelegateAdapter(Excluder.this, type)); } };
1,486
350
1,836
<no_super_class>
google_gson
gson/gson/src/main/java/com/google/gson/internal/JavaVersion.java
JavaVersion
extractBeginningInt
class JavaVersion { // Oracle defines naming conventions at // http://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html // However, many alternate implementations differ. For example, Debian used 9-debian as the // version string private static final int majorJavaVersion = determineMajorJavaVersion(); private static int determineMajorJavaVersion() { String javaVersion = System.getProperty("java.version"); return parseMajorJavaVersion(javaVersion); } // Visible for testing only static int parseMajorJavaVersion(String javaVersion) { int version = parseDotted(javaVersion); if (version == -1) { version = extractBeginningInt(javaVersion); } if (version == -1) { return 6; // Choose minimum supported JDK version as default } return version; } // Parses both legacy 1.8 style and newer 9.0.4 style private static int parseDotted(String javaVersion) { try { String[] parts = javaVersion.split("[._]", 3); int firstVer = Integer.parseInt(parts[0]); if (firstVer == 1 && parts.length > 1) { return Integer.parseInt(parts[1]); } else { return firstVer; } } catch (NumberFormatException e) { return -1; } } private static int extractBeginningInt(String javaVersion) {<FILL_FUNCTION_BODY>} /** * Gets the major Java version * * @return the major Java version, i.e. '8' for Java 1.8, '9' for Java 9 etc. */ public static int getMajorJavaVersion() { return majorJavaVersion; } /** * Gets a boolean value depending if the application is running on Java 9 or later * * @return {@code true} if the application is running on Java 9 or later; and {@code false} * otherwise. */ public static boolean isJava9OrLater() { return majorJavaVersion >= 9; } private JavaVersion() {} }
try { StringBuilder num = new StringBuilder(); for (int i = 0; i < javaVersion.length(); ++i) { char c = javaVersion.charAt(i); if (Character.isDigit(c)) { num.append(c); } else { break; } } return Integer.parseInt(num.toString()); } catch (NumberFormatException e) { return -1; }
571
118
689
<no_super_class>
google_gson
gson/gson/src/main/java/com/google/gson/internal/LazilyParsedNumber.java
LazilyParsedNumber
equals
class LazilyParsedNumber extends Number { private final String value; /** * @param value must not be null */ public LazilyParsedNumber(String value) { this.value = value; } private BigDecimal asBigDecimal() { return NumberLimits.parseBigDecimal(value); } @Override public int intValue() { try { return Integer.parseInt(value); } catch (NumberFormatException e) { try { return (int) Long.parseLong(value); } catch (NumberFormatException nfe) { return asBigDecimal().intValue(); } } } @Override public long longValue() { try { return Long.parseLong(value); } catch (NumberFormatException e) { return asBigDecimal().longValue(); } } @Override public float floatValue() { return Float.parseFloat(value); } @Override public double doubleValue() { return Double.parseDouble(value); } @Override public String toString() { return value; } /** * If somebody is unlucky enough to have to serialize one of these, serialize it as a BigDecimal * so that they won't need Gson on the other side to deserialize it. */ private Object writeReplace() throws ObjectStreamException { return asBigDecimal(); } private void readObject(ObjectInputStream in) throws IOException { // Don't permit directly deserializing this class; writeReplace() should have written a // replacement throw new InvalidObjectException("Deserialization is unsupported"); } @Override public int hashCode() { return value.hashCode(); } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} }
if (this == obj) { return true; } if (obj instanceof LazilyParsedNumber) { LazilyParsedNumber other = (LazilyParsedNumber) obj; return value.equals(other.value); } return false;
498
76
574
<methods>public void <init>() ,public byte byteValue() ,public abstract double doubleValue() ,public abstract float floatValue() ,public abstract int intValue() ,public abstract long longValue() ,public short shortValue() <variables>private static final long serialVersionUID
google_gson
gson/gson/src/main/java/com/google/gson/internal/LinkedTreeMap.java
EntrySet
remove
class EntrySet extends AbstractSet<Entry<K, V>> { @Override public int size() { return size; } @Override public Iterator<Entry<K, V>> iterator() { return new LinkedTreeMapIterator<Entry<K, V>>() { @Override public Entry<K, V> next() { return nextNode(); } }; } @Override public boolean contains(Object o) { return o instanceof Entry && findByEntry((Entry<?, ?>) o) != null; } @Override public boolean remove(Object o) {<FILL_FUNCTION_BODY>} @Override public void clear() { LinkedTreeMap.this.clear(); } }
if (!(o instanceof Entry)) { return false; } Node<K, V> node = findByEntry((Entry<?, ?>) o); if (node == null) { return false; } removeInternal(node, true); return true;
199
75
274
<methods>public void clear() ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public abstract Set<Entry<K,V>> entrySet() ,public boolean equals(java.lang.Object) ,public V get(java.lang.Object) ,public int hashCode() ,public boolean isEmpty() ,public Set<K> keySet() ,public V put(K, V) ,public void putAll(Map<? extends K,? extends V>) ,public V remove(java.lang.Object) ,public int size() ,public java.lang.String toString() ,public Collection<V> values() <variables>transient Set<K> keySet,transient Collection<V> values
google_gson
gson/gson/src/main/java/com/google/gson/internal/NonNullElementWrapperList.java
NonNullElementWrapperList
nonNull
class NonNullElementWrapperList<E> extends AbstractList<E> implements RandomAccess { // Explicitly specify ArrayList as type to guarantee that delegate implements RandomAccess private final ArrayList<E> delegate; @SuppressWarnings("NonApiType") public NonNullElementWrapperList(ArrayList<E> delegate) { this.delegate = Objects.requireNonNull(delegate); } @Override public E get(int index) { return delegate.get(index); } @Override public int size() { return delegate.size(); } private E nonNull(E element) {<FILL_FUNCTION_BODY>} @Override public E set(int index, E element) { return delegate.set(index, nonNull(element)); } @Override public void add(int index, E element) { delegate.add(index, nonNull(element)); } @Override public E remove(int index) { return delegate.remove(index); } /* The following methods are overridden because their default implementation is inefficient */ @Override public void clear() { delegate.clear(); } @SuppressWarnings("UngroupedOverloads") // this is intentionally ungrouped, see comment above @Override public boolean remove(Object o) { return delegate.remove(o); } @Override public boolean removeAll(Collection<?> c) { return delegate.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return delegate.retainAll(c); } @Override public boolean contains(Object o) { return delegate.contains(o); } @Override public int indexOf(Object o) { return delegate.indexOf(o); } @Override public int lastIndexOf(Object o) { return delegate.lastIndexOf(o); } @Override public Object[] toArray() { return delegate.toArray(); } @Override public <T> T[] toArray(T[] a) { return delegate.toArray(a); } @Override public boolean equals(Object o) { return delegate.equals(o); } @Override public int hashCode() { return delegate.hashCode(); } // TODO: Once Gson targets Java 8 also override List.sort }
if (element == null) { throw new NullPointerException("Element must be non-null"); } return element;
645
35
680
<methods>public boolean add(E) ,public void add(int, E) ,public boolean addAll(int, Collection<? extends E>) ,public void clear() ,public boolean equals(java.lang.Object) ,public abstract E get(int) ,public int hashCode() ,public int indexOf(java.lang.Object) ,public Iterator<E> iterator() ,public int lastIndexOf(java.lang.Object) ,public ListIterator<E> listIterator() ,public ListIterator<E> listIterator(int) ,public E remove(int) ,public E set(int, E) ,public List<E> subList(int, int) <variables>protected transient int modCount
google_gson
gson/gson/src/main/java/com/google/gson/internal/NumberLimits.java
NumberLimits
parseBigDecimal
class NumberLimits { private NumberLimits() {} private static final int MAX_NUMBER_STRING_LENGTH = 10_000; private static void checkNumberStringLength(String s) { if (s.length() > MAX_NUMBER_STRING_LENGTH) { throw new NumberFormatException("Number string too large: " + s.substring(0, 30) + "..."); } } public static BigDecimal parseBigDecimal(String s) throws NumberFormatException {<FILL_FUNCTION_BODY>} public static BigInteger parseBigInteger(String s) throws NumberFormatException { checkNumberStringLength(s); return new BigInteger(s); } }
checkNumberStringLength(s); BigDecimal decimal = new BigDecimal(s); // Cast to long to avoid issues with abs when value is Integer.MIN_VALUE if (Math.abs((long) decimal.scale()) >= 10_000) { throw new NumberFormatException("Number has unsupported scale: " + s); } return decimal;
184
95
279
<no_super_class>
google_gson
gson/gson/src/main/java/com/google/gson/internal/PreJava9DateFormatProvider.java
PreJava9DateFormatProvider
getDatePartOfDateTimePattern
class PreJava9DateFormatProvider { private PreJava9DateFormatProvider() {} /** * Returns the same DateFormat as {@code DateFormat.getDateTimeInstance(dateStyle, timeStyle, * Locale.US)} in Java 8 or below. */ public static DateFormat getUsDateTimeFormat(int dateStyle, int timeStyle) { String pattern = getDatePartOfDateTimePattern(dateStyle) + " " + getTimePartOfDateTimePattern(timeStyle); return new SimpleDateFormat(pattern, Locale.US); } private static String getDatePartOfDateTimePattern(int dateStyle) {<FILL_FUNCTION_BODY>} private static String getTimePartOfDateTimePattern(int timeStyle) { switch (timeStyle) { case DateFormat.SHORT: return "h:mm a"; case DateFormat.MEDIUM: return "h:mm:ss a"; case DateFormat.FULL: case DateFormat.LONG: return "h:mm:ss a z"; default: throw new IllegalArgumentException("Unknown DateFormat style: " + timeStyle); } } }
switch (dateStyle) { case DateFormat.SHORT: return "M/d/yy"; case DateFormat.MEDIUM: return "MMM d, yyyy"; case DateFormat.LONG: return "MMMM d, yyyy"; case DateFormat.FULL: return "EEEE, MMMM d, yyyy"; default: throw new IllegalArgumentException("Unknown DateFormat style: " + dateStyle); }
290
122
412
<no_super_class>
google_gson
gson/gson/src/main/java/com/google/gson/internal/Primitives.java
Primitives
wrap
class Primitives { private Primitives() {} /** Returns true if this type is a primitive. */ public static boolean isPrimitive(Type type) { return type instanceof Class<?> && ((Class<?>) type).isPrimitive(); } /** * Returns {@code true} if {@code type} is one of the nine primitive-wrapper types, such as {@link * Integer}. * * @see Class#isPrimitive */ public static boolean isWrapperType(Type type) { return type == Integer.class || type == Float.class || type == Byte.class || type == Double.class || type == Long.class || type == Character.class || type == Boolean.class || type == Short.class || type == Void.class; } /** * Returns the corresponding wrapper type of {@code type} if it is a primitive type; otherwise * returns {@code type} itself. Idempotent. * * <pre> * wrap(int.class) == Integer.class * wrap(Integer.class) == Integer.class * wrap(String.class) == String.class * </pre> */ @SuppressWarnings({"unchecked", "MissingBraces"}) public static <T> Class<T> wrap(Class<T> type) {<FILL_FUNCTION_BODY>} /** * Returns the corresponding primitive type of {@code type} if it is a wrapper type; otherwise * returns {@code type} itself. Idempotent. * * <pre> * unwrap(Integer.class) == int.class * unwrap(int.class) == int.class * unwrap(String.class) == String.class * </pre> */ @SuppressWarnings({"unchecked", "MissingBraces"}) public static <T> Class<T> unwrap(Class<T> type) { if (type == Integer.class) return (Class<T>) int.class; if (type == Float.class) return (Class<T>) float.class; if (type == Byte.class) return (Class<T>) byte.class; if (type == Double.class) return (Class<T>) double.class; if (type == Long.class) return (Class<T>) long.class; if (type == Character.class) return (Class<T>) char.class; if (type == Boolean.class) return (Class<T>) boolean.class; if (type == Short.class) return (Class<T>) short.class; if (type == Void.class) return (Class<T>) void.class; return type; } }
if (type == int.class) return (Class<T>) Integer.class; if (type == float.class) return (Class<T>) Float.class; if (type == byte.class) return (Class<T>) Byte.class; if (type == double.class) return (Class<T>) Double.class; if (type == long.class) return (Class<T>) Long.class; if (type == char.class) return (Class<T>) Character.class; if (type == boolean.class) return (Class<T>) Boolean.class; if (type == short.class) return (Class<T>) Short.class; if (type == void.class) return (Class<T>) Void.class; return type;
704
199
903
<no_super_class>
google_gson
gson/gson/src/main/java/com/google/gson/internal/ReflectionAccessFilterHelper.java
ReflectionAccessFilterHelper
getFilterResult
class ReflectionAccessFilterHelper { private ReflectionAccessFilterHelper() {} // Platform type detection is based on Moshi's Util.isPlatformType(Class) // See // https://github.com/square/moshi/blob/3c108919ee1cce88a433ffda04eeeddc0341eae7/moshi/src/main/java/com/squareup/moshi/internal/Util.java#L141 public static boolean isJavaType(Class<?> c) { return isJavaType(c.getName()); } private static boolean isJavaType(String className) { return className.startsWith("java.") || className.startsWith("javax."); } public static boolean isAndroidType(Class<?> c) { return isAndroidType(c.getName()); } private static boolean isAndroidType(String className) { return className.startsWith("android.") || className.startsWith("androidx.") || isJavaType(className); } public static boolean isAnyPlatformType(Class<?> c) { String className = c.getName(); return isAndroidType(className) // Covers Android and Java || className.startsWith("kotlin.") || className.startsWith("kotlinx.") || className.startsWith("scala."); } /** * Gets the result of applying all filters until the first one returns a result other than {@link * FilterResult#INDECISIVE}, or {@link FilterResult#ALLOW} if the list of filters is empty or all * returned {@code INDECISIVE}. */ public static FilterResult getFilterResult( List<ReflectionAccessFilter> reflectionFilters, Class<?> c) {<FILL_FUNCTION_BODY>} /** See {@link AccessibleObject#canAccess(Object)} (Java >= 9) */ public static boolean canAccess(AccessibleObject accessibleObject, Object object) { return AccessChecker.INSTANCE.canAccess(accessibleObject, object); } private abstract static class AccessChecker { public static final AccessChecker INSTANCE; static { AccessChecker accessChecker = null; // TODO: Ideally should use Multi-Release JAR for this version specific code if (JavaVersion.isJava9OrLater()) { try { final Method canAccessMethod = AccessibleObject.class.getDeclaredMethod("canAccess", Object.class); accessChecker = new AccessChecker() { @Override public boolean canAccess(AccessibleObject accessibleObject, Object object) { try { return (Boolean) canAccessMethod.invoke(accessibleObject, object); } catch (Exception e) { throw new RuntimeException("Failed invoking canAccess", e); } } }; } catch (NoSuchMethodException ignored) { // OK: will assume everything is accessible } } if (accessChecker == null) { accessChecker = new AccessChecker() { @Override public boolean canAccess(AccessibleObject accessibleObject, Object object) { // Cannot determine whether object can be accessed, so assume it can be accessed return true; } }; } INSTANCE = accessChecker; } public abstract boolean canAccess(AccessibleObject accessibleObject, Object object); } }
for (ReflectionAccessFilter filter : reflectionFilters) { FilterResult result = filter.check(c); if (result != FilterResult.INDECISIVE) { return result; } } return FilterResult.ALLOW;
864
67
931
<no_super_class>
google_gson
gson/gson/src/main/java/com/google/gson/internal/Streams.java
Streams
parse
class Streams { private Streams() { throw new UnsupportedOperationException(); } /** Takes a reader in any state and returns the next value as a JsonElement. */ public static JsonElement parse(JsonReader reader) throws JsonParseException {<FILL_FUNCTION_BODY>} /** Writes the JSON element to the writer, recursively. */ public static void write(JsonElement element, JsonWriter writer) throws IOException { TypeAdapters.JSON_ELEMENT.write(writer, element); } public static Writer writerForAppendable(Appendable appendable) { return appendable instanceof Writer ? (Writer) appendable : new AppendableWriter(appendable); } /** Adapts an {@link Appendable} so it can be passed anywhere a {@link Writer} is used. */ private static final class AppendableWriter extends Writer { private final Appendable appendable; private final CurrentWrite currentWrite = new CurrentWrite(); AppendableWriter(Appendable appendable) { this.appendable = appendable; } @SuppressWarnings("UngroupedOverloads") // this is intentionally ungrouped, see comment below @Override public void write(char[] chars, int offset, int length) throws IOException { currentWrite.setChars(chars); appendable.append(currentWrite, offset, offset + length); } @Override public void flush() {} @Override public void close() {} // Override these methods for better performance // They would otherwise unnecessarily create Strings or char arrays @Override public void write(int i) throws IOException { appendable.append((char) i); } @Override public void write(String str, int off, int len) throws IOException { // Appendable.append turns null -> "null", which is not desired here Objects.requireNonNull(str); appendable.append(str, off, off + len); } @Override public Writer append(CharSequence csq) throws IOException { appendable.append(csq); return this; } @Override public Writer append(CharSequence csq, int start, int end) throws IOException { appendable.append(csq, start, end); return this; } /** A mutable char sequence pointing at a single char[]. */ private static class CurrentWrite implements CharSequence { private char[] chars; private String cachedString; void setChars(char[] chars) { this.chars = chars; this.cachedString = null; } @Override public int length() { return chars.length; } @Override public char charAt(int i) { return chars[i]; } @Override public CharSequence subSequence(int start, int end) { return new String(chars, start, end - start); } // Must return string representation to satisfy toString() contract @Override public String toString() { if (cachedString == null) { cachedString = new String(chars); } return cachedString; } } } }
boolean isEmpty = true; try { JsonToken unused = reader.peek(); isEmpty = false; return TypeAdapters.JSON_ELEMENT.read(reader); } catch (EOFException e) { /* * For compatibility with JSON 1.5 and earlier, we return a JsonNull for * empty documents instead of throwing. */ if (isEmpty) { return JsonNull.INSTANCE; } // The stream ended prematurely so it is likely a syntax error. throw new JsonSyntaxException(e); } catch (MalformedJsonException e) { throw new JsonSyntaxException(e); } catch (IOException e) { throw new JsonIOException(e); } catch (NumberFormatException e) { throw new JsonSyntaxException(e); }
830
206
1,036
<no_super_class>
google_gson
gson/gson/src/main/java/com/google/gson/internal/UnsafeAllocator.java
UnsafeAllocator
create
class UnsafeAllocator { public abstract <T> T newInstance(Class<T> c) throws Exception; /** * Asserts that the class is instantiable. This check should have already occurred in {@link * ConstructorConstructor}; this check here acts as safeguard since trying to use Unsafe for * non-instantiable classes might crash the JVM on some devices. */ private static void assertInstantiable(Class<?> c) { String exceptionMessage = ConstructorConstructor.checkInstantiable(c); if (exceptionMessage != null) { throw new AssertionError( "UnsafeAllocator is used for non-instantiable type: " + exceptionMessage); } } public static final UnsafeAllocator INSTANCE = create(); private static UnsafeAllocator create() {<FILL_FUNCTION_BODY>} }
// try JVM // public class Unsafe { // public Object allocateInstance(Class<?> type); // } try { Class<?> unsafeClass = Class.forName("sun.misc.Unsafe"); Field f = unsafeClass.getDeclaredField("theUnsafe"); f.setAccessible(true); final Object unsafe = f.get(null); final Method allocateInstance = unsafeClass.getMethod("allocateInstance", Class.class); return new UnsafeAllocator() { @Override @SuppressWarnings("unchecked") public <T> T newInstance(Class<T> c) throws Exception { assertInstantiable(c); return (T) allocateInstance.invoke(unsafe, c); } }; } catch (Exception ignored) { // OK: try the next way } // try dalvikvm, post-gingerbread // public class ObjectStreamClass { // private static native int getConstructorId(Class<?> c); // private static native Object newInstance(Class<?> instantiationClass, int methodId); // } try { Method getConstructorId = ObjectStreamClass.class.getDeclaredMethod("getConstructorId", Class.class); getConstructorId.setAccessible(true); final int constructorId = (Integer) getConstructorId.invoke(null, Object.class); final Method newInstance = ObjectStreamClass.class.getDeclaredMethod("newInstance", Class.class, int.class); newInstance.setAccessible(true); return new UnsafeAllocator() { @Override @SuppressWarnings("unchecked") public <T> T newInstance(Class<T> c) throws Exception { assertInstantiable(c); return (T) newInstance.invoke(null, c, constructorId); } }; } catch (Exception ignored) { // OK: try the next way } // try dalvikvm, pre-gingerbread // public class ObjectInputStream { // private static native Object newInstance( // Class<?> instantiationClass, Class<?> constructorClass); // } try { final Method newInstance = ObjectInputStream.class.getDeclaredMethod("newInstance", Class.class, Class.class); newInstance.setAccessible(true); return new UnsafeAllocator() { @Override @SuppressWarnings("unchecked") public <T> T newInstance(Class<T> c) throws Exception { assertInstantiable(c); return (T) newInstance.invoke(null, c, Object.class); } }; } catch (Exception ignored) { // OK: try the next way } // give up return new UnsafeAllocator() { @Override public <T> T newInstance(Class<T> c) { throw new UnsupportedOperationException( "Cannot allocate " + c + ". Usage of JDK sun.misc.Unsafe is enabled, but it could not be used." + " Make sure your runtime is configured correctly."); } };
218
807
1,025
<no_super_class>
google_gson
gson/gson/src/main/java/com/google/gson/internal/bind/ArrayTypeAdapter.java
ArrayTypeAdapter
read
class ArrayTypeAdapter<E> extends TypeAdapter<Object> { public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { Type type = typeToken.getType(); if (!(type instanceof GenericArrayType || (type instanceof Class && ((Class<?>) type).isArray()))) { return null; } Type componentType = $Gson$Types.getArrayComponentType(type); TypeAdapter<?> componentTypeAdapter = gson.getAdapter(TypeToken.get(componentType)); @SuppressWarnings({"unchecked", "rawtypes"}) TypeAdapter<T> arrayAdapter = new ArrayTypeAdapter( gson, componentTypeAdapter, $Gson$Types.getRawType(componentType)); return arrayAdapter; } }; private final Class<E> componentType; private final TypeAdapter<E> componentTypeAdapter; public ArrayTypeAdapter( Gson context, TypeAdapter<E> componentTypeAdapter, Class<E> componentType) { this.componentTypeAdapter = new TypeAdapterRuntimeTypeWrapper<>(context, componentTypeAdapter, componentType); this.componentType = componentType; } @Override public Object read(JsonReader in) throws IOException {<FILL_FUNCTION_BODY>} @Override public void write(JsonWriter out, Object array) throws IOException { if (array == null) { out.nullValue(); return; } out.beginArray(); for (int i = 0, length = Array.getLength(array); i < length; i++) { @SuppressWarnings("unchecked") E value = (E) Array.get(array, i); componentTypeAdapter.write(out, value); } out.endArray(); } }
if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } ArrayList<E> list = new ArrayList<>(); in.beginArray(); while (in.hasNext()) { E instance = componentTypeAdapter.read(in); list.add(instance); } in.endArray(); int size = list.size(); // Have to copy primitives one by one to primitive array if (componentType.isPrimitive()) { Object array = Array.newInstance(componentType, size); for (int i = 0; i < size; i++) { Array.set(array, i, list.get(i)); } return array; } // But for Object[] can use ArrayList.toArray else { @SuppressWarnings("unchecked") E[] array = (E[]) Array.newInstance(componentType, size); return list.toArray(array); }
490
252
742
<methods>public void <init>() ,public final java.lang.Object fromJson(java.io.Reader) throws java.io.IOException,public final java.lang.Object fromJson(java.lang.String) throws java.io.IOException,public final java.lang.Object fromJsonTree(com.google.gson.JsonElement) ,public final TypeAdapter<java.lang.Object> nullSafe() ,public abstract java.lang.Object read(com.google.gson.stream.JsonReader) throws java.io.IOException,public final void toJson(java.io.Writer, java.lang.Object) throws java.io.IOException,public final java.lang.String toJson(java.lang.Object) ,public final com.google.gson.JsonElement toJsonTree(java.lang.Object) ,public abstract void write(com.google.gson.stream.JsonWriter, java.lang.Object) throws java.io.IOException<variables>
google_gson
gson/gson/src/main/java/com/google/gson/internal/bind/CollectionTypeAdapterFactory.java
Adapter
read
class Adapter<E> extends TypeAdapter<Collection<E>> { private final TypeAdapter<E> elementTypeAdapter; private final ObjectConstructor<? extends Collection<E>> constructor; public Adapter( Gson context, Type elementType, TypeAdapter<E> elementTypeAdapter, ObjectConstructor<? extends Collection<E>> constructor) { this.elementTypeAdapter = new TypeAdapterRuntimeTypeWrapper<>(context, elementTypeAdapter, elementType); this.constructor = constructor; } @Override public Collection<E> read(JsonReader in) throws IOException {<FILL_FUNCTION_BODY>} @Override public void write(JsonWriter out, Collection<E> collection) throws IOException { if (collection == null) { out.nullValue(); return; } out.beginArray(); for (E element : collection) { elementTypeAdapter.write(out, element); } out.endArray(); } }
if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } Collection<E> collection = constructor.construct(); in.beginArray(); while (in.hasNext()) { E instance = elementTypeAdapter.read(in); collection.add(instance); } in.endArray(); return collection;
252
100
352
<no_super_class>
google_gson
gson/gson/src/main/java/com/google/gson/internal/bind/DefaultDateTypeAdapter.java
DateType
deserializeToDate
class DateType<T extends Date> { public static final DateType<Date> DATE = new DateType<Date>(Date.class) { @Override protected Date deserialize(Date date) { return date; } }; private final Class<T> dateClass; protected DateType(Class<T> dateClass) { this.dateClass = dateClass; } protected abstract T deserialize(Date date); private TypeAdapterFactory createFactory(DefaultDateTypeAdapter<T> adapter) { return TypeAdapters.newFactory(dateClass, adapter); } public final TypeAdapterFactory createAdapterFactory(String datePattern) { return createFactory(new DefaultDateTypeAdapter<>(this, datePattern)); } public final TypeAdapterFactory createAdapterFactory(int dateStyle, int timeStyle) { return createFactory(new DefaultDateTypeAdapter<>(this, dateStyle, timeStyle)); } } private final DateType<T> dateType; /** * List of 1 or more different date formats used for de-serialization attempts. The first of them * is used for serialization as well. */ private final List<DateFormat> dateFormats = new ArrayList<>(); private DefaultDateTypeAdapter(DateType<T> dateType, String datePattern) { this.dateType = Objects.requireNonNull(dateType); dateFormats.add(new SimpleDateFormat(datePattern, Locale.US)); if (!Locale.getDefault().equals(Locale.US)) { dateFormats.add(new SimpleDateFormat(datePattern)); } } private DefaultDateTypeAdapter(DateType<T> dateType, int dateStyle, int timeStyle) { this.dateType = Objects.requireNonNull(dateType); dateFormats.add(DateFormat.getDateTimeInstance(dateStyle, timeStyle, Locale.US)); if (!Locale.getDefault().equals(Locale.US)) { dateFormats.add(DateFormat.getDateTimeInstance(dateStyle, timeStyle)); } if (JavaVersion.isJava9OrLater()) { dateFormats.add(PreJava9DateFormatProvider.getUsDateTimeFormat(dateStyle, timeStyle)); } } @Override public void write(JsonWriter out, Date value) throws IOException { if (value == null) { out.nullValue(); return; } DateFormat dateFormat = dateFormats.get(0); String dateFormatAsString; // Needs to be synchronized since JDK DateFormat classes are not thread-safe synchronized (dateFormats) { dateFormatAsString = dateFormat.format(value); } out.value(dateFormatAsString); } @Override public T read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } Date date = deserializeToDate(in); return dateType.deserialize(date); } private Date deserializeToDate(JsonReader in) throws IOException {<FILL_FUNCTION_BODY>
String s = in.nextString(); // Needs to be synchronized since JDK DateFormat classes are not thread-safe synchronized (dateFormats) { for (DateFormat dateFormat : dateFormats) { TimeZone originalTimeZone = dateFormat.getTimeZone(); try { return dateFormat.parse(s); } catch (ParseException ignored) { // OK: try the next format } finally { dateFormat.setTimeZone(originalTimeZone); } } } try { return ISO8601Utils.parse(s, new ParsePosition(0)); } catch (ParseException e) { throw new JsonSyntaxException( "Failed parsing '" + s + "' as Date; at path " + in.getPreviousPath(), e); }
807
205
1,012
<methods>public void <init>() ,public final T fromJson(java.io.Reader) throws java.io.IOException,public final T fromJson(java.lang.String) throws java.io.IOException,public final T fromJsonTree(com.google.gson.JsonElement) ,public final TypeAdapter<T> nullSafe() ,public abstract T read(com.google.gson.stream.JsonReader) throws java.io.IOException,public final void toJson(java.io.Writer, T) throws java.io.IOException,public final java.lang.String toJson(T) ,public final com.google.gson.JsonElement toJsonTree(T) ,public abstract void write(com.google.gson.stream.JsonWriter, T) throws java.io.IOException<variables>
google_gson
gson/gson/src/main/java/com/google/gson/internal/bind/JsonAdapterAnnotationTypeAdapterFactory.java
DummyTypeAdapterFactory
getTypeAdapter
class DummyTypeAdapterFactory implements TypeAdapterFactory { @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { throw new AssertionError("Factory should not be used"); } } /** Factory used for {@link TreeTypeAdapter}s created for {@code @JsonAdapter} on a class. */ private static final TypeAdapterFactory TREE_TYPE_CLASS_DUMMY_FACTORY = new DummyTypeAdapterFactory(); /** Factory used for {@link TreeTypeAdapter}s created for {@code @JsonAdapter} on a field. */ private static final TypeAdapterFactory TREE_TYPE_FIELD_DUMMY_FACTORY = new DummyTypeAdapterFactory(); private final ConstructorConstructor constructorConstructor; /** * For a class, if it is annotated with {@code @JsonAdapter} and refers to a {@link * TypeAdapterFactory}, stores the factory instance in case it has been requested already. Has to * be a {@link ConcurrentMap} because {@link Gson} guarantees to be thread-safe. */ // Note: In case these strong reference to TypeAdapterFactory instances are considered // a memory leak in the future, could consider switching to WeakReference<TypeAdapterFactory> private final ConcurrentMap<Class<?>, TypeAdapterFactory> adapterFactoryMap; public JsonAdapterAnnotationTypeAdapterFactory(ConstructorConstructor constructorConstructor) { this.constructorConstructor = constructorConstructor; this.adapterFactoryMap = new ConcurrentHashMap<>(); } // Separate helper method to make sure callers retrieve annotation in a consistent way private static JsonAdapter getAnnotation(Class<?> rawType) { return rawType.getAnnotation(JsonAdapter.class); } // this is not safe; requires that user has specified correct adapter class for @JsonAdapter @SuppressWarnings("unchecked") @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> targetType) { Class<? super T> rawType = targetType.getRawType(); JsonAdapter annotation = getAnnotation(rawType); if (annotation == null) { return null; } return (TypeAdapter<T>) getTypeAdapter(constructorConstructor, gson, targetType, annotation, true); } // Separate helper method to make sure callers create adapter in a consistent way private static Object createAdapter( ConstructorConstructor constructorConstructor, Class<?> adapterClass) { // TODO: The exception messages created by ConstructorConstructor are currently written in the // context of deserialization and for example suggest usage of TypeAdapter, which would not work // for @JsonAdapter usage return constructorConstructor.get(TypeToken.get(adapterClass)).construct(); } private TypeAdapterFactory putFactoryAndGetCurrent(Class<?> rawType, TypeAdapterFactory factory) { // Uses putIfAbsent in case multiple threads concurrently create factory TypeAdapterFactory existingFactory = adapterFactoryMap.putIfAbsent(rawType, factory); return existingFactory != null ? existingFactory : factory; } TypeAdapter<?> getTypeAdapter( ConstructorConstructor constructorConstructor, Gson gson, TypeToken<?> type, JsonAdapter annotation, boolean isClassAnnotation) {<FILL_FUNCTION_BODY>
Object instance = createAdapter(constructorConstructor, annotation.value()); TypeAdapter<?> typeAdapter; boolean nullSafe = annotation.nullSafe(); if (instance instanceof TypeAdapter) { typeAdapter = (TypeAdapter<?>) instance; } else if (instance instanceof TypeAdapterFactory) { TypeAdapterFactory factory = (TypeAdapterFactory) instance; if (isClassAnnotation) { factory = putFactoryAndGetCurrent(type.getRawType(), factory); } typeAdapter = factory.create(gson, type); } else if (instance instanceof JsonSerializer || instance instanceof JsonDeserializer) { JsonSerializer<?> serializer = instance instanceof JsonSerializer ? (JsonSerializer<?>) instance : null; JsonDeserializer<?> deserializer = instance instanceof JsonDeserializer ? (JsonDeserializer<?>) instance : null; // Uses dummy factory instances because TreeTypeAdapter needs a 'skipPast' factory for // `Gson.getDelegateAdapter` call and has to differentiate there whether TreeTypeAdapter was // created for @JsonAdapter on class or field TypeAdapterFactory skipPast; if (isClassAnnotation) { skipPast = TREE_TYPE_CLASS_DUMMY_FACTORY; } else { skipPast = TREE_TYPE_FIELD_DUMMY_FACTORY; } @SuppressWarnings({"unchecked", "rawtypes"}) TypeAdapter<?> tempAdapter = new TreeTypeAdapter(serializer, deserializer, gson, type, skipPast, nullSafe); typeAdapter = tempAdapter; // TreeTypeAdapter handles nullSafe; don't additionally call `nullSafe()` nullSafe = false; } else { throw new IllegalArgumentException( "Invalid attempt to bind an instance of " + instance.getClass().getName() + " as a @JsonAdapter for " + type.toString() + ". @JsonAdapter value must be a TypeAdapter, TypeAdapterFactory," + " JsonSerializer or JsonDeserializer."); } if (typeAdapter != null && nullSafe) { typeAdapter = typeAdapter.nullSafe(); } return typeAdapter;
828
555
1,383
<no_super_class>
google_gson
gson/gson/src/main/java/com/google/gson/internal/bind/JsonTreeWriter.java
JsonTreeWriter
endObject
class JsonTreeWriter extends JsonWriter { private static final Writer UNWRITABLE_WRITER = new Writer() { @Override public void write(char[] buffer, int offset, int counter) { throw new AssertionError(); } @Override public void flush() { throw new AssertionError(); } @Override public void close() { throw new AssertionError(); } }; /** Added to the top of the stack when this writer is closed to cause following ops to fail. */ private static final JsonPrimitive SENTINEL_CLOSED = new JsonPrimitive("closed"); /** The JsonElements and JsonArrays under modification, outermost to innermost. */ private final List<JsonElement> stack = new ArrayList<>(); /** The name for the next JSON object value. If non-null, the top of the stack is a JsonObject. */ private String pendingName; /** the JSON element constructed by this writer. */ private JsonElement product = JsonNull.INSTANCE; // TODO: is this really what we want?; public JsonTreeWriter() { super(UNWRITABLE_WRITER); } /** Returns the top level object produced by this writer. */ public JsonElement get() { if (!stack.isEmpty()) { throw new IllegalStateException("Expected one JSON element but was " + stack); } return product; } private JsonElement peek() { return stack.get(stack.size() - 1); } private void put(JsonElement value) { if (pendingName != null) { if (!value.isJsonNull() || getSerializeNulls()) { JsonObject object = (JsonObject) peek(); object.add(pendingName, value); } pendingName = null; } else if (stack.isEmpty()) { product = value; } else { JsonElement element = peek(); if (element instanceof JsonArray) { ((JsonArray) element).add(value); } else { throw new IllegalStateException(); } } } @CanIgnoreReturnValue @Override public JsonWriter beginArray() throws IOException { JsonArray array = new JsonArray(); put(array); stack.add(array); return this; } @CanIgnoreReturnValue @Override public JsonWriter endArray() throws IOException { if (stack.isEmpty() || pendingName != null) { throw new IllegalStateException(); } JsonElement element = peek(); if (element instanceof JsonArray) { stack.remove(stack.size() - 1); return this; } throw new IllegalStateException(); } @CanIgnoreReturnValue @Override public JsonWriter beginObject() throws IOException { JsonObject object = new JsonObject(); put(object); stack.add(object); return this; } @CanIgnoreReturnValue @Override public JsonWriter endObject() throws IOException {<FILL_FUNCTION_BODY>} @CanIgnoreReturnValue @Override public JsonWriter name(String name) throws IOException { Objects.requireNonNull(name, "name == null"); if (stack.isEmpty() || pendingName != null) { throw new IllegalStateException("Did not expect a name"); } JsonElement element = peek(); if (element instanceof JsonObject) { pendingName = name; return this; } throw new IllegalStateException("Please begin an object before writing a name."); } @CanIgnoreReturnValue @Override public JsonWriter value(String value) throws IOException { if (value == null) { return nullValue(); } put(new JsonPrimitive(value)); return this; } @CanIgnoreReturnValue @Override public JsonWriter value(boolean value) throws IOException { put(new JsonPrimitive(value)); return this; } @CanIgnoreReturnValue @Override public JsonWriter value(Boolean value) throws IOException { if (value == null) { return nullValue(); } put(new JsonPrimitive(value)); return this; } @CanIgnoreReturnValue @Override public JsonWriter value(float value) throws IOException { if (!isLenient() && (Float.isNaN(value) || Float.isInfinite(value))) { throw new IllegalArgumentException("JSON forbids NaN and infinities: " + value); } put(new JsonPrimitive(value)); return this; } @CanIgnoreReturnValue @Override public JsonWriter value(double value) throws IOException { if (!isLenient() && (Double.isNaN(value) || Double.isInfinite(value))) { throw new IllegalArgumentException("JSON forbids NaN and infinities: " + value); } put(new JsonPrimitive(value)); return this; } @CanIgnoreReturnValue @Override public JsonWriter value(long value) throws IOException { put(new JsonPrimitive(value)); return this; } @CanIgnoreReturnValue @Override public JsonWriter value(Number value) throws IOException { if (value == null) { return nullValue(); } if (!isLenient()) { double d = value.doubleValue(); if (Double.isNaN(d) || Double.isInfinite(d)) { throw new IllegalArgumentException("JSON forbids NaN and infinities: " + value); } } put(new JsonPrimitive(value)); return this; } @CanIgnoreReturnValue @Override public JsonWriter nullValue() throws IOException { put(JsonNull.INSTANCE); return this; } @Override public JsonWriter jsonValue(String value) throws IOException { throw new UnsupportedOperationException(); } @Override public void flush() throws IOException {} @Override public void close() throws IOException { if (!stack.isEmpty()) { throw new IOException("Incomplete document"); } stack.add(SENTINEL_CLOSED); } }
if (stack.isEmpty() || pendingName != null) { throw new IllegalStateException(); } JsonElement element = peek(); if (element instanceof JsonObject) { stack.remove(stack.size() - 1); return this; } throw new IllegalStateException();
1,587
79
1,666
<methods>public void <init>(java.io.Writer) ,public com.google.gson.stream.JsonWriter beginArray() throws java.io.IOException,public com.google.gson.stream.JsonWriter beginObject() throws java.io.IOException,public void close() throws java.io.IOException,public com.google.gson.stream.JsonWriter endArray() throws java.io.IOException,public com.google.gson.stream.JsonWriter endObject() throws java.io.IOException,public void flush() throws java.io.IOException,public final com.google.gson.FormattingStyle getFormattingStyle() ,public final boolean getSerializeNulls() ,public final com.google.gson.Strictness getStrictness() ,public final boolean isHtmlSafe() ,public boolean isLenient() ,public com.google.gson.stream.JsonWriter jsonValue(java.lang.String) throws java.io.IOException,public com.google.gson.stream.JsonWriter name(java.lang.String) throws java.io.IOException,public com.google.gson.stream.JsonWriter nullValue() throws java.io.IOException,public final void setFormattingStyle(com.google.gson.FormattingStyle) ,public final void setHtmlSafe(boolean) ,public final void setIndent(java.lang.String) ,public final void setLenient(boolean) ,public final void setSerializeNulls(boolean) ,public final void setStrictness(com.google.gson.Strictness) ,public com.google.gson.stream.JsonWriter value(java.lang.String) throws java.io.IOException,public com.google.gson.stream.JsonWriter value(boolean) throws java.io.IOException,public com.google.gson.stream.JsonWriter value(java.lang.Boolean) throws java.io.IOException,public com.google.gson.stream.JsonWriter value(float) throws java.io.IOException,public com.google.gson.stream.JsonWriter value(double) throws java.io.IOException,public com.google.gson.stream.JsonWriter value(long) throws java.io.IOException,public com.google.gson.stream.JsonWriter value(java.lang.Number) throws java.io.IOException<variables>private static final non-sealed java.lang.String[] HTML_SAFE_REPLACEMENT_CHARS,private static final non-sealed java.lang.String[] REPLACEMENT_CHARS,private static final java.util.regex.Pattern VALID_JSON_NUMBER_PATTERN,private java.lang.String deferredName,private java.lang.String formattedColon,private java.lang.String formattedComma,private com.google.gson.FormattingStyle formattingStyle,private boolean htmlSafe,private final non-sealed java.io.Writer out,private boolean serializeNulls,private int[] stack,private int stackSize,private com.google.gson.Strictness strictness,private boolean usesEmptyNewlineAndIndent
google_gson
gson/gson/src/main/java/com/google/gson/internal/bind/MapTypeAdapterFactory.java
Adapter
write
class Adapter<K, V> extends TypeAdapter<Map<K, V>> { private final TypeAdapter<K> keyTypeAdapter; private final TypeAdapter<V> valueTypeAdapter; private final ObjectConstructor<? extends Map<K, V>> constructor; public Adapter( Gson context, Type keyType, TypeAdapter<K> keyTypeAdapter, Type valueType, TypeAdapter<V> valueTypeAdapter, ObjectConstructor<? extends Map<K, V>> constructor) { this.keyTypeAdapter = new TypeAdapterRuntimeTypeWrapper<>(context, keyTypeAdapter, keyType); this.valueTypeAdapter = new TypeAdapterRuntimeTypeWrapper<>(context, valueTypeAdapter, valueType); this.constructor = constructor; } @Override public Map<K, V> read(JsonReader in) throws IOException { JsonToken peek = in.peek(); if (peek == JsonToken.NULL) { in.nextNull(); return null; } Map<K, V> map = constructor.construct(); if (peek == JsonToken.BEGIN_ARRAY) { in.beginArray(); while (in.hasNext()) { in.beginArray(); // entry array K key = keyTypeAdapter.read(in); V value = valueTypeAdapter.read(in); V replaced = map.put(key, value); if (replaced != null) { throw new JsonSyntaxException("duplicate key: " + key); } in.endArray(); } in.endArray(); } else { in.beginObject(); while (in.hasNext()) { JsonReaderInternalAccess.INSTANCE.promoteNameToValue(in); K key = keyTypeAdapter.read(in); V value = valueTypeAdapter.read(in); V replaced = map.put(key, value); if (replaced != null) { throw new JsonSyntaxException("duplicate key: " + key); } } in.endObject(); } return map; } @Override public void write(JsonWriter out, Map<K, V> map) throws IOException {<FILL_FUNCTION_BODY>} private String keyToString(JsonElement keyElement) { if (keyElement.isJsonPrimitive()) { JsonPrimitive primitive = keyElement.getAsJsonPrimitive(); if (primitive.isNumber()) { return String.valueOf(primitive.getAsNumber()); } else if (primitive.isBoolean()) { return Boolean.toString(primitive.getAsBoolean()); } else if (primitive.isString()) { return primitive.getAsString(); } else { throw new AssertionError(); } } else if (keyElement.isJsonNull()) { return "null"; } else { throw new AssertionError(); } } }
if (map == null) { out.nullValue(); return; } if (!complexMapKeySerialization) { out.beginObject(); for (Map.Entry<K, V> entry : map.entrySet()) { out.name(String.valueOf(entry.getKey())); valueTypeAdapter.write(out, entry.getValue()); } out.endObject(); return; } boolean hasComplexKeys = false; List<JsonElement> keys = new ArrayList<>(map.size()); List<V> values = new ArrayList<>(map.size()); for (Map.Entry<K, V> entry : map.entrySet()) { JsonElement keyElement = keyTypeAdapter.toJsonTree(entry.getKey()); keys.add(keyElement); values.add(entry.getValue()); hasComplexKeys |= keyElement.isJsonArray() || keyElement.isJsonObject(); } if (hasComplexKeys) { out.beginArray(); for (int i = 0, size = keys.size(); i < size; i++) { out.beginArray(); // entry array Streams.write(keys.get(i), out); valueTypeAdapter.write(out, values.get(i)); out.endArray(); } out.endArray(); } else { out.beginObject(); for (int i = 0, size = keys.size(); i < size; i++) { JsonElement keyElement = keys.get(i); out.name(keyToString(keyElement)); valueTypeAdapter.write(out, values.get(i)); } out.endObject(); }
741
429
1,170
<no_super_class>
google_gson
gson/gson/src/main/java/com/google/gson/internal/bind/NumberTypeAdapter.java
NumberTypeAdapter
getFactory
class NumberTypeAdapter extends TypeAdapter<Number> { /** Gson default factory using {@link ToNumberPolicy#LAZILY_PARSED_NUMBER}. */ private static final TypeAdapterFactory LAZILY_PARSED_NUMBER_FACTORY = newFactory(ToNumberPolicy.LAZILY_PARSED_NUMBER); private final ToNumberStrategy toNumberStrategy; private NumberTypeAdapter(ToNumberStrategy toNumberStrategy) { this.toNumberStrategy = toNumberStrategy; } private static TypeAdapterFactory newFactory(ToNumberStrategy toNumberStrategy) { final NumberTypeAdapter adapter = new NumberTypeAdapter(toNumberStrategy); return new TypeAdapterFactory() { @SuppressWarnings("unchecked") @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { return type.getRawType() == Number.class ? (TypeAdapter<T>) adapter : null; } }; } public static TypeAdapterFactory getFactory(ToNumberStrategy toNumberStrategy) {<FILL_FUNCTION_BODY>} @Override public Number read(JsonReader in) throws IOException { JsonToken jsonToken = in.peek(); switch (jsonToken) { case NULL: in.nextNull(); return null; case NUMBER: case STRING: return toNumberStrategy.readNumber(in); default: throw new JsonSyntaxException( "Expecting number, got: " + jsonToken + "; at path " + in.getPath()); } } @Override public void write(JsonWriter out, Number value) throws IOException { out.value(value); } }
if (toNumberStrategy == ToNumberPolicy.LAZILY_PARSED_NUMBER) { return LAZILY_PARSED_NUMBER_FACTORY; } else { return newFactory(toNumberStrategy); }
433
63
496
<methods>public void <init>() ,public final java.lang.Number fromJson(java.io.Reader) throws java.io.IOException,public final java.lang.Number fromJson(java.lang.String) throws java.io.IOException,public final java.lang.Number fromJsonTree(com.google.gson.JsonElement) ,public final TypeAdapter<java.lang.Number> nullSafe() ,public abstract java.lang.Number read(com.google.gson.stream.JsonReader) throws java.io.IOException,public final void toJson(java.io.Writer, java.lang.Number) throws java.io.IOException,public final java.lang.String toJson(java.lang.Number) ,public final com.google.gson.JsonElement toJsonTree(java.lang.Number) ,public abstract void write(com.google.gson.stream.JsonWriter, java.lang.Number) throws java.io.IOException<variables>
google_gson
gson/gson/src/main/java/com/google/gson/internal/bind/ObjectTypeAdapter.java
ObjectTypeAdapter
read
class ObjectTypeAdapter extends TypeAdapter<Object> { /** Gson default factory using {@link ToNumberPolicy#DOUBLE}. */ private static final TypeAdapterFactory DOUBLE_FACTORY = newFactory(ToNumberPolicy.DOUBLE); private final Gson gson; private final ToNumberStrategy toNumberStrategy; private ObjectTypeAdapter(Gson gson, ToNumberStrategy toNumberStrategy) { this.gson = gson; this.toNumberStrategy = toNumberStrategy; } private static TypeAdapterFactory newFactory(final ToNumberStrategy toNumberStrategy) { return new TypeAdapterFactory() { @SuppressWarnings("unchecked") @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { if (type.getRawType() == Object.class) { return (TypeAdapter<T>) new ObjectTypeAdapter(gson, toNumberStrategy); } return null; } }; } public static TypeAdapterFactory getFactory(ToNumberStrategy toNumberStrategy) { if (toNumberStrategy == ToNumberPolicy.DOUBLE) { return DOUBLE_FACTORY; } else { return newFactory(toNumberStrategy); } } /** * Tries to begin reading a JSON array or JSON object, returning {@code null} if the next element * is neither of those. */ private Object tryBeginNesting(JsonReader in, JsonToken peeked) throws IOException { switch (peeked) { case BEGIN_ARRAY: in.beginArray(); return new ArrayList<>(); case BEGIN_OBJECT: in.beginObject(); return new LinkedTreeMap<>(); default: return null; } } /** Reads an {@code Object} which cannot have any nested elements */ private Object readTerminal(JsonReader in, JsonToken peeked) throws IOException { switch (peeked) { case STRING: return in.nextString(); case NUMBER: return toNumberStrategy.readNumber(in); case BOOLEAN: return in.nextBoolean(); case NULL: in.nextNull(); return null; default: // When read(JsonReader) is called with JsonReader in invalid state throw new IllegalStateException("Unexpected token: " + peeked); } } @Override public Object read(JsonReader in) throws IOException {<FILL_FUNCTION_BODY>} @Override public void write(JsonWriter out, Object value) throws IOException { if (value == null) { out.nullValue(); return; } @SuppressWarnings("unchecked") TypeAdapter<Object> typeAdapter = (TypeAdapter<Object>) gson.getAdapter(value.getClass()); if (typeAdapter instanceof ObjectTypeAdapter) { out.beginObject(); out.endObject(); return; } typeAdapter.write(out, value); } }
// Either List or Map Object current; JsonToken peeked = in.peek(); current = tryBeginNesting(in, peeked); if (current == null) { return readTerminal(in, peeked); } Deque<Object> stack = new ArrayDeque<>(); while (true) { while (in.hasNext()) { String name = null; // Name is only used for JSON object members if (current instanceof Map) { name = in.nextName(); } peeked = in.peek(); Object value = tryBeginNesting(in, peeked); boolean isNesting = value != null; if (value == null) { value = readTerminal(in, peeked); } if (current instanceof List) { @SuppressWarnings("unchecked") List<Object> list = (List<Object>) current; list.add(value); } else { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) current; map.put(name, value); } if (isNesting) { stack.addLast(current); current = value; } } // End current element if (current instanceof List) { in.endArray(); } else { in.endObject(); } if (stack.isEmpty()) { return current; } else { // Continue with enclosing element current = stack.removeLast(); } }
778
425
1,203
<methods>public void <init>() ,public final java.lang.Object fromJson(java.io.Reader) throws java.io.IOException,public final java.lang.Object fromJson(java.lang.String) throws java.io.IOException,public final java.lang.Object fromJsonTree(com.google.gson.JsonElement) ,public final TypeAdapter<java.lang.Object> nullSafe() ,public abstract java.lang.Object read(com.google.gson.stream.JsonReader) throws java.io.IOException,public final void toJson(java.io.Writer, java.lang.Object) throws java.io.IOException,public final java.lang.String toJson(java.lang.Object) ,public final com.google.gson.JsonElement toJsonTree(java.lang.Object) ,public abstract void write(com.google.gson.stream.JsonWriter, java.lang.Object) throws java.io.IOException<variables>
google_gson
gson/gson/src/main/java/com/google/gson/internal/bind/TreeTypeAdapter.java
SingleTypeFactory
create
class SingleTypeFactory implements TypeAdapterFactory { private final TypeToken<?> exactType; private final boolean matchRawType; private final Class<?> hierarchyType; private final JsonSerializer<?> serializer; private final JsonDeserializer<?> deserializer; SingleTypeFactory( Object typeAdapter, TypeToken<?> exactType, boolean matchRawType, Class<?> hierarchyType) { serializer = typeAdapter instanceof JsonSerializer ? (JsonSerializer<?>) typeAdapter : null; deserializer = typeAdapter instanceof JsonDeserializer ? (JsonDeserializer<?>) typeAdapter : null; $Gson$Preconditions.checkArgument(serializer != null || deserializer != null); this.exactType = exactType; this.matchRawType = matchRawType; this.hierarchyType = hierarchyType; } @SuppressWarnings("unchecked") // guarded by typeToken.equals() call @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {<FILL_FUNCTION_BODY>} }
boolean matches = exactType != null ? exactType.equals(type) || (matchRawType && exactType.getType() == type.getRawType()) : hierarchyType.isAssignableFrom(type.getRawType()); return matches ? new TreeTypeAdapter<>( (JsonSerializer<T>) serializer, (JsonDeserializer<T>) deserializer, gson, type, this) : null;
285
112
397
<methods>public non-sealed void <init>() ,public abstract TypeAdapter<T> getSerializationDelegate() <variables>
google_gson
gson/gson/src/main/java/com/google/gson/internal/bind/TypeAdapterRuntimeTypeWrapper.java
TypeAdapterRuntimeTypeWrapper
write
class TypeAdapterRuntimeTypeWrapper<T> extends TypeAdapter<T> { private final Gson context; private final TypeAdapter<T> delegate; private final Type type; TypeAdapterRuntimeTypeWrapper(Gson context, TypeAdapter<T> delegate, Type type) { this.context = context; this.delegate = delegate; this.type = type; } @Override public T read(JsonReader in) throws IOException { return delegate.read(in); } @Override public void write(JsonWriter out, T value) throws IOException {<FILL_FUNCTION_BODY>} /** * Returns whether the type adapter uses reflection. * * @param typeAdapter the type adapter to check. */ private static boolean isReflective(TypeAdapter<?> typeAdapter) { // Run this in loop in case multiple delegating adapters are nested while (typeAdapter instanceof SerializationDelegatingTypeAdapter) { TypeAdapter<?> delegate = ((SerializationDelegatingTypeAdapter<?>) typeAdapter).getSerializationDelegate(); // Break if adapter does not delegate serialization if (delegate == typeAdapter) { break; } typeAdapter = delegate; } return typeAdapter instanceof ReflectiveTypeAdapterFactory.Adapter; } /** Finds a compatible runtime type if it is more specific */ private static Type getRuntimeTypeIfMoreSpecific(Type type, Object value) { if (value != null && (type instanceof Class<?> || type instanceof TypeVariable<?>)) { type = value.getClass(); } return type; } }
// Order of preference for choosing type adapters // First preference: a type adapter registered for the runtime type // Second preference: a type adapter registered for the declared type // Third preference: reflective type adapter for the runtime type // (if it is a subclass of the declared type) // Fourth preference: reflective type adapter for the declared type TypeAdapter<T> chosen = delegate; Type runtimeType = getRuntimeTypeIfMoreSpecific(type, value); if (runtimeType != type) { @SuppressWarnings("unchecked") TypeAdapter<T> runtimeTypeAdapter = (TypeAdapter<T>) context.getAdapter(TypeToken.get(runtimeType)); // For backward compatibility only check ReflectiveTypeAdapterFactory.Adapter here but not any // other wrapping adapters, see // https://github.com/google/gson/pull/1787#issuecomment-1222175189 if (!(runtimeTypeAdapter instanceof ReflectiveTypeAdapterFactory.Adapter)) { // The user registered a type adapter for the runtime type, so we will use that chosen = runtimeTypeAdapter; } else if (!isReflective(delegate)) { // The user registered a type adapter for Base class, so we prefer it over the // reflective type adapter for the runtime type chosen = delegate; } else { // Use the type adapter for runtime type chosen = runtimeTypeAdapter; } } chosen.write(out, value);
418
374
792
<methods>public void <init>() ,public final T fromJson(java.io.Reader) throws java.io.IOException,public final T fromJson(java.lang.String) throws java.io.IOException,public final T fromJsonTree(com.google.gson.JsonElement) ,public final TypeAdapter<T> nullSafe() ,public abstract T read(com.google.gson.stream.JsonReader) throws java.io.IOException,public final void toJson(java.io.Writer, T) throws java.io.IOException,public final java.lang.String toJson(T) ,public final com.google.gson.JsonElement toJsonTree(T) ,public abstract void write(com.google.gson.stream.JsonWriter, T) throws java.io.IOException<variables>
google_gson
gson/gson/src/main/java/com/google/gson/internal/sql/SqlDateTypeAdapter.java
SqlDateTypeAdapter
write
class SqlDateTypeAdapter extends TypeAdapter<java.sql.Date> { static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { return typeToken.getRawType() == java.sql.Date.class ? (TypeAdapter<T>) new SqlDateTypeAdapter() : null; } }; private final DateFormat format = new SimpleDateFormat("MMM d, yyyy"); private SqlDateTypeAdapter() {} @Override public java.sql.Date read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } String s = in.nextString(); synchronized (this) { TimeZone originalTimeZone = format.getTimeZone(); // Save the original time zone try { Date utilDate = format.parse(s); return new java.sql.Date(utilDate.getTime()); } catch (ParseException e) { throw new JsonSyntaxException( "Failed parsing '" + s + "' as SQL Date; at path " + in.getPreviousPath(), e); } finally { format.setTimeZone(originalTimeZone); // Restore the original time zone after parsing } } } @Override public void write(JsonWriter out, java.sql.Date value) throws IOException {<FILL_FUNCTION_BODY>} }
if (value == null) { out.nullValue(); return; } String dateString; synchronized (this) { dateString = format.format(value); } out.value(dateString);
414
63
477
<methods>public void <init>() ,public final java.sql.Date fromJson(java.io.Reader) throws java.io.IOException,public final java.sql.Date fromJson(java.lang.String) throws java.io.IOException,public final java.sql.Date fromJsonTree(com.google.gson.JsonElement) ,public final TypeAdapter<java.sql.Date> nullSafe() ,public abstract java.sql.Date read(com.google.gson.stream.JsonReader) throws java.io.IOException,public final void toJson(java.io.Writer, java.sql.Date) throws java.io.IOException,public final java.lang.String toJson(java.sql.Date) ,public final com.google.gson.JsonElement toJsonTree(java.sql.Date) ,public abstract void write(com.google.gson.stream.JsonWriter, java.sql.Date) throws java.io.IOException<variables>
google_gson
gson/gson/src/main/java/com/google/gson/internal/sql/SqlTimeTypeAdapter.java
SqlTimeTypeAdapter
read
class SqlTimeTypeAdapter extends TypeAdapter<Time> { static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { return typeToken.getRawType() == Time.class ? (TypeAdapter<T>) new SqlTimeTypeAdapter() : null; } }; private final DateFormat format = new SimpleDateFormat("hh:mm:ss a"); private SqlTimeTypeAdapter() {} @Override public Time read(JsonReader in) throws IOException {<FILL_FUNCTION_BODY>} @Override public void write(JsonWriter out, Time value) throws IOException { if (value == null) { out.nullValue(); return; } String timeString; synchronized (this) { timeString = format.format(value); } out.value(timeString); } }
if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } String s = in.nextString(); synchronized (this) { TimeZone originalTimeZone = format.getTimeZone(); // Save the original time zone try { Date date = format.parse(s); return new Time(date.getTime()); } catch (ParseException e) { throw new JsonSyntaxException( "Failed parsing '" + s + "' as SQL Time; at path " + in.getPreviousPath(), e); } finally { format.setTimeZone(originalTimeZone); // Restore the original time zone } }
278
173
451
<methods>public void <init>() ,public final java.sql.Time fromJson(java.io.Reader) throws java.io.IOException,public final java.sql.Time fromJson(java.lang.String) throws java.io.IOException,public final java.sql.Time fromJsonTree(com.google.gson.JsonElement) ,public final TypeAdapter<java.sql.Time> nullSafe() ,public abstract java.sql.Time read(com.google.gson.stream.JsonReader) throws java.io.IOException,public final void toJson(java.io.Writer, java.sql.Time) throws java.io.IOException,public final java.lang.String toJson(java.sql.Time) ,public final com.google.gson.JsonElement toJsonTree(java.sql.Time) ,public abstract void write(com.google.gson.stream.JsonWriter, java.sql.Time) throws java.io.IOException<variables>
google_gson
gson/gson/src/main/java/com/google/gson/internal/sql/SqlTimestampTypeAdapter.java
SqlTimestampTypeAdapter
read
class SqlTimestampTypeAdapter extends TypeAdapter<Timestamp> { static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { if (typeToken.getRawType() == Timestamp.class) { final TypeAdapter<Date> dateTypeAdapter = gson.getAdapter(Date.class); return (TypeAdapter<T>) new SqlTimestampTypeAdapter(dateTypeAdapter); } else { return null; } } }; private final TypeAdapter<Date> dateTypeAdapter; private SqlTimestampTypeAdapter(TypeAdapter<Date> dateTypeAdapter) { this.dateTypeAdapter = dateTypeAdapter; } @Override public Timestamp read(JsonReader in) throws IOException {<FILL_FUNCTION_BODY>} @Override public void write(JsonWriter out, Timestamp value) throws IOException { dateTypeAdapter.write(out, value); } }
Date date = dateTypeAdapter.read(in); return date != null ? new Timestamp(date.getTime()) : null;
287
36
323
<methods>public void <init>() ,public final java.sql.Timestamp fromJson(java.io.Reader) throws java.io.IOException,public final java.sql.Timestamp fromJson(java.lang.String) throws java.io.IOException,public final java.sql.Timestamp fromJsonTree(com.google.gson.JsonElement) ,public final TypeAdapter<java.sql.Timestamp> nullSafe() ,public abstract java.sql.Timestamp read(com.google.gson.stream.JsonReader) throws java.io.IOException,public final void toJson(java.io.Writer, java.sql.Timestamp) throws java.io.IOException,public final java.lang.String toJson(java.sql.Timestamp) ,public final com.google.gson.JsonElement toJsonTree(java.sql.Timestamp) ,public abstract void write(com.google.gson.stream.JsonWriter, java.sql.Timestamp) throws java.io.IOException<variables>
google_gson
gson/metrics/src/main/java/com/google/gson/metrics/BagOfPrimitives.java
BagOfPrimitives
hashCode
class BagOfPrimitives { public static final long DEFAULT_VALUE = 0; public long longValue; public int intValue; public boolean booleanValue; public String stringValue; public BagOfPrimitives() { this(DEFAULT_VALUE, 0, false, ""); } public BagOfPrimitives(long longValue, int intValue, boolean booleanValue, String stringValue) { this.longValue = longValue; this.intValue = intValue; this.booleanValue = booleanValue; this.stringValue = stringValue; } public int getIntValue() { return intValue; } public String getExpectedJson() { return "{" + "\"longValue\":" + longValue + "," + "\"intValue\":" + intValue + "," + "\"booleanValue\":" + booleanValue + "," + "\"stringValue\":\"" + stringValue + "\"" + "}"; } @Override public int hashCode() {<FILL_FUNCTION_BODY>} @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof BagOfPrimitives)) { return false; } BagOfPrimitives that = (BagOfPrimitives) o; return longValue == that.longValue && intValue == that.intValue && booleanValue == that.booleanValue && Objects.equal(stringValue, that.stringValue); } @Override public String toString() { return String.format( "(longValue=%d,intValue=%d,booleanValue=%b,stringValue=%s)", longValue, intValue, booleanValue, stringValue); } }
final int prime = 31; int result = 1; result = prime * result + (booleanValue ? 1231 : 1237); result = prime * result + intValue; result = prime * result + (int) (longValue ^ (longValue >>> 32)); result = prime * result + ((stringValue == null) ? 0 : stringValue.hashCode()); return result;
476
107
583
<no_super_class>
google_gson
gson/metrics/src/main/java/com/google/gson/metrics/BagOfPrimitivesDeserializationBenchmark.java
BagOfPrimitivesDeserializationBenchmark
timeBagOfPrimitivesStreaming
class BagOfPrimitivesDeserializationBenchmark { private Gson gson; private String json; public static void main(String[] args) { NonUploadingCaliperRunner.run(BagOfPrimitivesDeserializationBenchmark.class, args); } @BeforeExperiment void setUp() throws Exception { this.gson = new Gson(); BagOfPrimitives bag = new BagOfPrimitives(10L, 1, false, "foo"); this.json = gson.toJson(bag); } /** Benchmark to measure Gson performance for deserializing an object */ public void timeBagOfPrimitivesDefault(int reps) { for (int i = 0; i < reps; ++i) { gson.fromJson(json, BagOfPrimitives.class); } } /** Benchmark to measure deserializing objects by hand */ public void timeBagOfPrimitivesStreaming(int reps) throws IOException {<FILL_FUNCTION_BODY>} /** * This benchmark measures the ideal Gson performance: the cost of parsing a JSON stream and * setting object values by reflection. We should strive to reduce the discrepancy between this * and {@link #timeBagOfPrimitivesDefault(int)} . */ public void timeBagOfPrimitivesReflectionStreaming(int reps) throws Exception { for (int i = 0; i < reps; ++i) { StringReader reader = new StringReader(json); JsonReader jr = new JsonReader(reader); jr.beginObject(); BagOfPrimitives bag = new BagOfPrimitives(); while (jr.hasNext()) { String name = jr.nextName(); for (Field field : BagOfPrimitives.class.getDeclaredFields()) { if (field.getName().equals(name)) { Class<?> fieldType = field.getType(); if (fieldType.equals(long.class)) { field.setLong(bag, jr.nextLong()); } else if (fieldType.equals(int.class)) { field.setInt(bag, jr.nextInt()); } else if (fieldType.equals(boolean.class)) { field.setBoolean(bag, jr.nextBoolean()); } else if (fieldType.equals(String.class)) { field.set(bag, jr.nextString()); } else { throw new RuntimeException("Unexpected: type: " + fieldType + ", name: " + name); } } } } jr.endObject(); } } }
for (int i = 0; i < reps; ++i) { StringReader reader = new StringReader(json); JsonReader jr = new JsonReader(reader); jr.beginObject(); long longValue = 0; int intValue = 0; boolean booleanValue = false; String stringValue = null; while (jr.hasNext()) { String name = jr.nextName(); if (name.equals("longValue")) { longValue = jr.nextLong(); } else if (name.equals("intValue")) { intValue = jr.nextInt(); } else if (name.equals("booleanValue")) { booleanValue = jr.nextBoolean(); } else if (name.equals("stringValue")) { stringValue = jr.nextString(); } else { throw new IOException("Unexpected name: " + name); } } jr.endObject(); new BagOfPrimitives(longValue, intValue, booleanValue, stringValue); }
667
263
930
<no_super_class>
google_gson
gson/metrics/src/main/java/com/google/gson/metrics/CollectionsDeserializationBenchmark.java
CollectionsDeserializationBenchmark
timeCollectionsDefault
class CollectionsDeserializationBenchmark { private static final TypeToken<List<BagOfPrimitives>> LIST_TYPE_TOKEN = new TypeToken<List<BagOfPrimitives>>() {}; private static final Type LIST_TYPE = LIST_TYPE_TOKEN.getType(); private Gson gson; private String json; public static void main(String[] args) { NonUploadingCaliperRunner.run(CollectionsDeserializationBenchmark.class, args); } @BeforeExperiment void setUp() throws Exception { this.gson = new Gson(); List<BagOfPrimitives> bags = new ArrayList<>(); for (int i = 0; i < 100; ++i) { bags.add(new BagOfPrimitives(10L, 1, false, "foo")); } this.json = gson.toJson(bags, LIST_TYPE); } /** Benchmark to measure Gson performance for deserializing an object */ public void timeCollectionsDefault(int reps) {<FILL_FUNCTION_BODY>} /** Benchmark to measure deserializing objects by hand */ @SuppressWarnings("ModifiedButNotUsed") public void timeCollectionsStreaming(int reps) throws IOException { for (int i = 0; i < reps; ++i) { StringReader reader = new StringReader(json); JsonReader jr = new JsonReader(reader); jr.beginArray(); List<BagOfPrimitives> bags = new ArrayList<>(); while (jr.hasNext()) { jr.beginObject(); long longValue = 0; int intValue = 0; boolean booleanValue = false; String stringValue = null; while (jr.hasNext()) { String name = jr.nextName(); if (name.equals("longValue")) { longValue = jr.nextLong(); } else if (name.equals("intValue")) { intValue = jr.nextInt(); } else if (name.equals("booleanValue")) { booleanValue = jr.nextBoolean(); } else if (name.equals("stringValue")) { stringValue = jr.nextString(); } else { throw new IOException("Unexpected name: " + name); } } jr.endObject(); bags.add(new BagOfPrimitives(longValue, intValue, booleanValue, stringValue)); } jr.endArray(); } } /** * This benchmark measures the ideal Gson performance: the cost of parsing a JSON stream and * setting object values by reflection. We should strive to reduce the discrepancy between this * and {@link #timeCollectionsDefault(int)} . */ @SuppressWarnings("ModifiedButNotUsed") public void timeCollectionsReflectionStreaming(int reps) throws Exception { for (int i = 0; i < reps; ++i) { StringReader reader = new StringReader(json); JsonReader jr = new JsonReader(reader); jr.beginArray(); List<BagOfPrimitives> bags = new ArrayList<>(); while (jr.hasNext()) { jr.beginObject(); BagOfPrimitives bag = new BagOfPrimitives(); while (jr.hasNext()) { String name = jr.nextName(); for (Field field : BagOfPrimitives.class.getDeclaredFields()) { if (field.getName().equals(name)) { Class<?> fieldType = field.getType(); if (fieldType.equals(long.class)) { field.setLong(bag, jr.nextLong()); } else if (fieldType.equals(int.class)) { field.setInt(bag, jr.nextInt()); } else if (fieldType.equals(boolean.class)) { field.setBoolean(bag, jr.nextBoolean()); } else if (fieldType.equals(String.class)) { field.set(bag, jr.nextString()); } else { throw new RuntimeException("Unexpected: type: " + fieldType + ", name: " + name); } } } } jr.endObject(); bags.add(bag); } jr.endArray(); } } }
for (int i = 0; i < reps; ++i) { gson.fromJson(json, LIST_TYPE_TOKEN); }
1,107
43
1,150
<no_super_class>