answer
stringlengths
17
10.2M
package mobi.cangol.mobile.security; import android.test.InstrumentationTestCase; public class AESUtilsTest extends InstrumentationTestCase { public void testEncrypt() throws Exception { assertNotNull(AESUtils.encrypt("12345678", "test")); } public void testDecrypt() throws Exception { //assertEquals(AESUtils.decrypt("12345678", AESUtils.encrypt("12345678", "test")), "test"); } public void testToByte() throws Exception { } public void testToHex() throws Exception { } }
package prodocswing.forms; import java.awt.Font; import java.awt.Image; import java.io.File; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.text.DefaultFormatterFactory; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import prodoc.*; import prodocswing.PDTableModel; import prodocswing.TreeFolder; /** * * @author jhierrot */ public class MainWin extends javax.swing.JFrame { static private Font MenuFont=null; static private Font TreeFont=null; static private Font ListFont=null; static private Font DialogFont=null; private static DriverGeneric Session=null; static private DefaultTreeModel FoldTreeModel=null; private static SimpleDateFormat formatterTS = null; private static SimpleDateFormat formatterDate = null; private static DefaultFormatterFactory formFacTS = null; private static DefaultFormatterFactory formFacDate = null; static private String ActFolderId=PDFolders.ROOTFOLDER; static private PDTableModel DocsContained; static private int ExpFolds=0; static private int ExpDocs=0; private PDFolders FoldAct=null; static private String List=PDFolders.fACL+"/"+PDFolders.fFOLDTYPE+"/"+PDFolders.fPARENTID+"/"+PDFolders.fPDID+"/"+PDFolders.fTITLE+"/"+PDFolders.fPDAUTOR+"/"+PDFolders.fPDDATE; static private HashSet ExecFiles=new HashSet(); static private java.awt.Cursor DefCur=new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR); static private final java.awt.Cursor WaitCur=new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR); /** * @return the Session */ public static DriverGeneric getSession() { return Session; } /** Creates new form MainWin */ public MainWin() { initComponents(); TreeFolder.setPreferredSize(null); DocsTable.setAutoCreateRowSorter(true); DocsTable.setAutoCreateColumnsFromModel(true); SetMenu(); } /** 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() { jSplitPane1 = new javax.swing.JSplitPane(); jScrollPane1 = new javax.swing.JScrollPane(); TreeFolder = new javax.swing.JTree(); jSplitPane2 = new javax.swing.JSplitPane(); jScrollPane2 = new javax.swing.JScrollPane(); SelFolderDesc = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); DocsTable = new javax.swing.JTable(); menuBar = new javax.swing.JMenuBar(); FolderMenu = new javax.swing.JMenu(); AddFold = new javax.swing.JMenuItem(); DelFold = new javax.swing.JMenuItem(); ModFold = new javax.swing.JMenuItem(); jSeparator2 = new javax.swing.JPopupMenu.Separator(); AddFoldAdvanced = new javax.swing.JMenuItem(); ModFoldAdvanced = new javax.swing.JMenuItem(); RefreshFold = new javax.swing.JMenuItem(); SearchFold = new javax.swing.JMenuItem(); jSeparator6 = new javax.swing.JPopupMenu.Separator(); ExportFold = new javax.swing.JMenuItem(); ImportFold = new javax.swing.JMenuItem(); ImportExtFold = new javax.swing.JMenuItem(); jSeparator5 = new javax.swing.JPopupMenu.Separator(); exitMenuItem = new javax.swing.JMenuItem(); DocMenu = new javax.swing.JMenu(); AddDoc = new javax.swing.JMenuItem(); DelDoc = new javax.swing.JMenuItem(); jSeparator3 = new javax.swing.JPopupMenu.Separator(); AddDocAdvanced = new javax.swing.JMenuItem(); ModDocAdvanced = new javax.swing.JMenuItem(); ViewMetadata = new javax.swing.JMenuItem(); RefreshDocs = new javax.swing.JMenuItem(); jSeparator4 = new javax.swing.JPopupMenu.Separator(); CheckOut = new javax.swing.JMenuItem(); CheckIn = new javax.swing.JMenuItem(); CancelCheckout = new javax.swing.JMenuItem(); ListVersions = new javax.swing.JMenuItem(); jSeparator1 = new javax.swing.JPopupMenu.Separator(); SearchDocs = new javax.swing.JMenuItem(); ExportDoc = new javax.swing.JMenuItem(); ImportDoc = new javax.swing.JMenuItem(); OtherMenu = new javax.swing.JMenu(); PaperBin = new javax.swing.JMenuItem(); ChangePass = new javax.swing.JMenuItem(); AdminMenu = new javax.swing.JMenu(); ACLMenuItem = new javax.swing.JMenuItem(); GroupMenuItem = new javax.swing.JMenuItem(); UserMenuItem = new javax.swing.JMenuItem(); RolMenuItem = new javax.swing.JMenuItem(); MimeTypeMenuItem = new javax.swing.JMenuItem(); ReposMenuItem = new javax.swing.JMenuItem(); ObjDefMenuItem = new javax.swing.JMenuItem(); AuthentMenuItem = new javax.swing.JMenuItem(); CustomMenuItem = new javax.swing.JMenuItem(); helpMenu = new javax.swing.JMenu(); contentsMenuItem1 = new javax.swing.JMenuItem(); aboutMenuItem1 = new javax.swing.JMenuItem(); ReportBugs = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("OpenProdoc "+getVersion()); setIconImage(getIcon()); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); jSplitPane1.setDividerLocation(180); jSplitPane1.setDividerSize(4); TreeFolder.setFont(getFontTree()); TreeFolder.setModel(getTreeModel()); TreeFolder.setAlignmentX(0.3F); TreeFolder.setAutoscrolls(true); TreeFolder.setComponentPopupMenu(FolderMenu.getComponentPopupMenu()); TreeFolder.setMaximumSize(new java.awt.Dimension(400, 76)); TreeFolder.setMinimumSize(new java.awt.Dimension(200, 60)); TreeFolder.setPreferredSize(new java.awt.Dimension(200, 76)); TreeFolder.addTreeExpansionListener(new javax.swing.event.TreeExpansionListener() { public void treeCollapsed(javax.swing.event.TreeExpansionEvent evt) { } public void treeExpanded(javax.swing.event.TreeExpansionEvent evt) { TreeFolderTreeExpanded(evt); } }); TreeFolder.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() { public void valueChanged(javax.swing.event.TreeSelectionEvent evt) { TreeFolderValueChanged(evt); } }); jScrollPane1.setViewportView(TreeFolder); jSplitPane1.setLeftComponent(jScrollPane1); jSplitPane2.setDividerLocation(160); jSplitPane2.setDividerSize(4); jSplitPane2.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); jScrollPane2.setMinimumSize(new java.awt.Dimension(24, 48)); SelFolderDesc.setFont(getFontMenu()); SelFolderDesc.setVerticalAlignment(javax.swing.SwingConstants.TOP); jScrollPane2.setViewportView(SelFolderDesc); jSplitPane2.setTopComponent(jScrollPane2); DocsTable.setFont(getFontList()); DocsTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); DocsTable.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { DocsTableMouseClicked(evt); } }); jScrollPane3.setViewportView(DocsTable); jSplitPane2.setRightComponent(jScrollPane3); jSplitPane1.setRightComponent(jSplitPane2); menuBar.setFont(getFontMenu()); FolderMenu.setText(TT("Folders")); FolderMenu.setFont(getFontMenu()); AddFold.setFont(getFontMenu()); AddFold.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/add.png"))); // NOI18N AddFold.setText(TT("Add")); AddFold.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AddFoldActionPerformed(evt); } }); FolderMenu.add(AddFold); DelFold.setFont(getFontMenu()); DelFold.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/del.png"))); // NOI18N DelFold.setText(TT("Delete")); DelFold.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DelFoldActionPerformed(evt); } }); FolderMenu.add(DelFold); ModFold.setFont(getFontMenu()); ModFold.setText(TT("Update")); ModFold.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ModFoldActionPerformed(evt); } }); FolderMenu.add(ModFold); FolderMenu.add(jSeparator2); AddFoldAdvanced.setFont(getFontMenu()); AddFoldAdvanced.setText(TT("Extended_Add")); AddFoldAdvanced.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AddFoldAdvancedActionPerformed(evt); } }); FolderMenu.add(AddFoldAdvanced); ModFoldAdvanced.setFont(getFontMenu()); ModFoldAdvanced.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/edit.png"))); // NOI18N ModFoldAdvanced.setText(TT("Update_Extended")); ModFoldAdvanced.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ModFoldAdvancedActionPerformed(evt); } }); FolderMenu.add(ModFoldAdvanced); RefreshFold.setFont(getFontMenu()); RefreshFold.setText(TT("Refresh")); RefreshFold.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RefreshFoldActionPerformed(evt); } }); FolderMenu.add(RefreshFold); SearchFold.setFont(getFontMenu()); SearchFold.setText(TT("Search_Folders")); SearchFold.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SearchFoldActionPerformed(evt); } }); FolderMenu.add(SearchFold); FolderMenu.add(jSeparator6); ExportFold.setFont(getFontMenu()); ExportFold.setText(TT("Export_Folders")); ExportFold.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ExportFoldActionPerformed(evt); } }); FolderMenu.add(ExportFold); ImportFold.setFont(getFontMenu()); ImportFold.setText(TT("Import_Folders")); ImportFold.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ImportFoldActionPerformed(evt); } }); FolderMenu.add(ImportFold); ImportExtFold.setFont(getFontMenu()); ImportExtFold.setText(TT("Import_Ext_Systems")); ImportExtFold.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ImportExtFoldActionPerformed(evt); } }); FolderMenu.add(ImportExtFold); FolderMenu.add(jSeparator5); exitMenuItem.setFont(getFontMenu()); exitMenuItem.setText(TT("Exit")); exitMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitMenuItemActionPerformed(evt); } }); FolderMenu.add(exitMenuItem); menuBar.add(FolderMenu); DocMenu.setText(TT("Documents")); DocMenu.setFont(getFontMenu()); AddDoc.setFont(getFontMenu()); AddDoc.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/add.png"))); // NOI18N AddDoc.setText(TT("Add")); AddDoc.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AddDocActionPerformed(evt); } }); DocMenu.add(AddDoc); DelDoc.setFont(getFontMenu()); DelDoc.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/del.png"))); // NOI18N DelDoc.setText(TT("Delete")); DelDoc.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DelDocActionPerformed(evt); } }); DocMenu.add(DelDoc); DocMenu.add(jSeparator3); AddDocAdvanced.setFont(getFontMenu()); AddDocAdvanced.setText(TT("Extended_Add")); AddDocAdvanced.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AddDocAdvancedActionPerformed(evt); } }); DocMenu.add(AddDocAdvanced); ModDocAdvanced.setFont(getFontMenu()); ModDocAdvanced.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/edit.png"))); // NOI18N ModDocAdvanced.setText(TT("Update_Extended")); ModDocAdvanced.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ModDocAdvancedActionPerformed(evt); } }); DocMenu.add(ModDocAdvanced); ViewMetadata.setFont(getFontMenu()); ViewMetadata.setText(TT("Document_Attributes")); ViewMetadata.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ViewMetadataActionPerformed(evt); } }); DocMenu.add(ViewMetadata); RefreshDocs.setFont(getFontMenu()); RefreshDocs.setText(TT("Refresh")); RefreshDocs.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RefreshDocsActionPerformed(evt); } }); DocMenu.add(RefreshDocs); DocMenu.add(jSeparator4); CheckOut.setFont(getFontMenu()); CheckOut.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/checkout.png"))); // NOI18N CheckOut.setText("CheckOut"); CheckOut.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CheckOutActionPerformed(evt); } }); DocMenu.add(CheckOut); CheckIn.setFont(getFontMenu()); CheckIn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/checkin.png"))); // NOI18N CheckIn.setText("CheckIn"); CheckIn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CheckInActionPerformed(evt); } }); DocMenu.add(CheckIn); CancelCheckout.setFont(getFontMenu()); CancelCheckout.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/cancelcheckout.png"))); // NOI18N CancelCheckout.setText("CancelCheckout"); CancelCheckout.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CancelCheckoutActionPerformed(evt); } }); DocMenu.add(CancelCheckout); ListVersions.setFont(getFontMenu()); ListVersions.setText(TT("List_of_Versions")); ListVersions.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ListVersionsActionPerformed(evt); } }); DocMenu.add(ListVersions); DocMenu.add(jSeparator1); SearchDocs.setFont(getFontMenu()); SearchDocs.setText(TT("Search_Documents")); SearchDocs.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SearchDocsActionPerformed(evt); } }); DocMenu.add(SearchDocs); ExportDoc.setFont(getFontMenu()); ExportDoc.setText(TT("Export_Doc")); ExportDoc.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ExportDocActionPerformed(evt); } }); DocMenu.add(ExportDoc); ImportDoc.setFont(getFontMenu()); ImportDoc.setText(TT("Import_Doc")); ImportDoc.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ImportDocActionPerformed(evt); } }); DocMenu.add(ImportDoc); menuBar.add(DocMenu); OtherMenu.setText(TT("Other_Tasks")); OtherMenu.setFont(getFontMenu()); PaperBin.setFont(getFontMenu()); PaperBin.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/undel.png"))); // NOI18N PaperBin.setText(MainWin.TT("Trash_bin")); PaperBin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { PaperBinActionPerformed(evt); } }); OtherMenu.add(PaperBin); ChangePass.setFont(getFontMenu()); ChangePass.setText(MainWin.TT("Password_change")); ChangePass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ChangePassActionPerformed(evt); } }); OtherMenu.add(ChangePass); menuBar.add(OtherMenu); AdminMenu.setText(TT("Administration")); AdminMenu.setFont(getFontMenu()); ACLMenuItem.setFont(getFontMenu()); ACLMenuItem.setText("ACL"); ACLMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ACLMenuItemActionPerformed(evt); } }); AdminMenu.add(ACLMenuItem); GroupMenuItem.setFont(getFontMenu()); GroupMenuItem.setText(TT("Groups")); GroupMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { GroupMenuItemActionPerformed(evt); } }); AdminMenu.add(GroupMenuItem); UserMenuItem.setFont(getFontMenu()); UserMenuItem.setText(TT("Users")); UserMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { UserMenuItemActionPerformed(evt); } }); AdminMenu.add(UserMenuItem); RolMenuItem.setFont(getFontMenu()); RolMenuItem.setText(TT("Roles")); RolMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RolMenuItemActionPerformed(evt); } }); AdminMenu.add(RolMenuItem); MimeTypeMenuItem.setFont(getFontMenu()); MimeTypeMenuItem.setText(TT("Mime_Types")); MimeTypeMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { MimeTypeMenuItemActionPerformed(evt); } }); AdminMenu.add(MimeTypeMenuItem); ReposMenuItem.setFont(getFontMenu()); ReposMenuItem.setText(TT("Repositories")); ReposMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ReposMenuItemActionPerformed(evt); } }); AdminMenu.add(ReposMenuItem); ObjDefMenuItem.setFont(getFontMenu()); ObjDefMenuItem.setText(TT("Object_definitions")); ObjDefMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ObjDefMenuItemActionPerformed(evt); } }); AdminMenu.add(ObjDefMenuItem); AuthentMenuItem.setFont(getFontMenu()); AuthentMenuItem.setText(TT("Authenticators")); AuthentMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AuthentMenuItemActionPerformed(evt); } }); AdminMenu.add(AuthentMenuItem); CustomMenuItem.setFont(getFontMenu()); CustomMenuItem.setText(TT("Customizations")); CustomMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CustomMenuItemActionPerformed(evt); } }); AdminMenu.add(CustomMenuItem); menuBar.add(AdminMenu); helpMenu.setText(TT("Help")); helpMenu.setFont(getFontMenu()); contentsMenuItem1.setFont(getFontMenu()); contentsMenuItem1.setText(TT("Contents")); contentsMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { contentsMenuItem1ActionPerformed(evt); } }); helpMenu.add(contentsMenuItem1); aboutMenuItem1.setFont(getFontMenu()); aboutMenuItem1.setText(TT("About")); aboutMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { aboutMenuItem1ActionPerformed(evt); } }); helpMenu.add(aboutMenuItem1); ReportBugs.setFont(getFontMenu()); ReportBugs.setText(TT("Reporting_Bugs")); ReportBugs.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ReportBugsActionPerformed(evt); } }); helpMenu.add(ReportBugs); menuBar.add(helpMenu); setJMenuBar(menuBar); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 732, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 572, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed Disconnect(); }//GEN-LAST:event_exitMenuItemActionPerformed private void UserMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_UserMenuItemActionPerformed {//GEN-HEADEREND:event_UserMenuItemActionPerformed try { ListUsers LU = new ListUsers(this, true, new PDUser(getSession())); LU.setLocationRelativeTo(null); LU.setVisible(true); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_UserMenuItemActionPerformed private void formWindowClosing(java.awt.event.WindowEvent evt)//GEN-FIRST:event_formWindowClosing {//GEN-HEADEREND:event_formWindowClosing Disconnect(); }//GEN-LAST:event_formWindowClosing private void MimeTypeMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_MimeTypeMenuItemActionPerformed {//GEN-HEADEREND:event_MimeTypeMenuItemActionPerformed try { ListMimeTypes LMT = new ListMimeTypes(this, true, new PDMimeType(getSession())); LMT.setLocationRelativeTo(null); LMT.setVisible(true); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_MimeTypeMenuItemActionPerformed private void ACLMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_ACLMenuItemActionPerformed {//GEN-HEADEREND:event_ACLMenuItemActionPerformed try { ListAcl LA = new ListAcl(this, true, new PDACL(getSession())); LA.setLocationRelativeTo(null); LA.setVisible(true); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_ACLMenuItemActionPerformed private void GroupMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_GroupMenuItemActionPerformed {//GEN-HEADEREND:event_GroupMenuItemActionPerformed try { ListGroups LG = new ListGroups(this, true, new PDGroups(getSession())); LG.setLocationRelativeTo(null); LG.setVisible(true); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_GroupMenuItemActionPerformed private void RolMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_RolMenuItemActionPerformed {//GEN-HEADEREND:event_RolMenuItemActionPerformed try { ListRoles LR = new ListRoles(this, true, new PDRoles(getSession())); LR.setLocationRelativeTo(null); LR.setVisible(true); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_RolMenuItemActionPerformed private void ReposMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_ReposMenuItemActionPerformed {//GEN-HEADEREND:event_ReposMenuItemActionPerformed try { ListRepositories LR = new ListRepositories(this, true, new PDRepository(getSession())); LR.setLocationRelativeTo(null); LR.setVisible(true); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_ReposMenuItemActionPerformed private void TreeFolderTreeExpanded(javax.swing.event.TreeExpansionEvent evt)//GEN-FIRST:event_TreeFolderTreeExpanded {//GEN-HEADEREND:event_TreeFolderTreeExpanded DefaultMutableTreeNode TreeFold = (DefaultMutableTreeNode) evt.getPath().getLastPathComponent(); if ( ((TreeFolder) TreeFold.getUserObject()).isExpanded()) return; ExpandFold(TreeFold); }//GEN-LAST:event_TreeFolderTreeExpanded private void TreeFolderValueChanged(javax.swing.event.TreeSelectionEvent evt)//GEN-FIRST:event_TreeFolderValueChanged {//GEN-HEADEREND:event_TreeFolderValueChanged try { DefaultMutableTreeNode TreeFold = (DefaultMutableTreeNode) evt.getPath().getLastPathComponent(); FoldAct= ((TreeFolder) TreeFold.getUserObject()).getFold(); SelFolderDesc.setText(HtmlDesc(FoldAct)); ActFolderId=FoldAct.getPDId(); RefreshDocs(); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_TreeFolderValueChanged private void AddFoldActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_AddFoldActionPerformed {//GEN-HEADEREND:event_AddFoldActionPerformed String NewFoldChild=DialogReadString(TT("Add_Folder"),TT("Folder_name"), TT("Write_Folder_name"), null); if (NewFoldChild==null || NewFoldChild.length()==0) return; try { PDFolders Fold=new PDFolders(Session); Fold.setPDId(ActFolderId); Fold.CreateChild(NewFoldChild); TreePath ActualPath = TreeFolder.getSelectionPath(); DefaultMutableTreeNode TreeFold = (DefaultMutableTreeNode) ActualPath.getLastPathComponent(); ExpandFold(TreeFold); TreeFolder.setSelectionPath(ActualPath); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_AddFoldActionPerformed private void DelFoldActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_DelFoldActionPerformed {//GEN-HEADEREND:event_DelFoldActionPerformed try { TreePath selectionPath = TreeFolder.getSelectionPath(); DefaultMutableTreeNode TreeFold = (DefaultMutableTreeNode) selectionPath.getLastPathComponent(); PDFolders Fold= ((TreeFolder) TreeFold.getUserObject()).getFold(); DialogEditFold DEF = new DialogEditFold(this, true); DEF.setLocationRelativeTo(null); DEF.DelMode(); Fold.LoadFull(ActFolderId); DEF.setRecord(Fold.getRecord()); DEF.setVisible(true); if (DEF.isCancel()) return; ActFolderId=Fold.getParentId(); Fold.delete(); TreePath ParentFold = (TreePath) TreeFolder.getSelectionPath().getParentPath(); ExpandFold((DefaultMutableTreeNode)ParentFold.getLastPathComponent()); TreeFolder.setSelectionPath(selectionPath.getParentPath()); TreeFold = (DefaultMutableTreeNode) selectionPath.getParentPath().getLastPathComponent(); FoldAct= ((TreeFolder) TreeFold.getUserObject()).getFold(); SelFolderDesc.setText(HtmlDesc(FoldAct)); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_DelFoldActionPerformed private void AddFoldAdvancedActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_AddFoldAdvancedActionPerformed {//GEN-HEADEREND:event_AddFoldAdvancedActionPerformed try { DialogEditFold DEF = new DialogEditFold(this, true); DEF.setLocationRelativeTo(null); DEF.AddMode(); DEF.setAcl(FoldAct.getACL()); DEF.setVisible(true); if (DEF.isCancel()) return; PDFolders Fold=new PDFolders(Session); Fold.assignValues(DEF.getRecord()); Fold.setParentId(ActFolderId); Fold.insert(); TreePath ActualPath = TreeFolder.getSelectionPath(); ExpandFold((DefaultMutableTreeNode)ActualPath.getLastPathComponent()); TreeFolder.setSelectionPath(ActualPath); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_AddFoldAdvancedActionPerformed private void ModFoldActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_ModFoldActionPerformed {//GEN-HEADEREND:event_ModFoldActionPerformed try { TreePath selectionPath = TreeFolder.getSelectionPath(); DefaultMutableTreeNode TreeFold = (DefaultMutableTreeNode) selectionPath.getLastPathComponent(); PDFolders Fold= ((TreeFolder) TreeFold.getUserObject()).getFold(); String NewTitle=DialogReadString(TT("Update_Folder"),TT("Folder_name"), TT("Write_Folder_name"), Fold.getTitle()); if (NewTitle==null || NewTitle.length()==0) return; Fold.setTitle(NewTitle); Fold.update(); TreePath ParentFold = (TreePath) TreeFolder.getSelectionPath().getParentPath(); ExpandFold((DefaultMutableTreeNode)ParentFold.getLastPathComponent()); TreeFolder.setSelectionPath(selectionPath); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_ModFoldActionPerformed private void ModFoldAdvancedActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_ModFoldAdvancedActionPerformed {//GEN-HEADEREND:event_ModFoldAdvancedActionPerformed try { TreePath selectionPath = TreeFolder.getSelectionPath(); DefaultMutableTreeNode TreeFold = (DefaultMutableTreeNode) selectionPath.getLastPathComponent(); PDFolders Fold= ((TreeFolder) TreeFold.getUserObject()).getFold(); DialogEditFold DEF = new DialogEditFold(this, true); DEF.setLocationRelativeTo(null); DEF.EditMode(); Fold.LoadFull(Fold.getPDId()); DEF.setRecord(Fold.getRecord()); DEF.setVisible(true); if (DEF.isCancel()) return; Fold.assignValues(DEF.getRecord()); Fold.update(); TreePath ParentFold = (TreePath) TreeFolder.getSelectionPath().getParentPath(); ExpandFold((DefaultMutableTreeNode)ParentFold.getLastPathComponent()); TreeFolder.setSelectionPath(selectionPath); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_ModFoldAdvancedActionPerformed private void RefreshFoldActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_RefreshFoldActionPerformed {//GEN-HEADEREND:event_RefreshFoldActionPerformed DefaultMutableTreeNode TreeFold = (DefaultMutableTreeNode) TreeFolder.getSelectionPath().getLastPathComponent(); ExpandFold(TreeFold); }//GEN-LAST:event_RefreshFoldActionPerformed private void ObjDefMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_ObjDefMenuItemActionPerformed {//GEN-HEADEREND:event_ObjDefMenuItemActionPerformed ListObjDef LOD = new ListObjDef(this, true, new PDObjDefs(getSession())); LOD.setLocationRelativeTo(null); LOD.setVisible(true); }//GEN-LAST:event_ObjDefMenuItemActionPerformed private void AddDocActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddDocActionPerformed DialogEditDocReduced MD = new DialogEditDocReduced(this,true); PDDocs Doc; try { Doc = new PDDocs(getSession()); MD.setRecord(Doc.getRecSum()); MD.AddMode(); MD.setLocationRelativeTo(null); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); return; } while (true) { try { MD.setVisible(true); if (MD.isCancel()) return; Doc.assignValues(MD.getRecord()); if (MD.SelFile!=null) Doc.setFile(MD.SelFile.getAbsolutePath()); else throw new PDException("Error_retrieving_file"); Doc.setParentId(ActFolderId); Doc.insert(); RefreshDocs(); return; } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } } }//GEN-LAST:event_AddDocActionPerformed private void DelDocActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DelDocActionPerformed if (DocsTable.getSelectedRow()==-1) return; try { PDDocs Doc = new PDDocs(getSession()); DialogEditDoc MD = new DialogEditDoc(this,true); Doc.assignValues(DocsContained.getElement(DocsTable.convertRowIndexToModel(DocsTable.getSelectedRow()))); Doc.LoadFull(Doc.getPDId()); MD.DelMode(); MD.setRecord(Doc.getRecSum()); MD.setLocationRelativeTo(null); MD.setVisible(true); if (MD.isCancel()) return; Doc.assignValues(MD.getRecord()); Doc.delete(); RefreshDocs(); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_DelDocActionPerformed private void AddDocAdvancedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddDocAdvancedActionPerformed PDDocs Doc; DialogEditDoc MD = new DialogEditDoc(this,true); try { Doc = new PDDocs(getSession()); TreePath selectionPath = TreeFolder.getSelectionPath(); DefaultMutableTreeNode TreeFold = (DefaultMutableTreeNode) selectionPath.getLastPathComponent(); PDFolders Fold= ((TreeFolder) TreeFold.getUserObject()).getFold(); Doc.setACL(Fold.getACL()); MD.setRecord(Doc.getRecSum()); MD.AddMode(); MD.setLocationRelativeTo(null); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); return; } while (true) { try { MD.setVisible(true); if (MD.isCancel()) return; String SelectedType=(String)MD.getRecord().getAttr(PDDocs.fDOCTYPE).getValue(); if (!SelectedType.equalsIgnoreCase(Doc.getDocType())) Doc = new PDDocs(getSession(), SelectedType); Doc.assignValues(MD.getRecord()); if (MD.GetSelectPath()!=null && MD.GetSelectPath().length()>0) Doc.setFile(MD.GetSelectPath()); else throw new PDException("Error_retrieving_file"); Doc.setParentId(ActFolderId); Doc.insert(); RefreshDocs(); return; } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } } }//GEN-LAST:event_AddDocAdvancedActionPerformed private void ModDocAdvancedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ModDocAdvancedActionPerformed if (DocsTable.getSelectedRow()==-1) return; DialogEditDoc MD = new DialogEditDoc(this,true); PDDocs Doc; try { Doc = new PDDocs(getSession()); Doc.assignValues(DocsContained.getElement(DocsTable.convertRowIndexToModel(DocsTable.getSelectedRow()))); Doc.LoadFull(Doc.getPDId()); MD.setRecord(Doc.getRecSum().Copy()); // we need a copy to avoid edition on the same referenced values MD.EditMode(); MD.setLocationRelativeTo(null); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); return; } while (true) { try { MD.setVisible(true); if (MD.isCancel()) return; Doc.assignValues(MD.getRecord()); if (MD.GetSelectPath()!=null && MD.GetSelectPath().length()>0) Doc.setFile(MD.GetSelectPath()); Doc.update(); RefreshDocs(); return; } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } } }//GEN-LAST:event_ModDocAdvancedActionPerformed private void RefreshDocsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RefreshDocsActionPerformed RefreshDocs(); }//GEN-LAST:event_RefreshDocsActionPerformed private void CheckOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CheckOutActionPerformed if (DocsTable.getSelectedRow()==-1) return; try { PDDocs Doc = new PDDocs(getSession()); Doc.assignValues(DocsContained.getElement(DocsTable.convertRowIndexToModel(DocsTable.getSelectedRow()))); Doc.Checkout(); RefreshDocs(); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_CheckOutActionPerformed private void CheckInActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CheckInActionPerformed if (DocsTable.getSelectedRow()==-1) return; try { PDDocs Doc = new PDDocs(getSession()); Doc.assignValues(DocsContained.getElement(DocsTable.convertRowIndexToModel(DocsTable.getSelectedRow()))); String VersionLabel=DialogReadString(TT("Creating_a_new_version_of_document"), TT("Version_identifier"), TT("Type_a_version_name_or_identifier"), ""); if (VersionLabel==null) return; if (VersionLabel.length()==0) { Message(TT("Version_identifier_required")); return; } Doc.Checkin(VersionLabel); RefreshDocs(); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_CheckInActionPerformed private void CancelCheckoutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelCheckoutActionPerformed if (DocsTable.getSelectedRow()==-1) return; try { if (!MessageQuestion(TT("Do_you_want_to_cancel_edition_and_lost_changes"))) return; PDDocs Doc = new PDDocs(getSession()); Doc.assignValues(DocsContained.getElement(DocsTable.convertRowIndexToModel(DocsTable.getSelectedRow()))); Doc.CancelCheckout(); RefreshDocs(); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_CancelCheckoutActionPerformed private void PaperBinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PaperBinActionPerformed ListDeleted LD = new ListDeleted(this, true); LD.setLocationRelativeTo(null); LD.setVisible(true); }//GEN-LAST:event_PaperBinActionPerformed private void ListVersionsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ListVersionsActionPerformed if (DocsTable.getSelectedRow()==-1) return; ListVersions LV = new ListVersions(this, true, DocsContained.getElement(DocsTable.convertRowIndexToModel(DocsTable.getSelectedRow()))); LV.setLocationRelativeTo(null); LV.setVisible(true); }//GEN-LAST:event_ListVersionsActionPerformed private void SearchFoldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SearchFoldActionPerformed SearchFold SF = new SearchFold(this, true); SF.setLocationRelativeTo(null); SF.setFoldAct(ActFolderId); SF.setVisible(true); }//GEN-LAST:event_SearchFoldActionPerformed private void SearchDocsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SearchDocsActionPerformed SearchDocs SD = new SearchDocs(this, true); SD.setLocationRelativeTo(null); SD.setFoldAct(ActFolderId); SD.setVisible(true); }//GEN-LAST:event_SearchDocsActionPerformed private void AuthentMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AuthentMenuItemActionPerformed try { ListAuthenticators LA = new ListAuthenticators(this, true, new PDAuthenticators(getSession())); LA.setLocationRelativeTo(null); LA.setVisible(true); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_AuthentMenuItemActionPerformed private void ChangePassActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_ChangePassActionPerformed {//GEN-HEADEREND:event_ChangePassActionPerformed try { ChangePassword CP = new ChangePassword(this, true); CP.setLocationRelativeTo(null); CP.setVisible(true); if (CP.isCancel()) return; getSession().ChangePassword(getSession().getUser().getName(), CP.getOldPasswordField(), CP.getNewPasswordField1()); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_ChangePassActionPerformed private void CustomMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_CustomMenuItemActionPerformed {//GEN-HEADEREND:event_CustomMenuItemActionPerformed try { ListCustom LC = new ListCustom(this, true, new PDCustomization(getSession())); LC.setLocationRelativeTo(null); LC.setVisible(true); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_CustomMenuItemActionPerformed private void aboutMenuItem1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_aboutMenuItem1ActionPerformed {//GEN-HEADEREND:event_aboutMenuItem1ActionPerformed AboutOPD Ab=new AboutOPD(this, rootPaneCheckingEnabled); Ab.setLocationRelativeTo(null); Ab.setVisible(true); Ab.dispose(); }//GEN-LAST:event_aboutMenuItem1ActionPerformed private void contentsMenuItem1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_contentsMenuItem1ActionPerformed {//GEN-HEADEREND:event_contentsMenuItem1ActionPerformed Execute("doc"+OSSep()+getLang()+OSSep()+"MainWin.html"); }//GEN-LAST:event_contentsMenuItem1ActionPerformed private void DocsTableMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_DocsTableMouseClicked {//GEN-HEADEREND:event_DocsTableMouseClicked if (evt.getClickCount()<2) return; if (DocsTable.getSelectedRow()==-1) return; try { PDDocs Doc = new PDDocs(getSession()); Doc.assignValues(DocsContained.getElement(DocsTable.convertRowIndexToModel(DocsTable.getSelectedRow()))); String FileName; if (Doc.IsUrl()) FileName=Doc.getUrl(); else { FileName=Doc.getFileOpt(getTmp(), false); AddExec(FileName); } Execute(FileName); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_DocsTableMouseClicked private void ExportDocActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_ExportDocActionPerformed {//GEN-HEADEREND:event_ExportDocActionPerformed if (DocsTable.getSelectedRow()==-1) return; try { String FileName=MainWin.SelectFolderDestination(""); if (FileName.length()==0) return; PDDocs Doc = new PDDocs(getSession()); Doc.assignValues(DocsContained.getElement(DocsTable.convertRowIndexToModel(DocsTable.getSelectedRow()))); Doc.ExportXML(FileName, false); } catch (Exception ex) { MainWin.Message(MainWin.DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_ExportDocActionPerformed private void ImportDocActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_ImportDocActionPerformed {//GEN-HEADEREND:event_ImportDocActionPerformed String FileName=MainWin.SelectDestination(null, "opd", false); if (FileName.length()==0) return; try { PDDocs Doc = new PDDocs(getSession()); File FileImp=new File(FileName); getSession().ProcessXML(FileImp, ActFolderId); RefreshDocs(); } catch (Exception ex) { MainWin.Message(MainWin.DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_ImportDocActionPerformed private void ExportFoldActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_ExportFoldActionPerformed {//GEN-HEADEREND:event_ExportFoldActionPerformed try { ExpFolds=0; ExpDocs=0; DialogExportFolders ExpFold = new DialogExportFolders(this,true); ExpFold.setLocationRelativeTo(null); ExpFold.setVisible(true); if (ExpFold.isCancel()) return; setCursor(WaitCur); Export(FoldAct, ExpFold.SelFolder.getAbsolutePath(), ExpFold.IsOneLevel(), ExpFold.IncludeMetadata(), ExpFold.IncludeDocs()); setCursor(DefCur); Message(DrvTT("Exported")+" "+ExpFolds+" "+DrvTT("Folders")+" / "+ExpDocs +" "+DrvTT("Documents")); } catch (Exception ex) { setCursor(DefCur); MainWin.Message(MainWin.DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_ExportFoldActionPerformed private void ImportFoldActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_ImportFoldActionPerformed {//GEN-HEADEREND:event_ImportFoldActionPerformed try { ExpFolds=0; ExpDocs=0; DialogImportFolders ImpFold = new DialogImportFolders(this,true); ImpFold.setLocationRelativeTo(null); ImpFold.setVisible(true); if (ImpFold.isCancel()) return; setCursor(WaitCur); Import(FoldAct, ImpFold.SelFolder.getAbsolutePath(), ImpFold.IsOneLevel(), ImpFold.IncludeMetadata(), ImpFold.IncludeDocs(), ImpFold.FoldType(), ImpFold.DocType()); TreePath ActualPath = TreeFolder.getSelectionPath(); DefaultMutableTreeNode TreeFold = (DefaultMutableTreeNode) ActualPath.getLastPathComponent(); ExpandFold(TreeFold); TreeFolder.setSelectionPath(ActualPath); setCursor(DefCur); Message(DrvTT("Imported")+" "+ExpFolds+" "+DrvTT("Folders")+" / "+ExpDocs +" "+DrvTT("Documents")); } catch (Exception ex) { setCursor(DefCur); MainWin.Message(MainWin.DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_ImportFoldActionPerformed private void ReportBugsActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_ReportBugsActionPerformed {//GEN-HEADEREND:event_ReportBugsActionPerformed Execute("https://docs.google.com/spreadsheet/viewform?formkey%3DdFF6ZndKWXFUQnJ0MWtVZWdUWk10X2c6MQ"); }//GEN-LAST:event_ReportBugsActionPerformed private void ViewMetadataActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_ViewMetadataActionPerformed {//GEN-HEADEREND:event_ViewMetadataActionPerformed if (DocsTable.getSelectedRow()==-1) return; try { PDDocs Doc = new PDDocs(getSession()); DialogEditDoc MD = new DialogEditDoc(this,true); Doc.assignValues(DocsContained.getElement(DocsTable.convertRowIndexToModel(DocsTable.getSelectedRow()))); Doc.LoadFull(Doc.getPDId()); MD.ViewMode(); MD.setRecord(Doc.getRecSum()); MD.setLocationRelativeTo(null); MD.setVisible(true); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_ViewMetadataActionPerformed private void ImportExtFoldActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_ImportExtFoldActionPerformed {//GEN-HEADEREND:event_ImportExtFoldActionPerformed try { ExpFolds=0; ExpDocs=0; DialogImportExtFolders ImpFold = new DialogImportExtFolders(this,true); ImpFold.setLocationRelativeTo(null); ImpFold.setVisible(true); if (ImpFold.isCancel()) return; setCursor(WaitCur); ImportExt(FoldAct, ImpFold.SelFolder.getAbsolutePath(), ImpFold.DeleteAfterImport(), ImpFold.ImpFormat(), ImpFold.DefaultFoldType(), ImpFold.DateFormat(), ImpFold.TimeStampFormat()); TreePath ActualPath = TreeFolder.getSelectionPath(); DefaultMutableTreeNode TreeFold = (DefaultMutableTreeNode) ActualPath.getLastPathComponent(); ExpandFold(TreeFold); TreeFolder.setSelectionPath(ActualPath); setCursor(DefCur); Message(DrvTT("Imported")+" "+ExpFolds+" "+DrvTT("Folders")+" / "+ExpDocs +" "+DrvTT("Documents")); } catch (Exception ex) { setCursor(DefCur); MainWin.Message(MainWin.DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_ImportExtFoldActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { String PropertiesFile; if (args.length==0) PropertiesFile="Prodoc.properties"; // PropertiesFile="e:\\Prodoc\\Varios\\Prodoc_derby.properties"; // PropertiesFile="/media/Iomega/Prodoc/ProdocInstall/dist/Prodoc.properties"; // PropertiesFile="/media/Iomega/Prodoc/Varios/Prodoc_derby.properties"; else PropertiesFile=args[0]; if (!Connect(PropertiesFile)) System.exit(0); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { MainWin MW=new MainWin(); MW.setLocationRelativeTo(null); MW.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JMenuItem ACLMenuItem; private javax.swing.JMenuItem AddDoc; private javax.swing.JMenuItem AddDocAdvanced; private javax.swing.JMenuItem AddFold; private javax.swing.JMenuItem AddFoldAdvanced; private javax.swing.JMenu AdminMenu; private javax.swing.JMenuItem AuthentMenuItem; private javax.swing.JMenuItem CancelCheckout; private javax.swing.JMenuItem ChangePass; private javax.swing.JMenuItem CheckIn; private javax.swing.JMenuItem CheckOut; private javax.swing.JMenuItem CustomMenuItem; private javax.swing.JMenuItem DelDoc; private javax.swing.JMenuItem DelFold; private javax.swing.JMenu DocMenu; private javax.swing.JTable DocsTable; private javax.swing.JMenuItem ExportDoc; private javax.swing.JMenuItem ExportFold; private javax.swing.JMenu FolderMenu; private javax.swing.JMenuItem GroupMenuItem; private javax.swing.JMenuItem ImportDoc; private javax.swing.JMenuItem ImportExtFold; private javax.swing.JMenuItem ImportFold; private javax.swing.JMenuItem ListVersions; private javax.swing.JMenuItem MimeTypeMenuItem; private javax.swing.JMenuItem ModDocAdvanced; private javax.swing.JMenuItem ModFold; private javax.swing.JMenuItem ModFoldAdvanced; private javax.swing.JMenuItem ObjDefMenuItem; private javax.swing.JMenu OtherMenu; private javax.swing.JMenuItem PaperBin; private javax.swing.JMenuItem RefreshDocs; private javax.swing.JMenuItem RefreshFold; private javax.swing.JMenuItem ReportBugs; private javax.swing.JMenuItem ReposMenuItem; private javax.swing.JMenuItem RolMenuItem; private javax.swing.JMenuItem SearchDocs; private javax.swing.JMenuItem SearchFold; private javax.swing.JLabel SelFolderDesc; private javax.swing.JTree TreeFolder; private javax.swing.JMenuItem UserMenuItem; private javax.swing.JMenuItem ViewMetadata; private javax.swing.JMenuItem aboutMenuItem1; private javax.swing.JMenuItem contentsMenuItem1; private javax.swing.JMenuItem exitMenuItem; private javax.swing.JMenu helpMenu; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JPopupMenu.Separator jSeparator1; private javax.swing.JPopupMenu.Separator jSeparator2; private javax.swing.JPopupMenu.Separator jSeparator3; private javax.swing.JPopupMenu.Separator jSeparator4; private javax.swing.JPopupMenu.Separator jSeparator5; private javax.swing.JPopupMenu.Separator jSeparator6; private javax.swing.JSplitPane jSplitPane1; private javax.swing.JSplitPane jSplitPane2; private javax.swing.JMenuBar menuBar; // End of variables declaration//GEN-END:variables private static void EvaluateDef() { try { String FontDef=getSession().getUser().getCustomData().getSwingStyle(); String ListF[]=FontDef.split(","); MenuFont =new java.awt.Font(ListF[0], Integer.parseInt(ListF[1]), Integer.parseInt(ListF[2])); TreeFont =new java.awt.Font(ListF[3], Integer.parseInt(ListF[4]), Integer.parseInt(ListF[5])); ListFont =new java.awt.Font(ListF[6], Integer.parseInt(ListF[7]), Integer.parseInt(ListF[8])); DialogFont=new java.awt.Font(ListF[9], Integer.parseInt(ListF[10]), Integer.parseInt(ListF[11])); } catch (Exception ex) { MenuFont=new java.awt.Font("Arial", 0, 12); TreeFont=new java.awt.Font("Arial", 0, 12); ListFont=new java.awt.Font("Arial", 0, 12); DialogFont=new java.awt.Font("Arial", 0, 12); } } /** * * @return */ static public Font getFontMenu() { if (MenuFont==null) EvaluateDef(); return (MenuFont); } /** * * @return */ static public Font getFontTree() { if (TreeFont==null) EvaluateDef(); return (TreeFont); } /** * * @return */ static public Font getFontList() { if (ListFont==null) EvaluateDef(); return (ListFont); } /** * * @return */ static public Font getFontDialog() { if (DialogFont==null) EvaluateDef(); return (DialogFont); } private PDTableModel getTableModel() { return new PDTableModel(); } static private boolean Connect(String PropertiesFile) { LoginForm dialog = new LoginForm(new javax.swing.JFrame(), true); dialog.setLocationRelativeTo(null); for (int NumRetry = 0; NumRetry < 3; NumRetry++) { dialog.setVisible(true); if (dialog.getReturnStatus() == LoginForm.RET_CANCEL) return false; try { ProdocFW.InitProdoc("PD", PropertiesFile); Session = ProdocFW.getSession("PD", dialog.getLogin(), dialog.getPass()); return(true); } catch (PDException ex) { Message(DrvTT(ex.getLocalizedMessage())); } } return false; } static private void Disconnect() { try { if (getSession()!=null) { ProdocFW.freeSesion("PD", getSession()); } ProdocFW.ShutdownProdoc("PD"); } catch (PDException ex) { Message(DrvTT(ex.getLocalizedMessage())); } DestroyExec(); System.exit(0); } /** * * @param pMessage */ static public void Message(String pMessage) { DialogInfo DI=new DialogInfo(null, true); DI.SetMessage(DrvTT(pMessage)); DI.setLocationRelativeTo(null); DI.setVisible(true); } /** * * @param pMessage to show to the user * @return if the user selects OK */ static public boolean MessageQuestion(String pMessage) { DialogInfoQuestion DI=new DialogInfoQuestion(null, true); DI.SetMessage(DrvTT(pMessage)); DI.setLocationRelativeTo(null); DI.setVisible( true); return (DI.getReturnStatus()==DialogInfoQuestion.RET_OK); } /** * * @param RecomFileName * @param Ext * @param Save * @return */ static public String SelectDestination(String RecomFileName, String Ext, boolean Save) { JFileChooser fc = new JFileChooser(); //fc.setDialogTitle("Seleccionar Archivo"); if (Ext!=null) fc.setFileFilter(new FileNameExtensionFilter("file "+Ext, Ext)); if (RecomFileName!=null) fc.setSelectedFile(new File(RecomFileName)); if (!Save) { if (fc.showOpenDialog(null)!=JFileChooser.APPROVE_OPTION) return(""); } else { if (fc.showSaveDialog(null)!=JFileChooser.APPROVE_OPTION) return(""); } return(fc.getSelectedFile().getAbsolutePath()); } /** * * @param RecomFileName * @return */ static public String SelectFolderDestination(String RecomFileName) { JFileChooser fc = new JFileChooser(); if (RecomFileName!=null) fc.setSelectedFile(new File(RecomFileName)); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (fc.showSaveDialog(null)!=JFileChooser.APPROVE_OPTION) return(""); return(fc.getSelectedFile().getAbsolutePath()); } private TreeModel getTreeModel() { if (FoldTreeModel==null) { PDFolders RootFolder=null; try { RootFolder = new PDFolders(Session); RootFolder.Load(PDFolders.ROOTFOLDER); TreeFolder TF=new TreeFolder(RootFolder); DefaultMutableTreeNode RootTreeFolder = new DefaultMutableTreeNode(TF); FoldTreeModel=new DefaultTreeModel(RootTreeFolder); ExpandFold(RootTreeFolder); } catch (PDException ex) { Message(DrvTT(ex.getLocalizedMessage())); return(null); } } return(FoldTreeModel); } private void ExpandFold(DefaultMutableTreeNode ChildTreeFolder) { try { ChildTreeFolder.removeAllChildren(); PDFolders Fold= ((TreeFolder) ChildTreeFolder.getUserObject()).getFold(); HashSet Child =Fold.getListDirectDescendList(Fold.getPDId()); for (Iterator it = Child.iterator(); it.hasNext();) { String ChildId=(String)it.next(); if (ChildId.compareTo(Fold.getPDId())==0) continue; PDFolders ChildFolder=new PDFolders(Session); ChildFolder.LoadFull(ChildId); TreeFolder TFc=new TreeFolder(ChildFolder); DefaultMutableTreeNode ChildTreeFolder2=new DefaultMutableTreeNode(TFc); DefaultMutableTreeNode ChildTreeFolder3=new DefaultMutableTreeNode(null); ChildTreeFolder2.add(ChildTreeFolder3); ChildTreeFolder.add(ChildTreeFolder2); } (((TreeFolder) ChildTreeFolder.getUserObject())).setExpanded(true); FoldTreeModel.reload(ChildTreeFolder); TreeFolder.setPreferredSize(null); } catch (PDException ex) { Message(DrvTT(ex.getLocalizedMessage())); } } static private String FormatDate(Date d) { return( getFormatterTS().format(d)); } /** * * @param Title * @param FieldName * @param ToolTip * @param FieldText * @return */ static public String DialogReadString(String Title, String FieldName, String ToolTip, String FieldText) { DialogReadString dialog = new DialogReadString(new javax.swing.JFrame(), true); dialog.setLocationRelativeTo(null); dialog.SetVals(Title, FieldName, ToolTip, FieldText); dialog.setVisible(true); if (dialog.getReturnStatus() == DialogReadString.RET_CANCEL) return null; else return(dialog.getField()); } static private Image getIcon() { ImageIcon PDIcon=new ImageIcon("resources/LogoProdoc.jpg"); return PDIcon.getImage(); } /** * Refresh the list of documents * called after changing folder or adding, modifying or deleting a document */ private void RefreshDocs() { try { DocsContained = new PDTableModel(); DocsContained.setDrv(MainWin.getSession()); FoldAct.getListDirectDescendList(ActFolderId); PDDocs Doc = new PDDocs(getSession()); DocsContained.setListFields(Doc.getRecordStruct()); DocsContained.setCursor(Doc.getListContainedDocs(FoldAct.getPDId())); DocsTable.setModel(DocsContained); DocsTable.getColumnModel().removeColumn(DocsTable.getColumnModel().getColumn(13)); DocsTable.getColumnModel().removeColumn(DocsTable.getColumnModel().getColumn(12)); DocsTable.getColumnModel().removeColumn(DocsTable.getColumnModel().getColumn(11)); DocsTable.getColumnModel().removeColumn(DocsTable.getColumnModel().getColumn(10)); DocsTable.getColumnModel().removeColumn(DocsTable.getColumnModel().getColumn(9)); DocsTable.getColumnModel().removeColumn(DocsTable.getColumnModel().getColumn(8)); DocsTable.getColumnModel().removeColumn(DocsTable.getColumnModel().getColumn(7)); DocsTable.getColumnModel().removeColumn(DocsTable.getColumnModel().getColumn(6)); DocsTable.getColumnModel().removeColumn(DocsTable.getColumnModel().getColumn(5)); DocsTable.getColumnModel().removeColumn(DocsTable.getColumnModel().getColumn(0)); // 0 4 5 7 8 9 10 11 12 } catch (PDException ex) { Message(DrvTT(ex.getLocalizedMessage())); } } static int Execute(String Doc) { try { //String Order=""; String Orders[]= {"xdg-open", Doc}; String OS=System.getProperty("os.name"); if (OS.contains("Win")) Orders[0]="explorer"; else if (OS.contains("OS X") || OS.contains("Mac")) Orders[0]="open"; Runtime.getRuntime().exec(Orders); } catch (Exception ex) { Message(ex.getLocalizedMessage()); } return(0); } private String HtmlDesc(PDFolders FoldAct) throws PDException { StringBuilder Html=new StringBuilder("<html><b>"+FoldAct.getTitle()+"</b> ("+FoldAct.getFolderType() +") : "+FormatDate(FoldAct.getPDDate())+ "<hr> ACL="+FoldAct.getACL()); Record Rec=FoldAct.getRecSum(); Rec.initList(); Attribute Attr=Rec.nextAttr(); while (Attr!=null) { if (!List.contains(Attr.getName())) { Html.append("<br><b>").append(DrvTT(Attr.getUserName())).append("= </b>"); Html.append(Attr.Export()); } Attr=Rec.nextAttr(); } Html.append("</html>"); return(Html.toString()); } /** * * @param Text * @return */ static public String DrvTT(String Text) { if (getSession()==null) return( DriverGeneric.DefTT(Text) ); else return( getSession().TT(Text) ); } /** * * @param Text * @return */ static public String TT(String Text) { if (getSession()==null) return( DriverGeneric.DefTT(Text) ); else return( getSession().TT(Text) ); } /** * @return the formatterTS */ public static SimpleDateFormat getFormatterTS() { if (formatterTS==null) { try { formatterTS = new SimpleDateFormat(getSession().getPDCust().getTimeFormat()); } catch (PDException ex) { formatterTS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } } return formatterTS; } /** * @return the formatterDate */ public static SimpleDateFormat getFormatterDate() { if (formatterDate==null) { try { formatterDate = new SimpleDateFormat(getSession().getPDCust().getDateFormat()); } catch (PDException ex) { formatterDate = new SimpleDateFormat("yyyy-MM-dd"); } } return formatterDate; } /** * @return the formatTS */ public static String getFormatTS() { try { return (getSession().getPDCust().getTimeFormat() ); } catch (PDException ex) { return("yyyy-MM-dd HH:mm:ss"); } } /** * @return the formatDate */ public static String getFormatDate() { try { return(getSession().getPDCust().getDateFormat()); } catch (PDException ex) { return("yyyy-MM-dd"); } } /** * @return the formFacTS * @throws Exception */ public static DefaultFormatterFactory getFormFacTS() throws Exception { if (formFacTS==null) { // formFacTS = new DefaultFormatterFactory(new MaskFormatter(MainWin.getFormatTS())); formFacTS = new DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat((MainWin.getFormatTS())))); } return formFacTS; } /** * @return the formFacDate * @throws Exception */ public static DefaultFormatterFactory getFormFacDate() throws Exception { if (formFacDate==null) { // formFacDate = new DefaultFormatterFactory(new MaskFormatter(MainWin.getFormatDate())); formFacDate = new DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat((MainWin.getFormatDate())))); } return formFacDate; } private String getLang() { try { return(getSession().getPDCust().getLanguage()); } catch (PDException ex) { return("EN"); } } private String OSSep() { return(File.separator); } static public String getTmp() { String Tmp=System.getProperty("java.io.tmpdir"); return(Tmp); } /** * Used in mainWin.title and About form * @return the actual ProdocSwing Version */ static public String getVersion() { return("0.7"); } /** * * @param FoldAct OPD Folder to start exporting * @param SelFile Destination Folder to export * @param IsOneLevel When tru, the OPD folder and contained Docs (if IncDocs), are exported * @param IncMetadata when true, include metadata in the export * @param IncDocs when true, include docs in the export */ private void Export(PDFolders FoldAct, String SelFolder, boolean IsOneLevel, boolean IncMetadata, boolean IncDocs) throws Exception { String Destpath=SelFolder+File.separatorChar; File SOFolder=new File(Destpath+FoldAct.getTitle()); SOFolder.mkdir(); ExpFolds++; if (IncMetadata) { PrintWriter PW = new PrintWriter(Destpath+FoldAct.getTitle()+".opd"); PW.print(FoldAct.StartXML()); PW.print(FoldAct.toXML()); PW.print(FoldAct.EndXML()); PW.flush(); PW.close(); } if (IncDocs) { PDDocs Doc = new PDDocs(FoldAct.getDrv()); Cursor ListDocs=Doc.getListContainedDocs(FoldAct.getPDId()); Record Res=FoldAct.getDrv().NextRec(ListDocs); PDDocs ExpDoc=new PDDocs(FoldAct.getDrv()); while (Res!=null) { ExpDoc.assignValues(Res); ExpDoc.ExportXML(SOFolder.getAbsolutePath(), false); ExpDocs++; Res=FoldAct.getDrv().NextRec(ListDocs); } FoldAct.getDrv().CloseCursor(ListDocs); } if (!IsOneLevel) { HashSet ListFolder = FoldAct.getListDirectDescendList(FoldAct.getPDId()); PDFolders ChildFold=new PDFolders(FoldAct.getDrv()); for (Iterator it = ListFolder.iterator(); it.hasNext();) { String ChildId=(String)it.next(); ChildFold.LoadFull(ChildId); Export(ChildFold, SOFolder.getAbsolutePath(), IsOneLevel, IncMetadata, IncDocs); } } } private void Import(PDFolders FoldAct, String OriginPath, boolean IsOneLevel, boolean IncludeMetadata, boolean IncludeDocs, String FoldType, String DocType) throws PDException { PDFolders NewFold=new PDFolders(FoldAct.getDrv(), FoldType); if (IncludeMetadata) { NewFold=NewFold.ProcessXML(new File(OriginPath+".opd"), FoldAct.getPDId()); } else { String Name=OriginPath.substring(OriginPath.lastIndexOf(File.separatorChar)+1); NewFold.setTitle(Name); NewFold.setParentId(FoldAct.getPDId()); NewFold.insert(); } ExpFolds++; File ImpFold=new File(OriginPath); File []ListOrigin=ImpFold.listFiles(); ArrayList DirList=new ArrayList(5); for (int i = 0; i < ListOrigin.length; i++) { File ListElement = ListOrigin[i]; if (ListElement.isDirectory()) { if (!IsOneLevel) DirList.add(ListElement); continue; } if (IncludeDocs) { if (ListElement.getName().endsWith(".opd")) { if (IncludeMetadata) { ExpDocs+=getSession().ProcessXML(ListElement, NewFold.getPDId()); } } else { if (!IncludeMetadata) { PDDocs NewDoc=new PDDocs(FoldAct.getDrv(), DocType); NewDoc.setTitle(ListElement.getName()); NewDoc.setFile(ListElement.getAbsolutePath()); NewDoc.setDocDate(new Date(ListElement.lastModified())); NewDoc.setParentId(NewFold.getPDId()); NewDoc.insert(); ExpDocs++; } } } } ListOrigin=null; // to help gc and save memory during recursivity for (int i = 0; i < DirList.size(); i++) { File SubDir = (File) DirList.get(i); Import(NewFold, SubDir.getAbsolutePath(), IsOneLevel, IncludeMetadata, IncludeDocs, FoldType, DocType); } } private void ImportExt(PDFolders FoldAct, String OriginPath, boolean DeleteAfter, String Format, String DefFoldType, String DateFormat, String TimeStampFormat) throws PDException { PDFolders NewFold=new PDFolders(FoldAct.getDrv(), DefFoldType); HashSet ChildF=NewFold.getListDirectDescendList(FoldAct.getPDId()); String Name=OriginPath.substring(OriginPath.lastIndexOf(File.separatorChar)+1); try { String IdFold=NewFold.GetIdChild(FoldAct.getPDId(), Name); NewFold.Load(IdFold); } catch( PDException ex) { NewFold.setTitle(Name); NewFold.setParentId(FoldAct.getPDId()); NewFold.insert(); } ExpFolds++; File ImpFold=new File(OriginPath); File []ListOrigin=ImpFold.listFiles(); ArrayList DirList=new ArrayList(5); File ImageFile=null; for (int i = 0; i < ListOrigin.length; i++) { File ListElement = ListOrigin[i]; if (ListElement.isDirectory()) { DirList.add(ListElement); continue; } if (ListElement.getName().endsWith(".xml")) { ExpDocs++; if (Format.equals("Abby")) ImageFile=PDDocs.ProcessXMLAbby(getSession(), ListElement, NewFold.getPDId(), DateFormat, TimeStampFormat); // else // kofax if (DeleteAfter) { if (ImageFile!=null) ImageFile.delete(); ListElement.delete(); } } } ListOrigin=null; // to help gc and save memory during recursivity for (int i = 0; i < DirList.size(); i++) { File SubDir = (File) DirList.get(i); ImportExt(NewFold, SubDir.getAbsolutePath(), DeleteAfter, Format, DefFoldType, DateFormat, TimeStampFormat); if (DeleteAfter) SubDir.delete(); } } static protected void AddExec(String FileName) { ExecFiles.add(FileName); File f=new File(FileName); f.setReadOnly(); } static private void DestroyExec() { for (Iterator it = ExecFiles.iterator(); it.hasNext();) { try { String FileName = (String)it.next(); File f=new File(FileName); f.setWritable(true); f.delete(); } catch (Exception ex) { } } } private void SetMenu() { try { PDRoles R=MainWin.getSession().getUser().getRol(); ACLMenuItem.setVisible(R.isAllowCreateAcl() || R.isAllowMaintainAcl()); AuthentMenuItem.setVisible(R.isAllowCreateAuth() || R.isAllowMaintainAuth()); CustomMenuItem.setVisible(R.isAllowCreateCustom() || R.isAllowMaintainCustom()); GroupMenuItem.setVisible(R.isAllowCreateGroup() || R.isAllowMaintainGroup()); MimeTypeMenuItem.setVisible(R.isAllowCreateMime() || R.isAllowMaintainMime()); ObjDefMenuItem.setVisible(R.isAllowCreateObject() || R.isAllowMaintainObject()); ReposMenuItem.setVisible(R.isAllowCreateRepos() || R.isAllowMaintainRepos()); RolMenuItem.setVisible(R.isAllowCreateRole() || R.isAllowMaintainRole()); UserMenuItem.setVisible(R.isAllowCreateUser() || R.isAllowMaintainUser()); AddFold.setVisible(R.isAllowCreateFolder()); AddFoldAdvanced.setVisible(R.isAllowCreateFolder()); ImportFold.setVisible(R.isAllowCreateFolder()); ModFold.setVisible(R.isAllowMaintainFolder()); ModFoldAdvanced.setVisible(R.isAllowMaintainFolder()); DelFold.setVisible(R.isAllowMaintainFolder()); AddDoc.setVisible(R.isAllowCreateDoc()); AddDocAdvanced.setVisible(R.isAllowCreateDoc()); ImportDoc.setVisible(R.isAllowCreateDoc()); PaperBin.setVisible(R.isAllowCreateDoc() && R.isAllowMaintainDoc()); ModDocAdvanced.setVisible(R.isAllowMaintainDoc()); CheckOut.setVisible(R.isAllowMaintainDoc()); CancelCheckout.setVisible(R.isAllowMaintainDoc()); CheckIn.setVisible(R.isAllowMaintainDoc()); CheckOut.setVisible(R.isAllowMaintainDoc()); DelDoc.setVisible(R.isAllowMaintainDoc()); } catch (Exception ex) { Message(ex.getLocalizedMessage()); } } }
package org.intermine.bio.dataconversion; import java.io.IOException; import java.io.Reader; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.intermine.util.FormattedTextParser; /** * Parse NCBI Entrez gene_info file and return data structure for each row for later processing. * @author Richard Smith * */ public class NcbiGeneInfoParser { private Map<String, Set<GeneInfoRecord>> recordMap = new HashMap<String, Set<GeneInfoRecord>>(); private Map<String, Set<String>> duplicateEnsemblIds = new HashMap<String, Set<String>>(); private Map<String, Set<String>> duplicateSymbols = new HashMap<String, Set<String>>(); /** * Construct the parser with the file to read, the input file can be for a single taxon or for * multiple. * @param reader a reader for the gene_info file to be parsed * @throws IOException if problems reading file */ public NcbiGeneInfoParser(Reader reader) throws IOException { Iterator<String[]> lineIter = FormattedTextParser.parseTabDelimitedReader(reader); while (lineIter.hasNext()) { String[] line = lineIter.next(); String taxonId = line[0]; String entrez = line[1]; String defaultSymbol = line[2]; String synonyms = line[4]; String xrefs = line[5]; String mapLocation = line[7]; String defaultName = line[8]; String officialSymbol = line[10]; String officialName = line[11]; GeneInfoRecord record = new GeneInfoRecord(taxonId, entrez, officialSymbol, defaultSymbol, officialName, defaultName, mapLocation); record.ensemblIds.addAll(parseXrefs(xrefs, "Ensembl")); for (String synonym : synonyms.split("\\|")) { record.synonyms.add(synonym); } Set<GeneInfoRecord> taxonRecords = recordMap.get(taxonId); if (taxonRecords == null) { taxonRecords = new HashSet<GeneInfoRecord>(); recordMap.put(taxonId, taxonRecords); } taxonRecords.add(record); } } /** * Return information read from the file, for each taxon id there is one GeneInfoRecord per row * in the file. * @return a map from taxon id to gene information records */ public Map<String, Set<GeneInfoRecord>> getGeneInfoRecords() { return recordMap; } /** * Return true if the given Ensembl identifier is assigned to only one gene for the taxon * specified. * @param taxonId the taxon of the gene being looked up * @param ensemblId an ensembl gene identifier * @return true if this ensembl id is only mapped to one NCBI gene */ public boolean isUniquelyMappedEnsemblId(String taxonId, String ensemblId) { Set<String> taxonDuplicates = duplicateEnsemblIds.get(taxonId); if (taxonDuplicates == null) { taxonDuplicates = findDuplicateEnsemblIds(taxonId); duplicateEnsemblIds.put(taxonId, taxonDuplicates); } return !taxonDuplicates.contains(ensemblId); } private Set<String> findDuplicateEnsemblIds(String taxonId) { Set<String> duplicates = new HashSet<String>(); if (recordMap.containsKey(taxonId)) { Set<String> seenEnsembl = new HashSet<String>(); for (GeneInfoRecord record : recordMap.get(taxonId)) { for (String ensembl : record.ensemblIds) { if (seenEnsembl.contains(ensembl)) { duplicates.add(ensembl); } else { seenEnsembl.add(ensembl); } } } } return duplicates; } /** * Return true if the given symbol is is assigned to only one gene for the taxon specified. * @param taxonId the taxon of the gene being looked up * @param symbol a gene symbl to check * @return true if this true id is only assigned to one NCBI gene */ public boolean isUniqueSymbol(String taxonId, String symbol) { Set<String> taxonDuplicates = duplicateSymbols.get(taxonId); if (taxonDuplicates == null) { taxonDuplicates = findDuplicateSymbols(taxonId); duplicateSymbols.put(taxonId, taxonDuplicates); } return !taxonDuplicates.contains(symbol); } public Set<String> findDuplicateSymbols(String taxonId) { Set<String> duplicates = new HashSet<String>(); if (recordMap.containsKey(taxonId)) { Set<String> seenSymbols = new HashSet<String>(); for (GeneInfoRecord record : recordMap.get(taxonId)) { for (String symbol : new String[] {record.officialSymbol, record.defaultSymbol}) { if (seenSymbols.contains(symbol)) { duplicates.add(symbol); } else { seenSymbols.add(symbol); } } } } return duplicates; } private Set<String> parseXrefs(String xrefs, String prefix) { if (!prefix.endsWith(":")) { prefix = prefix + ":"; } Set<String> matched = new HashSet<String>(); for (String xref : xrefs.split("\\|")) { if (xref.startsWith(prefix)) { matched.add(xref.substring(prefix.length())); } } return matched; } }
package polyglot.ext.jl.ast; import polyglot.ast.*; import polyglot.types.*; import polyglot.visit.*; import polyglot.util.*; import java.util.*; /** * A <code>AmbAssign</code> represents a Java assignment expression to * an as yet unknown expression. */ public class AmbAssign_c extends Assign_c implements AmbAssign { public AmbAssign_c(Position pos, Expr left, Operator op, Expr right) { super(pos, left, op, right); } public Term entry() { if (operator() != Assign.ASSIGN) { return left(); } return right().entry(); } protected void acceptCFGAssign(CFGBuilder v) { v.visitCFG(right(), this); } protected void acceptCFGOpAssign(CFGBuilder v) { v.edge(left(), right().entry()); v.visitCFG(right(), this); } public Node disambiguate(AmbiguityRemover ar) throws SemanticException { Assign n = (Assign)super.disambiguate(ar); if (n.left() instanceof Local) { return ar.nodeFactory().LocalAssign(n.position(), (Local)left(), operator(), right()); } else if (n.left() instanceof Field) { return ar.nodeFactory().FieldAssign(n.position(), (Field)left(), operator(), right()); } else if (n.left() instanceof ArrayAccess) { return ar.nodeFactory().ArrayAccessAssign(n.position(), (ArrayAccess)left(), operator(), right()); } new Exception().printStackTrace(); throw new SemanticException("Could not disambiguate left side of assignment!", n.position()); } }
package org.intermine.bio.web.logic; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringReader; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.apache.struts.action.ActionMessage; import org.apache.struts.upload.FormFile; import org.intermine.api.InterMineAPI; import org.intermine.api.profile.Profile; import org.intermine.bio.web.model.ChromosomeInfo; import org.intermine.bio.web.model.GenomicRegion; import org.intermine.bio.web.model.GenomicRegionSearchConstraint; import org.intermine.bio.web.struts.GenomicRegionSearchForm; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.Model; import org.intermine.model.bio.Organism; import org.intermine.model.bio.SequenceFeature; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.objectstore.query.ConstraintSet; import org.intermine.objectstore.query.ContainsConstraint; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.QueryField; import org.intermine.objectstore.query.QueryObjectReference; import org.intermine.objectstore.query.Results; import org.intermine.objectstore.query.ResultsRow; import org.intermine.pathquery.Constraints; import org.intermine.pathquery.PathQuery; import org.intermine.util.StringUtil; import org.intermine.web.logic.WebUtil; import org.intermine.web.logic.config.WebConfig; import org.intermine.web.logic.session.SessionMethods; import org.json.JSONObject; /** * A class to provide genomic region search services in general. * * @author Fengyuan Hu */ public class GenomicRegionSearchService { @SuppressWarnings("unused") private static final Logger LOG = Logger .getLogger(GenomicRegionSearchService.class); private InterMineAPI interMineAPI = null; private Model model = null; private ObjectStore objectStore = null; private Properties webProperties = null; private Profile profile = null; private WebConfig webConfig = null; private static String orgFeatureJSONString = ""; private static final String GENOMIC_REGION_SEARCH_OPTIONS_DEFAULT = "genomic_region_search_options_default"; private static final String GENOMIC_REGION_SEARCH_RESULTS_DEFAULT = "genomic_region_search_results_default"; private static final int READ_AHEAD_CHARS = 10000; private GenomicRegionSearchConstraint grsc = null; // Key - organism : Value - map <key - chr : value - chromosome information> private static Map<String, Map<String, ChromosomeInfo>> chrInfoMap = null; private static Set<String> featureTypesInOrgs = null; private static Map<String, List<String>> featureTypeToSOTermMap = null; private static Map<String, Integer> orgTaxonIdMap = null; private List<String> selectionInfo = new ArrayList<String>(); /** * Constructor */ public GenomicRegionSearchService() { } /** * To set globally used variables. * @param request HttpServletRequest */ public void init (HttpServletRequest request) { this.webProperties = SessionMethods.getWebProperties( request.getSession().getServletContext()); this.webConfig = SessionMethods.getWebConfig(request); this.interMineAPI = SessionMethods.getInterMineAPI(request.getSession()); this.profile = SessionMethods.getProfile(request.getSession()); this.model = this.interMineAPI.getModel(); this.objectStore = this.interMineAPI.getObjectStore(); } /** * To call the queryOrganismAndSequenceFeatureTypes method in * GenomicRegionSearchQueryRunner. * * @return a JSON string * @throws Exception e */ public String setupWebData() throws Exception { // By default, query all organisms in the database // pre defined organism short names can be read out from web.properties String presetOrganisms = webProperties.getProperty( "genomicRegionSearch.defaultOrganisms"); List<String> orgList = new ArrayList<String>(); Set<String> chrOrgSet = getChromosomeInfomationMap().keySet(); if (chrOrgSet == null || chrOrgSet.size() == 0) { throw new RuntimeException( "Chromosome location information is missing..."); } else { if (presetOrganisms == null || "".equals(presetOrganisms)) { orgList = new ArrayList<String>(chrOrgSet); } else { // e.g. presetCollection [f,b,a], orgFromDBCollection [g,a,e,f] // results => [f,a] + [e,g] = [f,a,e,g] // some items in preset organisms will be removed if chro information not available List<String> presetOrgList = Arrays.asList(presetOrganisms .split(",")); List<String> trimedPresetOrgList = new ArrayList<String>(); for (String s : presetOrgList) { if (!"".equals(s.trim())) { trimedPresetOrgList.add(s.trim()); } } // Don't remove any items from chrOrgSet, just make a copy Set<String> chrOrgSetCopy = new TreeSet<String>(); for (String s : chrOrgSet) { chrOrgSetCopy.add(s); } for (String o : trimedPresetOrgList) { if (chrOrgSet.contains(o)) { chrOrgSetCopy.remove(o); } } trimedPresetOrgList.retainAll(chrOrgSet); orgList.addAll(trimedPresetOrgList); orgList.addAll(chrOrgSetCopy); } } // Exclude preset feature types (global) to display // Data should be comma separated class names String excludedFeatureTypes = webProperties.getProperty( "genomicRegionSearch.featureTypesExcluded.global"); List<String> excludedFeatureTypeList = new ArrayList<String>(); if (excludedFeatureTypes == null || "".equals(excludedFeatureTypes)) { excludedFeatureTypeList = null; } else { excludedFeatureTypeList = Arrays.asList(excludedFeatureTypes.split(",")); } if ("".equals(orgFeatureJSONString)) { orgFeatureJSONString = prepareWebData(orgList, excludedFeatureTypeList); return orgFeatureJSONString; } else { return orgFeatureJSONString; } } private String prepareWebData(List<String> orgList, List<String> excludedFeatureTypeList) { Query q = new Query(); q.setDistinct(true); QueryClass qcOrg = new QueryClass(Organism.class); QueryClass qcFeature = new QueryClass(SequenceFeature.class); QueryField qfOrgName = new QueryField(qcOrg, "shortName"); QueryField qfFeatureClass = new QueryField(qcFeature, "class"); q.addToSelect(qfOrgName); q.addToSelect(qfFeatureClass); q.addFrom(qcOrg); q.addFrom(qcFeature); q.addToOrderBy(qfOrgName, "ascending"); ConstraintSet constraints = new ConstraintSet(ConstraintOp.AND); q.setConstraint(constraints); // SequenceFeature.organism = Organism QueryObjectReference organism = new QueryObjectReference(qcFeature, "organism"); ContainsConstraint ccOrg = new ContainsConstraint(organism, ConstraintOp.CONTAINS, qcOrg); constraints.addConstraint(ccOrg); // constraints.addConstraint(new BagConstraint(qfOrgName, // ConstraintOp.IN, orgList)); Results results = objectStore.execute(q); // Parse results data to a map Map<String, Set<String>> resultsMap = new LinkedHashMap<String, Set<String>>(); Set<String> featureTypeSet = new LinkedHashSet<String>(); // TODO this will be very slow when query too many features if (results == null || results.size() < 0) { return ""; } else { for (Iterator<?> iter = results.iterator(); iter.hasNext();) { ResultsRow<?> row = (ResultsRow<?>) iter.next(); String org = (String) row.get(0); @SuppressWarnings("rawtypes") // TODO exception - feature type is NULL String featureType = ((Class) row.get(1)).getSimpleName(); if (!"Chromosome".equals(featureType) && orgList.contains(org)) { if (resultsMap.size() < 1) { featureTypeSet.add(featureType); resultsMap.put(org, featureTypeSet); } else { if (resultsMap.keySet().contains(org)) { resultsMap.get(org).add(featureType); } else { Set<String> s = new LinkedHashSet<String>(); s.add(featureType); resultsMap.put(org, s); } } } } } // Get all feature types for (Set<String> ftSet : resultsMap.values()) { // Exclude some feature types if (excludedFeatureTypeList != null) { ftSet.removeAll(excludedFeatureTypeList); } if (featureTypesInOrgs == null) { featureTypesInOrgs = new HashSet<String>(); featureTypesInOrgs.addAll(ftSet); } } getFeatureTypeToSOTermMap(); getOrganismToTaxonMap(); // Parse data to JSON string List<Object> ft = new ArrayList<Object>(); List<Object> gb = new ArrayList<Object>(); Map<String, Object> ma = new LinkedHashMap<String, Object>(); for (Entry<String, Set<String>> e : resultsMap.entrySet()) { Map<String, Object> mft = new LinkedHashMap<String, Object>(); Map<String, Object> mgb = new LinkedHashMap<String, Object>(); mft.put("organism", e.getKey()); List<Object> featureTypeAndDespMapList = new ArrayList<Object>(); for (String className : e.getValue()) { Map<String, String> featureTypeAndDespMap = new LinkedHashMap<String, String>(); String soTermDes = "description not avaliable"; List<String> soInfo = featureTypeToSOTermMap.get(className); if (soInfo != null) { soTermDes = featureTypeToSOTermMap.get(className).get(1); } featureTypeAndDespMap.put("featureType", className); featureTypeAndDespMap.put("description", soTermDes); featureTypeAndDespMapList.add(featureTypeAndDespMap); } mft.put("features", featureTypeAndDespMapList); ft.add(mft); mgb.put("organism", e.getKey()); mgb.put("genomeBuild", (OrganismGenomeBuildLookup .getGenomeBuildbyOrgansimAbbreviation(e.getKey()) == null) ? "not available" : OrganismGenomeBuildLookup .getGenomeBuildbyOrgansimAbbreviation(e .getKey())); gb.add(mgb); } ma.put("organisms", orgList); ma.put("genomeBuilds", gb); ma.put("featureTypes", ft); JSONObject jo = new JSONObject(ma); // Note: JSONObject toString will replace \' to \\', so don't convert it before the method // was called. Replace "\" in java -> "\\\\" String preDataStr = jo.toString(); preDataStr = preDataStr.replaceAll("'", "\\\\'"); return preDataStr; } /** * Get the name of customized options javascript, by default, it is named * "genomic_region_search_options_default.js" * * @return the name of options javascript name */ public String getOptionsJavascript() { String optionsJavascriptName = webProperties .getProperty("genomicRegionSearch.optionsJavascript"); if (optionsJavascriptName == null || "".equals(optionsJavascriptName)) { optionsJavascriptName = GENOMIC_REGION_SEARCH_OPTIONS_DEFAULT; } return optionsJavascriptName; } /** * Get the name of customized results javascript * * @return the name of results page */ public String getResultsJavascript() { String resultsJavascriptName = webProperties .getProperty("genomicRegionSearch.resultsJavascript"); if (resultsJavascriptName == null || "".equals(resultsJavascriptName)) { resultsJavascriptName = GENOMIC_REGION_SEARCH_RESULTS_DEFAULT; } return resultsJavascriptName; } /** * Get the name of customized options CSS * * @return the name of options css */ public String getOptionsCss() { String optionsCssName = webProperties.getProperty( "genomicRegionSearch.optionsCss"); if (optionsCssName == null || "".equals(optionsCssName)) { optionsCssName = GENOMIC_REGION_SEARCH_OPTIONS_DEFAULT; } return optionsCssName; } /** * Get the name of customized results CSS * * @return the name of results css */ public String getResultsCss() { String resultsCssName = webProperties.getProperty( "genomicRegionSearch.resultsCss"); if (resultsCssName == null || "".equals(resultsCssName)) { resultsCssName = GENOMIC_REGION_SEARCH_RESULTS_DEFAULT; } return resultsCssName; } /** * To parse form data * * @param grsForm GenomicRegionSearchForm * @return genomic region search constraint */ public ActionMessage parseGenomicRegionSearchForm( GenomicRegionSearchForm grsForm) { grsc = new GenomicRegionSearchConstraint(); ActionMessage actmsg = parseBasicInput(grsForm); if (actmsg != null) { return actmsg; } return null; } /** * * @param grsForm GenomicRegionSearchForm * @return ActionMessage */ public ActionMessage parseBasicInput(GenomicRegionSearchForm grsForm) { // Parse form String organism = (String) grsForm.get("organism"); String[] featureTypes = (String[]) grsForm.get("featureTypes"); String whichInput = (String) grsForm.get("whichInput"); String dataFormat = (String) grsForm.get("dataFormat"); FormFile formFile = (FormFile) grsForm.get("fileInput"); String pasteInput = (String) grsForm.get("pasteInput"); String extendedRegionSize = (String) grsForm.get("extendedRegionSize"); // Organism grsc.setOrgName(organism); grsc.setExtededRegionSize(Integer.parseInt(extendedRegionSize)); selectionInfo.add("<b>Selected organism: </b><i>" + organism + "</i>"); // Feature types if (featureTypes == null) { return new ActionMessage("genomicRegionSearch.spanFieldSelection", "feature types"); } // featureTypes in this case are (the last bit of) class instead of // featuretype in the db table; gain the full name by Model.getQualifiedTypeName(className) Set<Class<?>> ftSet = new HashSet<Class<?>>(); for (String f : featureTypes) { ClassDescriptor cld = model.getClassDescriptorByName(f); ftSet.add(cld.getType()); for (ClassDescriptor subCld : model.getAllSubs(cld)) { ftSet.add(subCld.getType()); } } String ftString = ""; for (String aFeaturetype : featureTypes) { aFeaturetype = WebUtil.formatPath(aFeaturetype, interMineAPI, webConfig); ftString = ftString + aFeaturetype + ", "; } selectionInfo.add("<b>Selected feature types: </b>" + ftString.substring(0, ftString.lastIndexOf(", "))); if (Integer.parseInt(extendedRegionSize) > 0) { if (Integer.parseInt(extendedRegionSize) >= 1000) { selectionInfo.add("<b>Extend Regions: </b>" + new DecimalFormat("#.##").format(Integer .parseInt(extendedRegionSize) / 1000) + " kbp"); } else { selectionInfo.add("<b>Extend Regions: </b>" + extendedRegionSize + "bp"); } } grsc.setFeatureTypes(ftSet); // File parsing BufferedReader reader = null; /* * FormFile used from Struts works a bit strangely. 1. Although the file * does't exist formFile.getInputStream() doesn't throw * FileNotFoundException. 2. When user specified empty file path or very * invalid file path, like file path not starting at '/' then * formFile.getFileName() returns empty string. */ if ("paste".equals(whichInput)) { if (pasteInput != null && pasteInput.length() != 0) { String trimmedText = pasteInput.trim(); if (trimmedText.length() == 0) { return new ActionMessage("genomicRegionSearch.noSpanPaste"); } reader = new BufferedReader(new StringReader(trimmedText)); } else { return new ActionMessage("genomicRegionSearch.noSpanFile"); } } else if ("file".equals(whichInput)) { if (formFile != null && formFile.getFileName() != null && formFile.getFileName().length() > 0) { String mimetype = formFile.getContentType(); if (!"application/octet-stream".equals(mimetype) && !mimetype.startsWith("text")) { return new ActionMessage("genomicRegionSearch.isNotText", mimetype); } if (formFile.getFileSize() == 0) { return new ActionMessage( "genomicRegionSearch.noSpanFileOrEmpty"); } try { reader = new BufferedReader(new InputStreamReader( formFile.getInputStream())); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } else { return new ActionMessage("genomicRegionSearch.spanInputType"); } // Validate text format try { reader.mark(READ_AHEAD_CHARS); } catch (IOException e) { e.printStackTrace(); } char[] buf = new char[READ_AHEAD_CHARS]; int read; Set<String> spanStringSet = new LinkedHashSet<String>(); try { read = reader.read(buf, 0, READ_AHEAD_CHARS); for (int i = 0; i < read; i++) { if (buf[i] == 0) { return new ActionMessage("genomicRegionSearch.isNotText", "binary"); } } reader.reset(); // Remove duplication String thisLine; while ((thisLine = reader.readLine()) != null) { spanStringSet.add(thisLine); } } catch (IOException e) { e.printStackTrace(); } // Parse uploaded spans to an arraylist; handle empty content and non-integer spans // Tab delimited format: "chr(tab)start(tab)end" or "chr:start..end" List<GenomicRegion> spanList = new ArrayList<GenomicRegion>(); for (String spanStr : spanStringSet) { GenomicRegion aSpan = new GenomicRegion(); // Use regular expression to validate user's input: String ddotsRegex = "[^:]+: ?\\d+\\.\\.\\d+$"; // "chr:start..end" - [^:]+:\d+\.{2,}\d+ String tabRegex = "[^\\t]+\\t\\d+\\t\\d+$"; // "chr:start-end" - [^:]+:\d+\-\d+ String dashRegex = "[^:]+: ?\\d+\\-\\d+$"; // "chr(tab)start(tab)end" - [^\t]+\t\d+\t\d+ String snpRegex = "[^:]+: ?\\d+$"; // "chr:singlePosition" - [^:]+:[\d]+$ if (Pattern.matches(ddotsRegex, spanStr)) { aSpan.setChr((spanStr.split(":"))[0]); String[] spanItems = (spanStr.split(":"))[1].split("\\.."); String start = spanItems[0].trim(); if ("isInterBaseCoordinate".equals(dataFormat)) { aSpan.setStart(Integer.valueOf(start) + 1); } else { aSpan.setStart(Integer.valueOf(start)); } aSpan.setEnd(Integer.valueOf(spanItems[1])); } else if (Pattern.matches(tabRegex, spanStr)) { String[] spanItems = spanStr.split("\t"); aSpan.setChr(spanItems[0]); if ("isInterBaseCoordinate".equals(dataFormat)) { aSpan.setStart(Integer.valueOf(spanItems[1]) + 1); } else { aSpan.setStart(Integer.valueOf(spanItems[1])); } aSpan.setEnd(Integer.valueOf(spanItems[2])); } else if (Pattern.matches(dashRegex, spanStr)) { aSpan.setChr((spanStr.split(":"))[0]); String[] spanItems = (spanStr.split(":"))[1].split("-"); String start = spanItems[0].trim(); if ("isInterBaseCoordinate".equals(dataFormat)) { aSpan.setStart(Integer.valueOf(start) + 1); } else { aSpan.setStart(Integer.valueOf(start)); } aSpan.setEnd(Integer.valueOf(spanItems[1])); } else if (Pattern.matches(snpRegex, spanStr)) { aSpan.setChr((spanStr.split(":"))[0]); String start = (spanStr.split(":"))[1].trim(); if ("isInterBaseCoordinate".equals(dataFormat)) { aSpan.setStart(Integer.valueOf(start) + 1); } else { aSpan.setStart(Integer.valueOf(start)); } aSpan.setEnd(Integer.valueOf((spanStr.split(":"))[1].trim())); } else { return new ActionMessage( "genomicRegionSearch.spanInWrongformat", spanStr); } spanList.add(aSpan); } grsc.setGenomicRegionList(spanList); return null; } /** * To prepare queries for genomic regions * * @return a list of prepared queries for genomic regions */ public Map<GenomicRegion, Query> createQueryList() { return GenomicRegionSearchUtil.createQueryList( grsc.getGenomicRegionList(), grsc.getExtendedRegionSize(), getChromosomeInfomationMap().get(grsc.getOrgName()), grsc.getOrgName(), grsc.getFeatureTypes()); } /** * @return the grsc */ public GenomicRegionSearchConstraint getConstraint() { return this.grsc; } /** * Get chromosome information as in a map, keys are lowercased chromosome ids * @return chrInfoMap */ public Map<String, Map<String, ChromosomeInfo>> getChromosomeInfomationMap() { if (chrInfoMap == null) { chrInfoMap = GenomicRegionSearchQueryRunner .getChromosomeInfo(interMineAPI, profile); } return chrInfoMap; } /** * * @return featureTypeToSOTermMap */ public Map<String, List<String>> getFeatureTypeToSOTermMap() { if (featureTypeToSOTermMap == null) { featureTypeToSOTermMap = GenomicRegionSearchQueryRunner .getFeatureAndSOInfo(interMineAPI); if (!(featureTypesInOrgs.size() == featureTypeToSOTermMap.size() && featureTypesInOrgs .containsAll(featureTypeToSOTermMap.keySet()))) { Map<String, List<String>> newFeatureTypeToSOTermMap = new HashMap<String, List<String>>(); for (String ft : featureTypesInOrgs) { if (featureTypeToSOTermMap.keySet().contains(ft)) { newFeatureTypeToSOTermMap.put(ft, featureTypeToSOTermMap.get(ft)); } else { List<String> des = new ArrayList<String>(); des.add(ft); des.add("description not avaliable"); newFeatureTypeToSOTermMap.put(ft, des); } } featureTypeToSOTermMap = newFeatureTypeToSOTermMap; } } return featureTypeToSOTermMap; } /** * * @return orgTaxonIdMap */ public Map<String, Integer> getOrganismToTaxonMap() { if (orgTaxonIdMap == null) { orgTaxonIdMap = GenomicRegionSearchQueryRunner.getTaxonInfo(interMineAPI, profile); } return orgTaxonIdMap; } /** * Validate input genomic regions * @return resultMap */ public Map<String, List<GenomicRegion>> validateGenomicRegions() { /* the Map has two key-value mappings * PASS-ArrayList<passedSpan> * ERROR-ArrayList<errorSpan> */ Map<String, List<GenomicRegion>> resultMap = new HashMap<String, List<GenomicRegion>>(); List<GenomicRegion> passedSpanList = new ArrayList<GenomicRegion>(); List<GenomicRegion> errorSpanList = new ArrayList<GenomicRegion>(); Map<String, ChromosomeInfo> chrInfo = chrInfoMap.get(grsc.getOrgName()); if (chrInfo == null) { // this should not happen return null; } // Create passedSpanList for (GenomicRegion gr : grsc.getGenomicRegionList()) { // User input could be x instead of X for human chromosome, converted to lowercase ChromosomeInfo ci = null; String chr = gr.getChr().toLowerCase(); if (chrInfo.containsKey(chr)) { ci = chrInfo.get(chr); } else { if (chr.startsWith("chr")) { // UCSC format if (chrInfo.containsKey(chr.substring(3))) { ci = chrInfo.get(chr.substring(3)); } else { continue; } } else { continue; } } if ((gr.getStart() >= 1 && gr.getStart() <= ci .getChrLength()) && (gr.getEnd() >= 1 && gr.getEnd() <= ci .getChrLength())) { if (gr.getStart() > gr.getEnd()) { // Start must be smaller than End GenomicRegion newSpan = new GenomicRegion(); newSpan.setChr(ci.getChrPID()); // converted to the right case newSpan.setStart(gr.getEnd()); newSpan.setEnd(gr.getStart()); passedSpanList.add(newSpan); } else { gr.setChr(ci.getChrPID()); passedSpanList.add(gr); } } } // make errorSpanList errorSpanList.addAll(grsc.getGenomicRegionList()); errorSpanList.removeAll(passedSpanList); resultMap.put("pass", passedSpanList); resultMap.put("error", errorSpanList); return resultMap; } /** * The message passed to results page * * @return resultMessages */ public List<String> getSelectionInformation() { return this.selectionInfo; } /** * Get organism for GenomicRegionSearchAjaxAction use. * * @param spanUUIDString uuid * @param spanConstraintMap map of contraints * @return the organism */ public String getGenomicRegionOrganismConstraint(String spanUUIDString, Map<GenomicRegionSearchConstraint, String> spanConstraintMap) { for (Entry<GenomicRegionSearchConstraint, String> e : spanConstraintMap .entrySet()) { if (e.getValue().equals(spanUUIDString)) { return e.getKey().getOrgName(); } } return null; } /** * Get flanking size for GenomicRegionSearchAjaxAction use. * * @param spanUUIDString uuid * @param spanConstraintMap map of contraints * @return the flanking size */ public int getGenomicRegionFlankingSizeConstraint(String spanUUIDString, Map<GenomicRegionSearchConstraint, String> spanConstraintMap) { for (Entry<GenomicRegionSearchConstraint, String> e : spanConstraintMap .entrySet()) { if (e.getValue().equals(spanUUIDString)) { return e.getKey().getExtendedRegionSize(); } } return 0; } /** * Get a set of ids of a span's overlap features. for * GenomicRegionSearchAjaxAction use. * * @param grString a genomic region in string * @param flankingSize int value of extended genomic region size * @param resultMap map of search results * @return String feature ids joined by comma */ public Set<Integer> getGenomicRegionOverlapFeaturesAsSet(String grString, int flankingSize, Map<GenomicRegion, List<List<String>>> resultMap) { Set<Integer> featureIdSet = new LinkedHashSet<Integer>(); GenomicRegion spanToExport = new GenomicRegion(); // spanString is extended span String[] temp = grString.split(":"); spanToExport.setChr(temp[0]); temp = temp[1].split("\\.\\."); spanToExport.setExtendedStart(Integer.parseInt(temp[0])); spanToExport.setExtendedEnd(Integer.parseInt(temp[1])); spanToExport.setExtendedRegionSize(flankingSize); spanToExport.setStart(spanToExport.getExtendedStart() + spanToExport.getExtendedRegionSize()); spanToExport.setEnd(spanToExport.getExtendedEnd() - spanToExport.getExtendedRegionSize()); for (List<String> sf : resultMap.get(spanToExport)) { // the first element (0) is InterMine Id, second (1) is PID featureIdSet.add(Integer.valueOf(sf.get(0))); } return featureIdSet; } /** * Get a set of ids of a span's overlap features by given feature type. for * GenomicRegionSearchAjaxAction use. * * @param grString a genomic region in string * @param flankingSize int value of extended genomic region size * @param resultMap map of search results * @param featureType e.g. Gene * @return String feature ids joined by comma */ public Set<Integer> getGenomicRegionOverlapFeaturesByType(String grString, int flankingSize, Map<GenomicRegion, List<List<String>>> resultMap, String featureType) { Set<Integer> featureIdSet = new LinkedHashSet<Integer>(); GenomicRegion spanToExport = new GenomicRegion(); // spanString is extended span String[] temp = grString.split(":"); spanToExport.setChr(temp[0]); temp = temp[1].split("\\.\\."); spanToExport.setExtendedStart(Integer.parseInt(temp[0])); spanToExport.setExtendedEnd(Integer.parseInt(temp[1])); spanToExport.setExtendedRegionSize(flankingSize); spanToExport.setStart(spanToExport.getExtendedStart() + spanToExport.getExtendedRegionSize()); spanToExport.setEnd(spanToExport.getExtendedEnd() - spanToExport.getExtendedRegionSize()); for (List<String> sf : resultMap.get(spanToExport)) { // the first element (0) is InterMine Id, second (1) is PID, 4 featureType if (sf.get(3).equals(featureType)) { featureIdSet.add(Integer.valueOf(sf.get(0))); } } return featureIdSet; } /** * Get a set of ids of all span's overlap features by given feature type. for * GenomicRegionSearchAjaxAction use. * * @param resultMap map of search results * @param featureType e.g. Gene * @return String feature ids joined by comma */ public Set<Integer> getAllGenomicRegionOverlapFeaturesByType( Map<GenomicRegion, List<List<String>>> resultMap, String featureType) { Set<Integer> featureIdSet = new LinkedHashSet<Integer>(); for (Entry<GenomicRegion, List<List<String>>> e : resultMap.entrySet()) { if (e.getValue() != null) { for (List<String> sf : e.getValue()) { if (sf.get(3).equals(featureType)) { // 3 featureType featureIdSet.add(Integer.valueOf(sf.get(0))); // 0 id } } } } return featureIdSet; } /** * Get a comma separated string of a span's overlap features. for * GenomicRegionSearchAjaxAction use. * * @param spanString span in string * @param flankingSize int value of extended genomic region size * @param resultMap map of search results * @return String feature ids joined by comma */ public String getGenomicRegionOverlapFeaturesAsString(String spanString, int flankingSize, Map<GenomicRegion, List<List<String>>> resultMap) { Set<Integer> featureSet = getGenomicRegionOverlapFeaturesAsSet( spanString, flankingSize, resultMap); return StringUtil.join(featureSet, ","); } /** * Check whether the results have empty features. for * GenomicRegionSearchAjaxAction use. * * @param resultMap map of search results * @return String "hasFeature" or "emptyFeature" */ public String isEmptyFeature( Map<GenomicRegion, List<List<String>>> resultMap) { for (List<List<String>> l : resultMap.values()) { if (l != null) { return "hasFeature"; } } return "emptyFeature"; } /** * Generate a html string with all feature type for list creation. * * @param resultMap map of search results * @return a html string */ public String generateCreateListHtml(Map<GenomicRegion, List<List<String>>> resultMap) { Set<String> ftSet = new TreeSet<String>(); for (List<List<String>> l : resultMap.values()) { if (l != null) { for (List<String> feature : l) { ftSet.add(feature.get(3)); // the 3rd is feature type } } } String clHtml = " or <a href=\"javascript: createList('all','all-regions');\">" + "Create List by feature type:</a>" + "<select id=\"all-regions\" style=\"margin: 4px 3px\">"; for (String ft : ftSet) { clHtml += "<option value=\"" + ft + "\">" + WebUtil.formatPath(ft, interMineAPI, webConfig) + "</option>"; } clHtml += "</select>"; return clHtml; } /** * Convert result map to HTML string. * * @param resultMap resultMap * @param genomicRegionList spanList * @param fromIdx offsetStart * @param toIdx offsetEnd * @param session the current session * @param orgName organism * @return a String of HTML */ public String convertResultMapToHTML( Map<GenomicRegion, List<List<String>>> resultMap, List<GenomicRegion> genomicRegionList, int fromIdx, int toIdx, HttpSession session, String orgName) { String baseURL = webProperties.getProperty("webapp.baseurl"); String path = webProperties.getProperty("webapp.path"); List<GenomicRegion> subGenomicRegionList = genomicRegionList.subList(fromIdx, toIdx + 1); // start to build the html for results table StringBuffer sb = new StringBuffer(); //TODO use HTML Template sb.append("<thead><tr valign=\"middle\">"); sb.append("<th align=\"center\">Genome Region</th>"); sb.append("<th align=\"center\">Feature</th>"); sb.append("<th align=\"center\">Feature Type</th>"); sb.append("<th align=\"center\">Location</th>"); sb.append("</tr></thead>"); sb.append("<tbody>"); for (GenomicRegion s : subGenomicRegionList) { String span = s.getExtendedRegion(); List<List<String>> features = resultMap.get(s); // get list of featureTypes String ftHtml = categorizeFeatureTypes(features, s); Set<String> ftSet = getFeatureTypeSet(features); /* * order: 0.id * 1.feature PID * 2.symbol * 3.feature type * 4.chr * 5.start * 6.end * see query fields in createQueryList method */ if (features != null) { int length = features.size(); List<String> firstFeature = features.get(0); String firstId = firstFeature.get(0); String firstPid = firstFeature.get(1); String firstSymbol = firstFeature.get(2); String firstFeatureType = firstFeature.get(3); String firstChr = firstFeature.get(4); String firstStart = firstFeature.get(5); String firstEnd = firstFeature.get(6); String loc = firstChr + ":" + firstStart + ".." + firstEnd; // translatedClassName String firstSoTerm = WebUtil.formatPath(firstFeatureType, interMineAPI, webConfig); String firstSoTermDes = featureTypeToSOTermMap.get(firstFeatureType).get(1); firstSoTermDes = firstSoTermDes.replaceAll("'", "\\\\'"); // hack - feature name is null, use id sb.append("<tr><td valign='top' rowspan='" + length + "'><b>" + span + "</b><br>"); if (s.isRegionExtended()) { String os = s.getOriginalRegion(); sb.append("<i>Original input: " + os + "</i><br>"); } String facet = "SequenceFeature"; if (ftSet != null) { if (ftSet.size() == 1) { facet = ftSet.iterator().next(); } } sb.append("<div style='align:center; padding-bottom:12px'>" + "<span class='fakelink exportDiv'> Export data </span>" + "<img class='exportDiv' style='position:relative; top:3px;' " + "border='0' src='model/images/download.png' title='export data' " + "height='18' width='18'/><ul class='contextMenu'><li class='tab'>" + "<a href='#javascript: exportFeatures(\"" + span + "\", " + "\"" + facet + "\", \"tab\");' class='ext_link'>TAB</a></li>" + "<li class='csv'><a href='#javascript: exportFeatures(\"" + span + "\", \"" + facet + "\", \"csv\");' class='ext_link'>CSV</a></li>" + "<li class='gff'><a href='#javascript: exportFeatures(\"" + span + "\", \"" + facet + "\", \"gff3\");' class='ext_link'>GFF3</a>" + "</li><li class='seq'><a href='#javascript: exportFeatures(\"" + span + "\", \"" + facet + "\", \"sequence\");' class='ext_link'>SEQ</a>" + "</li></ul></div><div style='align:center'>" + "<a href='javascript: exportToGalaxy(\"" + span + "\", \"" + orgName + "\");' class='ext_link'> Export to Galaxy <img border='0' " + "title='Export to Galaxy' src='model/images/Galaxy_logo_small.png' " + "class='arrow' style='height:5%; width:5%'></a></div>" + ftHtml + "</td><td><a target='' title='' href='" + baseURL + "/" + path + "/report.do?id=" + firstId + "'>"); if (firstSymbol == null || "".equals(firstSymbol)) { sb.append("<strong><i>unknown symbol</i></strong>"); } else { sb.append("<strong>" + firstSymbol + "</strong>"); } sb.append(" "); if (firstPid == null || "".equals(firstPid)) { sb.append("<span style='font-size: 11px;'><i>unknown DB identifier</i></span>"); } else { sb.append("<span style='font-size: 11px;'>" + firstPid + "</span>"); } sb.append("</a></td><td>" + firstSoTerm + "<a onclick=\"document.getElementById('ctxHelpTxt').innerHTML='" + firstSoTerm + ": " + firstSoTermDes + "';document.getElementById('ctxHelpDiv').style.display='';" + "window.scrollTo(0, 0);return false\" title=\"" + firstSoTermDes + "\"><img class=\"tinyQuestionMark\" " + "src=\"images/icons/information-small-blue.png\" alt=\"?\"></a>" + "</td><td>" + loc + "</td></tr>"); for (int i = 1; i < length; i++) { String id = features.get(i).get(0); String pid = features.get(i).get(1); String symbol = features.get(i).get(2); String featureType = features.get(i).get(3); String chr = features.get(i).get(4); String start = features.get(i).get(5); String end = features.get(i).get(6); String soTerm = WebUtil.formatPath(featureType, interMineAPI, webConfig); String soTermDes = featureTypeToSOTermMap.get(featureType).get(1); soTermDes = soTermDes.replaceAll("'", "\\\\'"); String location = chr + ":" + start + ".." + end; sb.append("<tr><td><a target='' title='' href='" + baseURL + "/" + path + "/report.do?id=" + id + "'>"); if (symbol == null || "".equals(symbol)) { sb.append("<strong><i>unknown symbol</i></strong>"); } else { sb.append("<strong>" + symbol + "</strong>"); } sb.append(" "); if (pid == null || "".equals(pid)) { sb.append("<span style='font-size: 11px;'>" + "<i>unknown DB identifier</i></span>"); } else { sb.append("<span style='font-size: 11px;'>" + pid + "</span>"); } sb.append("</a></td><td>" + soTerm + "<a onclick=\"document.getElementById('ctxHelpTxt').innerHTML='" + soTerm + ": " + soTermDes + "';document.getElementById('ctxHelpDiv').style.display='';" + "window.scrollTo(0, 0);return false\" title=\"" + soTermDes + "\"><img class=\"tinyQuestionMark\" " + "src=\"images/icons/information-small-blue.png\" alt=\"?\"></a>" + "</td><td>" + location + "</td></tr>"); } } else { sb.append("<tr><td><b>" + span + "</b></td><td colspan='3'><i>No overlap features found</i></td></tr>"); } } sb.append("</tbody>"); return sb.toString(); } /** * Get all feature types from a list of sequence features * @param features list of sequence features * @param s GenomicRegion * @return A html string with a dropdown list of feature types */ public String categorizeFeatureTypes(List<List<String>> features, GenomicRegion s) { String id = s.getChr() + "-" + s.getStart() + "-" + s.getEnd(); Set<String> ftSet = getFeatureTypeSet(features); if (ftSet == null) { return ""; } else { String ftHtml = "<div>" + "<a href=\"javascript: createList('" + s.getExtendedRegion() + "', '" + id + "');\">" + "Create List by</a>" + "<select id=\"" + id + "\" style=\"margin: 4px 3px\">"; for (String ft : ftSet) { ftHtml += "<option value=\"" + ft + "\">" + WebUtil.formatPath(ft, interMineAPI, webConfig) + "</option>"; } ftHtml += "</select></div>"; return ftHtml; } } /** * Get all feature types in a set * @param features list of sequence features * @param s GenomicRegion * @return a set of feature types of a genomic region */ public Set<String> getFeatureTypeSet(List<List<String>> features) { Set<String> ftSet = null; if (features != null) { ftSet = new TreeSet<String>(); for (List<String> feature : features) { ftSet.add(feature.get(3)); // the 3rd is feature type } } return ftSet; } /** * Calculate the number of matched bases. * * @param gr a GenomicRegion object * @param r a list of attributes * @return matched base count as String */ protected String getMatchedBaseCount(GenomicRegion gr, List<String> r) { int spanStart = gr.getStart(); int spanEnd = gr.getEnd(); int featureStart = Integer.valueOf(r.get(3)); int featureEnd = Integer.valueOf(r.get(4)); int matchedBaseCount = 0; if (featureStart <= spanStart && featureEnd >= spanStart && featureEnd <= spanEnd) { matchedBaseCount = featureEnd - spanStart + 1; } if (featureStart >= spanStart && featureStart <= spanEnd && featureEnd >= spanEnd) { matchedBaseCount = spanEnd - featureStart + 1; } if (featureStart >= spanStart && featureEnd <= spanEnd) { matchedBaseCount = featureEnd - featureStart + 1; } if (featureStart <= spanStart && featureEnd >= spanEnd) { matchedBaseCount = spanEnd - spanStart + 1; } return String.valueOf(matchedBaseCount); } /** * A flexiable way of setting query fields. * * @param featureIds set of feature intermine ids * @param featureType feature class name * @param views user defined views in web.properties * @return a pathquery */ public PathQuery getExportFeaturesQuery(Set<Integer> featureIds, String featureType, Set<String> views) { PathQuery q = new PathQuery(model); String path = featureType; if (views == null) { q.addView(path + ".primaryIdentifier"); q.addView(path + ".symbol"); q.addView(path + ".chromosomeLocation.locatedOn.primaryIdentifier"); q.addView(path + ".chromosomeLocation.start"); q.addView(path + ".chromosomeLocation.end"); q.addView(path + ".organism.name"); } else { for (String view : views) { q.addView(view.trim().replace("{0}", path)); } } q.addConstraint(Constraints.inIds(featureType, featureIds), "A"); return q; } /** * * @param organisms set of org names * @return set of taxonIds */ public Set<Integer> getTaxonIds(Set<String> organisms) { Set<Integer> taxIds = new HashSet<Integer>(); for (String org : organisms) { taxIds.add(this.getOrganismToTaxonMap().get(org)); } return taxIds; } /** * To serve UCSC Lift-Over */ public void serveLiftOver() { } }
package org.biojava3.alignment; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.biojava3.alignment.template.AlignedSequence; import org.biojava3.alignment.template.AlignedSequence.Step; import org.biojava3.alignment.template.Profile; import org.biojava3.alignment.template.ProfileView; import org.biojava3.alignment.template.SubstitutionMatrix; import org.biojava3.core.sequence.AccessionID; import org.biojava3.core.sequence.compound.AminoAcidCompound; import org.biojava3.core.sequence.compound.AminoAcidCompoundSet; import org.biojava3.core.sequence.io.util.IOUtils; import org.biojava3.core.sequence.location.template.Location; import org.biojava3.core.sequence.template.Compound; import org.biojava3.core.sequence.template.CompoundSet; import org.biojava3.core.sequence.template.Sequence; /** * Implements a data structure for the results of sequence alignment. Every {@link List} returned is unmodifiable. * * @author Mark Chapman * @param <S> each element of the alignment {@link Profile} is of type S * @param <C> each element of an {@link AlignedSequence} is a {@link Compound} of type C */ public class SimpleProfile<S extends Sequence<C>, C extends Compound> implements Profile<S, C> { private List<AlignedSequence<S, C>> list; private List<S> originals; private int length; protected SimpleProfile(AlignedSequence<S, C> query, AlignedSequence<S, C> target) { if (query.getLength() != target.getLength()) { throw new IllegalArgumentException("Aligned sequences differ in size"); } list = new ArrayList<AlignedSequence<S, C>>(); list.add(query); list.add(target); list = Collections.unmodifiableList(list); originals = new ArrayList<S>(); originals.add((S) query.getOriginalSequence()); originals.add((S) target.getOriginalSequence()); originals = Collections.unmodifiableList(originals); length = query.getLength(); } /** * Creates a profile from a single sequence. * * @param sequence sequence to seed profile */ public SimpleProfile(S sequence) { List<Step> s = new ArrayList<Step>(); for (int i = 0; i < sequence.getLength(); i++) { s.add(Step.COMPOUND); } list = new ArrayList<AlignedSequence<S, C>>(); list.add(new SimpleAlignedSequence<S, C>(sequence, s)); list = Collections.unmodifiableList(list); originals = new ArrayList<S>(); originals.add(sequence); originals = Collections.unmodifiableList(originals); length = sequence.getLength(); } protected SimpleProfile(S query, S target, List<Step> sx, int xb, int xa, List<Step> sy, int yb, int ya) { if (sx.size() != sy.size()) { throw new IllegalArgumentException("Alignments differ in size"); } list = new ArrayList<AlignedSequence<S, C>>(); list.add(new SimpleAlignedSequence<S, C>(query, sx, xb, xa)); list.add(new SimpleAlignedSequence<S, C>(target, sy, yb, ya)); list = Collections.unmodifiableList(list); originals = new ArrayList<S>(); originals.add(query); originals.add(target); originals = Collections.unmodifiableList(originals); length = sx.size(); } protected SimpleProfile(Profile<S, C> query, Profile<S, C> target, List<Step> sx, List<Step> sy) { if (sx.size() != sy.size()) { throw new IllegalArgumentException("Alignments differ in size"); } list = new ArrayList<AlignedSequence<S, C>>(); for (AlignedSequence<S, C> s : query) { list.add(new SimpleAlignedSequence<S, C>(s, sx)); } for (AlignedSequence<S, C> s : target) { list.add(new SimpleAlignedSequence<S, C>(s, sy)); } list = Collections.unmodifiableList(list); originals = new ArrayList<S>(); originals.addAll(query.getOriginalSequences()); originals.addAll(target.getOriginalSequences()); originals = Collections.unmodifiableList(originals); length = sx.size(); } public SimpleProfile(Collection<AlignedSequence<S,C>> alignedSequences) { list = new ArrayList<AlignedSequence<S,C>>(); originals = new ArrayList<S>(); Iterator<AlignedSequence<S,C>> itr = alignedSequences.iterator(); if(!itr.hasNext()) { throw new IllegalArgumentException("alignedSequences must not be empty"); } AlignedSequence<S, C> curAlignedSeq = itr.next(); length = curAlignedSeq.getLength(); list.add(curAlignedSeq); originals.add((S) curAlignedSeq.getOriginalSequence()); while (itr.hasNext()) { curAlignedSeq = itr.next(); if (curAlignedSeq.getLength() != length) { throw new IllegalArgumentException("Aligned sequences differ in size"); } list.add(curAlignedSeq); originals.add((S) curAlignedSeq.getOriginalSequence()); } list = Collections.unmodifiableList(list); originals = Collections.unmodifiableList(originals); } // methods for Profile @Override public AlignedSequence<S, C> getAlignedSequence(int listIndex) { return list.get(listIndex - 1); } @Override public AlignedSequence<S, C> getAlignedSequence(S sequence) { for (AlignedSequence<S, C> s : list) { if (s.equals(sequence) || s.getOriginalSequence().equals(sequence)) { return s; } } return null; } @Override public List<AlignedSequence<S, C>> getAlignedSequences() { return list; } @Override public List<AlignedSequence<S, C>> getAlignedSequences(int... listIndices) { List<AlignedSequence<S, C>> tempList = new ArrayList<AlignedSequence<S, C>>(); for (int i : listIndices) { tempList.add(getAlignedSequence(i)); } return Collections.unmodifiableList(tempList); } @Override public List<AlignedSequence<S, C>> getAlignedSequences(S... sequences) { List<AlignedSequence<S, C>> tempList = new ArrayList<AlignedSequence<S, C>>(); for (S s : sequences) { tempList.add(getAlignedSequence(s)); } return Collections.unmodifiableList(tempList); } @Override public C getCompoundAt(int listIndex, int alignmentIndex) { return getAlignedSequence(listIndex).getCompoundAt(alignmentIndex); } @Override public C getCompoundAt(S sequence, int alignmentIndex) { AlignedSequence<S, C> s = getAlignedSequence(sequence); return (s == null) ? null : s.getCompoundAt(alignmentIndex); } @Override public int[] getCompoundCountsAt(int alignmentIndex) { return getCompoundCountsAt(alignmentIndex, getCompoundSet().getAllCompounds()); } @Override public int[] getCompoundCountsAt(int alignmentIndex, List<C> compounds) { int[] counts = new int[compounds.size()]; C gap = getCompoundSet().getCompoundForString("-"); int igap = compounds.indexOf(gap); for (C compound : getCompoundsAt(alignmentIndex)) { int i = compounds.indexOf(compound); if (i >= 0 && i != igap && !getCompoundSet().compoundsEquivalent(compound, gap)) { counts[i]++; } } return counts; } @Override public List<C> getCompoundsAt(int alignmentIndex) { // TODO handle circular alignments List<C> column = new ArrayList<C>(); for (AlignedSequence<S, C> s : list) { column.add(s.getCompoundAt(alignmentIndex)); } return Collections.unmodifiableList(column); } @Override public CompoundSet<C> getCompoundSet() { return list.get(0).getCompoundSet(); } @Override public float[] getCompoundWeightsAt(int alignmentIndex) { return getCompoundWeightsAt(alignmentIndex, getCompoundSet().getAllCompounds()); } @Override public float[] getCompoundWeightsAt(int alignmentIndex, List<C> compounds) { float[] weights = new float[compounds.size()]; int[] counts = getCompoundCountsAt(alignmentIndex, compounds); float total = 0.0f; for (int i : counts) { total += i; } if (total > 0.0f) { for (int i = 0; i < weights.length; i++) { weights[i] = counts[i]/total; } } return weights; } @Override public int getIndexOf(C compound) { for (int i = 1; i <= length; i++) { if (getCompoundsAt(i).contains(compound)) { return i; } } return -1; } @Override public int[] getIndicesAt(int alignmentIndex) { int[] indices = new int[list.size()]; for (int i = 0; i < indices.length; i++) { indices[i] = list.get(i).getSequenceIndexAt(alignmentIndex); } return indices; } @Override public int getLastIndexOf(C compound) { for (int i = length; i >= 1; i if (getCompoundsAt(i).contains(compound)) { return i; } } return -1; } @Override public int getLength() { return length; } @Override public List<S> getOriginalSequences() { return originals; } @Override public int getSize() { int size = 0; for (AlignedSequence<S, C> s : list) { size += s.getOverlapCount(); } return size; } @Override public ProfileView<S, C> getSubProfile(Location location) { // TODO ProfileView<S, C> getSubProfile(Location) return null; } @Override public boolean hasGap(int alignmentIndex) { C gap = getCompoundSet().getCompoundForString("-"); for (C compound : getCompoundsAt(alignmentIndex)) { if (getCompoundSet().compoundsEquivalent(compound, gap)) { return true; } } return false; } @Override public boolean isCircular() { for (AlignedSequence<S, C> s : list) { if (s.isCircular()) { return true; } } return false; } @Override public String toString(int width) { return toString(width, null, IOUtils.getIDFormat(list), true, true, true, true, true, false); } @Override public String toString(StringFormat format) { switch (format) { case ALN: case CLUSTALW: default: return toString(60, String.format("CLUSTAL W MSA from BioJava%n%n"), IOUtils.getIDFormat(list) + " ", false, true, true, false, true, false); case FASTA: return toString(60, null, ">%s%n", false, false, false, false, false, false); case GCG: case MSF: return toString(50, IOUtils.getGCGHeader(list), IOUtils.getIDFormat(list), false, false, true, false, false, false); case PDBWEB: return toString(60, null, "%s", true, true, true, false, true, true); } } // method from Object @Override public String toString() { return toString(getLength(), null, null, false, false, false, false, false, false); } // method for Iterable @Override public Iterator<AlignedSequence<S, C>> iterator() { return list.iterator(); } // helper methods // creates formatted String private String toString(int width, String header, String idFormat, boolean seqIndexPre, boolean seqIndexPost, boolean interlaced, boolean aligIndices, boolean aligConservation, boolean webDisplay) { // TODO handle circular alignments StringBuilder s = (header == null) ? new StringBuilder() : new StringBuilder(header); if ( webDisplay && list.size() == 2){ s.append("<div><pre>"); } width = Math.max(1, width); int seqIndexPad = (int) (Math.floor(Math.log10(getLength())) + 2); String seqIndexFormatPre = "%" + seqIndexPad + "d ", seqIndexFormatPost = "%" + seqIndexPad + "d"; if (interlaced) { String aligIndFormat = "%-" + Math.max(1, width / 2) + "d %" + Math.max(1, width - (width / 2) - 1) + "d%n"; for (int i = 0; i < getLength(); i += width) { int start = i + 1, end = Math.min(getLength(), i + width); if (i > 0) { s.append(String.format("%n")); } if (aligIndices) { if (end < i + width) { int line = end - start + 1; aligIndFormat = "%-" + Math.max(1, line / 2) + "d %" + Math.max(1, line - (line / 2) - 1) + "d%n"; } if (idFormat != null) { s.append(String.format(idFormat, "")); } if (seqIndexPre) { s.append(String.format("%" + (seqIndexPad + 1) + "s", "")); } s.append(String.format(aligIndFormat, start, end)); } int counter = 0; for (AlignedSequence<S, C> as : list) { counter++; if ( webDisplay && list.size() == 2){ printSequenceAlignmentWeb(s, counter, idFormat, seqIndexPre, seqIndexFormatPre, seqIndexPost, seqIndexFormatPost, start, end); } else { if (idFormat != null) { s.append(String.format(idFormat, as.getAccession())); } if (seqIndexPre) { s.append(String.format(seqIndexFormatPre, as.getSequenceIndexAt(start))); } s.append(as.getSubSequence(start, end).getSequenceAsString()); if (seqIndexPost) { s.append(String.format(seqIndexFormatPost, as.getSequenceIndexAt(end))); } s.append(String.format("%n")); } if (aligConservation && list.size() == 2 && counter == 1) { printConservation(s, idFormat, seqIndexPad, seqIndexPre, start, end, webDisplay); } } } } else { for (AlignedSequence<S, C> as : list) { if (idFormat != null) { s.append(String.format(idFormat, as.getAccession())); } for (int i = 0; i < getLength(); i += width) { int start = i + 1, end = Math.min(getLength(), i + width); if (seqIndexPre) { s.append(String.format(seqIndexFormatPre, as.getSequenceIndexAt(start))); } s.append(as.getSubSequence(start, end).getSequenceAsString()); if (seqIndexPost) { s.append(String.format(seqIndexFormatPost, as.getSequenceIndexAt(end))); } s.append(String.format("%n")); } } } if (webDisplay && aligConservation && list.size() == 2) { s.append(IOUtils.getPDBLegend()); } return s.toString(); } private void printSequenceAlignmentWeb(StringBuilder s, int counter, String idFormat, boolean seqIndexPre, String seqIndexFormatPre, boolean seqIndexPost, String seqIndexFormatPost, int start, int end) { AlignedSequence<S,C> as1 = list.get(0), as2 = list.get(1), as = list.get(counter - 1); if (idFormat != null) { s.append(String.format(idFormat, as.getAccession())); } if (seqIndexPre) { s.append(String.format(seqIndexFormatPre, as.getSequenceIndexAt(start))); } String mySeq = as.getSubSequence(start, end).getSequenceAsString(); String s1 = as1.getSubSequence(start, end).getSequenceAsString(); String s2 = as2.getSubSequence(start, end).getSequenceAsString(); for (int i = 0; i < s1.length(); i++) { if (i >= s2.length() || i >= mySeq.length()) break; char c1 = s1.charAt(i); char c2 = s2.charAt(i); char c = mySeq.charAt(i); s.append(IOUtils.getPDBCharacter(true, c1, c2, isSimilar(c1, c2), c)); } if (seqIndexPost) { s.append(String.format(seqIndexFormatPost, as.getSequenceIndexAt(end))); } s.append(String.format("%n")); } private void printConservation(StringBuilder s, String idFormat, int seqIndexPad, boolean seqIndexPre, int start, int end, boolean webDisplay) { AlignedSequence<S,C> as1 = list.get(0), as2 = list.get(1); if (idFormat != null) { AccessionID ac1 = as1.getAccession(); String id1 = (ac1 == null) ? "null" : ac1.getID(); id1 = id1.replaceAll(".", " "); s.append(String.format(idFormat, id1)); } if (seqIndexPre) { s.append(String.format("%" + (seqIndexPad + 1) + "s", "")); } String subseq1 = as1.getSubSequence(start, end).getSequenceAsString(); String subseq2 = as2.getSubSequence(start, end).getSequenceAsString(); for ( int ii =0 ; ii < subseq1.length() ; ii++){ if ( ii >= subseq2.length()) break; char c1 = subseq1.charAt(ii); char c2 = subseq2.charAt(ii); s.append(IOUtils.getPDBConservation(webDisplay, c1, c2, isSimilar(c1, c2))); } s.append(String.format("%n")); } protected static final SubstitutionMatrix<AminoAcidCompound> matrix = SubstitutionMatrixHelper.getBlosum65(); private boolean isSimilar(char c1, char c2) { AminoAcidCompoundSet set = AminoAcidCompoundSet.getAminoAcidCompoundSet(); AminoAcidCompound aa1 = set.getCompoundForString(""+c1); AminoAcidCompound aa2 = set.getCompoundForString(""+c2); short val = matrix.getValue(aa1,aa2); return val > 0; } }
package bndtools.jareditor.internal; import java.io.IOException; import java.net.URI; import java.util.Collection; import java.util.Map; import java.util.TreeMap; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StyledCellLabelProvider; import org.eclipse.jface.viewers.StyledString; import org.eclipse.jface.viewers.TreePath; import org.eclipse.jface.viewers.TreeSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Tree; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.forms.AbstractFormPart; import org.eclipse.ui.forms.IManagedForm; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Section; import org.eclipse.ui.plugin.AbstractUIPlugin; public class JARContentTreePart extends AbstractFormPart { protected final IManagedForm managedForm; private final Tree tree; private final TreeViewer viewer; private final JARTreeContentProvider contentProvider = new JARTreeContentProvider(); private String[] selectedPath = null; public JARContentTreePart(final Composite parent, final IManagedForm managedForm) { this.managedForm = managedForm; FormToolkit toolkit = managedForm.getToolkit(); Section section = toolkit.createSection(parent, Section.TITLE_BAR | Section.EXPANDED); section.setText("Content Tree"); tree = toolkit.createTree(section, SWT.FULL_SELECTION | SWT.SINGLE); tree.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TREE_BORDER); section.setClient(tree); toolkit.paintBordersFor(section); viewer = new TreeViewer(tree); viewer.setContentProvider(contentProvider); viewer.setLabelProvider(new JARTreeLabelProvider()); managedForm.addPart(this); viewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(final SelectionChangedEvent event) { JARContentTreePart.this.managedForm.fireSelectionChanged(JARContentTreePart.this, event.getSelection()); } }); parent.setLayout(new GridLayout()); section.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); } @Override public void initialize(final IManagedForm form) { super.initialize(form); } @Override public boolean isStale() { // Claim to always be stale, so we always get refresh events. return true; } @Override public void refresh() { super.refresh(); Object input = getManagedForm().getInput(); viewer.setInput(input); refreshSelectedPath(); } private void refreshSelectedPath() { if (selectedPath != null) { TreePath treePath = contentProvider.findPath(selectedPath); if (treePath != null) { viewer.setSelection(new TreeSelection(treePath), true); } else { viewer.setSelection(TreeSelection.EMPTY); } } } @Override public boolean setFormInput(final Object input) { viewer.setInput(input); return false; } void setSelectedPath(final String[] path) { selectedPath = path; if ( (viewer != null) && (viewer.getInput() != null)) { refreshSelectedPath(); } } String[] getSelectedPath() { String[] result; if (viewer.getSelection().isEmpty()) { result = null; } else { TreeSelection selection = (TreeSelection) viewer.getSelection(); TreePath treePath = selection.getPaths()[0]; result = new String[treePath.getSegmentCount()]; for (int i = 0; i < result.length; i++) { result[i] = treePath.getSegment(i).toString(); } } return result; } private static class JARTreeLabelProvider extends StyledCellLabelProvider { private final Image folderImg = AbstractUIPlugin.imageDescriptorFromPlugin(PluginConstants.PLUGIN_ID, "/icons/fldr_obj.gif").createImage(); private final Image fileImg = AbstractUIPlugin.imageDescriptorFromPlugin(PluginConstants.PLUGIN_ID, "/icons/file_obj.gif").createImage(); public JARTreeLabelProvider() { super(); } @Override public void update(final ViewerCell cell) { ZipTreeNode node = (ZipTreeNode) cell.getElement(); String name = node.toString(); StyledString label = new StyledString(name); if (name.endsWith("/")) { cell.setImage(folderImg); } else { cell.setImage(fileImg); ZipEntry entry = node.getZipEntry(); if (entry != null) { label.append(String.format(" [sz: %,d; crc: %d]", entry.getSize(), entry.getCrc()), StyledString.QUALIFIER_STYLER); } } cell.setText(label.getString()); cell.setStyleRanges(label.getStyleRanges()); } @Override public void dispose() { super.dispose(); folderImg.dispose(); fileImg.dispose(); } } private class JARTreeContentProvider implements ITreeContentProvider { Map<String,ZipTreeNode> entryMap; public JARTreeContentProvider() { super(); } @Override public Object[] getChildren(final Object parentElement) { ZipTreeNode parentNode = (ZipTreeNode) parentElement; return parentNode.getChildren().toArray(); } @Override public Object getParent(final Object element) { return ((ZipTreeNode) element).getParent(); } @Override public boolean hasChildren(final Object element) { return ((ZipTreeNode) element).hasChildren(); } @Override public Object[] getElements(final Object inputElement) { return entryMap.values().toArray(); } @Override public void dispose() { } @Override public void inputChanged(final Viewer viewer, final Object oldInput, final Object newInput) { entryMap = new TreeMap<String,ZipTreeNode>(); final URI uri = URIHelper.retrieveFileURI((IEditorInput) newInput); if (uri != null) { ZipInputStream zis = null; try { zis = new ZipInputStream(uri.toURL().openStream()); ZipEntry entry; while ( (entry = zis.getNextEntry()) != null) { ZipTreeNode.addEntry(entryMap, entry); } zis.close(); } catch (IOException e) { Status status = new Status(IStatus.ERROR, PluginConstants.PLUGIN_ID, 0, "I/O error reading JAR file contents", e); ErrorDialog.openError(managedForm.getForm().getShell(), "Error", null, status); } finally { if (zis != null) { try { zis.close(); } catch (IOException e) { // nothing to do } } } } } public TreePath findPath(final String[] path) { if ( (path == null) || (path.length == 0)) { return null; } TreePath result = TreePath.EMPTY; ZipTreeNode current = entryMap.get(path[0]); if (current == null) { return null; } result = result.createChildPath(current); segments: for (int i = 1; i < path.length; i++) { Collection<ZipTreeNode> children = current.getChildren(); for (ZipTreeNode child: children) { if (path[i].equals(child.toString())) { current = child; result = result.createChildPath(child); continue segments; } } return null; } return result; } } }
package ch.elexis.core.data.activator; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.UUID; import org.eclipse.equinox.internal.app.CommandLineArgs; import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.elexis.Desk; import ch.elexis.admin.AbstractAccessControl; import ch.elexis.admin.RoleBasedAccessControl; import ch.elexis.core.constants.Preferences; import ch.elexis.core.constants.StringConstants; import ch.elexis.core.data.constants.ElexisSystemPropertyConstants; import ch.elexis.core.data.events.ElexisEvent; import ch.elexis.core.data.events.ElexisEventDispatcher; import ch.elexis.core.data.events.Heartbeat; import ch.elexis.core.data.events.Heartbeat.HeartListener; import ch.elexis.core.data.events.PatientEventListener; import ch.elexis.core.data.interfaces.ShutdownJob; import ch.elexis.core.data.interfaces.events.MessageEvent; import ch.elexis.core.data.interfaces.scripting.Interpreter; import ch.elexis.core.data.lock.LocalLockService; import ch.elexis.core.data.preferences.CorePreferenceInitializer; import ch.elexis.core.data.server.ElexisServerEventService; import ch.elexis.core.data.service.OrderService; import ch.elexis.core.data.service.StockCommissioningSystemService; import ch.elexis.core.data.service.StockService; import ch.elexis.core.lock.ILocalLockService; import ch.elexis.core.services.IOrderService; import ch.elexis.core.services.IStockCommissioningSystemService; import ch.elexis.data.Anwender; import ch.elexis.data.Kontakt; import ch.elexis.data.Mandant; import ch.elexis.data.PersistentObject; import ch.elexis.data.PersistentObjectFactory; import ch.elexis.data.Query; import ch.elexis.data.User; import ch.rgw.io.LockFile; import ch.rgw.io.Settings; import ch.rgw.io.SqlSettings; import ch.rgw.io.SysSettings; import ch.rgw.tools.Log; import ch.rgw.tools.StringTool; import ch.rgw.tools.VersionInfo; /** * @since 3.0.0 */ public class CoreHub implements BundleActivator { public static final String PLUGIN_ID = "ch.elexis.core.data"; /* * This version is needed to compare the DB */ public static String Version = "3.7.0.qualifier"; //$NON-NLS-1$ public static final String APPLICATION_NAME = "Elexis Core"; //$NON-NLS-1$ static final String neededJRE = "1.8.0"; //$NON-NLS-1$ public static final String DBVersion = "3.6.0"; //$NON-NLS-1$ protected static Logger log = LoggerFactory.getLogger(CoreHub.class.getName()); private static String LocalCfgFile = null; private static String elexis_version = null; private BundleContext context; /** Das Singleton-Objekt dieser Klasse */ public static CoreHub plugin; private static List<ShutdownJob> shutdownJobs = new LinkedList<>(); public static final PersistentObjectFactory poFactory = new PersistentObjectFactory(); /** Heartbeat */ public static Heartbeat heart; static File userDir; /** Globale Einstellungen (Werden in der Datenbank gespeichert) */ public static Settings globalCfg; /** * Lokale Einstellungen (Werden in userhome/localCfg_xxx.xml gespeichert) </br> * <b>WARNING: can not handle more than one / in config name!</b> */ public static Settings localCfg; /** Anwenderspezifische Einstellungen (Werden in der Datenbank gespeichert) */ public static Settings userCfg; /** Mandantspezifische EInstellungen (Werden in der Datenbank gespeichert) */ public static Settings mandantCfg; public static Anwender actUser; // TODO set /** * @deprecated please use {@link ElexisEventDispatcher#getSelectedMandator()} to retrieve * current mandator */ @Deprecated public static Mandant actMandant; private static boolean tooManyInstances; public static final CorePreferenceInitializer pin = new CorePreferenceInitializer(); /** Die zentrale Zugriffskontrolle */ public static final AbstractAccessControl acl = new RoleBasedAccessControl(); /** Lock Service **/ private static ILocalLockService localLockService; /** Stock Service **/ private static final StockService stockService = new StockService(); /** Order Service **/ private static final IOrderService orderService = new OrderService(); /** Event Service to transport Events to the Elexis Server */ private static ElexisServerEventService elexisServerEventService; /** * Stock commissioning system service */ private static final IStockCommissioningSystemService stockCommissioningSystemService = new StockCommissioningSystemService(); /** * The listener for patient events */ private final PatientEventListener eeli_pat = new PatientEventListener(); public static boolean isTooManyInstances(){ return tooManyInstances; } /** * get the base directory of this currently running elexis application * * @return the topmost directory of this application or null if this information could not be * retrieved */ public static String getBasePath(){ return FrameworkUtil.getBundle(CoreHub.class).getEntry("/").toString(); } /** * Return a directory suitable for temporary files. Most probably this will be a default tempdir * provided by the os. If none such exists, it will be the user dir. * * @return always a valid and writable directory. */ public static File getTempDir(){ File ret = null; String temp = System.getProperty("java.io.tmpdir"); //$NON-NLS-1$ if (!StringTool.isNothing(temp)) { ret = new File(temp); if (ret.exists() && ret.isDirectory()) { return ret; } else { if (ret.mkdirs()) { return ret; } } } return getWritableUserDir(); } /** * return a directory suitable for plugin specific configuration data. If no such dir exists, it * will be created. If it could not be created, the application will refuse to start. * * @return a directory that exists always and is always writable and readable for plugins of the * currently running elexis instance. Caution: this directory is not necessarily shared * among different OS-Users. In Windows it is normally %USERPROFILE%\elexis, in Linux * ~./elexis */ public static File getWritableUserDir(){ if (userDir == null) { String userhome = null; if (localCfg != null) { userhome = localCfg.get("elexis-userDir", null); //$NON-NLS-1$ } if (userhome == null) { userhome = System.getProperty("user.home"); //$NON-NLS-1$ } if (StringTool.isNothing(userhome)) { userhome = System.getProperty("java.io.tempdir"); //$NON-NLS-1$ } userDir = new File(userhome, "elexis"); //$NON-NLS-1$ } if (!userDir.exists()) { if (!userDir.mkdirs()) { System.err.print("fatal: could not create Userdir"); //$NON-NLS-1$ MessageEvent.fireLoggedError("Panic exit", "could not create userdir " + userDir.getAbsolutePath()); System.exit(-5); } } return userDir; } @Override public void start(BundleContext context) throws Exception{ this.context = context; log.debug("Starting " + CoreHub.class.getName()); plugin = this; localLockService = new LocalLockService(); elexisServerEventService = new ElexisServerEventService(); startUpBundle(); setUserDir(userDir); heart = Heartbeat.getInstance(); ElexisEventDispatcher.getInstance().addListeners(eeli_pat); // add core ClassLoader to default Script Interpreter Interpreter.classLoaders.add(CoreHub.class.getClassLoader()); if (!ElexisSystemPropertyConstants.RUN_MODE_FROM_SCRATCH .equals(System.getProperty(ElexisSystemPropertyConstants.RUN_MODE))) Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run(){ SysSettings localCfg = (SysSettings) CoreHub.localCfg; localCfg.write_xml(LocalCfgFile); } }); } public static String readElexisBuildVersion(){ if ( elexis_version != null ) { return elexis_version; } Properties prop = new Properties(); String url_name = "platform:/plugin/ch.elexis.core.data/rsc/version.properties"; try (InputStream inputStream = new URL(url_name).openConnection().getInputStream()) { if (inputStream != null) { prop.load(inputStream); elexis_version = prop.getProperty("elexis.version").replace("-SNAPSHOT", ""); } } catch (IOException e) { elexis_version = plugin.Version; // log.warn("Error reading build version information from [{}]", url_name, e); } return elexis_version; } @Override public void stop(BundleContext context) throws Exception{ log.debug("Stopping " + CoreHub.class.getName()); getLocalLockService().releaseAllLocks(); getLocalLockService().shutdown(); CoreHub.logoffAnwender(); PersistentObject.disconnect(); ElexisEventDispatcher.getInstance().removeListeners(eeli_pat); ElexisEventDispatcher.getInstance().dump(); globalCfg = null; heart.stop(); plugin = null; this.context = null; } private void startUpBundle(){ String[] args = CommandLineArgs.getApplicationArgs(); String config = "default"; //$NON-NLS-1$ for (String s : args) { if (s.startsWith("--use-config=")) { //$NON-NLS-1$ String[] c = s.split("="); //$NON-NLS-1$ config = c[1]; } } if (ElexisSystemPropertyConstants.RUN_MODE_FROM_SCRATCH .equals(System.getProperty(ElexisSystemPropertyConstants.RUN_MODE))) { config = UUID.randomUUID().toString(); } loadLocalCfg(config); // Damit Anfragen auf userCfg und mandantCfg bei nicht eingeloggtem User // keine NPE werfen userCfg = localCfg; mandantCfg = localCfg; VersionInfo vI = new VersionInfo(System.getProperty("java.version", "0.0.0")); //$NON-NLS-1$ //$NON-NLS-2$ log.info(getId() + "; Java: " + vI.version() + "\nencoding: " + System.getProperty("file.encoding")); if (vI.isOlder(neededJRE)) { MessageEvent.fireLoggedError("Invalid Java version", "Your Java version is older than " + neededJRE + ", please update."); } log.info("Basepath: " + getBasePath()); pin.initializeDefaultPreferences(); heart = Heartbeat.getInstance(); initializeLock(); } private static void initializeLock(){ final int timeoutSeconds = 600; try { final LockFile lockfile = new LockFile(userDir, "elexislock", 4, timeoutSeconds); //$NON-NLS-1$ final int n = lockfile.lock(); if (n == 0) { MessageEvent.fireLoggedError("Too many instances", "Too many concurrent instances of Elexis running. Check elexislock files in " + userDir); tooManyInstances = true; } else { tooManyInstances = false; HeartListener lockListener = new HeartListener() { long timeSet; @Override public void heartbeat(){ long now = System.currentTimeMillis(); if ((now - timeSet) > timeoutSeconds) { lockfile.updateLock(n); timeSet = now; } } }; heart.addListener(lockListener, Heartbeat.FREQUENCY_LOW); } } catch (IOException ex) { log.error("Can not aquire lock file in " + userDir + "; " + ex.getMessage()); //$NON-NLS-1$ } } public static String getId(){ StringBuilder sb = new StringBuilder(); sb.append(APPLICATION_NAME).append(" v.").append(Version).append("\n") .append(CoreHubHelper.getRevision(true, plugin)).append("\n") .append(System.getProperty("os.name")).append(StringConstants.SLASH) .append(System.getProperty("os.version")).append(StringConstants.SLASH) .append(System.getProperty("os.arch")); //$NON-NLS-1$ return sb.toString(); } private void loadLocalCfg(String branch){ LocalCfgFile = CoreHubHelper.getWritableUserDir() + "/localCfg_" + branch + ".xml"; String msg = "loadLocalCfg: Loading branch " + branch + " from " + LocalCfgFile; System.out.println(msg); log.debug(msg); SysSettings cfg = new SysSettings(SysSettings.USER_SETTINGS, Desk.class); cfg.read_xml(LocalCfgFile); CoreHub.localCfg = cfg; } public static void setMandant(Mandant newMandant){ if (actMandant != null && mandantCfg != null) { mandantCfg.flush(); } if (newMandant == null) { mandantCfg = userCfg; } else { mandantCfg = getUserSetting(newMandant); } actMandant = newMandant; ElexisEventDispatcher.getInstance() .fire(new ElexisEvent(newMandant, Mandant.class, ElexisEvent.EVENT_MANDATOR_CHANGED)); } public static Settings getUserSetting(Kontakt user){ if (StringConstants.ONE.equals(user.get(Kontakt.FLD_IS_USER))) { Settings settings = new SqlSettings(PersistentObject.getConnection(), "USERCONFIG", "Param", "Value", "UserID=" + user.getWrappedId()); return settings; } return null; } public Bundle getBundle(){ return context.getBundle(); } /** * get a list of all mandators known to this system */ public static List<Mandant> getMandantenList(){ Query<Mandant> qbe = new Query<>(Mandant.class); return qbe.execute(); } /** * get a list of all users known to this system */ public static List<Anwender> getUserList(){ Query<Anwender> qbe = new Query<>(Anwender.class); return qbe.execute(); } /** * Return the name of a config instance, the user chose. This is just the valuie of the * -Dconfig=xx runtime value or "default" if no -Dconfig was set */ public static String getCfgVariant(){ String config = System.getProperty("config"); return config == null ? "default" : config; } public void setUserDir(File dir){ userDir = dir; localCfg.set("elexis-userDir", dir.getAbsolutePath()); //$NON-NLS-1$ } /** * Add a ShutdownJob to the list of jobs that has to be done after the Elexis workbench was shut * down. * * @param job */ public static void addShutdownJob(final ShutdownJob job){ if (!shutdownJobs.contains(job)) { shutdownJobs.add(job); } } public static int getSystemLogLevel(){ return localCfg.get(Preferences.ABL_LOGLEVEL, Log.ERRORS); } /** * Perform the required tasks to log off the current {@link Anwender} * * @since 3.1 moved from {@link Anwender} class */ public static void logoffAnwender(){ if (CoreHub.actUser == null) return; if (CoreHub.userCfg != null) { CoreHub.userCfg.flush(); } getLocalLockService().releaseAllLocks(); CoreHub.setMandant(null); CoreHub.heart.suspend(); CoreHub.actUser = null; ElexisEventDispatcher.getInstance() .fire(new ElexisEvent(null, Anwender.class, ElexisEvent.EVENT_USER_CHANGED)); ElexisEventDispatcher.getInstance() .fire(new ElexisEvent(null, User.class, ElexisEvent.EVENT_DESELECTED)); CoreHub.userCfg = CoreHub.localCfg; } public static ILocalLockService getLocalLockService(){ return localLockService; } public static StockService getStockService(){ return stockService; } public static IStockCommissioningSystemService getStockCommissioningSystemService(){ return stockCommissioningSystemService; } public static IOrderService getOrderService(){ return orderService; } public static ElexisServerEventService getElexisServerEventService(){ return elexisServerEventService; } }
package net.bytebuddy.agent.builder; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import net.bytebuddy.ByteBuddy; import net.bytebuddy.asm.AsmVisitorWrapper; import net.bytebuddy.description.field.FieldDescription; import net.bytebuddy.description.method.MethodDescription; import net.bytebuddy.description.method.ParameterDescription; import net.bytebuddy.description.modifier.*; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.dynamic.ClassFileLocator; import net.bytebuddy.dynamic.DynamicType; import net.bytebuddy.dynamic.loading.ClassInjector; import net.bytebuddy.dynamic.loading.ClassReloadingStrategy; import net.bytebuddy.dynamic.scaffold.InstrumentedType; import net.bytebuddy.dynamic.scaffold.inline.MethodNameTransformer; import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy; import net.bytebuddy.implementation.ExceptionMethod; import net.bytebuddy.implementation.Implementation; import net.bytebuddy.implementation.LoadedTypeInitializer; import net.bytebuddy.implementation.auxiliary.AuxiliaryType; import net.bytebuddy.implementation.bytecode.*; import net.bytebuddy.implementation.bytecode.assign.Assigner; import net.bytebuddy.implementation.bytecode.assign.TypeCasting; import net.bytebuddy.implementation.bytecode.collection.ArrayFactory; import net.bytebuddy.implementation.bytecode.constant.ClassConstant; import net.bytebuddy.implementation.bytecode.constant.IntegerConstant; import net.bytebuddy.implementation.bytecode.constant.NullConstant; import net.bytebuddy.implementation.bytecode.constant.TextConstant; import net.bytebuddy.implementation.bytecode.member.FieldAccess; import net.bytebuddy.implementation.bytecode.member.MethodInvocation; import net.bytebuddy.implementation.bytecode.member.MethodReturn; import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess; import net.bytebuddy.matcher.ElementMatcher; import net.bytebuddy.pool.TypePool; import net.bytebuddy.utility.JavaInstance; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import java.io.*; import java.lang.instrument.ClassDefinition; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.Instrumentation; import java.lang.instrument.UnmodifiableClassException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.AccessControlContext; import java.security.AccessController; import java.security.ProtectionDomain; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; import static net.bytebuddy.matcher.ElementMatchers.*; public interface AgentBuilder { /** * <p> * Matches a type being loaded in order to apply the supplied * {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type. * </p> * <p> * <b>Note</b>: When applying a matcher, regard the performance implications by * {@link AgentBuilder#ignore(ElementMatcher)}. The former matcher is applied first such that it makes sense * to ignore name spaces that are irrelevant to instrumentation. If possible, it is also recommended, to * exclude class loaders such as for example the bootstrap class loader. * </p> * * @param matcher A matcher that decides if the entailed * {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should be applied for a type that * is being loaded. * @return A definable that represents this agent builder which allows for the definition of one or several * {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when the given {@code matcher} * indicates a match. */ Identified type(RawMatcher matcher); /** * <p> * Matches a type being loaded in order to apply the supplied * {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type. * </p> * <p> * <b>Note</b>: When applying a matcher, regard the performance implications by * {@link AgentBuilder#ignore(ElementMatcher)}. The former matcher is applied first such that it makes sense * to ignore name spaces that are irrelevant to instrumentation. If possible, it is also recommended, to exclude * class loaders such as for example the bootstrap class loader by using * {@link AgentBuilder#type(ElementMatcher, ElementMatcher)} instead. * </p> * * @param typeMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied on the type being loaded that * decides if the entailed {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should * be applied for that type. * @return A definable that represents this agent builder which allows for the definition of one or several * {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when the given {@code typeMatcher} * indicates a match. */ Identified type(ElementMatcher<? super TypeDescription> typeMatcher); /** * <p> * Matches a type being loaded in order to apply the supplied * {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type. * </p> * <p> * <b>Note</b>: When applying a matcher, regard the performance implications by * {@link AgentBuilder#ignore(ElementMatcher)}. The former matcher is applied first such that it makes sense * to ignore name spaces that are irrelevant to instrumentation. * </p> * * @param typeMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied on the type being * loaded that decides if the entailed * {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should be applied for * that type. * @param classLoaderMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied to the * {@link java.lang.ClassLoader} that is loading the type being loaded. This matcher * is always applied first where the type matcher is not applied in case that this * matcher does not indicate a match. * @return A definable that represents this agent builder which allows for the definition of one or several * {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when both the given * {@code typeMatcher} and {@code classLoaderMatcher} indicate a match. */ Identified type(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher); /** * Defines the given {@link net.bytebuddy.ByteBuddy} instance to be used by the created agent. * * @param byteBuddy The Byte Buddy instance to be used. * @return A new instance of this agent builder which makes use of the given {@code byteBuddy} instance. */ AgentBuilder with(ByteBuddy byteBuddy); /** * Defines the given {@link net.bytebuddy.agent.builder.AgentBuilder.Listener} to be notified by the created agent. * The given listener is notified after any other listener that is already registered. If a listener is registered * twice, it is also notified twice. * * @param listener The listener to be notified. * @return A new instance of this agent builder which creates an agent that informs the given listener about * events. */ AgentBuilder with(Listener listener); /** * Defines the use of the given binary locator for locating binary data to given class names. * * @param binaryLocator The binary locator to use. * @return A new instance of this agent builder which uses the given binary locator for looking up class files. */ AgentBuilder with(BinaryLocator binaryLocator); /** * Defines the use of the given definition handler that determines if a type should be rebased or redefined. * * @param typeStrategy The definition handler to use. * @return A new instance of this agent builder which uses the given definition handler. */ AgentBuilder with(TypeStrategy typeStrategy); /** * Defines classes to be loaded using the given access control context. * * @param accessControlContext The access control context to be used for loading classes. * @return A new instance of this agent builder which uses the given access control context for class loading. */ AgentBuilder with(AccessControlContext accessControlContext); /** * Defines a given initialization strategy to be applied to generated types. An initialization strategy is responsible * for setting up a type after it was loaded. This initialization must be performed after the transformation because * a Java agent is only invoked before loading a type. By default, the initialization logic is added to a class's type * initializer which queries a global object for any objects that are to be injected into the generated type. * * @param initializationStrategy The initialization strategy to use. * @return A new instance of this agent builder that applies the given initialization strategy. */ AgentBuilder with(InitializationStrategy initializationStrategy); /** * Specifies a strategy for modifying existing types. * * @param redefinitionStrategy The redefinition strategy to apply. * @return A new instance of this agent builder that applies the given redefinition strategy. */ AgentBuilder with(RedefinitionStrategy redefinitionStrategy); /** * <p> * Enables or disables management of the JVM's {@code LambdaMetafactory} which is responsible for creating classes that * implement lambda expressions. Without this feature enabled, classes that are represented by lambda expressions are * not instrumented by the JVM such that Java agents have no effect on them when a lambda expression's class is loaded * for the first time. * </p> * <p> * When activating this feature, Byte Buddy instruments the {@code LambdaMetafactory} and takes over the responsibility * of creating classes that represent lambda expressions. In doing so, Byte Buddy has the opportunity to apply the built * class file transformer. If the current VM does not support lambda expressions, activating this feature has no effect. * </p> * <p> * <b>Important</b>: If this feature is active, it is important to release the built class file transformer when * deactivating it. Normally, it is sufficient to call {@link Instrumentation#removeTransformer(ClassFileTransformer)}. * When this feature is enabled, it is however also required to invoke * {@link LambdaInstrumentationStrategy#release(ClassFileTransformer, Instrumentation)}. Otherwise, the executing VMs class * loader retains a reference to the class file transformer what can cause a memory leak. * </p> * * @param lambdaInstrumentationStrategy {@code true} if this feature should be enabled. * @return A new instance of this agent builder where this feature is explicitly enabled or disabled. */ AgentBuilder with(LambdaInstrumentationStrategy lambdaInstrumentationStrategy); /** * Enables class injection of auxiliary classes into the bootstrap class loader. * * @param folder The folder in which jar files of the injected classes are to be stored. * @param instrumentation The instrumentation instance that is used for appending jar files to the * bootstrap class path. * @return An agent builder with bootstrap class loader class injection enabled. */ AgentBuilder enableBootstrapInjection(File folder, Instrumentation instrumentation); /** * Enables the use of the given native method prefix for instrumented methods. Note that this prefix is also * applied when preserving non-native methods. The use of this prefix is also registered when installing the * final agent with an {@link java.lang.instrument.Instrumentation}. * * @param prefix The prefix to be used. * @return A new instance of this agent builder which uses the given native method prefix. */ AgentBuilder enableNativeMethodPrefix(String prefix); /** * Disables the use of a native method prefix for instrumented methods. * * @return A new instance of this agent builder which does not use a native method prefix. */ AgentBuilder disableNativeMethodPrefix(); /** * Disables injection of auxiliary classes into the bootstrap class path. * * @return A new instance of this agent builder which does not apply bootstrap class loader injection. */ AgentBuilder disableBootstrapInjection(); /** * <p> * Excludes any type that is matched by the provided matcher from instrumentation. By default, Byte Buddy does not * instrument synthetic types. * </p> * <p> * <b>Note</b>: For performance reasons, it is recommended to always include a matcher that excludes as many namespaces * as possible. Byte Buddy can determine a type's name without parsing its class file and can therefore discard such * types prematurely. When a different property of a type - such as for example its modifiers or its annotations is * accessed - Byte Buddy parses the class file lazily in order to allow for such a matching. Therefore, any exclusion * of a name should always be done as a first step and even if it does not influence the selection of what types are * matched. Without changing this property, the class file of every type is being parsed! * </p> * * @param ignoredTypes A matcher that identifies types that should not be instrumented. * @return A new instance of this agent builder that ignores all types that are matched by the provided matcher. * All previous matchers for ignored types are discarded. */ AgentBuilder ignore(ElementMatcher<? super TypeDescription> ignoredTypes); /** * Creates a {@link java.lang.instrument.ClassFileTransformer} that implements the configuration of this * agent builder. * * @return A class file transformer that implements the configuration of this agent builder. */ ClassFileTransformer makeRaw(); /** * Creates and installs a {@link java.lang.instrument.ClassFileTransformer} that implements the configuration of * this agent builder with a given {@link java.lang.instrument.Instrumentation}. If retransformation is enabled, * the installation also causes all loaded types to be retransformed. * * @param instrumentation The instrumentation on which this agent builder's configuration is to be installed. * @return The installed class file transformer. */ ClassFileTransformer installOn(Instrumentation instrumentation); /** * Creates and installs a {@link java.lang.instrument.ClassFileTransformer} that implements the configuration of * this agent builder with the Byte Buddy-agent which must be installed prior to calling this method. * * @return The installed class file transformer. */ ClassFileTransformer installOnByteBuddyAgent(); /** * Describes an {@link net.bytebuddy.agent.builder.AgentBuilder} which was handed a matcher for identifying * types to instrumented in order to supply one or several * {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s. */ interface Identified { /** * Applies the given transformer for the already supplied matcher. * * @param transformer The transformer to apply. * @return This agent builder with the transformer being applied when the previously supplied matcher * identified a type for instrumentation which also allows for the registration of subsequent transformers. */ Extendable transform(Transformer transformer); /** * This interface is used to allow for optionally providing several * {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer} to applied when a matcher identifies a type * to be instrumented. Any subsequent transformers are applied in the order they are registered. */ interface Extendable extends AgentBuilder, Identified { /* this is merely a unionizing interface that does not declare methods */ } } /** * A matcher that allows to determine if a {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer} * should be applied during the execution of a {@link java.lang.instrument.ClassFileTransformer} that was * generated by an {@link net.bytebuddy.agent.builder.AgentBuilder}. */ interface RawMatcher { /** * Decides if the given {@code typeDescription} should be instrumented with the entailed * {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s. * * @param typeDescription A description of the type to be instrumented. * @param classLoader The class loader of the instrumented type. Might be {@code null} if this class * loader represents the bootstrap class loader. * @param classBeingRedefined The class being redefined which is only not {@code null} if a retransformation * is applied. * @param protectionDomain The protection domain of the type being transformed. * @return {@code true} if the entailed {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should * be applied for the given {@code typeDescription}. */ boolean matches(TypeDescription typeDescription, ClassLoader classLoader, Class<?> classBeingRedefined, ProtectionDomain protectionDomain); /** * A raw matcher implementation that checks a {@link TypeDescription} * and its {@link java.lang.ClassLoader} against two suitable matchers in order to determine if the matched * type should be instrumented. */ class ForElementMatcherPair implements RawMatcher { /** * The type matcher to apply to a {@link TypeDescription}. */ private final ElementMatcher<? super TypeDescription> typeMatcher; /** * The class loader to apply to a {@link java.lang.ClassLoader}. */ private final ElementMatcher<? super ClassLoader> classLoaderMatcher; /** * Creates a new {@link net.bytebuddy.agent.builder.AgentBuilder.RawMatcher} that only matches the * supplied {@link TypeDescription} and its {@link java.lang.ClassLoader} against two matcher in order * to decided if an instrumentation should be conducted. * * @param typeMatcher The type matcher to apply to a * {@link TypeDescription}. * @param classLoaderMatcher The class loader to apply to a {@link java.lang.ClassLoader}. */ public ForElementMatcherPair(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) { this.typeMatcher = typeMatcher; this.classLoaderMatcher = classLoaderMatcher; } @Override public boolean matches(TypeDescription typeDescription, ClassLoader classLoader, Class<?> classBeingRedefined, ProtectionDomain protectionDomain) { return classLoaderMatcher.matches(classLoader) && typeMatcher.matches(typeDescription); } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && classLoaderMatcher.equals(((ForElementMatcherPair) other).classLoaderMatcher) && typeMatcher.equals(((ForElementMatcherPair) other).typeMatcher); } @Override public int hashCode() { int result = typeMatcher.hashCode(); result = 31 * result + classLoaderMatcher.hashCode(); return result; } @Override public String toString() { return "AgentBuilder.RawMatcher.ForElementMatcherPair{" + "typeMatcher=" + typeMatcher + ", classLoaderMatcher=" + classLoaderMatcher + '}'; } } } /** * A type strategy is responsible for creating a type builder for a type that is being instrumented. */ interface TypeStrategy { /** * Creates a type builder for a given type. * * @param typeDescription The type being instrumented. * @param byteBuddy The Byte Buddy configuration. * @param classFileLocator The class file locator to use. * @param methodNameTransformer The method name transformer to use. * @return A type builder for the given arguments. */ DynamicType.Builder<?> builder(TypeDescription typeDescription, ByteBuddy byteBuddy, ClassFileLocator classFileLocator, MethodNameTransformer methodNameTransformer); /** * Default implementations of type strategies. */ enum Default implements TypeStrategy { /** * A definition handler that performs a rebasing for all types. */ REBASE { @Override public DynamicType.Builder<?> builder(TypeDescription typeDescription, ByteBuddy byteBuddy, ClassFileLocator classFileLocator, MethodNameTransformer methodNameTransformer) { return byteBuddy.rebase(typeDescription, classFileLocator, methodNameTransformer); } }, /** * <p> * A definition handler that performs a redefinition for all types. * </p> * <p> * Note that the default agent builder is configured to apply a self initialization where a static class initializer * is added to the redefined class. This can be disabled by for example using a {@link InitializationStrategy.Minimal} or * {@link InitializationStrategy.NoOp}. Also, consider the constraints implied by {@link ByteBuddy#redefine(TypeDescription, ClassFileLocator)}. * </p> */ REDEFINE { @Override public DynamicType.Builder<?> builder(TypeDescription typeDescription, ByteBuddy byteBuddy, ClassFileLocator classFileLocator, MethodNameTransformer methodNameTransformer) { return byteBuddy.redefine(typeDescription, classFileLocator); } }; @Override public String toString() { return "AgentBuilder.TypeStrategy.Default." + name(); } } } /** * A transformer allows to apply modifications to a {@link net.bytebuddy.dynamic.DynamicType}. Such a modification * is then applied to any instrumented type that was matched by the preceding matcher. */ interface Transformer { /** * Allows for a transformation of a {@link net.bytebuddy.dynamic.DynamicType.Builder}. * * @param builder The dynamic builder to transform. * @param typeDescription The description of the type currently being instrumented. * @return A transformed version of the supplied {@code builder}. */ DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription); /** * A no-op implementation of a {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer} that does * not modify the supplied dynamic type. */ enum NoOp implements Transformer { /** * The singleton instance. */ INSTANCE; @Override public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription) { return builder; } @Override public String toString() { return "AgentBuilder.Transformer.NoOp." + name(); } } /** * A compound transformer that allows to group several * {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s as a single transformer. */ class Compound implements Transformer { /** * The transformers to apply in their application order. */ private final Transformer[] transformer; /** * Creates a new compound transformer. * * @param transformer The transformers to apply in their application order. */ public Compound(Transformer... transformer) { this.transformer = transformer; } @Override public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription) { for (Transformer transformer : this.transformer) { builder = transformer.transform(builder, typeDescription); } return builder; } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && Arrays.equals(transformer, ((Compound) other).transformer); } @Override public int hashCode() { return Arrays.hashCode(transformer); } @Override public String toString() { return "AgentBuilder.Transformer.Compound{" + "transformer=" + Arrays.toString(transformer) + '}'; } } } /** * A binary locator allows to specify how binary data is located by an * {@link net.bytebuddy.agent.builder.AgentBuilder}. */ interface BinaryLocator { /** * Creates a class file locator for the given class loader. * * @param classLoader The class loader for which a class file locator should be created. * Can be {@code null} to represent the bootstrap class loader. * @return An appropriate class file locator. */ ClassFileLocator classFileLocator(ClassLoader classLoader); /** * Creates a type pool for a given class file locator. * * @param classFileLocator The class file locator to use. * @param classLoader The class loader for which the class file locator was created. * @return A type pool for the supplied class file locator. */ TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader); /** * A default implementation of a {@link net.bytebuddy.agent.builder.AgentBuilder.BinaryLocator} that * is using a {@link net.bytebuddy.pool.TypePool.Default} with a * {@link net.bytebuddy.pool.TypePool.CacheProvider.Simple} and a * {@link net.bytebuddy.dynamic.ClassFileLocator.ForClassLoader}. */ enum Default implements BinaryLocator { /** * A binary locator that parses the code segment of each method for extracting information about parameter * names even if they are not explicitly included in a class file. * * @see net.bytebuddy.pool.TypePool.Default.ReaderMode#EXTENDED */ EXTENDED(TypePool.Default.ReaderMode.EXTENDED), /** * A binary locator that skips the code segment of each method and does therefore not extract information * about parameter names. Parameter names are still included if they are explicitly included in a class file. * * @see net.bytebuddy.pool.TypePool.Default.ReaderMode#FAST */ FAST(TypePool.Default.ReaderMode.FAST); /** * The reader mode to apply by this binary locator. */ private final TypePool.Default.ReaderMode readerMode; /** * Creates a new binary locator. * * @param readerMode The reader mode to apply by this binary locator. */ Default(TypePool.Default.ReaderMode readerMode) { this.readerMode = readerMode; } @Override public ClassFileLocator classFileLocator(ClassLoader classLoader) { return ClassFileLocator.ForClassLoader.of(classLoader); } @Override public TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader) { return new TypePool.LazyFacade(TypePool.Default.Precomputed.withObjectType(new TypePool.CacheProvider.Simple(), classFileLocator, readerMode)); } @Override public String toString() { return "AgentBuilder.BinaryLocator.Default." + name(); } } /** * <p> * A binary locator that loads referenced classes instead of describing unloaded versions. * </p> * <p> * <b>Important</b>: It is important to never query this binary locator for the currently instrumented type as this will yield a class * loading circularity which aborts any instrumentation with an error. * </p> * <p> * <b>Warning</b>: Warning, this binary locator <i>cannot be used for applying a redefinition</i> as it works on loaded classes only and * is agnostic of any way to locate a class file. * </p> */ enum ClassLoading implements BinaryLocator { /** * The singleton instance. */ INSTANCE; @Override public ClassFileLocator classFileLocator(ClassLoader classLoader) { return ClassFileLocator.NoOp.INSTANCE; } @Override public TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader) { return new TypePool.LazyFacade(TypePool.Default.ClassLoading.of(classFileLocator, classLoader)); } @Override public String toString() { return "AgentBuilder.BinaryLocator.ClassLoading." + name(); } } } /** * A listener that is informed about events that occur during an instrumentation process. */ interface Listener { /** * Invoked right before a successful transformation is applied. * * @param typeDescription The type that is being transformed. * @param dynamicType The dynamic type that was created. */ void onTransformation(TypeDescription typeDescription, DynamicType dynamicType); /** * Invoked when a type is not transformed but ignored. * * @param typeDescription The type being ignored. */ void onIgnored(TypeDescription typeDescription); /** * Invoked when an error has occurred. * * @param typeName The binary name of the instrumented type. * @param throwable The occurred error. */ void onError(String typeName, Throwable throwable); /** * Invoked after a class was attempted to be loaded, independently of its treatment. * * @param typeName The binary name of the instrumented type. */ void onComplete(String typeName); /** * A no-op implementation of a {@link net.bytebuddy.agent.builder.AgentBuilder.Listener}. */ enum NoOp implements Listener { /** * The singleton instance. */ INSTANCE; @Override public void onTransformation(TypeDescription typeDescription, DynamicType dynamicType) { /* do nothing */ } @Override public void onIgnored(TypeDescription typeDescription) { /* do nothing */ } @Override public void onError(String typeName, Throwable throwable) { /* do nothing */ } @Override public void onComplete(String typeName) { /* do nothing */ } @Override public String toString() { return "AgentBuilder.Listener.NoOp." + name(); } } /** * A listener that writes events to a {@link PrintStream}. This listener prints a line per event, including the event type and * the name of the type in question. */ class StreamWriting implements Listener { /** * The prefix that is appended to all written messages. */ protected static final String PREFIX = "[Byte Buddy]"; /** * The print stream written to. */ private final PrintStream printStream; /** * Creates a new stream writing listener. * * @param printStream The print stream written to. */ public StreamWriting(PrintStream printStream) { this.printStream = printStream; } /** * Creates a new stream writing listener that writes to {@link System#out}. * * @return A listener writing events to the standard output stream. */ public static Listener toSystemOut() { return new StreamWriting(System.out); } @Override public void onTransformation(TypeDescription typeDescription, DynamicType dynamicType) { printStream.println(PREFIX + " TRANSFORM " + typeDescription.getName()); } @Override public void onIgnored(TypeDescription typeDescription) { printStream.println(PREFIX + " IGNORE " + typeDescription.getName()); } @Override public void onError(String typeName, Throwable throwable) { printStream.println(PREFIX + " ERROR " + typeName); throwable.printStackTrace(printStream); } @Override public void onComplete(String typeName) { printStream.println(PREFIX + " COMPLETE " + typeName); } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && printStream.equals(((StreamWriting) other).printStream); } @Override public int hashCode() { return printStream.hashCode(); } @Override public String toString() { return "AgentBuilder.Listener.StreamWriting{" + "printStream=" + printStream + '}'; } } /** * A compound listener that allows to group several listeners in one instance. */ class Compound implements Listener { /** * The listeners that are represented by this compound listener in their application order. */ private final List<? extends Listener> listeners; /** * Creates a new compound listener. * * @param listener The listeners to apply in their application order. */ public Compound(Listener... listener) { this(Arrays.asList(listener)); } /** * Creates a new compound listener. * * @param listeners The listeners to apply in their application order. */ public Compound(List<? extends Listener> listeners) { this.listeners = listeners; } @Override public void onTransformation(TypeDescription typeDescription, DynamicType dynamicType) { for (Listener listener : listeners) { listener.onTransformation(typeDescription, dynamicType); } } @Override public void onIgnored(TypeDescription typeDescription) { for (Listener listener : listeners) { listener.onIgnored(typeDescription); } } @Override public void onError(String typeName, Throwable throwable) { for (Listener listener : listeners) { listener.onError(typeName, throwable); } } @Override public void onComplete(String typeName) { for (Listener listener : listeners) { listener.onComplete(typeName); } } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && listeners.equals(((Compound) other).listeners); } @Override public int hashCode() { return listeners.hashCode(); } @Override public String toString() { return "AgentBuilder.Listener.Compound{" + "listeners=" + listeners + '}'; } } } /** * An initialization strategy which determines the handling of {@link net.bytebuddy.implementation.LoadedTypeInitializer}s * and the loading of auxiliary types. */ interface InitializationStrategy { /** * Creates a new dispatcher for injecting this initialization strategy during a transformation process. * * @return The dispatcher to be used. */ Dispatcher dispatcher(); /** * A dispatcher for changing a class file to adapt a self-initialization strategy. */ interface Dispatcher { /** * Transforms the instrumented type to implement an appropriate initialization strategy. * * @param builder The builder which should implement the initialization strategy. * @return The given {@code builder} with the initialization strategy applied. */ DynamicType.Builder<?> apply(DynamicType.Builder<?> builder); /** * Registers a dynamic type for initialization and/or begins the initialization process. * * @param dynamicType The dynamic type that is created. * @param classLoader The class loader of the dynamic type. * @param injectorFactory The injector factory */ void register(DynamicType dynamicType, ClassLoader classLoader, InjectorFactory injectorFactory); /** * A factory for creating a {@link ClassInjector} only if it is required. */ interface InjectorFactory { /** * Resolves the class injector for this factory. * * @return The class injector for this factory. */ ClassInjector resolve(); } } /** * A non-initializing initialization strategy. */ enum NoOp implements InitializationStrategy, Dispatcher { /** * The singleton instance. */ INSTANCE; @Override public Dispatcher dispatcher() { return this; } @Override public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder) { return builder; } @Override public void register(DynamicType dynamicType, ClassLoader classLoader, InjectorFactory injectorFactory) { /* do nothing */ } @Override public String toString() { return "AgentBuilder.InitializationStrategy.NoOp." + name(); } } /** * An initialization strategy that adds a code block to an instrumented type's type initializer which * then calls a specific class that is responsible for the explicit initialization. */ enum SelfInjection implements InitializationStrategy { /** * A form of self-injection where auxiliary types that are annotated by * {@link net.bytebuddy.implementation.auxiliary.AuxiliaryType.SignatureRelevant} of the instrumented type are loaded lazily and * any other auxiliary type is loaded eagerly. */ SPLIT { @Override public InitializationStrategy.Dispatcher dispatcher() { return new SelfInjection.Dispatcher.Split(random.nextInt()); } }, /** * A form of self-injection where any auxiliary type is loaded lazily. */ LAZY { @Override public InitializationStrategy.Dispatcher dispatcher() { return new SelfInjection.Dispatcher.Lazy(random.nextInt()); } }, /** * A form of self-injection where any auxiliary type is loaded eagerly. */ EAGER { @Override public InitializationStrategy.Dispatcher dispatcher() { return new SelfInjection.Dispatcher.Eager(random.nextInt()); } }; /** * A generator for random identification values. */ protected final Random random; /** * Creates the self-injection strategy. */ SelfInjection() { random = new Random(); } @Override public String toString() { return "AgentBuilder.InitializationStrategy.SelfInjection." + name(); } /** * A dispatcher for a self-initialization strategy. */ protected abstract static class Dispatcher implements InitializationStrategy.Dispatcher { /** * A random identification for the applied self-initialization. */ protected final int identification; /** * Creates a new dispatcher. * * @param identification A random identification for the applied self-initialization. */ protected Dispatcher(int identification) { this.identification = identification; } @Override public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder) { return builder.initializer(NexusAccessor.INSTANCE.identifiedBy(identification)); } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && identification == ((Dispatcher) other).identification; } @Override public int hashCode() { return identification; } /** * A dispatcher for the {@link net.bytebuddy.agent.builder.AgentBuilder.InitializationStrategy.SelfInjection#SPLIT} strategy. */ protected static class Split extends Dispatcher { /** * Creates a new split dispatcher. * * @param identification A random identification for the applied self-initialization. */ protected Split(int identification) { super(identification); } @Override public void register(DynamicType dynamicType, ClassLoader classLoader, InjectorFactory injectorFactory) { Map<TypeDescription, byte[]> auxiliaryTypes = dynamicType.getAuxiliaryTypes(); LoadedTypeInitializer loadedTypeInitializer; if (!auxiliaryTypes.isEmpty()) { TypeDescription instrumentedType = dynamicType.getTypeDescription(); ClassInjector classInjector = injectorFactory.resolve(); Map<TypeDescription, byte[]> independentTypes = new LinkedHashMap<TypeDescription, byte[]>(auxiliaryTypes); Map<TypeDescription, byte[]> dependentTypes = new LinkedHashMap<TypeDescription, byte[]>(auxiliaryTypes); for (TypeDescription auxiliaryType : auxiliaryTypes.keySet()) { (auxiliaryType.getDeclaredAnnotations().isAnnotationPresent(AuxiliaryType.SignatureRelevant.class) ? dependentTypes : independentTypes).remove(auxiliaryType); } Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers = dynamicType.getLoadedTypeInitializers(); if (!independentTypes.isEmpty()) { for (Map.Entry<TypeDescription, Class<?>> entry : classInjector.inject(independentTypes).entrySet()) { loadedTypeInitializers.get(entry.getKey()).onLoad(entry.getValue()); } } Map<TypeDescription, LoadedTypeInitializer> lazyInitializers = new HashMap<TypeDescription, LoadedTypeInitializer>(loadedTypeInitializers); loadedTypeInitializers.keySet().removeAll(independentTypes.keySet()); loadedTypeInitializer = lazyInitializers.size() > 1 // there exist auxiliary types that need lazy loading ? new InjectingInitializer(instrumentedType, dependentTypes, lazyInitializers, classInjector) : lazyInitializers.get(instrumentedType); } else { loadedTypeInitializer = dynamicType.getLoadedTypeInitializers().get(dynamicType.getTypeDescription()); } if (loadedTypeInitializer.isAlive()) { NexusAccessor.INSTANCE.register(dynamicType.getTypeDescription().getName(), classLoader, identification, loadedTypeInitializer); } } @Override public String toString() { return "AgentBuilder.InitializationStrategy.SelfInjection.Dispatcher.Split{identification=" + identification + "}"; } } /** * A dispatcher for the {@link net.bytebuddy.agent.builder.AgentBuilder.InitializationStrategy.SelfInjection#LAZY} strategy. */ protected static class Lazy extends Dispatcher { /** * Creates a new lazy dispatcher. * * @param identification A random identification for the applied self-initialization. */ protected Lazy(int identification) { super(identification); } @Override public void register(DynamicType dynamicType, ClassLoader classLoader, InjectorFactory injectorFactory) { Map<TypeDescription, byte[]> auxiliaryTypes = dynamicType.getAuxiliaryTypes(); LoadedTypeInitializer loadedTypeInitializer = auxiliaryTypes.isEmpty() ? dynamicType.getLoadedTypeInitializers().get(dynamicType.getTypeDescription()) : new InjectingInitializer(dynamicType.getTypeDescription(), auxiliaryTypes, dynamicType.getLoadedTypeInitializers(), injectorFactory.resolve()); if (loadedTypeInitializer.isAlive()) { NexusAccessor.INSTANCE.register(dynamicType.getTypeDescription().getName(), classLoader, identification, loadedTypeInitializer); } } @Override public String toString() { return "AgentBuilder.InitializationStrategy.SelfInjection.Dispatcher.Lazy{identification=" + identification + "}"; } } /** * A dispatcher for the {@link net.bytebuddy.agent.builder.AgentBuilder.InitializationStrategy.SelfInjection#EAGER} strategy. */ protected static class Eager extends Dispatcher { /** * Creates a new eager dispatcher. * * @param identification A random identification for the applied self-initialization. */ protected Eager(int identification) { super(identification); } @Override public void register(DynamicType dynamicType, ClassLoader classLoader, InjectorFactory injectorFactory) { Map<TypeDescription, byte[]> auxiliaryTypes = dynamicType.getAuxiliaryTypes(); Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers = dynamicType.getLoadedTypeInitializers(); if (!auxiliaryTypes.isEmpty()) { for (Map.Entry<TypeDescription, Class<?>> entry : injectorFactory.resolve().inject(auxiliaryTypes).entrySet()) { loadedTypeInitializers.get(entry.getKey()).onLoad(entry.getValue()); } } LoadedTypeInitializer loadedTypeInitializer = loadedTypeInitializers.get(dynamicType.getTypeDescription()); if (loadedTypeInitializer.isAlive()) { NexusAccessor.INSTANCE.register(dynamicType.getTypeDescription().getName(), classLoader, identification, loadedTypeInitializer); } } @Override public String toString() { return "AgentBuilder.InitializationStrategy.SelfInjection.Dispatcher.Eager{identification=" + identification + "}"; } } /** * A type initializer that injects all auxiliary types of the instrumented type. */ protected static class InjectingInitializer implements LoadedTypeInitializer { /** * The instrumented type. */ private final TypeDescription instrumentedType; /** * The auxiliary types mapped to their class file representation. */ private final Map<TypeDescription, byte[]> rawAuxiliaryTypes; /** * The instrumented types and auxiliary types mapped to their loaded type initializers. * The instrumented types and auxiliary types mapped to their loaded type initializers. */ private final Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers; /** * The class injector to use. */ private final ClassInjector classInjector; /** * Creates a new injection initializer. * * @param instrumentedType The instrumented type. * @param rawAuxiliaryTypes The auxiliary types mapped to their class file representation. * @param loadedTypeInitializers The instrumented types and auxiliary types mapped to their loaded type initializers. * @param classInjector The class injector to use. */ protected InjectingInitializer(TypeDescription instrumentedType, Map<TypeDescription, byte[]> rawAuxiliaryTypes, Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers, ClassInjector classInjector) { this.instrumentedType = instrumentedType; this.rawAuxiliaryTypes = rawAuxiliaryTypes; this.loadedTypeInitializers = loadedTypeInitializers; this.classInjector = classInjector; } @Override public void onLoad(Class<?> type) { for (Map.Entry<TypeDescription, Class<?>> auxiliary : classInjector.inject(rawAuxiliaryTypes).entrySet()) { loadedTypeInitializers.get(auxiliary.getKey()).onLoad(auxiliary.getValue()); } loadedTypeInitializers.get(instrumentedType).onLoad(type); } @Override public boolean isAlive() { return true; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; InjectingInitializer that = (InjectingInitializer) o; return classInjector.equals(that.classInjector) && instrumentedType.equals(that.instrumentedType) && rawAuxiliaryTypes.equals(that.rawAuxiliaryTypes) && loadedTypeInitializers.equals(that.loadedTypeInitializers); } @Override public int hashCode() { int result = instrumentedType.hashCode(); result = 31 * result + rawAuxiliaryTypes.hashCode(); result = 31 * result + loadedTypeInitializers.hashCode(); result = 31 * result + classInjector.hashCode(); return result; } @Override public String toString() { return "AgentBuilder.InitializationStrategy.SelfInjection.Dispatcher.InjectingInitializer{" + "instrumentedType=" + instrumentedType + ", rawAuxiliaryTypes=" + rawAuxiliaryTypes + ", loadedTypeInitializers=" + loadedTypeInitializers + ", classInjector=" + classInjector + '}'; } } } /** * An accessor for making sure that the accessed {@link net.bytebuddy.agent.builder.Nexus} is the class that is loaded by the system class loader. */ protected enum NexusAccessor { /** * The singleton instance. */ INSTANCE; /** * The dispatcher for registering type initializers in the {@link Nexus}. */ private final Dispatcher dispatcher; /** * The {@link ClassLoader#getSystemClassLoader()} method. */ private final MethodDescription.InDefinedShape getSystemClassLoader; /** * The {@link java.lang.ClassLoader#loadClass(String)} method. */ private final MethodDescription.InDefinedShape loadClass; /** * The {@link Integer#valueOf(int)} method. */ private final MethodDescription.InDefinedShape valueOf; /** * The {@link java.lang.Class#getDeclaredMethod(String, Class[])} method. */ private final MethodDescription getDeclaredMethod; /** * The {@link java.lang.reflect.Method#invoke(Object, Object...)} method. */ private final MethodDescription invokeMethod; /** * Creates the singleton accessor. */ @SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Explicit delegation of the exception") NexusAccessor() { Dispatcher dispatcher; try { TypeDescription nexusType = new TypeDescription.ForLoadedType(Nexus.class); dispatcher = new Dispatcher.Available(ClassInjector.UsingReflection.ofSystemClassLoader() .inject(Collections.singletonMap(nexusType, ClassFileLocator.ForClassLoader.read(Nexus.class).resolve())) .get(nexusType) .getDeclaredMethod("register", String.class, ClassLoader.class, int.class, Object.class)); } catch (Exception exception) { try { dispatcher = new Dispatcher.Available(ClassLoader.getSystemClassLoader() .loadClass(Nexus.class.getName()) .getDeclaredMethod("register", String.class, ClassLoader.class, int.class, Object.class)); } catch (Exception ignored) { dispatcher = new Dispatcher.Unavailable(exception); } } this.dispatcher = dispatcher; getSystemClassLoader = new TypeDescription.ForLoadedType(ClassLoader.class).getDeclaredMethods() .filter(named("getSystemClassLoader").and(takesArguments(0))).getOnly(); loadClass = new TypeDescription.ForLoadedType(ClassLoader.class).getDeclaredMethods() .filter(named("loadClass").and(takesArguments(String.class))).getOnly(); getDeclaredMethod = new TypeDescription.ForLoadedType(Class.class).getDeclaredMethods() .filter(named("getDeclaredMethod").and(takesArguments(String.class, Class[].class))).getOnly(); invokeMethod = new TypeDescription.ForLoadedType(Method.class).getDeclaredMethods() .filter(named("invoke").and(takesArguments(Object.class, Object[].class))).getOnly(); valueOf = new TypeDescription.ForLoadedType(Integer.class).getDeclaredMethods() .filter(named("valueOf").and(takesArguments(int.class))).getOnly(); } /** * Registers a type initializer with the class loader's nexus. * * @param name The name of a type for which a loaded type initializer is registered. * @param classLoader The class loader for which a loaded type initializer is registered. * @param identification An identification for the initializer to run. * @param typeInitializer The loaded type initializer to be registered. */ public void register(String name, ClassLoader classLoader, int identification, LoadedTypeInitializer typeInitializer) { dispatcher.register(name, classLoader, identification, typeInitializer); } /** * Creates a byte code appender for injecting a self-initializing type initializer block into the generated class. * * @param identification The identification of the initialization. * @return An appropriate byte code appender. */ public ByteCodeAppender identifiedBy(int identification) { return new InitializationAppender(identification); } @Override public String toString() { return "AgentBuilder.InitializationStrategy.SelfInjection.NexusAccessor." + name(); } /** * A dispatcher for registering type initializers in the {@link Nexus}. */ protected interface Dispatcher { /** * Registers a type initializer with the class loader's nexus. * * @param name The name of a type for which a loaded type initializer is registered. * @param classLoader The class loader for which a loaded type initializer is registered. * @param identification An identification for the initializer to run. * @param typeInitializer The loaded type initializer to be registered. */ void register(String name, ClassLoader classLoader, int identification, LoadedTypeInitializer typeInitializer); /** * An enabled dispatcher for registering a type initializer in a {@link Nexus}. */ class Available implements Dispatcher { /** * Indicates that a static method is invoked by reflection. */ private static final Object STATIC_METHOD = null; /** * The method for registering a type initializer in the system class loader's {@link Nexus}. */ private final Method registration; /** * Creates a new dispatcher. * * @param registration The method for registering a type initializer in the system class loader's {@link Nexus}. */ protected Available(Method registration) { this.registration = registration; } @Override public void register(String name, ClassLoader classLoader, int identification, LoadedTypeInitializer typeInitializer) { try { registration.invoke(STATIC_METHOD, name, classLoader, identification, typeInitializer); } catch (IllegalAccessException exception) { throw new IllegalStateException("Cannot register type initializer for " + name, exception); } catch (InvocationTargetException exception) { throw new IllegalStateException("Cannot register type initializer for " + name, exception.getCause()); } } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && registration.equals(((Available) other).registration); } @Override public int hashCode() { return registration.hashCode(); } @Override public String toString() { return "AgentBuilder.InitializationStrategy.SelfInjection.NexusAccessor.Dispatcher.Available{" + "registration=" + registration + '}'; } } /** * A disabled dispatcher where a {@link Nexus} is not available. */ class Unavailable implements Dispatcher { /** * The exception that was raised during the dispatcher initialization. */ private final Exception exception; /** * Creates a new disabled dispatcher. * * @param exception The exception that was raised during the dispatcher initialization. */ protected Unavailable(Exception exception) { this.exception = exception; } @Override public void register(String name, ClassLoader classLoader, int identification, LoadedTypeInitializer typeInitializer) { throw new IllegalStateException("Could not locate registration method", exception); } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && exception.equals(((Unavailable) other).exception); } @Override public int hashCode() { return exception.hashCode(); } @Override public String toString() { return "AgentBuilder.InitializationStrategy.SelfInjection.NexusAccessor.Dispatcher.Unavailable{" + "exception=" + exception + '}'; } } } /** * A byte code appender for invoking a Nexus for initializing the instrumented type. */ protected static class InitializationAppender implements ByteCodeAppender { /** * The identification for the self-initialization to execute. */ private final int identification; /** * Creates a new initialization appender. * * @param identification The identification for the self-initialization to execute. */ protected InitializationAppender(int identification) { this.identification = identification; } @Override public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodDescription instrumentedMethod) { return new ByteCodeAppender.Simple(new StackManipulation.Compound( MethodInvocation.invoke(NexusAccessor.INSTANCE.getSystemClassLoader), new TextConstant(Nexus.class.getName()), MethodInvocation.invoke(NexusAccessor.INSTANCE.loadClass), new TextConstant("initialize"), ArrayFactory.forType(new TypeDescription.Generic.OfNonGenericType.ForLoadedType(Class.class)) .withValues(Arrays.asList( ClassConstant.of(TypeDescription.CLASS), ClassConstant.of(new TypeDescription.ForLoadedType(int.class)))), MethodInvocation.invoke(NexusAccessor.INSTANCE.getDeclaredMethod), NullConstant.INSTANCE, ArrayFactory.forType(TypeDescription.Generic.OBJECT) .withValues(Arrays.asList( ClassConstant.of(instrumentedMethod.getDeclaringType().asErasure()), new StackManipulation.Compound( IntegerConstant.forValue(identification), MethodInvocation.invoke(INSTANCE.valueOf)))), MethodInvocation.invoke(NexusAccessor.INSTANCE.invokeMethod), Removal.SINGLE )).apply(methodVisitor, implementationContext, instrumentedMethod); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; InitializationAppender that = (InitializationAppender) other; return identification == that.identification; } @Override public int hashCode() { return identification; } @Override public String toString() { return "AgentBuilder.InitializationStrategy.SelfInjection.NexusAccessor.InitializationAppender{" + "identification=" + identification + '}'; } } } } /** * An initialization strategy that loads auxiliary types before loading the instrumented type. This strategy skips all types * that are a subtype of the instrumented type which would cause a premature loading of the instrumented type and abort * the instrumentation process. */ enum Minimal implements InitializationStrategy, Dispatcher { /** * The singleton instance. */ INSTANCE; @Override public Dispatcher dispatcher() { return this; } @Override public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder) { return builder; } @Override public void register(DynamicType dynamicType, ClassLoader classLoader, InjectorFactory injectorFactory) { Map<TypeDescription, byte[]> auxiliaryTypes = dynamicType.getAuxiliaryTypes(); Map<TypeDescription, byte[]> independentTypes = new LinkedHashMap<TypeDescription, byte[]>(auxiliaryTypes); for (TypeDescription auxiliaryType : auxiliaryTypes.keySet()) { if (!auxiliaryType.getDeclaredAnnotations().isAnnotationPresent(AuxiliaryType.SignatureRelevant.class)) { independentTypes.remove(auxiliaryType); } } if (!independentTypes.isEmpty()) { ClassInjector classInjector = injectorFactory.resolve(); Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers = dynamicType.getLoadedTypeInitializers(); for (Map.Entry<TypeDescription, Class<?>> entry : classInjector.inject(independentTypes).entrySet()) { loadedTypeInitializers.get(entry.getKey()).onLoad(entry.getValue()); } } } @Override public String toString() { return "AgentBuilder.InitializationStrategy.Minimal." + name(); } } } enum RedefinitionStrategy { /** * Disables redefinition such that already loaded classes are not affected by the agent. */ DISABLED { @Override protected boolean isRetransforming(Instrumentation instrumentation) { return false; } @Override protected Collector makeCollector(Default.Transformation transformation) { throw new IllegalStateException("A disabled redefinition strategy cannot create a collector"); } }, /** * <p> * Applies a <b>redefinition</b> to all classes that are already loaded and that would have been transformed if * the built agent was registered before they were loaded. * </p> * <p> * <b>Important</b>: If a redefined class was previously instrumented, this instrumentation information is lost * during the instrumentation. The redefinition is applied upon the original byte code that is provided by a class * loader and not upon the code in its currently transformed format. Use * {@link net.bytebuddy.agent.builder.AgentBuilder.RedefinitionStrategy#RETRANSFORMATION} if this is a factual or * potential limitation. * </p> * <p> * <b>Note</b>: When applying a redefinition, it is normally required to use a {@link TypeStrategy} that applies * a redefinition instead of rebasing classes such as {@link TypeStrategy.Default#REDEFINE}. Also, consider * the constrains given by this type strategy. * </p> */ REDEFINITION { @Override protected boolean isRetransforming(Instrumentation instrumentation) { if (!instrumentation.isRedefineClassesSupported()) { throw new IllegalArgumentException("Cannot redefine classes: " + instrumentation); } return false; } @Override protected Collector makeCollector(Default.Transformation transformation) { return new Collector.ForRedefinition(transformation); } }, /** * <p> * Applies a <b>retransformation</b> to all classes that are already loaded and that would have been transformed if * the built agent was registered before they were loaded. * </p> * <p> * <b>Note</b>: When applying a redefinition, it is normally required to use a {@link TypeStrategy} that applies * a redefinition instead of rebasing classes such as {@link TypeStrategy.Default#REDEFINE}. Also, consider * the constrains given by this type strategy. * </p> */ RETRANSFORMATION { @Override protected boolean isRetransforming(Instrumentation instrumentation) { if (!instrumentation.isRetransformClassesSupported()) { throw new IllegalArgumentException("Cannot retransform classes: " + instrumentation); } return true; } @Override protected Collector makeCollector(Default.Transformation transformation) { return new Collector.ForRetransformation(transformation); } }; /** * Indicates if this strategy requires a class file transformer to be registered with a hint to apply the * transformer for retransformation. * * @param instrumentation The instrumentation instance used. * @return {@code true} if a class file transformer must be registered with a hint for retransformation. */ protected abstract boolean isRetransforming(Instrumentation instrumentation); /** * Indicates that this redefinition strategy applies a modification of already loaded classes. * * @return {@code true} if this redefinition strategy applies a modification of already loaded classes. */ protected boolean isEnabled() { return this != DISABLED; } /** * Creates a collector instance that is responsible for collecting loaded classes for potential retransformation. * * @param transformation The transformation that is registered for the agent. * @return A new collector for collecting already loaded classes for transformation. */ protected abstract Collector makeCollector(Default.Transformation transformation); @Override public String toString() { return "AgentBuilder.RedefinitionStrategy." + name(); } /** * A collector is responsible for collecting classes that are to be considered for modification. */ protected interface Collector { /** * Considers a loaded class for modification. * * @param type The type that is to be considered. * @param ignoredTypes A matcher that indicates what types are explicitly ignored. * @return {@code true} if the class is considered to be redefined. */ boolean consider(Class<?> type, ElementMatcher<? super TypeDescription> ignoredTypes); /** * Applies the represented type modification on all collected types. * * @param instrumentation The instrumentation to use. * @param byteBuddy The Byte Buddy configuration to use. * @param binaryLocator The binary locator to use. * @param typeStrategy The type strategy to use. * @param listener The listener to report to. * @param nativeMethodStrategy The native method strategy to apply. * @param accessControlContext The access control context to use. * @param initializationStrategy The initialization strategy to use. * @param bootstrapInjectionStrategy The bootstrap injection strategy to use. * @throws UnmodifiableClassException If an unmodifiable class is attempted to be modified. * @throws ClassNotFoundException If a class cannot be found while redefining another class. */ void apply(Instrumentation instrumentation, ByteBuddy byteBuddy, BinaryLocator binaryLocator, TypeStrategy typeStrategy, Listener listener, Default.NativeMethodStrategy nativeMethodStrategy, AccessControlContext accessControlContext, InitializationStrategy initializationStrategy, Default.BootstrapInjectionStrategy bootstrapInjectionStrategy) throws UnmodifiableClassException, ClassNotFoundException; /** * A collector that applies a <b>redefinition</b> of already loaded classes. */ class ForRedefinition implements Collector { /** * The transformation of the built agent. */ private final Default.Transformation transformation; /** * A list of already collected redefinitions. */ private final List<Entry> entries; /** * Creates a new collector for a redefinition. * * @param transformation The transformation of the built agent. */ protected ForRedefinition(Default.Transformation transformation) { this.transformation = transformation; entries = new ArrayList<Entry>(); } @Override public boolean consider(Class<?> type, ElementMatcher<? super TypeDescription> ignoredTypes) { Default.Transformation.Resolution resolution = transformation.resolve(new TypeDescription.ForLoadedType(type), type.getClassLoader(), type, type.getProtectionDomain(), ignoredTypes); return resolution.isResolved() && entries.add(new Entry(type, resolution)); } @Override public void apply(Instrumentation instrumentation, ByteBuddy byteBuddy, BinaryLocator binaryLocator, TypeStrategy typeStrategy, Listener listener, Default.NativeMethodStrategy nativeMethodStrategy, AccessControlContext accessControlContext, InitializationStrategy initializationStrategy, Default.BootstrapInjectionStrategy bootstrapInjectionStrategy) throws UnmodifiableClassException, ClassNotFoundException { List<ClassDefinition> classDefinitions = new ArrayList<ClassDefinition>(entries.size()); for (Entry entry : entries) { TypeDescription typeDescription = new TypeDescription.ForLoadedType(entry.getType()); try { classDefinitions.add(entry.resolve(initializationStrategy, binaryLocator.classFileLocator(entry.getType().getClassLoader()), typeStrategy, byteBuddy, nativeMethodStrategy, bootstrapInjectionStrategy, accessControlContext, listener)); } catch (Throwable throwable) { listener.onError(typeDescription.getName(), throwable); } finally { listener.onComplete(typeDescription.getName()); } } if (!classDefinitions.isEmpty()) { instrumentation.redefineClasses(classDefinitions.toArray(new ClassDefinition[classDefinitions.size()])); } } @Override public String toString() { return "AgentBuilder.RedefinitionStrategy.Collector.ForRedefinition{" + "transformation=" + transformation + ", entries=" + entries + '}'; } /** * An entry describing a type redefinition. */ protected static class Entry { /** * The type to be redefined. */ private final Class<?> type; /** * The resolved transformation for this type. */ private final Default.Transformation.Resolution resolution; /** * @param type The type to be redefined. * @param resolution The resolved transformation for this type. */ protected Entry(Class<?> type, Default.Transformation.Resolution resolution) { this.type = type; this.resolution = resolution; } /** * Returns the type that is being redefined. * * @return The type that is being redefined. */ public Class<?> getType() { return type; } /** * Resolves this entry into a fully defined class redefinition. * * @param initializationStrategy The initialization strategy to use. * @param classFileLocator The class file locator to use. * @param typeStrategy The type strategy to use. * @param byteBuddy The Byte Buddy configuration to use. * @param nativeMethodStrategy The native method strategy to use. * @param bootstrapInjectionStrategy The bootstrap injection strategy to use. * @param accessControlContext The access control context to use. * @param listener The listener to report to. * @return An appropriate class definition. */ protected ClassDefinition resolve(InitializationStrategy initializationStrategy, ClassFileLocator classFileLocator, TypeStrategy typeStrategy, ByteBuddy byteBuddy, Default.NativeMethodStrategy nativeMethodStrategy, Default.BootstrapInjectionStrategy bootstrapInjectionStrategy, AccessControlContext accessControlContext, Listener listener) { return new ClassDefinition(type, resolution.apply(initializationStrategy, classFileLocator, typeStrategy, byteBuddy, nativeMethodStrategy, bootstrapInjectionStrategy, accessControlContext, listener)); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; Entry entry = (Entry) other; return type.equals(entry.type) && resolution.equals(entry.resolution); } @Override public int hashCode() { int result = type.hashCode(); result = 31 * result + resolution.hashCode(); return result; } @Override public String toString() { return "AgentBuilder.RedefinitionStrategy.Collector.ForRedefinition.Entry{" + "type=" + type + ", resolution=" + resolution + '}'; } } } /** * A collector that applies a <b>retransformation</b> of already loaded classes. */ class ForRetransformation implements Collector { /** * The transformation defined by the built agent. */ private final Default.Transformation transformation; /** * The types that were collected for retransformation. */ private final List<Class<?>> types; /** * Creates a new collector for a retransformation. * * @param transformation The transformation defined by the built agent. */ protected ForRetransformation(Default.Transformation transformation) { this.transformation = transformation; types = new ArrayList<Class<?>>(); } @Override public boolean consider(Class<?> type, ElementMatcher<? super TypeDescription> ignoredTypes) { return transformation.resolve(new TypeDescription.ForLoadedType(type), type.getClassLoader(), type, type.getProtectionDomain(), ignoredTypes).isResolved() && types.add(type); } @Override public void apply(Instrumentation instrumentation, ByteBuddy byteBuddy, BinaryLocator binaryLocator, TypeStrategy typeStrategy, Listener listener, Default.NativeMethodStrategy nativeMethodStrategy, AccessControlContext accessControlContext, InitializationStrategy initializationStrategy, Default.BootstrapInjectionStrategy bootstrapInjectionStrategy) throws UnmodifiableClassException { if (!types.isEmpty()) { instrumentation.retransformClasses(types.toArray(new Class<?>[types.size()])); } } @Override public String toString() { return "AgentBuilder.RedefinitionStrategy.Collector.ForRetransformation{" + "transformation=" + transformation + ", types=" + types + '}'; } } } } /** * Implements the instrumentation of the {@code LambdaMetafactory} if this feature is enabled. */ enum LambdaInstrumentationStrategy implements Callable<Class<?>> { ENABLED { @Override protected void apply(ByteBuddy byteBuddy, Instrumentation instrumentation, ClassFileTransformer classFileTransformer) { if (LambdaFactory.register(classFileTransformer, new LambdaInstanceFactory(byteBuddy), this)) { Class<?> lambdaMetaFactory; try { lambdaMetaFactory = Class.forName("java.lang.invoke.LambdaMetafactory"); } catch (ClassNotFoundException ignored) { return; } byteBuddy.with(Implementation.Context.Disabled.Factory.INSTANCE) .redefine(lambdaMetaFactory) .visit(new AsmVisitorWrapper.ForDeclaredMethods() .method(named("metafactory"), MetaFactoryRedirection.INSTANCE) .method(named("altMetafactory"), AlternativeMetaFactoryRedirection.INSTANCE)) .make() .load(lambdaMetaFactory.getClassLoader(), ClassReloadingStrategy.of(instrumentation)); } } @Override public Class<?> call() throws Exception { TypeDescription lambdaFactory = new TypeDescription.ForLoadedType(LambdaFactory.class); return ClassInjector.UsingReflection.ofSystemClassLoader() .inject(Collections.singletonMap(lambdaFactory, ClassFileLocator.ForClassLoader.read(LambdaFactory.class).resolve())) .get(lambdaFactory); } }, /** * A strategy that does not instrument the {@code LambdaMetafactory}. */ DISABLED { @Override protected void apply(ByteBuddy byteBuddy, Instrumentation instrumentation, ClassFileTransformer classFileTransformer) { /* do nothing */ } @Override public Class<?> call() throws Exception { throw new IllegalStateException("Cannot inject LambdaFactory from disabled instrumentation strategy"); } }; /** * Indicates that an original implementation can be ignored when redefining a method. */ protected static final MethodVisitor IGNORE_ORIGINAL = null; /** * Releases the supplied class file transformer when it was built with {@link AgentBuilder#with(LambdaInstrumentationStrategy)} enabled. * Subsequently, the class file transformer is no longer applied when a class that represents a lambda expression is created. * * @param classFileTransformer The class file transformer to release. * @param instrumentation The instrumentation instance that is used to potentially rollback the instrumentation of the {@code LambdaMetafactory}. */ public static void release(ClassFileTransformer classFileTransformer, Instrumentation instrumentation) { if (LambdaFactory.release(classFileTransformer)) { try { ClassReloadingStrategy.of(instrumentation).reset(Class.forName("java.lang.invoke.LambdaMetafactory")); } catch (Exception exception) { throw new IllegalStateException("Could not release lambda transformer", exception); } } } /** * Returns an enabled lambda instrumentation strategy for {@code true}. * * @param enabled If lambda instrumentation should be enabled. * @return {@code true} if the returned strategy should be enabled. */ public static LambdaInstrumentationStrategy of(boolean enabled) { return enabled ? ENABLED : DISABLED; } /** * Applies a transformation to lambda instances if applicable. * * @param byteBuddy The Byte Buddy instance to use. * @param instrumentation The instrumentation instance for applying a redefinition. * @param classFileTransformer The class file transformer to apply. */ protected abstract void apply(ByteBuddy byteBuddy, Instrumentation instrumentation, ClassFileTransformer classFileTransformer); /** * Indicates if this strategy enables instrumentation of the {@code LambdaMetafactory}. * * @return {@code true} if this strategy is enabled. */ public boolean isEnabled() { return this == ENABLED; } @Override public String toString() { return "AgentBuilder.LambdaInstrumentationStrategy." + name(); } /** * A factory that creates instances that represent lambda expressions. */ protected static class LambdaInstanceFactory { /** * The name of a factory for a lambda expression. */ private static final String LAMBDA_FACTORY = "get$Lambda"; /** * A prefix for a field that represents a property of a lambda expression. */ private static final String FIELD_PREFIX = "arg$"; /** * The infix to use for naming classes that represent lambda expression. The additional prefix * is necessary because the subsequent counter is not sufficient to keep names unique compared * to the original factory. */ private static final String LAMBDA_TYPE_INFIX = "$$Lambda$ByteBuddy$"; /** * A type-safe constant to express that a class is not already loaded when applying a class file transformer. */ private static final Class<?> NOT_PREVIOUSLY_DEFINED = null; /** * A counter for naming lambda expressions randomly. */ private static final AtomicInteger LAMBDA_NAME_COUNTER = new AtomicInteger(); /** * The Byte Buddy instance to use for creating lambda objects. */ private final ByteBuddy byteBuddy; /** * Creates a new lambda instance factory. * * @param byteBuddy The Byte Buddy instance to use for creating lambda objects. */ protected LambdaInstanceFactory(ByteBuddy byteBuddy) { this.byteBuddy = byteBuddy; } /** * Applies this lambda meta factory. * * @param targetTypeLookup A lookup context representing the creating class of this lambda expression. * @param lambdaMethodName The name of the lambda expression's represented method. * @param factoryMethodType The type of the lambda expression's represented method. * @param lambdaMethodType The type of the lambda expression's factory method. * @param targetMethodHandle A handle representing the target of the lambda expression's method. * @param specializedLambdaMethodType A specialization of the type of the lambda expression's represented method. * @param serializable {@code true} if the lambda expression should be serializable. * @param markerInterfaces A list of interfaces for the lambda expression to represent. * @param additionalBridges A list of additional bridge methods to be implemented by the lambda expression. * @param classFileTransformers A collection of class file transformers to apply when creating the class. * @return A binary representation of the transformed class file. */ public byte[] make(Object targetTypeLookup, String lambdaMethodName, Object factoryMethodType, Object lambdaMethodType, Object targetMethodHandle, Object specializedLambdaMethodType, boolean serializable, List<Class<?>> markerInterfaces, List<?> additionalBridges, Collection<? extends ClassFileTransformer> classFileTransformers) { JavaInstance.MethodType factoryMethod = JavaInstance.MethodType.ofLoaded(factoryMethodType); JavaInstance.MethodType lambdaMethod = JavaInstance.MethodType.ofLoaded(lambdaMethodType); JavaInstance.MethodHandle targetMethod = JavaInstance.MethodHandle.ofLoaded(targetMethodHandle, targetTypeLookup); JavaInstance.MethodType specializedLambdaMethod = JavaInstance.MethodType.ofLoaded(specializedLambdaMethodType); Class<?> targetType = JavaInstance.MethodHandle.lookupType(targetTypeLookup); String lambdaClassName = targetType.getName() + LAMBDA_TYPE_INFIX + LAMBDA_NAME_COUNTER.incrementAndGet(); DynamicType.Builder<?> builder = byteBuddy .subclass(factoryMethod.getReturnType(), ConstructorStrategy.Default.NO_CONSTRUCTORS) .modifiers(TypeManifestation.FINAL, Visibility.PUBLIC) .implement(markerInterfaces) .name(lambdaClassName) .defineConstructor(Visibility.PUBLIC) .withParameters(factoryMethod.getParameterTypes()) .intercept(ConstructorImplementation.INSTANCE) .method(named(lambdaMethodName) .and(takesArguments(lambdaMethod.getParameterTypes())) .and(returns(lambdaMethod.getReturnType()))) .intercept(new LambdaMethodImplementation(targetMethod, specializedLambdaMethod)); int index = 0; for (TypeDescription capturedType : factoryMethod.getParameterTypes()) { builder = builder.defineField(FIELD_PREFIX + ++index, capturedType, Visibility.PRIVATE, FieldManifestation.FINAL); } if (!factoryMethod.getParameterTypes().isEmpty()) { builder = builder.defineMethod(LAMBDA_FACTORY, factoryMethod.getReturnType(), Visibility.PRIVATE, Ownership.STATIC) .withParameters(factoryMethod.getParameterTypes()) .intercept(FactoryImplementation.INSTANCE); } if (serializable) { if (!markerInterfaces.contains(Serializable.class)) { builder = builder.implement(Serializable.class); } builder = builder.defineMethod("writeReplace", Object.class, Visibility.PRIVATE) .intercept(new SerializationImplementation(new TypeDescription.ForLoadedType(targetType), factoryMethod.getReturnType(), lambdaMethodName, lambdaMethod, targetMethod, JavaInstance.MethodType.ofLoaded(specializedLambdaMethodType))); } else if (factoryMethod.getReturnType().isAssignableTo(Serializable.class)) { builder = builder.defineMethod("readObject", void.class, Visibility.PRIVATE) .withParameters(ObjectInputStream.class) .throwing(NotSerializableException.class) .intercept(ExceptionMethod.throwing(NotSerializableException.class, "Non-serializable lambda")) .defineMethod("writeObject", void.class, Visibility.PRIVATE) .withParameters(ObjectOutputStream.class) .throwing(NotSerializableException.class) .intercept(ExceptionMethod.throwing(NotSerializableException.class, "Non-serializable lambda")); } for (Object additionalBridgeType : additionalBridges) { JavaInstance.MethodType additionalBridge = JavaInstance.MethodType.ofLoaded(additionalBridgeType); builder = builder.defineMethod(lambdaMethodName, additionalBridge.getReturnType(), MethodManifestation.BRIDGE, Visibility.PUBLIC) .withParameters(additionalBridge.getParameterTypes()) .intercept(new BridgeMethodImplementation(lambdaMethodName, lambdaMethod)); } byte[] classFile = builder.make().getBytes(); for (ClassFileTransformer classFileTransformer : classFileTransformers) { try { byte[] transformedClassFile = classFileTransformer.transform(targetType.getClassLoader(), lambdaClassName.replace('.', '/'), NOT_PREVIOUSLY_DEFINED, targetType.getProtectionDomain(), classFile); classFile = transformedClassFile == null ? classFile : transformedClassFile; } catch (Throwable ignored) { /* do nothing */ } } return classFile; } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && byteBuddy.equals(((LambdaInstanceFactory) other).byteBuddy); } @Override public int hashCode() { return byteBuddy.hashCode(); } @Override public String toString() { return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory{" + "byteBuddy=" + byteBuddy + '}'; } /** * Implements a lambda class's constructor. */ protected enum ConstructorImplementation implements Implementation { /** * The singleton instance. */ INSTANCE; /** * A reference to the {@link Object} class's default constructor. */ private final MethodDescription.InDefinedShape objectConstructor; /** * Creates a new constructor implementation. */ ConstructorImplementation() { objectConstructor = TypeDescription.OBJECT.getDeclaredMethods().filter(isConstructor()).getOnly(); } @Override public ByteCodeAppender appender(Target implementationTarget) { return new Appender(implementationTarget.getInstrumentedType().getDeclaredFields()); } @Override public InstrumentedType prepare(InstrumentedType instrumentedType) { return instrumentedType; } @Override public String toString() { return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.ConstructorImplementation." + name(); } /** * An appender to implement the constructor. */ protected static class Appender implements ByteCodeAppender { /** * The fields that are declared by the instrumented type. */ private final List<FieldDescription.InDefinedShape> declaredFields; /** * Creates a new appender. * * @param declaredFields The fields that are declared by the instrumented type. */ protected Appender(List<FieldDescription.InDefinedShape> declaredFields) { this.declaredFields = declaredFields; } @Override public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) { List<StackManipulation> fieldAssignments = new ArrayList<StackManipulation>(declaredFields.size() * 3); for (ParameterDescription parameterDescription : instrumentedMethod.getParameters()) { fieldAssignments.add(MethodVariableAccess.REFERENCE.loadOffset(0)); fieldAssignments.add(MethodVariableAccess.of(parameterDescription.getType()).loadOffset(parameterDescription.getOffset())); fieldAssignments.add(FieldAccess.forField(declaredFields.get(parameterDescription.getIndex())).putter()); } return new Size(new StackManipulation.Compound( MethodVariableAccess.REFERENCE.loadOffset(0), MethodInvocation.invoke(INSTANCE.objectConstructor), new StackManipulation.Compound(fieldAssignments), MethodReturn.VOID ).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize()); } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && declaredFields.equals(((Appender) other).declaredFields); } @Override public int hashCode() { return declaredFields.hashCode(); } @Override public String toString() { return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.ConstructorImplementation.Appender{" + "declaredFields=" + declaredFields + '}'; } } } /** * An implementation of a instance factory for a lambda expression's class. */ protected enum FactoryImplementation implements Implementation { /** * The singleton instance. */ INSTANCE; @Override public ByteCodeAppender appender(Target implementationTarget) { return new Appender(implementationTarget.getInstrumentedType()); } @Override public InstrumentedType prepare(InstrumentedType instrumentedType) { return instrumentedType; } @Override public String toString() { return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.FactoryImplementation." + name(); } /** * An appender for a lambda expression factory. */ protected static class Appender implements ByteCodeAppender { /** * The instrumented type. */ private final TypeDescription instrumentedType; /** * Creates a new appender. * * @param instrumentedType The instrumented type. */ protected Appender(TypeDescription instrumentedType) { this.instrumentedType = instrumentedType; } @Override public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) { return new Size(new StackManipulation.Compound( TypeCreation.of(instrumentedType), Duplication.SINGLE, MethodVariableAccess.allArgumentsOf(instrumentedMethod), MethodInvocation.invoke(instrumentedType.getDeclaredMethods().filter(isConstructor()).getOnly()), MethodReturn.REFERENCE ).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize()); } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && instrumentedType.equals(((Appender) other).instrumentedType); } @Override public int hashCode() { return instrumentedType.hashCode(); } @Override public String toString() { return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.FactoryImplementation.Appender{" + "instrumentedType=" + instrumentedType + '}'; } } } /** * Implements a lambda expression's functional method. */ protected static class LambdaMethodImplementation implements Implementation { /** * The handle of the target method of the lambda expression. */ private final JavaInstance.MethodHandle targetMethod; /** * The specialized type of the lambda method. */ private final JavaInstance.MethodType specializedLambdaMethod; /** * Creates a implementation of a lambda expression's functional method. * * @param targetMethod The target method of the lambda expression. * @param specializedLambdaMethod The specialized type of the lambda method. */ protected LambdaMethodImplementation(JavaInstance.MethodHandle targetMethod, JavaInstance.MethodType specializedLambdaMethod) { this.targetMethod = targetMethod; this.specializedLambdaMethod = specializedLambdaMethod; } @Override public ByteCodeAppender appender(Target implementationTarget) { return new Appender(targetMethod.getOwnerType() .getDeclaredMethods() .filter(named(targetMethod.getName()) .and(returns(targetMethod.getReturnType())) .and(takesArguments(targetMethod.getParameterTypes()))) .getOnly(), specializedLambdaMethod, implementationTarget.getInstrumentedType().getDeclaredFields()); } @Override public InstrumentedType prepare(InstrumentedType instrumentedType) { return instrumentedType; } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; LambdaMethodImplementation that = (LambdaMethodImplementation) other; return targetMethod.equals(that.targetMethod) && specializedLambdaMethod.equals(that.specializedLambdaMethod); } @Override public int hashCode() { int result = targetMethod.hashCode(); result = 31 * result + specializedLambdaMethod.hashCode(); return result; } @Override public String toString() { return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.LambdaMethodImplementation{" + "targetMethod=" + targetMethod + ", specializedLambdaMethod=" + specializedLambdaMethod + '}'; } /** * An appender for a lambda expression's functional method. */ protected static class Appender implements ByteCodeAppender { /** * The target method of the lambda expression. */ private final MethodDescription targetMethod; /** * The specialized type of the lambda method. */ private final JavaInstance.MethodType specializedLambdaMethod; /** * The instrumented type's declared fields. */ private final List<FieldDescription.InDefinedShape> declaredFields; /** * Creates an appender of a lambda expression's functional method. * * @param targetMethod The target method of the lambda expression. * @param specializedLambdaMethod The specialized type of the lambda method. * @param declaredFields The instrumented type's declared fields. */ protected Appender(MethodDescription targetMethod, JavaInstance.MethodType specializedLambdaMethod, List<FieldDescription.InDefinedShape> declaredFields) { this.targetMethod = targetMethod; this.specializedLambdaMethod = specializedLambdaMethod; this.declaredFields = declaredFields; } @Override public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) { List<StackManipulation> fieldAccess = new ArrayList<StackManipulation>(declaredFields.size() * 2); for (FieldDescription.InDefinedShape fieldDescription : declaredFields) { fieldAccess.add(MethodVariableAccess.REFERENCE.loadOffset(0)); fieldAccess.add(FieldAccess.forField(fieldDescription).getter()); } List<StackManipulation> parameterAccess = new ArrayList<StackManipulation>(instrumentedMethod.getParameters().size() * 2); for (ParameterDescription parameterDescription : instrumentedMethod.getParameters()) { parameterAccess.add(MethodVariableAccess.of(parameterDescription.getType()).loadOffset(parameterDescription.getOffset())); parameterAccess.add(Assigner.DEFAULT.assign(parameterDescription.getType(), specializedLambdaMethod.getParameterTypes().get(parameterDescription.getIndex()).asGenericType(), Assigner.Typing.DYNAMIC)); } return new Size(new StackManipulation.Compound( new StackManipulation.Compound(fieldAccess), new StackManipulation.Compound(parameterAccess), MethodInvocation.invoke(targetMethod), MethodReturn.returning(targetMethod.getReturnType().asErasure()) ).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize()); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; Appender appender = (Appender) other; return targetMethod.equals(appender.targetMethod) && declaredFields.equals(appender.declaredFields) && specializedLambdaMethod.equals(appender.specializedLambdaMethod); } @Override public int hashCode() { int result = targetMethod.hashCode(); result = 31 * result + declaredFields.hashCode(); result = 31 * result + specializedLambdaMethod.hashCode(); return result; } @Override public String toString() { return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.LambdaMethodImplementation.Appender{" + "targetMethod=" + targetMethod + ", specializedLambdaMethod=" + specializedLambdaMethod + ", declaredFields=" + declaredFields + '}'; } } } /** * Implements the {@code writeReplace} method for serializable lambda expressions. */ protected static class SerializationImplementation implements Implementation { /** * The lambda expression's declaring type. */ private final TypeDescription targetType; /** * The lambda expression's functional type. */ private final TypeDescription lambdaType; /** * The lambda expression's functional method name. */ private final String lambdaMethodName; /** * The method type of the lambda expression's functional method. */ private final JavaInstance.MethodType lambdaMethod; /** * A handle that references the lambda expressions invocation target. */ private final JavaInstance.MethodHandle targetMethod; /** * The specialized method type of the lambda expression's functional method. */ private final JavaInstance.MethodType specializedMethod; /** * Creates a new implementation for a serializable's lambda expression's {@code writeReplace} method. * * @param targetType The lambda expression's declaring type. * @param lambdaType The lambda expression's functional type. * @param lambdaMethodName The lambda expression's functional method name. * @param lambdaMethod The method type of the lambda expression's functional method. * @param targetMethod A handle that references the lambda expressions invocation target. * @param specializedMethod The specialized method type of the lambda expression's functional method. */ protected SerializationImplementation(TypeDescription targetType, TypeDescription lambdaType, String lambdaMethodName, JavaInstance.MethodType lambdaMethod, JavaInstance.MethodHandle targetMethod, JavaInstance.MethodType specializedMethod) { this.targetType = targetType; this.lambdaType = lambdaType; this.lambdaMethodName = lambdaMethodName; this.lambdaMethod = lambdaMethod; this.targetMethod = targetMethod; this.specializedMethod = specializedMethod; } @Override public ByteCodeAppender appender(Target implementationTarget) { TypeDescription serializedLambda; try { serializedLambda = new TypeDescription.ForLoadedType(Class.forName("java.lang.invoke.SerializedLambda")); } catch (ClassNotFoundException exception) { throw new IllegalStateException("Cannot find class for lambda serialization", exception); } List<StackManipulation> lambdaArguments = new ArrayList<StackManipulation>(implementationTarget.getInstrumentedType().getDeclaredFields().size()); for (FieldDescription.InDefinedShape fieldDescription : implementationTarget.getInstrumentedType().getDeclaredFields()) { lambdaArguments.add(new StackManipulation.Compound(MethodVariableAccess.REFERENCE.loadOffset(0), FieldAccess.forField(fieldDescription).getter(), Assigner.DEFAULT.assign(fieldDescription.getType(), TypeDescription.Generic.OBJECT, Assigner.Typing.STATIC))); } return new ByteCodeAppender.Simple(new StackManipulation.Compound( TypeCreation.of(serializedLambda), Duplication.SINGLE, ClassConstant.of(targetType), new TextConstant(lambdaType.getInternalName()), new TextConstant(lambdaMethodName), new TextConstant(lambdaMethod.getDescriptor()), IntegerConstant.forValue(targetMethod.getHandleType().getIdentifier()), new TextConstant(targetMethod.getOwnerType().getInternalName()), new TextConstant(targetMethod.getName()), new TextConstant(targetMethod.getDescriptor()), new TextConstant(specializedMethod.getDescriptor()), ArrayFactory.forType(TypeDescription.Generic.OBJECT).withValues(lambdaArguments), MethodInvocation.invoke(serializedLambda.getDeclaredMethods().filter(isConstructor()).getOnly()), MethodReturn.REFERENCE )); } @Override public InstrumentedType prepare(InstrumentedType instrumentedType) { return instrumentedType; } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; SerializationImplementation that = (SerializationImplementation) other; return targetType.equals(that.targetType) && lambdaType.equals(that.lambdaType) && lambdaMethodName.equals(that.lambdaMethodName) && lambdaMethod.equals(that.lambdaMethod) && targetMethod.equals(that.targetMethod) && specializedMethod.equals(that.specializedMethod); } @Override public int hashCode() { int result = targetType.hashCode(); result = 31 * result + lambdaType.hashCode(); result = 31 * result + lambdaMethodName.hashCode(); result = 31 * result + lambdaMethod.hashCode(); result = 31 * result + targetMethod.hashCode(); result = 31 * result + specializedMethod.hashCode(); return result; } @Override public String toString() { return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.SerializationImplementation{" + "targetType=" + targetType + ", lambdaType=" + lambdaType + ", lambdaMethodName='" + lambdaMethodName + '\'' + ", lambdaMethod=" + lambdaMethod + ", targetMethod=" + targetMethod + ", specializedMethod=" + specializedMethod + '}'; } } /** * Implements an explicit bridge method for a lambda expression. */ protected static class BridgeMethodImplementation implements Implementation { /** * The name of the lambda expression's functional method. */ private final String lambdaMethodName; /** * The actual type of the lambda expression's functional method. */ private final JavaInstance.MethodType lambdaMethod; /** * Creates a new bridge method implementation for a lambda expression. * * @param lambdaMethodName The name of the lambda expression's functional method. * @param lambdaMethod The actual type of the lambda expression's functional method. */ protected BridgeMethodImplementation(String lambdaMethodName, JavaInstance.MethodType lambdaMethod) { this.lambdaMethodName = lambdaMethodName; this.lambdaMethod = lambdaMethod; } @Override public ByteCodeAppender appender(Target implementationTarget) { return new Appender(implementationTarget.invokeSuper(new MethodDescription.SignatureToken(lambdaMethodName, lambdaMethod.getReturnType(), lambdaMethod.getParameterTypes()))); } @Override public InstrumentedType prepare(InstrumentedType instrumentedType) { return instrumentedType; } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; BridgeMethodImplementation that = (BridgeMethodImplementation) other; return lambdaMethodName.equals(that.lambdaMethodName) && lambdaMethod.equals(that.lambdaMethod); } @Override public int hashCode() { int result = lambdaMethodName.hashCode(); result = 31 * result + lambdaMethod.hashCode(); return result; } @Override public String toString() { return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.BridgeMethodImplementation{" + "lambdaMethodName='" + lambdaMethodName + '\'' + ", lambdaMethod=" + lambdaMethod + '}'; } /** * An appender for implementing a bridge method for a lambda expression. */ protected static class Appender implements ByteCodeAppender { /** * The invocation of the bridge's target method. */ private final SpecialMethodInvocation bridgeTargetInvocation; /** * Creates a new appender for invoking a lambda expression's bridge method target. * * @param bridgeTargetInvocation The invocation of the bridge's target method. */ protected Appender(SpecialMethodInvocation bridgeTargetInvocation) { this.bridgeTargetInvocation = bridgeTargetInvocation; } @Override public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) { return new Compound(new Simple( MethodVariableAccess.allArgumentsOf(instrumentedMethod) .asBridgeOf(bridgeTargetInvocation.getMethodDescription()) .prependThisReference(), bridgeTargetInvocation, bridgeTargetInvocation.getMethodDescription().getReturnType().asErasure().isAssignableTo(instrumentedMethod.getReturnType().asErasure()) ? StackManipulation.Trivial.INSTANCE : TypeCasting.to(instrumentedMethod.getReceiverType().asErasure()), MethodReturn.returning(instrumentedMethod.getReturnType().asErasure()) )).apply(methodVisitor, implementationContext, instrumentedMethod); } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && bridgeTargetInvocation.equals(((Appender) other).bridgeTargetInvocation); } @Override public int hashCode() { return bridgeTargetInvocation.hashCode(); } @Override public String toString() { return "AgentBuilder.LambdaInstrumentationStrategy.LambdaInstanceFactory.BridgeMethodImplementation.Appender{" + "bridgeTargetInvocation=" + bridgeTargetInvocation + '}'; } } } } /** * Implements the regular lambda meta factory. The implementation represents the following code: * <blockquote><pre> * public static CallSite metafactory(MethodHandles.Lookup caller, * String invokedName, * MethodType invokedType, * MethodType samMethodType, * MethodHandle implMethod, * MethodType instantiatedMethodType) throws Exception { * Unsafe unsafe = Unsafe.getUnsafe(); * {@code Class<?>} lambdaClass = unsafe.defineAnonymousClass(caller.lookupClass(), * (byte[]) ClassLoader.getSystemClassLoader().loadClass("net.bytebuddy.agent.builder.LambdaFactory").getDeclaredMethod("make", * Object.class, * String.class, * Object.class, * Object.class, * Object.class, * Object.class, * boolean.class, * List.class, * List.class).invoke(null, * caller, * invokedName, * invokedType, * samMethodType, * implMethod, * instantiatedMethodType, * false, * Collections.emptyList(), * Collections.emptyList()), * null); * unsafe.ensureClassInitialized(lambdaClass); * return invokedType.parameterCount() == 0 * ? new ConstantCallSite(MethodHandles.constant(invokedType.returnType(), lambdaClass.getDeclaredConstructors()[0].newInstance())) * : new ConstantCallSite(MethodHandles.Lookup.IMPL_LOOKUP.findStatic(lambdaClass, "get$Lambda", invokedType)); * </pre></blockquote> */ protected enum MetaFactoryRedirection implements AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper { /** * The singleton instance. */ INSTANCE; @Override public MethodVisitor wrap(TypeDescription instrumentedType, MethodDescription.InDefinedShape methodDescription, MethodVisitor methodVisitor) { methodVisitor.visitCode(); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "sun/misc/Unsafe", "getUnsafe", "()Lsun/misc/Unsafe;", false); methodVisitor.visitVarInsn(Opcodes.ASTORE, 6); methodVisitor.visitVarInsn(Opcodes.ALOAD, 6); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup", "lookupClass", "()Ljava/lang/Class;", false); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/ClassLoader", "getSystemClassLoader", "()Ljava/lang/ClassLoader;", false); methodVisitor.visitLdcInsn("net.bytebuddy.agent.builder.LambdaFactory"); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/ClassLoader", "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;", false); methodVisitor.visitLdcInsn("make"); methodVisitor.visitIntInsn(Opcodes.BIPUSH, 9); methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class"); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;")); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_1); methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/String;")); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_2); methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;")); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_3); methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;")); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_4); methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;")); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_5); methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;")); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitIntInsn(Opcodes.BIPUSH, 6); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Boolean", "TYPE", "Ljava/lang/Class;"); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitIntInsn(Opcodes.BIPUSH, 7); methodVisitor.visitLdcInsn(Type.getType("Ljava/util/List;")); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitIntInsn(Opcodes.BIPUSH, 8); methodVisitor.visitLdcInsn(Type.getType("Ljava/util/List;")); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getDeclaredMethod", "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;", false); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitIntInsn(Opcodes.BIPUSH, 9); methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object"); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_1); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_2); methodVisitor.visitVarInsn(Opcodes.ALOAD, 2); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_3); methodVisitor.visitVarInsn(Opcodes.ALOAD, 3); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_4); methodVisitor.visitVarInsn(Opcodes.ALOAD, 4); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_5); methodVisitor.visitVarInsn(Opcodes.ALOAD, 5); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitIntInsn(Opcodes.BIPUSH, 6); methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitIntInsn(Opcodes.BIPUSH, 7); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Collections", "emptyList", "()Ljava/util/List;", false); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitIntInsn(Opcodes.BIPUSH, 8); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Collections", "emptyList", "()Ljava/util/List;", false); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Method", "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", false); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "[B"); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "sun/misc/Unsafe", "defineAnonymousClass", "(Ljava/lang/Class;[B[Ljava/lang/Object;)Ljava/lang/Class;", false); methodVisitor.visitVarInsn(Opcodes.ASTORE, 7); methodVisitor.visitVarInsn(Opcodes.ALOAD, 6); methodVisitor.visitVarInsn(Opcodes.ALOAD, 7); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "sun/misc/Unsafe", "ensureClassInitialized", "(Ljava/lang/Class;)V", false); methodVisitor.visitVarInsn(Opcodes.ALOAD, 2); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodType", "parameterCount", "()I", false); Label conditionalDefault = new Label(); methodVisitor.visitJumpInsn(Opcodes.IFNE, conditionalDefault); methodVisitor.visitTypeInsn(Opcodes.NEW, "java/lang/invoke/ConstantCallSite"); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 2); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodType", "returnType", "()Ljava/lang/Class;", false); methodVisitor.visitVarInsn(Opcodes.ALOAD, 7); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getDeclaredConstructors", "()[Ljava/lang/reflect/Constructor;", false); methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitInsn(Opcodes.AALOAD); methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object"); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Constructor", "newInstance", "([Ljava/lang/Object;)Ljava/lang/Object;", false); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/invoke/MethodHandles", "constant", "(Ljava/lang/Class;Ljava/lang/Object;)Ljava/lang/invoke/MethodHandle;", false); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/invoke/ConstantCallSite", "<init>", "(Ljava/lang/invoke/MethodHandle;)V", false); Label conditionalAlternative = new Label(); methodVisitor.visitJumpInsn(Opcodes.GOTO, conditionalAlternative); methodVisitor.visitLabel(conditionalDefault); methodVisitor.visitFrame(Opcodes.F_APPEND, 2, new Object[]{"sun/misc/Unsafe", "java/lang/Class"}, 0, null); methodVisitor.visitTypeInsn(Opcodes.NEW, "java/lang/invoke/ConstantCallSite"); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/invoke/MethodHandles$Lookup", "IMPL_LOOKUP", "Ljava/lang/invoke/MethodHandles$Lookup;"); methodVisitor.visitVarInsn(Opcodes.ALOAD, 7); methodVisitor.visitLdcInsn("get$Lambda"); methodVisitor.visitVarInsn(Opcodes.ALOAD, 2); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup", "findStatic", "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/MethodHandle;", false); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/invoke/ConstantCallSite", "<init>", "(Ljava/lang/invoke/MethodHandle;)V", false); methodVisitor.visitLabel(conditionalAlternative); methodVisitor.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[]{"java/lang/invoke/CallSite"}); methodVisitor.visitInsn(Opcodes.ARETURN); methodVisitor.visitMaxs(8, 8); methodVisitor.visitEnd(); return IGNORE_ORIGINAL; } @Override public String toString() { return "AgentBuilder.LambdaInstrumentationStrategy.MetaFactoryRedirection." + name(); } } /** * Implements the alternative lambda meta factory. The implementation represents the following code: * <blockquote><pre> * public static CallSite altMetafactory(MethodHandles.Lookup caller, * String invokedName, * MethodType invokedType, * Object... args) throws Exception { * int flags = (Integer) args[3]; * int argIndex = 4; * {@code Class<?>[]} markerInterface; * if ((flags {@code &} FLAG_MARKERS) != 0) { * int markerCount = (Integer) args[argIndex++]; * markerInterface = new {@code Class<?>}[markerCount]; * System.arraycopy(args, argIndex, markerInterface, 0, markerCount); * argIndex += markerCount; * } else { * markerInterface = new {@code Class<?>}[0]; * } * MethodType[] additionalBridge; * if ((flags {@code &} FLAG_BRIDGES) != 0) { * int bridgeCount = (Integer) args[argIndex++]; * additionalBridge = new MethodType[bridgeCount]; * System.arraycopy(args, argIndex, additionalBridge, 0, bridgeCount); * // argIndex += bridgeCount; * } else { * additionalBridge = new MethodType[0]; * } * Unsafe unsafe = Unsafe.getUnsafe(); * {@code Class<?>} lambdaClass = unsafe.defineAnonymousClass(caller.lookupClass(), * (byte[]) ClassLoader.getSystemClassLoader().loadClass("net.bytebuddy.agent.builder.LambdaFactory").getDeclaredMethod("make", * Object.class, * String.class, * Object.class, * Object.class, * Object.class, * Object.class, * boolean.class, * List.class, * List.class).invoke(null, * caller, * invokedName, * invokedType, * args[0], * args[1], * args[2], * (flags {@code &} FLAG_SERIALIZABLE) != 0, * Arrays.asList(markerInterface), * Arrays.asList(additionalBridge)), * null); * unsafe.ensureClassInitialized(lambdaClass); * return invokedType.parameterCount() == 0 * ? new ConstantCallSite(MethodHandles.constant(invokedType.returnType(), lambdaClass.getDeclaredConstructors()[0].newInstance())) * : new ConstantCallSite(MethodHandles.Lookup.IMPL_LOOKUP.findStatic(lambdaClass, "get$Lambda", invokedType)); * } * </pre></blockquote> */ protected enum AlternativeMetaFactoryRedirection implements AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper { /** * The singleton instance. */ INSTANCE; @Override public MethodVisitor wrap(TypeDescription instrumentedType, MethodDescription.InDefinedShape methodDescription, MethodVisitor methodVisitor) { methodVisitor.visitCode(); methodVisitor.visitVarInsn(Opcodes.ALOAD, 3); methodVisitor.visitInsn(Opcodes.ICONST_3); methodVisitor.visitInsn(Opcodes.AALOAD); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Integer"); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false); methodVisitor.visitVarInsn(Opcodes.ISTORE, 4); methodVisitor.visitInsn(Opcodes.ICONST_4); methodVisitor.visitVarInsn(Opcodes.ISTORE, 5); methodVisitor.visitVarInsn(Opcodes.ILOAD, 4); methodVisitor.visitInsn(Opcodes.ICONST_2); methodVisitor.visitInsn(Opcodes.IAND); Label markerInterfaceLoop = new Label(); methodVisitor.visitJumpInsn(Opcodes.IFEQ, markerInterfaceLoop); methodVisitor.visitVarInsn(Opcodes.ALOAD, 3); methodVisitor.visitVarInsn(Opcodes.ILOAD, 5); methodVisitor.visitIincInsn(5, 1); methodVisitor.visitInsn(Opcodes.AALOAD); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Integer"); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false); methodVisitor.visitVarInsn(Opcodes.ISTORE, 7); methodVisitor.visitVarInsn(Opcodes.ILOAD, 7); methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class"); methodVisitor.visitVarInsn(Opcodes.ASTORE, 6); methodVisitor.visitVarInsn(Opcodes.ALOAD, 3); methodVisitor.visitVarInsn(Opcodes.ILOAD, 5); methodVisitor.visitVarInsn(Opcodes.ALOAD, 6); methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitVarInsn(Opcodes.ILOAD, 7); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/System", "arraycopy", "(Ljava/lang/Object;ILjava/lang/Object;II)V", false); methodVisitor.visitVarInsn(Opcodes.ILOAD, 5); methodVisitor.visitVarInsn(Opcodes.ILOAD, 7); methodVisitor.visitInsn(Opcodes.IADD); methodVisitor.visitVarInsn(Opcodes.ISTORE, 5); Label markerInterfaceExit = new Label(); methodVisitor.visitJumpInsn(Opcodes.GOTO, markerInterfaceExit); methodVisitor.visitLabel(markerInterfaceLoop); methodVisitor.visitFrame(Opcodes.F_APPEND, 2, new Object[]{Opcodes.INTEGER, Opcodes.INTEGER}, 0, null); methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class"); methodVisitor.visitVarInsn(Opcodes.ASTORE, 6); methodVisitor.visitLabel(markerInterfaceExit); methodVisitor.visitFrame(Opcodes.F_APPEND, 1, new Object[]{"[Ljava/lang/Class;"}, 0, null); methodVisitor.visitVarInsn(Opcodes.ILOAD, 4); methodVisitor.visitInsn(Opcodes.ICONST_4); methodVisitor.visitInsn(Opcodes.IAND); Label additionalBridgesLoop = new Label(); methodVisitor.visitJumpInsn(Opcodes.IFEQ, additionalBridgesLoop); methodVisitor.visitVarInsn(Opcodes.ALOAD, 3); methodVisitor.visitVarInsn(Opcodes.ILOAD, 5); methodVisitor.visitIincInsn(5, 1); methodVisitor.visitInsn(Opcodes.AALOAD); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Integer"); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false); methodVisitor.visitVarInsn(Opcodes.ISTORE, 8); methodVisitor.visitVarInsn(Opcodes.ILOAD, 8); methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/invoke/MethodType"); methodVisitor.visitVarInsn(Opcodes.ASTORE, 7); methodVisitor.visitVarInsn(Opcodes.ALOAD, 3); methodVisitor.visitVarInsn(Opcodes.ILOAD, 5); methodVisitor.visitVarInsn(Opcodes.ALOAD, 7); methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitVarInsn(Opcodes.ILOAD, 8); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/System", "arraycopy", "(Ljava/lang/Object;ILjava/lang/Object;II)V", false); Label additionalBridgesExit = new Label(); methodVisitor.visitJumpInsn(Opcodes.GOTO, additionalBridgesExit); methodVisitor.visitLabel(additionalBridgesLoop); methodVisitor.visitFrame(Opcodes.F_SAME, 0, null, 0, null); methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/invoke/MethodType"); methodVisitor.visitVarInsn(Opcodes.ASTORE, 7); methodVisitor.visitLabel(additionalBridgesExit); methodVisitor.visitFrame(Opcodes.F_APPEND, 1, new Object[]{"[Ljava/lang/invoke/MethodType;"}, 0, null); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "sun/misc/Unsafe", "getUnsafe", "()Lsun/misc/Unsafe;", false); methodVisitor.visitVarInsn(Opcodes.ASTORE, 8); methodVisitor.visitVarInsn(Opcodes.ALOAD, 8); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup", "lookupClass", "()Ljava/lang/Class;", false); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/ClassLoader", "getSystemClassLoader", "()Ljava/lang/ClassLoader;", false); methodVisitor.visitLdcInsn("net.bytebuddy.agent.builder.LambdaFactory"); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/ClassLoader", "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;", false); methodVisitor.visitLdcInsn("make"); methodVisitor.visitIntInsn(Opcodes.BIPUSH, 9); methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class"); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;")); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_1); methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/String;")); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_2); methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;")); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_3); methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;")); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_4); methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;")); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_5); methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;")); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitIntInsn(Opcodes.BIPUSH, 6); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Boolean", "TYPE", "Ljava/lang/Class;"); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitIntInsn(Opcodes.BIPUSH, 7); methodVisitor.visitLdcInsn(Type.getType("Ljava/util/List;")); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitIntInsn(Opcodes.BIPUSH, 8); methodVisitor.visitLdcInsn(Type.getType("Ljava/util/List;")); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getDeclaredMethod", "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;", false); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitIntInsn(Opcodes.BIPUSH, 9); methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object"); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_1); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_2); methodVisitor.visitVarInsn(Opcodes.ALOAD, 2); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_3); methodVisitor.visitVarInsn(Opcodes.ALOAD, 3); methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitInsn(Opcodes.AALOAD); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_4); methodVisitor.visitVarInsn(Opcodes.ALOAD, 3); methodVisitor.visitInsn(Opcodes.ICONST_1); methodVisitor.visitInsn(Opcodes.AALOAD); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ICONST_5); methodVisitor.visitVarInsn(Opcodes.ALOAD, 3); methodVisitor.visitInsn(Opcodes.ICONST_2); methodVisitor.visitInsn(Opcodes.AALOAD); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitIntInsn(Opcodes.BIPUSH, 6); methodVisitor.visitVarInsn(Opcodes.ILOAD, 4); methodVisitor.visitInsn(Opcodes.ICONST_1); methodVisitor.visitInsn(Opcodes.IAND); Label callSiteConditional = new Label(); methodVisitor.visitJumpInsn(Opcodes.IFEQ, callSiteConditional); methodVisitor.visitInsn(Opcodes.ICONST_1); Label callSiteAlternative = new Label(); methodVisitor.visitJumpInsn(Opcodes.GOTO, callSiteAlternative); methodVisitor.visitLabel(callSiteConditional); methodVisitor.visitFrame(Opcodes.F_FULL, 9, new Object[]{"java/lang/invoke/MethodHandles$Lookup", "java/lang/String", "java/lang/invoke/MethodType", "[Ljava/lang/Object;", Opcodes.INTEGER, Opcodes.INTEGER, "[Ljava/lang/Class;", "[Ljava/lang/invoke/MethodType;", "sun/misc/Unsafe"}, 7, new Object[]{"sun/misc/Unsafe", "java/lang/Class", "java/lang/reflect/Method", Opcodes.NULL, "[Ljava/lang/Object;", "[Ljava/lang/Object;", Opcodes.INTEGER}); methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitLabel(callSiteAlternative); methodVisitor.visitFrame(Opcodes.F_FULL, 9, new Object[]{"java/lang/invoke/MethodHandles$Lookup", "java/lang/String", "java/lang/invoke/MethodType", "[Ljava/lang/Object;", Opcodes.INTEGER, Opcodes.INTEGER, "[Ljava/lang/Class;", "[Ljava/lang/invoke/MethodType;", "sun/misc/Unsafe"}, 8, new Object[]{"sun/misc/Unsafe", "java/lang/Class", "java/lang/reflect/Method", Opcodes.NULL, "[Ljava/lang/Object;", "[Ljava/lang/Object;", Opcodes.INTEGER, Opcodes.INTEGER}); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitIntInsn(Opcodes.BIPUSH, 7); methodVisitor.visitVarInsn(Opcodes.ALOAD, 6); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Arrays", "asList", "([Ljava/lang/Object;)Ljava/util/List;", false); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitIntInsn(Opcodes.BIPUSH, 8); methodVisitor.visitVarInsn(Opcodes.ALOAD, 7); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Arrays", "asList", "([Ljava/lang/Object;)Ljava/util/List;", false); methodVisitor.visitInsn(Opcodes.AASTORE); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Method", "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", false); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "[B"); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "sun/misc/Unsafe", "defineAnonymousClass", "(Ljava/lang/Class;[B[Ljava/lang/Object;)Ljava/lang/Class;", false); methodVisitor.visitVarInsn(Opcodes.ASTORE, 9); methodVisitor.visitVarInsn(Opcodes.ALOAD, 8); methodVisitor.visitVarInsn(Opcodes.ALOAD, 9); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "sun/misc/Unsafe", "ensureClassInitialized", "(Ljava/lang/Class;)V", false); methodVisitor.visitVarInsn(Opcodes.ALOAD, 2); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodType", "parameterCount", "()I", false); Label callSiteJump = new Label(); methodVisitor.visitJumpInsn(Opcodes.IFNE, callSiteJump); methodVisitor.visitTypeInsn(Opcodes.NEW, "java/lang/invoke/ConstantCallSite"); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 2); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodType", "returnType", "()Ljava/lang/Class;", false); methodVisitor.visitVarInsn(Opcodes.ALOAD, 9); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getDeclaredConstructors", "()[Ljava/lang/reflect/Constructor;", false); methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitInsn(Opcodes.AALOAD); methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object"); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Constructor", "newInstance", "([Ljava/lang/Object;)Ljava/lang/Object;", false); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/invoke/MethodHandles", "constant", "(Ljava/lang/Class;Ljava/lang/Object;)Ljava/lang/invoke/MethodHandle;", false); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/invoke/ConstantCallSite", "<init>", "(Ljava/lang/invoke/MethodHandle;)V", false); Label callSiteExit = new Label(); methodVisitor.visitJumpInsn(Opcodes.GOTO, callSiteExit); methodVisitor.visitLabel(callSiteJump); methodVisitor.visitFrame(Opcodes.F_APPEND, 1, new Object[]{"java/lang/Class"}, 0, null); methodVisitor.visitTypeInsn(Opcodes.NEW, "java/lang/invoke/ConstantCallSite"); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/invoke/MethodHandles$Lookup", "IMPL_LOOKUP", "Ljava/lang/invoke/MethodHandles$Lookup;"); methodVisitor.visitVarInsn(Opcodes.ALOAD, 9); methodVisitor.visitLdcInsn("get$Lambda"); methodVisitor.visitVarInsn(Opcodes.ALOAD, 2); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup", "findStatic", "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/MethodHandle;", false); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/invoke/ConstantCallSite", "<init>", "(Ljava/lang/invoke/MethodHandle;)V", false); methodVisitor.visitLabel(callSiteExit); methodVisitor.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[]{"java/lang/invoke/CallSite"}); methodVisitor.visitInsn(Opcodes.ARETURN); methodVisitor.visitMaxs(9, 10); methodVisitor.visitEnd(); return IGNORE_ORIGINAL; } @Override public String toString() { return "AgentBuilder.LambdaInstrumentationStrategy.AlternativeMetaFactoryRedirection." + name(); } } } /** * The default implementation of an {@link net.bytebuddy.agent.builder.AgentBuilder}. */ class Default implements AgentBuilder { /** * The name of the Byte Buddy {@code net.bytebuddy.agent.Installer} class. */ private static final String INSTALLER_TYPE = "net.bytebuddy.agent.Installer"; /** * The name of the {@code net.bytebuddy.agent.Installer} field containing an installed {@link Instrumentation}. */ private static final String INSTRUMENTATION_FIELD = "instrumentation"; /** * Indicator for access to a static member via reflection to make the code more readable. */ private static final Object STATIC_FIELD = null; /** * The value that is to be returned from a {@link java.lang.instrument.ClassFileTransformer} to indicate * that no class file transformation is to be applied. */ private static final byte[] NO_TRANSFORMATION = null; /** * The {@link net.bytebuddy.ByteBuddy} instance to be used. */ private final ByteBuddy byteBuddy; /** * The binary locator to use. */ private final BinaryLocator binaryLocator; /** * The definition handler to use. */ private final TypeStrategy typeStrategy; /** * The listener to notify on transformations. */ private final Listener listener; /** * The native method strategy to use. */ private final NativeMethodStrategy nativeMethodStrategy; /** * The access control context to use for loading classes. */ private final AccessControlContext accessControlContext; /** * The initialization strategy to use for creating classes. */ private final InitializationStrategy initializationStrategy; /** * The redefinition strategy to apply. */ private final RedefinitionStrategy redefinitionStrategy; /** * The injection strategy for injecting classes into the bootstrap class loader. */ private final BootstrapInjectionStrategy bootstrapInjectionStrategy; /** * A strategy to determine of the {@code LambdaMetfactory} should be instrumented to allow for the instrumentation * of classes that represent lambda expressions. */ private final LambdaInstrumentationStrategy lambdaInstrumentationStrategy; /** * A matcher that indicates any type that should be excluded from instrumentation. */ private final ElementMatcher<? super TypeDescription> ignoredTypes; /** * The transformation object for handling type transformations. */ private final Transformation transformation; /** * Creates a new default agent builder that uses a default {@link net.bytebuddy.ByteBuddy} instance for * creating classes. */ public Default() { this(new ByteBuddy()); } /** * Creates a new agent builder with default settings. * * @param byteBuddy The Byte Buddy instance to be used. */ public Default(ByteBuddy byteBuddy) { this(byteBuddy, BinaryLocator.Default.FAST, TypeStrategy.Default.REBASE, Listener.NoOp.INSTANCE, NativeMethodStrategy.Disabled.INSTANCE, AccessController.getContext(), InitializationStrategy.SelfInjection.SPLIT, RedefinitionStrategy.DISABLED, BootstrapInjectionStrategy.Disabled.INSTANCE, LambdaInstrumentationStrategy.DISABLED, isSynthetic(), Transformation.Ignored.INSTANCE); } /** * Creates a new default agent builder. * * @param byteBuddy The Byte Buddy instance to be used. * @param binaryLocator The binary locator to use. * @param typeStrategy The definition handler to use. * @param listener The listener to notify on transformations. * @param nativeMethodStrategy The native method strategy to apply. * @param accessControlContext The access control context to use for loading classes. * @param initializationStrategy The initialization strategy to use for transformed types. * @param redefinitionStrategy The redefinition strategy to apply. * @param bootstrapInjectionStrategy The injection strategy for injecting classes into the bootstrap class loader. * @param lambdaInstrumentationStrategy A strategy to determine of the {@code LambdaMetfactory} should be instrumented to allow for the * instrumentation of classes that represent lambda expressions. * @param ignoredTypes A matcher that indicates any type that should be excluded from instrumentation. * @param transformation The transformation object for handling type transformations. */ protected Default(ByteBuddy byteBuddy, BinaryLocator binaryLocator, TypeStrategy typeStrategy, Listener listener, NativeMethodStrategy nativeMethodStrategy, AccessControlContext accessControlContext, InitializationStrategy initializationStrategy, RedefinitionStrategy redefinitionStrategy, BootstrapInjectionStrategy bootstrapInjectionStrategy, LambdaInstrumentationStrategy lambdaInstrumentationStrategy, ElementMatcher<? super TypeDescription> ignoredTypes, Transformation transformation) { this.byteBuddy = byteBuddy; this.binaryLocator = binaryLocator; this.typeStrategy = typeStrategy; this.listener = listener; this.nativeMethodStrategy = nativeMethodStrategy; this.accessControlContext = accessControlContext; this.initializationStrategy = initializationStrategy; this.redefinitionStrategy = redefinitionStrategy; this.bootstrapInjectionStrategy = bootstrapInjectionStrategy; this.lambdaInstrumentationStrategy = lambdaInstrumentationStrategy; this.ignoredTypes = ignoredTypes; this.transformation = transformation; } @Override public Identified type(RawMatcher matcher) { return new Matched(matcher, Transformer.NoOp.INSTANCE); } @Override public Identified type(ElementMatcher<? super TypeDescription> typeMatcher) { return type(typeMatcher, any()); } @Override public Identified type(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) { return type(new RawMatcher.ForElementMatcherPair(typeMatcher, classLoaderMatcher)); } @Override public AgentBuilder with(ByteBuddy byteBuddy) { return new Default(byteBuddy, binaryLocator, typeStrategy, listener, nativeMethodStrategy, accessControlContext, initializationStrategy, redefinitionStrategy, bootstrapInjectionStrategy, lambdaInstrumentationStrategy, ignoredTypes, transformation); } @Override public AgentBuilder with(Listener listener) { return new Default(byteBuddy, binaryLocator, typeStrategy, new Listener.Compound(this.listener, listener), nativeMethodStrategy, accessControlContext, initializationStrategy, redefinitionStrategy, bootstrapInjectionStrategy, lambdaInstrumentationStrategy, ignoredTypes, transformation); } @Override public AgentBuilder with(TypeStrategy typeStrategy) { return new Default(byteBuddy, binaryLocator, typeStrategy, listener, nativeMethodStrategy, accessControlContext, initializationStrategy, redefinitionStrategy, bootstrapInjectionStrategy, lambdaInstrumentationStrategy, ignoredTypes, transformation); } @Override public AgentBuilder with(BinaryLocator binaryLocator) { return new Default(byteBuddy, binaryLocator, typeStrategy, listener, nativeMethodStrategy, accessControlContext, initializationStrategy, redefinitionStrategy, bootstrapInjectionStrategy, lambdaInstrumentationStrategy, ignoredTypes, transformation); } @Override public AgentBuilder enableNativeMethodPrefix(String prefix) { return new Default(byteBuddy, binaryLocator, typeStrategy, listener, NativeMethodStrategy.ForPrefix.of(prefix), accessControlContext, initializationStrategy, redefinitionStrategy, bootstrapInjectionStrategy, lambdaInstrumentationStrategy, ignoredTypes, transformation); } @Override public AgentBuilder disableNativeMethodPrefix() { return new Default(byteBuddy, binaryLocator, typeStrategy, listener, NativeMethodStrategy.Disabled.INSTANCE, accessControlContext, initializationStrategy, redefinitionStrategy, bootstrapInjectionStrategy, lambdaInstrumentationStrategy, ignoredTypes, transformation); } @Override public AgentBuilder with(AccessControlContext accessControlContext) { return new Default(byteBuddy, binaryLocator, typeStrategy, listener, nativeMethodStrategy, accessControlContext, initializationStrategy, redefinitionStrategy, bootstrapInjectionStrategy, lambdaInstrumentationStrategy, ignoredTypes, transformation); } @Override public AgentBuilder with(RedefinitionStrategy redefinitionStrategy) { return new Default(byteBuddy, binaryLocator, typeStrategy, listener, nativeMethodStrategy, accessControlContext, initializationStrategy, redefinitionStrategy, bootstrapInjectionStrategy, lambdaInstrumentationStrategy, ignoredTypes, transformation); } @Override public AgentBuilder with(InitializationStrategy initializationStrategy) { return new Default(byteBuddy, binaryLocator, typeStrategy, listener, nativeMethodStrategy, accessControlContext, initializationStrategy, redefinitionStrategy, bootstrapInjectionStrategy, lambdaInstrumentationStrategy, ignoredTypes, transformation); } @Override public AgentBuilder enableBootstrapInjection(File folder, Instrumentation instrumentation) { return new Default(byteBuddy, binaryLocator, typeStrategy, listener, nativeMethodStrategy, accessControlContext, initializationStrategy, redefinitionStrategy, new BootstrapInjectionStrategy.Enabled(folder, instrumentation), lambdaInstrumentationStrategy, ignoredTypes, transformation); } @Override public AgentBuilder disableBootstrapInjection() { return new Default(byteBuddy, binaryLocator, typeStrategy, listener, nativeMethodStrategy, accessControlContext, initializationStrategy, redefinitionStrategy, BootstrapInjectionStrategy.Disabled.INSTANCE, lambdaInstrumentationStrategy, ignoredTypes, transformation); } @Override public AgentBuilder ignore(ElementMatcher<? super TypeDescription> ignoredTypes) { return new Default(byteBuddy, binaryLocator, typeStrategy, listener, nativeMethodStrategy, accessControlContext, initializationStrategy, redefinitionStrategy, bootstrapInjectionStrategy, lambdaInstrumentationStrategy, ignoredTypes, transformation); } @Override public AgentBuilder with(LambdaInstrumentationStrategy lambdaInstrumentationStrategy) { return new Default(byteBuddy, binaryLocator, typeStrategy, listener, nativeMethodStrategy, accessControlContext, initializationStrategy, redefinitionStrategy, bootstrapInjectionStrategy, lambdaInstrumentationStrategy, ignoredTypes, transformation); } @Override public ClassFileTransformer makeRaw() { return new ExecutingTransformer(byteBuddy, binaryLocator, typeStrategy, listener, nativeMethodStrategy, accessControlContext, initializationStrategy, bootstrapInjectionStrategy, ignoredTypes, transformation); } @Override public ClassFileTransformer installOn(Instrumentation instrumentation) { ClassFileTransformer classFileTransformer = makeRaw(); instrumentation.addTransformer(classFileTransformer, redefinitionStrategy.isRetransforming(instrumentation)); if (nativeMethodStrategy.isEnabled(instrumentation)) { instrumentation.setNativeMethodPrefix(classFileTransformer, nativeMethodStrategy.getPrefix()); } lambdaInstrumentationStrategy.apply(byteBuddy, instrumentation, classFileTransformer); if (redefinitionStrategy.isEnabled()) { RedefinitionStrategy.Collector collector = redefinitionStrategy.makeCollector(transformation); for (Class<?> type : instrumentation.getAllLoadedClasses()) { TypeDescription typeDescription = new TypeDescription.ForLoadedType(type); try { if (!instrumentation.isModifiableClass(type) || !collector.consider(type, ignoredTypes)) { try { try { listener.onIgnored(typeDescription); } finally { listener.onComplete(typeDescription.getName()); } } catch (Throwable ignored) { // Ignore exceptions that are thrown by listeners to mimic the behavior of a transformation. } } } catch (Throwable throwable) { try { try { listener.onError(typeDescription.getName(), throwable); } finally { listener.onComplete(typeDescription.getName()); } } catch (Throwable ignored) { // Ignore exceptions that are thrown by listeners to mimic the behavior of a transformation. } } } try { collector.apply(instrumentation, byteBuddy, binaryLocator, typeStrategy, listener, nativeMethodStrategy, accessControlContext, initializationStrategy, bootstrapInjectionStrategy); } catch (UnmodifiableClassException exception) { throw new IllegalStateException("Cannot modify at least one class: " + collector, exception); } catch (ClassNotFoundException exception) { throw new IllegalStateException("Cannot find at least one class class: " + collector, exception); } } return classFileTransformer; } @Override public ClassFileTransformer installOnByteBuddyAgent() { try { Instrumentation instrumentation = (Instrumentation) ClassLoader.getSystemClassLoader() .loadClass(INSTALLER_TYPE) .getDeclaredField(INSTRUMENTATION_FIELD) .get(STATIC_FIELD); if (instrumentation == null) { throw new IllegalStateException("The Byte Buddy agent is not installed"); } return installOn(instrumentation); } catch (RuntimeException exception) { throw exception; } catch (Exception exception) { throw new IllegalStateException("The Byte Buddy agent is not installed or not accessible", exception); } } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; Default aDefault = (Default) other; return binaryLocator.equals(aDefault.binaryLocator) && byteBuddy.equals(aDefault.byteBuddy) && listener.equals(aDefault.listener) && nativeMethodStrategy.equals(aDefault.nativeMethodStrategy) && typeStrategy.equals(aDefault.typeStrategy) && accessControlContext.equals(aDefault.accessControlContext) && initializationStrategy == aDefault.initializationStrategy && redefinitionStrategy == aDefault.redefinitionStrategy && bootstrapInjectionStrategy.equals(aDefault.bootstrapInjectionStrategy) && lambdaInstrumentationStrategy.equals(aDefault.lambdaInstrumentationStrategy) && ignoredTypes.equals(aDefault.ignoredTypes) && transformation.equals(aDefault.transformation); } @Override public int hashCode() { int result = byteBuddy.hashCode(); result = 31 * result + binaryLocator.hashCode(); result = 31 * result + listener.hashCode(); result = 31 * result + typeStrategy.hashCode(); result = 31 * result + nativeMethodStrategy.hashCode(); result = 31 * result + accessControlContext.hashCode(); result = 31 * result + initializationStrategy.hashCode(); result = 31 * result + redefinitionStrategy.hashCode(); result = 31 * result + bootstrapInjectionStrategy.hashCode(); result = 31 * result + lambdaInstrumentationStrategy.hashCode(); result = 31 * result + ignoredTypes.hashCode(); result = 31 * result + transformation.hashCode(); return result; } @Override public String toString() { return "AgentBuilder.Default{" + "byteBuddy=" + byteBuddy + ", binaryLocator=" + binaryLocator + ", typeStrategy=" + typeStrategy + ", listener=" + listener + ", nativeMethodStrategy=" + nativeMethodStrategy + ", accessControlContext=" + accessControlContext + ", initializationStrategy=" + initializationStrategy + ", redefinitionStrategy=" + redefinitionStrategy + ", bootstrapInjectionStrategy=" + bootstrapInjectionStrategy + ", lambdaInstrumentationStrategy=" + lambdaInstrumentationStrategy + ", ignoredTypes=" + ignoredTypes + ", transformation=" + transformation + '}'; } /** * An injection strategy for injecting classes into the bootstrap class loader. */ protected interface BootstrapInjectionStrategy { /** * Creates an injector for the bootstrap class loader. * * @param protectionDomain The protection domain to be used. * @return A class injector for the bootstrap class loader. */ ClassInjector make(ProtectionDomain protectionDomain); /** * A disabled bootstrap injection strategy. */ enum Disabled implements BootstrapInjectionStrategy { /** * The singleton instance. */ INSTANCE; @Override public ClassInjector make(ProtectionDomain protectionDomain) { throw new IllegalStateException("Injecting classes into the bootstrap class loader was not enabled"); } @Override public String toString() { return "AgentBuilder.Default.BootstrapInjectionStrategy.Disabled." + name(); } } /** * An enabled bootstrap injection strategy. */ class Enabled implements BootstrapInjectionStrategy { /** * The folder in which jar files are to be saved. */ private final File folder; /** * The instrumentation to use for appending jar files. */ private final Instrumentation instrumentation; /** * Creates a new enabled bootstrap class loader injection strategy. * * @param folder The folder in which jar files are to be saved. * @param instrumentation The instrumentation to use for appending jar files. */ public Enabled(File folder, Instrumentation instrumentation) { this.folder = folder; this.instrumentation = instrumentation; } @Override public ClassInjector make(ProtectionDomain protectionDomain) { return ClassInjector.UsingInstrumentation.of(folder, ClassInjector.UsingInstrumentation.Target.BOOTSTRAP, instrumentation); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; Enabled enabled = (Enabled) other; return folder.equals(enabled.folder) && instrumentation.equals(enabled.instrumentation); } @Override public int hashCode() { int result = folder.hashCode(); result = 31 * result + instrumentation.hashCode(); return result; } @Override public String toString() { return "AgentBuilder.Default.BootstrapInjectionStrategy.Enabled{" + "folder=" + folder + ", instrumentation=" + instrumentation + '}'; } } } /** * A strategy for determining if a native method name prefix should be used when rebasing methods. */ protected interface NativeMethodStrategy { /** * Determines if this strategy enables name prefixing for native methods. * * @param instrumentation The instrumentation used. * @return {@code true} if this strategy indicates that a native method prefix should be used. */ boolean isEnabled(Instrumentation instrumentation); /** * Resolves the method name transformer for this strategy. * * @return A method name transformer for this strategy. */ MethodNameTransformer resolve(); /** * Returns the method prefix if the strategy is enabled. This method must only be called if this strategy enables prefixing. * * @return The method prefix. */ String getPrefix(); /** * A native method strategy that suffixes method names with a random suffix and disables native method rebasement. */ enum Disabled implements NativeMethodStrategy { /** * The singleton instance. */ INSTANCE; @Override public MethodNameTransformer resolve() { return MethodNameTransformer.Suffixing.withRandomSuffix(); } @Override public boolean isEnabled(Instrumentation instrumentation) { return false; } @Override public String getPrefix() { throw new IllegalStateException("A disabled native method strategy does not define a method name prefix"); } @Override public String toString() { return "AgentBuilder.Default.NativeMethodStrategy.Disabled." + name(); } } /** * A native method strategy that prefixes method names with a fixed value for supporting rebasing of native methods. */ class ForPrefix implements NativeMethodStrategy { /** * The method name prefix. */ private final String prefix; /** * Creates a new name prefixing native method strategy. * * @param prefix The method name prefix. */ protected ForPrefix(String prefix) { this.prefix = prefix; } /** * Creates a new native method strategy for prefixing method names. * * @param prefix The method name prefix. * @return An appropriate native method strategy. */ protected static NativeMethodStrategy of(String prefix) { if (prefix.length() == 0) { throw new IllegalArgumentException("A method name prefix must not be the empty string"); } return new ForPrefix(prefix); } @Override public MethodNameTransformer resolve() { return new MethodNameTransformer.Prefixing(prefix); } @Override public boolean isEnabled(Instrumentation instrumentation) { if (!instrumentation.isNativeMethodPrefixSupported()) { throw new IllegalArgumentException("A prefix for native methods is not supported: " + instrumentation); } return true; } @Override public String getPrefix() { return prefix; } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && prefix.equals(((ForPrefix) other).prefix); } @Override public int hashCode() { return prefix.hashCode(); } @Override public String toString() { return "AgentBuilder.Default.NativeMethodStrategy.ForPrefix{" + "prefix='" + prefix + '\'' + '}'; } } } /** * A transformation serves as a handler for modifying a class. */ protected interface Transformation { /** * Resolves an attempted transformation to a specific transformation. * * @param typeDescription A description of the type that is to be transformed. * @param classLoader The class loader of the type being transformed. * @param classBeingRedefined In case of a type redefinition, the loaded type being transformed or {@code null} if that is not the case. * @param protectionDomain The protection domain of the type being transformed. * @param ignoredTypes A matcher for types that are explicitly ignored. * @return A resolution for the given type. */ Resolution resolve(TypeDescription typeDescription, ClassLoader classLoader, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, ElementMatcher<? super TypeDescription> ignoredTypes); /** * A resolution to a transformation. */ interface Resolution { /** * Returns {@code true} if this resolution represents an actual type transformation. If this value is {@code false}, * this resolution will not attempt to transform a class. * * @return {@code true} if this resolution attempts to transform a type, {@code false} otherwise. */ boolean isResolved(); /** * Transforms a type or returns {@code null} if a type is not to be transformed. * * @param initializationStrategy The initialization strategy to use. * @param classFileLocator The class file locator to use. * @param typeStrategy The definition handler to use. * @param byteBuddy The Byte Buddy instance to use. * @param methodNameTransformer The method name transformer to be used. * @param bootstrapInjectionStrategy The bootstrap injection strategy to be used. * @param accessControlContext The access control context to be used. * @param listener The listener to be invoked to inform about an applied or non-applied transformation. * @return The class file of the transformed class or {@code null} if no transformation is attempted. */ byte[] apply(InitializationStrategy initializationStrategy, ClassFileLocator classFileLocator, TypeStrategy typeStrategy, ByteBuddy byteBuddy, NativeMethodStrategy methodNameTransformer, BootstrapInjectionStrategy bootstrapInjectionStrategy, AccessControlContext accessControlContext, Listener listener); /** * A canonical implementation of a non-resolved resolution. */ class Unresolved implements Resolution { /** * The type that is not transformed. */ private final TypeDescription typeDescription; /** * Creates a new unresolved resolution. * * @param typeDescription The type that is not transformed. */ protected Unresolved(TypeDescription typeDescription) { this.typeDescription = typeDescription; } @Override public boolean isResolved() { return false; } @Override public byte[] apply(InitializationStrategy initializationStrategy, ClassFileLocator classFileLocator, TypeStrategy typeStrategy, ByteBuddy byteBuddy, NativeMethodStrategy methodNameTransformer, BootstrapInjectionStrategy bootstrapInjectionStrategy, AccessControlContext accessControlContext, Listener listener) { listener.onIgnored(typeDescription); return NO_TRANSFORMATION; } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && typeDescription.equals(((Unresolved) other).typeDescription); } @Override public int hashCode() { return typeDescription.hashCode(); } @Override public String toString() { return "AgentBuilder.Default.Transformation.Resolution.Unresolved{" + "typeDescription=" + typeDescription + '}'; } } } /** * A transformation that does not attempt to transform any type. */ enum Ignored implements Transformation { /** * The singleton instance. */ INSTANCE; @Override public Resolution resolve(TypeDescription typeDescription, ClassLoader classLoader, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, ElementMatcher<? super TypeDescription> ignoredTypes) { return new Resolution.Unresolved(typeDescription); } @Override public String toString() { return "AgentBuilder.Default.Transformation.Ignored." + name(); } } /** * A simple, active transformation. */ class Simple implements Transformation { /** * The raw matcher that is represented by this transformation. */ private final RawMatcher rawMatcher; /** * The transformer that is represented by this transformation. */ private final Transformer transformer; /** * Creates a new transformation. * * @param rawMatcher The raw matcher that is represented by this transformation. * @param transformer The transformer that is represented by this transformation. */ protected Simple(RawMatcher rawMatcher, Transformer transformer) { this.rawMatcher = rawMatcher; this.transformer = transformer; } @Override public Transformation.Resolution resolve(TypeDescription typeDescription, ClassLoader classLoader, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, ElementMatcher<? super TypeDescription> ignoredTypes) { return !ignoredTypes.matches(typeDescription) && rawMatcher.matches(typeDescription, classLoader, classBeingRedefined, protectionDomain) ? new Resolution(typeDescription, classLoader, protectionDomain, transformer) : new Transformation.Resolution.Unresolved(typeDescription); } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && rawMatcher.equals(((Simple) other).rawMatcher) && transformer.equals(((Simple) other).transformer); } @Override public int hashCode() { int result = rawMatcher.hashCode(); result = 31 * result + transformer.hashCode(); return result; } @Override public String toString() { return "AgentBuilder.Default.Transformation.Simple{" + "rawMatcher=" + rawMatcher + ", transformer=" + transformer + '}'; } /** * A resolution that performs a type transformation. */ protected static class Resolution implements Transformation.Resolution { /** * A description of the transformed type. */ private final TypeDescription typeDescription; /** * The class loader of the transformed type. */ private final ClassLoader classLoader; /** * The protection domain of the transformed type. */ private final ProtectionDomain protectionDomain; /** * The transformer to be applied. */ private final Transformer transformer; /** * Creates a new active transformation. * * @param typeDescription A description of the transformed type. * @param classLoader The class loader of the transformed type. * @param protectionDomain The protection domain of the transformed type. * @param transformer The transformer to be applied. */ protected Resolution(TypeDescription typeDescription, ClassLoader classLoader, ProtectionDomain protectionDomain, Transformer transformer) { this.typeDescription = typeDescription; this.classLoader = classLoader; this.protectionDomain = protectionDomain; this.transformer = transformer; } @Override public boolean isResolved() { return true; } @Override public byte[] apply(InitializationStrategy initializationStrategy, ClassFileLocator classFileLocator, TypeStrategy typeStrategy, ByteBuddy byteBuddy, NativeMethodStrategy methodNameTransformer, BootstrapInjectionStrategy bootstrapInjectionStrategy, AccessControlContext accessControlContext, Listener listener) { InitializationStrategy.Dispatcher dispatcher = initializationStrategy.dispatcher(); DynamicType.Unloaded<?> dynamicType = dispatcher.apply(transformer.transform(typeStrategy.builder(typeDescription, byteBuddy, classFileLocator, methodNameTransformer.resolve()), typeDescription)).make(); dispatcher.register(dynamicType, classLoader, new BootstrapClassLoaderCapableInjectorFactory(bootstrapInjectionStrategy, classLoader, protectionDomain, accessControlContext)); listener.onTransformation(typeDescription, dynamicType); return dynamicType.getBytes(); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; Resolution that = (Resolution) other; return typeDescription.equals(that.typeDescription) && !(classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) && !(protectionDomain != null ? !protectionDomain.equals(that.protectionDomain) : that.protectionDomain != null) && transformer.equals(that.transformer); } @Override public int hashCode() { int result = typeDescription.hashCode(); result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0); result = 31 * result + (protectionDomain != null ? protectionDomain.hashCode() : 0); result = 31 * result + transformer.hashCode(); return result; } @Override public String toString() { return "AgentBuilder.Default.Transformation.Simple.Resolution{" + "typeDescription=" + typeDescription + ", classLoader=" + classLoader + ", protectionDomain=" + protectionDomain + ", transformer=" + transformer + '}'; } /** * An injector factory that resolves to a bootstrap class loader injection if this is necessary and enabled. */ protected static class BootstrapClassLoaderCapableInjectorFactory implements InitializationStrategy.Dispatcher.InjectorFactory { /** * The bootstrap injection strategy being used. */ private final BootstrapInjectionStrategy bootstrapInjectionStrategy; /** * The class loader for which to create an injection factory. */ private final ClassLoader classLoader; /** * The protection domain of the created classes. */ private final ProtectionDomain protectionDomain; /** * The access control context to be used. */ private final AccessControlContext accessControlContext; /** * Creates a new bootstrap class loader capable injector factory. * * @param bootstrapInjectionStrategy The bootstrap injection strategy being used. * @param classLoader The class loader for which to create an injection factory. * @param protectionDomain The protection domain of the created classes. * @param accessControlContext The access control context to be used. */ protected BootstrapClassLoaderCapableInjectorFactory(BootstrapInjectionStrategy bootstrapInjectionStrategy, ClassLoader classLoader, ProtectionDomain protectionDomain, AccessControlContext accessControlContext) { this.bootstrapInjectionStrategy = bootstrapInjectionStrategy; this.classLoader = classLoader; this.protectionDomain = protectionDomain; this.accessControlContext = accessControlContext; } @Override public ClassInjector resolve() { return classLoader == null ? bootstrapInjectionStrategy.make(protectionDomain) : new ClassInjector.UsingReflection(classLoader, protectionDomain, accessControlContext); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; BootstrapClassLoaderCapableInjectorFactory that = (BootstrapClassLoaderCapableInjectorFactory) other; return bootstrapInjectionStrategy.equals(that.bootstrapInjectionStrategy) && !(classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) && !(protectionDomain != null ? !protectionDomain.equals(that.protectionDomain) : that.protectionDomain != null) && accessControlContext.equals(that.accessControlContext); } @Override public int hashCode() { int result = bootstrapInjectionStrategy.hashCode(); result = 31 * result + (protectionDomain != null ? protectionDomain.hashCode() : 0); result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0); result = 31 * result + accessControlContext.hashCode(); return result; } @Override public String toString() { return "AgentBuilder.Default.Transformation.Simple.Resolution.BootstrapClassLoaderCapableInjectorFactory{" + "bootstrapInjectionStrategy=" + bootstrapInjectionStrategy + ", classLoader=" + classLoader + ", protectionDomain=" + protectionDomain + ", accessControlContext=" + accessControlContext + '}'; } } } } /** * A compound transformation that applied several transformation in the given order and applies the first active transformation. */ class Compound implements Transformation { /** * The list of transformations to apply in their application order. */ private final List<? extends Transformation> transformations; /** * Creates a new compound transformation. * * @param transformation An array of transformations to apply in their application order. */ protected Compound(Transformation... transformation) { this(Arrays.asList(transformation)); } /** * Creates a new compound transformation. * * @param transformations A list of transformations to apply in their application order. */ protected Compound(List<? extends Transformation> transformations) { this.transformations = transformations; } @Override public Resolution resolve(TypeDescription typeDescription, ClassLoader classLoader, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, ElementMatcher<? super TypeDescription> ignoredTypes) { for (Transformation transformation : transformations) { Resolution resolution = transformation.resolve(typeDescription, classLoader, classBeingRedefined, protectionDomain, ignoredTypes); if (resolution.isResolved()) { return resolution; } } return new Resolution.Unresolved(typeDescription); } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && transformations.equals(((Compound) other).transformations); } @Override public int hashCode() { return transformations.hashCode(); } @Override public String toString() { return "AgentBuilder.Default.Transformation.Compound{" + "transformations=" + transformations + '}'; } } } /** * A {@link java.lang.instrument.ClassFileTransformer} that implements the enclosing agent builder's * configuration. */ protected static class ExecutingTransformer implements ClassFileTransformer { /** * The Byte Buddy instance to be used. */ private final ByteBuddy byteBuddy; /** * The binary locator to use. */ private final BinaryLocator binaryLocator; /** * The definition handler to use. */ private final TypeStrategy typeStrategy; /** * The listener to notify on transformations. */ private final Listener listener; /** * The native method strategy to apply. */ private final NativeMethodStrategy nativeMethodStrategy; /** * The access control context to use for loading classes. */ private final AccessControlContext accessControlContext; /** * The initialization strategy to use for transformed types. */ private final InitializationStrategy initializationStrategy; /** * The injection strategy for injecting classes into the bootstrap class loader. */ private final BootstrapInjectionStrategy bootstrapInjectionStrategy; /** * A matcher that indicates any type that should be excluded from instrumentation. */ private final ElementMatcher<? super TypeDescription> ignoredTypes; /** * The transformation object for handling type transformations. */ private final Transformation transformation; /** * Creates a new class file transformer. * * @param byteBuddy The Byte Buddy instance to be used. * @param binaryLocator The binary locator to use. * @param typeStrategy The definition handler to use. * @param listener The listener to notify on transformations. * @param nativeMethodStrategy The native method strategy to apply. * @param accessControlContext The access control context to use for loading classes. * @param initializationStrategy The initialization strategy to use for transformed types. * @param bootstrapInjectionStrategy The injection strategy for injecting classes into the bootstrap class loader. * @param ignoredTypes A matcher that indicates any type that should be excluded from instrumentation. * @param transformation The transformation object for handling type transformations. */ public ExecutingTransformer(ByteBuddy byteBuddy, BinaryLocator binaryLocator, TypeStrategy typeStrategy, Listener listener, NativeMethodStrategy nativeMethodStrategy, AccessControlContext accessControlContext, InitializationStrategy initializationStrategy, BootstrapInjectionStrategy bootstrapInjectionStrategy, ElementMatcher<? super TypeDescription> ignoredTypes, Transformation transformation) { this.byteBuddy = byteBuddy; this.binaryLocator = binaryLocator; this.typeStrategy = typeStrategy; this.listener = listener; this.nativeMethodStrategy = nativeMethodStrategy; this.accessControlContext = accessControlContext; this.initializationStrategy = initializationStrategy; this.bootstrapInjectionStrategy = bootstrapInjectionStrategy; this.ignoredTypes = ignoredTypes; this.transformation = transformation; } @Override public byte[] transform(ClassLoader classLoader, String internalTypeName, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] binaryRepresentation) { if (internalTypeName == null) { return NO_TRANSFORMATION; } String binaryTypeName = internalTypeName.replace('/', '.'); try { ClassFileLocator classFileLocator = ClassFileLocator.Simple.of(binaryTypeName, binaryRepresentation, binaryLocator.classFileLocator(classLoader)); return transformation.resolve(classBeingRedefined == null ? binaryLocator.typePool(classFileLocator, classLoader).describe(binaryTypeName).resolve() : new TypeDescription.ForLoadedType(classBeingRedefined), classLoader, classBeingRedefined, protectionDomain, ignoredTypes).apply(initializationStrategy, classFileLocator, typeStrategy, byteBuddy, nativeMethodStrategy, bootstrapInjectionStrategy, accessControlContext, listener); } catch (Throwable throwable) { listener.onError(binaryTypeName, throwable); return NO_TRANSFORMATION; } finally { listener.onComplete(binaryTypeName); } } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; ExecutingTransformer that = (ExecutingTransformer) other; return byteBuddy.equals(that.byteBuddy) && binaryLocator.equals(that.binaryLocator) && typeStrategy.equals(that.typeStrategy) && initializationStrategy.equals(that.initializationStrategy) && listener.equals(that.listener) && nativeMethodStrategy.equals(that.nativeMethodStrategy) && bootstrapInjectionStrategy.equals(that.bootstrapInjectionStrategy) && accessControlContext.equals(that.accessControlContext) && ignoredTypes.equals(that.ignoredTypes) && transformation.equals(that.transformation); } @Override public int hashCode() { int result = byteBuddy.hashCode(); result = 31 * result + binaryLocator.hashCode(); result = 31 * result + typeStrategy.hashCode(); result = 31 * result + initializationStrategy.hashCode(); result = 31 * result + listener.hashCode(); result = 31 * result + nativeMethodStrategy.hashCode(); result = 31 * result + bootstrapInjectionStrategy.hashCode(); result = 31 * result + accessControlContext.hashCode(); result = 31 * result + ignoredTypes.hashCode(); result = 31 * result + transformation.hashCode(); return result; } @Override public String toString() { return "AgentBuilder.Default.ExecutingTransformer{" + "byteBuddy=" + byteBuddy + ", binaryLocator=" + binaryLocator + ", typeStrategy=" + typeStrategy + ", initializationStrategy=" + initializationStrategy + ", listener=" + listener + ", nativeMethodStrategy=" + nativeMethodStrategy + ", bootstrapInjectionStrategy=" + bootstrapInjectionStrategy + ", accessControlContext=" + accessControlContext + ", ignoredTypes=" + ignoredTypes + ", transformation=" + transformation + '}'; } } /** * A helper class that describes a {@link net.bytebuddy.agent.builder.AgentBuilder.Default} after supplying * a {@link net.bytebuddy.agent.builder.AgentBuilder.RawMatcher} such that one or several * {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s can be supplied. */ protected class Matched implements Identified.Extendable { /** * The supplied raw matcher. */ private final RawMatcher rawMatcher; /** * The supplied transformer. */ private final Transformer transformer; /** * Creates a new matched default agent builder. * * @param rawMatcher The supplied raw matcher. * @param transformer The supplied transformer. */ protected Matched(RawMatcher rawMatcher, Transformer transformer) { this.rawMatcher = rawMatcher; this.transformer = transformer; } @Override public Identified.Extendable transform(Transformer transformer) { return new Matched(rawMatcher, new Transformer.Compound(this.transformer, transformer)); } @Override public Identified type(RawMatcher matcher) { return materialize().type(matcher); } @Override public Identified type(ElementMatcher<? super TypeDescription> typeMatcher) { return materialize().type(typeMatcher); } @Override public Identified type(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) { return materialize().type(typeMatcher, classLoaderMatcher); } @Override public AgentBuilder with(ByteBuddy byteBuddy) { return materialize().with(byteBuddy); } @Override public AgentBuilder with(Listener listener) { return materialize().with(listener); } @Override public AgentBuilder with(TypeStrategy typeStrategy) { return materialize().with(typeStrategy); } @Override public AgentBuilder with(BinaryLocator binaryLocator) { return materialize().with(binaryLocator); } @Override public AgentBuilder with(AccessControlContext accessControlContext) { return materialize().with(accessControlContext); } @Override public AgentBuilder with(InitializationStrategy initializationStrategy) { return materialize().with(initializationStrategy); } @Override public AgentBuilder with(RedefinitionStrategy redefinitionStrategy) { return materialize().with(redefinitionStrategy); } @Override public AgentBuilder with(LambdaInstrumentationStrategy lambdaInstrumentationStrategy) { return materialize().with(lambdaInstrumentationStrategy); } @Override public AgentBuilder enableBootstrapInjection(File folder, Instrumentation instrumentation) { return materialize().enableBootstrapInjection(folder, instrumentation); } @Override public AgentBuilder disableBootstrapInjection() { return materialize().disableBootstrapInjection(); } @Override public AgentBuilder enableNativeMethodPrefix(String prefix) { return materialize().enableNativeMethodPrefix(prefix); } @Override public AgentBuilder disableNativeMethodPrefix() { return materialize().disableNativeMethodPrefix(); } @Override public AgentBuilder ignore(ElementMatcher<? super TypeDescription> ignoredTypes) { return materialize().ignore(ignoredTypes); } @Override public ClassFileTransformer makeRaw() { return materialize().makeRaw(); } @Override public ClassFileTransformer installOn(Instrumentation instrumentation) { return materialize().installOn(instrumentation); } @Override public ClassFileTransformer installOnByteBuddyAgent() { return materialize().installOnByteBuddyAgent(); } /** * Materializes the currently described {@link net.bytebuddy.agent.builder.AgentBuilder.Default.Transformation}. * * @return An agent builder that represents the currently described entry of this instance. */ protected AgentBuilder materialize() { return new Default(byteBuddy, binaryLocator, typeStrategy, listener, nativeMethodStrategy, accessControlContext, initializationStrategy, redefinitionStrategy, bootstrapInjectionStrategy, lambdaInstrumentationStrategy, ignoredTypes, new Transformation.Compound(new Transformation.Simple(rawMatcher, transformer), transformation)); } /** * Returns the outer instance. * * @return The outer instance. */ private Default getOuter() { return Default.this; } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && rawMatcher.equals(((Matched) other).rawMatcher) && transformer.equals(((Matched) other).transformer) && Default.this.equals(((Matched) other).getOuter()); } @Override public int hashCode() { int result = rawMatcher.hashCode(); result = 31 * result + transformer.hashCode(); result = 31 * result + Default.this.hashCode(); return result; } @Override public String toString() { return "AgentBuilder.Default.Matched{" + "rawMatcher=" + rawMatcher + ", transformer=" + transformer + ", agentBuilder=" + Default.this + '}'; } } } }
package com.wmu.churchlogger; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.Arrays; import java.util.Scanner; import javax.swing.table.DefaultTableModel; public class DBAccess { String url = "jdbc:mysql://localhost:3306/"; String dbName = "CLogger"; String driver = "com.mysql.jdbc.Driver"; String userName = "pastor"; String password = "loggingrox"; Connection connection; public DBAccess(){ try { System.out.println("Connecting to Database..."); Class.forName(driver).newInstance(); connection = DriverManager.getConnection(url+dbName,userName,password); System.out.println("Connected..."); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { //what is this for? -Addison } //build the database!! try { this.buildDatabaseSchema(); } catch (SQLException e) { e.printStackTrace(); } } /** * @return status of execution */ public boolean initializeDBFromScratch() { return true; } private byte[] getPW(String user_name) { return null; } public boolean compareUPass(String user_name, String password) { MessageDigest digest; try { digest = MessageDigest.getInstance("SHA-256"); digest.reset(); digest.update(generateSalt()); byte[] hashedBytes = digest.digest(password.getBytes("UTF-8")); if(Arrays.equals(hashedBytes, getPW(user_name))) { } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return false; } public byte[] generateSalt() { SecureRandom random = new SecureRandom(); byte bytes[] = new byte[20]; random.nextBytes(bytes); return bytes; } /** * All rights to: Omry Yadan * @param conn * @param in * @throws SQLException * @throws FileNotFoundException */ public void buildDatabaseSchema() throws SQLException { InputStream in; try { in = new FileInputStream(new File("assets/scripts/createTablesChurchLogger.sql")); Scanner s = new Scanner(in); s.useDelimiter("(;(\r)?\n)|( Statement st = null; try { st = connection.createStatement(); while (s.hasNext()) { String line = s.next(); if (line.startsWith("/*!") && line.endsWith("*/")) { int i = line.indexOf(' '); line = line.substring(i + 1, line.length() - " */".length()); } if (line.trim().length() > 0) { st.execute(line); } } fillDatabase(); s.close(); } finally { if (st != null) st.close(); } } catch (FileNotFoundException e) { System.err.println("File missing from assets/scripts"); e.printStackTrace(); } } /** * Fills the database with example data * @throws SQLException */ private void fillDatabase() throws SQLException { System.out.println("About to add Addison."); addMember("Addison", "Webb", 0, "(269) 615-5084", "addison.f.webb@gmail.com", "2014-04-08", "1991-11-28", "NA", "8380 Copper Harbor St.", "Kalamazoo", "MI", 49009); addMember("Kendrick", "AWSguy", 0, "(207) 798-0903", "kendrick.cline@wmich.edu", "2014-04-08", "1992-1-1", "Cool guy", "1234 Road St.", "Kalamazoo", "MI", 49009); addMember("Dillon", "Toughguy", 0, "(517) 974-3360", "dillon.burton@wmich.com", "2014-04-08", "1991-1-1", "Cool guy", "5678 Another St.", "Kalamazoo", "MI", 49009); addMember("Josh", "MYSQLguy", 0, "(989) 430-6826", "josh.dkyourlastname@wmich.com", "2014-04-08", "1991-1-1", "Cool guy", "9012 Long Rd.", "Kalamazoo", "MI", 49009); } /** * Creates the table model for the member list UI. * @return the table model to be used to populate a UI table. * @throws SQLException */ public DefaultTableModel updateMemberTable() throws SQLException{ System.out.println("DBAccess: updateMemberTable running"); DefaultTableModel tableModel = new DefaultTableModel(); //initialize result set object Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT fname, lname, phone, email, join_date, straddress, zip" + " FROM members NATURAL JOIN info NATURAL JOIN member_address"); //initialize metadata object ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); System.out.println("column count: " + rsmd.getColumnCount()); String[] recordString = new String[13]; int i; //add column headers Object[] columnHeadings = new String[] { "First Name", "Last Name", "Phone", "Email", "Join Date", "Stree Address", "Zip" }; tableModel.setColumnIdentifiers(columnHeadings); System.out.println("Right before parsing of result set"); while(rs.next()){ for(i = 0; i < columnCount; i++){ System.out.println(i); try{ recordString[i] = rs.getString(i + 1); } catch(NullPointerException e){ recordString[i] = "Null"; } System.out.println(recordString[i]); } tableModel.addRow(recordString); } System.out.println("after parsing"); return tableModel; } /** * Adds member to database. All parameters must be passed. * @param firstName Full first name. * @param lastName Full last name. * @param churchID 3 digit church code. * @param phone Format: (123) 555-1234 * @param email Full email address. * @param joinDate YYYY-MM-DD * @param birthDate YYYY-MM-DD * @param note Any notes about the member. * @param strAddress Full street address. * @param city Full city name. * @param state 2 character state code. * @param zip Must be 5 digit number. */ public void addMember(String firstName, String lastName, int churchID, String phone, String email, String joinDate, String birthDate, String note, String strAddress, String city, String state, int zip){ Statement st = null; try{ st = connection.createStatement(); st.execute("BEGIN"); st.execute("INSERT INTO members (fname, lname, cID) VALUES ('" + firstName + "', '" + lastName + "', '" + churchID + "')"); st.execute("SELECT LAST_INSERT_ID() INTO @lastID"); st.execute("INSERT INTO info (mID, phone, email, join_date, birth_date, note) VALUES (@lastID, '" + phone + "', '" + email + "', '" + joinDate + "', '" + birthDate + "', '" + note + "')"); st.execute("INSERT INTO member_address (mID, straddress, city, state, zip) VALUES (@lastID, '" + strAddress + "', '" + city + "', '" + state + "', '" + zip + "')"); st.execute("COMMIT"); } catch(SQLException e){ System.out.println("SQL Exception: " + e); } } public void closeDBConnection() { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } }
package replicant; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nonnull; import javax.annotation.Nullable; import replicant.spy.RequestCompletedEvent; /** * Connection state used by the connector to manage connection to backend system. * This includes a list of pending requests, pending messages that needs to be applied * to the local state etc. */ public final class Connection { //TODO: Make this package access after all classes migrated to replicant package private static final Logger LOG = Logger.getLogger( Connection.class.getName() ); private static final Level LOG_LEVEL = Level.INFO; @Nonnull private final Connector _connector; private final String _connectionId; private final Map<String, RequestEntry> _requests = new HashMap<>(); private int _requestId; /** * Pending actions that will change the area of interest. */ private final LinkedList<AreaOfInterestRequest> _pendingAreaOfInterestRequests = new LinkedList<>(); /** * The set of data load actions that still need to have the json parsed. */ private final LinkedList<MessageResponse> _unparsedResponses = new LinkedList<>(); /** * The set of data load actions that have their json parsed. They are inserted into * this list according to their sequence. */ private final LinkedList<MessageResponse> _pendingResponses = new LinkedList<>(); /** * Sometimes a data load action occurs that is not initiated by the server. These do not * typically need to be sequenced and are prioritized above other actions. */ private final LinkedList<MessageResponse> _outOfBandResponses = new LinkedList<>(); private int _lastRxSequence; /** * The current message action being processed. */ @Nullable private MessageResponse _currentMessageResponse; @Nonnull private List<AreaOfInterestRequest> _currentAreaOfInterestRequests = new ArrayList<>(); public Connection( @Nonnull final Connector connector, @Nonnull final String connectionId ) { _connector = Objects.requireNonNull( connector ); _connectionId = Objects.requireNonNull( connectionId ); } @Nonnull public String getConnectionId() { return _connectionId; } public final void requestSubscribe( @Nonnull final ChannelAddress address, @Nullable final Object filterParameter ) { enqueueAreaOfInterestRequest( address, AreaOfInterestAction.ADD, filterParameter ); } public void requestSubscriptionUpdate( @Nonnull final ChannelAddress address, @Nullable final Object filterParameter ) { enqueueAreaOfInterestRequest( address, AreaOfInterestAction.UPDATE, filterParameter ); } public void requestUnsubscribe( @Nonnull final ChannelAddress address ) { enqueueAreaOfInterestRequest( address, AreaOfInterestAction.REMOVE, null ); } private void enqueueAreaOfInterestRequest( @Nonnull final ChannelAddress descriptor, @Nonnull final AreaOfInterestAction action, @Nullable final Object filterParameter ) { getPendingAreaOfInterestRequests().add( new AreaOfInterestRequest( descriptor, action, filterParameter ) ); } public void enqueueResponse( @Nonnull final String rawJsonData ) { getUnparsedResponses().add( new MessageResponse( rawJsonData ) ); } public void enqueueOutOfBandResponse( @Nonnull final String rawJsonData, @Nonnull final SafeProcedure oobCompletionAction ) { getOutOfBandResponses().add( new MessageResponse( rawJsonData, oobCompletionAction ) ); } public LinkedList<AreaOfInterestRequest> getPendingAreaOfInterestRequests() { return _pendingAreaOfInterestRequests; } public LinkedList<MessageResponse> getUnparsedResponses() { return _unparsedResponses; } public LinkedList<MessageResponse> getParsedResponses() { return _pendingResponses; } public LinkedList<MessageResponse> getOutOfBandResponses() { return _outOfBandResponses; } public int getLastRxSequence() { return _lastRxSequence; } public void setLastRxSequence( final int lastRxSequence ) { _lastRxSequence = lastRxSequence; } @Nonnull public final RequestEntry newRequest( @Nullable final String name, @Nullable final String cacheKey ) { final RequestEntry entry = new RequestEntry( nextRequestId(), name, cacheKey ); _requests.put( entry.getRequestId(), entry ); if ( LOG.isLoggable( LOG_LEVEL ) ) { LOG.log( LOG_LEVEL, "Created request " + entry ); } return entry; } public final void completeRequest( @Nonnull final RequestEntry request, @Nonnull final SafeProcedure completionAction ) { if ( request.isExpectingResults() && !request.haveResultsArrived() ) { request.setCompletionAction( completionAction ); } else { completionAction.call(); removeRequest( request.getRequestId() ); } if ( Replicant.areSpiesEnabled() && _connector.getReplicantContext().getSpy().willPropagateSpyEvents() ) { _connector .getReplicantContext() .getSpy() .reportSpyEvent( new RequestCompletedEvent( _connector.getSystemType(), request.getRequestId(), request.getName(), request.isNormalCompletion(), request.isExpectingResults(), request.haveResultsArrived() ) ); } } @Nullable public RequestEntry getRequest( @Nonnull final String requestID ) { return _requests.get( requestID ); } public Map<String, RequestEntry> getRequests() { return _requests; } public boolean removeRequest( @Nonnull final String requestID ) { return null != _requests.remove( requestID ); } private String nextRequestId() { return String.valueOf( ++_requestId ); } @Nullable public MessageResponse getCurrentMessageResponse() { return _currentMessageResponse; } public void setCurrentMessageResponse( @Nullable final MessageResponse currentMessageResponse ) { _currentMessageResponse = currentMessageResponse; } @Nonnull public List<AreaOfInterestRequest> getCurrentAreaOfInterestRequests() { return _currentAreaOfInterestRequests; } }
package org.antlr.v4.parse; import org.antlr.runtime.Token; import org.antlr.v4.Tool; import org.antlr.v4.codegen.CodeGenerator; import org.antlr.v4.tool.ErrorType; import org.antlr.v4.tool.Grammar; import org.antlr.v4.tool.ast.GrammarAST; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedHashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TokenVocabParser { protected final Grammar g; public TokenVocabParser(Grammar g) { this.g = g; } /** Load a vocab file {@code <vocabName>.tokens} and return mapping. */ public Map<String,Integer> load() { Map<String,Integer> tokens = new LinkedHashMap<String,Integer>(); int maxTokenType = -1; File fullFile = getImportedVocabFile(); FileInputStream fis = null; BufferedReader br = null; Tool tool = g.tool; String vocabName = g.getOptionString("tokenVocab"); try { Pattern tokenDefPattern = Pattern.compile("([^\n]+?)[ \\t]*?=[ \\t]*?([0-9]+)"); fis = new FileInputStream(fullFile); InputStreamReader isr; if (tool.grammarEncoding != null) { isr = new InputStreamReader(fis, tool.grammarEncoding); } else { isr = new InputStreamReader(fis); } br = new BufferedReader(isr); String tokenDef = br.readLine(); int lineNum = 1; while ( tokenDef!=null ) { Matcher matcher = tokenDefPattern.matcher(tokenDef); if ( matcher.find() ) { String tokenID = matcher.group(1); String tokenTypeS = matcher.group(2); int tokenType; try { tokenType = Integer.valueOf(tokenTypeS); } catch (NumberFormatException nfe) { tool.errMgr.toolError(ErrorType.TOKENS_FILE_SYNTAX_ERROR, vocabName + CodeGenerator.VOCAB_FILE_EXTENSION, " bad token type: "+tokenTypeS, lineNum); tokenType = Token.INVALID_TOKEN_TYPE; } tool.log("grammar", "import "+tokenID+"="+tokenType); tokens.put(tokenID, tokenType); maxTokenType = Math.max(maxTokenType,tokenType); lineNum++; } else { if ( tokenDef.length()>0 ) { // ignore blank lines tool.errMgr.toolError(ErrorType.TOKENS_FILE_SYNTAX_ERROR, vocabName + CodeGenerator.VOCAB_FILE_EXTENSION, " bad token def: " + tokenDef, lineNum); } } tokenDef = br.readLine(); } } catch (FileNotFoundException fnfe) { GrammarAST inTree = g.ast.getOptionAST("tokenVocab"); String inTreeValue = inTree.getToken().getText(); if ( vocabName.equals(inTreeValue) ) { tool.errMgr.grammarError(ErrorType.CANNOT_FIND_TOKENS_FILE_REFD_IN_GRAMMAR, g.fileName, inTree.getToken(), fullFile); } else { // must be from -D option on cmd-line not token in tree tool.errMgr.toolError(ErrorType.CANNOT_FIND_TOKENS_FILE_GIVEN_ON_CMDLINE, fullFile, g.name); } } catch (Exception e) { tool.errMgr.toolError(ErrorType.ERROR_READING_TOKENS_FILE, e, fullFile, e.getMessage()); } finally { try { if ( br!=null ) br.close(); } catch (IOException ioe) { tool.errMgr.toolError(ErrorType.ERROR_READING_TOKENS_FILE, ioe, fullFile, ioe.getMessage()); } } return tokens; } /** Return a File descriptor for vocab file. Look in library or * in -o output path. antlr -o foo T.g4 U.g4 where U needs T.tokens * won't work unless we look in foo too. If we do not find the * file in the lib directory then must assume that the .tokens file * is going to be generated as part of this build and we have defined * .tokens files so that they ALWAYS are generated in the base output * directory, which means the current directory for the command line tool if there * was no output directory specified. */ public File getImportedVocabFile() { String vocabName = g.getOptionString("tokenVocab"); File f = new File(g.tool.libDirectory, File.separator + vocabName + CodeGenerator.VOCAB_FILE_EXTENSION); if (f.exists()) { return f; } // We did not find the vocab file in the lib directory, so we need // to look for it in the output directory which is where .tokens // files are generated (in the base, not relative to the input // location.) f = new File(g.tool.outputDirectory, vocabName + CodeGenerator.VOCAB_FILE_EXTENSION); if ( f.exists() ) { return f; } // Still not found? Use the grammar's subfolder then. String fileDirectory; if (g.fileName.lastIndexOf(File.separatorChar) == -1) { // No path is included in the file name, so make the file // directory the same as the parent grammar (which might still be just "" // but when it is not, we will write the file in the correct place. fileDirectory = "."; } else { fileDirectory = g.fileName.substring(0, g.fileName.lastIndexOf(File.separatorChar)); } return new File(fileDirectory, vocabName + CodeGenerator.VOCAB_FILE_EXTENSION); } }
import java.lang.Thread; import com.sun.star.awt.Rectangle; import com.sun.star.awt.XWindow; import com.sun.star.beans.Property; import com.sun.star.beans.PropertyValue; import com.sun.star.beans.XPropertySet; import com.sun.star.beans.XPropertySetInfo; import com.sun.star.container.XIndexAccess; import com.sun.star.container.XChild; import com.sun.star.container.XEnumerationAccess; import com.sun.star.container.XEnumeration; import com.sun.star.frame.XComponentLoader; import com.sun.star.frame.XController; import com.sun.star.frame.XDesktop; import com.sun.star.frame.XFrame; import com.sun.star.frame.XTasksSupplier; import com.sun.star.frame.XTask; import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.lang.XServiceInfo; import com.sun.star.lang.XServiceName; import com.sun.star.lang.XTypeProvider; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; import com.sun.star.uno.Type; import com.sun.star.drawing.XDrawView; import com.sun.star.drawing.XDrawPage; import com.sun.star.drawing.XShapes; import com.sun.star.drawing.XShape; import com.sun.star.drawing.XShapeDescriptor; import drafts.com.sun.star.accessibility.XAccessible; import drafts.com.sun.star.accessibility.XAccessibleContext; import drafts.com.sun.star.accessibility.XAccessibleComponent; import drafts.com.sun.star.accessibility.XAccessibleRelationSet; import drafts.com.sun.star.accessibility.XAccessibleStateSet; public class InformationWriter implements Print { Print maPrinter; public InformationWriter (Print aPrinter) { maPrinter = aPrinter; } public void drawPageTest (XInterface xPage) { try { printProperty (xPage, "BorderBottom ", "BorderBottom"); printProperty (xPage, "BorderLeft ", "BorderLeft"); printProperty (xPage, "BorderRight ", "BorderRight"); printProperty (xPage, "BorderTop ", "BorderTop"); printProperty (xPage, "Height ", "Height"); printProperty (xPage, "Width ", "Width"); printProperty (xPage, "Number ", "Number"); } catch (Exception e) { System.out.println ("caught exception while testing draw page:" + e); } } public void printProperty (XInterface xObject, String prefix, String name) { try { XPropertySet xPropertySet = (XPropertySet) UnoRuntime.queryInterface( XPropertySet.class, xObject); println (prefix + xPropertySet.getPropertyValue (name)); } catch (Exception e) { println ("caught exception while getting property " + name + " : " + e); } } public void showShapes (XDrawPage xPage) { try { XIndexAccess xShapeList = (XIndexAccess) UnoRuntime.queryInterface( XIndexAccess.class, xPage); println ("There are " + xShapeList.getCount() + " shapes"); for (int i=0; i<xShapeList.getCount(); i++) { XShape xShape = (XShape) UnoRuntime.queryInterface( XShape.class, xShapeList.getByIndex (i)); XShapeDescriptor xShapeDescriptor = (XShapeDescriptor) UnoRuntime.queryInterface( XShapeDescriptor.class, xShape); String sName = xShapeDescriptor.getShapeType (); println (" shape " + i + " : " + sName); XPropertySet xPropertySet = (XPropertySet) UnoRuntime.queryInterface( XPropertySet.class, xShape); Integer nZOrder = (Integer) xPropertySet.getPropertyValue ("ZOrder"); println (" zorder = " + nZOrder); } } catch (Exception e) { println ("caught exception in showShapes: " + e); } } /** @descr Print all available services of the given object to the standard output. */ public void showServices (XInterface xObject) { try { println ("Services:"); XMultiServiceFactory xMSF = (XMultiServiceFactory) UnoRuntime.queryInterface ( XMultiServiceFactory.class, xObject ); if (xMSF == null) println (" object does not support interface XMultiServiceFactory"); else { String[] sServiceNames = xMSF.getAvailableServiceNames (); println (" object can create " + sServiceNames.length + " services"); for (int i=0; i<sServiceNames.length; i++) println (" service " + i + " : " + sServiceNames[i]); } } catch (Exception e) { println ("caught exception in showServices : " + e); } } /** @descr Print the service and implementation name of the given object. */ public void showInfo (XInterface xObject) { try { System.out.println ("Info:"); // Use interface XServiceName to retrieve name of (main) service. XServiceName xSN = (XServiceName) UnoRuntime.queryInterface ( XServiceName.class, xObject); if (xSN == null) println (" interface XServiceName not supported"); else { println (" Service name : " + xSN.getServiceName ()); } // Use interface XServiceInfo to retrieve information about // supported services. XServiceInfo xSI = (XServiceInfo) UnoRuntime.queryInterface ( XServiceInfo.class, xObject); if (xSI == null) println (" interface XServiceInfo not supported"); else { println (" Implementation name : " + xSI.getImplementationName ()); } } catch (Exception e) { println ("caught exception in showInfo : " + e); } } /** @descr Print information about supported interfaces. */ public void showInterfaces (XInterface xObject) { try { println ("Interfaces:"); // Use interface XTypeProvider to retrieve a list of supported // interfaces. XTypeProvider xTP = (XTypeProvider) UnoRuntime.queryInterface ( XTypeProvider.class, xObject); if (xTP == null) println (" interface XTypeProvider not supported"); else { Type[] aTypeList = xTP.getTypes (); println (" object supports " + aTypeList.length + " interfaces"); for (int i=0; i<aTypeList.length; i++) println (" " + i + " : " + aTypeList[i].getTypeName()); } } catch (Exception e) { println ("caught exception in showInterfaces : " + e); } } /** @descr Print information concerning the accessibility of the given object. */ public boolean showAccessibility (XInterface xObject, int depth) { try { // Create indentation string. String sIndent = ""; while (depth sIndent += " "; // Get XAccessibleContext object if given object does not // already support this interface. XAccessibleContext xContext = (XAccessibleContext) UnoRuntime.queryInterface ( XAccessibleContext.class, xObject); if (xContext == null) { XAccessible xAccessible = (XAccessible) UnoRuntime.queryInterface ( XAccessible.class, xObject); if (xAccessible == null) { println (sIndent + "given object " + xObject + " is not accessible"); return false; } else xContext = xAccessible.getAccessibleContext(); } // Print information about the accessible context. if (xContext != null) { println (sIndent + "Name : " + xContext.getAccessibleName()); println (sIndent + "Description : " + xContext.getAccessibleDescription()); println (sIndent + "Role : " + xContext.getAccessibleRole()); String sHasParent; if (xContext.getAccessibleParent() != null) { println (sIndent + "Has parent : yes"); println (sIndent + "Parent index : " + xContext.getAccessibleIndexInParent()); } else println (sIndent + "Has parent : no"); println (sIndent + "Child count : " + xContext.getAccessibleChildCount()); print (sIndent + "Relation set : "); XAccessibleRelationSet xRelationSet = xContext.getAccessibleRelationSet(); if (xRelationSet != null) { print (xRelationSet.getRelationCount() + " ("); for (int i=0; i<xRelationSet.getRelationCount(); i++) { if (i > 0) print (", "); print (xRelationSet.getRelation(i).toString()); } println (")"); } else println ("no relation set"); print (sIndent + "State set : "); XAccessibleStateSet xStateSet = xContext.getAccessibleStateSet(); if (xStateSet != null) { XIndexAccess xStates = (XIndexAccess) UnoRuntime.queryInterface ( XIndexAccess.class, xStateSet); print (xStates.getCount() + " ("); for (int i=0; i<xStates.getCount(); i++) { if (i > 0) print (", "); print (xStates.getByIndex(i).toString()); } println (")"); } else println ("no state set"); showAccessibleComponent (xContext, sIndent); } else println ("object has no accessible context."); // showInfo (xContext); // showServices (xContext); // showInterfaces (xContext); } catch (Exception e) { System.out.println ("caught exception in showAccessibility :" + e); } return true; } /** @descr Print information about the given accessible component. */ public void showAccessibleComponent (XInterface xObject, String sIndent) { try { XAccessibleComponent xComponent = (XAccessibleComponent) UnoRuntime.queryInterface ( XAccessibleComponent.class, xObject); // Print information about the accessible context. if (xComponent != null) { println (sIndent + "Position : " + xComponent.getLocation().X+", " + xComponent.getLocation().Y); println (sIndent + "Screen position : " + xComponent.getLocationOnScreen().X+", " + xComponent.getLocationOnScreen().Y); println (sIndent + "Size : " + xComponent.getSize().Width+", " + xComponent.getSize().Height); } } catch (Exception e) { System.out.println ( "caught exception in showAccessibleComponent : " + e); } } /** Show a textual representation of the accessibility subtree rooted in xRoot. */ public boolean showAccessibilityTree (XAccessible xRoot, int depth) { try { if ( ! showAccessibility (xRoot, depth)) return false; String sIndent = ""; for (int i=0; i<depth; i++) sIndent += " "; // Iterate over children and show them. XAccessibleContext xContext = xRoot.getAccessibleContext(); if (xContext != null) { int n = xContext.getAccessibleChildCount(); for (int i=0; i<n; i++) { println (sIndent + "child " + i + " :"); showAccessibilityTree (xContext.getAccessibleChild(i),depth+1); } } else println ("Accessible object has no context"); } catch (Exception e) { System.out.println ( "caught exception in showAccessibleTree : " + e); return false; } return true; } public void showProperties (XInterface xObject) { XPropertySet xSet = (XPropertySet) UnoRuntime.queryInterface ( XPropertySet.class, xObject); if (xSet == null) println ("object does not support XPropertySet"); else { XPropertySetInfo xInfo = xSet.getPropertySetInfo (); Property[] aProperties = xInfo.getProperties (); int n = aProperties.length; for (int i=0; i<n; i++) println (i + " : " + aProperties[i].Name +", " + aProperties[i].Type); } } public void print (String text) { maPrinter.print (text); } public void println (String text) { maPrinter.println (text); } }
package com.drone.ui; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import com.drone.Drone; import com.drone.GaugeConfiguration; import com.drone.navdata.DroneNavData; import com.vaadin.addon.touchkit.ui.HorizontalButtonGroup; import com.vaadin.addon.touchkit.ui.Popover; import com.vaadin.server.FontAwesome; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.ComboBox; import com.vaadin.ui.VerticalLayout; public class AddGaugeDialog extends Popover { private static final long serialVersionUID = -2633336549420617084L; private GaugePanel panel; private Drone drone; private ComboBox gaugeSelector; public AddGaugeDialog(GaugePanel panel, Drone drone) { this.panel = panel; setWidth(200, Unit.PIXELS); setResizable(false); setClosable(true); center(); this.drone = drone; VerticalLayout layout = new VerticalLayout(); layout.setMargin(true); layout.setSpacing(true); List<GaugeConfiguration> availableGauges = determineAvailableGauges(); gaugeSelector = new ComboBox("Gauges"); gaugeSelector.setWidth(100, Unit.PERCENTAGE); gaugeSelector.setNullSelectionAllowed(false); layout.addComponent(gaugeSelector); for (GaugeConfiguration configuration : availableGauges) { gaugeSelector.addItem(configuration); gaugeSelector.setItemCaption(configuration, configuration .property().getName()); } HorizontalButtonGroup buttonLayout = new HorizontalButtonGroup(); Button add = new Button(FontAwesome.PLUS); Button close = new Button(FontAwesome.MINUS); add.addClickListener(e -> onAddClicked()); close.addClickListener(e -> close()); buttonLayout.addComponents(add, close); layout.addComponent(buttonLayout); layout.setComponentAlignment(buttonLayout, Alignment.BOTTOM_RIGHT); setContent(layout); } private void onAddClicked() { panel.addGauge((GaugeConfiguration) gaugeSelector.getValue()); close(); } private List<GaugeConfiguration> determineAvailableGauges() { List<GaugeConfiguration> droneProperties = new ArrayList<>(); Class<?> navDataInterface = null; for (Class<?> droneInterface : drone.getNavData().getClass() .getInterfaces()) { if (droneInterface.equals(DroneNavData.class)) { navDataInterface = droneInterface; } } if (navDataInterface == null) { throw new RuntimeException( "Drone's nav data does not implement DroneNavData interface"); } for (Method method : navDataInterface.getMethods()) { if (method.isAnnotationPresent(GaugeConfiguration.class)) { droneProperties.add(method .getAnnotation(GaugeConfiguration.class)); } } return droneProperties; } }
package com.twu.biblioteca; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.LinkedList; import static com.twu.biblioteca.PredefinedBooksDetails.*; import static com.twu.biblioteca.PredefinedMovieDetails.*; import static com.twu.biblioteca.PredefinedUserDetails.*; import static org.junit.Assert.*; public class LibraryTest { private Library library; private Book bookA, bookB, bookC, bookD, bookE; private Movie movieA, movieB, movieC, movieD; private final ByteArrayOutputStream outStream = new ByteArrayOutputStream(); private Customer customer; @Before public void setup(){ System.setOut(new PrintStream(outStream)); bookA = new Book(BOOK_ONE_NAME, BOOK_ONE_AUTHOR, BOOK_ONE_PUBLISHING_YEAR); bookB = new Book(BOOK_TWO_NAME, BOOK_TWO_AUTHOR, BOOK_TWO_PUBLISHING_YEAR); bookC = new Book(BOOK_THREE_NAME, BOOK_THREE_AUTHOR, BOOK_THREE_PUBLISHING_YEAR); bookD = new Book(BOOK_FOUR_NAME, BOOK_FOUR_AUTHOR, BOOK_FOUR_PUBLISHING_YEAR); bookE = new Book(BOOK_FIVE_NAME, BOOK_FIVE_AUTHOR, BOOK_FIVE_PUBLISHING_YEAR); movieA = new Movie(MOVIE_ONE_NAME, MOVIE_ONE_YEAR, MOVIE_ONE_DIRECTOR, MOVIE_ONE_RATING); movieB = new Movie(MOVIE_TWO_NAME, MOVIE_TWO_YEAR, MOVIE_TWO_DIRECTOR, MOVIE_TWO_RATING); movieC = new Movie(MOVIE_THREE_NAME, MOVIE_THREE_YEAR, MOVIE_THREE_DIRECTOR, MOVIE_THREE_RATING); movieD = new Movie(MOVIE_FOUR_NAME, MOVIE_FOUR_YEAR, MOVIE_FOUR_DIRECTOR, MOVIE_FOUR_RATING); LinkedList<LibraryItem> itemsList = new LinkedList<LibraryItem>(); itemsList.add(bookA); itemsList.add(bookB); itemsList.add(bookC); itemsList.add(bookD); itemsList.add(bookE); itemsList.add(movieA); itemsList.add(movieB); itemsList.add(movieC); itemsList.add(movieD); library = new Library(itemsList); customer = new Customer(DEFAULT_USERNAME); } @After public void cleanUp(){ System.setOut(null); } @Test public void testGetAllItemsList(){ assertEquals(9, library.getItemsList().size()); } @Test public void testGetAllBooksList(){ assertEquals(5, library.getAllBooksList().size()); } @Test public void testGetAllMoviesList(){ assertEquals(4, library.getAllMoviesList().size()); } @Test public void testGetAvailableItemListAfterBookAHasBeenCheckedOut(){ assertEquals(9, library.getAvailableItemsList().size()); bookA.checkOut(); assertEquals(8, library.getAvailableItemsList().size()); } @Test public void testGetAvailableBooksListAfterBookAHasBeenCheckedOut(){ assertEquals(5, library.getAvailableBooksList().size()); bookA.checkOut(); assertEquals(4, library.getAvailableBooksList().size()); } @Test public void testGetAvailableMoviesListAfterBookAHasBeenCheckedOut(){ assertEquals(4, library.getAvailableMoviesList().size()); bookA.checkOut(); assertEquals(4, library.getAvailableMoviesList().size()); } @Test public void testGetAvailableItemListAfterMovieAHasBeenCheckedOut(){ assertEquals(9, library.getAvailableItemsList().size()); bookA.checkOut(); assertEquals(8, library.getAvailableItemsList().size()); } @Test public void testGetAvailableBooksListAfterMovieAHasBeenCheckedOut(){ assertEquals(5, library.getAvailableBooksList().size()); movieA.checkOut(); assertEquals(5, library.getAvailableBooksList().size()); } @Test public void testGetAvailableMoviesListAfterMovieAHasBeenCheckedOut(){ assertEquals(4, library.getAvailableMoviesList().size()); movieA.checkOut(); assertEquals(3, library.getAvailableMoviesList().size()); } @Test public void testGetAvailableItemListAfterBookAHasBeenCheckedIn(){ bookA.checkOut(); assertEquals(8, library.getAvailableItemsList().size()); bookA.checkIn(); assertEquals(9, library.getAvailableItemsList().size()); } @Test public void testGetAvailableBooksListAfterBookAHasBeenCheckedIn(){ bookA.checkOut(); assertEquals(4, library.getAvailableBooksList().size()); bookA.checkIn(); assertEquals(5, library.getAvailableBooksList().size()); } @Test public void testGetAvailableMoviesListAfterMovieAHasBeenCheckedIn(){ bookA.checkOut(); assertEquals(4, library.getAvailableMoviesList().size()); bookA.checkIn(); assertEquals(4, library.getAvailableMoviesList().size()); } @Test public void testGetAvailableItemListAfterMovieAHasBeenCheckedIn(){ movieA.checkOut(); assertEquals(8, library.getAvailableItemsList().size()); movieA.checkIn(); assertEquals(9, library.getAvailableItemsList().size()); } @Test public void testGetAvailableBooksListAfterMovieAHasBeenCheckedIn(){ movieA.checkOut(); assertEquals(5, library.getAvailableBooksList().size()); movieA.checkIn(); assertEquals(5, library.getAvailableBooksList().size()); } @Test public void testGetAvailableMoviesListAfterBookAHasBeenCheckedIn(){ movieA.checkOut(); assertEquals(3, library.getAvailableMoviesList().size()); movieA.checkIn(); assertEquals(4, library.getAvailableMoviesList().size()); } @Test public void testShowAvailableBooksList(){ bookA.checkOut(); library.showAvailableBooksList(); assertEquals("The Old Man and the Sea Ernest Hemingway 1990\n" + "Programming Pearl Jon Bentley 2003\n" + "Hamlet Shakespeare 1972\n" + "Gone with the wind Margaret Mitchell 1980\n", outStream.toString()); outStream.reset(); bookD.checkOut(); library.showAvailableBooksList(); assertEquals("The Old Man and the Sea Ernest Hemingway 1990\n" + "Programming Pearl Jon Bentley 2003\n" + "Gone with the wind Margaret Mitchell 1980\n", outStream.toString()); } @Test public void testShowAvailableMoviesList(){ movieA.checkOut(); library.showAvailableMoviesList(); assertEquals("Jurassic Park 1990 Spielberg 7\n" + "007 2001 Louis 7\n" + "Lord of the Ring 2002 Tom 8\n", outStream.toString()); outStream.reset(); movieA.checkIn(); library.showAvailableMoviesList(); assertEquals("Star War 1996 Jim 9\n" + "Jurassic Park 1990 Spielberg 7\n" + "007 2001 Louis 7\n" + "Lord of the Ring 2002 Tom 8\n", outStream.toString()); } @Test public void testFindItem(){ assertNotNull(library.findItem(BOOK_ONE_NAME)); assertNotNull(library.findItem(MOVIE_TWO_NAME)); assertNull(library.findItem("Galaxy War")); } @Test public void testBookAIsAvailable(){ assertNotNull(library.findItemIfAvailable(BOOK_ONE_NAME)); assertTrue(library.findItemIfAvailable(BOOK_ONE_NAME) instanceof Book); } @Test public void testBookAIsNotAvailableAfterBeingCheckedOut(){ bookA.checkOut(); assertNull(library.findItemIfAvailable(BOOK_ONE_NAME)); } @Test public void testMovieAIsAvailable(){ assertNotNull(library.findItemIfAvailable(MOVIE_ONE_NAME)); assertTrue(library.findItemIfAvailable(MOVIE_ONE_NAME) instanceof Movie); } @Test public void testMovieAIsNotAvailableAfterBeingCheckedOut(){ movieA.checkOut(); assertNull(library.findItemIfAvailable(MOVIE_ONE_NAME)); } @Test public void testBuyBookA(){ assertEquals(SystemMessageType.INVALID_BOOK_OPTION, library.processBooksOperations("buy One Hundred Years of Solitude", customer)); assertFalse(bookA.getCheckOutStatus()); } @Test public void testSellBookA(){ assertEquals(SystemMessageType.INVALID_BOOK_OPTION, library.processBooksOperations("sell One Hundred Years of Solitude",customer)); assertFalse(bookA.getCheckOutStatus()); } @Test public void testBorrowBookA(){ assertEquals(SystemMessageType.SUCCESSFUL_CHECKOUT, library.processBooksOperations("borrow One Hundred Years of Solitude", customer)); assertTrue(bookA.getCheckOutStatus()); } @Test public void testBorrowUnknownBook(){ bookA.checkOut(); assertEquals(SystemMessageType.UNSUCCESSFUL_CHECKOUT, library.processBooksOperations("borrow One", customer)); } @Test public void testSellBookBAfterBorrowing(){ bookB.checkOut(); assertEquals(SystemMessageType.INVALID_BOOK_OPTION, library.processBooksOperations("sell The Old Man and the Sea", customer)); assertTrue(bookB.getCheckOutStatus()); } @Test public void testBuyBookBAfterBorrowing(){ bookB.checkOut(); assertEquals(SystemMessageType.INVALID_BOOK_OPTION, library.processBooksOperations("buy The Old Man and the Sea", customer)); assertTrue(bookB.getCheckOutStatus()); } @Test public void testReturnBookBAfterBorrowing(){ customer.borrowBook(bookB); assertEquals(SystemMessageType.SUCCESSFUL_RETURN, library.processBooksOperations("return The Old Man and the Sea", customer)); assertFalse(bookB.getCheckOutStatus()); } @Test public void testReturnUnknownBookAfterBorrowingBookB(){ customer.borrowBook(bookB); assertEquals(SystemMessageType.UNSUCCESSFUL_RETURN, library.processBooksOperations("return Galaxy War",customer)); } }
package sed.sky; import ssim.util.MathExt; import com.jme3.math.Vector3f; import chlib.noise.NoiseUtil; public class CloudHeightField { private int size; private int numOctaves; private float zoom; private Vector3f shift; private float cloudCover; public CloudHeightField(int size, int numOctaves) { this.size = size; this.numOctaves = numOctaves; } public float getZoom() { return zoom; } public void setZoom(float zoom) { this.zoom = zoom; } public Vector3f getShift() { return shift; } public void setShift(Vector3f shift) { this.shift = shift; } public float getCloudCover() { return cloudCover; } public void setCloudCover(float cloudCover) { this.cloudCover = cloudCover; } /** * @return a rows-first array with height data in [0,255] */ public float[][] generate() { return generate(null); } /** * @param store a float[][] to store the result * @return a rows-first array with height data in [0,255] */ public float[][] generate(float[][] store) { if(store == null) { store = new float[size][size]; } for(int column = 0; column < size; column++) { for(int row = 0; row < size; row++) { // alternative: NoiseUtil.turbulance2 float turbulance = NoiseUtil.fBm( (shift.x * size + column)/zoom, (shift.y * size + row)/zoom, shift.z, numOctaves, 2f, .5f); // float turbulance = NoiseUtil.turbulance2( // (shift.x * size + column)/zoom, // (shift.y * size + row)/zoom, // shift.z, // numOctaves); float height = (turbulance*255f) - cloudCover; height = MathExt.clamp(height, 0, 255); store[column][row] = height; } } return store; } }
package server; import java.io.FileInputStream; import java.security.Key; import java.security.KeyFactory; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.security.cert.Certificate; import java.security.spec.X509EncodedKeySpec; import java.util.logging.Level; import java.util.logging.Logger; import javax.crypto.Cipher; import database.DatabaseConnector; import dto.Validator; public class SecurityValidator { private static String securityKeyBasePath; private static String securityKeystoreAlias; private static String securityKeystorePassword; private static String securityKeystoreFile; private static String securityKeystorePrivatekey; public SecurityValidator() { securityKeyBasePath = ConfigurationProperties.securityKeyBasePath(); securityKeystoreAlias = ConfigurationProperties.securityKeystoreTallierAllias(); securityKeystorePassword = ConfigurationProperties.securityKeystoreTallierPassword(); securityKeystoreFile = securityKeyBasePath + ConfigurationProperties.securityKeystoreTallierFile(); securityKeystorePrivatekey = securityKeyBasePath + ConfigurationProperties.securityKeystoreTallierPrivatekey(); } public Validator checkSignature(String sig, int user_id) { DatabaseConnector dbc = new DatabaseConnector(); String pk = (String) dbc.getPubKeyByUserID(user_id).getObject(); Validator val = new Validator(); val.setVerified(false); if (pk == null) { val.setStatus("No public key available"); return val; } byte[] pubKey = hexStringtoByteArray(pk); byte[] signature = hexStringtoByteArray(sig); try { PublicKey PK = KeyFactory.getInstance("RSA").generatePublic( new X509EncodedKeySpec(pubKey)); Signature ver = Signature.getInstance("SHA256WITHRSA"); ver.initVerify(PK); ver.update(signature); val.setVerified(ver.verify(signature)); if (val.isVerified()) val.setStatus("Signature verified"); else val.setStatus("Signature did not verify"); return val; } catch (Exception ex) { Logger lgr = Logger.getLogger(SecurityValidator.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } return val; } public byte[] hexStringtoByteArray(String hex) { int len = hex.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character .digit(hex.charAt(i + 1), 16)); } return data; } public static String byteArraytoHex(byte[] arr) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < arr.length; i++) { sb.append(Integer.toString((arr[i] & 0xff) + 0x100, 16) .substring(1)); } return sb.toString(); } public String decrypt(String ciph) { byte[] ct = hexStringtoByteArray(ciph); try { PrivateKey priv = getPrivateKey(); Cipher dec = Cipher.getInstance("RSA"); dec.init(Cipher.DECRYPT_MODE, priv); byte[] plain = dec.doFinal(ct); String plaintext = byteArraytoHex(plain); return plaintext; } catch (Exception ex) { Logger lgr = Logger.getLogger(SecurityValidator.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } return null; } public PrivateKey getPrivateKey() { KeyStore ks; try { ks = KeyStore.getInstance("PKCS12"); // get user password and file input stream char[] password = "t@l1i3r".toCharArray(); java.io.FileInputStream fis = null; try { fis = new java.io.FileInputStream( "/Users/Steven/School Work/Grad School/" + "Research/Du-Vote/CERTUS-Server/resources/keys/pkcs12.p12"); ks.load(fis, password); } finally { if (fis != null) { fis.close(); } } KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection( password); // get my private key KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) ks .getEntry("tallier", protParam); PrivateKey myPrivateKey = pkEntry.getPrivateKey(); return myPrivateKey; } catch (Exception ex) { Logger lgr = Logger.getLogger(SecurityValidator.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); return null; } } public Validator getTallierPublicKey(){ Validator val=new Validator(); try{ FileInputStream is = new FileInputStream("/Users/Steven/School Work/Grad School/" + "Research/Du-Vote/CERTUS-Server/resources/keys/Tallier-Keys"); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(is, "t@l1i3r".toCharArray()); String alias = "tallier"; Key key = keystore.getKey(alias, "t@l1i3r".toCharArray()); if (key instanceof PrivateKey) { // Get certificate of public key Certificate cert = keystore.getCertificate(alias); // Get public key PublicKey publicKey = cert.getPublicKey(); val.setVerified(true); val.setStatus("Retrieved public key"); val.setObject(publicKey); return val; } else{ val.setVerified(false); val.setStatus("Failed to retrieve public key"); return val; } } catch(Exception ex){ Logger lgr = Logger.getLogger(DatabaseConnector.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); val.setStatus("Error occured"); val.setVerified(false); return val; } } }
package servlets; import java.io.IOException; import java.util.ArrayList; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import rmi.Initializer; import service.HtmlService; import service.ElectionService; import service.HeaderService; import service.LoginService; import service.TallyingService; import service.VotingService; import com.sun.xml.internal.messaging.saaj.packaging.mime.Header; import dto.CandidateDto; import dto.ElectionDto; import dto.ElectionProgressDto; import dto.Validator; import enumeration.ElectionStatus; import enumeration.ElectionType; import enumeration.Status; /** * Dmitriy Karmazin | dkarmazi * Servlet implementation class ElectionServlet */ @WebServlet(name = "election", urlPatterns = { "/election" }) public class ElectionServlet extends HttpServlet { private static final long serialVersionUID = 1L; private String mode = "1"; private String messageAlert = ""; private String messageLabel = ""; private String outModal = ""; private String outElections = ""; private String placeHoldElecName = "Enter election name here"; private String placeHoldElecDesc = "Enter election description here"; private String placeHoldElecEndTime = "Enter election end time here"; private String placeHoldElecCand = "Enter candidates names, one per line, candidates will appear in the same order as you specify."; private String placeHoldElecUsers = "Enter users emails, one per line."; private String tooltipElectionPassword = "Please specify a unique password which will be used to protect votes of this election.<br/> You will need this password in order to start tallying and publish the results of the election.<br/>WARNING: without this password, tallying of this election is impossible."; /** * @see HttpServlet#HttpServlet() */ public ElectionServlet() { super(); } /** * Dmitriy Karmazin * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // check authentication if (HeaderService.isTempUser(request)){ RequestDispatcher rd = getServletContext().getRequestDispatcher("/inviteduser"); rd.forward(request, response); } else if(HeaderService.isAuthenticated(request)) { resetGlobals(); routineExistingElections(request); request.setAttribute("mode", mode); request.setAttribute("message_alert", messageAlert); request.setAttribute("message_label", messageLabel); request.setAttribute("out_elections", outElections); request.setAttribute("out_modal", outModal); RequestDispatcher rd = getServletContext().getRequestDispatcher("/election.jsp"); rd.forward(request, response); } else { RequestDispatcher rd = getServletContext().getRequestDispatcher("/login"); rd.forward(request, response); } } /** * Dmitriy Karmazin * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if(HeaderService.isAuthenticated(request)) { resetGlobals(); if (request.getParameter("button_add_election") != null) { // SHOW NEW ELECTION SCREEN routineAddNewElectionModal(); } else if (request.getParameter("save_new_election") != null) { // ADDING A NEW ELECTION routineAddNewElection(request); } else if (request.getParameter("election") != null) { // SHOW EDIT ELECTION SCREEN routineEditElectionModal(request); } else if (request.getParameter("save_edit_election") != null) { // SAVE EDITED ELECTION routineEditElectionSave(request); } else if (request.getParameter("btn_elec_add_users") != null) { // SHOW USERS SCREEN routineElectionUsersModal(request); } else if (request.getParameter("save_edit_election_users") != null) { routineElectionUsers(request); } else if (request.getParameter("btn_elec_open") != null || request.getParameter("btn_elec_close") != null) { // PERFORM ACTION ON ELECTION routineActionOnElection(request); } else if(request.getParameter("btn_elec_publish") != null) { // PUBLISH BUTTON PRESSED routinePublishElectionModal(request); } else if(request.getParameter("btn_elec_publish_with_password") != null) { // PUBLISH BUTTON PRESSED routinePublishElection(request); } // refresh existing elections routineExistingElections(request); request.setAttribute("mode", mode); request.setAttribute("message_alert", messageAlert); request.setAttribute("message_label", messageLabel); request.setAttribute("out_elections", outElections); request.setAttribute("out_modal", outModal); RequestDispatcher rd = getServletContext().getRequestDispatcher( "/election.jsp"); rd.forward(request, response); } else { RequestDispatcher rd = getServletContext().getRequestDispatcher("/login"); rd.forward(request, response); } } /** * Dmitriy Karmazin * This function returns HTML output for all existing elections * @param elections * @return */ public String drawExistingElections(HttpServletRequest request, ArrayList<ElectionDto> elections) { String out = ""; if(elections != null && elections.size() != 0) { out += "<h5>Existing elections</h5>"; out += "<form action=\"election\" method=\"post\">"; out += "<table><thead><tr>"; out += "<th>Election Name</th>"; out += "<th>Election Status</th>"; out += "<th>Votes Collected</th>"; out += "<th>Eligible to Vote</th>"; out += "<th>Action</th>"; out += "</tr></thead><tbody>"; for (ElectionDto e : elections) { int voted = 0, votersTotal = 0; Validator v2 = TallyingService.voteProgressStatusForElection(request, e.getElectionId()); if(v2.isVerified()) { ElectionProgressDto epd = (ElectionProgressDto) v2.getObject(); voted = epd.getTotalVotes(); votersTotal = epd.getTotalEligible(); } String trClass = getElectionTableRowClass(e.getStatus()); out += "<tr class =\"" + trClass + "\">"; out += "<td class =\"" + trClass + "\">" + e.getElectionName() + "</td>"; out += "<td class =\"" + trClass + "\">" + drawElectionStatus(e.getStatus(), e.getStatusDescription()) + "</td>"; out += "<td class =\"" + trClass + "\">" + voted + " votes</td>"; out += "<td class =\"" + trClass + "\">" + votersTotal + "</td>"; out += "<td class =\"" + trClass + "\">" + drawElectionAction(e.getElectionId(), e.getStatus(), e.getElectionType()) + "</td>"; out += "</tr>"; } out += "</tbody></table></form>"; } else { out += "<div class=\"label secondary\">No elections exist yet</div>"; } return out; } /** * Dmitriy Karmazin * This method draws HTML modal output for a new election * @param e - election object to draw * @return HTML output */ public String drawNewElection(ElectionDto e) { String out = "", valElecName = "", valElecDesc = "", valElecCand = "", valElecEndTime = "", valRegEmails = "", valUnRegEmails = "", valPasswordErrorMessage = "", valElecCandErrorMessage = "", usersFieldStyle = ""; boolean valEmailListError = false, valPasswordError = false, valRequired = true, valElecCandError = false; int valElecId = 0, valElecAvailability = ElectionType.PRIVATE.getCode(); // checking null case if(e != null) { valElecId = e.getElectionId(); valElecName = e.getElectionName(); valElecDesc = e.getElectionDescription(); valElecCand = e.getCandidatesListString(); valElecCandError = e.isCandidateListError(); valElecCandErrorMessage = e.getCandidateListErrorMessage(); valElecEndTime = e.getCloseDatetime(); valElecAvailability = e.getElectionType(); valRegEmails = e.getRegisteredEmailList(); valEmailListError = e.isEmailListError(); valUnRegEmails = (valEmailListError) ? e.getUnregisteredEmailList() : ""; valPasswordError = e.isPasswordError(); valPasswordErrorMessage = e.getPasswordErrorMessage(); } if(valElecAvailability != ElectionType.PRIVATE.getCode()) { usersFieldStyle = "style=\"display: none;\""; valRequired = false; } out += "<form id=\"form_elec_new\" action=\"election\" method=\"post\" data-abide>"; out += "<div class=\"row\">"; out += "<h5>Add new election</h5>"; // draw election info out += "<div class=\"large-6 medium-6 columns\">"; out += "<fieldset><legend>Election Information</legend>"; out += HtmlService.drawInputTextAlphanumeric("new_election_name", "Election Name", placeHoldElecName, valElecName); out += HtmlService.drawInputTextareaAlphanumeric("new_election_description", "Election Description", placeHoldElecDesc, valElecDesc, false, "", true, ""); out += HtmlService.drawInputTextAlphanumericOptional("new_election_end_time", "Election Closing Time", placeHoldElecEndTime, valElecEndTime); out += "</fieldset>"; // password out += "<fieldset><legend>Protect election by password " + HtmlService.getToolTip(tooltipElectionPassword) + "</legend>"; out += HtmlService.drawInputTextPasswordAndConfirmation("new_election_password", "Election Password", "new_election_password_confirm", "Confirm Election Password", false); out += "</fieldset>"; out += "</div>"; // column 2 out += "<div class=\"large-6 medium-6 columns\">"; // candidates out += "<fieldset><legend>Add candidates</legend>"; out += HtmlService.drawInputTextareaAlphanumeric("new_election_candidates", "Candidates names", placeHoldElecCand, valElecCand, valElecCandError, valElecCandErrorMessage, true, ""); out += "</fieldset>"; // public and private out += "<fieldset><legend>Election availability</legend>"; out += HtmlService.drawSelectBoxElectionPrivateOrPublic("new_election_availability", valElecAvailability); // draw allowed users info out += "<div id=\"new_election_users_column\" " + usersFieldStyle + ">"; out += HtmlService.drawInputTextareaAlphanumeric("new_election_users", "Users emails", placeHoldElecUsers, valRegEmails, valEmailListError, "Not all users are registered in the system.", valRequired, ""); out += "</div>"; // draw failed users select out += "<div id=\"new_election_users_invite\" " + usersFieldStyle + ">"; out += HtmlService.drawCheckBoxesElectionPrivateOrPublic("new_election_users_invited", valEmailListError, valUnRegEmails); out += "</div>"; out += "</fieldset>"; out += "</div>"; out += "</div>"; // button and password out += "<div class=\"row\">"; out += "<div class=\"large-3 large-centered medium-3 medium-centered columns\">"; out += "<button class=\"radius button center\" type=\"submit\" name=\"save_new_election\" value=\"" + valElecId + "\">Save Election</button>"; out += "</div>"; out += "</div>"; out += "</form>"; return out; } /** * Dmitriy Karmazin * This function returns HTML output for editing election modal * @param e * @return */ public String drawEditElection(ElectionDto e) { String out = "", valElecName = "", valElecDesc = "", valElecCand = "", valElecEndTime = "", valRegEmails = "", valUnRegEmails = "", valElecCandErrorMessage = "", usersStyle = ""; int valElecId = 0, valElecAvailability = 0; boolean valEmailListError = false, valElecCandError = false, valRequired = true; // checking null case if(e != null) { valElecId = e.getElectionId(); valElecName = e.getElectionName(); valElecDesc = e.getElectionDescription(); valElecCand = e.getCandidatesListString(); valElecCandError = e.isCandidateListError(); valElecCandErrorMessage = e.getCandidateListErrorMessage(); valElecEndTime = e.getCloseDatetime(); valElecAvailability = e.getElectionType(); valRegEmails = e.getRegisteredEmailList(); valEmailListError = e.isEmailListError(); valUnRegEmails = (valEmailListError) ? e.getUnregisteredEmailList() : ""; } if(valElecAvailability != ElectionType.PRIVATE.getCode()) { usersStyle = "style=\"display: none;\""; valRequired = false; } out += "<form id=\"form_elec_edit\" action=\"election\" method=\"post\" data-abide>"; out += "<div class=\"row\">"; out += "<h5>Edit election</h5>"; // draw election info out += "<div class=\"large-6 medium-6 columns\">"; out += "<fieldset><legend>Election Information</legend>"; out += HtmlService.drawInputTextAlphanumeric("edit_election_name", "Election Name", placeHoldElecName, valElecName); out += HtmlService.drawInputTextareaAlphanumeric("edit_election_description", "Election Description", placeHoldElecDesc, valElecDesc, false, "", true, ""); out += HtmlService.drawInputTextAlphanumericOptional("edit_election_end_time", "Election Closing Time", placeHoldElecEndTime, valElecEndTime); out += "</fieldset>"; out += "<fieldset><legend>Add candidates</legend>"; out += HtmlService.drawInputTextareaAlphanumeric("edit_election_candidates", "Candidates names", placeHoldElecCand, valElecCand, valElecCandError, valElecCandErrorMessage, true, ""); out += "</fieldset>"; out += "</div>"; // draw allowed users info out += "<div class=\"large-6 medium-6 columns\">"; out += "<fieldset><legend>Election availability</legend>"; out += HtmlService.drawSelectBoxElectionPrivateOrPublic("edit_election_availability", valElecAvailability); // draw allowed users info out += "<div id=\"edit_election_users_column\" " + usersStyle + ">"; out += HtmlService.drawInputTextareaAlphanumeric("edit_election_users", "Users emails", placeHoldElecUsers, valRegEmails, valEmailListError, "Not all users are registered in the system.", valRequired, ""); out += "</div>"; out += "<div id=\"edit_election_users_invite\" " + usersStyle + ">"; out += HtmlService.drawCheckBoxesElectionPrivateOrPublic("edit_election_users_invited", valEmailListError, valUnRegEmails); out += "</div>"; out += "</fieldset>"; out += "</div>"; out += "</div>"; // button out += "<div class=\"row\">"; out += "<div class=\"large-3 large-centered medium-3 medium-centered columns\">"; out += "<button class=\"radius button right\" type=\"submit\" name=\"save_edit_election\" value=\"" + valElecId + "\">Save Election</button>"; out += "</div>"; out += "</div>"; out += "</form>"; return out; } public String drawElectionUsers(ElectionDto e) { String out = "", valElecName = "", valCurrentEmailList = "", valRegEmails = "", valUnRegEmails = "", valEmailListErrorMessage = ""; int valElecId = 0; boolean valEmailListError = false, valRequired = true; // checking null case if(e != null) { valElecId = e.getElectionId(); valElecName = e.getElectionName(); valCurrentEmailList = e.getCurrentEmailList(); valRegEmails = e.getRegisteredEmailList(); valEmailListError = e.isEmailListError(); valEmailListErrorMessage = e.getEmailListMessage(); valUnRegEmails = (valEmailListError) ? e.getUnregisteredEmailList() : ""; } out += "<h5>Add users to private election: " + valElecName + "</h5>"; out += "<form id=\"form_elec_edit\" action=\"election\" method=\"post\" data-abide>"; out += "<div class=\"row\">"; // draw election info out += "<div class=\"large-6 medium-6 columns\">"; out += "<fieldset><legend>Existing Users</legend>"; out += HtmlService.drawInputTextareaReadonly("edit_election_users", "Existing users", "No users", valCurrentEmailList, ""); out += "</fieldset>"; out += "</div>"; // draw allowed users info out += "<div id=\"edit_election_users_column\" class=\"large-6 medium-6 columns\">"; out += "<fieldset><legend>Invite additional users to vote</legend>"; out += HtmlService.drawInputTextareaAlphanumeric("edit_election_new_users", "Users emails", placeHoldElecUsers, valRegEmails, valEmailListError, "Not all users are registered in the system.", true, ""); out += HtmlService.drawCheckBoxesElectionPrivateOrPublic("edit_election_new_users_invited", valEmailListError, valUnRegEmails); out += "</fieldset>"; out += "</div>"; out += "</div>"; // button out += "<div class=\"row\">"; out += "<div class=\"large-3 large-centered medium-3 medium-centered columns\">"; out += "<button class=\"radius button right\" type=\"submit\" name=\"save_edit_election_users\" value=\"" + valElecId + "\">Save Election</button>"; out += "</div>"; out += "</div>"; out += "</form>"; return out; } /** * Dmitriy Karmazin * This function returns HTML output for action for given election and it's status * @param electionId * @param statusId * @return */ public String drawElectionAction(int electionId, int statusId, int electionTypeId) { String out = ""; if(statusId == ElectionStatus.NEW.getCode()) { out += "<button class=\"label radius\" type=\"submit\" name=\"btn_elec_open\" value=\"" + electionId + "\">Open</button>"; out += " / "; out += "<button class=\"label radius\" type=\"submit\" name=\"election\" value=\"" + electionId + "\">Edit</button>"; } else if(statusId == ElectionStatus.OPEN.getCode()) { out += "<button class=\"label radius\" type=\"submit\" name=\"btn_elec_close\" value=\"" + electionId + "\">Close</button>"; if(electionTypeId == ElectionType.PRIVATE.getCode()) { out += " / "; out += "<button class=\"label radius\" type=\"submit\" name=\"btn_elec_add_users\" value=\"" + electionId + "\">Add users</button>"; } } else if(statusId == ElectionStatus.CLOSED.getCode()) { out += "<button class=\"label radius\" type=\"submit\" name=\"btn_elec_open\" value=\"" + electionId + "\">Reopen</button>"; out += " / "; out += "<button class=\"label radius\" type=\"submit\" name=\"btn_elec_publish\" value=\"" + electionId + "\">Publish</button>"; } else if(statusId == ElectionStatus.PUBLISHED.getCode()) { out += ""; } return out; } public String getElectionTableRowClass(int statusId) { String out = ""; if(statusId == ElectionStatus.NEW.getCode()) { out += "election_new"; } else if(statusId == ElectionStatus.OPEN.getCode()) { out += "election_open"; } else if(statusId == ElectionStatus.CLOSED.getCode()) { out += "election_closed"; } else if(statusId == ElectionStatus.PUBLISHED.getCode()) { out += "election_published"; } return out; } /** * Dmitriy Karmazin * @param status - current status of election * @param value - string representation of status * @return */ public String drawElectionStatus(int status, String value) { String out = "", outClass=""; if(status == ElectionStatus.NEW.getCode()) { outClass = "label clear"; } else if(status == ElectionStatus.OPEN.getCode()) { outClass = "label clear"; } else if(status == ElectionStatus.CLOSED.getCode()) { outClass = "label clear"; } else if(status == ElectionStatus.PUBLISHED.getCode()) { outClass = "label clear"; } else { return out; } out = "<span class=\"" + outClass + "\">" + value + "</span>"; return out; } /** * Dmitriy Karmazin * This function returns HTML output for edit button for an eletion */ public String drawElectionEdit(int electionId, int statusId) { String out = ""; if(statusId == ElectionStatus.NEW.getCode()) { out += "<button class=\"label button_link radius\" type=\"submit\" name=\"election\" value=\"" + electionId + "\">Edit</button></td>"; } return out; } /** * Dmitriy Karmazin * This functions resets all global variables for this class */ private void resetGlobals() { this.mode = "1"; this.messageAlert = ""; this.messageLabel = ""; this.outModal = ""; this.outElections = ""; } /** * Dmitriy Karmazin * This function sets global variables to display existing elections */ public void routineExistingElections(HttpServletRequest request) { // get the list of elections from DB ArrayList<ElectionDto> allElections = new ArrayList<ElectionDto>(); Validator v = ElectionService.selectElectionsForOwner(request, HeaderService.getUserId(request)); if(v.isVerified()) { allElections = (ArrayList<ElectionDto>) v.getObject(); } else { messageAlert = HtmlService.drawMessageAlert(v.getStatus(), "alert") ; } outElections = drawExistingElections(request, allElections); } /** * Dmitriy Karmazin * This function makes required actions to insert a new election to DB * @param request */ public void routineAddNewElection(HttpServletRequest request) { resetGlobals(); // prepare new election ElectionDto newElection = new ElectionDto(); newElection.setElectionName(request.getParameter("new_election_name")); newElection.setElectionDescription(request.getParameter("new_election_description")); newElection.setCandidatesListString(request.getParameter("new_election_candidates")); newElection.setCloseDatetime(request.getParameter("new_election_end_time")); newElection.setElectionType(Integer.parseInt(request.getParameter("new_election_availability"))); newElection.setEmailList(request.getParameter("new_election_users")); newElection.setPassword(request.getParameter("new_election_password")); newElection.setEmailListInvited(getStringFromArray(request.getParameterValues("new_election_users_invited"))); newElection.setOwnerId(HeaderService.getUserId(request)); // insert attempt Validator vElection = ElectionService.addElection(request, newElection); if (vElection.isVerified()) { //insert was successful mode = "1"; messageAlert = HtmlService.drawMessageAlert(vElection.getStatus(), "success"); } else { // errors, send back to add election screen mode = "2"; messageLabel = HtmlService.drawMessageLabel(vElection.getStatus(), "alert"); outModal = drawNewElection((ElectionDto)vElection.getObject()); } } /** * Dmitriy Karmazin * This function performs required routines to open edit modal * @param request */ public void routineEditElectionModal(HttpServletRequest request) { resetGlobals(); // get election by provided election id int electionId = Integer.parseInt(request.getParameter("election")); Validator vEditElection = ElectionService.selectElectionForOwner(request, electionId); if (vEditElection.isVerified()) { ElectionDto editElection = (ElectionDto) vEditElection.getObject(); this.mode = "2"; this.outModal = drawEditElection(editElection); } else { messageAlert = HtmlService.drawMessageAlert(vEditElection.getStatus(), "alert"); } } /** * Dmitriy Karmazin * This performs routines required to update an existing election * @param request */ public void routineEditElectionSave(HttpServletRequest request) { resetGlobals(); String usersToInvite = getStringFromArray(request.getParameterValues("edit_election_users_invited")); ElectionDto editElection = new ElectionDto(); editElection.setElectionId(Integer.parseInt(request.getParameter("save_edit_election"))); editElection.setElectionName(request.getParameter("edit_election_name")); editElection.setElectionDescription(request.getParameter("edit_election_description")); editElection.setCandidatesListString(request.getParameter("edit_election_candidates")); editElection.setCloseDatetime(request.getParameter("edit_election_end_time")); editElection.setElectionType(Integer.parseInt(request.getParameter("edit_election_availability"))); editElection.setEmailList(request.getParameter("edit_election_users")); editElection.setEmailListInvited(getStringFromArray(request.getParameterValues("edit_election_users_invited"))); editElection.setOwnerId(HeaderService.getUserId(request)); // update existing election Validator vEditElection = ElectionService.editElection(request, editElection); if (vEditElection.isVerified()) { // insert of candidates was successful this.mode = "1"; this.messageAlert = HtmlService.drawMessageAlert( vEditElection.getStatus(), "success"); } else { // error, return to editing screen this.mode = "2"; this.messageLabel = HtmlService.drawMessageLabel( vEditElection.getStatus(), "alert"); this.outModal = drawEditElection((ElectionDto) vEditElection.getObject()); } } /** * Dmitriy Karmazin * This function performs required actions to show add new election modal */ public void routineAddNewElectionModal() { resetGlobals(); mode = "2"; messageLabel = HtmlService.drawMessageLabel("Please fill in required fields", "secondary"); outModal = drawNewElection(null); } /** * Dmitriy Karmazin * This function performs a particular action on given election * @param request */ public void routineActionOnElection(HttpServletRequest request) { resetGlobals(); // get election id int electionId = 0, action = -1; if(request.getParameter("btn_elec_open") != null) { electionId = Integer.parseInt(request.getParameter("btn_elec_open")); action = ElectionStatus.OPEN.getCode(); } else if(request.getParameter("btn_elec_close") != null) { electionId = Integer.parseInt(request.getParameter("btn_elec_close")); } else if(request.getParameter("btn_elec_publish") != null) { electionId = Integer.parseInt(request.getParameter("btn_elec_publish")); action = ElectionStatus.PUBLISHED.getCode(); } Validator v1 = ElectionService.selectElectionForOwner(request, electionId); if (v1.isVerified()) { ElectionDto e = (ElectionDto) v1.getObject(); if (e.getStatus() == ElectionStatus.NEW.getCode()) { // open election Validator v2 = ElectionService.openElection(request, electionId); messageAlert = HtmlService.drawMessageAlert( v2.getStatus(), ""); } else if (e.getStatus() == ElectionStatus.OPEN.getCode()) { // close election Validator v3 = ElectionService .closeElection(request, electionId); messageAlert = HtmlService.drawMessageAlert( v3.getStatus(), "success"); } else if (e.getStatus() == ElectionStatus.CLOSED.getCode() && action == ElectionStatus.OPEN.getCode()) { // reopen Validator v4 = ElectionService.reOpenElection(request, electionId); messageAlert = HtmlService.drawMessageAlert( v4.getStatus(), "success"); } } else { messageAlert = HtmlService.drawMessageAlert( v1.getStatus(), "alert"); } } /** * Dmitriy Karmazin * This function performs all routines required to display users editing modal * @param request */ public void routineElectionUsersModal(HttpServletRequest request) { resetGlobals(); int electionId = 0; if(request.getParameter("btn_elec_add_users") != null) { electionId = Integer.parseInt(request.getParameter("btn_elec_add_users")); } Validator vElectionUsers = ElectionService.selectElectionFullDetail(request, electionId); if (vElectionUsers.isVerified()) { ElectionDto editElection = (ElectionDto) vElectionUsers.getObject(); this.mode = "2"; this.outModal = drawElectionUsers(editElection); } else { messageAlert = HtmlService.drawMessageAlert(vElectionUsers.getStatus(), "alert"); } } public void routineElectionUsers(HttpServletRequest request) { resetGlobals(); int electionId = 0; if(request.getParameter("save_edit_election_users") != null) { electionId = Integer.parseInt(request.getParameter("save_edit_election_users")); } // prepare new election ElectionDto newElection = new ElectionDto(); newElection.setElectionId(electionId); newElection.setEmailList(request.getParameter("edit_election_new_users")); newElection.setEmailListInvited(getStringFromArray(request.getParameterValues("edit_election_new_users_invited"))); newElection.setOwnerId(HeaderService.getUserId(request)); // insert attempt Validator vElection = ElectionService.addAdditionalUsersToElection(request, newElection); if (vElection.isVerified()) { //insert was successful mode = "1"; messageAlert = HtmlService.drawMessageAlert(vElection.getStatus(), "success"); } else { // errors, send back to add election screen mode = "2"; messageLabel = HtmlService.drawMessageLabel(vElection.getStatus(), "alert"); outModal = drawElectionUsers((ElectionDto) vElection.getObject()); } } /** * Dmitriy Karmazin * This function performs all activities to display modal before publishing election results * @param request */ public void routinePublishElectionModal(HttpServletRequest request) { resetGlobals(); int electionId = 0; if(request.getParameter("btn_elec_publish") != null) { electionId = Integer.parseInt(request.getParameter("btn_elec_publish")); } Validator vEditElection = ElectionService.selectElectionForOwner(request, electionId); if (vEditElection.isVerified()) { this.mode = "2"; this.outModal = drawPasswordWithConfirmForElection((ElectionDto) vEditElection.getObject()); } else { messageAlert = HtmlService.drawMessageAlert(vEditElection.getStatus(), "alert"); } } /** * Dmitriy Karmazin * This function returns HTML output for password modal * @param e * @return */ public String drawPasswordWithConfirmForElection(ElectionDto e) { String out = "", valElecName = "", valPasswordErrorMessage = ""; int valElecId = 0; boolean valPasswordError = false; // checking null case if(e != null) { valElecId = e.getElectionId(); valElecName = e.getElectionName(); valPasswordError = e.isPasswordError(); valPasswordErrorMessage = (valPasswordError) ? "Invalid password" : ""; } out += "<form id=\"form_elec_new\" action=\"election\" method=\"post\" data-abide>"; out += "<div class=\"row\">"; out += "<div class=\"large-6 large-centered medium-6 medium-centered columns\">"; out += "<h5>Publish Election Results: " + valElecName + "</h5>"; out += "<fieldset><legend>Please Enter Election Password</legend>"; out += "<p class=\"global_warning\">Warning! Election publishing is irrevocable action.<br>The results of this election will become available to voters and you will not be able to reopen this election anymore.<br> Enter election password and click 'Publish Election' to proceed or click 'Cancel Publishing' otherwise.</p>"; out += HtmlService.drawInputTextPassword("election_publish_password", "Election Password", "", "", valPasswordError, valPasswordErrorMessage); out += "</fieldset>"; out += "<button class=\"radius button left\" type=\"submit\" name=\"btn_elec_publish_with_password\" value=\"" + valElecId + "\">Publish Election</button>"; out += "<button class=\"button alert right\" type=\"button\" id=\"btn_elec_publish_cancel\" \">Cancel Publishing</button>"; out += "</div>"; out += "</div>"; out += "</form>"; return out; } /** * Dmitriy Karmazin * This function performes routines required for publishing an election * @param request */ public void routinePublishElection(HttpServletRequest request) { resetGlobals(); int electionId = 0; String password = ""; if(request.getParameter("btn_elec_publish_with_password") != null) { electionId = Integer.parseInt(request.getParameter("btn_elec_publish_with_password")); } if(request.getParameter("election_publish_password") != null) { password = request.getParameter("election_publish_password"); } Validator v1 = ElectionService.publishResults(request, electionId, password); if(v1.isVerified()) { messageAlert = HtmlService.drawMessageAlert("Election published", "success"); } else { mode = "2"; outModal = drawPasswordWithConfirmForElection((ElectionDto) v1.getObject()); messageLabel = HtmlService.drawMessageLabel(v1.getStatus(), "alert"); } } /** * Dmitriy Karmazin * This function returns string out of given array * @param arrayOfStrings * @return */ public String getStringFromArray(String[] arrayOfStrings) { String out = ""; String deliminter = System.getProperty("line.separator"); if(arrayOfStrings != null) { for(String str : arrayOfStrings) { out += str + deliminter; } } return out; } }
package org.jboss.xnio; /** * The version class. */ public final class Version { private Version() {} /** * The current XNIO version. */ public static final String VERSION = "1.0.0.CR1"; /** * Print out the current XNIO version on {@code System.out}. * * @param args ignored */ public static void main(String[] args) { System.out.print(VERSION); } }
package com.exedio.cope; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import com.exedio.cope.testmodel.AttributeItem; import com.exedio.cope.testmodel.Main; /** * Tests the model itself, without creating/using any persistent data. * @author Ralf Wiebicke */ public class ModelTest extends TestmodelTest { public void testSupportsReadCommitted() { assertEquals( true, model.hasCurrentTransaction() ); assertEquals(dialect.supportsReadCommitted, model.supportsReadCommitted()); } public static final void assertEquals(final String expected, final String actual) { assertEquals(" } public void testConnect() { final Properties defaultProps = getProperties(); // test duplicate call of connect final Date connectDate = model.getConnectDate(); assertNotNull(connectDate); try { model.connect(defaultProps); fail(); } catch(IllegalStateException e) { assertEquals("model already been connected", e.getMessage()); } assertSame(connectDate, model.getConnectDate()); } @Deprecated // OK: test deprecated api public void testAttributeOption() throws IOException { final AttributeItem item = null; assertEquals(false, item.MANDATORY.isFinal); assertEquals(false, item.MANDATORY.unique); assertEquals(false, item.MANDATORY.optional); assertEquals(false, item.OPTIONAL.isFinal); assertEquals(false, item.OPTIONAL.unique); assertEquals(true, item.OPTIONAL.optional); assertEquals(false, item.UNIQUE.isFinal); assertEquals(true, item.UNIQUE.unique); assertEquals(false, item.UNIQUE.optional); assertEquals(false, item.UNIQUE_OPTIONAL.isFinal); assertEquals(true, item.UNIQUE_OPTIONAL.unique); assertEquals(true, item.UNIQUE_OPTIONAL.optional); assertEquals(true, item.FINAL.isFinal); assertEquals(false, item.FINAL.unique); assertEquals(false, item.FINAL.optional); assertEquals(true, item.FINAL_OPTIONAL.isFinal); assertEquals(false, item.FINAL_OPTIONAL.unique); assertEquals(true, item.FINAL_OPTIONAL.optional); assertEquals(true, item.FINAL_UNIQUE.isFinal); assertEquals(true, item.FINAL_UNIQUE.unique); assertEquals(false, item.FINAL_UNIQUE.optional); assertEquals(true, item.FINAL_UNIQUE_OPTIONAL.isFinal); assertEquals(true, item.FINAL_UNIQUE_OPTIONAL.unique); assertEquals(true, item.FINAL_UNIQUE_OPTIONAL.optional); } public void testType() throws IOException { final AttributeItem item = null; assertEquals(AttributeItem.class, item.TYPE.getJavaClass()); assertEquals(true, item.TYPE.hasUniqueJavaClass()); assertEquals(item.TYPE, Type.findByJavaClass(AttributeItem.class)); try { Type.findByJavaClass(Item.class); fail(); } catch(IllegalArgumentException e) { assertEquals("there is no type for class com.exedio.cope.Item", e.getMessage()); } assertEquals(item.TYPE, model.findTypeByID(item.TYPE.getID())); assertSame(item.TYPE, item.TYPE.getThis().getType()); assertEquals("AttributeItem.this", item.TYPE.getThis().getID()); assertEquals("AttributeItem.this", item.TYPE.getThis().toString()); assertEquals("this", item.TYPE.getThis().getName()); final Field[] attributes = { item.someString, item.someNotNullString, item.someInteger, item.someNotNullInteger, item.someLong, item.someNotNullLong, item.someDouble, item.someNotNullDouble, item.someDate, item.day, item.someBoolean, item.someNotNullBoolean, item.someItem, item.someNotNullItem, item.someEnum, item.someNotNullEnum, item.someData.getBody(), item.someData.getContentType(), item.someData.getLastModified(), }; assertEqualsUnmodifiable(Arrays.asList(attributes), item.TYPE.getFields()); assertEqualsUnmodifiable(Arrays.asList(attributes), item.TYPE.getDeclaredFields()); assertEqualsUnmodifiable(list(), item.TYPE.getUniqueConstraints()); assertEqualsUnmodifiable(list(), item.TYPE.getDeclaredUniqueConstraints()); final Feature[] features = { item.TYPE.getThis(), item.someString, item.someStringUpperCase, item.someStringLength, item.someNotNullString, item.someInteger, item.someNotNullInteger, item.someLong, item.someNotNullLong, item.someDouble, item.someNotNullDouble, item.someDate, item.day, item.someBoolean, item.someNotNullBoolean, item.someItem, item.someNotNullItem, item.someEnum, item.someNotNullEnum, item.someData, item.someData.getBody(), item.someData.getContentType(), item.someData.getLastModified(), }; assertEqualsUnmodifiable(Arrays.asList(features), item.TYPE.getFeatures()); assertEqualsUnmodifiable(Arrays.asList(features), item.TYPE.getDeclaredFeatures()); assertEquals(item.someString, item.TYPE.getDeclaredFeature("someString")); assertEquals(item.someStringUpperCase, item.TYPE.getDeclaredFeature("someStringUpperCase")); try { new Type<Item>(null); fail(); } catch(NullPointerException e) {} try { new Type<Item>(Item.class); fail(); } catch(IllegalArgumentException e) { assertEquals("Cannot make a type for " + Item.class + " itself, but only for subclasses.", e.getMessage()); } try { new Type<Item>(castItemClass(NoItem.class)); fail(); } catch(IllegalArgumentException e) { assertEquals(NoItem.class.toString() + " is not a subclass of Item", e.getMessage()); } try { new Type<NoCreationConstructor>(NoCreationConstructor.class); fail(); } catch(IllegalArgumentException e) { assertEquals( NoCreationConstructor.class.getName() + " does not have a creation constructor", e.getMessage()); assertEquals(NoSuchMethodException.class, e.getCause().getClass()); } try { new Type<NoReactivationConstructor>(NoReactivationConstructor.class); fail(); } catch(IllegalArgumentException e) { assertEquals(e.getMessage(), NoReactivationConstructor.class.getName() + " does not have a reactivation constructor", e.getMessage()); assertEquals(NoSuchMethodException.class, e.getCause().getClass()); } try { new Model((Type[])null); fail(); } catch(NullPointerException e) { assertEquals("types must not be null", e.getMessage()); } try { new Model(new Type[]{}); fail(); } catch(IllegalArgumentException e) { assertEquals("types must not be empty", e.getMessage()); } // TODO put this into an extra test called an extra ant target { final String prefix = System.getProperty("com.exedio.cope.testprotocol.prefix"); if(prefix!=null) { final java.util.Properties databaseInfo = model.getDatabaseInfo(); final java.util.Properties prefixed = new java.util.Properties(); final File file = new File(System.getProperty("com.exedio.cope.testprotocol.file")); for(Iterator i = databaseInfo.keySet().iterator(); i.hasNext(); ) { final String name = (String)i.next(); prefixed.setProperty(prefix+'.'+name, databaseInfo.getProperty(name)); } final Properties p = model.getProperties(); for(final Properties.Field field : p.getFields()) { if(field.getDefaultValue()!=null && field!=p.mediaRooturl && !field.hasHiddenValue() && field.isSpecified() && field.getValue()!=null) prefixed.setProperty(prefix+".cope."+field.getKey(), field.getValue().toString()); } final PrintStream out = new PrintStream(new FileOutputStream(file, true)); prefixed.store(out, null); out.close(); } } } static class NoItem { NoItem() { // just a dummy constructor } } static class NoCreationConstructor extends Item { private static final long serialVersionUID = 1l; NoCreationConstructor() { super(new SetValue[]{}); } } static class NoReactivationConstructor extends Item { private static final long serialVersionUID = 1l; NoReactivationConstructor(final SetValue[] initialAttributes) { super(initialAttributes); } } @SuppressWarnings("unchecked") // OK: test bad API usage private static final Class<Item> castItemClass(Class c) { return c; } public void testDisconnect() { assertWithin(Main.beforeModel, Main.afterModel, model.getInitializeDate()); model.commit(); final Properties p = model.getProperties(); assertNotNull(p); model.disconnect(); try { model.getProperties(); fail(); } catch(IllegalStateException e) { assertEquals("model not yet connected, use connect(Properties)", e.getMessage()); } assertEquals(null, model.getConnectDate()); try { model.disconnect(); fail(); } catch(IllegalStateException e) { assertEquals("model not yet connected, use connect(Properties)", e.getMessage()); } assertEquals(null, model.getConnectDate()); final Date before = new Date(); model.connect(p); final Date after = new Date(); assertSame(p, model.getProperties()); assertWithin(before, after, model.getConnectDate()); model.startTransaction("ModelTest.testDisconnect"); } }
package io.debezium.connector.postgresql.connection.wal2json; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.kafka.connect.data.Field; import org.apache.kafka.connect.errors.ConnectException; import org.postgresql.core.Oid; import org.postgresql.geometric.PGpoint; import org.postgresql.jdbc.PgArray; import org.postgresql.util.PGInterval; import org.postgresql.util.PGmoney; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.debezium.connector.postgresql.PostgresValueConverter; import io.debezium.connector.postgresql.RecordsStreamProducer.PgConnectionSupplier; import io.debezium.connector.postgresql.connection.ReplicationMessage; import io.debezium.document.Array; import io.debezium.document.Document; import io.debezium.document.Value; import io.debezium.util.Strings; /** * Replication message representing message sent by the wal2json logical decoding plug-in. * * @author Jiri Pechanec */ class Wal2JsonReplicationMessage implements ReplicationMessage { private static final Logger LOGGER = LoggerFactory.getLogger(Wal2JsonReplicationMessage.class); private final int txId; private final long commitTime; private final Document rawMessage; public Wal2JsonReplicationMessage(final int txId, final long commitTime, final Document rawMessage) { this.txId = txId; this.commitTime = commitTime; this.rawMessage = rawMessage; } @Override public Operation getOperation() { final String operation = rawMessage.getString("kind"); switch (operation) { case "insert": return Operation.INSERT; case "update": return Operation.UPDATE; case "delete": return Operation.DELETE; } throw new IllegalArgumentException( "Unknown operation '" + operation + "' in replication stream message"); } @Override public long getCommitTime() { return commitTime; } @Override public int getTransactionId() { return txId; } @Override public String getTable() { return "\"" + rawMessage.getString("schema") + "\".\"" + rawMessage.getString("table") + "\""; } @Override public List<ReplicationMessage.Column> getOldTupleList() { final Document oldkeys = rawMessage.getDocument("oldkeys"); return oldkeys != null ? transform(oldkeys, "keynames", "keytypes", "keyvalues") : null; } @Override public List<ReplicationMessage.Column> getNewTupleList() { return transform(rawMessage, "columnnames", "columntypes", "columnvalues"); } private List<ReplicationMessage.Column> transform(final Document data, final String nameField, final String typeField, final String valueField) { final Array columnNames = data.getArray(nameField); final Array columnTypes = data.getArray(typeField); final Array columnValues = data.getArray(valueField); if (columnNames.size() != columnTypes.size() || columnNames.size() != columnValues.size()) { throw new ConnectException("Column related arrays do not have the same size"); } final List<ReplicationMessage.Column> columns = new ArrayList<>(columnNames.size()); for (int i = 0; i < columnNames.size(); i++) { String columnName = columnNames.get(i).asString(); String columnType = columnTypes.get(i).asString(); Value rawValue = columnValues.get(i); columns.add(new ReplicationMessage.Column() { @Override public Object getValue(PgConnectionSupplier connection) { return Wal2JsonReplicationMessage.this.getValue(columnName, columnType, rawValue, connection); } @Override public String getType() { return columnType; } @Override public String getName() { return columnName; } }); } return columns; } /** * Converts the value (string representation) coming from wal2json plugin to * a Java value based on the type of the column from the message. This value will be converted later on if necessary by the * {@link PostgresValueConverter#converter(Column, Field)} instance to match whatever the Connect schema type expects. * * Note that the logic here is tightly coupled (i.e. dependent) on the wal2json plugin logic which writes the actual * JSON messages. * @param a supplier to get a connection to Postgres instance for array handling * * @return the value; may be null */ public Object getValue(String columnName, String columnType, Value rawValue, final PgConnectionSupplier connection) { switch (columnType) { case "bool": return rawValue.isNotNull() ? rawValue.asBoolean() : null; case "int2": case "int4": return rawValue.isNotNull() ? rawValue.asInteger() : null; case "int8": case "oid": return rawValue.isNotNull() ? rawValue.asLong() : null; case "float4": return rawValue.isNotNull() ? rawValue.asFloat() : null; case "float8": return rawValue.isNotNull() ? rawValue.asDouble() : null; case "numeric": return rawValue.isNotNull() ? rawValue.asDouble() : null; case "char": case "varchar": case "bpchar": case "text": case "json": case "jsonb": case "xml": case "uuid": case "bit": case "varbit": case "tstzrange": return rawValue.isNotNull() ? rawValue.asString() : null; case "date": return rawValue.isNotNull() ? DateTimeFormat.get().date(rawValue.asString()) : null; case "timestamp": return rawValue.isNotNull() ? DateTimeFormat.get().timestamp(rawValue.asString()) : null; case "timestamptz": return rawValue.isNotNull() ? DateTimeFormat.get().timestampWithTimeZone(rawValue.asString()) : null; case "time": return rawValue.isNotNull() ? DateTimeFormat.get().time(rawValue.asString()) : null; case "timetz": return rawValue.isNotNull() ? DateTimeFormat.get().timeWithTimeZone(rawValue.asString()) : null; case "bytea": return Strings.hexStringToByteArray(rawValue.asString()); case "point": try { return rawValue.isNotNull() ? new PGpoint(rawValue.asString()) : null; } catch (final SQLException e) { LOGGER.error("Failed to parse point {}, {}", rawValue.asString(), e); throw new ConnectException(e); } case "money": try { return rawValue.isNotNull() ? new PGmoney(rawValue.asString()).val : null; } catch (final SQLException e) { LOGGER.error("Failed to parse money {}, {}", rawValue.asString(), e); throw new ConnectException(e); } case "interval": try { return rawValue.isNotNull() ? new PGInterval(rawValue.asString()) : null; } catch (final SQLException e) { LOGGER.error("Failed to parse point {}, {}", rawValue.asString(), e); throw new ConnectException(e); } case "_int2": case "_int4": case "_int8": case "_text": case "_numeric": case "_float4": case "_float8": case "_bool": case "_date": case "_time": case "_timetz": case "_timestamp": case "_timestamptz": case "_bytea": case "_varchar": case "_oid": case "_bpchar": case "_money": case "_name": case "_interval": case "_char": case "_varbit": case "_uuid": case "_xml": case "_point": case "_jsonb": case "_json": case "_ref_cursor": try { if (rawValue.isNull()) { return null; } final String dataString = rawValue.asString(); PgArray arrayData = new PgArray(connection.get(), Oid.valueOf(columnType.substring(1) + "_array"), dataString); Object deserializedArray = arrayData.getArray(); return Arrays.asList((Object[])deserializedArray); } catch (SQLException e) { LOGGER.warn("Unexpected exception trying to process PgArray column '{}'", columnName, e); } return null; } LOGGER.warn("processing column '{}' with unknown data type '{}' as byte array", columnName, columnType); return rawValue.asBytes(); } }
package org.drools.planner.core.localsearch.decider.acceptor.tabu; import org.drools.planner.core.localsearch.LocalSearchSolverPhaseScope; import org.drools.planner.core.localsearch.LocalSearchStepScope; import org.drools.planner.core.localsearch.decider.MoveScope; import org.drools.planner.core.move.Move; import org.drools.planner.core.score.buildin.simple.DefaultSimpleScore; import org.drools.planner.core.solver.DefaultSolverScope; import org.drools.planner.core.testdata.domain.TestdataValue; import org.junit.Test; import java.util.Arrays; import java.util.Collection; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class PlanningValueTabuAcceptorTest { @Test public void tabuSize() { PlanningValueTabuAcceptor acceptor = new PlanningValueTabuAcceptor(); acceptor.setTabuSize(2); acceptor.setAspirationEnabled(true); TestdataValue v0 = new TestdataValue("v0"); TestdataValue v1 = new TestdataValue("v1"); TestdataValue v2 = new TestdataValue("v2"); TestdataValue v3 = new TestdataValue("v3"); TestdataValue v4 = new TestdataValue("v4"); DefaultSolverScope solverScope = new DefaultSolverScope(); solverScope.setBestScore(new DefaultSimpleScore(0)); LocalSearchSolverPhaseScope solverPhaseScope = new LocalSearchSolverPhaseScope(solverScope); acceptor.phaseStarted(solverPhaseScope); //FIRST STEP: no values in tabuList, acceptor should accept everything. LocalSearchStepScope stepScope0 = new LocalSearchStepScope(solverPhaseScope); stepScope0.setStepIndex(0); MoveScope moveScope1 = buildMoveScope(stepScope0, v1); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, v0))); assertEquals(true, acceptor.isAccepted(moveScope1)); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, v2))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, v3))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, v4))); //Repeated calls containing values which are not in tabuList should get accepted too. assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, v2))); //We accept first move, v1 should be added to tabuList stepScope0.setStep(moveScope1.getMove()); acceptor.stepEnded(stepScope0); //SECOND STEP: v1 in tabuList, acceptor should accept every move //except a move containing v1 LocalSearchStepScope stepScope1 = new LocalSearchStepScope(solverPhaseScope); stepScope1.setStepIndex(1); MoveScope moveScope2 = buildMoveScope(stepScope1, v2); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, v0))); //moves containing values which are in tabuList should not get accepted assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, v1))); //Any amount of repeated calls containing moves with values which are in tabuList //should get rejected too assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, v1))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, v1))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, v1))); assertEquals(true, acceptor.isAccepted(moveScope2)); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, v3))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, v4))); //Repeated calls for same move containing values which are not in tabuList should get accepted too. assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, v2))); //We accept move with v2, tabuList should contain v1 and v2 stepScope1.setStep(moveScope2.getMove()); acceptor.stepEnded(stepScope1); //3rd STEP: v1 & v2 in tabuList, acceptor should accept every move //except a move containing v1 and v2 LocalSearchStepScope stepScope2 = new LocalSearchStepScope(solverPhaseScope); stepScope2.setStepIndex(2); MoveScope moveScope4 = buildMoveScope(stepScope2, v4); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope2, v0))); //moves containing values which are in tabuList should not get accepted assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, v1))); //moves containing values which are in tabuList should not get accepted assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, v2))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope2, v3))); assertEquals(true, acceptor.isAccepted(moveScope4)); //Repeated calls for same move containing values which are in tabuList should not get accepted either assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, v2))); //We accept move with v4, tabuList should contain v2 and v4 //v1 should be removed from tabuList stepScope2.setStep(moveScope4.getMove()); acceptor.stepEnded(stepScope2); //4th STEP: v2 and v4 in tabuList, acceptor should accept every move //except a move containing v1 and v2 LocalSearchStepScope stepScope3 = new LocalSearchStepScope(solverPhaseScope); stepScope3.setStepIndex(3); MoveScope moveScope3 = buildMoveScope(stepScope3, v3); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope3, v0))); //v1 not in tabuList anymore, move should get accepted assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope3, v1))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, v2))); assertEquals(true, acceptor.isAccepted(moveScope3)); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, v4))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, v2))); //We accept move with v3, tabuList should contain v3 and v4 //v2 should be removed from tabuList stepScope3.setStep(moveScope3.getMove()); acceptor.stepEnded(stepScope3); //5th STEP: v4 and v3 in tabuList, acceptor should accept every move //except a move containing v1 and v2 LocalSearchStepScope stepScope4 = new LocalSearchStepScope(solverPhaseScope); stepScope4.setStepIndex(4); MoveScope moveScope1Again = buildMoveScope(stepScope4, v1); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope4, v0))); assertEquals(true, acceptor.isAccepted(moveScope1Again)); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope4, v2))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope4, v3))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope4, v4))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope4, v2))); //Value one gets accepted again stepScope4.setStep(moveScope1Again.getMove()); acceptor.stepEnded(stepScope4); acceptor.phaseEnded(solverPhaseScope); } @Test public void tabuSizeMultipleEntitiesPerStep() { PlanningValueTabuAcceptor acceptor = new PlanningValueTabuAcceptor(); acceptor.setTabuSize(2); acceptor.setAspirationEnabled(true); TestdataValue v0 = new TestdataValue("v0"); TestdataValue v1 = new TestdataValue("v1"); TestdataValue v2 = new TestdataValue("v2"); TestdataValue v3 = new TestdataValue("v3"); TestdataValue v4 = new TestdataValue("v4"); DefaultSolverScope solverScope = new DefaultSolverScope(); solverScope.setBestScore(new DefaultSimpleScore(0)); LocalSearchSolverPhaseScope solverPhaseScope = new LocalSearchSolverPhaseScope(solverScope); acceptor.phaseStarted(solverPhaseScope); //FIRST STEP: no values in tabuList, acceptor should accept everything. LocalSearchStepScope stepScope0 = new LocalSearchStepScope(solverPhaseScope); stepScope0.setStepIndex(0); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, v0))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, v1))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, v2))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, v3))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, v4))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, v0, v1))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, v0, v2))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, v0, v3))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, v0, v4))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, v1, v2))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, v1, v3))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, v1, v4))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, v2, v3))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, v2, v4))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, v3, v4))); stepScope0.setStep(buildMoveScope(stepScope0, v0, v2).getMove()); acceptor.stepEnded(stepScope0); //SECOND STEP: v0 and v2 in tabuList, acceptor should accept every move //except a move containing either v0 or v2 or both LocalSearchStepScope stepScope1 = new LocalSearchStepScope(solverPhaseScope); stepScope1.setStepIndex(1); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, v0))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, v1))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, v2))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, v3))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, v4))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, v0, v1))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, v0, v2))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, v0, v3))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, v0, v4))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, v1, v2))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, v1, v3))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, v1, v4))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, v2, v3))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, v2, v4))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, v3, v4))); stepScope1.setStep(buildMoveScope(stepScope1, v1).getMove()); acceptor.stepEnded(stepScope1); //THIRD STEP: v0, v2, v1 in tabuList, acceptor should accept every move //except a move containing either v0, v2, v1 or a combination of those LocalSearchStepScope stepScope2 = new LocalSearchStepScope(solverPhaseScope); stepScope2.setStepIndex(2); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, v0))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, v1))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, v2))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope2, v3))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope2, v4))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, v0, v1))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, v0, v2))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, v0, v3))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, v0, v4))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, v1, v2))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, v1, v3))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, v1, v4))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, v2, v3))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, v2, v4))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope2, v3, v4))); stepScope2.setStep(buildMoveScope(stepScope2, v3, v4).getMove()); acceptor.stepEnded(stepScope2); //4TH STEP: v3, v4, v1 in tabuList, acceptor should accept every move //except a move containing either v3, v4, v1 or a combination of those //v0 and v2 should've been released from the tabuList LocalSearchStepScope stepScope3 = new LocalSearchStepScope(solverPhaseScope); stepScope3.setStepIndex(3); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope3, v0))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, v1))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope3, v2))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, v3))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, v4))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, v0, v1))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope3, v0, v2))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, v0, v3))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, v0, v4))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, v1, v2))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, v1, v3))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, v1, v4))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, v2, v3))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, v2, v4))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, v3, v4))); stepScope3.setStep(buildMoveScope(stepScope3, v0).getMove()); acceptor.stepEnded(stepScope3); acceptor.phaseEnded(solverPhaseScope); } @Test public void aspiration() { PlanningValueTabuAcceptor acceptor = new PlanningValueTabuAcceptor(); acceptor.setTabuSize(2); //We want to accepted moves containing values from tabuList //if moves are better than best solution found (not working solution) acceptor.setAspirationEnabled(true); TestdataValue v0 = new TestdataValue("v0"); TestdataValue v1 = new TestdataValue("v1"); DefaultSolverScope solverScope = new DefaultSolverScope(); //We set best score to -100 solverScope.setBestScore(new DefaultSimpleScore(-100)); LocalSearchSolverPhaseScope solverPhaseScope = new LocalSearchSolverPhaseScope(solverScope); acceptor.phaseStarted(solverPhaseScope); //First step: we accept a move containing v1, so v1 should be added to //TabuList LocalSearchStepScope stepScope0 = new LocalSearchStepScope(solverPhaseScope); stepScope0.setStepIndex(0); stepScope0.setStep(buildMoveScope(stepScope0, v1).getMove()); acceptor.stepEnded(stepScope0); //Second step: tabuList contains v1 so any move containing v1 with a //resulting score less than the globally best known score (-100) should //get rejected. Otherwise the move will be accepted even though it //contains a tabu value LocalSearchStepScope stepScope2 = new LocalSearchStepScope(solverPhaseScope); stepScope2.setStepIndex(1); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope2, -120, v0))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope2, -20, v0))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, -120, v1))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope2, -20, v1))); assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, -120, v0, v1))); assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope2, -20, v0, v1))); stepScope2.setStep(buildMoveScope(stepScope2, -20, v1).getMove()); acceptor.stepEnded(stepScope2); acceptor.phaseEnded(solverPhaseScope); } private MoveScope buildMoveScope(LocalSearchStepScope stepScope, TestdataValue... values) { return buildMoveScope(stepScope, 0, values); } private MoveScope buildMoveScope(LocalSearchStepScope stepScope, int score, TestdataValue... values) { MoveScope moveScope = new MoveScope(stepScope); Move move = mock(Move.class); when(move.getPlanningValues()).thenReturn((Collection) Arrays.asList(values)); moveScope.setMove(move); moveScope.setScore(new DefaultSimpleScore(score)); return moveScope; } }
package org.vitrivr.cineast.standalone.util; import com.github.rvesse.airline.model.CommandMetadata; import com.github.rvesse.airline.parser.errors.ParseRestrictionViolatedException; import org.jline.builtins.Completers; import org.jline.reader.Completer; import org.jline.reader.EndOfFileException; import org.jline.reader.LineReader; import org.jline.reader.LineReaderBuilder; import org.jline.reader.impl.completer.AggregateCompleter; import org.jline.reader.impl.completer.StringsCompleter; import org.jline.terminal.Terminal; import org.jline.terminal.TerminalBuilder; import org.jline.utils.AttributedStringBuilder; import org.jline.utils.AttributedStyle; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * Helper class that can be used to start an interactive CLI. * * @author Ralph Gasser * @version 1.0 */ public class CLI { private static final String PROMPT = "cineast> "; private CLI() { } /** * Starts the interactive CLI. This is method will block. */ public static void start(Class<?> cliClass) { Terminal terminal = null; try { terminal = TerminalBuilder.terminal(); //basic terminal } catch (IOException e) { System.err.println("Could not initialize Terminal: "); System.err.println(e.getMessage()); System.err.println("Exiting..."); System.exit(-1); } final com.github.rvesse.airline.Cli<Runnable> cli = new com.github.rvesse.airline.Cli<>(cliClass); final List<String> commandNames = cli.getMetadata().getDefaultGroupCommands().stream() .map(CommandMetadata::getName).collect(Collectors.toList()); final Completer completer = new AggregateCompleter( new StringsCompleter("quit", "exit", "stop"), new StringsCompleter(commandNames), new Completers.FileNameCompleter() ); final LineReader lineReader = LineReaderBuilder.builder() .terminal(terminal) .completer(completer) .build(); terminal.writer().println("Welcome to the interactive Cineast CLI."); try { while (true) { final String line; /* Catch ^D end of file as exit method */ try { line = lineReader.readLine(PROMPT).trim(); } catch (EndOfFileException e) { break; } if (line.toLowerCase().equals("exit") || line.toLowerCase().equals("quit") || line.toLowerCase().equals("stop")) { break; } /* Try to parse user input. */ try { final Runnable command = cli.parse(CLI.splitLine(line)); command.run(); } catch (ParseRestrictionViolatedException e) { terminal.writer().println( new AttributedStringBuilder().style(AttributedStyle.DEFAULT.foreground(AttributedStyle.RED)) .append("Error: ").append(e.getMessage()).toAnsi() ); } catch (Exception e) { terminal.writer().println( new AttributedStringBuilder().style(AttributedStyle.DEFAULT.foreground(AttributedStyle.RED)) .append("Error: ").append(e.getMessage()).toAnsi() ); } } } catch (IllegalStateException | NoSuchElementException e) { System.out.println("System.in was closed; exiting"); } } final static Pattern lineSplitRegex = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'"); private static String[] splitLine(String line){ if (line == null || line.isEmpty()){ return new String[0]; } List<String> matchList = new ArrayList<String>(); Matcher regexMatcher = lineSplitRegex.matcher(line); while (regexMatcher.find()) { if (regexMatcher.group(1) != null) { // Add double-quoted string without the quotes matchList.add(regexMatcher.group(1)); } else if (regexMatcher.group(2) != null) { // Add single-quoted string without the quotes matchList.add(regexMatcher.group(2)); } else { // Add unquoted word matchList.add(regexMatcher.group()); } } return matchList.toArray(new String[matchList.size()]); } }
package ua.com.fielden.platform.swing.review.report.analysis.lifecycle; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Insets; import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import org.apache.log4j.xml.DOMConfigurator; import org.jfree.chart.ChartMouseEvent; import org.jfree.chart.ChartMouseListener; import org.jfree.chart.ChartRenderingInfo; import org.jfree.chart.JFreeChart; import org.jfree.chart.entity.ChartEntity; import org.jfree.chart.entity.XYItemEntity; import org.jfree.chart.plot.XYPlot; import org.jfree.data.gantt.TaskSeries; import org.jfree.data.gantt.TaskSeriesCollection; import org.jfree.ui.RefineryUtilities; import org.joda.time.DateTime; import ua.com.fielden.platform.application.AbstractUiApplication; import ua.com.fielden.platform.branding.SplashController; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.entity.Entity; import ua.com.fielden.platform.equery.lifecycle.EntityPropertyLifecycle; import ua.com.fielden.platform.equery.lifecycle.IGroup; import ua.com.fielden.platform.equery.lifecycle.IProperty; import ua.com.fielden.platform.equery.lifecycle.IProperty.ITimeProperty; import ua.com.fielden.platform.equery.lifecycle.IProperty.IValueProperty; import ua.com.fielden.platform.equery.lifecycle.LifecycleModel; import ua.com.fielden.platform.equery.lifecycle.LifecycleModelTest; import ua.com.fielden.platform.swing.categorychart.ChartPanel; import ua.com.fielden.platform.swing.utils.SimpleLauncher; import ua.com.fielden.platform.swing.utils.SwingUtilitiesEx; import ua.com.fielden.platform.swing.view.BaseFrame; import ua.com.fielden.platform.swing.view.IEntityMasterCache; import ua.com.fielden.platform.utils.EntityUtils; import ua.com.fielden.platform.utils.Pair; import com.jidesoft.plaf.LookAndFeelFactory; public class TimelineManagementControlExample extends AbstractUiApplication implements ChartMouseListener, MouseListener, MouseMotionListener { private LifecycleModel<Entity> chartEntryModel; private TaskSeriesCollection mainDataSet = new TaskSeriesCollection(); ChartPanel localChartPanel = null; boolean canMove = false; double finalMovePointY = 0; ChartRenderingInfo info = null;; double initialMovePointY = 0; JFreeChart jfreechart = null; // final TaskSeriesCollection mainDataSet = new TaskSeriesCollection(); // if (chartEntryModel != null) { // for (final EntityPropertyLifecycle<T> epl : chartEntryModel.getLifecycleData()) { // final TaskSeries taskSeries = new TaskSeries(epl.getInfo(true)); // for (final ValuedInterval vi : epl.getIntervals()) { // taskSeries.add(new ColoredTask("ColoredTask", new SimpleTimePeriod(vi.getFrom().toDate(), vi.getTo().toDate()), vi.getColor(), vi.getInfo())); // mainDataSet.add(taskSeries); XYItemEntity xyItemEntity = null; @Override protected void beforeUiExposure(final String[] args, final SplashController splashController) throws Throwable { SwingUtilitiesEx.installNimbusLnFifPossible(); com.jidesoft.utils.Lm.verifyLicense("Fielden Management Services", "Rollingstock Management System", "xBMpKdqs3vWTvP9gxUR4jfXKGNz9uq52"); LookAndFeelFactory.installJideExtension(); chartEntryModel = createLifecycleModel(); mainDataSet = LifecycleChartFactory.createMainDataSet(chartEntryModel); super.beforeUiExposure(args, splashController); } private TaskSeries localTaskSeries() { return mainDataSet.getSeries(0); // TODO take an appropriate series } /** * Creates testing lifecycle model. * * @return */ private static LifecycleModel<Entity> createLifecycleModel() { final LifecycleModelTest lmt = new LifecycleModelTest(); final List<EntityPropertyLifecycle<Entity>> ld = new ArrayList<EntityPropertyLifecycle<Entity>>(); ld.add(lmt.createEPL("A0001", 0)); ld.add(lmt.createEPL("A0002", 5)); // the same lifecycle just shifted to the right on 5 millis. ld.add(lmt.createEPL("A0003", -2)); ld.add(lmt.createEPL("A0004", 2)); ld.add(lmt.createEPL("A0005", 1)); ld.add(lmt.createEPL("A0006", -1)); ld.add(lmt.createUnavailableEPL("A0007")); final LifecycleModel<Entity> lm = new LifecycleModel<Entity>(lmt.date(15), lmt.date(55), ld, new LinkedHashMap<IProperty, Object>(), true){ @Override protected IGroup<Entity> createGroupByValue(final IValueProperty property, final Object value, final LifecycleModel<Entity> parent, final List<Integer> indexes) { return null; } @Override protected IGroup<Entity> createGroupByModelAndPeriod(final ITimeProperty timeProperty, final LifecycleModel<Entity> narrowedModel, final LifecycleModel<Entity> parent) { return null; } @Override public Pair<? extends LifecycleModel<Entity>, ? extends LifecycleModel<Entity>> split(final DateTime moment, final boolean copy, final boolean full) { return null; } @Override protected LifecycleModel<Entity> copy(final LinkedHashMap<IProperty, Object> extractedGroupingValues) { return null; } }; return lm; } @Override protected void exposeUi(final String[] args, final SplashController splashController) throws Throwable { final BaseFrame mainApplicationFrame = new BaseFrame("Timeline management control example", new HashMap<Class<? extends AbstractEntity<?>>, IEntityMasterCache>()); final JFreeChart chart = LifecycleChartFactory.createAvailabilityChart(chartEntryModel, mainDataSet); // final ChartPanel localChartPanel = new ChartPanel(chart); // localChartPanel.addChartMouseListener(this); // localChartPanel.addMouseMotionListener(this); // localChartPanel.addMouseListener(this); jfreechart = chart; // ChartFactory.createTimeSeriesChart("Series & Point Dragging Demo", "Date", "Price Per Unit", createDataset(), true, true, false); localChartPanel = new ChartPanel(jfreechart); localChartPanel.addChartMouseListener(this); localChartPanel.addMouseMotionListener(this); localChartPanel.addMouseListener(this); localChartPanel.setPreferredSize(new Dimension(750, 500)); localChartPanel.setAutoscrolls(false); // localChartPanel.setMouseZoomable(false); localChartPanel.setMouseWheelEnabled(true); this.info = localChartPanel.getChartRenderingInfo(); /* final XYPlot localXYPlot = (XYPlot) jfreechart.getPlot(); final XYItemRenderer localXYItemRenderer = localXYPlot.getRenderer(); localXYItemRenderer.setSeriesStroke(0, new BasicStroke(2.0F)); final XYLineAndShapeRenderer localXYLineAndShapeRenderer = (XYLineAndShapeRenderer) localXYPlot.getRenderer(); localXYLineAndShapeRenderer.setBaseShapesVisible(true); localXYLineAndShapeRenderer.setSeriesFillPaint(0, Color.white); localXYLineAndShapeRenderer.setUseFillPaint(true); localXYLineAndShapeRenderer.setLegendItemToolTipGenerator(new StandardXYSeriesLabelGenerator("Tooltip {0}")); final ValueAxis range = localXYPlot.getRangeAxis(); range.setLowerBound(0); // set lower limit so that can't move in -ve // range range.setUpperBound(10000); // set upper limit as per app. needs */ // final ChartPanel chartPanel = new ChartPanel(chart) { // private static final long serialVersionUID = -4977378293075789317L; // @Override // public void mouseDragged(final MouseEvent mouseEvent) { // super.mouseDragged(mouseEvent); // /*Insets insets = getInsets(); // int x = (int) ((event.getX() - insets.left) / this.scaleX); // int y = (int) ((event.getY() - insets.top) / this.scaleY); // // this.anchor = new Point2D.Double(x, y); // ChartEntity entity = null; // if (this.info != null) { // EntityCollection entities = this.info.getEntityCollection(); // if (entities != null) { // entity = entities.getEntity(x, y); // } // }*/ // chartPanel.addChartMouseListener(new ChartMouseListener() { // @Override // public void chartMouseClicked(final ChartMouseEvent event) { // if (event.getTrigger().isControlDown() && /*event.getTrigger().getClickCount() == 2 && */ !event.getTrigger().isConsumed()) { // performCustomAction(new AnalysisDataEvent<>(mainApplicationFrame, event /*chartMouseEvent*/)); // //if (event.getTrigger().getClickCount() == 2 && !event.getTrigger().isConsumed()) { // // event.getTrigger().consume(); // // mouseDoubleClicked(event); // //} else if (event.getTrigger().getClickCount() == 1) { // // event.getTrigger().consume(); // // if (getChart().getPlot() instanceof CategoryPlot) { // // final CategoryPlot plot = getChart().getCategoryPlot(); // // final CategoryItemRenderer renderer = plot.getRenderer(); // // labelVisible = !labelVisible; // // renderer.setBaseItemLabelsVisible(labelVisible); // @Override // public void chartMouseMoved(final ChartMouseEvent event) { // // ignored for now mainApplicationFrame.setPreferredSize(new Dimension(1280, 800)); mainApplicationFrame.add(localChartPanel); mainApplicationFrame.pack(); RefineryUtilities.centerFrameOnScreen(mainApplicationFrame); SimpleLauncher.show("Timeline management control example", mainApplicationFrame, null); } // protected void performCustomAction(final AnalysisDataEvent<ChartMouseEvent> clickedData) { // final ChartEntity entity = clickedData.getData().getEntity(); // System.err.println("CTRL + " + entity); // if (entity instanceof CategoryItemEntity) { // createDoubleClickAction(createChoosenItem(((CategoryItemEntity) entity).getColumnKey())).actionPerformed(null); // } else if (entity instanceof CategoryLabelEntity) { // createDoubleClickAction(createChoosenItem(((CategoryLabelEntity) entity).getKey())).actionPerformed(null); // private Pair<String, Object> createChoosenItem(final Comparable<?> columnKey) { // final EntityWrapper entityWrapper = (EntityWrapper) columnKey; // final List<String> categories = getModel().getChartAnalysisDataProvider().categoryProperties(); // if(categories.size() == 1){ // return new Pair<String, Object>(categories.get(0), entityWrapper.getEntity()); // return null; public static void main(final String[] args) { DOMConfigurator.configure("src/main/resources/log4j.xml"); new TimelineManagementControlExample().launch(args); } public void chartMouseClicked(final ChartMouseEvent paramChartMouseEvent) { } public void chartMouseMoved(final ChartMouseEvent paramChartMouseEvent) { } /* public XYDataset createDataset() { localTimeSeries.add(new Month(1, 2002), 500.19999999999999D); localTimeSeries.add(new Month(2, 2002), 694.10000000000002D); localTimeSeries.add(new Month(3, 2002), 734.39999999999998D); localTimeSeries.add(new Month(4, 2002), 453.19999999999999D); localTimeSeries.add(new Month(5, 2002), 200.19999999999999D); localTimeSeries.add(new Month(6, 2002), 345.60000000000002D); localTimeSeries.add(new Month(7, 2002), 500.19999999999999D); localTimeSeries.add(new Month(8, 2002), 694.10000000000002D); localTimeSeries.add(new Month(9, 2002), 734.39999999999998D); localTimeSeries.add(new Month(10, 2002), 453.19999999999999D); localTimeSeries.add(new Month(11, 2002), 500.19999999999999D); localTimeSeries.add(new Month(12, 2002), 345.60000000000002D); timeseriescollection.addSeries(localTimeSeries); return timeseriescollection; }*/ public void mouseClicked(final MouseEvent e) { } public void mouseDragged(final MouseEvent e) { // at a time use one of them. // moveTimeSeries(e); // comment or uncomment to enable or disable series // movement movePoint(e); // comment or uncomment to enable or disable selected // point movement } public void mouseEntered(final MouseEvent e) { } public void mouseExited(final MouseEvent e) { canMove = false; // stop movement if cursor is moved out from the chart // area initialMovePointY = 0; localChartPanel.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } private XYItemEntity determineAnItemUnderACursor(final ChartPanel chartPanel, final int x0, final int y0) { final Insets insets = chartPanel.getInsets(); final int x = (int) ((x0 - insets.left) / chartPanel.getScaleX()); final int y = (int) ((y0 - insets.top) / chartPanel.getScaleY()); final ChartEntity entity = this.info.getEntityCollection().getEntity(x, y); if ((entity != null) && (entity instanceof XYItemEntity)) { return (XYItemEntity) entity; } else { return null; } } public void mouseMoved(final MouseEvent e) { final XYItemEntity newItemEntity = determineAnItemUnderACursor((ChartPanel) e.getSource(), e.getX(), e.getY()); if (!EntityUtils.equalsEx(newItemEntity, xyItemEntity)) { xyItemEntity = newItemEntity; System.err.println(" xyItemEntity has been changed to == " + xyItemEntity); } provideCursor(e, false); } public void provideCursor(final MouseEvent e, final boolean pressed) { final int gap = 3; if (xyItemEntity == null) { localChartPanel.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } else if (!EntityUtils.equalsEx(xyItemEntity, determineAnItemUnderACursor((ChartPanel) e.getSource(), e.getX() - gap, e.getY()))) { // the left boundary of xyItemEntity has been found localChartPanel.setCursor(new Cursor(Cursor.W_RESIZE_CURSOR)); } else if (!EntityUtils.equalsEx(xyItemEntity, determineAnItemUnderACursor((ChartPanel) e.getSource(), e.getX() + gap, e.getY()))) { // the right boundary of xyItemEntity has been found localChartPanel.setCursor(new Cursor(Cursor.E_RESIZE_CURSOR)); } else { localChartPanel.setCursor(pressed ? new Cursor(Cursor.MOVE_CURSOR) : new Cursor(Cursor.HAND_CURSOR)); } } public void mousePressed(final MouseEvent e) { // final int x = e.getX(); // initialized point whenenver mouse is pressed // final int y = e.getY(); final ChartPanel chartPanel = (ChartPanel) e.getSource(); final Insets insets = chartPanel.getInsets(); final int x = (int) ((e.getX() - insets.left) / chartPanel.getScaleX()); final int y = (int) ((e.getY() - insets.top) / chartPanel.getScaleY()); // this.anchor = new Point2D.Double(x, y); // ChartEntity entity = null; // if (this.info != null) { // final EntityCollection entities = this.info.getEntityCollection(); // if (entities != null) { // entity = entities.getEntity(x, y); // final EntityCollection entities = this.info.getEntityCollection(); // final ChartMouseEvent cme = new ChartMouseEvent(jfreechart, e, entities // .getEntity(x, y)); // final ChartEntity entity = cme.getEntity(); // if ((entity != null) && (entity instanceof XYItemEntity)) { // xyItemEntity = (XYItemEntity) entity; // } else if (!(entity instanceof XYItemEntity)) { // xyItemEntity = null; // return; // if (xyItemEntity == null) { // return; // return if not pressed on any series point // System.err.println(" xyItemEntity == " + xyItemEntity); final Point pt = e.getPoint(); final XYPlot xy = jfreechart.getXYPlot(); final Rectangle2D dataArea = localChartPanel.getChartRenderingInfo() .getPlotInfo().getDataArea(); final Point2D p = localChartPanel.translateScreenToJava2D(pt); initialMovePointY = xy.getRangeAxis().java2DToValue(p.getY(), dataArea, xy.getRangeAxisEdge()); canMove = true; provideCursor(e, true); // localChartPanel.setCursor(new Cursor(Cursor.MOVE_CURSOR)); } public void mouseReleased(final MouseEvent e) { // stop dragging on mouse released canMove = false; initialMovePointY = 0; provideCursor(e, false); } public void movePoint(final MouseEvent me) { // try { // if (canMove) { // final int itemIndex = xyItemEntity.getItem(); // final Point pt = me.getPoint(); // final XYPlot xy = jfreechart.getXYPlot(); // final Rectangle2D dataArea = localChartPanel.getChartRenderingInfo() // .getPlotInfo().getDataArea(); // final Point2D p = localChartPanel.translateScreenToJava2D(pt); // finalMovePointY = xy.getRangeAxis().java2DToValue(p.getY(), // dataArea, xy.getRangeAxisEdge()); // final double difference = finalMovePointY - initialMovePointY; // if (localTaskSeries().getValue(itemIndex).doubleValue() // + difference > xy.getRangeAxis().getRange().getLength() // || localTaskSeries().getValue(itemIndex).doubleValue() // + difference < 0.0D) { // initialMovePointY = finalMovePointY; // // retrict movement for upper and lower limit (upper limit // // should be as per application needs) // final double targetPoint = localTaskSeries().getValue(itemIndex) // .doubleValue() // + difference; // if (targetPoint > 10000 || targetPoint < 0) { // return; // } else // localTaskSeries().update(itemIndex, targetPoint); // jfreechart.fireChartChanged(); // localChartPanel.updateUI(); // initialMovePointY = finalMovePointY; // } catch (final Exception e) { // e.printStackTrace(); // System.out.println(e); } // public void moveTimeSeries(final MouseEvent me) { // try { // if (canMove) { // final Point pt = me.getPoint(); // final XYPlot xy = jfreechart.getXYPlot(); // final Rectangle2D dataArea = localChartPanel.getChartRenderingInfo() // .getPlotInfo().getDataArea(); // final Point2D p = localChartPanel.translateScreenToJava2D(pt); // finalMovePointY = xy.getRangeAxis().java2DToValue(p.getY(), // dataArea, xy.getRangeAxisEdge()); // final double difference = finalMovePointY - initialMovePointY; // for (int i = 0; i < localTaskSeries().getItemCount(); i++) { // if (localTaskSeries().getValue(i).doubleValue() + difference > xy // .getRangeAxis().getRange().getLength() // || localTaskSeries().getValue(i).doubleValue() // + difference < 0.0D) { // initialMovePointY = finalMovePointY; // // retrict movement for upper and lower limit (upper limit // // should be as per application needs) // for (int i = 0; i < localTaskSeries().getItemCount(); i++) { // final double targetPoint = localTaskSeries().getValue(i) // .doubleValue() // + difference; // if (targetPoint > 10000 || targetPoint < 0) { // return; // for (int i = 0; i < localTaskSeries().getItemCount(); i++) { // final double targetPoint = localTaskSeries().getValue(i) // .doubleValue() // + difference; // localTaskSeries().update(i, targetPoint); // jfreechart.fireChartChanged(); // localChartPanel.updateUI(); // initialMovePointY = finalMovePointY; // } catch (final Exception e) { // System.out.println(e); }
package info.evanchik.eclipse.karaf.workbench; import info.evanchik.eclipse.karaf.core.LogWrapper; import info.evanchik.eclipse.karaf.ui.KarafUIPluginActivator; import info.evanchik.eclipse.karaf.workbench.internal.MBeanProviderManager; import info.evanchik.eclipse.karaf.workbench.internal.RuntimeDataProviderManager; import info.evanchik.eclipse.karaf.workbench.internal.eclipse.EclipseRuntimeDataProvider; import info.evanchik.eclipse.karaf.workbench.jmx.IJMXTransportRegistry; import info.evanchik.eclipse.karaf.workbench.jmx.JMXServiceDescriptor; import info.evanchik.eclipse.karaf.workbench.jmx.internal.JMXServiceManager; import info.evanchik.eclipse.karaf.workbench.jmx.internal.JMXTransportRegistry; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; /** * The activator class controls the plug-in life cycle */ public class KarafWorkbenchActivator extends AbstractUIPlugin { // The plug-in ID public static final String PLUGIN_ID = "info.evanchik.eclipse.karaf.workbench"; public static final String JMX_CONNECTOR_PROVIDER_EXTENSION_ID = "jmxConnectorProvider"; public static final String BUNDLE_OBJ_IMG = "bundle_obj"; //$NON-NLS-1$ public static final String LOGO_16X16_IMG = "logo16"; //$NON-NLS-1$ public static final String SERVICE_IMG = "service"; private EclipseRuntimeDataProvider eclipseWorkbenchDataProvider; private JMXServiceManager jmxServiceManager; private JMXTransportRegistry jmxTransportRegistry; private MBeanProviderManager mbeanProviderManager; private RuntimeDataProviderManager runtimeDataProviderManager; private static KarafWorkbenchActivator plugin; /** * Returns the shared instance * * @return the shared instance */ public static KarafWorkbenchActivator getDefault() { return plugin; } /** * Getter for the {@link LogWrapper} object that makes logging much easier * on the caller. * * @return the {@link LogWrapper} instance */ public static LogWrapper getLogger() { return new LogWrapper(getDefault().getLog(), PLUGIN_ID); } /** * The constructor */ public KarafWorkbenchActivator() { } /** * * @return */ public EclipseRuntimeDataProvider getEclipseWorkbenchDataProvider() { return eclipseWorkbenchDataProvider; } /** * Getter for the {@link WorkbenchServiceManager<JMXServiceDescriptor>} * implementation. There is only one per plugin instance. * * @return the {@code WorkbenchServiceManager<JMXServiceDescriptor>} * instance */ public WorkbenchServiceManager<JMXServiceDescriptor> getJMXServiceManager() { return jmxServiceManager; } /** * Getter for the {@link IJMXTransportRegistry} implementation. There is * only on per plugin instance. * * @return the {@link IJMXTransportRegistry} instance */ public IJMXTransportRegistry getJMXTransportRegistry() { return jmxTransportRegistry; } /** * * @return */ public WorkbenchServiceManager<MBeanProvider> getMBeanProviderManager() { return mbeanProviderManager; } public RuntimeDataProviderManager getRuntimeDataProviderManager() { return runtimeDataProviderManager; } @Override public void start(final BundleContext context) throws Exception { super.start(context); plugin = this; jmxServiceManager = new JMXServiceManager(); jmxTransportRegistry = new JMXTransportRegistry(); mbeanProviderManager = new MBeanProviderManager(); runtimeDataProviderManager = new RuntimeDataProviderManager(); eclipseWorkbenchDataProvider = new EclipseRuntimeDataProvider(getBundle().getBundleContext()); registerEclipseRuntimeDataProvider(); } @Override public void stop(final BundleContext context) throws Exception { plugin = null; super.stop(context); runtimeDataProviderManager.remove(eclipseWorkbenchDataProvider); jmxServiceManager = null; jmxTransportRegistry = null; mbeanProviderManager = null; runtimeDataProviderManager = null; eclipseWorkbenchDataProvider = null; } /** * Creates the {@link ImageRegistery} for this plugin. Images can be * retrieved using the static accessor method * {@link KarafUIPluginActivator#getImageDescriptor(String)} * * @see org.eclipse.ui.plugin.AbstractUIPlugin#createImageRegistry() */ @Override protected void initializeImageRegistry(final ImageRegistry imageRegistry) { registerImage(imageRegistry, BUNDLE_OBJ_IMG, "icons/obj16/bundle_obj.gif"); registerImage(imageRegistry, LOGO_16X16_IMG, "icons/obj16/felixLogo16x16.gif"); registerImage(imageRegistry, "logo32", "icons/obj32/felixLogo32x32.gif"); registerImage(imageRegistry, "logo64", "icons/obj64/felixLogo64x64.gif"); registerImage(imageRegistry, SERVICE_IMG, "icons/obj16/generic_element.gif"); } private void registerEclipseRuntimeDataProvider() { eclipseWorkbenchDataProvider.start(); runtimeDataProviderManager.add(eclipseWorkbenchDataProvider); } /** * Registers an {@link ImageDescriptor} with the {@link ImageRegistry} * * @param registry * the instance of {@link ImageRegistry} * @param key * the key to register the image under * @param imageUrl * the URL of the image to be registered */ private void registerImage(final ImageRegistry registry, final String key, final String imageUrl) { final ImageDescriptor id = imageDescriptorFromPlugin(PLUGIN_ID, imageUrl); registry.put(key, id); } }
package org.asynchttpclient.netty.channel; import static org.asynchttpclient.util.MiscUtils.trimStackTrace; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.group.ChannelGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.oio.OioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http.HttpContentDecompressor; import io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder; import io.netty.handler.codec.http.websocketx.WebSocket08FrameEncoder; import io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator; import io.netty.handler.ssl.SslHandler; import io.netty.handler.stream.ChunkedWriteHandler; import io.netty.util.Timer; import io.netty.util.concurrent.DefaultThreadFactory; import io.netty.util.concurrent.GenericFutureListener; import java.io.IOException; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; import org.asynchttpclient.AsyncHandler; import org.asynchttpclient.AsyncHttpClientConfig; import org.asynchttpclient.SslEngineFactory; import org.asynchttpclient.channel.pool.ConnectionPoolPartitioning; import org.asynchttpclient.handler.AsyncHandlerExtensions; import org.asynchttpclient.netty.Callback; import org.asynchttpclient.netty.NettyResponseFuture; import org.asynchttpclient.netty.channel.exception.PoolAlreadyClosedException; import org.asynchttpclient.netty.channel.exception.TooManyConnectionsException; import org.asynchttpclient.netty.channel.exception.TooManyConnectionsPerHostException; import org.asynchttpclient.netty.channel.pool.ChannelPool; import org.asynchttpclient.netty.channel.pool.DefaultChannelPool; import org.asynchttpclient.netty.channel.pool.NoopChannelPool; import org.asynchttpclient.netty.handler.AsyncHttpClientHandler; import org.asynchttpclient.netty.handler.HttpProtocol; import org.asynchttpclient.netty.handler.WebSocketProtocol; import org.asynchttpclient.netty.request.NettyRequestSender; import org.asynchttpclient.netty.ssl.DefaultSslEngineFactory; import org.asynchttpclient.proxy.ProxyServer; import org.asynchttpclient.uri.Uri; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ChannelManager { private static final Logger LOGGER = LoggerFactory.getLogger(ChannelManager.class); public static final String PINNED_ENTRY = "entry"; public static final String HTTP_CLIENT_CODEC = "http"; public static final String SSL_HANDLER = "ssl"; public static final String DEFLATER_HANDLER = "deflater"; public static final String INFLATER_HANDLER = "inflater"; public static final String CHUNKED_WRITER_HANDLER = "chunked-writer"; public static final String WS_DECODER_HANDLER = "ws-decoder"; public static final String WS_FRAME_AGGREGATOR = "ws-aggregator"; public static final String WS_ENCODER_HANDLER = "ws-encoder"; public static final String AHC_HTTP_HANDLER = "ahc-http"; public static final String AHC_WS_HANDLER = "ahc-ws"; private final AsyncHttpClientConfig config; private final SslEngineFactory sslEngineFactory; private final EventLoopGroup eventLoopGroup; private final boolean allowReleaseEventLoopGroup; private final Class<? extends Channel> socketChannelClass; private final Bootstrap httpBootstrap; private final Bootstrap wsBootstrap; private final long handshakeTimeout; private final IOException tooManyConnections; private final IOException tooManyConnectionsPerHost; private final ChannelPool channelPool; private final boolean maxTotalConnectionsEnabled; private final Semaphore freeChannels; private final ChannelGroup openChannels; private final boolean maxConnectionsPerHostEnabled; private final ConcurrentHashMap<Object, Semaphore> freeChannelsPerHost = new ConcurrentHashMap<>(); private final ConcurrentHashMap<Channel, Object> channelId2PartitionKey = new ConcurrentHashMap<>(); private AsyncHttpClientHandler wsHandler; public ChannelManager(final AsyncHttpClientConfig config, Timer nettyTimer) { this.config = config; try { this.sslEngineFactory = config.getSslEngineFactory() != null ? config.getSslEngineFactory() : new DefaultSslEngineFactory(config); } catch (SSLException e) { throw new ExceptionInInitializerError(e); } ChannelPool channelPool = config.getChannelPool(); if (channelPool == null) { if (config.isKeepAlive()) { channelPool = new DefaultChannelPool(config, nettyTimer); } else { channelPool = NoopChannelPool.INSTANCE; } } this.channelPool = channelPool; tooManyConnections = trimStackTrace(new TooManyConnectionsException(config.getMaxConnections())); tooManyConnectionsPerHost = trimStackTrace(new TooManyConnectionsPerHostException(config.getMaxConnectionsPerHost())); maxTotalConnectionsEnabled = config.getMaxConnections() > 0; maxConnectionsPerHostEnabled = config.getMaxConnectionsPerHost() > 0; if (maxTotalConnectionsEnabled || maxConnectionsPerHostEnabled) { openChannels = new CleanupChannelGroup("asyncHttpClient") { @Override public boolean remove(Object o) { boolean removed = super.remove(o); if (removed) { if (maxTotalConnectionsEnabled) freeChannels.release(); if (maxConnectionsPerHostEnabled) { Object partitionKey = channelId2PartitionKey.remove(Channel.class.cast(o)); if (partitionKey != null) { Semaphore hostFreeChannels = freeChannelsPerHost.get(partitionKey); if (hostFreeChannels != null) hostFreeChannels.release(); } } } return removed; } }; freeChannels = new Semaphore(config.getMaxConnections()); } else { openChannels = new CleanupChannelGroup("asyncHttpClient"); freeChannels = null; } handshakeTimeout = config.getHandshakeTimeout(); // check if external EventLoopGroup is defined ThreadFactory threadFactory = config.getThreadFactory() != null ? config.getThreadFactory() : new DefaultThreadFactory(config.getThreadPoolName()); allowReleaseEventLoopGroup = config.getEventLoopGroup() == null; if (allowReleaseEventLoopGroup) { if (config.isUseNativeTransport()) { eventLoopGroup = newEpollEventLoopGroup(threadFactory); socketChannelClass = getEpollSocketChannelClass(); } else { eventLoopGroup = new NioEventLoopGroup(0, threadFactory); socketChannelClass = NioSocketChannel.class; } } else { eventLoopGroup = config.getEventLoopGroup(); if (eventLoopGroup instanceof OioEventLoopGroup) throw new IllegalArgumentException("Oio is not supported"); if (eventLoopGroup instanceof NioEventLoopGroup) { socketChannelClass = NioSocketChannel.class; } else { socketChannelClass = getEpollSocketChannelClass(); } } httpBootstrap = new Bootstrap().channel(socketChannelClass).group(eventLoopGroup); wsBootstrap = new Bootstrap().channel(socketChannelClass).group(eventLoopGroup); // default to PooledByteBufAllocator httpBootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); wsBootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); if (config.getConnectTimeout() > 0) { httpBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout()); wsBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout()); } for (Entry<ChannelOption<Object>, Object> entry : config.getChannelOptions().entrySet()) { ChannelOption<Object> key = entry.getKey(); Object value = entry.getValue(); httpBootstrap.option(key, value); wsBootstrap.option(key, value); } } private EventLoopGroup newEpollEventLoopGroup(ThreadFactory threadFactory) { try { Class<?> epollEventLoopGroupClass = Class.forName("io.netty.channel.epoll.EpollEventLoopGroup"); return (EventLoopGroup) epollEventLoopGroupClass.getConstructor(int.class, ThreadFactory.class).newInstance(0, threadFactory); } catch (Exception e) { throw new IllegalArgumentException(e); } } @SuppressWarnings("unchecked") private Class<? extends Channel> getEpollSocketChannelClass() { try { return (Class<? extends Channel>) Class.forName("io.netty.channel.epoll.EpollSocketChannel"); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(e); } } public void configureBootstraps(NettyRequestSender requestSender) { HttpProtocol httpProtocol = new HttpProtocol(this, config, requestSender); final AsyncHttpClientHandler httpHandler = new AsyncHttpClientHandler(config, this, requestSender, httpProtocol); WebSocketProtocol wsProtocol = new WebSocketProtocol(this, config, requestSender); wsHandler = new AsyncHttpClientHandler(config, this, requestSender, wsProtocol); final NoopHandler pinnedEntry = new NoopHandler(); httpBootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline() .addLast(PINNED_ENTRY, pinnedEntry) .addLast(HTTP_CLIENT_CODEC, newHttpClientCodec()) .addLast(INFLATER_HANDLER, newHttpContentDecompressor()) .addLast(CHUNKED_WRITER_HANDLER, new ChunkedWriteHandler()) .addLast(AHC_HTTP_HANDLER, httpHandler); ch.config().setOption(ChannelOption.AUTO_READ, false); if (config.getHttpAdditionalChannelInitializer() != null) config.getHttpAdditionalChannelInitializer().initChannel(ch); } }); wsBootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline() .addLast(PINNED_ENTRY, pinnedEntry) .addLast(HTTP_CLIENT_CODEC, newHttpClientCodec()) .addLast(AHC_WS_HANDLER, wsHandler); if (config.getWsAdditionalChannelInitializer() != null) config.getWsAdditionalChannelInitializer().initChannel(ch); } }); } private HttpContentDecompressor newHttpContentDecompressor() { if (config.isKeepEncodingHeader()) return new HttpContentDecompressor() { @Override protected String getTargetContentEncoding(String contentEncoding) throws Exception { return contentEncoding; } }; else return new HttpContentDecompressor(); } public final void tryToOfferChannelToPool(Channel channel, AsyncHandler<?> asyncHandler, boolean keepAlive, Object partitionKey) { if (channel.isActive() && keepAlive) { LOGGER.debug("Adding key: {} for channel {}", partitionKey, channel); Channels.setDiscard(channel); if (asyncHandler instanceof AsyncHandlerExtensions) AsyncHandlerExtensions.class.cast(asyncHandler).onConnectionOffer(channel); channelPool.offer(channel, partitionKey); if (maxConnectionsPerHostEnabled) channelId2PartitionKey.putIfAbsent(channel, partitionKey); } else { // not offered closeChannel(channel); } } public Channel poll(Uri uri, String virtualHost, ProxyServer proxy, ConnectionPoolPartitioning connectionPoolPartitioning) { Object partitionKey = connectionPoolPartitioning.getPartitionKey(uri, virtualHost, proxy); return channelPool.poll(partitionKey); } public boolean removeAll(Channel connection) { return channelPool.removeAll(connection); } private boolean tryAcquireGlobal() { return !maxTotalConnectionsEnabled || freeChannels.tryAcquire(); } private Semaphore getFreeConnectionsForHost(Object partitionKey) { return freeChannelsPerHost.computeIfAbsent(partitionKey, pk -> new Semaphore(config.getMaxConnectionsPerHost())); } private boolean tryAcquirePerHost(Object partitionKey) { return !maxConnectionsPerHostEnabled || getFreeConnectionsForHost(partitionKey).tryAcquire(); } public void preemptChannel(Object partitionKey) throws IOException { if (!channelPool.isOpen()) throw PoolAlreadyClosedException.INSTANCE; if (!tryAcquireGlobal()) throw tooManyConnections; if (!tryAcquirePerHost(partitionKey)) { if (maxTotalConnectionsEnabled) freeChannels.release(); throw tooManyConnectionsPerHost; } } private void doClose() { channelPool.destroy(); openChannels.close(); for (Channel channel : openChannels) { Object attribute = Channels.getAttribute(channel); if (attribute instanceof NettyResponseFuture<?>) { NettyResponseFuture<?> nettyFuture = (NettyResponseFuture<?>) attribute; nettyFuture.cancelTimeouts(); } } } @SuppressWarnings({ "unchecked", "rawtypes" }) public void close() { if (allowReleaseEventLoopGroup) { io.netty.util.concurrent.Future whenEventLoopGroupClosed = eventLoopGroup.shutdownGracefully(config.getShutdownQuietPeriod(), config.getShutdownTimeout(), TimeUnit.MILLISECONDS); whenEventLoopGroupClosed.addListener((GenericFutureListener<?>) new GenericFutureListener<io.netty.util.concurrent.Future<?>>() { public void operationComplete(io.netty.util.concurrent.Future<?> future) throws Exception { doClose(); }; }); } else doClose(); } public void closeChannel(Channel channel) { LOGGER.debug("Closing Channel {} ", channel); Channels.setDiscard(channel); removeAll(channel); Channels.silentlyCloseChannel(channel); openChannels.remove(channel); } public void abortChannelPreemption(Object partitionKey) { if (maxTotalConnectionsEnabled) freeChannels.release(); if (maxConnectionsPerHostEnabled) getFreeConnectionsForHost(partitionKey).release(); } public void registerOpenChannel(Channel channel, Object partitionKey) { openChannels.add(channel); if (maxConnectionsPerHostEnabled) { channelId2PartitionKey.put(channel, partitionKey); } } private HttpClientCodec newHttpClientCodec() { return new HttpClientCodec( config.getHttpClientCodecMaxInitialLineLength(), config.getHttpClientCodecMaxHeaderSize(), config.getHttpClientCodecMaxChunkSize(), false); } private SslHandler createSslHandler(String peerHost, int peerPort) { SSLEngine sslEngine = sslEngineFactory.newSslEngine(config, peerHost, peerPort); SslHandler sslHandler = new SslHandler(sslEngine); if (handshakeTimeout > 0) sslHandler.setHandshakeTimeoutMillis(handshakeTimeout); return sslHandler; } public static boolean isSslHandlerConfigured(ChannelPipeline pipeline) { return pipeline.get(SSL_HANDLER) != null; } public void upgradeProtocol(ChannelPipeline pipeline, Uri requestUri) throws SSLException { if (pipeline.get(HTTP_CLIENT_CODEC) != null) pipeline.remove(HTTP_CLIENT_CODEC); if (requestUri.isSecured()) if (isSslHandlerConfigured(pipeline)) { pipeline.addAfter(SSL_HANDLER, HTTP_CLIENT_CODEC, newHttpClientCodec()); } else { pipeline.addAfter(PINNED_ENTRY, HTTP_CLIENT_CODEC, newHttpClientCodec()); pipeline.addAfter(PINNED_ENTRY, SSL_HANDLER, createSslHandler(requestUri.getHost(), requestUri.getExplicitPort())); } else pipeline.addAfter(PINNED_ENTRY, HTTP_CLIENT_CODEC, newHttpClientCodec()); if (requestUri.isWebSocket()) { pipeline.addAfter(AHC_HTTP_HANDLER, AHC_WS_HANDLER, wsHandler); pipeline.remove(AHC_HTTP_HANDLER); } } public SslHandler addSslHandler(ChannelPipeline pipeline, Uri uri, String virtualHost) { String peerHost; int peerPort; if (virtualHost != null) { int i = virtualHost.indexOf(':'); if (i == -1) { peerHost = virtualHost; peerPort = uri.getSchemeDefaultPort(); } else { peerHost = virtualHost.substring(0, i); peerPort = Integer.valueOf(virtualHost.substring(i + 1)); } } else { peerHost = uri.getHost(); peerPort = uri.getExplicitPort(); } SslHandler sslHandler = createSslHandler(peerHost, peerPort); pipeline.addFirst(ChannelManager.SSL_HANDLER, sslHandler); return sslHandler; } public Bootstrap getBootstrap(Uri uri, ProxyServer proxy) { return uri.isWebSocket() && proxy == null ? wsBootstrap : httpBootstrap; } public void upgradePipelineForWebSockets(ChannelPipeline pipeline) { pipeline.addAfter(HTTP_CLIENT_CODEC, WS_ENCODER_HANDLER, new WebSocket08FrameEncoder(true)); pipeline.remove(HTTP_CLIENT_CODEC); pipeline.addBefore(AHC_WS_HANDLER, WS_DECODER_HANDLER, new WebSocket08FrameDecoder(false, false, config.getWebSocketMaxFrameSize())); pipeline.addAfter(WS_DECODER_HANDLER, WS_FRAME_AGGREGATOR, new WebSocketFrameAggregator(config.getWebSocketMaxBufferSize())); } public final Callback newDrainCallback(final NettyResponseFuture<?> future, final Channel channel, final boolean keepAlive, final Object partitionKey) { return new Callback(future) { public void call() { tryToOfferChannelToPool(channel, future.getAsyncHandler(), keepAlive, partitionKey); } }; } public void drainChannelAndOffer(final Channel channel, final NettyResponseFuture<?> future) { drainChannelAndOffer(channel, future, future.isKeepAlive(), future.getPartitionKey()); } public void drainChannelAndOffer(final Channel channel, final NettyResponseFuture<?> future, boolean keepAlive, Object partitionKey) { Channels.setAttribute(channel, newDrainCallback(future, channel, keepAlive, partitionKey)); } public ChannelPool getChannelPool() { return channelPool; } }
package com.newsblur.fragment; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Display; import android.view.LayoutInflater; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnCreateContextMenuListener; import android.view.ViewGroup; import android.widget.ExpandableListView; import android.widget.ExpandableListView.OnChildClickListener; import android.widget.ExpandableListView.OnGroupClickListener; import android.widget.Toast; import com.newsblur.R; import com.newsblur.activity.AllStoriesItemsList; import com.newsblur.activity.FeedItemsList; import com.newsblur.activity.ItemsList; import com.newsblur.activity.NewsBlurApplication; import com.newsblur.activity.SavedStoriesItemsList; import com.newsblur.activity.SocialFeedItemsList; import com.newsblur.database.DatabaseConstants; import com.newsblur.database.FeedProvider; import com.newsblur.database.MixedExpandableListAdapter; import com.newsblur.network.APIManager; import com.newsblur.network.MarkFeedAsReadTask; import com.newsblur.network.MarkFolderAsReadTask; import com.newsblur.util.AppConstants; import com.newsblur.util.ImageLoader; import com.newsblur.util.PrefConstants; import com.newsblur.util.UIUtils; import com.newsblur.view.FolderTreeViewBinder; import com.newsblur.view.SocialFeedViewBinder; public class FolderListFragment extends Fragment implements OnGroupClickListener, OnChildClickListener, OnCreateContextMenuListener { private ContentResolver resolver; private MixedExpandableListAdapter folderAdapter; private FolderTreeViewBinder groupViewBinder; private APIManager apiManager; private int currentState = AppConstants.STATE_SOME; private SocialFeedViewBinder blogViewBinder; private SharedPreferences sharedPreferences; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // all cursors are initially queried in the "some" unread state to match the default view mode Cursor folderCursor = resolver.query(FeedProvider.FOLDERS_URI, null, null, new String[] { DatabaseConstants.getFolderSelectionFromState(AppConstants.STATE_SOME) }, null); Cursor socialFeedCursor = resolver.query(FeedProvider.SOCIAL_FEEDS_URI, null, DatabaseConstants.getBlogSelectionFromState(AppConstants.STATE_SOME), null, null); Cursor countCursor = resolver.query(FeedProvider.FEED_COUNT_URI, null, DatabaseConstants.getBlogSelectionFromState(AppConstants.STATE_SOME), null, null); Cursor sharedCountCursor = resolver.query(FeedProvider.SOCIALCOUNT_URI, null, DatabaseConstants.getBlogSelectionFromState(AppConstants.STATE_SOME), null, null); Cursor savedCountCursor = resolver.query(FeedProvider.STARRED_STORIES_COUNT_URI, null, null, null, null); ImageLoader imageLoader = ((NewsBlurApplication) getActivity().getApplicationContext()).getImageLoader(); groupViewBinder = new FolderTreeViewBinder(imageLoader); blogViewBinder = new SocialFeedViewBinder(getActivity()); folderAdapter = new MixedExpandableListAdapter(getActivity(), folderCursor, socialFeedCursor, countCursor, sharedCountCursor, savedCountCursor); folderAdapter.setViewBinders(groupViewBinder, blogViewBinder); } @Override public void onAttach(Activity activity) { sharedPreferences = activity.getSharedPreferences(PrefConstants.PREFERENCES, 0); resolver = activity.getContentResolver(); apiManager = new APIManager(activity); super.onAttach(activity); } @Override public void onStart() { super.onStart(); hasUpdated(); } public void hasUpdated() { folderAdapter.notifyDataSetChanged(); checkOpenFolderPreferences(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_folderfeedlist, container); ExpandableListView list = (ExpandableListView) v.findViewById(R.id.folderfeed_list); list.setGroupIndicator(getResources().getDrawable(R.drawable.transparent)); list.setOnCreateContextMenuListener(this); Display display = getActivity().getWindowManager().getDefaultDisplay(); list.setIndicatorBounds( display.getWidth() - UIUtils.convertDPsToPixels(getActivity(), 20), display.getWidth() - UIUtils.convertDPsToPixels(getActivity(), 10)); list.setChildDivider(getActivity().getResources().getDrawable(R.drawable.divider_light)); list.setAdapter(folderAdapter); list.setOnGroupClickListener(this); list.setOnChildClickListener(this); return v; } private ExpandableListView getListView() { return (ExpandableListView) (this.getView().findViewById(R.id.folderfeed_list)); } public void checkOpenFolderPreferences() { if (sharedPreferences == null) { sharedPreferences = getActivity().getSharedPreferences(PrefConstants.PREFERENCES, 0); } for (int i = 0; i < folderAdapter.getGroupCount(); i++) { String groupName = folderAdapter.getGroupName(i); if (sharedPreferences.getBoolean(AppConstants.FOLDER_PRE + "_" + groupName, true)) { this.getListView().expandGroup(i); } else { this.getListView().collapseGroup(i); } } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { MenuInflater inflater = getActivity().getMenuInflater(); ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) menuInfo; int type = ExpandableListView.getPackedPositionType(info.packedPosition); switch(type) { case ExpandableListView.PACKED_POSITION_TYPE_GROUP: int groupPosition = ExpandableListView.getPackedPositionGroup(info.packedPosition); if (! folderAdapter.isRowSavedStories(groupPosition) ) { inflater.inflate(R.menu.context_folder, menu); } break; case ExpandableListView.PACKED_POSITION_TYPE_CHILD: inflater.inflate(R.menu.context_feed, menu); break; } } @Override public boolean onContextItemSelected(MenuItem item) { final ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) item.getMenuInfo(); if (item.getItemId() == R.id.menu_mark_feed_as_read) { new MarkFeedAsReadTask(getActivity(), apiManager) { @Override protected void onPostExecute(Boolean result) { if (result.booleanValue()) { ContentValues values = new ContentValues(); values.put(DatabaseConstants.FEED_NEGATIVE_COUNT, 0); values.put(DatabaseConstants.FEED_NEUTRAL_COUNT, 0); values.put(DatabaseConstants.FEED_POSITIVE_COUNT, 0); resolver.update(FeedProvider.FEEDS_URI.buildUpon().appendPath(Long.toString(info.id)).build(), values, null, null); folderAdapter.notifyDataSetChanged(); Toast.makeText(getActivity(), R.string.toast_marked_feed_as_read, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity(), R.string.toast_error_marking_feed_as_read, Toast.LENGTH_LONG).show(); } } }.execute(Long.toString(info.id)); return true; } else if (item.getItemId() == R.id.menu_delete_feed) { int childPosition = ExpandableListView.getPackedPositionChild(info.packedPosition); int groupPosition = ExpandableListView.getPackedPositionGroup(info.packedPosition); Cursor childCursor = folderAdapter.getChild(groupPosition, childPosition); String feedTitle = childCursor.getString(childCursor.getColumnIndex(DatabaseConstants.FEED_TITLE)); // TODO: is there a better way to map group position onto folderName than asking the list adapter? Cursor folderCursor = ((MixedExpandableListAdapter) this.getListView().getExpandableListAdapter()).getGroup(groupPosition); String folderName = folderCursor.getString(folderCursor.getColumnIndex(DatabaseConstants.FOLDER_NAME)); DialogFragment deleteFeedFragment = DeleteFeedFragment.newInstance(info.id, feedTitle, folderName); deleteFeedFragment.show(getFragmentManager(), "dialog"); return true; } else if (item.getItemId() == R.id.menu_mark_folder_as_read) { int groupPosition = ExpandableListView.getPackedPositionGroup(info.packedPosition); // all folder but the root All Stories one use the simple method if (!folderAdapter.isFolderRoot(groupPosition)) { // TODO: is there a better way to get the folder ID for a group position that asking the list view? final Cursor folderCursor = ((MixedExpandableListAdapter) this.getListView().getExpandableListAdapter()).getGroup(groupPosition); String folderId = folderCursor.getString(folderCursor.getColumnIndex(DatabaseConstants.FOLDER_NAME)); new MarkFolderAsReadTask(apiManager, resolver) { @Override protected void onPostExecute(Boolean result) { if (result) { folderAdapter.notifyDataSetChanged(); Toast.makeText(getActivity(), R.string.toast_marked_folder_as_read, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity(), R.string.toast_error_marking_feed_as_read, Toast.LENGTH_SHORT).show(); } } }.execute(folderId); } else { // TODO is social feed actually all shared stories ? Should this be used for expandable and position == 0 ? /*final Cursor socialFeedCursor = ((MixedExpandableListAdapter) list.getExpandableListAdapter()).getGroup(groupPosition); String socialFeedId = socialFeedCursor.getString(socialFeedCursor.getColumnIndex(DatabaseConstants.SOCIAL_FEED_ID)); new MarkSocialFeedAsReadTask(apiManager, resolver){ @Override protected void onPostExecute(Boolean result) { if (result.booleanValue()) { folderAdapter.notifyDataSetChanged(); Toast.makeText(getActivity(), R.string.toast_marked_socialfeed_as_read, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity(), R.string.toast_error_marking_feed_as_read, Toast.LENGTH_LONG).show(); } } }.execute(socialFeedId);*/ new AsyncTask<Void, Void, Boolean>() { private List<String> feedIds = new ArrayList<String>(); @Override protected Boolean doInBackground(Void... arg) { return apiManager.markAllAsRead(); } @Override protected void onPostExecute(Boolean result) { if (result) { ContentValues values = new ContentValues(); values.put(DatabaseConstants.FEED_NEGATIVE_COUNT, 0); values.put(DatabaseConstants.FEED_NEUTRAL_COUNT, 0); values.put(DatabaseConstants.FEED_POSITIVE_COUNT, 0); resolver.update(FeedProvider.FEEDS_URI, values, null, null); folderAdapter.notifyDataSetChanged(); UIUtils.safeToast(getActivity(), R.string.toast_marked_all_stories_as_read, Toast.LENGTH_SHORT); } else { UIUtils.safeToast(getActivity(), R.string.toast_error_marking_feed_as_read, Toast.LENGTH_SHORT); } }; }.execute(); } return true; } return super.onContextItemSelected(item); } public void changeState(int state) { groupViewBinder.setState(state); blogViewBinder.setState(state); currentState = state; String groupSelection = DatabaseConstants.getFolderSelectionFromState(state); String blogSelection = DatabaseConstants.getBlogSelectionFromState(state); // the countCursor always counts neutral/"some" unreads, no matter what mode we are in String countSelection = DatabaseConstants.getBlogSelectionFromState(AppConstants.STATE_SOME); folderAdapter.currentState = state; Cursor cursor = resolver.query(FeedProvider.FOLDERS_URI, null, null, new String[] { groupSelection }, null); Cursor blogCursor = resolver.query(FeedProvider.SOCIAL_FEEDS_URI, null, blogSelection, null, null); Cursor countCursor = resolver.query(FeedProvider.FEED_COUNT_URI, null, countSelection, null, null); folderAdapter.setBlogCursor(blogCursor); folderAdapter.setGroupCursor(cursor); folderAdapter.setCountCursor(countCursor); folderAdapter.notifyDataSetChanged(); checkOpenFolderPreferences(); } @Override public boolean onGroupClick(ExpandableListView list, View group, int groupPosition, long id) { // The root "All Stories" folder goes to a special activity if (folderAdapter.isFolderRoot(groupPosition)) { Intent i = new Intent(getActivity(), AllStoriesItemsList.class); i.putExtra(AllStoriesItemsList.EXTRA_STATE, currentState); startActivity(i); return true; } else if (folderAdapter.isRowSavedStories(groupPosition)) { Intent i = new Intent(getActivity(), SavedStoriesItemsList.class); startActivity(i); return true; } else { if ((group != null) && (group.findViewById(R.id.row_foldersums) != null)) { String groupName = folderAdapter.getGroupName(groupPosition); if (list.isGroupExpanded(groupPosition)) { group.findViewById(R.id.row_foldersums).setVisibility(View.VISIBLE); sharedPreferences.edit().putBoolean(AppConstants.FOLDER_PRE + "_" + groupName, false).commit(); } else { group.findViewById(R.id.row_foldersums).setVisibility(View.INVISIBLE); sharedPreferences.edit().putBoolean(AppConstants.FOLDER_PRE + "_" + groupName, true).commit(); } } return false; } } @Override public boolean onChildClick(ExpandableListView list, View childView, int groupPosition, int childPosition, long id) { if (groupPosition == 0) { Cursor blurblogCursor = folderAdapter.getBlogCursor(childPosition); String username = blurblogCursor.getString(blurblogCursor.getColumnIndex(DatabaseConstants.SOCIAL_FEED_USERNAME)); String userIcon = blurblogCursor.getString(blurblogCursor.getColumnIndex(DatabaseConstants.SOCIAL_FEED_ICON)); String userId = blurblogCursor.getString(blurblogCursor.getColumnIndex(DatabaseConstants.SOCIAL_FEED_ID)); String blurblogTitle = blurblogCursor.getString(blurblogCursor.getColumnIndex(DatabaseConstants.SOCIAL_FEED_TITLE)); final Intent intent = new Intent(getActivity(), SocialFeedItemsList.class); intent.putExtra(ItemsList.EXTRA_BLURBLOG_USER_ICON, userIcon); intent.putExtra(ItemsList.EXTRA_BLURBLOG_USERNAME, username); intent.putExtra(ItemsList.EXTRA_BLURBLOG_TITLE, blurblogTitle); intent.putExtra(ItemsList.EXTRA_BLURBLOG_USERID, userId); intent.putExtra(ItemsList.EXTRA_STATE, currentState); getActivity().startActivity(intent); } else { final Intent intent = new Intent(getActivity(), FeedItemsList.class); Cursor childCursor = folderAdapter.getChild(groupPosition, childPosition); String feedId = childCursor.getString(childCursor.getColumnIndex(DatabaseConstants.FEED_ID)); String feedTitle = childCursor.getString(childCursor.getColumnIndex(DatabaseConstants.FEED_TITLE)); final Cursor folderCursor = ((MixedExpandableListAdapter) list.getExpandableListAdapter()).getGroup(groupPosition); String folderName = folderCursor.getString(folderCursor.getColumnIndex(DatabaseConstants.FOLDER_NAME)); intent.putExtra(FeedItemsList.EXTRA_FEED, feedId); intent.putExtra(FeedItemsList.EXTRA_FEED_TITLE, feedTitle); intent.putExtra(FeedItemsList.EXTRA_FOLDER_NAME, folderName); intent.putExtra(ItemsList.EXTRA_STATE, currentState); getActivity().startActivity(intent); } return true; } }
package simulation; import akka.japi.pf.ReceiveBuilder; import akka.japi.pf.UnitPFBuilder; import drones.messages.*; import drones.models.*; import play.libs.Akka; import scala.concurrent.Promise; import scala.concurrent.duration.Duration; import scala.concurrent.duration.FiniteDuration; import simulation.messages.SetConnectionLostMessage; import simulation.messages.SetCrashedMessage; import java.io.Serializable; import java.util.concurrent.TimeUnit; public class DroneActorSimulator extends DroneActor { private class ProgressToDestinationMessage implements Serializable { private Location destination; private FiniteDuration timeStep; public ProgressToDestinationMessage(Location destination, FiniteDuration timestep) { this.destination = destination; this.timeStep = timestep; } public Location getDestination() { return destination; } public FiniteDuration getTimeStep() { return timeStep; } } private byte batteryLowLevel = 10; private byte batteryCriticalLevel = 5; private boolean initialized = false; private boolean crashed = false; private boolean connectionLost = false; private double maxHeight; private double topSpeed; // assume m/s private boolean flyingToDestination; // TODO: settable delay, sleep/suspend // Control stuff @Override protected UnitPFBuilder<Object> createListeners() { return ReceiveBuilder. match(BatteryPercentageChangedMessage.class, m -> processBatteryLevel(m.getPercent())). match(SetCrashedMessage.class, m -> setCrashed(m.isCrashed())). match(SetConnectionLostMessage.class, m -> setConnectionLost(m.isConnectionLost())). match(ProgressToDestinationMessage.class, m -> progressToDestination(m.getDestination(), m.getTimeStep())); } protected void processBatteryLevel(byte percentage) { if(percentage < batteryLowLevel) { if(percentage < batteryCriticalLevel) { if(!connectionLost) { tellSelf(new AlertStateChangedMessage(AlertState.BATTERY_CRITICAL)); tellSelf(new LandRequestMessage()); tellSelf(new NavigationStateChangedMessage( NavigationState.UNAVAILABLE, NavigationStateReason.BATTERY_LOW)); } else { alertState.setValue(AlertState.BATTERY_CRITICAL); state.setValue(FlyingState.LANDED); navigationState.setValue(NavigationState.UNAVAILABLE); navigationStateReason.setValue(NavigationStateReason.BATTERY_LOW); } } else { if(!connectionLost) { tellSelf(new AlertStateChangedMessage(AlertState.BATTERY_LOW)); } else { alertState.setValue(AlertState.BATTERY_LOW); } } } } protected void setCrashed(boolean crashed) { if (crashed) { tellSelf(new AltitudeChangedMessage(0.0)); tellSelf(new FlyingStateChangedMessage(FlyingState.EMERGENCY)); tellSelf(new AlertStateChangedMessage(AlertState.USER_EMERGENCY)); tellSelf(new SpeedChangedMessage(0, 0, 0)); tellSelf(new NavigationStateChangedMessage( NavigationState.UNAVAILABLE, NavigationStateReason.STOPPED )); } else { tellSelf(new FlyingStateChangedMessage(FlyingState.LANDED)); tellSelf(new AlertStateChangedMessage(AlertState.NONE)); tellSelf(new NavigationStateChangedMessage( NavigationState.AVAILABLE, NavigationStateReason.ENABLED )); } this.crashed = crashed; } protected void setConnectionLost(boolean connectionLost) { if(connectionLost) { // Don't tell self (we don't want this messages published as we are out of range alertState.setValue(AlertState.CUT_OUT); navigationState.setValue(NavigationState.UNAVAILABLE); navigationStateReason.setValue(NavigationStateReason.CONNECTION_LOST); } else { tellSelf(new AlertStateChangedMessage(AlertState.NONE)); tellSelf(new NavigationStateChangedMessage( NavigationState.AVAILABLE, NavigationStateReason.ENABLED )); } this.connectionLost = connectionLost; } protected void progressToDestination(Location destination, FiniteDuration timeFlown) { // Check if moveToLocation wasn't cancelled if(flyingToDestination) { Location currentLocation = location.getRawValue(); // Calculate distance double distance = Location.distance(currentLocation, destination); // assume in meters double timeTillArrival = distance/topSpeed; double timeStep = timeFlown.toUnit(TimeUnit.SECONDS); Location newLocation; if (timeTillArrival > timeStep) { // Not there yet double deltaLongtitude = destination.getLongtitude() - currentLocation.getLongtitude(); double deltaLatitude = destination.getLatitude() - currentLocation.getLatitude(); double deltaAltitude = destination.getHeigth() - currentLocation.getHeigth(); double fraction = timeStep/timeTillArrival; double newLongtitude = currentLocation.getLongtitude() + deltaLongtitude * fraction; double newLatitude = currentLocation.getLatitude() + deltaLatitude * fraction; double newHeight = currentLocation.getHeigth() + deltaAltitude * fraction; newLocation = new Location(newLatitude, newLongtitude, newHeight); } else { newLocation = destination; } // Update current location if (!connectionLost) { tellSelf(new LocationChangedMessage( newLocation.getLongtitude(), newLocation.getLatitude(), newLocation.getHeigth())); } else { location.setValue(newLocation); } // Check if we have arrived ore not if (timeTillArrival < timeStep) { // We have arrived if(!connectionLost) { tellSelf(new FlyingStateChangedMessage(FlyingState.HOVERING)); tellSelf(new NavigationStateChangedMessage( NavigationState.AVAILABLE, NavigationStateReason.FINISHED )); } else { state.setValue(FlyingState.HOVERING); navigationState.setValue(NavigationState.AVAILABLE); navigationStateReason.setValue(NavigationStateReason.FINISHED); } } else { // Schedule to fly further Akka.system().scheduler().scheduleOnce( timeFlown, self(), new ProgressToDestinationMessage(destination, timeFlown), Akka.system().dispatcher(), self()); } } else { // Flying aborted if(!connectionLost) { tellSelf(new FlyingStateChangedMessage(FlyingState.HOVERING)); tellSelf(new NavigationStateChangedMessage( NavigationState.AVAILABLE, NavigationStateReason.STOPPED )); } else { state.setValue(FlyingState.HOVERING); navigationState.setValue(NavigationState.AVAILABLE); navigationStateReason.setValue(NavigationStateReason.STOPPED); } } } // Utility methods protected void tellSelf(Object msg) { self().tell(msg, self()); } public DroneActorSimulator() { state.setValue(FlyingState.LANDED); alertState.setValue(AlertState.NONE); location.setValue(new Location(0.0, 0.0, 0.0)); batteryPercentage.setValue((byte) 100); rotation.setValue(new Rotation(0, 0, 0)); speed.setValue(new Speed(0.0, 0.0, 0.0)); altitude.setValue(0.0); version.setValue(new DroneVersion("1.0", "1.0")); navigationState.setValue(NavigationState.AVAILABLE); navigationStateReason.setValue(NavigationStateReason.ENABLED); gpsFix.setValue(false); maxHeight = 10; topSpeed = 10; } // Implementation of DroneActor @Override protected void init(Promise<Void> p) { if(connectionLost) { return; } initialized = true; p.success(null); } @Override protected void takeOff(Promise<Void> p) { if(connectionLost) { return; } if(!initialized) { p.failure(new DroneException("Failed to send command. Not initialized yet.")); return; } if(crashed) { p.failure(new DroneException("Drone crashed, unable to execute commands")); return; } switch (state.getRawValue()) { case EMERGENCY: p.failure(new DroneException("Drone is in emergency status")); break; case LANDING: // Land drone before taking off again tellSelf(new FlyingStateChangedMessage(FlyingState.LANDED)); // Fall-through case LANDED: tellSelf(new FlyingStateChangedMessage(FlyingState.TAKINGOFF)); tellSelf(new AltitudeChangedMessage(1.0)); tellSelf(new FlyingStateChangedMessage(FlyingState.HOVERING)); // Fall-throug default: // TODO: set navigation status? p.success(null); } } @Override protected void land(Promise<Void> p) { if(connectionLost) { return; } if(!initialized) { p.failure(new DroneException("Failed to send command. Not initialized yet.")); return; } if(crashed) { p.failure(new DroneException("Drone crashed, unable to execute commands")); return; } switch (state.getRawValue()) { case EMERGENCY: p.failure(new DroneException("Drone is in emergency status")); break; case TAKINGOFF: // Hover drone before landing again tellSelf(new FlyingStateChangedMessage(FlyingState.HOVERING)); // Fall-through case HOVERING: tellSelf(new FlyingStateChangedMessage(FlyingState.LANDING)); // Fall-through default: tellSelf(new AltitudeChangedMessage(0.0)); tellSelf(new FlyingStateChangedMessage(FlyingState.LANDED)); p.success(null); } } @Override protected void move3d(Promise<Void> p, double vx, double vy, double vz, double vr) { if(connectionLost) { return; } if(!initialized) { p.failure(new DroneException("Failed to send command. Not initialized yet.")); return; } if(crashed) { p.failure(new DroneException("Drone crashed, unable to execute commands")); return; } // TODO: need specification of this method p.success(null); } @Override protected void moveToLocation(Promise<Void> p, double latitude, double longitude, double altitude) { if(connectionLost) { return; } if(!initialized) { p.failure(new DroneException("Failed to send command. Not initialized yet.")); return; } if(crashed) { p.failure(new DroneException("Drone crashed, unable to execute commands")); return; } FlyingState flyingState = state.getRawValue(); if(flyingState == FlyingState.FLYING || flyingState == FlyingState.HOVERING) { double height = Math.min(altitude, maxHeight); Location destination = new Location(latitude, longitude, height); tellSelf(new FlyingStateChangedMessage(FlyingState.FLYING)); tellSelf(new NavigationStateChangedMessage( NavigationState.IN_PROGRESS, NavigationStateReason.REQUESTED )); tellSelf(new SpeedChangedMessage(10, 10, 10)); // Schedule to fly further Akka.system().scheduler().scheduleOnce( new FiniteDuration(1, TimeUnit.SECONDS), self(), new ProgressToDestinationMessage(destination, Duration.create(1, TimeUnit.SECONDS)), Akka.system().dispatcher(), self()); p.success(null); } else { p.failure(new DroneException("Drone is unable to move in current state: " + flyingState.name())); } } @Override protected void cancelMoveToLocation(Promise<Void> p) { if(connectionLost) { return; } if(!initialized) { p.failure(new DroneException("Failed to send command. Not initialized yet.")); return; } if(crashed) { p.failure(new DroneException("Drone crashed, unable to execute commands")); return; } if(state.getRawValue() == FlyingState.EMERGENCY) { p.failure(new DroneException("Unable to send commands to drone in emergency state")); } else { flyingToDestination = false; p.success(null); } } @Override protected void setMaxHeight(Promise<Void> p, float meters) { if(connectionLost) { return; } if(!initialized) { p.failure(new DroneException("Failed to send command. Not initialized yet.")); return; } /* TODO: necessary here? if(crashed) { p.failure(new DroneException("Drone crashed, unable to execute commands")); return; } */ maxHeight = meters; p.success(null); } @Override protected void setMaxTilt(Promise<Void> p, float degrees) { if(connectionLost) { return; } if(!initialized) { p.failure(new DroneException("Failed to send command. Not initialized yet.")); return; } /* TODO: necessary here? if(crashed) { p.failure(new DroneException("Drone crashed, unable to execute commands")); return; } */ p.success(null); } @Override protected void setOutdoor(Promise<Void> p, boolean outdoor) { if(connectionLost) { return; } if(!initialized) { p.failure(new DroneException("Failed to send command. Not initialized yet.")); return; } /* TODO: necessary here? if(crashed) { p.failure(new DroneException("Drone crashed, unable to execute commands")); return; } */ // no effect on simulation p.success(null); } @Override protected void setHull(Promise<Void> p, boolean hull) { if(connectionLost) { return; } if(!initialized) { p.failure(new DroneException("Failed to send command. Not initialized yet.")); return; } /* TODO: necessary here? if(crashed) { p.failure(new DroneException("Drone crashed, unable to execute commands")); return; } */ // No effect on simulation p.success(null); } @Override protected void flatTrim(Promise<Void> p) { if(connectionLost) { return; } if(!initialized) { p.failure(new DroneException("Failed to send command. Not initialized yet.")); return; } /* TODO: necessary here? if(crashed) { p.failure(new DroneException("Drone crashed, unable to execute commands")); return; } */ // TODO: find out what this should do p.success(null); } }
/* * $Id: NullPlugin.java,v 1.21 2003-02-24 18:39:53 tal Exp $ */ package org.lockss.test; import java.io.*; import java.util.*; import java.net.*; import java.security.MessageDigest; import org.lockss.daemon.*; import org.lockss.plugin.*; import org.lockss.state.*; import org.lockss.test.*; /** * Base class for test plugins that don't want to implement all the * required methods. * Extend only the nested classes to which you need to add bahavior. */ public class NullPlugin { /** * Base class for test <code>Plugin</code>s. Default methods do nothing * or return constants. */ public static class Plugin implements org.lockss.plugin.Plugin { protected Plugin() { } public void initPlugin() { } public void stopPlugin() { } public String getPluginId() { return "NullPlugin"; } public String getVersion() { return "NullVersion"; } public List getSupportedAUNames() { return null; } public List getAUConfigProperties() { return null; } public String getAUIdFromConfig(Configuration config) throws org.lockss.daemon.ArchivalUnit.ConfigurationException { return null; } public org.lockss.daemon.ArchivalUnit configureAU(Configuration config) throws org.lockss.daemon.ArchivalUnit.ConfigurationException { return null; } public org.lockss.daemon.ArchivalUnit createAU(Configuration auConfig) throws org.lockss.daemon.ArchivalUnit.ConfigurationException { return null; } public org.lockss.daemon.ArchivalUnit getAU(String auId) { return null; } public Collection getAllAUs() { return null; }; } /** * Base class for test <code>CachedUrl</code>s. Default methods do nothing * or return constants. */ public static class CachedUrl implements org.lockss.daemon.CachedUrl { protected CachedUrl() { } public String toString() { return "[NullPlugin.CachedUrl]"; } public String getUrl() { return null; } public boolean hasContent() { return false; } public boolean isLeaf() { return true; } public int getType() { return CachedUrlSetNode.TYPE_CACHED_URL; } public InputStream openForReading() { return new StringInputStream(""); } public Properties getProperties() { return new Properties(); } } /** * Base class for test <code>UrlCacher</code>s. Default methods do nothing * or return constants. */ public static class UrlCacher implements org.lockss.daemon.UrlCacher { private String url; private String contents = null; private Properties props = new Properties(); protected UrlCacher() { } public String getUrl() { return null; } public org.lockss.daemon.CachedUrlSet getCachedUrlSet() { return null; } public String toString() { return "[NullPlugin.UrlCacher]"; } public org.lockss.daemon.CachedUrl getCachedUrl() { return new CachedUrl(); } public boolean shouldBeCached() { return false; } public void cache() throws IOException { } public void storeContent(InputStream input, Properties headers) throws IOException { } public InputStream getUncachedInputStream() { return new StringInputStream(""); } public Properties getUncachedProperties() { return new Properties(); } } /** * Base class for test <code>CachedUrlSet</code>s. Default methods do * nothing or return constants or empty enumerations. */ public static class CachedUrlSet implements org.lockss.daemon.CachedUrlSet { public String toString() { return "[NullPlugin.CachedUrlSet]"; } public CachedUrlSetSpec getSpec() { return null; } public org.lockss.daemon.ArchivalUnit getArchivalUnit() { return null; } public void storeActualHashDuration(long elapsed, Exception err) { } public Iterator flatSetIterator() { return null; } public Iterator treeSetIterator() { return null; } public Iterator treeIterator() { return null; } public boolean isLeaf() { return false; } public int getType() { return CachedUrlSetNode.TYPE_CACHED_URL_SET; } public org.lockss.daemon.CachedUrlSetHasher getContentHasher(MessageDigest hasher) { return new CachedUrlSetHasher(); } public org.lockss.daemon.CachedUrlSetHasher getNameHasher(MessageDigest hasher) { return new CachedUrlSetHasher(); } public long estimatedHashDuration() { return 1000; } public boolean hasContent() { return false; } public org.lockss.daemon.CachedUrl makeCachedUrl(String url) { return new CachedUrl(); } public org.lockss.daemon.UrlCacher makeUrlCacher(String url) { return new UrlCacher(); } public boolean containsUrl(String url) { return false; } public int hashCode() { return 0; } public String getUrl() { return "null"; } } public static class ArchivalUnit implements org.lockss.daemon.ArchivalUnit { public void setConfiguration(Configuration config) { } public org.lockss.daemon.CachedUrlSet makeCachedUrlSet(String url, String lwrBound, String uprBound) { return null; } public org.lockss.daemon.CachedUrlSet getAUCachedUrlSet() { return null; } public CrawlSpec getCrawlSpec() { return null; } public boolean shouldBeCached(String url) { return false; } public String getPluginId() { return "null"; } public String getAUId() { return "null"; } public void pause() { } public int hashCode() { return 0; } public List getNewContentCrawlUrls() { return null; } public boolean shouldCrawlForNewContent(AuState aus) { return false; } } /** * Base class for test <code>CachedUrlSetHasher</code>s. Default methods * do nothing or return constants. */ public static class CachedUrlSetHasher implements org.lockss.daemon.CachedUrlSetHasher { public boolean finished() { return false; } public int hashStep(int numBytes) { return 0; } } }
package analysis.dynamicsim; import gnu.trove.map.hash.TObjectDoubleHashMap; import java.awt.Point; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.PriorityQueue; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JProgressBar; import javax.xml.stream.XMLStreamException; import flanagan.math.Fmath; import flanagan.math.PsRandom; import main.Gui; import main.util.dataparser.DTSDParser; import main.util.dataparser.DataParser; import main.util.dataparser.TSDParser; import odk.lang.FastMath; import org.apache.commons.math.stat.descriptive.DescriptiveStatistics; import org.sbml.jsbml.ASTNode; import org.sbml.jsbml.Annotation; import org.sbml.jsbml.AssignmentRule; import org.sbml.jsbml.Compartment; import org.sbml.jsbml.Constraint; import org.sbml.jsbml.Event; import org.sbml.jsbml.EventAssignment; import org.sbml.jsbml.InitialAssignment; import org.sbml.jsbml.KineticLaw; import org.sbml.jsbml.ListOf; import org.sbml.jsbml.LocalParameter; import org.sbml.jsbml.Model; import org.sbml.jsbml.ModifierSpeciesReference; import org.sbml.jsbml.Parameter; import org.sbml.jsbml.RateRule; import org.sbml.jsbml.Reaction; import org.sbml.jsbml.Rule; import org.sbml.jsbml.SBMLDocument; import org.sbml.jsbml.SBMLErrorLog; import org.sbml.jsbml.SBMLException; import org.sbml.jsbml.SBMLReader; import org.sbml.jsbml.Species; import org.sbml.jsbml.SpeciesReference; import org.sbml.jsbml.SBMLWriter; import org.sbml.jsbml.text.parser.ParseException; import biomodel.util.GlobalConstants; public abstract class Simulator { //SBML model protected Model model = null; //generates random numbers based on the xorshift method protected XORShiftRandom randomNumberGenerator = null; //allows for access to a propensity from a reaction ID protected TObjectDoubleHashMap<String> reactionToPropensityMap = null; //allows for access to reactant/product speciesID and stoichiometry from a reaction ID //note that species and stoichiometries need to be thought of as unique for each reaction protected HashMap<String, HashSet<StringDoublePair> > reactionToSpeciesAndStoichiometrySetMap = null; protected HashMap<String, HashSet<StringStringPair> > reactionToNonconstantStoichiometriesSetMap = null; //allows for access to reactant/modifier speciesID and stoichiometry from a reaction ID protected HashMap<String, HashSet<StringDoublePair> > reactionToReactantStoichiometrySetMap = null; //allows for access to a kinetic formula tree from a reaction protected HashMap<String, ASTNode> reactionToFormulaMap = null; //allows for access to a set of reactions that a species is in (as a reactant or modifier) from a species ID protected HashMap<String, HashSet<String> > speciesToAffectedReactionSetMap = null; //allows for access to species booleans from a species ID protected HashMap<String, Boolean> speciesToIsBoundaryConditionMap = null; protected HashMap<String, Boolean> speciesToHasOnlySubstanceUnitsMap = null; protected HashMap<String, String> speciesToSubstanceUnitsMap = null; protected HashMap<String, String> speciesToConversionFactorMap = null; protected HashMap<String, String> speciesToCompartmentNameMap = null; protected TObjectDoubleHashMap<String> speciesToCompartmentSizeMap = null; //a linked (ordered) set of all species IDs, to allow easy access to their values via the variableToValue map protected LinkedHashSet<String> speciesIDSet = null; //allows for access to species and parameter values from a variable ID protected TObjectDoubleHashMap<String> variableToValueMap = null; //stores events in order of fire time and priority protected PriorityQueue<EventToFire> triggeredEventQueue = null; protected HashSet<String> untriggeredEventSet = null; //hashmaps that allow for access to event information from the event's id protected HashMap<String, ASTNode> eventToPriorityMap = null; protected HashMap<String, ASTNode> eventToDelayMap = null; protected HashMap<String, Boolean> eventToHasDelayMap = null; protected HashMap<String, Boolean> eventToTriggerPersistenceMap = null; protected HashMap<String, Boolean> eventToUseValuesFromTriggerTimeMap = null; protected HashMap<String, ASTNode> eventToTriggerMap = null; protected HashMap<String, Boolean> eventToTriggerInitiallyTrueMap = null; protected HashMap<String, Boolean> eventToPreviousTriggerValueMap = null; protected HashMap<String, HashSet<Object> > eventToAssignmentSetMap = null; //allows for access to the reactions whose propensity changes when an event fires protected HashMap<String, HashSet<String> > eventToAffectedReactionSetMap = null; //allows for access to the set of events that a variable is in protected HashMap<String, HashSet<String> > variableToEventSetMap = null; //allows for access to the set of assignment rules that a variable (rhs) in an assignment rule affects protected HashMap<String, HashSet<AssignmentRule> > variableToAffectedAssignmentRuleSetMap = null; //allows to access to whether or not a variable is in an assignment or rate rule rule (RHS) protected HashMap<String, Boolean> variableToIsInAssignmentRuleMap = null; protected HashMap<String, Boolean> variableToIsInRateRuleMap = null; //allows for access to the set of constraints that a variable affects protected HashMap<String, HashSet<ASTNode> > variableToAffectedConstraintSetMap = null; protected HashMap<String, Boolean> variableToIsInConstraintMap = null; protected HashMap<String, Boolean> variableToIsConstantMap = null; //compares two events based on fire time and priority protected EventComparator eventComparator = new EventComparator(); //allows access to a component's location on the grid from its ID protected LinkedHashMap<String, Point> componentToLocationMap = null; //allows access to a component's set of reactions from its ID protected HashMap<String, HashSet<String> > componentToReactionSetMap = null; //allows access to a component's set of variables (species and parameters) from its ID protected HashMap<String, HashSet<String> > componentToVariableSetMap = null; protected HashMap<String, HashSet<String> > componentToEventSetMap = null; protected HashSet<String> componentIDSet = new HashSet<String>(); protected LinkedHashSet<String> compartmentIDSet = new LinkedHashSet<String>(); protected LinkedHashSet<String> nonconstantParameterIDSet = new LinkedHashSet<String>(); //initial model -- used for resetting when doing multiple dynamic runs protected ListOf<Species> initialSpecies = new ListOf<Species>(); protected ListOf<Reaction> initialReactions = new ListOf<Reaction>(); protected ListOf<Event> initialEvents = new ListOf<Event>(); protected ListOf<Parameter> initialParameters = new ListOf<Parameter>(); protected ListOf<Compartment> initialCompartments = new ListOf<Compartment>(); //locations parameter annotations for placing compartments protected HashMap<String, String> submodelIDToLocationsMap = new HashMap<String, String>(); protected ArrayList<String> interestingSpecies = new ArrayList<String>(); protected HashSet<String> ibiosimFunctionDefinitions = new HashSet<String>(); //propensity variables protected double totalPropensity = 0.0; protected double minPropensity = Double.MAX_VALUE / 10.0; protected double maxPropensity = Double.MIN_VALUE / 10.0; //file writing variables protected FileWriter TSDWriter = null; protected BufferedWriter bufferedTSDWriter = null; //boolean flags protected boolean cancelFlag = false; protected boolean constraintFailureFlag = false; protected boolean sbmlHasErrorsFlag = false; protected double currentTime; protected String SBMLFileName; protected double timeLimit; protected double maxTimeStep; protected double minTimeStep; protected JProgressBar progress; protected double printInterval; protected int currentRun; protected String outputDirectory; protected long numSpecies; protected long numParameters; protected long numReactions; protected long numEvents; protected long numRules; protected int numAssignmentRules; protected long numConstraints; protected int numInitialAssignments; protected int numRateRules; protected int minRow = Integer.MAX_VALUE; protected int minCol = Integer.MAX_VALUE; protected int maxRow = Integer.MIN_VALUE; protected int maxCol = Integer.MIN_VALUE; protected boolean stoichAmpBoolean = false; protected double stoichAmpGridValue = 1.0; //true means the model is dynamic protected boolean dynamicBoolean = false; protected boolean printConcentrations = false; protected int diffCount = 0; protected int totalCount = 0; protected int memCount = 0; protected JFrame running = new JFrame(); PsRandom prng = new PsRandom(); /** * does lots of initialization * * @param SBMLFileName * @param outputDirectory * @param timeLimit * @param maxTimeStep * @param randomSeed * @param progress * @param printInterval * @param initializationTime * @throws IOException * @throws XMLStreamException */ public Simulator(String SBMLFileName, String outputDirectory, double timeLimit, double maxTimeStep, double minTimeStep, long randomSeed, JProgressBar progress, double printInterval, Long initializationTime, double stoichAmpValue, JFrame running, String[] interestingSpecies, String quantityType) throws IOException, XMLStreamException { long initTime1 = System.nanoTime(); this.SBMLFileName = SBMLFileName; this.timeLimit = timeLimit; this.maxTimeStep = maxTimeStep; this.minTimeStep = minTimeStep; this.progress = progress; this.printInterval = printInterval; this.outputDirectory = outputDirectory; this.running = running; this.interestingSpecies.clear(); for (int i = 0; i < interestingSpecies.length; ++i) this.interestingSpecies.add(interestingSpecies[i]); if (quantityType != null && quantityType.equals("concentration")) this.printConcentrations = true; if (stoichAmpValue <= 1.0) stoichAmpBoolean = false; else { stoichAmpBoolean = true; stoichAmpGridValue = stoichAmpValue; } SBMLReader reader = new SBMLReader(); SBMLDocument document = null; document = reader.readSBML(SBMLFileName); SBMLErrorLog errors = document.getListOfErrors(); //if the sbml document has errors, tell the user and don't simulate if (document.getNumErrors() > 0) { String errorString = ""; for (int i = 0; i < errors.getNumErrors(); i++) { errorString += errors.getError(i); } JOptionPane.showMessageDialog(Gui.frame, "The SBML file contains " + document.getNumErrors() + " error(s):\n" + errorString, "SBML Error", JOptionPane.ERROR_MESSAGE); sbmlHasErrorsFlag = true; } model = document.getModel(); numSpecies = model.getNumSpecies(); numParameters = model.getNumParameters(); numReactions = model.getNumReactions(); numEvents = model.getNumEvents(); numRules = model.getNumRules(); numConstraints = model.getNumConstraints(); numInitialAssignments = model.getNumInitialAssignments(); //set initial capacities for collections (1.5 is used to multiply numReactions due to reversible reactions) speciesToAffectedReactionSetMap = new HashMap<String, HashSet<String> >((int) numSpecies); speciesToIsBoundaryConditionMap = new HashMap<String, Boolean>((int) numSpecies); variableToIsConstantMap = new HashMap<String, Boolean>((int) (numSpecies + numParameters)); speciesToHasOnlySubstanceUnitsMap = new HashMap<String, Boolean>((int) numSpecies); speciesToSubstanceUnitsMap = new HashMap<String, String>((int) numSpecies); speciesToConversionFactorMap = new HashMap<String, String>((int) numSpecies); speciesToCompartmentNameMap = new HashMap<String, String>((int) numSpecies); speciesToCompartmentSizeMap = new TObjectDoubleHashMap<String>((int) numSpecies); speciesIDSet = new LinkedHashSet<String>((int) numSpecies); reactionToNonconstantStoichiometriesSetMap = new HashMap<String, HashSet<StringStringPair> >(); variableToValueMap = new TObjectDoubleHashMap<String>((int) numSpecies + (int) numParameters); reactionToPropensityMap = new TObjectDoubleHashMap<String>((int) (numReactions * 1.5)); reactionToSpeciesAndStoichiometrySetMap = new HashMap<String, HashSet<StringDoublePair> >((int) (numReactions * 1.5)); reactionToReactantStoichiometrySetMap = new HashMap<String, HashSet<StringDoublePair> >((int) (numReactions * 1.5)); reactionToFormulaMap = new HashMap<String, ASTNode>((int) (numReactions * 1.5)); componentToLocationMap = new LinkedHashMap<String, Point>(); componentToReactionSetMap = new HashMap<String, HashSet<String> >(); componentToVariableSetMap = new HashMap<String, HashSet<String> >(); componentToEventSetMap = new HashMap<String, HashSet<String> >(); if (numEvents > 0) { triggeredEventQueue = new PriorityQueue<EventToFire>((int) numEvents, eventComparator); untriggeredEventSet = new HashSet<String>((int) numEvents); eventToPriorityMap = new HashMap<String, ASTNode>((int) numEvents); eventToDelayMap = new HashMap<String, ASTNode>((int) numEvents); eventToHasDelayMap = new HashMap<String, Boolean>((int) numEvents); eventToTriggerMap = new HashMap<String, ASTNode>((int) numEvents); eventToTriggerInitiallyTrueMap = new HashMap<String, Boolean>((int) numEvents); eventToTriggerPersistenceMap = new HashMap<String, Boolean>((int) numEvents); eventToUseValuesFromTriggerTimeMap = new HashMap<String, Boolean>((int) numEvents); eventToAssignmentSetMap = new HashMap<String, HashSet<Object> >((int) numEvents); eventToAffectedReactionSetMap = new HashMap<String, HashSet<String> >((int) numEvents); eventToPreviousTriggerValueMap = new HashMap<String, Boolean>((int) numEvents); variableToEventSetMap = new HashMap<String, HashSet<String> >((int) numEvents); } if (numRules > 0) { variableToAffectedAssignmentRuleSetMap = new HashMap<String, HashSet<AssignmentRule> >((int) numRules); variableToIsInAssignmentRuleMap = new HashMap<String, Boolean>((int) (numSpecies + numParameters)); variableToIsInRateRuleMap = new HashMap<String, Boolean>((int) (numSpecies + numParameters)); } if (numConstraints > 0) { variableToAffectedConstraintSetMap = new HashMap<String, HashSet<ASTNode> >((int) numConstraints); variableToIsInConstraintMap = new HashMap<String, Boolean>((int) (numSpecies + numParameters)); } ibiosimFunctionDefinitions.add("uniform"); ibiosimFunctionDefinitions.add("exponential"); ibiosimFunctionDefinitions.add("gamma"); ibiosimFunctionDefinitions.add("chisq"); ibiosimFunctionDefinitions.add("lognormal"); ibiosimFunctionDefinitions.add("laplace"); ibiosimFunctionDefinitions.add("cauchy"); ibiosimFunctionDefinitions.add("poisson"); ibiosimFunctionDefinitions.add("binomial"); ibiosimFunctionDefinitions.add("bernoulli"); ibiosimFunctionDefinitions.add("normal"); initializationTime = System.nanoTime() - initTime1; } /** * replaces ROWX_COLY with ROWA_COLB in a kinetic law * this has to be done without re-parsing the formula string because the row/col * values can be negative, which gets parsed incorrectly * * @param node * @param oldString * @param newString */ private void alterNode(ASTNode node, String oldString, String newString) { if (node.isName() && node.getName().contains(oldString)) { node.setVariable(model.getSpecies(newString + "__" + node.getName().split("__")[1])); } else { for (ASTNode childNode : node.getChildren()) alterNode(childNode, oldString, newString); } } /** * replaceArgument() doesn't work when you're replacing a localParameter, so this * does that -- finds the oldString within node and replaces it with the local parameter * specified by newString * * @param node * @param reactionID * @param oldString * @param newString */ private void alterLocalParameter(ASTNode node, Reaction reaction, String oldString, String newString) { String reactionID = reaction.getId(); if (node.isName() && node.getName().equals(oldString)) { node.setVariable(reaction.getKineticLaw().getLocalParameter(newString)); } else { for (ASTNode childNode : node.getChildren()) alterLocalParameter(childNode, reaction, oldString, newString); } } /** * alters the kinetic laws and stoichiometries of grid diffusion reactions * in accordance with the stoichiometry amplification parameters specified by the user * * @param model */ private static void applyStoichiometryAmplification(Model model, double stoichAmpValue) { if (stoichAmpValue <= 1.0) return; for (Reaction reaction : model.getListOfReactions()) { //stoichiometry amplification -- alter the stoichiometry if (reaction.getId().contains("_Diffusion_")) { //these are all forward reactions, so adjust the stoichiometries of the reactant for (SpeciesReference reactant : reaction.getListOfReactants()) reactant.setStoichiometry(stoichAmpValue); //alter the kinetic laws by dividing by the stoichiometry amplification value //this will alter the propensities accordingly ASTNode divisionNode = new ASTNode(); divisionNode.setValue(1.0 / stoichAmpValue); reaction.getKineticLaw().getMath().multiplyWith(divisionNode); } } } /** * cancels the current run */ protected abstract void cancel(); /** * clears data structures for new run */ protected abstract void clear(); /** * copies parts of the model that may change during a dynamic run */ protected void createModelCopy() { initialSpecies = model.getListOfSpecies().clone(); initialReactions = model.getListOfReactions().clone(); initialEvents = model.getListOfEvents().clone(); initialParameters = model.getListOfParameters().clone(); initialCompartments = model.getListOfCompartments().clone(); } /** * uses an existing component to create a new component and update data structures and the simulation state * this is used for "birth" events in dynamic models * * @param parentComponentID * @param eventID the ID of the division event that just fired */ protected void duplicateComponent(String parentComponentID, String eventID, String symmetry) { //determine new component ID int componentNumber = componentToReactionSetMap.size() + 1; String childComponentID = "C" + String.valueOf(componentNumber); while (componentToReactionSetMap.keySet().contains(childComponentID) == true || componentIDSet.contains(childComponentID) == true) { ++componentNumber; childComponentID = "C" + String.valueOf(componentNumber); } //the component ID is just the child name with no ancestry information //the compartment ID contains the ancestry information componentIDSet.add(childComponentID); //only use the immediate parent for the new ID childComponentID = childComponentID + "_of_" + parentComponentID.split("_of_")[0]; Compartment childCompartment = model.createCompartment(); String compartID = ""; //duplicate compartment for (Compartment comp : model.getListOfCompartments()) { if (comp.getId().contains(parentComponentID + "__")) { compartID = comp.getId(); childCompartment.setSize(comp.getSize()); childCompartment.setConstant(comp.getConstant()); } } childCompartment.setId(childComponentID + "__" + compartID.split("__")[1]); compartmentIDSet.add(childCompartment.getId()); variableToValueMap.put(childCompartment.getId(), childCompartment.getSize()); variableToIsConstantMap.put(childCompartment.getId(), childCompartment.getConstant()); //reactions that change and thus need their propensities re-evaluated HashSet<String> reactionsToAdjust = new HashSet<String>(); //determine new component location //choose a random direction and place the component adjacent to the parent //0 = left, 1 = right, 2 = above, 3 = below int randomDirection = (int) (randomNumberGenerator.nextDouble() * 8.0); Point parentLocation = componentToLocationMap.get(parentComponentID); Point childLocation = (Point) parentLocation.clone(); //MOVE COMPONENTS //this places the child and shuffles others around as needed moveComponent(parentComponentID, childComponentID, parentLocation, childLocation, randomDirection, reactionsToAdjust); //DUPLICATE VARIABLES and alter them to coincide with the new ID HashSet<String> childComponentVariableSet = new HashSet<String>(); if (componentToVariableSetMap.containsKey(parentComponentID) == false) componentToVariableSetMap.put(parentComponentID, new HashSet<String>()); for (String parentVariableID : componentToVariableSetMap.get(parentComponentID)) { String childVariableID = parentVariableID.replace(parentComponentID, childComponentID); childComponentVariableSet.add(childVariableID); //this means it's a species if (speciesIDSet.contains(parentVariableID)) { //if it's a promoter, double it first, as it's a dna-based species if (model.getSpecies(parentVariableID).isSetSBOTerm() && model.getSpecies(parentVariableID).getSBOTerm() == GlobalConstants.SBO_PROMOTER_SPECIES) variableToValueMap.put(parentVariableID, variableToValueMap.get(parentVariableID) * 2); //duplicate species into the model Species newSpecies = model.getSpecies(parentVariableID).clone(); newSpecies.setId(childVariableID); newSpecies.setMetaId(childVariableID); model.addSpecies(newSpecies); if (speciesToHasOnlySubstanceUnitsMap.get(parentVariableID) == false) speciesToCompartmentSizeMap.put(childVariableID, speciesToCompartmentSizeMap.get(parentVariableID)); if (speciesToHasOnlySubstanceUnitsMap.get(parentVariableID) == false) speciesToCompartmentNameMap.put(childVariableID, speciesToCompartmentNameMap.get(parentVariableID)); //the speciesToAffectedReactionSetMap gets filled-in later speciesToAffectedReactionSetMap.put(childVariableID, new HashSet<String>(20)); speciesToIsBoundaryConditionMap.put(childVariableID, speciesToIsBoundaryConditionMap.get(parentVariableID)); variableToIsConstantMap.put(childVariableID, variableToIsConstantMap.get(parentVariableID)); speciesToHasOnlySubstanceUnitsMap.put(childVariableID, speciesToHasOnlySubstanceUnitsMap.get(parentVariableID)); speciesIDSet.add(childVariableID); //divide the parent species amount by two by default //unless there is an event assignment or if the species is constant/bc if (variableToIsConstantMap.get(parentVariableID) == true || speciesToIsBoundaryConditionMap.get(parentVariableID)) { variableToValueMap.put(childVariableID, variableToValueMap.get(parentVariableID)); } else { //go through the event assignments to find ones that affect this particular species //this is used to determine, via species quantity conservation, how much the daughter cell gets HashSet<Object> assignmentSetMap = this.eventToAssignmentSetMap.get(eventID); boolean setInAssignment = false; for (Object assignment : assignmentSetMap) { if (((EventAssignment) assignment).getVariable().equals(parentVariableID)) { double totalAmount = variableToValueMap.get(parentVariableID); double afterEventAmount = evaluateExpressionRecursive(((EventAssignment) assignment).getMath()); double childAmount = totalAmount - afterEventAmount; variableToValueMap.put(childVariableID, childAmount); variableToValueMap.put(parentVariableID, afterEventAmount); setInAssignment = true; } } if (setInAssignment == false) { variableToValueMap.put(childVariableID, (int) ((variableToValueMap.get(parentVariableID) / 2) + 1)); variableToValueMap.put(parentVariableID, (int) ((variableToValueMap.get(parentVariableID) / 2) + 1)); } } } //this means it's a parameter else { variableToValueMap.put(childVariableID, variableToValueMap.get(parentVariableID)); } } componentToVariableSetMap.put(childComponentID, childComponentVariableSet); //DUPLICATE REACTIONS and alter them to coincide with the new ID HashSet<String> childReactionSet = new HashSet<String>(); if (componentToReactionSetMap.containsKey(parentComponentID) == false) componentToReactionSetMap.put(parentComponentID, new HashSet<String>()); for (String parentReactionID : componentToReactionSetMap.get(parentComponentID)) { String parentReactionFormula = ""; String childReactionID = parentReactionID.replace(parentComponentID, childComponentID); childReactionSet.add(childReactionID); parentReactionFormula = reactionToFormulaMap.get(parentReactionID).toFormula(); ASTNode childFormulaNode = reactionToFormulaMap.get(parentReactionID).clone(); String thing = ""; try { String childReactionFormula = parentReactionFormula.replace(parentComponentID, childComponentID); if (parentReactionID.contains("MembraneDiffusion")) { String parentRowCol = "ROW" + (int) parentLocation.getX() + "_" + "COL" + (int) parentLocation.getY(); String childRowCol = "ROW" + (int) childLocation.getX() + "_" + "COL" + (int) childLocation.getY(); //formulas as ASTNodes can't have negative numbers in species IDs parentRowCol = parentRowCol.replace("ROW-", "ROW_negative_"); parentRowCol = parentRowCol.replace("COL-", "COL_negative_"); childRowCol = childRowCol.replace("ROW-", "ROW_negative_"); childRowCol = childRowCol.replace("COL-", "COL_negative_"); if (childReactionFormula.contains("ROW") && childReactionFormula.contains("COL")) { alterNode(childFormulaNode, parentRowCol, childRowCol); } else { String childSpeciesID = ((String[])childReactionFormula.split("\\*"))[1]; String underlyingSpeciesID = childSpeciesID.split("__")[childSpeciesID.split("__").length - 1]; //we want the parent's kmdiff parameter, as the child's doesn't exist childReactionFormula = childReactionFormula.replace(childSpeciesID + "__kmdiff", parentComponentID + "__" + underlyingSpeciesID + "__kmdiff"); thing = childReactionFormula; childFormulaNode = ASTNode.parseFormula(childReactionFormula); } } else childFormulaNode = ASTNode.parseFormula(childReactionFormula); } catch (ParseException e) { System.err.println(thing); e.printStackTrace(); } reactionToSpeciesAndStoichiometrySetMap.put(childReactionID, new HashSet<StringDoublePair>()); reactionToReactantStoichiometrySetMap.put(childReactionID, new HashSet<StringDoublePair>()); boolean notEnoughMoleculesFlag = false; if (reactionToSpeciesAndStoichiometrySetMap.containsKey(parentReactionID) == false) reactionToSpeciesAndStoichiometrySetMap.put(parentReactionID, new HashSet<StringDoublePair>()); //add species/stoichiometry pairs for this new reaction for (StringDoublePair parentSpeciesAndStoichiometry : reactionToSpeciesAndStoichiometrySetMap.get(parentReactionID)) { double childStoichiometry = parentSpeciesAndStoichiometry.doub; String childSpeciesID = ""; if (parentSpeciesAndStoichiometry.string.contains("ROW") && parentSpeciesAndStoichiometry.string.contains("COL")) { String parentRowCol = "ROW" + (int) parentLocation.getX() + "_" + "COL" + (int) parentLocation.getY(); String childRowCol = "ROW" + (int) childLocation.getX() + "_" + "COL" + (int) childLocation.getY(); childSpeciesID = parentSpeciesAndStoichiometry.string.replace(parentRowCol, childRowCol); } else childSpeciesID = parentSpeciesAndStoichiometry.string.replace(parentComponentID, childComponentID); reactionToSpeciesAndStoichiometrySetMap.get(childReactionID) .add(new StringDoublePair(childSpeciesID, childStoichiometry)); if (speciesToAffectedReactionSetMap.containsKey(parentSpeciesAndStoichiometry.string)) speciesToAffectedReactionSetMap.get(childSpeciesID).add(childReactionID); //make sure there are enough molecules for this species //(if the molecule is a reactant -- if it's a product then it's being added) if (variableToValueMap.get(childSpeciesID) < childStoichiometry && reactionToReactantStoichiometrySetMap.get(parentReactionID).contains(childSpeciesID)) notEnoughMoleculesFlag = true; } if (reactionToReactantStoichiometrySetMap.containsKey(parentReactionID) == false) reactionToReactantStoichiometrySetMap.put(parentReactionID, new HashSet<StringDoublePair>()); //add reactant/stoichiometry pairs for this new reactions for (StringDoublePair parentReactantAndStoichiometry : reactionToReactantStoichiometrySetMap.get(parentReactionID)) { double childStoichiometry = parentReactantAndStoichiometry.doub; String childSpeciesID = ""; if (parentReactantAndStoichiometry.string.contains("ROW") && parentReactantAndStoichiometry.string.contains("COL")) { String parentRowCol = "ROW" + (int) parentLocation.getX() + "_" + "COL" + (int) parentLocation.getY(); String childRowCol = "ROW" + (int) childLocation.getX() + "_" + "COL" + (int) childLocation.getY(); childSpeciesID = parentReactantAndStoichiometry.string.replace(parentRowCol, childRowCol); } else childSpeciesID = parentReactantAndStoichiometry.string.replace(parentComponentID, childComponentID); reactionToReactantStoichiometrySetMap.get(childReactionID).add( new StringDoublePair(childSpeciesID, childStoichiometry)); } reactionToFormulaMap.put(childReactionID, childFormulaNode); double propensity; if (notEnoughMoleculesFlag == true) propensity = 0.0; else { //calculate propensity propensity = evaluateExpressionRecursive(childFormulaNode); if (propensity < minPropensity && propensity > 0) minPropensity = propensity; if (propensity > maxPropensity) maxPropensity = propensity; totalPropensity += propensity; } reactionToPropensityMap.put(childReactionID, propensity); } componentToReactionSetMap.put(childComponentID, childReactionSet); reactionsToAdjust.addAll(componentToReactionSetMap.get(parentComponentID)); //update propensities for the parent reactions, as their species values may have changed updatePropensities(reactionsToAdjust); updateAfterDynamicChanges(); //DUPLICATE EVENTS HashSet<String> childEventSet = new HashSet<String>(); if (componentToEventSetMap.containsKey(parentComponentID) == false) componentToEventSetMap.put(parentComponentID, new HashSet<String>()); for (String parentEventID : componentToEventSetMap.get(parentComponentID)) { String childEventID = parentEventID.replace(parentComponentID, childComponentID); untriggeredEventSet.add(childEventID); childEventSet.add(childEventID); //hashmaps that allow for access to event information from the event's id eventToPriorityMap.put(childEventID, eventToPriorityMap.get(parentEventID)); eventToDelayMap.put(childEventID, eventToDelayMap.get(parentEventID).clone()); eventToHasDelayMap.put(childEventID, eventToHasDelayMap.get(parentEventID)); eventToTriggerPersistenceMap.put(childEventID, eventToTriggerPersistenceMap.get(parentEventID)); eventToUseValuesFromTriggerTimeMap.put(childEventID, eventToUseValuesFromTriggerTimeMap.get(parentEventID)); eventToTriggerMap.put(childEventID, eventToTriggerMap.get(parentEventID).clone()); eventToTriggerInitiallyTrueMap.put(childEventID, eventToTriggerInitiallyTrueMap.get(parentEventID)); eventToPreviousTriggerValueMap.put(childEventID, eventToTriggerInitiallyTrueMap.get(childEventID)); //symmetric division creates two new things essentially: there are two children, not a parent and child //untrigger the parent division event if (symmetry.equals("symmetric")) { //untrigger the event untriggeredEventSet.add(parentEventID); eventToPreviousTriggerValueMap.put(parentEventID, eventToTriggerInitiallyTrueMap.get(parentEventID)); //remove the event from the queue //copy the triggered event queue -- except the parent event PriorityQueue<EventToFire> newTriggeredEventQueue = new PriorityQueue<EventToFire>(5, eventComparator); while (triggeredEventQueue.size() > 0) { EventToFire event = triggeredEventQueue.poll(); EventToFire eventToAdd = new EventToFire(event.eventID, (HashSet<Object>) event.eventAssignmentSet.clone(), event.fireTime); if (parentEventID.equals(event.eventID) == false) newTriggeredEventQueue.add(eventToAdd); } triggeredEventQueue = newTriggeredEventQueue; } HashSet<Object> assignmentSetMap = new HashSet<Object>(); //copy event assignments for the new child event for (Object assignment : eventToAssignmentSetMap.get(parentEventID)) { String variableID = ((EventAssignment) assignment).getVariable(); if (variableToEventSetMap.containsKey(variableID) == false) variableToEventSetMap.put(variableID, new HashSet<String>()); variableToEventSetMap.get(variableID).add(childEventID); EventAssignment ea = ((EventAssignment)assignment).clone(); ea.setVariable(((EventAssignment)assignment).getVariable() .replace(parentComponentID, childComponentID)); try { // ea.setMath(ASTNode.parseFormula(((EventAssignment)assignment).getMath().toFormula() // .replace(parentComponentID, childComponentID))); ea.setFormula(((EventAssignment)assignment).getMath().toFormula() .replace(parentComponentID, childComponentID)); } catch (ParseException e) { e.printStackTrace(); } assignmentSetMap.add(ea); if (speciesToAffectedReactionSetMap.containsKey(variableID)) { eventToAffectedReactionSetMap.put(childEventID, new HashSet<String>()); eventToAffectedReactionSetMap.get(childEventID).addAll( speciesToAffectedReactionSetMap.get(variableID)); } } eventToAssignmentSetMap.put(childEventID, assignmentSetMap); } componentToEventSetMap.put(childComponentID, childEventSet); // System.err.println("REACTIONS"); // for (String reactionID : reactionToPropensityMap.keySet()) { // if (//reactionID.contains("_of_") || // reactionID.contains("Diffusion") // System.err.println(reactionID); // System.err.println(); // System.err.println("VARIABLES"); // for (String variableID : this.speciesIDSet) { //// if (//variableID.contains("_of_") || //// variableID.contains("ROW") // System.err.println(variableID + " " + variableToValueMap.get(variableID)); // for (String event : this.eventToAssignmentSetMap.keySet()) { // System.err.println(event); // System.err.println(this.eventToAssignmentSetMap.get(event)); // System.err.println(); // System.err.println("duplicate finished"); } /** * simulator-specific component erasure stuff * @param reactionIDs */ protected abstract void eraseComponentFurther(HashSet<String> reactionIDs); /** * erases all traces of a component (ie, its reactions and species and parameters, etc) and updates data structures * and the simulation state * used for "death" events in dynamic models * * @param componentID */ protected HashSet<String> eraseComponent(String componentID) { for (String reactionID : componentToReactionSetMap.get(componentID)) { reactionToPropensityMap.remove(reactionID); reactionToSpeciesAndStoichiometrySetMap.remove(reactionID); reactionToReactantStoichiometrySetMap.remove(reactionID); reactionToFormulaMap.remove(reactionID); } //simulator-specific data structure erasal eraseComponentFurther(componentToReactionSetMap.get(componentID)); for (String variableID : componentToVariableSetMap.get(componentID)) { variableToEventSetMap.remove(variableID); if (variableToAffectedAssignmentRuleSetMap != null) variableToAffectedAssignmentRuleSetMap.remove(variableID); if (variableToIsInAssignmentRuleMap != null) variableToIsInAssignmentRuleMap.remove(variableID); if (variableToAffectedConstraintSetMap != null) variableToAffectedConstraintSetMap.remove(variableID); if (variableToIsInConstraintMap != null) variableToIsInConstraintMap.remove(variableID); variableToIsConstantMap.remove(variableID); variableToValueMap.remove(variableID); speciesToIsBoundaryConditionMap.remove(variableID); speciesToHasOnlySubstanceUnitsMap.remove(variableID); speciesToCompartmentNameMap.remove(variableID); speciesToCompartmentSizeMap.remove(variableID); speciesIDSet.remove(variableID); } String compartmentIDToRemove = ""; for (String compartmentID : compartmentIDSet) if (compartmentID.contains(componentID + "__")) compartmentIDToRemove = compartmentID; compartmentIDSet.remove(compartmentIDToRemove); // for (String eventID : componentToEventSetMap.get(componentID)) { // triggeredEventQueue.remove(eventID); // untriggeredEventSet.remove(eventID); // eventToPriorityMap.remove(eventID); // eventToDelayMap.remove(eventID); // eventToHasDelayMap.remove(eventID); // eventToTriggerPersistenceMap.remove(eventID); // eventToUseValuesFromTriggerTimeMap.remove(eventID); // eventToTriggerMap.remove(eventID); // eventToTriggerInitiallyTrueMap.remove(eventID); // eventToPreviousTriggerValueMap.remove(eventID); // eventToAssignmentSetMap.remove(eventID); // eventToAffectedReactionSetMap.remove(eventID); HashSet<String> deadEvents = new HashSet<String>(); deadEvents.addAll(componentToEventSetMap.get(componentID)); componentToLocationMap.remove(componentID); componentToReactionSetMap.remove(componentID); componentToVariableSetMap.remove(componentID); componentToEventSetMap.remove(componentID); updateAfterDynamicChanges(); return deadEvents; } /** * calculates an expression using a recursive algorithm * * @param node the AST with the formula * @return the evaluated expression */ protected double evaluateExpressionRecursive(ASTNode node) { //these if/else-ifs before the else are leaf conditions //logical constant, logical operator, or relational operator if (node.isBoolean()) { switch (node.getType()) { case CONSTANT_TRUE: return 1.0; case CONSTANT_FALSE: return 0.0; case LOGICAL_NOT: return getDoubleFromBoolean(!(getBooleanFromDouble(evaluateExpressionRecursive(node.getLeftChild())))); case LOGICAL_AND: { boolean andResult = true; for (int childIter = 0; childIter < node.getChildCount(); ++childIter) andResult = andResult && getBooleanFromDouble(evaluateExpressionRecursive(node.getChild(childIter))); return getDoubleFromBoolean(andResult); } case LOGICAL_OR: { boolean orResult = false; for (int childIter = 0; childIter < node.getChildCount(); ++childIter) orResult = orResult || getBooleanFromDouble(evaluateExpressionRecursive(node.getChild(childIter))); return getDoubleFromBoolean(orResult); } case LOGICAL_XOR: { boolean xorResult = getBooleanFromDouble(evaluateExpressionRecursive(node.getChild(0))); for (int childIter = 1; childIter < node.getChildCount(); ++childIter) xorResult = xorResult ^ getBooleanFromDouble(evaluateExpressionRecursive(node.getChild(childIter))); return getDoubleFromBoolean(xorResult); } case RELATIONAL_EQ: return getDoubleFromBoolean( evaluateExpressionRecursive(node.getLeftChild()) == evaluateExpressionRecursive(node.getRightChild())); case RELATIONAL_NEQ: return getDoubleFromBoolean( evaluateExpressionRecursive(node.getLeftChild()) != evaluateExpressionRecursive(node.getRightChild())); case RELATIONAL_GEQ: return getDoubleFromBoolean( evaluateExpressionRecursive(node.getLeftChild()) >= evaluateExpressionRecursive(node.getRightChild())); case RELATIONAL_LEQ: return getDoubleFromBoolean( evaluateExpressionRecursive(node.getLeftChild()) <= evaluateExpressionRecursive(node.getRightChild())); case RELATIONAL_GT: return getDoubleFromBoolean( evaluateExpressionRecursive(node.getLeftChild()) > evaluateExpressionRecursive(node.getRightChild())); case RELATIONAL_LT: return getDoubleFromBoolean( evaluateExpressionRecursive(node.getLeftChild()) < evaluateExpressionRecursive(node.getRightChild())); } } //if it's a mathematical constant else if (node.isConstant()) { switch (node.getType()) { case CONSTANT_E: return Math.E; case CONSTANT_PI: return Math.PI; } } //if it's a number else if (node.isNumber()) return node.getReal(); //if it's a user-defined variable //eg, a species name or global/local parameter else if (node.isName()) { String name = node.getName().replace("_negative_","-"); if (node.getType().equals(org.sbml.jsbml.ASTNode.Type.NAME_TIME)) { return currentTime; } //if it's a reaction id return the propensity else if (reactionToPropensityMap.keySet().contains(node.getName())) { return reactionToPropensityMap.get(node.getName()); } else { double value; if (this.speciesToHasOnlySubstanceUnitsMap.containsKey(name) && this.speciesToHasOnlySubstanceUnitsMap.get(name) == false) { value = (variableToValueMap.get(name) / variableToValueMap.get(speciesToCompartmentNameMap.get(name))); } else value = variableToValueMap.get(name); return value; } } //operators/functions with two children else { ASTNode leftChild = node.getLeftChild(); ASTNode rightChild = node.getRightChild(); switch (node.getType()) { case PLUS: { double sum = 0.0; for (int childIter = 0; childIter < node.getChildCount(); ++childIter) sum += evaluateExpressionRecursive(node.getChild(childIter)); return sum; } case MINUS: { double sum = evaluateExpressionRecursive(leftChild); for (int childIter = 1; childIter < node.getChildCount(); ++childIter) sum -= evaluateExpressionRecursive(node.getChild(childIter)); return sum; } case TIMES: { double product = 1.0; for (int childIter = 0; childIter < node.getChildCount(); ++childIter) product *= evaluateExpressionRecursive(node.getChild(childIter)); return product; } case DIVIDE: return (evaluateExpressionRecursive(leftChild) / evaluateExpressionRecursive(rightChild)); case FUNCTION_POWER: return (FastMath.pow(evaluateExpressionRecursive(leftChild), evaluateExpressionRecursive(rightChild))); case FUNCTION: { //use node name to determine function //i'm not sure what to do with completely user-defined functions, though String nodeName = node.getName(); //generates a uniform random number between the upper and lower bound if (nodeName.equals("uniform")) { double leftChildValue = evaluateExpressionRecursive(node.getLeftChild()); double rightChildValue = evaluateExpressionRecursive(node.getRightChild()); double lowerBound = FastMath.min(leftChildValue, rightChildValue); double upperBound = FastMath.max(leftChildValue, rightChildValue); return prng.nextDouble(lowerBound, upperBound); } else if (nodeName.equals("exponential")) { return prng.nextExponential(evaluateExpressionRecursive(node.getLeftChild()), 1); } else if (nodeName.equals("gamma")) { return prng.nextGamma(1, evaluateExpressionRecursive(node.getLeftChild()), evaluateExpressionRecursive(node.getRightChild())); } else if (nodeName.equals("chisq")) { return prng.nextChiSquare((int) evaluateExpressionRecursive(node.getLeftChild())); } else if (nodeName.equals("lognormal")) { return prng.nextLogNormal(evaluateExpressionRecursive(node.getLeftChild()), evaluateExpressionRecursive(node.getRightChild())); } else if (nodeName.equals("laplace")) { //function doesn't exist in current libraries return 0; } else if (nodeName.equals("cauchy")) { return prng.nextLorentzian(0, evaluateExpressionRecursive(node.getLeftChild())); } else if (nodeName.equals("poisson")) { return prng.nextPoissonian(evaluateExpressionRecursive(node.getLeftChild())); } else if (nodeName.equals("binomial")) { return prng.nextBinomial(evaluateExpressionRecursive(node.getLeftChild()), (int) evaluateExpressionRecursive(node.getRightChild())); } else if (nodeName.equals("bernoulli")) { return prng.nextBinomial(evaluateExpressionRecursive(node.getLeftChild()), 1); } else if (nodeName.equals("normal")) { return prng.nextGaussian(evaluateExpressionRecursive(node.getLeftChild()), evaluateExpressionRecursive(node.getRightChild())); } else if (nodeName.equals("get2DArrayElement")) { // int leftIndex = node.getChild(1).getInteger(); // int rightIndex = node.getChild(2).getInteger(); // String speciesName = "ROW" + leftIndex + "_COL" + rightIndex + "__" + node.getChild(0).getName(); // //check bounds // //if species exists, return its value/amount // if (variableToValueMap.containsKey(speciesName)) // return variableToValueMap.get(speciesName); } else if (nodeName.equals("neighborQuantityLeftFull")) { int leftIndex = (int) evaluateExpressionRecursive(node.getChild(1)); int rightIndex = (int) evaluateExpressionRecursive(node.getChild(2)); String specName = node.getChild(0).getName().split("__")[node.getChild(0).getName().split("__").length - 1]; String speciesName = "ROW" + leftIndex + "_COL" + (rightIndex - 1) + "__" + specName; if (variableToValueMap.containsKey(speciesName)) return variableToValueMap.get(speciesName); else return 1; } else if (nodeName.equals("neighborQuantityRightFull")) { int leftIndex = (int) evaluateExpressionRecursive(node.getChild(1)); int rightIndex = (int) evaluateExpressionRecursive(node.getChild(2)); String specName = node.getChild(0).getName().split("__")[node.getChild(0).getName().split("__").length - 1]; String speciesName = "ROW" + leftIndex + "_COL" + (rightIndex + 1) + "__" + specName; if (variableToValueMap.containsKey(speciesName)) { return variableToValueMap.get(speciesName); } else return 1; } else if (nodeName.equals("neighborQuantityAboveFull")) { int leftIndex = (int) evaluateExpressionRecursive(node.getChild(1)); int rightIndex = (int) evaluateExpressionRecursive(node.getChild(2)); String specName = node.getChild(0).getName().split("__")[node.getChild(0).getName().split("__").length - 1]; String speciesName = "ROW" + (leftIndex - 1) + "_COL" + rightIndex + "__" + specName; if (variableToValueMap.containsKey(speciesName)) return variableToValueMap.get(speciesName); else return 1; } else if (nodeName.equals("neighborQuantityBelowFull")) { int leftIndex = (int) evaluateExpressionRecursive(node.getChild(1)); int rightIndex = (int) evaluateExpressionRecursive(node.getChild(2)); String specName = node.getChild(0).getName().split("__")[node.getChild(0).getName().split("__").length - 1]; String speciesName = "ROW" + (leftIndex + 1) + "_COL" + rightIndex + "__" + specName; if (variableToValueMap.containsKey(speciesName)) return variableToValueMap.get(speciesName); else return 1; } else if (nodeName.equals("getCompartmentLocationX")) { return this.componentToLocationMap.get(node.getChild(0).getName().split("__")[0]).getX(); } else if (nodeName.equals("getCompartmentLocationY")) { return this.componentToLocationMap.get(node.getChild(0).getName().split("__")[0]).getY(); } break; } case FUNCTION_ABS: return FastMath.abs(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_ARCCOS: return FastMath.acos(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_ARCSIN: return FastMath.asin(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_ARCTAN: return FastMath.atan(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_CEILING: return FastMath.ceil(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_COS: return FastMath.cos(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_COSH: return FastMath.cosh(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_EXP: return FastMath.exp(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_FLOOR: return FastMath.floor(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_LN: return FastMath.log(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_LOG: return FastMath.log10(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_SIN: return FastMath.sin(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_SINH: return FastMath.sinh(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_TAN: return FastMath.tan(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_TANH: return FastMath.tanh(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_PIECEWISE: { //loop through child triples //if child 1 is true, return child 0, else return child 2 for (int childIter = 0; childIter < node.getChildCount(); childIter += 3) { if ((childIter + 1) < node.getChildCount() && getBooleanFromDouble(evaluateExpressionRecursive(node.getChild(childIter + 1)))) { return evaluateExpressionRecursive(node.getChild(childIter)); } else if ((childIter + 2) < node.getChildCount()) { return evaluateExpressionRecursive(node.getChild(childIter + 2)); } } return 0; } case FUNCTION_ROOT: return FastMath.pow(evaluateExpressionRecursive(node.getRightChild()), 1 / evaluateExpressionRecursive(node.getLeftChild())); case FUNCTION_SEC: return Fmath.sec(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_SECH: return Fmath.sech(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_FACTORIAL: return Fmath.factorial(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_COT: return Fmath.cot(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_COTH: return Fmath.coth(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_CSC: return Fmath.csc(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_CSCH: return Fmath.csch(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_DELAY: //NOT PLANNING TO SUPPORT THIS return 0; case FUNCTION_ARCTANH: return Fmath.atanh(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_ARCSINH: return Fmath.asinh(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_ARCCOSH: return Fmath.acosh(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_ARCCOT: return Fmath.acot(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_ARCCOTH: return Fmath.acoth(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_ARCCSC: return Fmath.acsc(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_ARCCSCH: return Fmath.acsch(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_ARCSEC: return Fmath.asec(evaluateExpressionRecursive(node.getChild(0))); case FUNCTION_ARCSECH: return Fmath.asech(evaluateExpressionRecursive(node.getChild(0))); } //end switch } return 0.0; } /** * adds species and reactions to the model that are implicit in arrays * basically, it takes an arrayed model and flattens it * * this also applies stoichiometry amplification at the end (if needed) * i did it this way to avoid another read/write of the model, as i have to * do it within the simulator in order to use jsbml instead of libsbml */ public static void expandArrays(String filename, double stoichAmpValue) { //open the sbml file for reading/writing SBMLReader reader = new SBMLReader(); SBMLDocument document = null; try { document = reader.readSBML(filename); } catch (Exception e) { e.printStackTrace(); return; } Model model = document.getModel(); boolean arraysExist = false; //ARRAYED SPECIES BUSINESS //create all new species that are implicit in the arrays and put them into the model ArrayList<Species> speciesToAdd = new ArrayList<Species>(); ArrayList<String> speciesToRemove = new ArrayList<String>(); HashMap<String, Boolean> speciesToIsArrayedMap = new HashMap<String, Boolean>(); HashMap<String, SpeciesDimensions> arrayedSpeciesToDimensionsMap = new HashMap<String, SpeciesDimensions>(); for (Species species : model.getListOfSpecies()) { String speciesID = species.getId(); //check to see if the species is arrayed if (stripAnnotation(species.getAnnotationString()).contains("array:array")) { arraysExist = true; speciesToIsArrayedMap.put(speciesID, true); speciesToRemove.add(speciesID); int numRowsLower = 0; int numColsLower = 0; int numRowsUpper = 0; int numColsUpper = 0; String[] annotationString = stripAnnotation(species.getAnnotationString()).split("="); numColsLower = Integer.valueOf(((String[])(annotationString[1].split(" ")))[0].replace("\"","")); numColsUpper = Integer.valueOf(((String[])(annotationString[2].split(" ")))[0].replace("\"","")); numRowsLower = Integer.valueOf(((String[])(annotationString[3].split(" ")))[0].replace("\"","")); numRowsUpper = Integer.valueOf(((String[])(annotationString[4].split(" ")))[0].replace("\"","")); SpeciesDimensions speciesDimensions = new SpeciesDimensions(numRowsLower, numRowsUpper, numColsLower, numColsUpper); arrayedSpeciesToDimensionsMap.put(speciesID, speciesDimensions); //loop through all species in the array //prepend the row/col information to create a new ID for (int row = numRowsLower; row <= numRowsUpper; ++row) { for (int col = numColsLower; col <= numColsUpper; ++col) { speciesID = "ROW" + row + "_COL" + col + "__" + species.getId(); Species newSpecies = new Species(); newSpecies = species.clone(); newSpecies.setMetaId(speciesID); newSpecies.setId(speciesID); newSpecies.setAnnotation(new Annotation()); speciesToAdd.add(newSpecies); } } } else speciesToIsArrayedMap.put(speciesID, false); } //end species for loop //add new row/col species to the model for (Species species : speciesToAdd) { model.addSpecies(species); } //ARRAYED EVENTS BUSINESS ArrayList<String> eventsToRemove = new ArrayList<String>(); ArrayList<Event> eventsToAdd = new ArrayList<Event>(); for (Event event : model.getListOfEvents()) { if (stripAnnotation(event.getAnnotationString()).contains("array")) { arraysExist = true; eventsToRemove.add(event.getId()); String annotationString = stripAnnotation(event.getAnnotationString()).replace("<annotation>",""). replace("</annotation>","").replace("\"",""); String[] splitAnnotation = annotationString.split("array:"); ArrayList<String> eventCompartments = new ArrayList<String>(); splitAnnotation[splitAnnotation.length - 2] = ((String[])splitAnnotation[splitAnnotation.length - 2].split("xmlns:"))[0]; for (int i = 2; i < splitAnnotation.length; ++i) { String compartmentID = ((String[])splitAnnotation[i].split("="))[0]; eventCompartments.add(compartmentID); } //loop through all compartments and create an event for each one for (String compartmentID : eventCompartments) { Event newEvent = new Event(); newEvent.setVersion(event.getVersion()); newEvent.setLevel(event.getLevel()); newEvent.setId(compartmentID + "__" + event.getId()); newEvent.setMetaId(compartmentID + "__" + event.getId()); event.getTrigger().getMath().updateVariables(); newEvent.setTrigger(event.getTrigger().clone()); // //at this point, the formula has something like neighborQuantity(Species1) // //this needs to become neighborQuantity(Species1, CompartmentLocationX(Comp1), CompartmentLocationY(Comp1)) // if (newEvent.getTrigger().getMath().toFormula().contains("neighborQuantity")) { // String triggerMath = newEvent.getTrigger().getMath().toFormula(); // ArrayList<ASTNode> nqNodes = new ArrayList<ASTNode>(); // this.getSatisfyingNodesLax(newEvent.getTrigger().getMath(), "neighborQuantity", nqNodes); // //loop through all neighbor quantity nodes in the trigger formula // for (ASTNode nqNode : nqNodes) { // String direction = ""; // if (triggerMath.contains("QuantityLeft")) // direction = "Left"; // else if (triggerMath.contains("QuantityRight")) // direction = "Right"; // else if (triggerMath.contains("QuantityAbove")) // direction = "Above"; // else // direction = "Below"; // String speciesID = nqNode.toFormula().split( // "neighborQuantity" + direction)[1].replace("(","").replace(")",""); // try { // ASTNode newFormula = ASTNode.parseFormula( // "neighborQuantity" + direction + "Full(" + compartmentID + "__" + speciesID + // ", getCompartmentLocationX(" + compartmentID + "__Cell" + // "), getCompartmentLocationY(" + compartmentID + "__Cell" + "))"); // for (int i = 0; i < ((ASTNode) nqNode.getParent()).getChildCount(); ++i) { // if (((ASTNode) nqNode.getParent().getChildAt(i)).isFunction() && // ((ASTNode) nqNode.getParent().getChildAt(i)).getVariable().toString() // .contains("neighborQuantity" + direction)) { // ((ASTNode) nqNode.getParent()).replaceChild(i, newFormula); // break; // } catch (ParseException e) { // e.printStackTrace(); if (event.isSetPriority()) newEvent.setPriority(event.getPriority().clone()); if (event.isSetDelay()) { newEvent.setDelay(event.getDelay().clone()); } newEvent.setUseValuesFromTriggerTime(event.getUseValuesFromTriggerTime()); for (EventAssignment eventAssignment : event.getListOfEventAssignments()) { EventAssignment ea = eventAssignment.clone(); ea.setMath(eventAssignment.getMath().clone()); ea.setVariable(eventAssignment.getVariable()); newEvent.addEventAssignment(ea); } for (EventAssignment eventAssignment : newEvent.getListOfEventAssignments()) { eventAssignment.setVariable(compartmentID + "__" + eventAssignment.getVariable()); //prepends the compartment ID to all variables in the event assignment prependToVariableNodes(eventAssignment.getMath(), compartmentID + "__", model); } eventsToAdd.add(newEvent); } } } for (Event eventToAdd : eventsToAdd) { model.addEvent(eventToAdd); } //ARRAYED REACTION BUSINESS //if a reaction has arrayed species //new reactions that are implicit are created and added to the model ArrayList<Reaction> reactionsToAdd = new ArrayList<Reaction>(); ArrayList<String> reactionsToRemove = new ArrayList<String>(); for (Reaction reaction : model.getListOfReactions()) { String reactionID = reaction.getId(); ArrayList<Integer> membraneDiffusionRows = new ArrayList<Integer>(); ArrayList<Integer> membraneDiffusionCols = new ArrayList<Integer>(); ArrayList<String> membraneDiffusionCompartments = new ArrayList<String>(); //MEMBRANE DIFFUSION REACTIONS //if it's a membrane diffusion reaction it'll have the appropriate locations as an annotation //so parse them and store them in the above arraylists if (reactionID.contains("MembraneDiffusion")) { arraysExist = true; String annotationString = stripAnnotation(reaction.getAnnotationString()).replace("<annotation>",""). replace("</annotation>","").replace("\"",""); String[] splitAnnotation = annotationString.split("array:"); if (splitAnnotation.length <= 1) { continue; } splitAnnotation[splitAnnotation.length - 2] = ((String[])splitAnnotation[splitAnnotation.length - 2].split("xmlns:"))[0]; for (int i = 2; i < splitAnnotation.length; ++i) { String compartmentID = ((String[])splitAnnotation[i].split("="))[0]; String row = ((String[])((String[])splitAnnotation[i].split(" ")[0].split("="))[1].split(","))[0].replace("(",""); String col = ((String[])((String[])splitAnnotation[i].split(" ")[0].split("="))[1].split(","))[1].replace(")",""); membraneDiffusionRows.add(Integer.valueOf(row.trim())); membraneDiffusionCols.add(Integer.valueOf(col.trim())); membraneDiffusionCompartments.add(compartmentID); } int membraneDiffusionIndex = 0; reactionsToRemove.add(reaction.getId()); reaction.setAnnotation(new Annotation()); //loop through all appropriate row/col pairs and create a membrane diffusion reaction for each one for (String compartmentID : membraneDiffusionCompartments) { int row = membraneDiffusionRows.get(membraneDiffusionIndex); int col = membraneDiffusionCols.get(membraneDiffusionIndex); //create a new reaction and set the ID Reaction newReaction = new Reaction(); newReaction = reaction.clone(); newReaction.setListOfReactants(new ListOf<SpeciesReference>()); newReaction.setListOfProducts(new ListOf<SpeciesReference>()); newReaction.setListOfModifiers(new ListOf<ModifierSpeciesReference>()); newReaction.setId(compartmentID + "__" + reactionID); newReaction.setMetaId(compartmentID + "__" + reactionID); newReaction.setReversible(true); newReaction.setFast(false); newReaction.setCompartment(reaction.getCompartment()); //alter the kinetic law to so that it has the correct indexes as children for the //get2DArrayElement function //get the nodes to alter (that are arguments for the get2DArrayElement method) ArrayList<ASTNode> get2DArrayElementNodes = new ArrayList<ASTNode>(); getSatisfyingNodes(newReaction.getKineticLaw().getMath(), "get2DArrayElement", get2DArrayElementNodes); boolean reactantBool = false; //replace the get2darrayelement stuff with the proper explicit species/parameters for (ASTNode node : get2DArrayElementNodes) { if (node.getLeftChild().getName().contains("kmdiff")) { String parameterName = node.getLeftChild().getName(); //see if the species-specific one exists //if it doesn't, use the default //you'll need to parse the species name from the reaction id, probably String speciesID = reactionID.replace("MembraneDiffusion_",""); if (model.getParameter(compartmentID + "__" + speciesID + "__" + parameterName) == null) node.setVariable(model.getParameter(parameterName)); else node.setVariable(model.getParameter(compartmentID + "__" + speciesID + "__" + parameterName)); for (int i = 0; i < node.getChildCount(); ++i) node.removeChild(i); for (int i = 0; i < node.getChildCount(); ++i) node.removeChild(i); } //this means it's a species, which we need to prepend with the row/col prefix else { if (node.getChildCount() > 0 && model.getParameter(node.getLeftChild().getName()) == null) { //reactant if (reactantBool == true) { node.setVariable(model.getSpecies( "ROW" + row + "_COL" + col + "__" + node.getLeftChild().getName())); } //product else { node.setVariable(model.getSpecies( compartmentID + "__" + node.getLeftChild().getName())); reactantBool = true; } } for (int i = 0; i < node.getChildCount(); ++i) node.removeChild(i); for (int i = 0; i < node.getChildCount(); ++i) node.removeChild(i); } } //loop through reactants for (SpeciesReference reactant : reaction.getListOfReactants()) { //create a new reactant and add it to the new reaction SpeciesReference newReactant = new SpeciesReference(); newReactant = reactant.clone(); newReactant.setSpecies(compartmentID + "__" + newReactant.getSpecies()); newReactant.setAnnotation(new Annotation()); newReaction.addReactant(newReactant); } //loop through products for (SpeciesReference product : reaction.getListOfProducts()) { //create a new reactant and add it to the new reaction SpeciesReference newProduct = new SpeciesReference(); newProduct = product.clone(); newProduct.setSpecies("ROW" + row + "_COL" + col + "__" + newProduct.getSpecies()); newProduct.setAnnotation(new Annotation()); newReaction.addProduct(newProduct); } boolean i = false, j = false; for (LocalParameter lp : newReaction.getKineticLaw().getListOfLocalParameters()) { if (lp.getId().equals("i")) i = true; else if (lp.getId().equals("j")) j = true; } if (i) newReaction.getKineticLaw().getListOfLocalParameters().remove("i"); if (j) newReaction.getKineticLaw().getListOfLocalParameters().remove("j"); reactionsToAdd.add(newReaction); ++membraneDiffusionIndex; } } //end if membrane diffusion //NON-MEMBRANE DIFFUSION REACTIONS //check to see if the (non-membrane-diffusion) reaction has arrayed species //right now i'm only checking the first reactant species, due to a bad assumption //about the homogeneity of the arrayed reaction (ie, if one species is arrayed, they all are) else if (reaction.getNumReactants() > 0 && speciesToIsArrayedMap.get(reaction.getReactant(0).getSpeciesInstance().getId()) == true) { arraysExist = true; reactionsToRemove.add(reaction.getId()); //get the reactant dimensions, which tells us how many new reactions are going to be created SpeciesDimensions reactantDimensions = arrayedSpeciesToDimensionsMap.get(reaction.getReactant(0).getSpeciesInstance().getId()); boolean abort = false; //loop through all of the new formerly-implicit reactants for (int row = reactantDimensions.numRowsLower; row <= reactantDimensions.numRowsUpper; ++row) { for (int col = reactantDimensions.numColsLower; col <= reactantDimensions.numColsUpper; ++col) { //create a new reaction and set the ID Reaction newReaction = new Reaction(); newReaction = reaction.clone(); newReaction.setListOfReactants(new ListOf<SpeciesReference>()); newReaction.setListOfProducts(new ListOf<SpeciesReference>()); newReaction.setListOfModifiers(new ListOf<ModifierSpeciesReference>()); newReaction.setId("ROW" + row + "_COL" + col + "_" + reactionID); newReaction.setMetaId("ROW" + row + "_COL" + col + "_" + reactionID); newReaction.setReversible(false); newReaction.setFast(false); newReaction.setCompartment(reaction.getCompartment()); //get the nodes to alter ArrayList<ASTNode> get2DArrayElementNodes = new ArrayList<ASTNode>(); //return the head node of the get2DArrayElement function getSatisfyingNodes(newReaction.getKineticLaw().getMath(), "get2DArrayElement", get2DArrayElementNodes); //loop through all reactants for (SpeciesReference reactant : reaction.getListOfReactants()) { reactant.unsetMetaId(); //find offsets //the row offset is in the kinetic law via i //the col offset is in the kinetic law via j int rowOffset = 0; int colOffset = 0; ASTNode reactantHeadNode = null; //go through the get2DArrayElement nodes and find the one corresponding to the reactant for (ASTNode headNode : get2DArrayElementNodes) { //make sure it's a reactant node if (headNode.getChildCount() > 0 && model.getParameter(headNode.getLeftChild().getName()) == null) { reactantHeadNode = headNode; break; } } if (reactantHeadNode.getChild(1).getType().name().equals("PLUS")) rowOffset = reactantHeadNode.getChild(1).getRightChild().getInteger(); else if (reactantHeadNode.getChild(1).getType().name().equals("MINUS")) rowOffset = -1 * reactantHeadNode.getChild(1).getRightChild().getInteger(); if (reactantHeadNode.getChild(2).getType().name().equals("PLUS")) colOffset = reactantHeadNode.getChild(2).getRightChild().getInteger(); else if (reactantHeadNode.getChild(2).getType().name().equals("MINUS")) colOffset = -1 * reactantHeadNode.getChild(2).getRightChild().getInteger(); //create a new reactant and add it to the new reaction SpeciesReference newReactant = new SpeciesReference(); newReactant = reactant.clone(); newReactant.setSpecies(model.getSpecies("ROW" + (row + rowOffset) + "_COL" + (col + colOffset) + "__" + newReactant.getSpecies())); newReactant.setAnnotation(new Annotation()); newReaction.addReactant(newReactant); //put this reactant in place of the get2DArrayElement function call for (int i = 0; i < reactantHeadNode.getChildCount(); ++i) reactantHeadNode.removeChild(i); for (int i = 0; i < reactantHeadNode.getChildCount(); ++i) reactantHeadNode.removeChild(i); reactantHeadNode.setVariable(model.getSpecies(newReactant.getSpecies())); }// end looping through reactants //loop through all modifiers for (ModifierSpeciesReference modifier : reaction.getListOfModifiers()) { modifier.unsetMetaId(); } //loop through all products for (SpeciesReference product : reaction.getListOfProducts()) { product.unsetMetaId(); //find offsets int rowOffset = 0; int colOffset = 0; ASTNode productHeadNode = null; //go through the get2DArrayElement nodes and find the one corresponding to the product for (ASTNode headNode : get2DArrayElementNodes) { //make sure it's a product node //only the product has children, as the reactant's children get deleted if (headNode.getChildCount() > 0 && model.getParameter(headNode.getLeftChild().getName()) == null) { productHeadNode = headNode; break; } } if (productHeadNode.getChild(1).getType().name().equals("PLUS")) rowOffset = productHeadNode.getChild(1).getRightChild().getInteger(); else if (productHeadNode.getChild(1).getType().name().equals("MINUS")) rowOffset = -1 * productHeadNode.getChild(1).getRightChild().getInteger(); if (productHeadNode.getChild(2).getType().name().equals("PLUS")) colOffset = productHeadNode.getChild(2).getRightChild().getInteger(); else if (productHeadNode.getChild(2).getType().name().equals("MINUS")) colOffset = -1 * productHeadNode.getChild(2).getRightChild().getInteger(); //don't create reactions with products that don't exist if (row + rowOffset < reactantDimensions.numRowsLower || col + colOffset < reactantDimensions.numColsLower || row + rowOffset > reactantDimensions.numRowsUpper || col + colOffset > reactantDimensions.numColsUpper) { abort = true; break; } //create a new product and add it to the new reaction SpeciesReference newProduct = new SpeciesReference(); newProduct = product.clone(); newProduct.setSpecies(model.getSpecies("ROW" + (row + rowOffset) + "_COL" + (col + colOffset) + "__" + newProduct.getSpecies())); newProduct.setAnnotation(new Annotation()); newReaction.addProduct(newProduct); //put this reactant in place of the get2DArrayElement function call for (int i = 0; i < productHeadNode.getChildCount(); ++i) productHeadNode.removeChild(i); //put this reactant in place of the get2DArrayElement function call for (int i = 0; i < productHeadNode.getChildCount(); ++i) productHeadNode.removeChild(i); productHeadNode.setVariable(model.getSpecies(newProduct.getSpecies())); } //end looping through products if (abort == false) { boolean i = false, j = false; //checking for these local parameters using getLocalParameters() doesn't seem to work for (LocalParameter lp : newReaction.getKineticLaw().getListOfLocalParameters()) { lp.unsetMetaId(); if (lp.getId().equals("i")) i = true; else if (lp.getId().equals("j")) j = true; } if (i) newReaction.getKineticLaw().getListOfLocalParameters().remove("i"); if (j) newReaction.getKineticLaw().getListOfLocalParameters().remove("j"); //this isn't a reversible reaction; only take the left side if (newReaction.getId().contains("Degradation") == false) { newReaction.getKineticLaw().setMath(newReaction.getKineticLaw().getMath().getLeftChild()); } reactionsToAdd.add(newReaction); } else abort = false; } } } }// end looping through reactions //add in the new explicit array reactions for (Reaction reactionToAdd : reactionsToAdd) { reactionToAdd.setMetaId(reactionToAdd.getId()); if (model.getReaction(reactionToAdd.getId())!=null) { model.removeReaction(reactionToAdd.getId()); } model.addReaction(reactionToAdd); } ListOf<Reaction> allReactions = model.getListOfReactions(); //remove original array reaction(s) for (String reactionToRemove : reactionsToRemove) allReactions.remove(reactionToRemove); model.setListOfReactions(allReactions); ListOf<Species> allSpecies = model.getListOfSpecies(); //remove the original array species from the model for (String speciesID : speciesToRemove) allSpecies.remove(speciesID); model.setListOfSpecies(allSpecies); ListOf<Event> allEvents = model.getListOfEvents(); //remove original array event(s) for (String eventID : eventsToRemove) allEvents.remove(eventID); model.setListOfEvents(allEvents); ArrayList<String> parametersToRemove = new ArrayList<String>(); //get rid of the locations parameters for (Parameter parameter : model.getListOfParameters()) { if (parameter.getId().contains("_locations")) { // if (parameter.getId().contains("_locations")) // this.submodelIDToLocationsMap.put( // parameter.getId().replace("__locations",""), stripAnnotation(parameter.getAnnotationString())); parametersToRemove.add(parameter.getId()); } } for (String parameterID : parametersToRemove) model.removeParameter(parameterID); applyStoichiometryAmplification(model, stoichAmpValue); if (arraysExist) { SBMLWriter writer = new SBMLWriter(); PrintStream p; try { p = new PrintStream(new FileOutputStream(filename), true, "UTF-8"); p.print(writer.writeSBMLToString(model.getSBMLDocument())); } catch (Exception e) { e.printStackTrace(); } } } /** * fires events * * @param noAssignmentRulesFlag * @param noConstraintsFlag */ protected HashSet<String> fireEvents(final boolean noAssignmentRulesFlag, final boolean noConstraintsFlag) { //temporary set of events to remove from the triggeredEventQueue HashSet<String> untriggeredEvents = new HashSet<String>(); //loop through all triggered events //if they aren't persistent and the trigger is no longer true //remove from triggered queue and put into untriggered set for (EventToFire triggeredEvent : triggeredEventQueue) { String triggeredEventID = triggeredEvent.eventID; //if the trigger evaluates to false and the trigger isn't persistent if (eventToTriggerPersistenceMap.get(triggeredEventID) == false && getBooleanFromDouble(evaluateExpressionRecursive(eventToTriggerMap.get(triggeredEventID))) == false) { untriggeredEvents.add(triggeredEventID); eventToPreviousTriggerValueMap.put(triggeredEventID, false); } if (eventToTriggerPersistenceMap.get(triggeredEventID) == true && getBooleanFromDouble(evaluateExpressionRecursive(eventToTriggerMap.get(triggeredEventID))) == false) { untriggeredEventSet.add(triggeredEventID); } } //copy the triggered event queue -- except the events that are now untriggered //this is done because the remove function can't work with just a string; it needs to match events //this also re-evaluates the priorities in case they have changed PriorityQueue<EventToFire> newTriggeredEventQueue = new PriorityQueue<EventToFire>(5, eventComparator); while (triggeredEventQueue.size() > 0) { EventToFire event = triggeredEventQueue.poll(); EventToFire eventToAdd = new EventToFire(event.eventID, (HashSet<Object>) event.eventAssignmentSet.clone(), event.fireTime); if (untriggeredEvents.contains(event.eventID) == false) newTriggeredEventQueue.add(eventToAdd); else untriggeredEventSet.add(event.eventID); } triggeredEventQueue = newTriggeredEventQueue; //loop through untriggered events //if the trigger is no longer true //set the previous trigger value to false for (String untriggeredEventID : untriggeredEventSet) { if (eventToTriggerPersistenceMap.get(untriggeredEventID) == false && getBooleanFromDouble(evaluateExpressionRecursive(eventToTriggerMap.get(untriggeredEventID))) == false) eventToPreviousTriggerValueMap.put(untriggeredEventID, false); } //these are sets of things that need to be re-evaluated or tested due to the event firing HashSet<String> affectedReactionSet = new HashSet<String>(); HashSet<AssignmentRule> affectedAssignmentRuleSet = new HashSet<AssignmentRule>(); HashSet<ASTNode> affectedConstraintSet = new HashSet<ASTNode>(); //set of fired events to add to the untriggered set HashSet<String> firedEvents = new HashSet<String>(); //set of events to be removed due to component erasure HashSet<String> deadEvents = new HashSet<String>(); //fire all events whose fire time is less than the current time while (triggeredEventQueue.size() > 0 && triggeredEventQueue.peek().fireTime <= currentTime) { EventToFire eventToFire = triggeredEventQueue.poll(); String eventToFireID = eventToFire.eventID; //System.err.println("firing " + eventToFireID); if (eventToAffectedReactionSetMap.get(eventToFireID) != null) affectedReactionSet.addAll(eventToAffectedReactionSetMap.get(eventToFireID)); firedEvents.add(eventToFireID); eventToPreviousTriggerValueMap.put(eventToFireID, true); //handle dynamic events //the duplication method handles all event assignments //so those only get executed here if it's not a dynamic event if (eventToFire.eventID.contains("__AsymmetricDivision__")) { String compartmentID = ((String[])eventToFire.eventID.split("__"))[0]; duplicateComponent(compartmentID, eventToFire.eventID, "asymmetric"); } else if (eventToFire.eventID.contains("__SymmetricDivision__")) { String compartmentID = ((String[])eventToFire.eventID.split("__"))[0]; duplicateComponent(compartmentID, eventToFire.eventID, "symmetric"); } else if (eventToFire.eventID.contains("__Death__")) { String compartmentID = ((String[])eventToFire.eventID.split("__"))[0]; deadEvents = eraseComponent(compartmentID); firedEvents.removeAll(deadEvents); if (deadEvents.size() > 0) { for (String eventID : deadEvents) { untriggeredEventSet.remove(eventID); eventToPriorityMap.remove(eventID); eventToDelayMap.remove(eventID); eventToHasDelayMap.remove(eventID); eventToTriggerPersistenceMap.remove(eventID); eventToUseValuesFromTriggerTimeMap.remove(eventID); eventToTriggerMap.remove(eventID); eventToTriggerInitiallyTrueMap.remove(eventID); eventToPreviousTriggerValueMap.remove(eventID); eventToAssignmentSetMap.remove(eventID); eventToAffectedReactionSetMap.remove(eventID); } //copy the triggered event queue -- except the events that are now dead/removed newTriggeredEventQueue = new PriorityQueue<EventToFire>(5, eventComparator); while (triggeredEventQueue.size() > 0) { EventToFire event = triggeredEventQueue.poll(); EventToFire eventToAdd = new EventToFire(event.eventID, (HashSet<Object>) event.eventAssignmentSet.clone(), event.fireTime); if (deadEvents.contains(event.eventID) == false) newTriggeredEventQueue.add(eventToAdd); } triggeredEventQueue = newTriggeredEventQueue; } } else if (eventToFire.eventID.contains("__Move")) { int direction = (int) (randomNumberGenerator.nextDouble() * 4.0); if (eventToFire.eventID.contains("__MoveLeft__")) direction = 0; else if (eventToFire.eventID.contains("__MoveRight__")) direction = 1; else if (eventToFire.eventID.contains("__MoveAbove__")) direction = 2; else if (eventToFire.eventID.contains("__MoveBelow__")) direction = 3; //reactions that change and thus need their propensities re-evaluated HashSet<String> reactionsToAdjust = new HashSet<String>(); String compartmentID = ((String[])eventToFire.eventID.split("__"))[0]; Point parentLocation = componentToLocationMap.get(compartmentID); Point childLocation = (Point) parentLocation.clone(); moveComponent(compartmentID, "", new Point(), childLocation, direction, reactionsToAdjust); updatePropensities(reactionsToAdjust); updateAfterDynamicChanges(); } else { //execute all assignments for this event for (Object eventAssignment : eventToFire.eventAssignmentSet) { String variable; double assignmentValue; if (eventToUseValuesFromTriggerTimeMap.get(eventToFireID) == true) { variable = ((StringDoublePair) eventAssignment).string; assignmentValue = ((StringDoublePair) eventAssignment).doub; } //assignment needs to be evaluated else { variable = ((EventAssignment) eventAssignment).getVariable(); assignmentValue = evaluateExpressionRecursive(((EventAssignment) eventAssignment).getMath()); } //update the species, but only if it's not a constant (bound. cond. is fine) if (variableToIsConstantMap.get(variable) == false) { if (speciesToHasOnlySubstanceUnitsMap.containsKey(variable) && speciesToHasOnlySubstanceUnitsMap.get(variable) == false) variableToValueMap.put(variable, assignmentValue * speciesToCompartmentSizeMap.get(variable)); else variableToValueMap.put(variable, assignmentValue); } //if this variable that was just updated is part of an assignment rule (RHS) //then re-evaluate that assignment rule if (noAssignmentRulesFlag == false && variableToIsInAssignmentRuleMap.get(variable) == true) affectedAssignmentRuleSet.addAll(variableToAffectedAssignmentRuleSetMap.get(variable)); if (noConstraintsFlag == false && variableToIsInConstraintMap.get(variable) == true) affectedConstraintSet.addAll(variableToAffectedConstraintSetMap.get(variable)); } //end loop through assignments } //after an event fires, need to make sure the queue is updated untriggeredEvents.clear(); //loop through all triggered events //if they aren't persistent and the trigger is no longer true //remove from triggered queue and put into untriggered set for (EventToFire triggeredEvent : triggeredEventQueue) { String triggeredEventID = triggeredEvent.eventID; //if the trigger evaluates to false and the trigger isn't persistent if (eventToTriggerPersistenceMap.get(triggeredEventID) == false && getBooleanFromDouble(evaluateExpressionRecursive(eventToTriggerMap.get(triggeredEventID))) == false) { untriggeredEvents.add(triggeredEventID); eventToPreviousTriggerValueMap.put(triggeredEventID, false); } if (eventToTriggerPersistenceMap.get(triggeredEventID) == true && getBooleanFromDouble(evaluateExpressionRecursive(eventToTriggerMap.get(triggeredEventID))) == false) untriggeredEventSet.add(triggeredEventID); } //copy the triggered event queue -- except the events that are now untriggered //this is done because the remove function can't work with just a string; it needs to match events //this also re-evaluates the priorities in case they have changed newTriggeredEventQueue = new PriorityQueue<EventToFire>(5, eventComparator); while (triggeredEventQueue.size() > 0) { EventToFire event = triggeredEventQueue.poll(); EventToFire eventToAdd = new EventToFire(event.eventID, (HashSet<Object>) event.eventAssignmentSet.clone(), event.fireTime); if (untriggeredEvents.contains(event.eventID) == false) newTriggeredEventQueue.add(eventToAdd); else untriggeredEventSet.add(event.eventID); } triggeredEventQueue = newTriggeredEventQueue; //some events might trigger after this handleEvents(noAssignmentRulesFlag, noConstraintsFlag); }//end loop through event queue //add the fired events back into the untriggered set //this allows them to trigger/fire again later untriggeredEventSet.addAll(firedEvents); if (affectedAssignmentRuleSet.size() > 0) performAssignmentRules(affectedAssignmentRuleSet); if (affectedConstraintSet.size() > 0) { if (testConstraints(affectedConstraintSet) == false) constraintFailureFlag = true; } return affectedReactionSet; } /** * recursively puts every astnode child into the arraylist passed in * * @param node * @param nodeChildrenList */ protected void getAllASTNodeChildren(ASTNode node, ArrayList<ASTNode> nodeChildrenList) { for (ASTNode child : node.getChildren()) { if (child.getChildCount() == 0) nodeChildrenList.add(child); else { nodeChildrenList.add(child); getAllASTNodeChildren(child, nodeChildrenList); } } } /** * returns a set of all the reactions that the recently performed reaction affects * "affect" means that the species updates will change the affected reaction's propensity * * @param selectedReactionID the reaction that was recently performed * @return the set of all reactions that the performed reaction affects the propensity of */ protected HashSet<String> getAffectedReactionSet(String selectedReactionID, final boolean noAssignmentRulesFlag) { HashSet<String> affectedReactionSet = new HashSet<String>(20); affectedReactionSet.add(selectedReactionID); //loop through the reaction's reactants and products for (StringDoublePair speciesAndStoichiometry : reactionToSpeciesAndStoichiometrySetMap.get(selectedReactionID)) { String speciesID = speciesAndStoichiometry.string; affectedReactionSet.addAll(speciesToAffectedReactionSetMap.get(speciesID)); //if the species is involved in an assignment rule then it its changing may affect a reaction's propensity if (noAssignmentRulesFlag == false && variableToIsInAssignmentRuleMap.get(speciesID)) { //this assignment rule is going to be evaluated, so the rule's variable's value will change for (AssignmentRule assignmentRule : variableToAffectedAssignmentRuleSetMap.get(speciesID)) { if (speciesToAffectedReactionSetMap.get(assignmentRule.getVariable())!=null) { affectedReactionSet.addAll(speciesToAffectedReactionSetMap .get(assignmentRule.getVariable())); } } } } return affectedReactionSet; } /** * kind of a hack to mingle doubles and booleans for the expression evaluator * * @param value the double to be translated to a boolean * @return the translated boolean value */ protected boolean getBooleanFromDouble(double value) { if (value == 0.0) return false; else return true; } /** * kind of a hack to mingle doubles and booleans for the expression evaluator * * @param value the boolean to be translated to a double * @return the translated double value */ protected double getDoubleFromBoolean(boolean value) { if (value == true) return 1.0; else return 0.0; } /** * recursively puts the nodes that have the same name as the quarry string passed in into the arraylist passed in * so, the entire tree is searched through, which i don't think is possible with the jsbml methods * * @param node node to search through * @param quarry string to search for * @param satisfyingNodes list of nodes that satisfy the condition */ static void getSatisfyingNodes(ASTNode node, String quarry, ArrayList<ASTNode> satisfyingNodes) { if (node.isName() && node.getName().equals(quarry)) satisfyingNodes.add(node); else if (node.isFunction() && node.getName().equals(quarry)) satisfyingNodes.add(node); else { for (ASTNode childNode : node.getChildren()) getSatisfyingNodes(childNode, quarry, satisfyingNodes); } } /** * recursively puts the nodes that have the same name as the quarry string passed in into the arraylist passed in * so, the entire tree is searched through, which i don't think is possible with the jsbml methods * the lax version uses contains instead of equals * * @param node node to search through * @param quarry string to search for * @param satisfyingNodes list of nodes that satisfy the condition */ void getSatisfyingNodesLax(ASTNode node, String quarry, ArrayList<ASTNode> satisfyingNodes) { if (node.isName() && node.getName().contains(quarry)) satisfyingNodes.add(node); else if (node.isFunction() && node.getName().contains(quarry)) satisfyingNodes.add(node); else { for (ASTNode childNode : node.getChildren()) getSatisfyingNodesLax(childNode, quarry, satisfyingNodes); } } /** * updates the event queue and fires events and so on * @param currentTime the current time in the simulation */ protected void handleEvents(final boolean noAssignmentRulesFlag, final boolean noConstraintsFlag) { HashSet<String> triggeredEvents = new HashSet<String>(); //loop through all untriggered events //if any trigger, evaluate the fire time(s) and add them to the queue for (String untriggeredEventID : untriggeredEventSet) { // System.err.println(untriggeredEventID); // System.err.println(eventToTriggerMap.get(untriggeredEventID)); //if the trigger evaluates to true if (getBooleanFromDouble(evaluateExpressionRecursive(eventToTriggerMap.get(untriggeredEventID))) == true) { //skip the event if it's initially true and this is time == 0 if (currentTime == 0.0 && eventToTriggerInitiallyTrueMap.get(untriggeredEventID) == true) continue; //switch from false to true must happen if (eventToPreviousTriggerValueMap.get(untriggeredEventID) == true) continue; triggeredEvents.add(untriggeredEventID); //if assignment is to be evaluated at trigger time, evaluate it and replace the ASTNode assignment if (eventToUseValuesFromTriggerTimeMap.get(untriggeredEventID) == true) { //temporary hashset of evaluated assignments HashSet<Object> evaluatedAssignments = new HashSet<Object>(); for (Object evAssignment : eventToAssignmentSetMap.get(untriggeredEventID)) { EventAssignment eventAssignment = (EventAssignment) evAssignment; evaluatedAssignments.add(new StringDoublePair( eventAssignment.getVariable(), evaluateExpressionRecursive(eventAssignment.getMath()))); } double fireTime = currentTime; if (eventToHasDelayMap.get(untriggeredEventID) == true) fireTime += evaluateExpressionRecursive(eventToDelayMap.get(untriggeredEventID)); triggeredEventQueue.add(new EventToFire( untriggeredEventID, evaluatedAssignments, fireTime)); } else { double fireTime = currentTime; if (eventToHasDelayMap.get(untriggeredEventID) == true) fireTime += evaluateExpressionRecursive(eventToDelayMap.get(untriggeredEventID)); triggeredEventQueue.add(new EventToFire( untriggeredEventID, eventToAssignmentSetMap.get(untriggeredEventID), fireTime)); } } else { eventToPreviousTriggerValueMap.put(untriggeredEventID, false); } } //remove recently triggered events from the untriggered set //when they're fired, they get put back into the untriggered set untriggeredEventSet.removeAll(triggeredEvents); } public void replaceArgument(ASTNode formula,String bvar, ASTNode arg) { int n = 0; for (int i = 0; i < formula.getChildCount(); i++) { ASTNode child = formula.getChild(i); if (child.isString() && child.getName().equals(bvar)) { formula.replaceChild(n, arg.clone()); } else if (child.getChildCount() > 0) { replaceArgument(child, bvar, arg); } n++; } } /** * inlines a formula with function definitions * * @param formula * @return */ protected ASTNode inlineFormula(ASTNode formula) { if (formula.isFunction() == false || formula.isLeaf() == false) { for (int i = 0; i < formula.getChildCount(); ++i) formula.replaceChild(i, inlineFormula(formula.getChild(i)));//.clone())); } if (formula.isFunction() && model.getFunctionDefinition(formula.getName()) != null) { if (ibiosimFunctionDefinitions.contains(formula.getName())) return formula; ASTNode inlinedFormula = model.getFunctionDefinition(formula.getName()).getBody().clone(); ASTNode oldFormula = formula.clone(); ArrayList<ASTNode> inlinedChildren = new ArrayList<ASTNode>(); this.getAllASTNodeChildren(inlinedFormula, inlinedChildren); if (inlinedChildren.size() == 0) inlinedChildren.add(inlinedFormula); HashMap<String, Integer> inlinedChildToOldIndexMap = new HashMap<String, Integer>(); for (int i = 0; i < model.getFunctionDefinition(formula.getName()).getNumArguments(); ++i) { inlinedChildToOldIndexMap.put(model.getFunctionDefinition(formula.getName()).getArgument(i).getName(), i); } for (int i = 0; i < inlinedChildren.size(); ++i) { ASTNode child = inlinedChildren.get(i); if (child.isLeaf() && child.isName()) { int index = inlinedChildToOldIndexMap.get(child.getName()); replaceArgument(inlinedFormula,child.toFormula(), oldFormula.getChild(index)); if (inlinedFormula.getChildCount() == 0) inlinedFormula = oldFormula.getChild(index); } } return inlinedFormula; } else { return formula; } } /** * moves a component in a given direction * moves components out of the way if needed * creates grid reactions if the grid expands * * @param parentComponentID * @param direction */ protected void moveComponent(String parentComponentID, String childComponentID, Point parentLocation, Point childLocation, int direction, HashSet<String> reactionsToAdjust) { HashSet<Integer> newRows = new HashSet<Integer>(); HashSet<Integer> newCols = new HashSet<Integer>(); //find the grid bounds for (Point location : componentToLocationMap.values()) { if ((int) location.getX() < minRow) { minRow = (int) location.getX(); } else if ((int) location.getX() > maxRow) { maxRow = (int) location.getX(); } if ((int) location.getY() < minCol) { minCol = (int) location.getY(); } else if ((int) location.getY() > maxCol) { maxCol = (int) location.getY(); } } switch (direction) { case 0: childLocation.y -= 1; break; case 1: childLocation.y += 1; break; case 2: childLocation.x -= 1; break; case 3: childLocation.x += 1; break; case 4: {childLocation.x += 1; childLocation.y -= 1; break;} case 5: {childLocation.x -= 1; childLocation.y += 1; break;} case 6: {childLocation.x -= 1; childLocation.y -= 1; break;} case 7: {childLocation.x += 1; childLocation.y += 1; break;} } HashSet<Point> locationsToMove = new HashSet<Point>(); //if this place is taken, make room by moving the cells in the way if (componentToLocationMap.containsValue(childLocation)) { //empty location is the location that needs to become empty so the child can go there Point emptyLocation = (Point) childLocation.clone(); //find all of the locations that are in the way and put them in the hashset //this is done my moving in the direction chosen until an empty space is found while (componentToLocationMap.containsValue(emptyLocation) == true) { locationsToMove.add((Point) emptyLocation.clone()); switch (direction) { case 0: emptyLocation.y -= 1; break; case 1: emptyLocation.y += 1; break; case 2: emptyLocation.x -= 1; break; case 3: emptyLocation.x += 1; break; case 4: {emptyLocation.x += 1; emptyLocation.y -= 1; break;} case 5: {emptyLocation.x -= 1; emptyLocation.y += 1; break;} case 6: {emptyLocation.x -= 1; emptyLocation.y -= 1; break;} case 7: {emptyLocation.x += 1; emptyLocation.y += 1; break;} } } LinkedHashMap<String, Point> componentToLocationMapCopy = (LinkedHashMap<String, Point>) componentToLocationMap.clone(); //move the cells that are in the way for (Map.Entry<String, Point> componentAndLocation : componentToLocationMapCopy.entrySet()) { String compID = componentAndLocation.getKey(); if (locationsToMove.contains(componentAndLocation.getValue())) { switch (direction) { case 0: componentToLocationMap.get(compID).y -= 1; break; case 1: componentToLocationMap.get(compID).y += 1; break; case 2: componentToLocationMap.get(compID).x -= 1; break; case 3: componentToLocationMap.get(compID).x += 1; break; case 4: {componentToLocationMap.get(compID).x += 1; componentToLocationMap.get(compID).y -= 1; break;} case 5: {componentToLocationMap.get(compID).x -= 1; componentToLocationMap.get(compID).y += 1; break;} case 6: {componentToLocationMap.get(compID).x -= 1; componentToLocationMap.get(compID).y -= 1; break;} case 7: {componentToLocationMap.get(compID).x += 1; componentToLocationMap.get(compID).y += 1; break;} } //keep track of min row/col and max row/col so you know the bounds of the grid if ((int) componentToLocationMap.get(compID).getX() < minRow) { minRow = (int) componentToLocationMap.get(compID).getX(); newRows.add(minRow); } else if ((int) componentToLocationMap.get(compID).getX() > maxRow) { maxRow = (int) componentToLocationMap.get(compID).getX(); newRows.add(maxRow); } if ((int) componentToLocationMap.get(compID).getY() < minCol) { minCol = (int) componentToLocationMap.get(compID).getY(); newCols.add(minCol); } else if ((int) componentToLocationMap.get(compID).getY() > maxCol) { maxCol = (int) componentToLocationMap.get(compID).getY(); newCols.add(maxCol); } } } } //now that an empty space has been created (if necessary), put in the child component //or move the parent component (if the ID is "" then it's a pure move not a duplication) if (childComponentID.equals("")) componentToLocationMap.put(parentComponentID, childLocation); else componentToLocationMap.put(childComponentID, childLocation); //keep track of min row/col and max row/col so you know the bounds of the grid //this set of ifs is necessary because locationsToMove might be empty (if nothing's in the way) if ((int) childLocation.getX() < minRow) { minRow = (int) childLocation.getX(); newRows.add(minRow); } else if ((int) childLocation.getX() > maxRow) { maxRow = (int) childLocation.getX(); newRows.add(maxRow); } if ((int) childLocation.getY() < minCol) { minCol = (int) childLocation.getY(); newCols.add(minCol); } else if ((int) childLocation.getY() > maxCol) { maxCol = (int) childLocation.getY(); newCols.add(maxCol); } HashSet<String> underlyingSpeciesIDs = new HashSet<String>(); HashSet<String> newGridSpeciesIDs = new HashSet<String>(); HashMap<String, String> newGridSpeciesIDToOldRowSubstring = new HashMap<String, String>(); HashMap<String, String> newGridSpeciesIDToOldColSubstring = new HashMap<String, String>(); HashMap<String, String> newGridSpeciesIDToNewRowSubstring = new HashMap<String, String>(); HashMap<String, String> newGridSpeciesIDToNewColSubstring = new HashMap<String, String>(); for (String speciesID : speciesIDSet) { //find the grid species if (speciesID.contains("ROW") && speciesID.contains("COL") && speciesID.contains("__")) { underlyingSpeciesIDs.add(speciesID.split("__")[1]); } } //if there are new rows or cols added to the grid //add new grid species if (newRows.size() > 0) { for (int newRow : newRows) { //create new grid species for this new row for (int col = minCol; col <= maxCol; ++col) { for (String underlyingSpeciesID : underlyingSpeciesIDs) { String nonnegRow = Integer.toString(newRow); String nonnegCol = Integer.toString(col); if (newRow < 0) nonnegRow = nonnegRow.replace("-", "_negative_"); if (col < 0) nonnegCol = nonnegCol.replace("-", "_negative_"); String newID = "ROW" + nonnegRow + "_COL" + nonnegCol + "__" + underlyingSpeciesID; String newIDWithNegatives = "ROW" + newRow + "_COL" + col + "__" + underlyingSpeciesID; if (model.getSpecies(newID) != null) continue; newGridSpeciesIDs.add(newIDWithNegatives); newGridSpeciesIDToOldRowSubstring.put(newIDWithNegatives, "ROW" + newRow); newGridSpeciesIDToOldColSubstring.put(newIDWithNegatives, "COL" + col); newGridSpeciesIDToNewRowSubstring.put(newIDWithNegatives, "ROW" + nonnegRow); newGridSpeciesIDToNewColSubstring.put(newIDWithNegatives, "COL" + nonnegCol); Species gridSpecies = null; //find a grid species to take values from for (Species species : model.getListOfSpecies()) { if (species.getId().contains("__" + underlyingSpeciesID) && species.getId().contains("ROW") && species.getId().contains("COL")) gridSpecies = species; } Species newSpecies = gridSpecies.clone(); newSpecies.setId(newID); newSpecies.setMetaId(newID); //add new grid species to the model (so that altering the kinetic law through jsbml can work) model.addSpecies(newSpecies); //add a new species to the simulation data structures setupSingleSpecies(gridSpecies, newIDWithNegatives); variableToValueMap.put(newID.replace("_negative_","-"), 0); speciesToAffectedReactionSetMap.put(newID.replace("_negative_","-"), new HashSet<String>()); } } } } if (newCols.size() > 0) { for (int newCol : newCols) { //create new grid species for this new col for (int row = minRow; row <= maxRow; ++row) { for (String underlyingSpeciesID : underlyingSpeciesIDs) { String nonnegRow = Integer.toString(row); String nonnegCol = Integer.toString(newCol); if (row < 0) nonnegRow = nonnegRow.replace("-", "_negative_"); if (newCol < 0) nonnegCol = nonnegCol.replace("-", "_negative_"); String newID = "ROW" + nonnegRow + "_COL" + nonnegCol + "__" + underlyingSpeciesID; String newIDWithNegatives = "ROW" + row + "_COL" + newCol + "__" + underlyingSpeciesID; newGridSpeciesIDs.add(newIDWithNegatives); newGridSpeciesIDToOldRowSubstring.put(newIDWithNegatives, "ROW" + row); newGridSpeciesIDToOldColSubstring.put(newIDWithNegatives, "COL" + newCol); newGridSpeciesIDToNewRowSubstring.put(newIDWithNegatives, "ROW" + nonnegRow); newGridSpeciesIDToNewColSubstring.put(newIDWithNegatives, "COL" + nonnegCol); if (model.getSpecies(newID) != null) continue; Species gridSpecies = null; //find a grid species to take values from for (Species species : model.getListOfSpecies()) { if (species.getId().contains("__" + underlyingSpeciesID) && species.getId().contains("ROW") && species.getId().contains("COL")) gridSpecies = species; } Species newSpecies = gridSpecies.clone(); newSpecies.setId(newID); newSpecies.setMetaId(newID); //add new grid species to the model (so that altering the kinetic law through jsbml can work) model.addSpecies(newSpecies); //add a new species to the simulation data structures setupSingleSpecies(gridSpecies, newIDWithNegatives); variableToValueMap.put(newID.replace("_negative_","-"), 0); speciesToAffectedReactionSetMap.put(newID.replace("_negative_","-"), new HashSet<String>()); } } } } //create new grid diffusion and degradation reactions for the new grid species for (String speciesID : newGridSpeciesIDs) { String newGridSpeciesID = speciesID.replace( newGridSpeciesIDToOldRowSubstring.get(speciesID), newGridSpeciesIDToNewRowSubstring.get(speciesID)).replace( newGridSpeciesIDToOldColSubstring.get(speciesID), newGridSpeciesIDToNewColSubstring.get(speciesID)); String[] splitID = speciesID.split("_"); int row = Integer.valueOf(splitID[0].replace("ROW","")); int col = Integer.valueOf(splitID[1].replace("COL","")); ArrayList<Point> neighborLocations = new ArrayList<Point>(); neighborLocations.add(new Point(row+1,col)); //right neighborLocations.add(new Point(row,col+1)); //below neighborLocations.add(new Point(row-1,col)); //left neighborLocations.add(new Point(row,col-1)); //above String underlyingSpeciesID = speciesID.split("__")[1]; ASTNode newNode = new ASTNode(); //find a grid diffusion reaction with this underlying species to take values from for (Map.Entry<String, ASTNode> reactionAndFormula : reactionToFormulaMap.entrySet()) { String reactionID = reactionAndFormula.getKey(); if (reactionID.contains("Diffusion_" + underlyingSpeciesID + "_Below") || reactionID.contains("Diffusion_" + underlyingSpeciesID + "_Above") || reactionID.contains("Diffusion_" + underlyingSpeciesID + "_Left") || reactionID.contains("Diffusion_" + underlyingSpeciesID + "_Right")) { newNode = reactionAndFormula.getValue().clone(); } } int directionIndex = 0; for (Point neighborLocation : neighborLocations) { int nRow = (int) neighborLocation.getX(); int nCol = (int) neighborLocation.getY(); String neighborID = "ROW" + nRow + "_COL" + nCol + "__" + underlyingSpeciesID; String fdString = "", rvString = ""; switch (directionIndex) { case 0: fdString = "Below"; rvString = "Above"; break; case 1: fdString = "Right"; rvString = "Left"; break; case 2: fdString = "Above"; rvString = "Below"; break; case 3: fdString = "Left"; rvString = "Right"; break; } //make sure that the neighbor exists (ie, is a species contained on the current grid size) if (speciesIDSet.contains(neighborID)) { if (nRow < 0) neighborID = neighborID.replace("ROW" + nRow, "ROW" + "_negative_" + (-1 * nRow)); if (nCol < 0) neighborID = neighborID.replace("COL" + nCol, "COL" + "_negative_" + (-1 * nCol)); //create forward reaction (to the neighbor) if it doesn't exist already if (reactionToPropensityMap.containsKey("ROW" + row + "_COL" + col + "_Diffusion_" + underlyingSpeciesID + "_" + fdString) == false) { //alter kinetic law for forward reaction newNode.getRightChild().setVariable(model.getSpecies(newGridSpeciesID)); String newReactionID = "ROW" + row + "_COL" + col + "_Diffusion_" + underlyingSpeciesID + "_" + fdString; if (row < 0) newReactionID = newReactionID.replace("ROW" + row, "ROW" + "_negative_" + (-1 * row)); if (col < 0) newReactionID = newReactionID.replace("COL" + col, "COL" + "_negative_" + (-1 * col)); Reaction fdReaction = model.createReaction(newReactionID); KineticLaw fdKineticLaw = model.createKineticLaw(); fdKineticLaw.setMath(newNode.clone()); fdReaction.setKineticLaw(fdKineticLaw); if (model.getSpecies(newGridSpeciesID)!=null) { SpeciesReference reactant = new SpeciesReference(model.getSpecies(newGridSpeciesID)); reactant.setStoichiometry(1); fdReaction.addReactant(reactant); } if (model.getSpecies(neighborID)!=null) { SpeciesReference product = new SpeciesReference(model.getSpecies(neighborID)); product.setStoichiometry(1); fdReaction.addProduct(product); } setupLocalParameters(fdReaction.getKineticLaw(), fdReaction); setupSingleReaction(fdReaction.getId(), fdReaction.getKineticLaw().getMath(), false, fdReaction.getListOfReactants(), fdReaction.getListOfProducts(), fdReaction.getListOfModifiers()); } //create the reverse reaction (from the neighbor) if it doesn't already exist if (reactionToPropensityMap.containsKey("ROW" + nRow + "_COL" + nCol + "_Diffusion_" + underlyingSpeciesID + "_" + rvString) == false) { //alter kinetic law for reverse reaction newNode.getRightChild().setVariable(model.getSpecies(neighborID)); String newReactionID = "ROW" + nRow + "_COL" + nCol + "_Diffusion_" + underlyingSpeciesID + "_" + rvString; if (nRow < 0) newReactionID = newReactionID.replace("ROW" + nRow, "ROW" + "_negative_" + (-1 * nRow)); if (nCol < 0) newReactionID = newReactionID.replace("COL" + nCol, "COL" + "_negative_" + (-1 * nCol)); //create reverse reaction Reaction rvReaction = model.createReaction(newReactionID); KineticLaw rvKineticLaw = model.createKineticLaw(); rvKineticLaw.setMath(newNode.clone()); rvReaction.setKineticLaw(rvKineticLaw); if (model.getSpecies(neighborID)!=null) { SpeciesReference reactant = new SpeciesReference(model.getSpecies(neighborID)); reactant.setStoichiometry(1); rvReaction.addReactant(reactant); } if (model.getSpecies(newGridSpeciesID)!=null) { SpeciesReference product = new SpeciesReference(model.getSpecies(newGridSpeciesID)); product.setStoichiometry(1); rvReaction.addProduct(product); } setupLocalParameters(rvReaction.getKineticLaw(), rvReaction); setupSingleReaction(rvReaction.getId(), rvReaction.getKineticLaw().getMath(), false, rvReaction.getListOfReactants(), rvReaction.getListOfProducts(), rvReaction.getListOfModifiers()); } } ++directionIndex; } ASTNode degradationNode = new ASTNode(); // for (Map.Entry<String, ASTNode> reactionAndFormula : reactionToFormulaMap.entrySet()) { // String reactionID = reactionAndFormula.getKey(); Boolean isDegradable = false; //create degradation reaction for each grid species //find a grid degradation reaction to copy from for (Map.Entry<String, ASTNode> reactionAndFormula : reactionToFormulaMap.entrySet()) { String reactionID = reactionAndFormula.getKey(); if (reactionID.contains("Degradation_" + underlyingSpeciesID)) { degradationNode = reactionAndFormula.getValue().clone(); degradationNode.getRightChild().setVariable(model.getSpecies(newGridSpeciesID)); isDegradable = true; break; } } if (isDegradable) { String newDegReactionID = "ROW" + row + "_COL" + col + "_Degradation_" + underlyingSpeciesID; if (row < 0) newDegReactionID = newDegReactionID.replace("ROW" + row, "ROW" + "_negative_" + (-1 * row)); if (col < 0) newDegReactionID = newDegReactionID.replace("COL" + col, "COL" + "_negative_" + (-1 * col)); if (reactionToPropensityMap.containsKey(newDegReactionID) == false) { Reaction degReaction = model.createReaction(newDegReactionID); KineticLaw degKineticLaw = model.createKineticLaw(); degKineticLaw.setMath(degradationNode.clone()); degReaction.setKineticLaw(degKineticLaw); if (model.getSpecies(newGridSpeciesID)!=null) { SpeciesReference reactant = new SpeciesReference(model.getSpecies(newGridSpeciesID)); reactant.setStoichiometry(1); degReaction.addReactant(reactant); } setupLocalParameters(degReaction.getKineticLaw(), degReaction); setupSingleReaction(degReaction.getId(), degReaction.getKineticLaw().getMath(), false, degReaction.getListOfReactants(), degReaction.getListOfProducts(), degReaction.getListOfModifiers()); } } } //MOVE MEMBRANE DIFFUSION REACTIONS FOR COMPONENTS THAT HAVE MOVED if (locationsToMove.size() > 0) { for (Point locationToMove : locationsToMove) { //adjust these locations to their new, moved location switch (direction) { case 0: locationToMove.y -= 1; break; case 1: locationToMove.y += 1; break; case 2: locationToMove.x -= 1; break; case 3: locationToMove.x += 1; break; case 4: {locationToMove.x += 1; locationToMove.y -= 1; break;} case 5: {locationToMove.x -= 1; locationToMove.y += 1; break;} case 6: {locationToMove.x -= 1; locationToMove.y -= 1; break;} case 7: {locationToMove.x += 1; locationToMove.y += 1; break;} } } //find the membrane diffusion reactions for these moved components and alter it for (String compID : componentToLocationMap.keySet()) { int compX = (int) componentToLocationMap.get(compID).getX(); int compY = (int) componentToLocationMap.get(compID).getY(); for (Point locationToMove : locationsToMove) { if (locationToMove.x == compX && locationToMove.y == compY) { if (componentToReactionSetMap.get(compID)==null) continue; for (String reactionID : componentToReactionSetMap.get(compID)) { //only need to change the rv membrane diffusion reaction if (reactionID.contains("MembraneDiffusion")) { ASTNode formulaNode = reactionToFormulaMap.get(reactionID); //the right child is the one to alter ASTNode speciesNode = formulaNode.getRightChild(); Point oldLocation = (Point) locationToMove.clone(); switch (direction) { case 0: oldLocation.y = locationToMove.y + 1; break; case 1: oldLocation.y = locationToMove.y - 1; break; case 2: oldLocation.x = locationToMove.x + 1; break; case 3: oldLocation.x = locationToMove.x - 1; break; case 4: {oldLocation.x = locationToMove.x - 1; oldLocation.y = locationToMove.y + 1; break;} case 5: {oldLocation.x = locationToMove.x + 1; oldLocation.y = locationToMove.y - 1; break;} case 6: {oldLocation.x = locationToMove.x + 1; oldLocation.y = locationToMove.y + 1; break;} case 7: {oldLocation.x = locationToMove.x - 1; oldLocation.y = locationToMove.y - 1; break;} } String oldRowCol = "ROW" + (int) oldLocation.x + "_COL" + (int) oldLocation.y; oldRowCol = oldRowCol.replace("ROW-", "ROW_negative_"); oldRowCol = oldRowCol.replace("COL-", "COL_negative_"); String newRowCol = "ROW" + (int) locationToMove.x + "_COL" + (int) locationToMove.y; newRowCol = newRowCol.replace("ROW-", "ROW_negative_"); newRowCol = newRowCol.replace("COL-", "COL_negative_"); //adjust kinetic law speciesNode.setVariable(model.getSpecies(speciesNode.getName().replace(oldRowCol, newRowCol))); newRowCol = newRowCol.replace("ROW_negative_", "ROW-"); newRowCol = newRowCol.replace("COL_negative_", "COL-"); oldRowCol = oldRowCol.replace("ROW_negative_", "ROW-"); oldRowCol = oldRowCol.replace("COL_negative_", "COL-"); //adjust reactants/products for (StringDoublePair speciesAndStoichiometry : reactionToSpeciesAndStoichiometrySetMap.get(reactionID)) { speciesAndStoichiometry.string = speciesAndStoichiometry.string.replace(oldRowCol, newRowCol); } for (StringDoublePair reactantAndStoichiometry : reactionToReactantStoichiometrySetMap.get(reactionID)) { reactantAndStoichiometry.string = reactantAndStoichiometry.string.replace(oldRowCol, newRowCol); } //remove the old, now out-dated species to affected reaction pairs //put in the new up-to-date pairs for (String speciesID : speciesToAffectedReactionSetMap.keySet()) { if (speciesID.contains(oldRowCol + "_")) { HashSet<String> reactionsToRemove = new HashSet<String>(); for (String reaction : speciesToAffectedReactionSetMap.get(speciesID)) { if (reaction.contains("MembraneDiffusion")) reactionsToRemove.add(reaction); } for (String reactionToRemove : reactionsToRemove) speciesToAffectedReactionSetMap.get(speciesID).remove(reactionToRemove); } if (speciesID.contains(newRowCol + "_")) { speciesToAffectedReactionSetMap.get(speciesID).add(reactionID); } } //adjust propensity reactionsToAdjust.add(reactionID); } } } } } } } /** * performs assignment rules that may have changed due to events or reactions firing * * @param affectedAssignmentRuleSet the set of assignment rules that have been affected */ protected HashSet<String> performAssignmentRules(HashSet<AssignmentRule> affectedAssignmentRuleSet) { HashSet<String> affectedVariables = new HashSet<String>(); for (AssignmentRule assignmentRule : affectedAssignmentRuleSet) { String variable = assignmentRule.getVariable(); //update the species count (but only if the species isn't constant) (bound cond is fine) if (variableToIsConstantMap.containsKey(variable) && variableToIsConstantMap.get(variable) == false || variableToIsConstantMap.containsKey(variable) == false) { if (speciesToHasOnlySubstanceUnitsMap.containsKey(variable) && speciesToHasOnlySubstanceUnitsMap.get(variable) == false) { variableToValueMap.put(variable, evaluateExpressionRecursive(assignmentRule.getMath()) * variableToValueMap.get(speciesToCompartmentNameMap.get(variable))); } else { variableToValueMap.put(variable, evaluateExpressionRecursive(assignmentRule.getMath())); } affectedVariables.add(variable); } } return affectedVariables; } /** * performs every rate rule using the current time step * * @param delta_t * @return */ protected HashSet<String> performRateRules(double delta_t) { HashSet<String> affectedVariables = new HashSet<String>(); for (Rule rule : model.getListOfRules()) { if (rule.isRate()) { RateRule rateRule = (RateRule) rule; String variable = rateRule.getVariable(); //update the species count (but only if the species isn't constant) (bound cond is fine) if (variableToIsConstantMap.containsKey(variable) && variableToIsConstantMap.get(variable) == false) { if (speciesToHasOnlySubstanceUnitsMap.containsKey(variable) && speciesToHasOnlySubstanceUnitsMap.get(variable) == false) { variableToValueMap.adjustValue(variable, delta_t * ( evaluateExpressionRecursive(rateRule.getMath()) * variableToValueMap.get(speciesToCompartmentNameMap.get(variable)))); } else { variableToValueMap.adjustValue(variable, delta_t * evaluateExpressionRecursive(rateRule.getMath())); } affectedVariables.add(variable); } } } return affectedVariables; } /** * updates reactant/product species counts based on their stoichiometries * * @param selectedReactionID the reaction to perform */ protected void performReaction(String selectedReactionID, final boolean noAssignmentRulesFlag, final boolean noConstraintsFlag) { //these are sets of things that need to be re-evaluated or tested due to the reaction firing HashSet<AssignmentRule> affectedAssignmentRuleSet = new HashSet<AssignmentRule>(); HashSet<ASTNode> affectedConstraintSet = new HashSet<ASTNode>(); //loop through the reaction's reactants and products and update their amounts for (StringDoublePair speciesAndStoichiometry : reactionToSpeciesAndStoichiometrySetMap.get(selectedReactionID)) { double stoichiometry = speciesAndStoichiometry.doub; String speciesID = speciesAndStoichiometry.string; //this means the stoichiometry isn't constant, so look to the variableToValue map if (reactionToNonconstantStoichiometriesSetMap.containsKey(selectedReactionID)) { for (StringStringPair doubleID : reactionToNonconstantStoichiometriesSetMap.get(selectedReactionID)) { //string1 is the species ID; string2 is the speciesReference ID if (doubleID.string1.equals(speciesID)) { stoichiometry = variableToValueMap.get(doubleID.string2); //this is to get the plus/minus correct, as the variableToValueMap has //a stoichiometry without the reactant/product plus/minus data stoichiometry *= (int)(speciesAndStoichiometry.doub/Math.abs(speciesAndStoichiometry.doub)); break; } } } //update the species count if the species isn't a boundary condition or constant //note that the stoichiometries are earlier modified with the correct +/- sign if (speciesToIsBoundaryConditionMap.get(speciesID) == false && variableToIsConstantMap.get(speciesID) == false) { if (speciesToConversionFactorMap.containsKey(speciesID)) { variableToValueMap.adjustValue(speciesID, stoichiometry * variableToValueMap.get(speciesToConversionFactorMap.get(speciesID))); } else { variableToValueMap.adjustValue(speciesID, stoichiometry); } } //if this variable that was just updated is part of an assignment rule (RHS) //then re-evaluate that assignment rule if (noAssignmentRulesFlag == false && variableToIsInAssignmentRuleMap.get(speciesID) == true) affectedAssignmentRuleSet.addAll(variableToAffectedAssignmentRuleSetMap.get(speciesID)); if (noConstraintsFlag == false && variableToIsInConstraintMap.get(speciesID) == true) affectedConstraintSet.addAll(variableToAffectedConstraintSetMap.get(speciesID)); } if (affectedAssignmentRuleSet.size() > 0) performAssignmentRules(affectedAssignmentRuleSet); if (affectedConstraintSet.size() > 0) { if (testConstraints(affectedConstraintSet) == false) constraintFailureFlag = true; } } /** * recursively finds all variable nodes and prepends a string to the variable * static version * * @param node * @param toPrepend */ private static void prependToVariableNodes(ASTNode node, String toPrepend, Model model) { if (node.isName()) { //only prepend to species and parameters if (model.getSpecies(toPrepend + node.getName()) != null) node.setVariable(model.getSpecies(toPrepend + node.getName())); else if (model.getParameter(toPrepend + node.getName()) != null) node.setVariable(model.getParameter(toPrepend + node.getName())); } else { for (ASTNode childNode : node.getChildren()) prependToVariableNodes(childNode, toPrepend, model); } } /** * appends the current species states to the TSD file * * @throws IOException */ protected void printToTSD(double printTime) throws IOException { String commaSpace = ""; //dynamic printing requires re-printing the species values each time step if (dynamicBoolean == true) { bufferedTSDWriter.write("(\"time\""); commaSpace = ", "; //if there's an interesting species, only those get printed if (interestingSpecies.size() > 0) { for (String speciesID : interestingSpecies) bufferedTSDWriter.write(commaSpace + "\"" + speciesID + "\""); //always print compartment location IDs for (String componentLocationID : componentToLocationMap.keySet()) { String locationX = componentLocationID + "__locationX"; String locationY = componentLocationID + "__locationY"; bufferedTSDWriter.write(commaSpace + "\"" + locationX + "\", \"" + locationY + "\""); } } else { //print the species IDs for (String speciesID : speciesIDSet) bufferedTSDWriter.write(commaSpace + "\"" + speciesID + "\""); //print compartment location IDs for (String componentLocationID : componentToLocationMap.keySet()) { String locationX = componentLocationID + "__locationX"; String locationY = componentLocationID + "__locationY"; bufferedTSDWriter.write(commaSpace + "\"" + locationX + "\", \"" + locationY + "\""); } //print compartment IDs (for sizes) for (String componentID : compartmentIDSet) { try { bufferedTSDWriter.write(", \"" + componentID + "\""); } catch (IOException e) { e.printStackTrace(); } } //print nonconstant parameter IDs for (String parameterID : nonconstantParameterIDSet) { try { bufferedTSDWriter.write(", \"" + parameterID + "\""); } catch (IOException e) { e.printStackTrace(); } } } bufferedTSDWriter.write("),\n"); } bufferedTSDWriter.write("("); commaSpace = ""; //print the current time bufferedTSDWriter.write(printTime + ", "); //if there's an interesting species, only those get printed if (interestingSpecies.size() > 0) { for (String speciesID : interestingSpecies) { if (printConcentrations == true) { bufferedTSDWriter.write(commaSpace + (variableToValueMap.get(speciesID) / variableToValueMap.get(speciesToCompartmentNameMap.get(speciesID)))); } else bufferedTSDWriter.write(commaSpace + variableToValueMap.get(speciesID)); commaSpace = ", "; } //always print component location values for (String componentID : componentToLocationMap.keySet()) { bufferedTSDWriter.write(commaSpace + (int) componentToLocationMap.get(componentID).getX()); bufferedTSDWriter.write(commaSpace + (int) componentToLocationMap.get(componentID).getY()); } } else { //loop through the speciesIDs and print their current value to the file for (String speciesID : speciesIDSet) { bufferedTSDWriter.write(commaSpace + variableToValueMap.get(speciesID)); commaSpace = ", "; } //print component location values for (String componentID : componentToLocationMap.keySet()) { bufferedTSDWriter.write(commaSpace + (int) componentToLocationMap.get(componentID).getX()); commaSpace = ", "; bufferedTSDWriter.write(commaSpace + (int) componentToLocationMap.get(componentID).getY()); } //print compartment sizes for (String componentID : compartmentIDSet) { bufferedTSDWriter.write(commaSpace + variableToValueMap.get(componentID)); commaSpace = ", "; } //print nonconstant parameter values for (String parameterID : nonconstantParameterIDSet) { bufferedTSDWriter.write(commaSpace + variableToValueMap.get(parameterID)); commaSpace = ", "; } } bufferedTSDWriter.write(")"); bufferedTSDWriter.flush(); } /** * parses TSD files for all runs and prints mean and standard deviation TSDs * * @throws IOException */ protected void printStatisticsTSD() throws IOException { //the last run is the number of runs int numRuns = currentRun; HashMap<String, ArrayList<DescriptiveStatistics> > speciesStatistics = new HashMap<String, ArrayList<DescriptiveStatistics> >(); ArrayList<String> allSpecies = new ArrayList<String>(); HashSet<String> speciesSet = new HashSet<String>(); //if it's dynamic, we have to parse every run's file to get the full list of species if (dynamicBoolean == true) { for (int run = 1; run <= numRuns; ++run) { DTSDParser dtsdParser = new DTSDParser(outputDirectory + "run-" + run + ".dtsd"); speciesSet.addAll(dtsdParser.getSpecies()); } speciesSet.remove("time"); allSpecies.add("time"); allSpecies.addAll(speciesSet); } //store the TSD data for analysis for (int run = 1; run <= numRuns; ++run) { DTSDParser dtsdParser = null; TSDParser tsdParser = null; HashMap<String, ArrayList<Double> > runStatistics = null; if (dynamicBoolean == true) { dtsdParser = new DTSDParser(outputDirectory + "run-" + run + ".dtsd"); //allSpecies = dtsdParser.getSpecies(); runStatistics = dtsdParser.getHashMap(allSpecies); } else { tsdParser = new TSDParser(outputDirectory + "run-" + run + ".tsd", false); allSpecies = tsdParser.getSpecies(); runStatistics = tsdParser.getHashMap(); } for (int speciesIndex = 0; speciesIndex < allSpecies.size(); ++speciesIndex) { String species = allSpecies.get(speciesIndex); for (int index = 0; index < runStatistics.get(species).size(); ++index) { Double speciesData = runStatistics.get(species).get(index); if (speciesStatistics.size() <= speciesIndex) speciesStatistics.put(species, new ArrayList<DescriptiveStatistics>()); if (speciesStatistics.get(species).size() <= index) speciesStatistics.get(species).add(new DescriptiveStatistics()); speciesStatistics.get(species).get(index).addValue(speciesData.doubleValue()); } } } DataParser statsParser = new DataParser(null, null); ArrayList<ArrayList<Double> > meanTSDData = new ArrayList<ArrayList<Double> >(); //calculate and print the mean tsd for (String species : allSpecies) { ArrayList<Double> speciesData = new ArrayList<Double>(); for (int index = 0; index < speciesStatistics.get(species).size(); ++index) speciesData.add(speciesStatistics.get(species).get(index).getMean()); meanTSDData.add(speciesData); } statsParser.setData(meanTSDData); statsParser.setSpecies(allSpecies); statsParser.outputTSD(outputDirectory + "mean.tsd"); //calculate and print the standard deviation tsd ArrayList<ArrayList<Double> > standardDeviationTSDData = new ArrayList<ArrayList<Double> >(); for (String species : allSpecies) { ArrayList<Double> speciesData = new ArrayList<Double>(); if (species.equals("time")) { for (int index = 0; index < speciesStatistics.get(species).size(); ++index) speciesData.add(speciesStatistics.get(species).get(index).getMean()); } else { for (int index = 0; index < speciesStatistics.get(species).size(); ++index) speciesData.add(speciesStatistics.get(species).get(index).getStandardDeviation()); } standardDeviationTSDData.add(speciesData); } statsParser.setData(standardDeviationTSDData); statsParser.setSpecies(allSpecies); statsParser.outputTSD(outputDirectory + "standard_deviation.tsd"); //calculate and print the variance tsd ArrayList<ArrayList<Double> > varianceTSDData = new ArrayList<ArrayList<Double> >(); for (String species : allSpecies) { ArrayList<Double> speciesData = new ArrayList<Double>(); if (species.equals("time")) { for (int index = 0; index < speciesStatistics.get(species).size(); ++index) speciesData.add(speciesStatistics.get(species).get(index).getMean()); } else { for (int index = 0; index < speciesStatistics.get(species).size(); ++index) speciesData.add(speciesStatistics.get(species).get(index).getVariance()); } varianceTSDData.add(speciesData); } statsParser.setData(varianceTSDData); statsParser.setSpecies(allSpecies); statsParser.outputTSD(outputDirectory + "variance.tsd"); } /** * reverts the model back to its pre-dynamic state * (during duplication events, the model is altered because of jsbml restrictions) */ protected void resetModel() { model.setListOfSpecies(initialSpecies.clone()); model.setListOfReactions(initialReactions.clone()); model.setListOfEvents(initialEvents.clone()); model.setListOfParameters(initialParameters.clone()); model.setListOfCompartments(initialCompartments.clone()); } /** * non-static version of the method that flattens arrays into the sbml model * this one doesn't print the model back out, though */ protected void setupArrays() { boolean arraysExist = false; //ARRAYED SPECIES BUSINESS //create all new species that are implicit in the arrays and put them into the model ArrayList<Species> speciesToAdd = new ArrayList<Species>(); ArrayList<String> speciesToRemove = new ArrayList<String>(); HashMap<String, Boolean> speciesToIsArrayedMap = new HashMap<String, Boolean>(); HashMap<String, SpeciesDimensions> arrayedSpeciesToDimensionsMap = new HashMap<String, SpeciesDimensions>(); for (Species species : model.getListOfSpecies()) { String speciesID = species.getId(); //check to see if the species is arrayed if (stripAnnotation(species.getAnnotationString()).contains("array:array")) { arraysExist = true; speciesToIsArrayedMap.put(speciesID, true); speciesToRemove.add(speciesID); int numRowsLower = 0; int numColsLower = 0; int numRowsUpper = 0; int numColsUpper = 0; String[] annotationString = stripAnnotation(species.getAnnotationString()).split("="); numColsLower = Integer.valueOf(((String[])(annotationString[1].split(" ")))[0].replace("\"","")); numColsUpper = Integer.valueOf(((String[])(annotationString[2].split(" ")))[0].replace("\"","")); numRowsLower = Integer.valueOf(((String[])(annotationString[3].split(" ")))[0].replace("\"","")); numRowsUpper = Integer.valueOf(((String[])(annotationString[4].split(" ")))[0].replace("\"","")); SpeciesDimensions speciesDimensions = new SpeciesDimensions(numRowsLower, numRowsUpper, numColsLower, numColsUpper); arrayedSpeciesToDimensionsMap.put(speciesID, speciesDimensions); //loop through all species in the array //prepend the row/col information to create a new ID for (int row = numRowsLower; row <= numRowsUpper; ++row) { for (int col = numColsLower; col <= numColsUpper; ++col) { speciesID = "ROW" + row + "_COL" + col + "__" + species.getId(); Species newSpecies = new Species(); newSpecies = species.clone(); newSpecies.setMetaId(speciesID); newSpecies.setId(speciesID); newSpecies.setAnnotation(new Annotation()); speciesToAdd.add(newSpecies); } } } else speciesToIsArrayedMap.put(speciesID, false); } //end species for loop //add new row/col species to the model for (Species species : speciesToAdd) { model.addSpecies(species); } //ARRAYED EVENTS BUSINESS ArrayList<String> eventsToRemove = new ArrayList<String>(); ArrayList<Event> eventsToAdd = new ArrayList<Event>(); for (Event event : model.getListOfEvents()) { if (stripAnnotation(event.getAnnotationString()).contains("array")) { arraysExist = true; eventsToRemove.add(event.getId()); String annotationString = stripAnnotation(event.getAnnotationString()).replace("<annotation>",""). replace("</annotation>","").replace("\"",""); String[] splitAnnotation = annotationString.split("array:"); ArrayList<String> eventCompartments = new ArrayList<String>(); splitAnnotation[splitAnnotation.length - 2] = ((String[])splitAnnotation[splitAnnotation.length - 2].split("xmlns:"))[0]; for (int i = 2; i < splitAnnotation.length; ++i) { String compartmentID = ((String[])splitAnnotation[i].split("="))[0]; eventCompartments.add(compartmentID); } //loop through all compartments and create an event for each one for (String compartmentID : eventCompartments) { Event newEvent = new Event(); newEvent.setVersion(event.getVersion()); newEvent.setLevel(event.getLevel()); newEvent.setId(compartmentID + "__" + event.getId()); newEvent.setMetaId(compartmentID + "__" + event.getId()); event.getTrigger().getMath().updateVariables(); newEvent.setTrigger(event.getTrigger().clone()); //at this point, the formula has something like neighborQuantity(Species1) //this needs to become neighborQuantity(Species1, CompartmentLocationX(Comp1), CompartmentLocationY(Comp1)) if (newEvent.getTrigger().getMath().toFormula().contains("neighborQuantity")) { String triggerMath = newEvent.getTrigger().getMath().toFormula(); ArrayList<ASTNode> nqNodes = new ArrayList<ASTNode>(); this.getSatisfyingNodesLax(newEvent.getTrigger().getMath(), "neighborQuantity", nqNodes); //loop through all neighbor quantity nodes in the trigger formula for (ASTNode nqNode : nqNodes) { String direction = ""; if (triggerMath.contains("QuantityLeft")) direction = "Left"; else if (triggerMath.contains("QuantityRight")) direction = "Right"; else if (triggerMath.contains("QuantityAbove")) direction = "Above"; else direction = "Below"; String speciesID = nqNode.toFormula().split( "neighborQuantity" + direction)[1].replace("(","").replace(")",""); try { ASTNode newFormula = ASTNode.parseFormula( "neighborQuantity" + direction + "Full(" + compartmentID + "__" + speciesID + ", getCompartmentLocationX(" + compartmentID + "__Cell" + "), getCompartmentLocationY(" + compartmentID + "__Cell" + "))"); for (int i = 0; i < ((ASTNode) nqNode.getParent()).getChildCount(); ++i) { if (((ASTNode) nqNode.getParent().getChildAt(i)).isFunction() && ((ASTNode) nqNode.getParent().getChildAt(i)).getVariable().toString() .contains("neighborQuantity" + direction)) { ((ASTNode) nqNode.getParent()).replaceChild(i, newFormula); break; } } } catch (ParseException e) { e.printStackTrace(); } } } if (event.isSetPriority()) newEvent.setPriority(event.getPriority().clone()); if (event.isSetDelay()) newEvent.setDelay(event.getDelay().clone()); newEvent.setUseValuesFromTriggerTime(event.getUseValuesFromTriggerTime()); for (EventAssignment eventAssignment : event.getListOfEventAssignments()) { EventAssignment ea = eventAssignment.clone(); ea.setMath(eventAssignment.getMath().clone()); ea.setVariable(eventAssignment.getVariable()); newEvent.addEventAssignment(ea); } for (EventAssignment eventAssignment : newEvent.getListOfEventAssignments()) { eventAssignment.setVariable(compartmentID + "__" + eventAssignment.getVariable()); //prepends the compartment ID to all variables in the event assignment prependToVariableNodes(eventAssignment.getMath(), compartmentID + "__", model); } eventsToAdd.add(newEvent); } } } for (Event eventToAdd : eventsToAdd) { model.addEvent(eventToAdd); } //ARRAYED REACTION BUSINESS //if a reaction has arrayed species //new reactions that are implicit are created and added to the model ArrayList<Reaction> reactionsToAdd = new ArrayList<Reaction>(); ArrayList<String> reactionsToRemove = new ArrayList<String>(); for (Reaction reaction : model.getListOfReactions()) { String reactionID = reaction.getId(); ArrayList<Integer> membraneDiffusionRows = new ArrayList<Integer>(); ArrayList<Integer> membraneDiffusionCols = new ArrayList<Integer>(); ArrayList<String> membraneDiffusionCompartments = new ArrayList<String>(); //MEMBRANE DIFFUSION REACTIONS //if it's a membrane diffusion reaction it'll have the appropriate locations as an annotation //so parse them and store them in the above arraylists if (reactionID.contains("MembraneDiffusion")) { arraysExist = true; String annotationString = stripAnnotation(reaction.getAnnotationString()).replace("<annotation>",""). replace("</annotation>","").replace("\"",""); String[] splitAnnotation = annotationString.split("array:"); if (splitAnnotation.length <= 1) { continue; } splitAnnotation[splitAnnotation.length - 2] = ((String[])splitAnnotation[splitAnnotation.length - 2].split("xmlns:"))[0]; for (int i = 2; i < splitAnnotation.length; ++i) { String compartmentID = ((String[])splitAnnotation[i].split("="))[0]; String row = ((String[])((String[])splitAnnotation[i].split(" ")[0].split("="))[1].split(","))[0].replace("(",""); String col = ((String[])((String[])splitAnnotation[i].split(" ")[0].split("="))[1].split(","))[1].replace(")",""); membraneDiffusionRows.add(Integer.valueOf(row.trim())); membraneDiffusionCols.add(Integer.valueOf(col.trim())); membraneDiffusionCompartments.add(compartmentID); } int membraneDiffusionIndex = 0; reactionsToRemove.add(reaction.getId()); reaction.setAnnotation(new Annotation()); //loop through all appropriate row/col pairs and create a membrane diffusion reaction for each one for (String compartmentID : membraneDiffusionCompartments) { int row = membraneDiffusionRows.get(membraneDiffusionIndex); int col = membraneDiffusionCols.get(membraneDiffusionIndex); //create a new reaction and set the ID Reaction newReaction = new Reaction(); newReaction = reaction.clone(); newReaction.setListOfReactants(new ListOf<SpeciesReference>()); newReaction.setListOfProducts(new ListOf<SpeciesReference>()); newReaction.setListOfModifiers(new ListOf<ModifierSpeciesReference>()); newReaction.setId(compartmentID + "__" + reactionID); newReaction.setMetaId(compartmentID + "__" + reactionID); newReaction.setReversible(true); newReaction.setFast(false); newReaction.setCompartment(reaction.getCompartment()); //alter the kinetic law to so that it has the correct indexes as children for the //get2DArrayElement function //get the nodes to alter (that are arguments for the get2DArrayElement method) ArrayList<ASTNode> get2DArrayElementNodes = new ArrayList<ASTNode>(); getSatisfyingNodes(newReaction.getKineticLaw().getMath(), "get2DArrayElement", get2DArrayElementNodes); boolean reactantBool = false; //replace the get2darrayelement stuff with the proper explicit species/parameters for (ASTNode node : get2DArrayElementNodes) { if (node.getLeftChild().getName().contains("kmdiff")) { String parameterName = node.getLeftChild().getName(); //see if the species-specific one exists //if it doesn't, use the default //you'll need to parse the species name from the reaction id, probably String speciesID = reactionID.replace("MembraneDiffusion_",""); if (model.getParameter(compartmentID + "__" + speciesID + "__" + parameterName) == null) node.setVariable(model.getParameter(parameterName)); else node.setVariable(model.getParameter(compartmentID + "__" + speciesID + "__" + parameterName)); for (int i = 0; i < node.getChildCount(); ++i) node.removeChild(i); for (int i = 0; i < node.getChildCount(); ++i) node.removeChild(i); } //this means it's a species, which we need to prepend with the row/col prefix else { if (node.getChildCount() > 0 && model.getParameter(node.getLeftChild().getName()) == null) { //reactant if (reactantBool == true) { node.setVariable(model.getSpecies( "ROW" + row + "_COL" + col + "__" + node.getLeftChild().getName())); } //product else { node.setVariable(model.getSpecies( compartmentID + "__" + node.getLeftChild().getName())); reactantBool = true; } } for (int i = 0; i < node.getChildCount(); ++i) node.removeChild(i); for (int i = 0; i < node.getChildCount(); ++i) node.removeChild(i); } } //loop through reactants for (SpeciesReference reactant : reaction.getListOfReactants()) { //create a new reactant and add it to the new reaction SpeciesReference newReactant = new SpeciesReference(); newReactant = reactant.clone(); newReactant.setSpecies(compartmentID + "__" + newReactant.getSpecies()); newReactant.setAnnotation(new Annotation()); newReaction.addReactant(newReactant); } //loop through products for (SpeciesReference product : reaction.getListOfProducts()) { //create a new reactant and add it to the new reaction SpeciesReference newProduct = new SpeciesReference(); newProduct = product.clone(); newProduct.setSpecies("ROW" + row + "_COL" + col + "__" + newProduct.getSpecies()); newProduct.setAnnotation(new Annotation()); newReaction.addProduct(newProduct); } boolean i = false, j = false; for (LocalParameter lp : newReaction.getKineticLaw().getListOfLocalParameters()) { if (lp.getId().equals("i")) i = true; else if (lp.getId().equals("j")) j = true; } if (i) newReaction.getKineticLaw().getListOfLocalParameters().remove("i"); if (j) newReaction.getKineticLaw().getListOfLocalParameters().remove("j"); reactionsToAdd.add(newReaction); ++membraneDiffusionIndex; } } //end if membrane diffusion //NON-MEMBRANE DIFFUSION REACTIONS //check to see if the (non-membrane-diffusion) reaction has arrayed species //right now i'm only checking the first reactant species, due to a bad assumption //about the homogeneity of the arrayed reaction (ie, if one species is arrayed, they all are) else if (reaction.getNumReactants() > 0 && speciesToIsArrayedMap.get(reaction.getReactant(0).getSpeciesInstance().getId()) == true) { arraysExist = true; reactionsToRemove.add(reaction.getId()); //get the reactant dimensions, which tells us how many new reactions are going to be created SpeciesDimensions reactantDimensions = arrayedSpeciesToDimensionsMap.get(reaction.getReactant(0).getSpeciesInstance().getId()); boolean abort = false; //loop through all of the new formerly-implicit reactants for (int row = reactantDimensions.numRowsLower; row <= reactantDimensions.numRowsUpper; ++row) { for (int col = reactantDimensions.numColsLower; col <= reactantDimensions.numColsUpper; ++col) { //create a new reaction and set the ID Reaction newReaction = new Reaction(); newReaction = reaction.clone(); newReaction.setListOfReactants(new ListOf<SpeciesReference>()); newReaction.setListOfProducts(new ListOf<SpeciesReference>()); newReaction.setListOfModifiers(new ListOf<ModifierSpeciesReference>()); newReaction.setId("ROW" + row + "_COL" + col + "_" + reactionID); newReaction.setMetaId("ROW" + row + "_COL" + col + "_" + reactionID); newReaction.setReversible(false); newReaction.setFast(false); newReaction.setCompartment(reaction.getCompartment()); //get the nodes to alter ArrayList<ASTNode> get2DArrayElementNodes = new ArrayList<ASTNode>(); //return the head node of the get2DArrayElement function getSatisfyingNodes(newReaction.getKineticLaw().getMath(), "get2DArrayElement", get2DArrayElementNodes); //loop through all reactants for (SpeciesReference reactant : reaction.getListOfReactants()) { //find offsets //the row offset is in the kinetic law via i //the col offset is in the kinetic law via j int rowOffset = 0; int colOffset = 0; ASTNode reactantHeadNode = null; //go through the get2DArrayElement nodes and find the one corresponding to the reactant for (ASTNode headNode : get2DArrayElementNodes) { //make sure it's a reactant node if (headNode.getChildCount() > 0 && model.getParameter(headNode.getLeftChild().getName()) == null) { reactantHeadNode = headNode; break; } } if (reactantHeadNode.getChild(1).getType().name().equals("PLUS")) rowOffset = reactantHeadNode.getChild(1).getRightChild().getInteger(); else if (reactantHeadNode.getChild(1).getType().name().equals("MINUS")) rowOffset = -1 * reactantHeadNode.getChild(1).getRightChild().getInteger(); if (reactantHeadNode.getChild(2).getType().name().equals("PLUS")) colOffset = reactantHeadNode.getChild(2).getRightChild().getInteger(); else if (reactantHeadNode.getChild(2).getType().name().equals("MINUS")) colOffset = -1 * reactantHeadNode.getChild(2).getRightChild().getInteger(); //create a new reactant and add it to the new reaction SpeciesReference newReactant = new SpeciesReference(); newReactant = reactant.clone(); newReactant.setSpecies(model.getSpecies("ROW" + (row + rowOffset) + "_COL" + (col + colOffset) + "__" + newReactant.getSpecies())); newReactant.setAnnotation(new Annotation()); newReaction.addReactant(newReactant); //put this reactant in place of the get2DArrayElement function call for (int i = 0; i < reactantHeadNode.getChildCount(); ++i) reactantHeadNode.removeChild(i); for (int i = 0; i < reactantHeadNode.getChildCount(); ++i) reactantHeadNode.removeChild(i); reactantHeadNode.setVariable(model.getSpecies(newReactant.getSpecies())); }// end looping through reactants //loop through all modifiers //for (ModifierSpeciesReference modifier : reaction.getListOfModifiers()) { //loop through all products for (SpeciesReference product : reaction.getListOfProducts()) { //find offsets int rowOffset = 0; int colOffset = 0; ASTNode productHeadNode = null; //go through the get2DArrayElement nodes and find the one corresponding to the product for (ASTNode headNode : get2DArrayElementNodes) { //make sure it's a product node //only the product has children, as the reactant's children get deleted if (headNode.getChildCount() > 0 && model.getParameter(headNode.getLeftChild().getName()) == null) { productHeadNode = headNode; break; } } if (productHeadNode.getChild(1).getType().name().equals("PLUS")) rowOffset = productHeadNode.getChild(1).getRightChild().getInteger(); else if (productHeadNode.getChild(1).getType().name().equals("MINUS")) rowOffset = -1 * productHeadNode.getChild(1).getRightChild().getInteger(); if (productHeadNode.getChild(2).getType().name().equals("PLUS")) colOffset = productHeadNode.getChild(2).getRightChild().getInteger(); else if (productHeadNode.getChild(2).getType().name().equals("MINUS")) colOffset = -1 * productHeadNode.getChild(2).getRightChild().getInteger(); //don't create reactions with products that don't exist if (row + rowOffset < reactantDimensions.numRowsLower || col + colOffset < reactantDimensions.numColsLower || row + rowOffset > reactantDimensions.numRowsUpper || col + colOffset > reactantDimensions.numColsUpper) { abort = true; break; } //create a new product and add it to the new reaction SpeciesReference newProduct = new SpeciesReference(); newProduct = product.clone(); newProduct.setSpecies(model.getSpecies("ROW" + (row + rowOffset) + "_COL" + (col + colOffset) + "__" + newProduct.getSpecies())); newProduct.setAnnotation(new Annotation()); newReaction.addProduct(newProduct); //put this reactant in place of the get2DArrayElement function call for (int i = 0; i < productHeadNode.getChildCount(); ++i) productHeadNode.removeChild(i); //put this reactant in place of the get2DArrayElement function call for (int i = 0; i < productHeadNode.getChildCount(); ++i) productHeadNode.removeChild(i); productHeadNode.setVariable(model.getSpecies(newProduct.getSpecies())); } //end looping through products if (abort == false) { boolean i = false, j = false; //checking for these local parameters using getLocalParameters() doesn't seem to work for (LocalParameter lp : newReaction.getKineticLaw().getListOfLocalParameters()) { if (lp.getId().equals("i")) i = true; else if (lp.getId().equals("j")) j = true; } if (i) newReaction.getKineticLaw().getListOfLocalParameters().remove("i"); if (j) newReaction.getKineticLaw().getListOfLocalParameters().remove("j"); //this isn't a reversible reaction; only take the left side if (newReaction.getId().contains("Degradation") == false) { newReaction.getKineticLaw().setMath(newReaction.getKineticLaw().getMath().getLeftChild()); } reactionsToAdd.add(newReaction); } else abort = false; } } } }// end looping through reactions //add in the new explicit array reactions for (Reaction reactionToAdd : reactionsToAdd) { reactionToAdd.setMetaId(reactionToAdd.getId()); if (model.getReaction(reactionToAdd.getId())!=null) { model.removeReaction(reactionToAdd.getId()); } model.addReaction(reactionToAdd); } ListOf<Reaction> allReactions = model.getListOfReactions(); //remove original array reaction(s) for (String reactionToRemove : reactionsToRemove) allReactions.remove(reactionToRemove); model.setListOfReactions(allReactions); ListOf<Species> allSpecies = model.getListOfSpecies(); //remove the original array species from the model for (String speciesID : speciesToRemove) allSpecies.remove(speciesID); model.setListOfSpecies(allSpecies); ListOf<Event> allEvents = model.getListOfEvents(); //remove original array event(s) for (String eventID : eventsToRemove) allEvents.remove(eventID); model.setListOfEvents(allEvents); ArrayList<String> parametersToRemove = new ArrayList<String>(); //get rid of the locations parameters for (Parameter parameter : model.getListOfParameters()) { if (parameter.getId().contains("_locations")) { if (parameter.getId().contains("_locations")) this.submodelIDToLocationsMap.put( parameter.getId().replace("__locations",""), stripAnnotation(parameter.getAnnotationString())); parametersToRemove.add(parameter.getId()); } } for (String parameterID : parametersToRemove) model.removeParameter(parameterID); if (arraysExist) { SBMLWriter writer = new SBMLWriter(); PrintStream p; try { p = new PrintStream(new FileOutputStream(SBMLFileName), true, "UTF-8"); p.print(writer.writeSBMLToString(model.getSBMLDocument())); } catch (Exception e) { e.printStackTrace(); } } } /** * creates hashmaps for representing and keeping track of a grid (of cells) */ protected void setupGrid() { //go through all reaction IDs and group them by compartment ID for (String reactionID : reactionToPropensityMap.keySet()) { if (reactionID.contains("__") == false) continue; //this will leave us with compartmentID or stuff_compartmentID String componentID = ((String[])reactionID.split("__"))[0]; //if there's an underscore, remove everything before it to leave the compartmentID String[] splitReactionID = componentID.split("_"); componentID = splitReactionID[splitReactionID.length - 1]; //the location of the component can be parsed from the membrane diffusion reaction product if (reactionID.contains("MembraneDiffusion")) { String productID = ""; for (StringDoublePair sdp : reactionToSpeciesAndStoichiometrySetMap.get(reactionID)) { if (sdp.string.contains("ROW") && sdp.string.contains("COL")) productID = sdp.string; } String[] locationInfo = ((String[])productID.split("__"))[0].split("_"); int row, col; if (locationInfo[0].length() <= 0) { row = 0; col = 0; } else { row = Integer.valueOf(locationInfo[0].replace("ROW","")); col = Integer.valueOf(locationInfo[1].replace("COL","")); } componentToLocationMap.put(componentID, new Point(row, col)); } if (componentToReactionSetMap.containsKey(componentID) == false) componentToReactionSetMap.put(componentID, new HashSet<String>()); componentToReactionSetMap.get(componentID).add(reactionID); } //go through the species and parameters and group them by compartment ID for (String variableID : variableToValueMap.keySet()) { if (variableID.contains("__") == false) continue; //this will leave us with compartmentID or stuff_compartmentID String componentID = ((String[])variableID.split("__"))[0]; //if there's an underscore, remove everything before it to leave the compartmentID String[] splitVariableID = componentID.split("_"); componentID = splitVariableID[splitVariableID.length - 1]; if (componentToVariableSetMap.containsKey(componentID) == false) componentToVariableSetMap.put(componentID, new HashSet<String>()); componentToVariableSetMap.get(componentID).add(variableID); } //go through events and group them by compartment ID if (eventToDelayMap != null) { for (String eventID : eventToDelayMap.keySet()) { if (eventID.contains("__") == false) continue; String componentID = ((String[])eventID.split("__"))[0]; //if there's an underscore, remove everything before it to leave the compartmentID String[] splitEventID = componentID.split("_"); componentID = splitEventID[splitEventID.length - 1]; componentIDSet.add(componentID); if (componentToEventSetMap.containsKey(componentID) == false) componentToEventSetMap.put(componentID, new HashSet<String>()); componentToEventSetMap.get(componentID).add(eventID); } } //if the location information couldn't be parsed from membrane diffusion reactions //(ie, if there aren't any membrane diffusion reactions) if (componentToLocationMap.size() < componentToVariableSetMap.size()) { for (String annotationString : this.submodelIDToLocationsMap.values()) { annotationString = annotationString.replace("<annotation>",""). replace("</annotation>","").replace("\"",""); String[] splitAnnotation = annotationString.split("array:"); splitAnnotation[splitAnnotation.length - 2] = ((String[])splitAnnotation[splitAnnotation.length - 2].split("xmlns:"))[0]; for (int i = 2; i < splitAnnotation.length; ++i) { String compartmentID = ((String[])splitAnnotation[i].split("="))[0]; String row = ((String[])((String[])splitAnnotation[i].split(" ")[0].split("="))[1].split(","))[0].replace("(",""); String col = ((String[])((String[])splitAnnotation[i].split(" ")[0].split("="))[1].split(","))[1].replace(")",""); componentToLocationMap.put(compartmentID, new Point(Integer.valueOf(row.trim()), Integer.valueOf(col.trim()))); } } } } /** * sets up a single species * * @param species * @param speciesID */ private void setupSingleSpecies(Species species, String speciesID) { speciesID = speciesID.replace("_negative_", "-"); if (speciesIDSet.contains(speciesID)) return; if (species.isSetInitialAmount()) variableToValueMap.put(speciesID, species.getInitialAmount()); else if (species.isSetInitialConcentration()) { variableToValueMap.put(speciesID, species.getInitialConcentration() * species.getCompartmentInstance().getSize()); } if (species.getConversionFactor() != null) speciesToConversionFactorMap.put(speciesID, species.getConversionFactor()); if (numRules > 0) variableToIsInAssignmentRuleMap.put(speciesID, false); if (numConstraints > 0) variableToIsInConstraintMap.put(speciesID, false); if (species.hasOnlySubstanceUnits() == false) { speciesToCompartmentSizeMap.put(speciesID, species.getCompartmentInstance().getSize()); speciesToCompartmentNameMap.put(speciesID, species.getCompartment()); if (Double.isNaN(species.getCompartmentInstance().getSize())) speciesToCompartmentSizeMap.put(speciesID, 1.0); } speciesToAffectedReactionSetMap.put(speciesID, new HashSet<String>(20)); speciesToIsBoundaryConditionMap.put(speciesID, species.isBoundaryCondition()); variableToIsConstantMap.put(speciesID, species.isConstant()); speciesToHasOnlySubstanceUnitsMap.put(speciesID, species.hasOnlySubstanceUnits()); speciesIDSet.add(speciesID); } /** * puts species-related information into data structures * * @throws IOException */ protected void setupSpecies() throws IOException { //add values to hashmap for easy access to species amounts for (Species species : model.getListOfSpecies()) { setupSingleSpecies(species, species.getId()); } } /** * puts initial assignment-related information into data structures */ protected void setupInitialAssignments() { HashSet<AssignmentRule> allAssignmentRules = new HashSet<AssignmentRule>(); //perform all assignment rules for (Rule rule : model.getListOfRules()) { if (rule.isAssignment()) allAssignmentRules.add((AssignmentRule)rule); } performAssignmentRules(allAssignmentRules); HashSet<String> affectedVariables = new HashSet<String>(); //calculate initial assignments a lot of times in case there are dependencies //running it the number of initial assignments times will avoid problems //and all of them will be fully calculated and determined for (int i = 0; i < numInitialAssignments; ++i) { for (InitialAssignment initialAssignment : model.getListOfInitialAssignments()) { String variable = initialAssignment.getVariable().replace("_negative_","-"); initialAssignment.setMath(inlineFormula(initialAssignment.getMath())); if (speciesToHasOnlySubstanceUnitsMap.containsKey(variable) && speciesToHasOnlySubstanceUnitsMap.get(variable) == false) { variableToValueMap.put(variable, evaluateExpressionRecursive(initialAssignment.getMath()) * variableToValueMap.get(speciesToCompartmentNameMap.get(variable))); } else { variableToValueMap.put(variable, evaluateExpressionRecursive(initialAssignment.getMath())); } affectedVariables.add(variable); } } //perform assignment rules again for variable that may have changed due to the initial assignments //they aren't set up yet, so just perform them all performAssignmentRules(allAssignmentRules); //this is kind of weird, but apparently if an initial assignment changes a compartment size //i need to go back and update species amounts because they used the non-changed-by-assignment sizes for (Species species : model.getListOfSpecies()) { if (species.isSetInitialConcentration()) { String speciesID = species.getId(); //revert to the initial concentration value if (Double.isNaN(variableToValueMap.get(speciesID)) == false) variableToValueMap.put(speciesID, variableToValueMap.get(speciesID) / species.getCompartmentInstance().getSize()); else variableToValueMap.put(speciesID, species.getInitialConcentration()); //multiply by the new compartment size to get into amount variableToValueMap.put(speciesID, variableToValueMap.get(speciesID) * variableToValueMap.get(speciesToCompartmentNameMap.get(speciesID))); } } } /** * sets up the local parameters in a single kinetic law * * @param kineticLaw * @param reactionID */ private void setupLocalParameters(KineticLaw kineticLaw, Reaction reaction) { String reactionID = reaction.getId(); reactionID = reactionID.replace("_negative_","-"); for (int i = 0; i < kineticLaw.getLocalParameterCount(); i++) { LocalParameter localParameter = kineticLaw.getLocalParameter(i); String parameterID = ""; //the parameters don't get reset after each run, so don't re-do this prepending if (localParameter.getId().contains(reactionID + "_") == false) parameterID = reactionID + "_" + localParameter.getId(); else parameterID = localParameter.getId(); //System.out.println("Before: " + localParameter.getId() + " after: " + parameterID); String oldParameterID = localParameter.getId(); variableToValueMap.put(parameterID, localParameter.getValue()); //alter the local parameter ID so that it goes to the local and not global value if (localParameter.getId() != parameterID) { localParameter.setId(parameterID); localParameter.setMetaId(parameterID); } //System.out.println("After: " + localParameter.getId()); //for some reason, changing the local parameter sometimes changes the kinetic law instances //of that parameter id (and sometimes doesn't), so those ones are fine and ignore them //if (kineticLaw.getMath().toFormula().contains(parameterID) == false) { alterLocalParameter(kineticLaw.getMath(), reaction, oldParameterID, parameterID); } //System.out.println(kineticLaw.getMath().toFormula()); } /** * sets up a single (non-local) parameter * * @param parameter */ private void setupSingleParameter(Parameter parameter) { String parameterID = parameter.getId(); variableToValueMap.put(parameterID, parameter.getValue()); variableToIsConstantMap.put(parameterID, parameter.getConstant()); if (parameter.getConstant() == false) nonconstantParameterIDSet.add(parameterID); if (numRules > 0) variableToIsInAssignmentRuleMap.put(parameterID, false); if (numConstraints > 0) variableToIsInConstraintMap.put(parameterID, false); } /** * puts parameter-related information into data structures */ protected void setupParameters() { //add local parameters for (Reaction reaction : model.getListOfReactions()) { KineticLaw kineticLaw = reaction.getKineticLaw(); setupLocalParameters(kineticLaw, reaction); } //add values to hashmap for easy access to global parameter values //NOTE: the IDs for the parameters and species must be unique, so putting them in the //same hashmap is okay for (Parameter parameter : model.getListOfParameters()) { setupSingleParameter(parameter); } //add compartment sizes in for (Compartment compartment : model.getListOfCompartments()) { String compartmentID = compartment.getId(); compartmentIDSet.add(compartmentID); variableToValueMap.put(compartmentID, compartment.getSize()); if (Double.isNaN(compartment.getSize())) variableToValueMap.put(compartmentID, 1.0); variableToIsConstantMap.put(compartmentID, compartment.getConstant()); if (numRules > 0) variableToIsInAssignmentRuleMap.put(compartmentID, false); if (numConstraints > 0) variableToIsInConstraintMap.put(compartmentID, false); } } /** * puts rule-related information into data structures */ protected void setupRules() { numAssignmentRules = 0; numRateRules = 0; //NOTE: assignmentrules are performed in setupinitialassignments //loop through all assignment rules //store which variables (RHS) affect the rule variable (LHS) //so when those RHS variables change, we know to re-evaluate the rule //and change the value of the LHS variable for (Rule rule : model.getListOfRules()) { if (rule.isAssignment()) { //Rules don't have a getVariable method, so this needs to be cast to an ExplicitRule rule.setMath(inlineFormula(rule.getMath())); AssignmentRule assignmentRule = (AssignmentRule) rule; //list of all children of the assignmentRule math ArrayList<ASTNode> formulaChildren = new ArrayList<ASTNode>(); if (assignmentRule.getMath().getChildCount() == 0) formulaChildren.add(assignmentRule.getMath()); else getAllASTNodeChildren(assignmentRule.getMath(), formulaChildren); for (ASTNode ruleNode : formulaChildren) { if (ruleNode.isName()) { String nodeName = ruleNode.getName(); variableToAffectedAssignmentRuleSetMap.put(nodeName, new HashSet<AssignmentRule>()); variableToAffectedAssignmentRuleSetMap.get(nodeName).add(assignmentRule); variableToIsInAssignmentRuleMap.put(nodeName, true); } } ++numAssignmentRules; } else if (rule.isRate()) { //Rules don't have a getVariable method, so this needs to be cast to an ExplicitRule rule.setMath(inlineFormula(rule.getMath())); RateRule rateRule = (RateRule) rule; //list of all children of the assignmentRule math ArrayList<ASTNode> formulaChildren = new ArrayList<ASTNode>(); if (rateRule.getMath().getChildCount() == 0) formulaChildren.add(rateRule.getMath()); else getAllASTNodeChildren(rateRule.getMath(), formulaChildren); for (ASTNode ruleNode : formulaChildren) { if (ruleNode.isName()) { String nodeName = ruleNode.getName(); //not sure these are needed, as they only evaluate with each time step //not when other variables update // variableToAffectedRateRuleSetMap.put(nodeName, new HashSet<AssignmentRule>()); // variableToAffectedRateRuleSetMap.get(nodeName).add(rateRule); variableToIsInRateRuleMap.put(nodeName, true); } } ++numRateRules; } } //don't think this is necessary // //loop through the formulas and inline any user-defined functions // for (Rule rule : model.getListOfRules()) { // if (rule.isAssignment() || rule.isRate()) { // rule.setMath(inlineFormula(rule.getMath())); // System.err.println(rule.getMath()); } /** * puts constraint-related information into data structures */ protected void setupConstraints() { //loop through all constraints to find out which variables affect which constraints //this is stored in a hashmap, as is whether the variable is in a constraint for (Constraint constraint : model.getListOfConstraints()) { constraint.setMath(inlineFormula(constraint.getMath())); for (ASTNode constraintNode : constraint.getMath().getListOfNodes()) { if (constraintNode.isName()) { String nodeName = constraintNode.getName(); variableToAffectedConstraintSetMap.put(nodeName, new HashSet<ASTNode>()); variableToAffectedConstraintSetMap.get(nodeName).add(constraint.getMath()); variableToIsInConstraintMap.put(nodeName, true); } } } } /** * sets up a single event * * @param event */ protected void setupSingleEvent(Event event) { String eventID = event.getId(); //these events are what determines if a model is dynamic or not if (eventID.contains("Division__") || eventID.contains("Death__") || eventID.contains("__Move")) dynamicBoolean = true; if (event.isSetPriority()) eventToPriorityMap.put(eventID, inlineFormula(event.getPriority().getMath())); if (event.isSetDelay()) { eventToDelayMap.put(eventID, inlineFormula(event.getDelay().getMath())); eventToHasDelayMap.put(eventID, true); } else eventToHasDelayMap.put(eventID, false); if (event.getTrigger().getMath().toFormula().contains("neighborQuantity") == false) event.getTrigger().setMath(inlineFormula(event.getTrigger().getMath())); eventToTriggerMap.put(eventID, event.getTrigger().getMath()); eventToTriggerInitiallyTrueMap.put(eventID, event.getTrigger().isInitialValue()); eventToPreviousTriggerValueMap.put(eventID, event.getTrigger().isInitialValue()); eventToTriggerPersistenceMap.put(eventID, event.getTrigger().getPersistent()); eventToUseValuesFromTriggerTimeMap.put(eventID, event.isUseValuesFromTriggerTime()); eventToAssignmentSetMap.put(eventID, new HashSet<Object>()); eventToAffectedReactionSetMap.put(eventID, new HashSet<String>()); untriggeredEventSet.add(eventID); for (EventAssignment assignment : event.getListOfEventAssignments()) { String variableID = assignment.getVariable(); assignment.setMath(inlineFormula(assignment.getMath())); eventToAssignmentSetMap.get(eventID).add(assignment); if (variableToEventSetMap.containsKey(variableID) == false) variableToEventSetMap.put(variableID, new HashSet<String>()); variableToEventSetMap.get(variableID).add(eventID); //if the variable is a species, add the reactions it's in //to the event to affected reaction hashmap, which is used //for updating propensities after an event fires if (speciesToAffectedReactionSetMap.containsKey(variableID)) { eventToAffectedReactionSetMap.get(eventID).addAll( speciesToAffectedReactionSetMap.get(variableID)); } } } /** * puts event-related information into data structures */ protected void setupEvents() { //add event information to hashmaps for easy/fast access //this needs to happen after calculating initial propensities //so that the speciesToAffectedReactionSetMap is populated for (Event event : model.getListOfEvents()) { setupSingleEvent(event); } } /** * does a minimized initialization process to prepare for a new run */ protected abstract void setupForNewRun(int newRun); /** * opens output file and seeds rng for new run * * @param randomSeed * @param currentRun * @throws IOException */ protected void setupForOutput(long randomSeed, int currentRun) { this.currentRun = currentRun; randomNumberGenerator = new XORShiftRandom(randomSeed); try { String extension = ".tsd"; if (dynamicBoolean == true) extension = ".dtsd"; TSDWriter = new FileWriter(outputDirectory + "run-" + currentRun + extension); bufferedTSDWriter = new BufferedWriter(TSDWriter); bufferedTSDWriter.write('('); if (currentRun > 1 && dynamicBoolean == false) { bufferedTSDWriter.write("(" + "\"" + "time" + "\""); //if there's an interesting species, only those get printed if (interestingSpecies.size() > 0) { for (String speciesID : interestingSpecies) bufferedTSDWriter.write(", \"" + speciesID + "\""); if (dynamicBoolean == false) bufferedTSDWriter.write("),\n"); } else { for (String speciesID : speciesIDSet) { bufferedTSDWriter.write(", \"" + speciesID + "\""); } //print compartment IDs (for sizes) for (String componentID : compartmentIDSet) { bufferedTSDWriter.write(", \"" + componentID + "\""); } //print nonconstant parameter IDs for (String parameterID : nonconstantParameterIDSet) { try { bufferedTSDWriter.write(", \"" + parameterID + "\""); } catch (IOException e) { e.printStackTrace(); } } bufferedTSDWriter.write("),\n"); } } } catch (IOException e) { e.printStackTrace(); } } /** * calculates the initial propensity of a single reaction * also does some initialization stuff * * @param reactionID * @param reactionFormula * @param reversible * @param reactantsList * @param productsList * @param modifiersList */ private void setupSingleReaction(String reactionID, ASTNode reactionFormula, boolean reversible, ListOf<SpeciesReference> reactantsList, ListOf<SpeciesReference> productsList, ListOf<ModifierSpeciesReference> modifiersList) { reactionID = reactionID.replace("_negative_","-"); boolean notEnoughMoleculesFlagFd = false; boolean notEnoughMoleculesFlagRv = false; boolean notEnoughMoleculesFlag = false; //if it's a reversible reaction //split into a forward and reverse reaction (based on the minus sign in the middle) //and calculate both propensities if (reversible == true) { //distributes the left child across the parentheses if (reactionFormula.getType().equals(ASTNode.Type.TIMES)) { ASTNode distributedNode = new ASTNode(); reactionFormula = inlineFormula(reactionFormula); if (reactionFormula.getChildCount() >= 2 && reactionFormula.getChild(1).getType().equals(ASTNode.Type.PLUS)) distributedNode = ASTNode.sum( ASTNode.times(reactionFormula.getLeftChild(), reactionFormula.getRightChild().getLeftChild()), ASTNode.times(new ASTNode(-1), reactionFormula.getLeftChild(), reactionFormula.getRightChild().getRightChild())); else if (reactionFormula.getChildCount() >= 2 && reactionFormula.getChild(1).getType().equals(ASTNode.Type.MINUS)) distributedNode = ASTNode.diff( ASTNode.times(reactionFormula.getLeftChild(), reactionFormula.getRightChild().getLeftChild()), ASTNode.times(reactionFormula.getLeftChild(), reactionFormula.getRightChild().getRightChild())); reactionFormula = distributedNode; } reactionToSpeciesAndStoichiometrySetMap.put(reactionID + "_fd", new HashSet<StringDoublePair>()); reactionToSpeciesAndStoichiometrySetMap.put(reactionID + "_rv", new HashSet<StringDoublePair>()); reactionToReactantStoichiometrySetMap.put(reactionID + "_fd", new HashSet<StringDoublePair>()); reactionToReactantStoichiometrySetMap.put(reactionID + "_rv", new HashSet<StringDoublePair>()); for (SpeciesReference reactant : reactantsList) { String reactantID = reactant.getSpecies().replace("_negative_","-"); //stoichiometry amplification -- alter the stoichiometry if (reactionID.contains("_Diffusion_") && stoichAmpBoolean == true) reactant.setStoichiometry(stoichAmpGridValue); double reactantStoichiometry; //if there was an initial assignment for the reactant //this applies regardless of constancy of the reactant if (variableToValueMap.containsKey(reactant.getId())) reactantStoichiometry = variableToValueMap.get(reactant.getId()); else reactantStoichiometry = reactant.getStoichiometry(); reactionToSpeciesAndStoichiometrySetMap.get(reactionID + "_fd").add( new StringDoublePair(reactantID, -reactantStoichiometry)); reactionToSpeciesAndStoichiometrySetMap.get(reactionID + "_rv").add( new StringDoublePair(reactantID, reactantStoichiometry)); //not having a minus sign is intentional as this isn't used for calculations reactionToReactantStoichiometrySetMap.get(reactionID + "_fd").add( new StringDoublePair(reactantID, reactantStoichiometry)); //if there was not initial assignment for the reactant if (reactant.getConstant() == false && variableToValueMap.containsKey(reactant.getId()) == false && reactant.getId().length() > 0) { if (reactionToNonconstantStoichiometriesSetMap.containsKey(reactionID + "_fd") == false) reactionToNonconstantStoichiometriesSetMap.put(reactionID + "_fd", new HashSet<StringStringPair>()); if (reactionToNonconstantStoichiometriesSetMap.containsKey(reactionID + "_rv") == false) reactionToNonconstantStoichiometriesSetMap.put(reactionID + "_rv", new HashSet<StringStringPair>()); reactionToNonconstantStoichiometriesSetMap.get(reactionID + "_fd") .add(new StringStringPair(reactantID + "_fd", reactant.getId())); reactionToNonconstantStoichiometriesSetMap.get(reactionID + "_rv") .add(new StringStringPair(reactantID + "_rv", reactant.getId())); variableToValueMap.put(reactant.getId(), reactantStoichiometry); } //as a reactant, this species affects the reaction's propensity in the forward direction speciesToAffectedReactionSetMap.get(reactantID).add(reactionID + "_fd"); //make sure there are enough molecules for this species //(in the reverse direction, molecules aren't subtracted, but added) if (variableToValueMap.get(reactantID) < reactantStoichiometry) notEnoughMoleculesFlagFd = true; } for (SpeciesReference product : productsList) { String productID = product.getSpecies().replace("_negative_","-"); //stoichiometry amplification -- alter the stoichiometry if (reactionID.contains("_Diffusion_") && stoichAmpBoolean == true) product.setStoichiometry(stoichAmpGridValue); double productStoichiometry; //if there was an initial assignment if (variableToValueMap.containsKey(product.getId())) productStoichiometry = variableToValueMap.get(product.getId()); else productStoichiometry = product.getStoichiometry(); reactionToSpeciesAndStoichiometrySetMap.get(reactionID + "_fd").add( new StringDoublePair(productID, productStoichiometry)); reactionToSpeciesAndStoichiometrySetMap.get(reactionID + "_rv").add( new StringDoublePair(productID, -productStoichiometry)); //not having a minus sign is intentional as this isn't used for calculations reactionToReactantStoichiometrySetMap.get(reactionID + "_rv").add( new StringDoublePair(productID, productStoichiometry)); //if there wasn't an initial assignment if (product.getConstant() == false && variableToValueMap.containsKey(product.getId()) == false && product.getId().length() > 0) { if (reactionToNonconstantStoichiometriesSetMap.containsKey(reactionID) == false) reactionToNonconstantStoichiometriesSetMap.put(reactionID, new HashSet<StringStringPair>()); reactionToNonconstantStoichiometriesSetMap.get(reactionID) .add(new StringStringPair(productID, product.getId())); variableToValueMap.put(product.getId(), productStoichiometry); } //as a product, this species affects the reaction's propensity in the reverse direction speciesToAffectedReactionSetMap.get(productID).add(reactionID + "_rv"); //make sure there are enough molecules for this species //(in the forward direction, molecules aren't subtracted, but added) if (variableToValueMap.get(productID) < productStoichiometry) notEnoughMoleculesFlagRv = true; } for (ModifierSpeciesReference modifier : modifiersList) { String modifierID = modifier.getSpecies(); modifierID = modifierID.replace("_negative_","-"); String forwardString = "", reverseString = ""; try { forwardString = ASTNode.formulaToString(reactionFormula.getLeftChild()); reverseString = ASTNode.formulaToString(reactionFormula.getRightChild()); } catch (SBMLException e) { e.printStackTrace(); } //check the kinetic law to see which direction the modifier affects the reaction's propensity if (forwardString.contains(modifierID)) speciesToAffectedReactionSetMap.get(modifierID).add(reactionID + "_fd"); if (reverseString.contains(modifierID)) speciesToAffectedReactionSetMap.get(modifierID).add(reactionID + "_rv"); } double propensity; reactionToFormulaMap.put(reactionID + "_rv", inlineFormula(reactionFormula.getRightChild())); reactionToFormulaMap.put(reactionID + "_fd", inlineFormula(reactionFormula.getLeftChild())); //calculate forward reaction propensity if (notEnoughMoleculesFlagFd == true) propensity = 0.0; else { //the left child is what's left of the minus sign propensity = evaluateExpressionRecursive(inlineFormula(reactionFormula.getLeftChild())); //stoichiometry amplification -- alter the propensity if (reactionID.contains("_Diffusion_") && stoichAmpBoolean == true) propensity *= (1.0 / stoichAmpGridValue); if ((propensity < minPropensity) && (propensity > 0)) minPropensity = propensity; if (propensity > maxPropensity) maxPropensity = propensity; totalPropensity += propensity; } reactionToPropensityMap.put(reactionID + "_fd", propensity); //calculate reverse reaction propensity if (notEnoughMoleculesFlagRv == true) propensity = 0.0; else { //the right child is what's right of the minus sign propensity = evaluateExpressionRecursive(inlineFormula(reactionFormula.getRightChild())); //stoichiometry amplification -- alter the propensity if (reactionID.contains("_Diffusion_") && stoichAmpBoolean == true) propensity *= (1.0 / stoichAmpGridValue); if ((propensity < minPropensity) && (propensity > 0)) minPropensity = propensity; if (propensity > maxPropensity) maxPropensity = propensity; totalPropensity += propensity; } reactionToPropensityMap.put(reactionID + "_rv", propensity); } //if it's not a reversible reaction else { reactionToSpeciesAndStoichiometrySetMap.put(reactionID, new HashSet<StringDoublePair>()); reactionToReactantStoichiometrySetMap.put(reactionID, new HashSet<StringDoublePair>()); for (SpeciesReference reactant : reactantsList) { String reactantID = reactant.getSpecies().replace("_negative_","-"); //stoichiometry amplification -- alter the stoichiometry if (reactionID.contains("_Diffusion_") && stoichAmpBoolean == true) { reactant.setStoichiometry(stoichAmpGridValue); } double reactantStoichiometry; //if there was an initial assignment for the speciesref id if (variableToValueMap.containsKey(reactant.getId())) reactantStoichiometry = variableToValueMap.get(reactant.getId()); else reactantStoichiometry = reactant.getStoichiometry(); reactionToSpeciesAndStoichiometrySetMap.get(reactionID).add( new StringDoublePair(reactantID, -reactantStoichiometry)); reactionToReactantStoichiometrySetMap.get(reactionID).add( new StringDoublePair(reactantID, reactantStoichiometry)); //if there wasn't an initial assignment if (reactant.getConstant() == false && variableToValueMap.containsKey(reactant.getId()) == false && reactant.getId().length() > 0) { if (reactionToNonconstantStoichiometriesSetMap.containsKey(reactionID) == false) reactionToNonconstantStoichiometriesSetMap.put(reactionID, new HashSet<StringStringPair>()); reactionToNonconstantStoichiometriesSetMap.get(reactionID) .add(new StringStringPair(reactantID, reactant.getId())); variableToValueMap.put(reactant.getId(), reactantStoichiometry); } //as a reactant, this species affects the reaction's propensity speciesToAffectedReactionSetMap.get(reactantID).add(reactionID); //make sure there are enough molecules for this species if (variableToValueMap.get(reactantID) < reactantStoichiometry) notEnoughMoleculesFlag = true; } for (SpeciesReference product : productsList) { //stoichiometry amplification -- alter the stoichiometry if (reactionID.contains("_Diffusion_") && stoichAmpBoolean == true) product.setStoichiometry(stoichAmpGridValue); String productID = product.getSpecies().replace("_negative_","-"); double productStoichiometry; //if there was an initial assignment for the speciesref id if (variableToValueMap.containsKey(product.getId())) productStoichiometry = variableToValueMap.get(product.getId()); else productStoichiometry = product.getStoichiometry(); reactionToSpeciesAndStoichiometrySetMap.get(reactionID).add( new StringDoublePair(productID, productStoichiometry)); if (product.getConstant() == false && variableToValueMap.containsKey(product.getId()) == false && product.getId().length() > 0) { if (reactionToNonconstantStoichiometriesSetMap.containsKey(reactionID) == false) reactionToNonconstantStoichiometriesSetMap.put(reactionID, new HashSet<StringStringPair>()); reactionToNonconstantStoichiometriesSetMap.get(reactionID) .add(new StringStringPair(productID, product.getId())); variableToValueMap.put(product.getId(), productStoichiometry); } //don't need to check if there are enough, because products are added } for (ModifierSpeciesReference modifier : modifiersList) { String modifierID = modifier.getSpecies(); modifierID = modifierID.replace("_negative_","-"); //as a modifier, this species affects the reaction's propensity speciesToAffectedReactionSetMap.get(modifierID).add(reactionID); } reactionToFormulaMap.put(reactionID, inlineFormula(reactionFormula)); double propensity; if (notEnoughMoleculesFlag == true) propensity = 0.0; else { //calculate propensity propensity = evaluateExpressionRecursive(inlineFormula(reactionFormula)); //stoichiometry amplification -- alter the propensity if (reactionID.contains("_Diffusion_") && stoichAmpBoolean == true) propensity *= (1.0 / stoichAmpGridValue); if (propensity < minPropensity && propensity > 0) minPropensity = propensity; if (propensity > maxPropensity) maxPropensity = propensity; totalPropensity += propensity; } reactionToPropensityMap.put(reactionID, propensity); } } /** * calculates the initial propensities for each reaction in the model * * @param numReactions the number of reactions in the model */ protected void setupReactions() { //loop through all reactions and calculate their propensities for (Reaction reaction : model.getListOfReactions()) { String reactionID = reaction.getId(); ASTNode reactionFormula = reaction.getKineticLaw().getMath(); setupSingleReaction(reactionID, reactionFormula, reaction.getReversible(), reaction.getListOfReactants(), reaction.getListOfProducts(), reaction.getListOfModifiers()); } } /** * abstract simulate method * each simulator needs a simulate method */ protected abstract void simulate(); /** * returns an annotation with only array information remaining * * @param annotation * @return */ public static String stripAnnotation(String annotation) { if (annotation.contains("array:array")) { //only leave the stuff in these two namespaces, which should appear mutually exclusively annotation = annotation.replace("<annotation>","").replace("</annotation>",""); for (int i = 0; i < annotation.length() - 12; ++i) { if (annotation.substring(i, i + 12).equals("<array:array")) annotation = annotation.substring(i); } for (int i = 0; i < annotation.length() - 2; ++i) { if (annotation.substring(i, i + 2).equals("/>")) { annotation = annotation.substring(0, i + 2); break; } } return "<annotation>" + annotation + "</annotation>"; } else if (annotation.contains("ibiosim:ibiosim")) { //only leave the stuff in these two namespaces, which should appear mutually exclusively annotation = annotation.replace("<annotation>","").replace("</annotation>",""); for (int i = 0; i < annotation.length() - 16; ++i) { if (annotation.substring(i, i + 16).equals("<ibiosim:ibiosim")) annotation = annotation.substring(i); } for (int i = 0; i < annotation.length() - 2; ++i) { if (annotation.substring(i, i + 2).equals("/>")) { annotation = annotation.substring(0, i + 2); break; } } return "<annotation>" + annotation + "</annotation>"; } else return new String(""); } /** * this evaluates a set of constraints that have been affected by an event or reaction firing * and returns the OR'd boolean result * * @param affectedConstraintSet the set of constraints affected * @return the boolean result of the constraints' evaluation */ protected boolean testConstraints(HashSet<ASTNode> affectedConstraintSet) { //check all of the affected constraints //if one evaluates to true, then the simulation halts for (ASTNode constraint : affectedConstraintSet) { if (getBooleanFromDouble(evaluateExpressionRecursive(constraint)) == true) return true; } return false; } /** * is called after duplicateComponent or deleteComponent is called */ protected abstract void updateAfterDynamicChanges(); /** * updates the propensities of the reaction set passed in * * @param reactionSet */ private void updatePropensities(HashSet<String> reactionSet) { for (String reactionID : reactionSet) { boolean notEnoughMoleculesFlag = false; HashSet<StringDoublePair> reactantStoichiometrySet = reactionToReactantStoichiometrySetMap.get(reactionID); //check for enough molecules for the reaction to occur for (StringDoublePair speciesAndStoichiometry : reactantStoichiometrySet) { String speciesID = speciesAndStoichiometry.string; double stoichiometry = speciesAndStoichiometry.doub; if (reactionToNonconstantStoichiometriesSetMap.containsKey(reactionID)) { for (StringStringPair doubleID : reactionToNonconstantStoichiometriesSetMap.get(reactionID)) { //string1 is the species ID; string2 is the speciesReference ID if (doubleID.string1.equals(speciesID)) { stoichiometry = variableToValueMap.get(doubleID.string2); break; } } } //if there aren't enough molecules to satisfy the stoichiometry if (variableToValueMap.get(speciesID) < stoichiometry) { notEnoughMoleculesFlag = true; break; } } double newPropensity = 0.0; if (notEnoughMoleculesFlag == false) newPropensity = evaluateExpressionRecursive(reactionToFormulaMap.get(reactionID)); //stoichiometry amplification -- alter the propensity if (reactionID.contains("_Diffusion_") && stoichAmpBoolean == true) { newPropensity *= (1.0 / stoichAmpGridValue); } if (newPropensity > 0.0 && newPropensity < minPropensity) minPropensity = newPropensity; if (newPropensity > maxPropensity) maxPropensity = newPropensity; double oldPropensity = reactionToPropensityMap.get(reactionID); //add the difference of new v. old propensity to the total propensity totalPropensity += newPropensity - oldPropensity; reactionToPropensityMap.put(reactionID, newPropensity); } } //EVENT TO FIRE INNER CLASS /** * easy way to store multiple data points for events that are firing */ protected class EventToFire { public String eventID = ""; public HashSet<Object> eventAssignmentSet = null; public double fireTime = 0.0; public EventToFire(String eventID, HashSet<Object> eventAssignmentSet, double fireTime) { this.eventID = eventID; this.eventAssignmentSet = eventAssignmentSet; this.fireTime = fireTime; } } //EVENT COMPARATOR INNER CLASS /** * compares two events to see which one should be before the other in the priority queue */ protected class EventComparator implements Comparator<EventToFire> { /** * compares two events based on their fire times and priorities */ public int compare(EventToFire event1, EventToFire event2) { if (event1.fireTime > event2.fireTime) return 1; else if (event1.fireTime < event2.fireTime) return -1; else { if (eventToPriorityMap.get(event1.eventID) == null) { if (eventToPriorityMap.get(event2.eventID) != null) return -1; else { if ((Math.random() * 100) > 50) { return -1; } else { return 1; } } } if (evaluateExpressionRecursive(eventToPriorityMap.get(event1.eventID)) > evaluateExpressionRecursive(eventToPriorityMap.get(event2.eventID))) return -1; else if ( evaluateExpressionRecursive(eventToPriorityMap.get(event1.eventID)) < evaluateExpressionRecursive(eventToPriorityMap.get(event2.eventID))) return 1; else { if ((Math.random() * 100) > 50) { return -1; } else { return 1; } } } } } //STRING DOUBLE PAIR INNER CLASS /** * class to combine a string and a double */ protected class StringDoublePair { public String string; public double doub; StringDoublePair(String s, double d) { string = s; doub = d; } } //STRING STRING PAIR INNER CLASS /** * class to combine a string and a string */ protected class StringStringPair { public String string1; public String string2; StringStringPair(String s1, String s2) { string1 = s1; string2 = s2; } } }
package hex.glrm; import Jama.CholeskyDecomposition; import Jama.Matrix; import Jama.QRDecomposition; import Jama.SingularValueDecomposition; import hex.*; import hex.gram.Gram; import hex.gram.Gram.*; import hex.kmeans.KMeans; import hex.kmeans.KMeansModel; import hex.pca.PCA; import hex.pca.PCAModel; import hex.schemas.GLRMV99; import hex.glrm.GLRMModel.GLRMParameters; import hex.schemas.ModelBuilderSchema; import hex.svd.SVD; import hex.svd.SVDModel; import water.*; import water.fvec.Chunk; import water.fvec.Frame; import water.fvec.NewChunk; import water.fvec.Vec; import water.util.ArrayUtils; import water.util.Log; import water.util.RandomUtils; import java.util.Arrays; import java.util.Random; public class GLRM extends ModelBuilder<GLRMModel,GLRMModel.GLRMParameters,GLRMModel.GLRMOutput> { // Convergence tolerance private final double TOLERANCE = 1e-6; // Maximum number of columns when categoricals expanded private final int MAX_COLS_EXPANDED = 5000; // Number of columns in training set (p) private transient int _ncolA; private transient int _ncolY; // With categoricals expanded into 0/1 indicator cols // Number of columns in fitted X matrix (k) private transient int _ncolX; @Override public ModelBuilderSchema schema() { return new GLRMV99(); } @Override public Job<GLRMModel> trainModelImpl(long work) { return start(new GLRMDriver(), work); } @Override public long progressUnits() { return _parms._max_iterations + 1; } @Override public ModelCategory[] can_build() { return new ModelCategory[]{ModelCategory.Clustering}; } @Override public BuilderVisibility builderVisibility() { return BuilderVisibility.Experimental; }; public enum Initialization { Random, SVD, PlusPlus, User } // Called from an http request public GLRM(GLRMParameters parms) { super("GLRM", parms); init(false); } @Override public void init(boolean expensive) { super.init(expensive); if (_parms._loading_key == null) _parms._loading_key = Key.make("GLRMLoading_" + Key.rand()); if (_parms._gamma_x < 0) error("_gamma_x", "gamma must be a non-negative number"); if (_parms._gamma_y < 0) error("_gamma_y", "gamma_y must be a non-negative number"); if (_parms._max_iterations < 1 || _parms._max_iterations > 1e6) error("_max_iterations", "max_iterations must be between 1 and 1e6 inclusive"); if (_parms._init_step_size <= 0) error ("_init_step_size", "init_step_size must be a positive number"); if (_parms._min_step_size < 0 || _parms._min_step_size > _parms._init_step_size) error("_min_step_size", "min_step_size must be between 0 and " + _parms._init_step_size); if (_train == null) return; if (_train.numCols() < 2) error("_train", "_train must have more than one column"); // TODO: Initialize _parms._k = min(ncol(_train), nrow(_train)) if not set _ncolY = _train.numColsExp(true, false); int k_min = (int) Math.min(_ncolY, _train.numRows()); if (_ncolY > MAX_COLS_EXPANDED) warn("_train", "_train has " + _ncolY + " columns when categoricals are expanded. Algorithm may be slow."); if (_parms._k < 1 || _parms._k > k_min) error("_k", "_k must be between 1 and " + k_min); if (null != _parms._user_points) { // Check dimensions of user-specified centers if (_parms._init != GLRM.Initialization.User) error("init", "init must be 'User' if providing user-specified points"); if (_parms._user_points.get().numCols() != _train.numCols()) error("_user_points", "The user-specified points must have the same number of columns (" + _train.numCols() + ") as the training observations"); else if (_parms._user_points.get().numRows() != _parms._k) error("_user_points", "The user-specified points must have k = " + _parms._k + " rows"); else { int zero_vec = 0; Vec[] centersVecs = _parms._user_points.get().vecs(); for (int c = 0; c < _train.numCols(); c++) { if(centersVecs[c].naCnt() > 0) { error("_user_points", "The user-specified points cannot contain any missing values"); break; } else if(centersVecs[c].isConst() && centersVecs[c].max() == 0) zero_vec++; } if (zero_vec == _train.numCols()) error("_user_points", "The user-specified points cannot all be zero"); } } _ncolX = _parms._k; _ncolA = _train.numCols(); } // Squared Frobenius norm of a matrix (sum of squared entries) public static double frobenius2(double[][] x) { if(x == null) return 0; double frob = 0; for(int i = 0; i < x.length; i++) { for(int j = 0; j < x[0].length; j++) frob += x[i][j] * x[i][j]; } return frob; } // Transform each column of a 2-D array, assuming categoricals sorted before numeric cols public static double[][] transform(double[][] centers, double[] normSub, double[] normMul, int ncats, int nnums) { int K = centers.length; int N = centers[0].length; assert ncats + nnums == N; double[][] value = new double[K][N]; double[] means = normSub == null ? MemoryManager.malloc8d(nnums) : normSub; double[] mults = normMul == null ? MemoryManager.malloc8d(nnums) : normMul; for (int clu = 0; clu < K; clu++) { System.arraycopy(centers[clu], 0, value[clu], 0, ncats); for (int col = 0; col < nnums; col++) value[clu][ncats+col] = (centers[clu][ncats+col] - means[col]) * mults[col]; } return value; } // More efficient implementation assuming sdata cols aligned with adaptedFrame public static double[][] expandCats(double[][] sdata, DataInfo dinfo) { if(sdata == null || dinfo._cats == 0) return sdata; assert sdata[0].length == dinfo._adaptedFrame.numCols(); // Column count for expanded matrix int catsexp = dinfo._catOffsets[dinfo._catOffsets.length-1]; double[][] cexp = new double[sdata.length][catsexp + dinfo._nums]; // Expand out categorical columns int cidx; for(int j = 0; j < dinfo._cats; j++) { for(int i = 0; i < sdata.length; i++) { if (Double.isNaN(sdata[i][j])) { if (dinfo._catMissing[j] == 0) continue; // Skip if entry missing and no NA bucket. All indicators will be zero. else cidx = dinfo._catOffsets[j+1]-1; // Otherwise, missing value turns into extra (last) factor } else cidx = dinfo.getCategoricalId(j, (int)sdata[i][j]); if(cidx >= 0) cexp[i][cidx] = 1; // Ignore categorical levels outside domain } } // Copy over numeric columns for(int j = 0; j < dinfo._nums; j++) { for(int i = 0; i < sdata.length; i++) cexp[i][catsexp+j] = sdata[i][dinfo._cats+j]; } return cexp; } class GLRMDriver extends H2O.H2OCountedCompleter<GLRMDriver> { // Initialize Y and X matrices // tinfo = original training data A, dinfo = [A,X,W] where W is working copy of X (initialized here) private double[][] initialXY(DataInfo tinfo, DataInfo dinfo) { double[][] centers, centers_exp = null; if (null != _parms._user_points) { // User-specified starting points Vec[] centersVecs = _parms._user_points.get().vecs(); centers = new double[_parms._k][_ncolA]; // Get the centers and put into array for (int c = 0; c < _ncolA; c++) { for (int r = 0; r < _parms._k; r++) centers[r][c] = centersVecs[c].at(r); } // Permute cluster columns to align with dinfo and expand out categoricals centers = ArrayUtils.permuteCols(centers, tinfo._permutation); centers_exp = expandCats(centers, tinfo); } else if (_parms._init == Initialization.Random) { // Generate array from standard normal distribution return ArrayUtils.gaussianArray(_parms._k, _ncolY); } else if (_parms._init == Initialization.SVD) { // Run SVD on A'A/n (Gram) and set Y to be the right singular vectors PCAModel.PCAParameters parms = new PCAModel.PCAParameters(); parms._train = _parms._train; parms._ignored_columns = _parms._ignored_columns; parms._ignore_const_cols = _parms._ignore_const_cols; parms._score_each_iteration = _parms._score_each_iteration; parms._use_all_factor_levels = true; // Since GLRM requires Y matrix to have fully expanded ncols parms._k = _parms._k; parms._max_iterations = _parms._max_iterations; parms._transform = _parms._transform; parms._seed = _parms._seed; parms._pca_method = PCAModel.PCAParameters.Method.GramSVD; PCAModel pca = null; PCA job = null; try { job = new PCA(parms); pca = job.trainModel().get(); } finally { if (job != null) job.remove(); if (pca != null) pca.remove(); } // Ensure SVD centers align with adapted training frame cols assert pca._output._permutation.length == tinfo._permutation.length; for(int i = 0; i < tinfo._permutation.length; i++) assert pca._output._permutation[i] == tinfo._permutation[i]; centers_exp = ArrayUtils.transpose(pca._output._eigenvectors_raw); // for(int i = 0; i < centers_exp.length; i++) // ArrayUtils.mult(centers_exp[i], pca._output._std_deviation[i] * Math.sqrt(pca._output._nobs-1)); } else if (_parms._init == Initialization.PlusPlus) { // Run k-means++ and use resulting cluster centers as initial Y KMeansModel.KMeansParameters parms = new KMeansModel.KMeansParameters(); parms._train = _parms._train; parms._ignored_columns = _parms._ignored_columns; parms._ignore_const_cols = _parms._ignore_const_cols; parms._score_each_iteration = _parms._score_each_iteration; parms._init = KMeans.Initialization.PlusPlus; parms._k = _parms._k; parms._max_iterations = _parms._max_iterations; parms._standardize = true; parms._seed = _parms._seed; parms._pred_indicator = true; KMeansModel km = null; KMeans job = null; try { job = new KMeans(parms); km = job.trainModel().get(); // Score only if clusters well-defined and closed-form solution does not exist double frob = frobenius2(km._output._centers_raw); if(frob != 0 && !Double.isNaN(frob) && !_parms.hasClosedForm()) initialXKmeans(dinfo, km); } finally { if (job != null) job.remove(); if (km != null) km.remove(); } // Permute cluster columns to align with dinfo, normalize nums, and expand out cats to indicator cols centers = ArrayUtils.permuteCols(km._output._centers_raw, tinfo.mapNames(km._output._names)); centers = transform(centers, tinfo._normSub, tinfo._normMul, tinfo._cats, tinfo._nums); centers_exp = expandCats(centers, tinfo); } else error("_init", "Initialization method " + _parms._init + " is undefined"); // If all centers are zero or any are NaN, initialize to standard normal random matrix assert centers_exp != null && centers_exp[0].length == _ncolY; double frob = frobenius2(centers_exp); // TODO: Don't need to calculate twice if k-means++ if(frob == 0 || Double.isNaN(frob)) { warn("_init", "Initialization failed. Setting initial Y to standard normal random matrix instead"); centers_exp = ArrayUtils.gaussianArray(_parms._k, _ncolY); } return centers_exp; } // Set X to matrix of indicator columns, e.g. k = 4, cluster = 3 -> [0, 0, 1, 0] private void initialXKmeans(DataInfo dinfo, KMeansModel km) { // Frame pred = km.score(_parms.train()); Log.info("Initializing X to matrix of indicator columns corresponding to cluster assignments"); final KMeansModel model = km; new MRTask() { @Override public void map( Chunk chks[] ) { double tmp [] = new double[_ncolA]; double preds[] = new double[_ncolX]; for(int row = 0; row < chks[0]._len; row++) { double p[] = model.score_indicator(chks, row, tmp, preds); for(int c = 0; c < preds.length; c++) { chks[_ncolA+c].set(row, p[c]); chks[_ncolA+_ncolX+c].set(row, p[c]); } } } }.doAll(dinfo._adaptedFrame); } // In case of L2 loss and regularization, initialize closed form X = AY'(YY' + \gamma)^(-1) private void initialXClosedForm(DataInfo dinfo, double[][] yt, double[] normSub, double[] normMul) { Log.info("Initializing X = AY'(YY' + gamma I)^(-1) where A = training data"); double[][] ygram = ArrayUtils.formGram(yt); if (_parms._gamma_y > 0) { for(int i = 0; i < ygram.length; i++) ygram[i][i] += _parms._gamma_y; } CholeskyDecomposition yychol = regularizedCholesky(ygram, 10, false); if(!yychol.isSPD()) Log.warn("Initialization failed: (YY' + gamma I) is non-SPD. Setting initial X to standard normal random matrix. Results will be numerically unstable"); else { CholMulTask cmtsk = new CholMulTask(dinfo, _parms, yychol, yt, _ncolA, _ncolX, normSub, normMul); cmtsk.doAll(dinfo._adaptedFrame); } } // Stopping criteria private boolean isDone(GLRMModel model, int steps_in_row, double step) { if (!isRunning()) return true; // Stopped/cancelled // Stopped for running out of iterations if (model._output._iterations >= _parms._max_iterations) return true; // Stopped for falling below minimum step size if (step <= _parms._min_step_size) return true; // Stopped when enough steps and average decrease in objective per iteration < TOLERANCE if (model._output._iterations > 10 && steps_in_row > 3 && Math.abs(model._output._avg_change_obj) < TOLERANCE) return true; return false; // Not stopping } // Regularized Cholesky decomposition using H2O implementation public Cholesky regularizedCholesky(Gram gram, int max_attempts) { int attempts = 0; double addedL2 = 0; // TODO: Should I report this to the user? Cholesky chol = gram.cholesky(null); while(!chol.isSPD() && attempts < max_attempts) { if(addedL2 == 0) addedL2 = 1e-5; else addedL2 *= 10; ++attempts; gram.addDiag(addedL2); // try to add L2 penalty to make the Gram SPD Log.info("Added L2 regularization = " + addedL2 + " to diagonal of Gram matrix"); gram.cholesky(chol); } if(!chol.isSPD()) throw new Gram.NonSPDMatrixException(); return chol; } public Cholesky regularizedCholesky(Gram gram) { return regularizedCholesky(gram, 10); } // Regularized Cholesky decomposition using JAMA implementation public CholeskyDecomposition regularizedCholesky(double[][] gram, int max_attempts, boolean throw_exception) { int attempts = 0; double addedL2 = 0; Matrix gmat = new Matrix(gram); CholeskyDecomposition chol = new CholeskyDecomposition(gmat); while(!chol.isSPD() && attempts < max_attempts) { if(addedL2 == 0) addedL2 = 1e-5; else addedL2 *= 10; ++attempts; for(int i = 0; i < gram.length; i++) gmat.set(i,i,addedL2); // try to add L2 penalty to make the Gram SPD Log.info("Added L2 regularization = " + addedL2 + " to diagonal of Gram matrix"); chol = new CholeskyDecomposition(gmat); } if(!chol.isSPD() && throw_exception) throw new Gram.NonSPDMatrixException(); return chol; } public CholeskyDecomposition regularizedCholesky(double[][] gram) { return regularizedCholesky(gram, 10, true); } // Recover singular values and eigenvectors of XY public void recoverSVD(GLRMModel model, DataInfo xinfo) { // NOTE: Gram computes X'X/n where n = nrow(A) = number of rows in training set GramTask xgram = new GramTask(self(), xinfo).doAll(xinfo._adaptedFrame); Cholesky xxchol = regularizedCholesky(xgram._gram); // R from QR decomposition of X = QR is upper triangular factor of Cholesky of X'X // Gram = X'X/n = LL' -> X'X = (L*sqrt(n))(L'*sqrt(n)) Matrix x_r = new Matrix(xxchol.getL()).transpose(); x_r = x_r.times(Math.sqrt(_train.numRows())); QRDecomposition yt_qr = new QRDecomposition(new Matrix(model._output._archetypes)); Matrix yt_r = yt_qr.getR(); // S from QR decomposition of Y' = ZS Matrix rrmul = x_r.times(yt_r.transpose()); SingularValueDecomposition rrsvd = new SingularValueDecomposition(rrmul); // RS' = U \Sigma V' // Eigenvectors are V'Z' = (ZV)' Matrix eigvec = yt_qr.getQ().times(rrsvd.getV()); model._output._eigenvectors = eigvec.getArray(); // Singular values ordered in weakly descending order by algorithm model._output._singular_vals = rrsvd.getSingularValues(); } @Override protected void compute2() { GLRMModel model = null; DataInfo dinfo = null, xinfo = null, tinfo = null; Frame fr = null, x = null; boolean overwriteX = false; try { init(true); // Initialize parameters _parms.read_lock_frames(GLRM.this); // Fetch & read-lock input frames if (error_count() > 0) throw new IllegalArgumentException("Found validation errors: " + validationErrors()); // The model to be built model = new GLRMModel(dest(), _parms, new GLRMModel.GLRMOutput(GLRM.this)); model.delete_and_lock(self()); // Save adapted frame info for scoring later tinfo = new DataInfo(Key.make(), _train, _valid, 0, true, _parms._transform, DataInfo.TransformType.NONE, false, false, /* weights */ false, /* offset */ false); DKV.put(tinfo._key, tinfo); // Save training frame adaptation information for use in scoring later model._output._normSub = tinfo._normSub == null ? new double[tinfo._nums] : tinfo._normSub; if(tinfo._normMul == null) { model._output._normMul = new double[tinfo._nums]; Arrays.fill(model._output._normMul, 1.0); } else model._output._normMul = tinfo._normMul; model._output._permutation = tinfo._permutation; model._output._nnums = tinfo._nums; model._output._ncats = tinfo._cats; model._output._catOffsets = tinfo._catOffsets; model._output._names_expanded = tinfo.coefNames(); long nobs = _train.numRows() * _train.numCols(); for(int i = 0; i < _train.numCols(); i++) nobs -= _train.vec(i).naCnt(); // TODO: Should we count NAs? model._output._nobs = nobs; // 0) Initialize Y and X matrices // Jam A and X into a single frame for distributed computation // [A,X,W] A is read-only training data, X is matrix from prior iteration, W is working copy of X this iteration Vec[] vecs = new Vec[_ncolA + 2*_ncolX]; for (int i = 0; i < _ncolA; i++) vecs[i] = _train.vec(i); for (int i = _ncolA; i < vecs.length; i++) vecs[i] = _train.anyVec().makeGaus(_parms._seed); // By default, initialize X to random Gaussian matrix fr = new Frame(null, vecs); dinfo = new DataInfo(Key.make(), fr, null, 0, true, _parms._transform, DataInfo.TransformType.NONE, false, false, /* weights */ false, /* offset */ false); DKV.put(dinfo._key, dinfo); // Use closed form solution for X if L2 loss and regularization double[][] yt = initialXY(tinfo, dinfo); yt = ArrayUtils.transpose(yt); if (_parms.hasClosedForm()) initialXClosedForm(dinfo, yt, model._output._normSub, model._output._normMul); // Compute initial objective function ObjCalc objtsk = new ObjCalc(dinfo, _parms, yt, _ncolA, _ncolX, model._output._normSub, model._output._normMul, _parms._gamma_x != 0).doAll(dinfo._adaptedFrame); model._output._objective = objtsk._loss + _parms._gamma_x * objtsk._xold_reg + _parms._gamma_y * _parms.regularize_y(yt); model._output._iterations = 0; model._output._avg_change_obj = 2 * TOLERANCE; // Run at least 1 iteration model.update(_key); // Update model in K/V store update(1); // One unit of work double step = _parms._init_step_size; // Initial step size int steps_in_row = 0; // Keep track of number of steps taken that decrease objective while (!isDone(model, steps_in_row, step)) { // TODO: Should step be divided by number of original or expanded (with 0/1 categorical) cols? // 1) Update X matrix given fixed Y UpdateX xtsk = new UpdateX(dinfo, _parms, yt, step/_ncolA, overwriteX, _ncolA, _ncolX, model._output._normSub, model._output._normMul); xtsk.doAll(dinfo._adaptedFrame); // 2) Update Y matrix given fixed X UpdateY ytsk = new UpdateY(dinfo, _parms, yt, step/_ncolA, _ncolA, _ncolX, model._output._normSub, model._output._normMul); double[][] ytnew = ytsk.doAll(dinfo._adaptedFrame)._ytnew; // 3) Compute average change in objective function objtsk = new ObjCalc(dinfo, _parms, ytnew, _ncolA, _ncolX, model._output._normSub, model._output._normMul).doAll(dinfo._adaptedFrame); double obj_new = objtsk._loss + _parms._gamma_x * xtsk._xreg + _parms._gamma_y * ytsk._yreg; model._output._avg_change_obj = (model._output._objective - obj_new) / nobs; model._output._iterations++; // step = 1.0 / model._output._iterations; // Step size \alpha_k = 1/iters if(model._output._avg_change_obj > 0) { // Objective decreased this iteration model._output._archetypes = yt = ytnew; model._output._objective = obj_new; step *= 1.05; steps_in_row = Math.max(1, steps_in_row+1); overwriteX = true; } else { // If objective increased, re-run with smaller step size step = step / Math.max(1.5, -steps_in_row); steps_in_row = Math.min(0, steps_in_row-1); overwriteX = false; Log.info("Iteration " + model._output._iterations + ": Objective increased to " + obj_new + "; reducing step size to " + step); } model._output._step_size = step; model.update(self()); // Update model in K/V store update(1); // One unit of work } // 4) Save solution to model output // Save X frame for user reference later Vec[] xvecs = new Vec[_ncolX]; if(overwriteX) { for (int i = 0; i < _ncolX; i++) xvecs[i] = fr.vec(idx_xnew(i, _ncolA, _ncolX)); } else { for (int i = 0; i < _ncolX; i++) xvecs[i] = fr.vec(idx_xold(i, _ncolA)); } x = new Frame(_parms._loading_key, null, xvecs); xinfo = new DataInfo(Key.make(), x, null, 0, true, DataInfo.TransformType.NONE, DataInfo.TransformType.NONE, false, false, /* weights */ false, /* offset */ false); DKV.put(x._key, x); DKV.put(xinfo._key, xinfo); model._output._loading_key = _parms._loading_key; model._output._archetypes = yt; model._output._step_size = step; if (_parms._recover_svd) recoverSVD(model, xinfo); // Optional: This computes XY, but do we need it? // BMulTask tsk = new BMulTask(self(), xinfo, yt).doAll(dinfo._adaptedFrame.numCols(), xinfo._adaptedFrame); // tsk.outputFrame(_parms._destination_key, _train._names, null); model.update(self()); done(); } catch (Throwable t) { Job thisJob = DKV.getGet(_key); if (thisJob._state == JobState.CANCELLED) { Log.info("Job cancelled by user."); } else { t.printStackTrace(); failed(t); throw t; } } finally { _parms.read_unlock_frames(GLRM.this); if (model != null) model.unlock(_key); if (tinfo != null) tinfo.remove(); if (dinfo != null) dinfo.remove(); if (xinfo != null) xinfo.remove(); // if (x != null && !_parms._keep_loading) x.delete(); // Clean up unused copy of X matrix if (fr != null) { if(overwriteX) { for (int i = 0; i < _ncolX; i++) fr.vec(idx_xold(i, _ncolA)).remove(); } else { for (int i = 0; i < _ncolX; i++) fr.vec(idx_xnew(i, _ncolA, _ncolX)).remove(); } } } tryComplete(); } Key self() { return _key; } } // In chunk, first _ncolA cols are A, next _ncolX cols are X protected static int idx_xold(int c, int ncolA) { return ncolA+c; } protected static int idx_xnew(int c, int ncolA, int ncolX) { return ncolA+ncolX+c; } protected static int idx_ycat(int c, int level, DataInfo dinfo) { // TODO: Deal with case of missing bucket // assert !Double.isNaN(level) && level >= 0 && level < dinfo._catLvls[c].length; assert dinfo._adaptedFrame.domains() != null : "Domain of categorical column cannot be null"; assert !Double.isNaN(level) && level >= 0 && level < dinfo._adaptedFrame.domains()[c].length; return dinfo._catOffsets[c]+level; } protected static int idx_ynum(int c, DataInfo dinfo) { return dinfo._catOffsets[dinfo._catOffsets.length-1]+c; } protected static Chunk chk_xold(Chunk chks[], int c, int ncolA) { return chks[ncolA+c]; } protected static Chunk chk_xnew(Chunk chks[], int c, int ncolA, int ncolX) { return chks[ncolA+ncolX+c]; } protected static double[][] yt_block(double[][] yt, int cidx, DataInfo dinfo) { return yt_block(yt, cidx, dinfo, false); } protected static double[][] yt_block(double[][] yt, int cidx, DataInfo dinfo, boolean transpose) { int catlvls = dinfo._adaptedFrame.domains() == null ? 1 : dinfo._adaptedFrame.domains()[cidx].length; // double[][] block = new double[dinfo._catLvls[cidx].length][yt[0].length]; double[][] block; if(transpose) { block = new double[yt[0].length][catlvls]; for (int col = 0; col < block.length; col++) { for (int level = 0; level < block[0].length; level++) { block[col][level] = yt[idx_ycat(cidx, level, dinfo)][col]; } } } else { block = new double[catlvls][yt[0].length]; for (int col = 0; col < block[0].length; col++) { for (int level = 0; level < block.length; level++) { block[level][col] = yt[idx_ycat(cidx, level, dinfo)][col]; } } } return block; } private static class UpdateX extends MRTask<UpdateX> { // Input DataInfo _dinfo; GLRMParameters _parms; final double _alpha; // Step size divided by num cols in A final boolean _update; // Should we update X from working copy? final double[][] _yt; // _yt = Y' (transpose of Y) final int _ncolA; // Number of cols in training frame final int _ncolX; // Number of cols in X (k) final double[] _normSub; // For standardizing training data final double[] _normMul; // Output double _loss; // Loss evaluated on A - XY using new X (and current Y) double _xreg; // Regularization evaluated on new X UpdateX(DataInfo dinfo, GLRMParameters parms, double[][] yt, double alpha, boolean update, int ncolA, int ncolX, double[] normSub, double[] normMul) { assert yt != null && yt[0].length == ncolX; _parms = parms; _yt = yt; _alpha = alpha; _update = update; _ncolA = ncolA; _ncolX = ncolX; // dinfo contains [A,X,W], but we only use its info on A (cols 1 to ncolA) assert dinfo._cats <= ncolA; _dinfo = dinfo; _normSub = normSub; _normMul = normMul; } @Override public void map(Chunk[] cs) { assert (_ncolA + 2*_ncolX) == cs.length; double[] a = new double[_ncolA]; Random rand = RandomUtils.getRNG(_parms._seed + cs[0].start()); _loss = _xreg = 0; for(int row = 0; row < cs[0]._len; row++) { double[] grad = new double[_ncolX]; double[] xnew = new double[_ncolX]; // Copy old working copy of X to current X if requested if(_update) { for(int k = 0; k < _ncolX; k++) chk_xold(cs,k,_ncolA).set(row, chk_xnew(cs,k,_ncolA,_ncolX).atd(row)); } // Compute gradient of objective at row // Categorical columns for(int j = 0; j < _dinfo._cats; j++) { a[j] = cs[j].atd(row); if(Double.isNaN(a[j])) continue; // Skip missing observations in row // Calculate x_i * Y_j where Y_j is sub-matrix corresponding to categorical col j // double[] xy = new double[_dinfo._catLvls[j].length]; double[] xy = new double[_dinfo._adaptedFrame.domains()[j].length]; for(int level = 0; level < xy.length; level++) { for(int k = 0; k < _ncolX; k++) { xy[level] += chk_xold(cs,k,_ncolA).atd(row) * _yt[idx_ycat(j,level,_dinfo)][k]; } } // Gradient wrt x_i is matrix product \grad L_{i,j}(x_i * Y_j, A_{i,j}) * Y_j' double[] weight = _parms.mlgrad(xy, (int)a[j]); double[][] ytsub = yt_block(_yt,j,_dinfo); for(int k = 0; k < _ncolX; k++) { for(int c = 0; c < weight.length; c++) grad[k] += weight[c] * ytsub[c][k]; } } // Numeric columns for(int j = _dinfo._cats; j < _ncolA; j++) { int js = j - _dinfo._cats; int yidx = idx_ynum(js,_dinfo); a[j] = cs[j].atd(row); if(Double.isNaN(a[j])) continue; // Skip missing observations in row // Inner product x_i * y_j double xy = 0; for(int k = 0; k < _ncolX; k++) xy += chk_xold(cs,k,_ncolA).atd(row) * _yt[yidx][k]; // Sum over y_j weighted by gradient of loss \grad L_{i,j}(x_i * y_j, A_{i,j}) double weight = _parms.lgrad(xy, (a[j] - _normSub[js]) * _normMul[js]); for(int k = 0; k < _ncolX; k++) grad[k] += weight * _yt[yidx][k]; } // Update row x_i of working copy with new values double[] u = new double[_ncolX]; for(int k = 0; k < _ncolX; k++) { double xold = chk_xold(cs,k,_ncolA).atd(row); // Old value of x_i u[k] = xold - _alpha * grad[k]; // xnew[k] = _parms.rproxgrad_x(xold - _alpha * grad[k], _alpha); // Proximal gradient // chk_xnew(cs,k,_ncolA,_ncolX).set(row, xnew[k]); // _xreg += _parms.regularize_x(xnew[k]); } xnew = _parms.rproxgrad_x(u, _alpha, rand); _xreg += _parms.regularize_x(xnew); for(int k = 0; k < _ncolX; k++) chk_xnew(cs,k,_ncolA,_ncolX).set(row,xnew[k]); // Compute loss function using new x_i // Categorical columns for(int j = 0; j < _dinfo._cats; j++) { if(Double.isNaN(a[j])) continue; // Skip missing observations in row double[] xy = ArrayUtils.multVecArr(xnew, yt_block(_yt,j,_dinfo,true)); _loss += _parms.mloss(xy, (int) a[j]); } // Numeric columns for(int j = _dinfo._cats; j < _ncolA; j++) { int js = j - _dinfo._cats; if(Double.isNaN(a[j])) continue; // Skip missing observations in row double xy = ArrayUtils.innerProduct(xnew, _yt[idx_ynum(js,_dinfo)]); _loss += _parms.loss(xy, (a[j] - _normSub[js]) * _normMul[js]); } } } @Override public void reduce(UpdateX other) { _loss += other._loss; _xreg += other._xreg; } } private static class UpdateY extends MRTask<UpdateY> { // Input DataInfo _dinfo; GLRMParameters _parms; final double _alpha; // Step size divided by num cols in A final double[][] _ytold; // Old Y' matrix final int _ncolA; // Number of cols in training frame final int _ncolX; // Number of cols in X (k) final double[] _normSub; // For standardizing training data final double[] _normMul; // Output double[][] _ytnew; // New Y matrix double _yreg; // Regularization evaluated on new Y UpdateY(DataInfo dinfo, GLRMParameters parms, double[][] yt, double alpha, int ncolA, int ncolX, double[] normSub, double[] normMul) { assert yt != null && yt[0].length == ncolX; _parms = parms; _alpha = alpha; _ncolA = ncolA; _ncolX = ncolX; _ytold = yt; _yreg = 0; // _ytnew = new double[_ncolA][_ncolX]; // dinfo contains [A,X,W], but we only use its info on A (cols 1 to ncolA) assert dinfo._cats <= ncolA; _dinfo = dinfo; _normSub = normSub; _normMul = normMul; } @Override public void map(Chunk[] cs) { assert (_ncolA + 2*_ncolX) == cs.length; _ytnew = new double[_ytold.length][_ncolX]; // Categorical columns for(int j = 0; j < _dinfo._cats; j++) { // Compute gradient of objective at column for(int row = 0; row < cs[0]._len; row++) { double a = cs[j].atd(row); if(Double.isNaN(a)) continue; // Skip missing observations in column // Calculate x_i * Y_j where Y_j is sub-matrix corresponding to categorical col j // double[] xy = new double[_dinfo._catLvls[j].length]; double[] xy = new double[_dinfo._adaptedFrame.domains()[j].length]; for(int level = 0; level < xy.length; level++) { for(int k = 0; k < _ncolX; k++) { xy[level] += chk_xnew(cs,k,_ncolA,_ncolX).atd(row) * _ytold[idx_ycat(j,level,_dinfo)][k]; } } // Gradient for level p is x_i weighted by \grad_p L_{i,j}(x_i * Y_j, A_{i,j}) double[] weight = _parms.mlgrad(xy, (int)a); for(int level = 0; level < xy.length; level++) { for(int k = 0; k < _ncolX; k++) _ytnew[idx_ycat(j,level,_dinfo)][k] += weight[level] * chk_xnew(cs,k,_ncolA,_ncolX).atd(row); } } } // Numeric columns for(int j = _dinfo._cats; j < _ncolA; j++) { int js = j - _dinfo._cats; int yidx = idx_ynum(js,_dinfo); // Compute gradient of objective at column for(int row = 0; row < cs[0]._len; row++) { double a = cs[j].atd(row); if(Double.isNaN(a)) continue; // Skip missing observations in column // Inner product x_i * y_j double xy = 0; for(int k = 0; k < _ncolX; k++) xy += chk_xnew(cs,k,_ncolA,_ncolX).atd(row) * _ytold[yidx][k]; // Sum over x_i weighted by gradient of loss \grad L_{i,j}(x_i * y_j, A_{i,j}) double weight = _parms.lgrad(xy, (a - _normSub[js]) * _normMul[js]); for(int k = 0; k < _ncolX; k++) _ytnew[yidx][k] += weight * chk_xnew(cs,k,_ncolA,_ncolX).atd(row); } } } @Override public void reduce(UpdateY other) { ArrayUtils.add(_ytnew, other._ytnew); } @Override protected void postGlobal() { assert _ytnew.length == _ytold.length && _ytnew[0].length == _ytold[0].length; Random rand = RandomUtils.getRNG(_parms._seed); // Compute new y_j values using proximal gradient for(int j = 0; j < _ytnew.length; j++) { double[] u = new double[_ytnew[0].length]; for(int k = 0; k < _ytnew[0].length; k++) { // double u = _ytold[j][k] - _alpha * _ytnew[j][k]; // _ytnew[j][k] = _parms.rproxgrad_y(u, _alpha); // _yreg += _parms.regularize_y(_ytnew[j][k]); u[k] = _ytold[j][k] - _alpha * _ytnew[j][k]; } _ytnew[j] = _parms.rproxgrad_y(u, _alpha, rand); _yreg += _parms.regularize_y(_ytnew[j]); } } } // Calculate the sum loss function in the optimization objective private static class ObjCalc extends MRTask<ObjCalc> { // Input DataInfo _dinfo; GLRMParameters _parms; final double[][] _yt; // _yt = Y' (transpose of Y) final int _ncolA; // Number of cols in training frame final int _ncolX; // Number of cols in X (k) final double[] _normSub; // For standardizing training data final double[] _normMul; final boolean _regX; // Should I calculate regularization of (old) X matrix? // Output double _loss; double _xold_reg; ObjCalc(DataInfo dinfo, GLRMParameters parms, double[][] yt, int ncolA, int ncolX, double[] normSub, double[] normMul) { this(dinfo, parms, yt, ncolA, ncolX, normSub, normMul, false); } ObjCalc(DataInfo dinfo, GLRMParameters parms, double[][] yt, int ncolA, int ncolX, double[] normSub, double[] normMul, boolean regX) { assert yt != null && yt[0].length == ncolX; _parms = parms; _yt = yt; _ncolA = ncolA; _ncolX = ncolX; _regX = regX; _loss = _xold_reg = 0; assert dinfo._cats <= ncolA; _dinfo = dinfo; _normSub = normSub; _normMul = normMul; } @Override public void map(Chunk[] cs) { assert (_ncolA + 2*_ncolX) == cs.length; for(int row = 0; row < cs[0]._len; row++) { // Categorical columns for(int j = 0; j < _dinfo._cats; j++) { double a = cs[j].atd(row); if (Double.isNaN(a)) continue; // Skip missing observations in row // Calculate x_i * Y_j where Y_j is sub-matrix corresponding to categorical col j // double[] xy = new double[_dinfo._catLvls[j].length]; double[] xy = new double[_dinfo._adaptedFrame.domains()[j].length]; for(int level = 0; level < xy.length; level++) { for(int k = 0; k < _ncolX; k++) { xy[level] += chk_xnew(cs,k,_ncolA,_ncolX).atd(row) * _yt[idx_ycat(j,level,_dinfo)][k]; } } _loss += _parms.mloss(xy, (int)a); } // Numeric columns for(int j = _dinfo._cats; j < _ncolA; j++) { double a = cs[j].atd(row); if (Double.isNaN(a)) continue; // Skip missing observations in row // Inner product x_i * y_j double xy = 0; int js = j - _dinfo._cats; for(int k = 0; k < _ncolX; k++) xy += chk_xnew(cs,k,_ncolA,_ncolX).atd(row) * _yt[idx_ynum(js,_dinfo)][k]; _loss += _parms.loss(xy, (a - _normSub[js]) * _normMul[js]); } // Calculate regularization term for old X if requested if(_regX) { int idx = 0; double[] xrow = new double[_ncolX]; for(int j = _ncolA; j < _ncolA+_ncolX; j++) { // double x = cs[j].atd(row); // _xold_reg += _parms.regularize_x(x); xrow[idx] = cs[j].atd(row); idx++; } assert idx == _ncolX; _xold_reg += _parms.regularize_x(xrow); } } } } // Solves XD = AY' for X where A is n by p, Y is k by p, D is k by k, and n >> p > k // Resulting matrix X = (AY')D^(-1) will have dimensions n by k private static class CholMulTask extends MRTask<CholMulTask> { DataInfo _dinfo; GLRMParameters _parms; final double[][] _yt; // _yt = Y' (transpose of Y) final int _ncolA; // Number of cols in training frame final int _ncolX; // Number of cols in X (k) final double[] _normSub; // For standardizing training data final double[] _normMul; CholeskyDecomposition _chol; // Cholesky decomposition of D = D', since we solve D'X' = DX' = AY' CholMulTask(DataInfo dinfo, GLRMParameters parms, CholeskyDecomposition chol, double[][] yt, double[] normSub, double[] normMul) { this(dinfo, parms, chol, yt, yt.length, yt[0].length, normSub, normMul); } CholMulTask(DataInfo dinfo, GLRMParameters parms, CholeskyDecomposition chol, double[][] yt, int ncolA, int ncolX, double[] normSub, double[] normMul) { assert yt != null && yt[0].length == ncolX; _parms = parms; _yt = yt; _ncolA = ncolA; _ncolX = ncolX; _chol = chol; assert dinfo._cats <= ncolA; _dinfo = dinfo; _normSub = normSub; _normMul = normMul; } // [A,X,W] A is read-only training data, X is left matrix in A = XY decomposition, W is working copy of X @Override public void map(Chunk[] cs) { assert (_ncolA + 2*_ncolX) == cs.length; double[] xrow = new double[_ncolX]; for(int row = 0; row < cs[0]._len; row++) { // 1) Compute single row of AY' for (int k = 0; k < _ncolX; k++) { // Categorical columns double x = 0; for(int d = 0; d < _dinfo._cats; d++) { double a = cs[d].atd(row); if (Double.isNaN(a)) continue; x += _yt[idx_ycat(d, (int)a, _dinfo)][k]; } // Numeric columns for (int d = _dinfo._cats; d < _ncolA; d++) { int ds = d - _dinfo._cats; double a = cs[d].atd(row); if (Double.isNaN(a)) continue; x += (a - _normSub[ds]) * _normMul[ds] * _yt[idx_ynum(ds,_dinfo)][k]; } xrow[k] = x; } // 2) Cholesky solve for single row of X // _chol.solve(xrow); Matrix tmp = _chol.solve(new Matrix(new double[][] {xrow}).transpose()); xrow = tmp.getColumnPackedCopy(); // 3) Save row of solved values into X (and copy W = X) int i = 0; for(int d = _ncolA; d < _ncolA+_ncolX; d++) { cs[d].set(row, xrow[i]); cs[d+_ncolX].set(row, xrow[i++]); } assert i == xrow.length; } } } // Computes XY where X is n by k, Y is k by p, and k <= p // The resulting matrix Z = XY will have dimensions n by p private static class BMulTask extends FrameTask<BMulTask> { double[][] _yt; // _yt = Y' (transpose of Y) BMulTask(Key jobKey, DataInfo dinfo, final double[][] yt) { super(jobKey, dinfo); _yt = yt; } @Override protected void processRow(long gid, DataInfo.Row row, NewChunk[] outputs) { assert row.nBins + _dinfo._nums == _yt[0].length; for(int p = 0; p < _yt.length; p++) { double x = row.innerProduct(_yt[p]); outputs[p].addNum(x); } } } }
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Vector; import org.simgrid.msg.Msg; import org.simgrid.msg.Host; import org.simgrid.msg.Process; public class LFC extends Process { // A Logical File Catalog service is defined by: // hostName: the name of the host that runs the service // catalog: a vector of logical files protected String hostName; private Vector<LogicalFile> catalog; // A simulation can begin with some logical files referenced in the LFC. // In that case, the LFC process is launched with an argument which is the // name of a CSV file stored in working directory that contains logical // file description in the following format: // name,size,se_1<:se_2:...:se_n> // The populate function reads and parses that file, create LogicalFile // objects and add them to the local catalog. private void populate(String csvFile){ Msg.info("Population of LFC '"+ hostName + "' from '"+ csvFile + "'"); try { BufferedReader br = new BufferedReader(new FileReader(csvFile)); String line = ""; while ((line = br.readLine()) != null) { String[] fileInfo = line.split(","); String[] seNames = fileInfo[2].split(":"); LogicalFile file = new LogicalFile(fileInfo[0], Long.valueOf(fileInfo[1]).longValue(), seNames); Msg.info("Importing file '" + file.toString()); catalog.add(file); } br.close(); } catch (IOException e) { e.printStackTrace(); } } // A worker might want to register a new logical file, or a replica on an // existing file in the catalog. This function first checks if a file with // the same name already exists. If it does, it determines whether it is a // new replica or not. Otherwise, it creates a new entry in the catalog for // that file. private void register(LogicalFile newFile){ if (catalog.contains((Object) newFile)){ LogicalFile file = catalog.get(catalog.indexOf(newFile)); if (!file.getLocations().contains((Object) newFile.getSEName())){ // This has to be a new replica Msg.info("New replica for '" + newFile.getName () + "' on '" + newFile.getSEName() + "'"); file.addLocation(newFile.getSEName()); } else { Msg.debug(file.toString() + "is already registered"); } } else { // This file is not registered yet, create and add it Msg.debug ("'" + newFile.getName() + "' is not registered yet"); catalog.add(newFile); Msg.debug("LFC '"+ hostName + "' registered " + newFile.toString()); } } public LFC(Host host, String name, String[]args) { super(host,name,args); this.hostName = getHost().getName(); this.catalog = new Vector<>(); } public void main(String[] args) { boolean stop = false; Msg.debug("Register LFC on "+ hostName); VIPSimulator.getLFCList().add(hostName); // If this LFC process is started with an argument, we populate the // catalog from the CSV file given as args[0] String csvFile = (args.length > 0 ? args[0] : null); if (csvFile != null){ populate(csvFile); Msg.debug(this.toString()); } while (!stop){ Message message = Message.getFrom(hostName); // To prevent message mixing, a specific mailbox is used whose name // is the concatenation of LFC's hostName and sender mailbox String returnMailbox = hostName+message.getSenderMailbox(); switch(message.getType()){ case REGISTER_FILE: // Add an entry for the received logical file, if needed // Then send back an ACK to the the sender register(message.getFile()); Message.sendTo(returnMailbox, Message.Type.REGISTER_ACK); Msg.debug("LFC '"+ hostName + "' sent back an ACK to '" + message.getSenderMailbox() + "'"); break; case ASK_LOGICAL_FILE: LogicalFile file = getLogicalFileByName(message.getLogicalName()); // If this logical file is available on several locations, a // single one is selected before returning the file to the // worker asking for it. file.selectLocation(); Message.sendTo(returnMailbox, Message.Type.SEND_LOGICAL_FILE, file); Msg.debug("LFC '"+ hostName + "' returned Logical " + file.toString() + " back to '" + message.getSenderMailbox() + "'"); break; case ASK_LS: Vector<LogicalFile> directoryContents = new Vector<LogicalFile>(); for (LogicalFile f : catalog) if (f.getName().matches(message.getLogicalName()+"(.*)")) directoryContents.add(f); Message.sendTo(returnMailbox, Message.Type.SEND_LS, directoryContents); break; case FINALIZE: Msg.verb("Goodbye!"); stop = true; break; default: break; } } } public LogicalFile getLogicalFileByName (String logicalFileName) { LogicalFile file = catalog.get(catalog.indexOf((Object) new LogicalFile (logicalFileName, 0, ""))); if(file == null){ Msg.error("File '" + logicalFileName + "' is stored on no SE. Exiting with status 1"); System.exit(1); } return file; } public Vector<LogicalFile> getResults(){ Vector<LogicalFile> results = new Vector<LogicalFile>(); for (LogicalFile file : catalog) if (file.getName().matches("results/(.*)partial(.*)")){ results.add(file); } return results; } public String getSEName (String logicalFileName){ return getLogicalFileByName(logicalFileName).getSEName(); } public String toString () { return catalog.toString(); } }
public class Rel extends Node { public Node left, right; public int op; public Rel(int op, Node left, Node right) { this.op = op; this.left = left; this.right = right; } @Override public Value interp(Scope s) { Value lv = left.interp(s); Value rv = right.interp(s); if (lv instanceof StringValue && rv instanceof StringValue) { String l = ((StringValue) lv).value; String r = ((StringValue) rv).value; return new BoolValue(op(l.compareTo(r), 0)); } if (lv instanceof IntValue && rv instanceof IntValue) { int l = ((IntValue) lv).value; int r = ((IntValue) rv).value; return new BoolValue(op(l, r)); } if (lv instanceof FloatValue && rv instanceof FloatValue) { int l = (int) ((FloatValue) lv).value; int r = (int) ((FloatValue) rv).value; return new BoolValue(op(l, r)); } // // eg. Type.Dict == Type.dict if (lv instanceof Type && rv instanceof Type) return new BoolValue(lv == rv); S.error("Type compare unsupport error: %s, %s", lv, rv); return Value.FALSE; // never touch } private boolean op(int l, int r) { boolean ret = false; switch (op) { case '>': ret = l > r; break; case '<': ret = l < r; break; case Tag.EQ: ret = l == r; break; case Tag.NE: ret = l != r; break; case Tag.LE: ret = l <= r; break; case Tag.GE: ret = l >= r; break; default: S.error(": " + (char) op); } return ret; } @Override public String toString() { return left + " " + Tag.descOf(op) + " " + right; } }
package ch.ethz.globis.disindex.codec; import ch.ethz.globis.disindex.codec.api.FieldDecoder; import ch.ethz.globis.disindex.codec.api.ResponseDecoder; import java.util.List; /** * Decodes response messages sent by the server to the client. * * @param <K> The type of the key. * @param <V> The type of the value. */ public class ByteResponseDecoder<K, V> implements ResponseDecoder<K, V> { FieldDecoder<V> valueDecoder; public ByteResponseDecoder(FieldDecoder<V> valueDecoder) { this.valueDecoder = valueDecoder; } @Override public V decodePut(byte[] payload) { return valueDecoder.decode(payload); } @Override public V decodeGet(byte[] payload) { return valueDecoder.decode(payload); } @Override public List<V> decodeGetRange(List<byte[]> payload) { throw new UnsupportedOperationException("Operation not yet implemented"); } @Override public List<V> decodeGetKNN(List<byte[]> payload) { throw new UnsupportedOperationException("Operation not yet implemented"); } @Override public boolean decodeCreate(byte[] payload) { return (payload.length == 1 && payload[0] == MessageCode.SUCCESS); } }
package com.xpn.xwiki.doc; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.ResourceBundle; import org.jmock.Mock; import org.jmock.core.Invocation; import org.jmock.core.stub.CustomStub; import org.xwiki.display.internal.DisplayConfiguration; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.EntityReferenceSerializer; import org.xwiki.rendering.configuration.RenderingConfiguration; import org.xwiki.rendering.internal.configuration.DefaultRenderingConfiguration; import org.xwiki.rendering.syntax.Syntax; import org.xwiki.security.authorization.Right; import org.xwiki.velocity.VelocityEngine; import org.xwiki.velocity.VelocityManager; import org.xwiki.velocity.XWikiVelocityException; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.classes.BaseClass; import com.xpn.xwiki.objects.classes.PropertyClass; import com.xpn.xwiki.objects.classes.TextAreaClass; import com.xpn.xwiki.store.XWikiStoreInterface; import com.xpn.xwiki.store.XWikiVersioningStoreInterface; import com.xpn.xwiki.test.AbstractBridgedXWikiComponentTestCase; import com.xpn.xwiki.user.api.XWikiRightService; import com.xpn.xwiki.web.XWikiMessageTool; /** * Unit tests for {@link XWikiDocument}. * * @version $Id$ */ public class XWikiDocumentTest extends AbstractBridgedXWikiComponentTestCase { private static final String DOCWIKI = "WikiDescriptor"; private static final String DOCSPACE = "Space"; private static final String DOCNAME = "Page"; private static final String DOCFULLNAME = DOCSPACE + "." + DOCNAME; private static final DocumentReference DOCUMENT_REFERENCE = new DocumentReference(DOCWIKI, DOCSPACE, DOCNAME); private static final String CLASSNAME = DOCFULLNAME; private static final DocumentReference CLASS_REFERENCE = DOCUMENT_REFERENCE; private XWikiDocument document; private XWikiDocument translatedDocument; private Mock mockXWiki; private Mock mockXWikiVersioningStore; private Mock mockXWikiStoreInterface; private Mock mockXWikiMessageTool; private Mock mockXWikiRightService; private Mock mockVelocityEngine; private Mock mockDisplayConfiguration; private CustomStub velocityEngineEvaluateStub; private BaseClass baseClass; private BaseObject baseObject; private EntityReferenceSerializer<String> defaultEntityReferenceSerializer; @Override protected void setUp() throws Exception { super.setUp(); this.defaultEntityReferenceSerializer = getComponentManager().getInstance(EntityReferenceSerializer.TYPE_STRING); this.document = new XWikiDocument(new DocumentReference(DOCWIKI, DOCSPACE, DOCNAME)); this.document.setSyntax(Syntax.XWIKI_1_0); this.document.setLanguage("en"); this.document.setDefaultLanguage("en"); this.document.setNew(false); this.translatedDocument = new XWikiDocument(); this.translatedDocument.setSyntax(Syntax.XWIKI_2_0); this.translatedDocument.setLanguage("fr"); this.translatedDocument.setNew(false); getContext().put("isInRenderingEngine", true); this.mockXWiki = mock(XWiki.class); this.mockXWikiVersioningStore = mock(XWikiVersioningStoreInterface.class); this.mockXWikiVersioningStore.stubs().method("getXWikiDocumentArchive").will(returnValue(null)); this.mockXWikiStoreInterface = mock(XWikiStoreInterface.class); this.document.setStore((XWikiStoreInterface) this.mockXWikiStoreInterface.proxy()); this.mockXWikiMessageTool = mock(XWikiMessageTool.class, new Class[] {ResourceBundle.class, XWikiContext.class}, new Object[] {null, getContext()}); this.mockXWikiMessageTool.stubs().method("get").will(returnValue("message")); this.mockXWikiRightService = mock(XWikiRightService.class); this.mockXWikiRightService.stubs().method("hasProgrammingRights").will(returnValue(true)); this.mockXWiki.stubs().method("getVersioningStore").will(returnValue(this.mockXWikiVersioningStore.proxy())); this.mockXWiki.stubs().method("getStore").will(returnValue(this.mockXWikiStoreInterface.proxy())); this.mockXWiki.stubs().method("getDocument").will(returnValue(this.document)); this.mockXWiki.stubs().method("getLanguagePreference").will(returnValue("en")); this.mockXWiki.stubs().method("getSectionEditingDepth").will(returnValue(2L)); this.mockXWiki.stubs().method("getRightService").will(returnValue(this.mockXWikiRightService.proxy())); getContext().setWiki((XWiki) this.mockXWiki.proxy()); getContext().put("msg", this.mockXWikiMessageTool.proxy()); this.baseClass = this.document.getxWikiClass(); this.baseClass.addTextField("string", "String", 30); this.baseClass.addTextAreaField("area", "Area", 10, 10); this.baseClass.addTextAreaField("puretextarea", "Pure text area", 10, 10); // set the text areas an non interpreted content ((TextAreaClass) this.baseClass.getField("puretextarea")).setContentType("puretext"); this.baseClass.addPasswordField("passwd", "Password", 30); this.baseClass.addBooleanField("boolean", "Boolean", "yesno"); this.baseClass.addNumberField("int", "Int", 10, "integer"); this.baseClass.addStaticListField("stringlist", "StringList", "value1, value2"); this.mockXWiki.stubs().method("getClass").will(returnValue(this.baseClass)); this.mockXWiki.stubs().method("getXClass").will(returnValue(this.baseClass)); this.baseObject = this.document.newObject(CLASSNAME, getContext()); this.baseObject.setStringValue("string", "string"); this.baseObject.setLargeStringValue("area", "area"); this.baseObject.setStringValue("passwd", "passwd"); this.baseObject.setIntValue("boolean", 1); this.baseObject.setIntValue("int", 42); this.baseObject.setStringListValue("stringlist", Arrays.asList("VALUE1", "VALUE2")); this.mockXWikiStoreInterface.stubs().method("search").will(returnValue(new ArrayList<XWikiDocument>())); // Set the default link label generator format to %np for some tests below. // We need to do this since we don't depend on xwiki-platform-rendering-configuration-default (which contains // an overridden RenderingConfiguration impl that sets the format to %np by default). DefaultRenderingConfiguration renderingConfiguration = getComponentManager().getInstance(RenderingConfiguration.class); renderingConfiguration.setLinkLabelFormat("%np"); } @Override protected void registerComponents() throws Exception { super.registerComponents(); getContextualAuthorizationManager().stubs() .method("hasAccess").with(eq(Right.PROGRAM)).will(returnValue(true)); // Setup display configuration. this.mockDisplayConfiguration = registerMockComponent(DisplayConfiguration.class); this.mockDisplayConfiguration.stubs().method("getDocumentDisplayerHint").will(returnValue("default")); this.mockDisplayConfiguration.stubs().method("getTitleHeadingDepth").will(returnValue(2)); // Setup the mock Velocity engine. Mock mockVelocityManager = registerMockComponent(VelocityManager.class); this.mockVelocityEngine = mock(VelocityEngine.class); mockVelocityManager.stubs().method("getVelocityContext").will(returnValue(null)); mockVelocityManager.stubs().method("getVelocityEngine").will(returnValue(this.mockVelocityEngine.proxy())); velocityEngineEvaluateStub = new CustomStub("Implements VelocityEngine.evaluate") { @Override public Object invoke(Invocation invocation) throws Throwable { // Output the given text without changes. StringWriter writer = (StringWriter) invocation.parameterValues.get(1); String text = (String) invocation.parameterValues.get(3); writer.append(text); return true; } }; this.mockVelocityEngine.stubs().method("evaluate").will(velocityEngineEvaluateStub); this.mockVelocityEngine.stubs().method("startedUsingMacroNamespace"); this.mockVelocityEngine.stubs().method("stoppedUsingMacroNamespace"); } public void testGetDisplayTitleWhenNoTitleAndNoContent() { this.document.setContent("Some content"); assertEquals("Page", this.document.getDisplayTitle(getContext())); } public void testGetDisplayWhenTitleExists() { this.document.setContent("Some content"); this.document.setTitle("Title"); this.mockVelocityEngine.expects(once()).method("evaluate").with(null, ANYTHING, ANYTHING, eq("Title")) .will(velocityEngineEvaluateStub); assertEquals("Title", this.document.getDisplayTitle(getContext())); } public void testGetDisplayWhenNoTitleButSectionExists() { getConfigurationSource().setProperty("xwiki.title.compatibility", "1"); this.document.setContent("Some content\n1 Title"); this.mockVelocityEngine.expects(once()).method("evaluate").with(null, ANYTHING, ANYTHING, eq("Title")) .will(velocityEngineEvaluateStub); assertEquals("Title", this.document.getDisplayTitle(getContext())); } /** * Verify that if an error happens when evaluation the title, we fallback to the computed title. */ public void testGetDisplayTitleWhenVelocityError() { this.document.setContent("Some content"); this.document.setTitle("some content that generate a velocity error"); this.mockVelocityEngine.expects(once()).method("evaluate") .will(throwException(new XWikiVelocityException("message"))); assertEquals("Page", this.document.getDisplayTitle(getContext())); } public void testGetxWikiClass() { this.document.getxWikiClass(); ((PropertyClass)this.baseObject.getxWikiClass(getContext()).get("string")).getxWikiClass(getContext()); } public void testExtractTitle() { this.mockXWiki.stubs().method("exists").will(returnValue(false)); this.document.setSyntax(Syntax.XWIKI_2_0); this.document.setContent("content not in section\n" + "= header 1=\nheader 1 content\n" + "== header 2==\nheader 2 content"); assertEquals("header 1", this.document.extractTitle()); this.document.setContent("content not in section\n" + "= **header 1**=\nheader 1 content\n" + "== header 2==\nheader 2 content"); assertEquals("<strong>header 1</strong>", this.document.extractTitle()); this.document.setContent("content not in section\n" + "= [[Space.Page]]=\nheader 1 content\n" + "== header 2==\nheader 2 content"); this.mockXWiki.stubs().method("getURL").will(returnValue("/reference")); assertEquals("<span class=\"wikicreatelink\"><a href=\"/reference\"><span class=\"wikigeneratedlinkcontent\">" + "Page" + "</span></a></span>", this.document.extractTitle()); this.document.setContent("content not in section\n" + "= #set($var ~= \"value\")=\nheader 1 content\n" + "== header 2==\nheader 2 content"); assertEquals("#set($var = \"value\")", this.document.extractTitle()); this.document.setContent("content not in section\n" + "= {{groovy}}print \"value\"{{/groovy}}=\nheader 1 content\n" + "== header 2==\nheader 2 content"); assertEquals("value", this.document.extractTitle()); this.document.setContent("content not in section\n=== header 3==="); assertEquals("", this.document.extractTitle()); } public void testExtractTitle10() { this.document.setContent("content not in section\n" + "1 header 1\nheader 1 content\n" + "1.1 header 2\nheader 2 content"); assertEquals("header 1", this.document.extractTitle()); this.document.setContent("content not in section\n"); assertEquals("", this.document.extractTitle()); } public void testSetAbsoluteParentReference() { XWikiDocument doc = new XWikiDocument(new DocumentReference("docwiki", "docspace", "docpage")); doc.setParentReference(new DocumentReference("docwiki", "docspace", "docpage2")); assertEquals("docspace.docpage2", doc.getParent()); } }
package gov.hhs.fha.nhinc.admingui.display; import gov.hhs.fha.nhinc.admingui.services.FhirResourceService; import gov.hhs.fha.nhinc.connectmgr.ConnectionManagerCache; import gov.hhs.fha.nhinc.connectmgr.ConnectionManagerException; import gov.hhs.fha.nhinc.nhinclib.NhincConstants; import gov.hhs.fha.nhinc.nhinclib.NullChecker; import org.apache.log4j.Logger; /** * * @author jassmit */ public class FhirDisplayController implements DisplayController { private static final Logger LOG = Logger.getLogger(FhirDisplayController.class); @Override public void checkDisplay() { String[] resourceNames = new String[]{FhirResourceService.BINARY_RESOURCE_NAME, FhirResourceService.DOCREF_RESOURCE_NAME, FhirResourceService.PATIENT_RESOURCE_NAME }; for(String resourceName : resourceNames) { boolean hasResource; try { hasResource = checkForResource(resourceName); } catch(ConnectionManagerException e) { LOG.warn(e, e); hasResource = false; } if(hasResource == true) { DisplayHolder.getInstance().setFhirEnabled(hasResource); return; } } DisplayHolder.getInstance().setFhirEnabled(false); } private boolean checkForResource(String resourceName) throws ConnectionManagerException { return NullChecker.isNotNullish(ConnectionManagerCache.getInstance().getAdapterEndpointURL(resourceName, NhincConstants.ADAPTER_API_LEVEL.LEVEL_a0)); } }
package com.hockeyhurd.entity.tileentity.renderer; import net.minecraft.block.Block; import net.minecraft.client.model.ModelChest; import net.minecraft.client.renderer.tileentity.TileEntityChestRenderer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import com.hockeyhurd.block.machines.BlockGlowChest; import com.hockeyhurd.entity.tileentity.TileEntityGlowChest; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class TileEntityGlowChestRenderer extends TileEntityChestRenderer { private static final ResourceLocation texture_ = new ResourceLocation("extratools", "textures/blocks/GlowChest.png"); // private static final ResourceLocation texture_ = new ResourceLocation("textures/entity/chest/normal.png"); private ModelChest field_147510_h = new ModelChest(); private static final String __OBFID = "CL_00000965"; public TileEntityGlowChestRenderer() { } public void renderTileEntityAt(TileEntityGlowChest entity, double x, double y, double z, float p_147500_8_) { int i; if (!entity.hasWorldObj()) i = 0; else { Block block = entity.getBlockType(); i = entity.getBlockMetadata(); if (block instanceof BlockGlowChest && i == 0) { try { ((BlockGlowChest) block).func_149954_e(entity.getWorldObj(), entity.xCoord, entity.yCoord, entity.zCoord); } catch (ClassCastException e) { FMLLog.severe("Attempted to render a chest at %d, %d, %d that was not a chest", entity.xCoord, entity.yCoord, entity.zCoord); } i = entity.getBlockMetadata(); } } ModelChest modelchest; modelchest = this.field_147510_h; if (entity.func_145980_j() == 0) this.bindTexture(texture_); GL11.glPushMatrix(); GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glTranslatef((float) x, (float) y + 1.0F, (float) z + 1.0F); GL11.glScalef(1.0F, -1.0F, -1.0F); GL11.glTranslatef(0.5F, 0.5F, 0.5F); short short1 = 0; if (i == 2) short1 = 180; if (i == 3) short1 = 0; if (i == 4) short1 = 90; if (i == 5) short1 = -90; // if (i == 2) GL11.glTranslatef(1.0F, 0.0F, 0.0F); // if (i == 5) GL11.glTranslatef(0.0F, 0.0F, -1.0F); GL11.glRotatef((float) short1, 0.0F, 1.0F, 0.0F); GL11.glTranslatef(-0.5F, -0.5F, -0.5F); float f1 = entity.prevLidAngle + (entity.lidAngle - entity.prevLidAngle) * p_147500_8_; float f2; f1 = 1.0F - f1; f1 = 1.0F - f1 * f1 * f1; modelchest.chestLid.rotateAngleX = -(f1 * (float) Math.PI / 2.0F); modelchest.renderAll(); GL11.glDisable(GL12.GL_RESCALE_NORMAL); GL11.glPopMatrix(); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); } public void renderTileEntityAt(TileEntity p_147500_1_, double p_147500_2_, double p_147500_4_, double p_147500_6_, float p_147500_8_) { this.renderTileEntityAt((TileEntityGlowChest) p_147500_1_, p_147500_2_, p_147500_4_, p_147500_6_, p_147500_8_); } }
package fr.synchrotron.soleil.ica.msvervice.management; import fr.synchrotron.soleil.ica.msvervice.management.handlers.POMExportHandler; import fr.synchrotron.soleil.ica.msvervice.management.handlers.POMImportHandler; import fr.synchrotron.soleil.ica.msvervice.vertx.verticle.pomexporter.POMExporterWorkerVerticle; import fr.synchrotron.soleil.ica.msvervice.vertx.verticle.pomimport.POMImporterWorkerVerticle; import io.netty.handler.codec.http.HttpResponseStatus; import org.vertx.java.core.AsyncResult; import org.vertx.java.core.AsyncResultHandler; import org.vertx.java.core.Handler; import org.vertx.java.core.eventbus.EventBus; import org.vertx.java.core.http.HttpServerRequest; import org.vertx.java.core.http.RouteMatcher; import org.vertx.java.core.json.JsonObject; import org.vertx.java.platform.Verticle; import java.io.IOException; import java.util.Map; import java.util.Properties; /** * @author Gregory Boissinot */ public class HttpEndpointManager extends Verticle { public static final long SEND_MS_TIMEOUT = 10 * 1000l; // in ms private static final String MONGODB_PROPERTIES_FILEPATH = "/infra.properties"; @Override public void start() { try { final EventBus eventBus = vertx.eventBus(); //-- Deploy Required Verticle final AsyncResultHandler<String> asyncResultHandler = new AsyncResultHandler<String>() { @Override public void handle(AsyncResult<String> asyncResult) { onVerticleLoaded(asyncResult); } }; final JsonObject jsonObject = createConfig(); container.deployWorkerVerticle( POMImporterWorkerVerticle.class.getCanonicalName(), jsonObject, 1, true, asyncResultHandler); container.deployWorkerVerticle( POMExporterWorkerVerticle.class.getCanonicalName(), jsonObject, 1, true, asyncResultHandler); RouteMatcher routeMatcher = new RouteMatcher(); //-- POM IMPORTER final POMImportHandler pomImportHandler = new POMImportHandler(eventBus); routeMatcher.post("/pom/import", pomImportHandler); routeMatcher.put("/pom/import", pomImportHandler); //--POM EXPORTER final POMExportHandler pomExportHandler = new POMExportHandler(eventBus); routeMatcher.post("/pom/export", pomExportHandler); routeMatcher.allWithRegEx(".*", new Handler<HttpServerRequest>() { @Override public void handle(HttpServerRequest request) { request.response().setStatusCode(HttpResponseStatus.NOT_FOUND.code()); request.response().end("Path or Http method not supported.\n"); } }); final int serverPort = getServerPort(container.config()); vertx.createHttpServer().requestHandler(routeMatcher).listen(serverPort); container.logger().info("Webserver started on " + serverPort); } catch (Throwable e) { container.logger().error(e.getMessage()); } } private int getServerPort(JsonObject config) { final Integer port = config.getInteger("port"); if (port == null) { throw new ConfigurationException("A port number is required"); } return port; } private void onVerticleLoaded(AsyncResult<String> asyncResult) { if (!asyncResult.succeeded()) { container.logger().info(asyncResult.cause()); } } private JsonObject createConfig() { final JsonObject config = container.config(); Properties properties = loadInfraFile(MONGODB_PROPERTIES_FILEPATH); for (Map.Entry<Object, Object> objectObjectEntry : properties.entrySet()) { String propKey = (String) objectObjectEntry.getKey(); if (!config.containsField(propKey)) { String propValue = (String) objectObjectEntry.getValue(); config.putString(propKey, propValue); } } return config; } private Properties loadInfraFile(String propertiedFilePath) { Properties properties = new Properties(); try { properties.load(this.getClass().getResourceAsStream(propertiedFilePath)); return properties; } catch (IOException ioe) { throw new RuntimeException(ioe); } } }
package org.iidp.ostmap.commons.tokenizer; import org.junit.Assert; import org.junit.Test; import java.util.List; public class TokenizerTest { private static final String INPUT_TEXT1 = "this is some text\n and +i love (it) #truelove @test''...../''!+<>!!! " ; private static final String INPUT_TEXT2 = "Hello Example ..."; private static final String[] TOKENS1 = new String[] { "this" ,"is", "some", "text", "and" , "love", "it", "#truelove", "truelove","@test", "test"}; private static final String[] TOKENS2 = new String[] { "hello" ,"example" }; @Test public void testGetTokens(){ Tokenizer tokenizer = new Tokenizer(); List<String> tokens1 = tokenizer.tokenizeString(INPUT_TEXT1); for(String s: tokens1){ System.out.println(s); Boolean equal1 = false; for(int i= 0 ; i<TOKENS1.length;i++){ if(s.equals(TOKENS1[i])){ equal1= true; break; } } Assert.assertTrue(equal1); } List<String> tokens2 = tokenizer.tokenizeString(INPUT_TEXT2); for(String s: tokens2){ Boolean equal2 = false; for(int i= 0 ; i<TOKENS2.length;i++){ if(s.equals(TOKENS2[i])){ equal2= true; break; } } Assert.assertTrue(equal2); } } }
package simpleserver.nbt; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class NBTList<T extends NBTag> extends NBTag { private ArrayList<T> value; private byte tagId; NBTList(DataInputStream in, Boolean named) throws Exception { super(in, named); } public NBTList(byte tagId) { this.tagId = tagId; value = new ArrayList<T>(); } public NBTList(NBT tag) { this(tag.id()); } public NBTList(String name, byte tagId) { super(name); this.tagId = tagId; value = new ArrayList<T>(); } public NBTList(String name, NBT tag) { this(name, tag.id()); } @Override protected byte id() { return 9; } @Override List<T> get() { return value; } public int size() { return value.size(); } public void clear() { value.clear(); } public NBT type() { return NBT.values()[tagId]; } @SuppressWarnings( { "unchecked", "hiding" }) public <T extends NBTag> T cast() { return (T) this; } public void add(T tag) { if (tagId == tag.id()) { value.add(tag); } } public boolean contains(T obj) { return value.contains(obj); } public T get(int index) { return value.get(index); } public NBTByte getByte(int index) { return (NBTByte) value.get(index); } public NBTShort getShort(int index) { return (NBTShort) value.get(index); } public NBTInt getInt(int index) { return (NBTInt) value.get(index); } public NBTLong getLong(int name) { return (NBTLong) value.get(name); } public NBTFloat getFloat(int index) { return (NBTFloat) value.get(index); } public NBTDouble getDouble(int index) { return (NBTDouble) value.get(index); } public NBTArray getArray(int index) { return (NBTArray) value.get(index); } public NBTString getString(int index) { return (NBTString) value.get(index); } @SuppressWarnings("unchecked") public NBTList<NBTag> getList(int index) { return (NBTList<NBTag>) value.get(index); } public NBTCompound getCompound(int index) { return (NBTCompound) value.get(index); } @SuppressWarnings("unchecked") @Override protected void loadValue(DataInputStream in) throws Exception { tagId = in.readByte(); int length = in.readInt(); value = new ArrayList<T>(length); for (int i = 0; i < length; i++) { value.add((T) NBT.loadTag(in, false, tagId)); } } @Override protected void saveValue(DataOutputStream out) throws IOException { out.writeByte(tagId); out.writeInt(size()); for (NBTag tag : value) { tag.save(out, false); } } @Override protected String valueToString(int level) { StringBuilder string = new StringBuilder(); string.append("[\n"); for (NBTag tag : value) { string.append(tag.toString(level + 1) + "\n"); } string.append(indent(level)); string.append("]"); return string.toString(); } }
package ome.xml.meta; import net.imglib2.meta.Axes; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; import org.scijava.service.AbstractService; import org.scijava.service.Service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ome.scifio.DefaultImageMetadata; import ome.scifio.FormatException; import ome.scifio.FormatService; import ome.scifio.ImageMetadata; import ome.scifio.Metadata; import ome.scifio.Reader; import ome.scifio.common.DateTools; import ome.scifio.io.Location; import ome.scifio.services.ServiceException; import ome.scifio.util.FormatTools; import ome.scifio.util.SCIFIOMetadataTools; import ome.xml.model.*; import ome.xml.model.enums.Correction; import ome.xml.model.enums.DetectorType; import ome.xml.model.enums.DimensionOrder; import ome.xml.model.enums.EnumerationException; import ome.xml.model.enums.ExperimentType; import ome.xml.model.enums.Immersion; import ome.xml.model.enums.LaserMedium; import ome.xml.model.enums.LaserType; import ome.xml.model.enums.PixelType; import ome.xml.model.enums.handlers.CorrectionEnumHandler; import ome.xml.model.enums.handlers.DetectorTypeEnumHandler; import ome.xml.model.enums.handlers.ExperimentTypeEnumHandler; import ome.xml.model.enums.handlers.ImmersionEnumHandler; import ome.xml.model.enums.handlers.LaserMediumEnumHandler; import ome.xml.model.enums.handlers.LaserTypeEnumHandler; import ome.xml.model.primitives.*; import ome.xml.services.OMEXMLService; @Plugin(type = Service.class) public class DefaultOMEXMLMetadataService extends AbstractService implements OMEXMLMetadataService { // -- Constants -- private static final Logger LOGGER = LoggerFactory.getLogger(DefaultOMEXMLMetadataService.class); // -- Static fields -- private boolean defaultDateEnabled = true; // -- Parameters -- @Parameter FormatService formatService; // -- Utility methods - OME-XML -- /** * Populates the 'pixels' element of the given metadata store, using core * metadata from the given reader. */ public void populatePixels(MetadataStore store, Metadata meta) { populatePixels(store, meta, false, true); } /** * Populates the 'pixels' element of the given metadata store, using core * metadata from the given reader. If the 'doPlane' flag is set, * then the 'plane' elements will be populated as well. */ public void populatePixels(MetadataStore store, Metadata meta, boolean doPlane) { populatePixels(store, meta, doPlane, true); } /** * Populates the 'pixels' element of the given metadata store, using core * metadata from the given reader. If the 'doPlane' flag is set, * then the 'plane' elements will be populated as well. * If the 'doImageName' flag is set, then the image name will be populated * as well. By default, 'doImageName' is true. */ public void populatePixels(MetadataStore store, Metadata meta, boolean doPlane, boolean doImageName) { if (store == null || meta == null) return; for (int i=0; i<meta.getImageCount(); i++) { String imageName = null; if (doImageName) { Location f = new Location(getContext(), meta.getDatasetName()); imageName = f.getName(); } String pixelType = FormatTools.getPixelTypeString(meta.getPixelType(i)); String order = FormatTools.findDimensionOrder(meta, i); int xSize = meta.getAxisLength(i, Axes.X); int ySize = meta.getAxisLength(i, Axes.Y); int zSize = meta.getAxisLength(i, Axes.Z); int cSize = meta.getAxisLength(i, Axes.CHANNEL); int tSize = meta.getAxisLength(i, Axes.TIME); populateMetadata(store, meta.getDatasetName(), i, imageName, meta.isLittleEndian(i), order, pixelType, xSize, ySize, zSize, cSize, tSize, meta.getRGBChannelCount(i)); OMEXMLService service = formatService.getInstance(OMEXMLService.class); if (service.isOMEXMLRoot(store.getRoot())) { //TODO any way or reason to access a base store? if(service.isOMEXMLMetadata(store)) { OMEXMLMetadata omeMeta; try { omeMeta = service.getOMEMetadata(service.asRetrieve(store)); omeMeta.resolveReferences(); } catch (ServiceException e) { LOGGER.warn("Failed to resolve references", e); } } OME root = (OME) store.getRoot(); BinData bin = root.getImage(i).getPixels().getBinData(0); bin.setLength(new NonNegativeLong(0L)); store.setRoot(root); } if (doPlane) { for (int q=0; q<meta.getPlaneCount(i); q++) { int[] coords = FormatTools.getZCTCoords(meta, i, q); store.setPlaneTheZ(new NonNegativeInteger(coords[0]), i, q); store.setPlaneTheC(new NonNegativeInteger(coords[1]), i, q); store.setPlaneTheT(new NonNegativeInteger(coords[2]), i, q); } } } } /** * Populates the given {@link MetadataStore}, for the specified imageIndex, using * the provided values. * <p> * After calling this method, the metadata store will be sufficiently * populated for use with an {@link IFormatWriter} (assuming it is also a * {@link MetadataRetrieve}). * </p> */ public void populateMetadata(MetadataStore store, int imageIndex, String imageName, boolean littleEndian, String dimensionOrder, String pixelType, int sizeX, int sizeY, int sizeZ, int sizeC, int sizeT, int samplesPerPixel) { populateMetadata(store, null, imageIndex, imageName, littleEndian, dimensionOrder, pixelType, sizeX, sizeY, sizeZ, sizeC, sizeT, samplesPerPixel); } /** * Populates the given {@link MetadataStore}, for the specified imageIndex, using * the values from the provided {@link DatasetMetadata}. * <p> * After calling this method, the metadata store will be sufficiently * populated for use with an {@link IFormatWriter} (assuming it is also a * {@link MetadataRetrieve}). * </p> */ public void populateMetadata(MetadataStore store, int imageIndex, String imageName, Metadata datasetMeta) { int sizeX = datasetMeta.getAxisLength(imageIndex, Axes.X); int sizeY = datasetMeta.getAxisLength(imageIndex, Axes.Y); int sizeZ = datasetMeta.getAxisLength(imageIndex, Axes.Z); int sizeC = datasetMeta.getAxisLength(imageIndex, Axes.CHANNEL); int sizeT = datasetMeta.getAxisLength(imageIndex, Axes.TIME); final String pixelType = FormatTools.getPixelTypeString(datasetMeta.getPixelType(imageIndex)); final int effSizeC = datasetMeta.getImageCount() / sizeZ / sizeT; final int samplesPerPixel = sizeC / effSizeC; populateMetadata(store, null, imageIndex, imageName, datasetMeta.isLittleEndian(imageIndex), FormatTools.findDimensionOrder(datasetMeta, imageIndex), pixelType, sizeX, sizeY, sizeZ, sizeC, sizeT, samplesPerPixel); } /** * Populates the given {@link MetadataStore}, for the specified imageIndex, using * the provided values. * <p> * After calling this method, the metadata store will be sufficiently * populated for use with an {@link IFormatWriter} (assuming it is also a * {@link MetadataRetrieve}). * </p> */ public void populateMetadata(MetadataStore store, String file, int imageIndex, String imageName, boolean littleEndian, String dimensionOrder, String pixelType, int sizeX, int sizeY, int sizeZ, int sizeC, int sizeT, int samplesPerPixel) { store.setImageID(createLSID("Image", imageIndex), imageIndex); setDefaultCreationDate(store, file, imageIndex); if (imageName != null) store.setImageName(imageName, imageIndex); populatePixelsOnly(store, imageIndex, littleEndian, dimensionOrder, pixelType, sizeX, sizeY, sizeZ, sizeC, sizeT, samplesPerPixel); } public void populatePixelsOnly(MetadataStore store, Reader r) { Metadata dMeta = r.getMetadata(); for (int imageIndex=0; imageIndex<r.getImageCount(); imageIndex++) { String pixelType = FormatTools.getPixelTypeString(dMeta.getPixelType(imageIndex)); populatePixelsOnly(store, imageIndex, dMeta.isLittleEndian(imageIndex), FormatTools.findDimensionOrder(dMeta, imageIndex), pixelType, dMeta.getAxisLength(imageIndex, Axes.X), dMeta.getAxisLength(imageIndex, Axes.Y), dMeta.getAxisLength(imageIndex, Axes.Z), dMeta.getAxisLength(imageIndex, Axes.CHANNEL), dMeta.getAxisLength(imageIndex, Axes.TIME), dMeta.getRGBChannelCount(imageIndex)); } } public void populatePixelsOnly(MetadataStore store, int imageIndex, boolean littleEndian, String dimensionOrder, String pixelType, int sizeX, int sizeY, int sizeZ, int sizeC, int sizeT, int samplesPerPixel) { store.setPixelsID(createLSID("Pixels", imageIndex), imageIndex); store.setPixelsBinDataBigEndian(!littleEndian, imageIndex, 0); try { store.setPixelsDimensionOrder( DimensionOrder.fromString(dimensionOrder), imageIndex); } catch (EnumerationException e) { LOGGER.warn("Invalid dimension order: " + dimensionOrder, e); } try { store.setPixelsType(PixelType.fromString(pixelType), imageIndex); } catch (EnumerationException e) { LOGGER.warn("Invalid pixel type: " + pixelType, e); } store.setPixelsSizeX(new PositiveInteger(sizeX), imageIndex); store.setPixelsSizeY(new PositiveInteger(sizeY), imageIndex); store.setPixelsSizeZ(new PositiveInteger(sizeZ), imageIndex); store.setPixelsSizeC(new PositiveInteger(sizeC), imageIndex); store.setPixelsSizeT(new PositiveInteger(sizeT), imageIndex); int effSizeC = sizeC / samplesPerPixel; for (int i=0; i<effSizeC; i++) { store.setChannelID(createLSID("Channel", imageIndex, i), imageIndex, i); store.setChannelSamplesPerPixel(new PositiveInteger(samplesPerPixel), imageIndex, i); } } /** * Disables the setting of a default creation date. * * By default, missing creation dates will be replaced with the corresponding * file's last modification date, or the current time if the modification * date is not available. * * Calling this method with the 'enabled' parameter set to 'false' causes * missing creation dates to be left as null. * * @param enabled See above. * @see #setDefaultCreationDate(MetadataStore, String, int) */ public void setDefaultDateEnabled(boolean enabled) { defaultDateEnabled = enabled; } /** * Sets a default creation date. If the named file exists, then the creation * date is set to the file's last modification date. Otherwise, it is set * to the current date. * * @see #setDefaultDateEnabled(boolean) */ public void setDefaultCreationDate(MetadataStore store, String id, int imageIndex) { if (!defaultDateEnabled) { return; } Location file = id == null ? null : new Location(getContext(), id).getAbsoluteFile(); long time = System.currentTimeMillis(); if (file != null && file.exists()) time = file.lastModified(); store.setImageAcquisitionDate(new Timestamp(DateTools.convertDate( time, DateTools.UNIX)), imageIndex); } /** * * @throws FormatException if there is a missing metadata field, * or the metadata object is uninitialized */ public void verifyMinimumPopulated(MetadataRetrieve src) throws FormatException { verifyMinimumPopulated(src, 0); } /** * * @throws FormatException if there is a missing metadata field, * or the metadata object is uninitialized */ public void verifyMinimumPopulated(MetadataRetrieve src, int n) throws FormatException { if (src == null) { throw new FormatException("Metadata object is null; " + "call IFormatWriter.setMetadataRetrieve() first"); } if (src instanceof MetadataStore && ((MetadataStore) src).getRoot() == null) { throw new FormatException("Metadata object has null root; " + "call IMetadata.createRoot() first"); } if (src.getImageID(n) == null) { throw new FormatException("Image ID #" + n + " is null"); } if (src.getPixelsID(n) == null) { throw new FormatException("Pixels ID #" + n + " is null"); } for (int i=0; i<src.getChannelCount(n); i++) { if (src.getChannelID(n, i) == null) { throw new FormatException("Channel ID #" + i + " in Image #" + n + " is null"); } } if (src.getPixelsBinDataBigEndian(n, 0) == null) { throw new FormatException("BigEndian #" + n + " is null"); } if (src.getPixelsDimensionOrder(n) == null) { throw new FormatException("DimensionOrder #" + n + " is null"); } if (src.getPixelsType(n) == null) { throw new FormatException("PixelType #" + n + " is null"); } if (src.getPixelsSizeC(n) == null) { throw new FormatException("SizeC #" + n + " is null"); } if (src.getPixelsSizeT(n) == null) { throw new FormatException("SizeT #" + n + " is null"); } if (src.getPixelsSizeX(n) == null) { throw new FormatException("SizeX #" + n + " is null"); } if (src.getPixelsSizeY(n) == null) { throw new FormatException("SizeY #" + n + " is null"); } if (src.getPixelsSizeZ(n) == null) { throw new FormatException("SizeZ #" + n + " is null"); } } /** * Adjusts the given dimension order as needed so that it contains exactly * one of each of the following characters: 'X', 'Y', 'Z', 'C', 'T'. */ public String makeSaneDimensionOrder(String dimensionOrder) { String order = dimensionOrder.toUpperCase(); order = order.replaceAll("[^XYZCT]", ""); String[] axes = new String[] {"X", "Y", "C", "Z", "T"}; for (String axis : axes) { if (order.indexOf(axis) == -1) order += axis; while (order.indexOf(axis) != order.lastIndexOf(axis)) { order = order.replaceFirst(axis, ""); } } return order; } /** * Constructs an LSID, given the object type and indices. * For example, if the arguments are "Detector", 1, and 0, the LSID will * be "Detector:1:0". */ public String createLSID(String type, int... indices) { StringBuffer lsid = new StringBuffer(type); for (int index : indices) { lsid.append(":"); lsid.append(index); } return lsid.toString(); } /** * Retrieves an {@link ome.xml.model.enums.ExperimentType} enumeration * value for the given String. * * @throws ome.xml.model.enums.EnumerationException if an appropriate * enumeration value is not found. */ public ExperimentType getExperimentType(String value) throws FormatException { ExperimentTypeEnumHandler handler = new ExperimentTypeEnumHandler(); try { return (ExperimentType) handler.getEnumeration(value); } catch (EnumerationException e) { throw new FormatException("ExperimentType creation failed", e); } } /** * Retrieves an {@link ome.xml.model.enums.LaserType} enumeration * value for the given String. * * @throws ome.xml.model.enums.EnumerationException if an appropriate * enumeration value is not found. */ public LaserType getLaserType(String value) throws FormatException { LaserTypeEnumHandler handler = new LaserTypeEnumHandler(); try { return (LaserType) handler.getEnumeration(value); } catch (EnumerationException e) { throw new FormatException("LaserType creation failed", e); } } /** * Retrieves an {@link ome.xml.model.enums.LaserMedium} enumeration * value for the given String. * * @throws ome.xml.model.enums.EnumerationException if an appropriate * enumeration value is not found. */ public LaserMedium getLaserMedium(String value) throws FormatException { LaserMediumEnumHandler handler = new LaserMediumEnumHandler(); try { return (LaserMedium) handler.getEnumeration(value); } catch (EnumerationException e) { throw new FormatException("LaserMedium creation failed", e); } } /** * Retrieves an {@link ome.xml.model.enums.Immersion} enumeration * value for the given String. * * @throws ome.xml.model.enums.EnumerationException if an appropriate * enumeration value is not found. */ public Immersion getImmersion(String value) throws FormatException { ImmersionEnumHandler handler = new ImmersionEnumHandler(); try { return (Immersion) handler.getEnumeration(value); } catch (EnumerationException e) { throw new FormatException("Immersion creation failed", e); } } /** * Retrieves an {@link ome.xml.model.enums.Correction} enumeration * value for the given String. * * @throws ome.xml.model.enums.EnumerationException if an appropriate * enumeration value is not found. */ public Correction getCorrection(String value) throws FormatException { CorrectionEnumHandler handler = new CorrectionEnumHandler(); try { return (Correction) handler.getEnumeration(value); } catch (EnumerationException e) { throw new FormatException("Correction creation failed", e); } } /** * Retrieves an {@link ome.xml.model.enums.DetectorType} enumeration * value for the given String. * * @throws ome.xml.model.enums.EnumerationException if an appropriate * enumeration value is not found. */ public DetectorType getDetectorType(String value) throws FormatException { DetectorTypeEnumHandler handler = new DetectorTypeEnumHandler(); try { return (DetectorType) handler.getEnumeration(value); } catch (EnumerationException e) { throw new FormatException("DetectorType creation failed", e); } } /** * Uses the provided MetadataRetrieve to populate the format-agnostic * image information in the provided Metadata object (that is, the * ImageMetadata). * * @param retrieve * @param meta */ public void populateMetadata(MetadataRetrieve retrieve, Metadata meta) { meta.setDatasetName(retrieve.getImageName(0)); for (int i=0; i<retrieve.getImageCount(); i++) { ImageMetadata iMeta; if (i >= meta.getImageCount()) { iMeta = new DefaultImageMetadata(); meta.add(iMeta); } else iMeta = meta.get(i); populateImageMetadata(retrieve, i, iMeta); } } /** * Populates the provided ImageMetadata object using the specified * image index into the MetadataRetrieve. * * @param retrieve * @param iMeta */ public void populateImageMetadata(MetadataRetrieve retrieve, int imageIndex, ImageMetadata iMeta) { int sizeX = retrieve.getPixelsSizeX(imageIndex).getValue(); int sizeY = retrieve.getPixelsSizeY(imageIndex).getValue(); int sizeZ = retrieve.getPixelsSizeZ(imageIndex).getValue(); int sizeC = retrieve.getPixelsSizeC(imageIndex).getValue(); int sizeT = retrieve.getPixelsSizeZ(imageIndex).getValue(); String dimensionOrder = retrieve.getPixelsDimensionOrder(imageIndex).getValue(); boolean little = !retrieve.getPixelsBinDataBigEndian(imageIndex, 0); String pixelType = retrieve.getPixelsType(imageIndex).getValue(); int rgbCCount = retrieve.getChannelSamplesPerPixel(imageIndex, 0).getValue(); SCIFIOMetadataTools.populateDimensions(iMeta, dimensionOrder, sizeX, sizeY, sizeZ, sizeC, sizeT); iMeta.setLittleEndian(little); iMeta.setPixelType(FormatTools.pixelTypeFromString(pixelType)); iMeta.setBitsPerPixel(FormatTools.getBitsPerPixel(iMeta.getPixelType())); if (rgbCCount > 1) iMeta.setRGB(true); iMeta.setPlaneCount(sizeZ * (sizeC / rgbCCount) * sizeT); } }
package org.deviceconnect.message; import android.net.Uri; import android.util.Log; import org.deviceconnect.message.intent.message.IntentDConnectMessage; import org.deviceconnect.sdk.BuildConfig; import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; import org.java_websocket.drafts.Draft_17; import org.java_websocket.framing.Framedata; import org.java_websocket.handshake.ServerHandshake; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.URI; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; /** * WebSocket. * @author NTT DOCOMO, INC. */ class DConnectWebSocketClient { private static final boolean DEBUG = BuildConfig.DEBUG; private static final String TAG = "DConnectSDK"; private static final String JOIN_SERVICE_ID = "_"; /** * Device Connect Manager. */ private final Map<String, List<HttpDConnectSDK.OnEventListener>> mListenerMap = new HashMap<>(); /** * WebSocket. */ private HttpDConnectSDK.OnWebSocketListener mOnWebSocketListener; /** * WebSocket. */ private WebSocketClient mWebSocketClient; /** * WebSocket. * <p> * truefalse * </p> */ private boolean isEstablishedWebSocket; /** * WebSocket(ms). */ private int mTimeout = 30 * 1000; /** * WebSocket. * @param onWebSocketListener */ void setOnWebSocketListener(final HttpDConnectSDK.OnWebSocketListener onWebSocketListener) { mOnWebSocketListener = onWebSocketListener; } /** * WebSocket(ms). * @param timeout (ms) */ void setTimeout(final int timeout) { mTimeout = timeout; } /** * Device Connect ManagerWebSocket. * @param uri URI * @param origin * @param accessToken */ void connect(final String uri, final String origin, final String accessToken) { if (mWebSocketClient != null) { if (DEBUG) { Log.w(TAG, "WebSocketClient is already connected."); } return; } Map<String, String> headers = new HashMap<>(); if (origin != null) { headers.put(IntentDConnectMessage.EXTRA_ORIGIN, origin); } mWebSocketClient = new WebSocketClient(URI.create(uri), new Draft_17(), headers, mTimeout) { @Override public void onMessage(final String message) { try { JSONObject json = new JSONObject(message); if (!isEstablishedWebSocket) { if (json.getInt(DConnectMessage.EXTRA_RESULT) == DConnectMessage.RESULT_OK) { isEstablishedWebSocket = true; if (mOnWebSocketListener != null) { mOnWebSocketListener.onOpen(); } } else { if (mOnWebSocketListener != null) { RuntimeException ex = new RuntimeException(); mOnWebSocketListener.onError(ex); } } } else { String key = createPath(json); synchronized (mListenerMap) { List<DConnectSDK.OnEventListener> listeners = mListenerMap.get(key); if (listeners != null) { for (DConnectSDK.OnEventListener l : listeners) { l.onMessage(new DConnectEventMessage(message)); } } } } } catch (JSONException e) { if (DEBUG) { Log.w(TAG, "The message from Device Connect Manager is invalid.", e); } if (mOnWebSocketListener != null) { mOnWebSocketListener.onError(e); } } } @Override public void onOpen(final ServerHandshake handshake) { sendAccessToken(accessToken); } @Override public void onClose(final int code, final String reason, final boolean remote) { isEstablishedWebSocket = false; DConnectWebSocketClient.this.close(); if (mOnWebSocketListener != null) { mOnWebSocketListener.onClose(); } } @Override public void onWebsocketPing(final WebSocket conn, final Framedata f) { super.onWebsocketPing(conn, f); } @Override public void onWebsocketPong(final WebSocket conn, final Framedata f) { super.onWebsocketPong(conn, f); } @Override public void onError(final Exception ex) { isEstablishedWebSocket = false; if (mOnWebSocketListener != null) { mOnWebSocketListener.onError(ex); } } }; if (uri.startsWith("wss")) { try { SSLSocketFactory factory = createSSLSocketFactory(); mWebSocketClient.setSocket(factory.createSocket()); } catch (NoSuchAlgorithmException | KeyManagementException | IOException e) { if (mOnWebSocketListener != null) { mOnWebSocketListener.onError(e); } return; } } mWebSocketClient.connect(); } /** * WebSocket. * @return truefalse */ boolean isConnected() { return isEstablishedWebSocket; } /** * . * @param json * @return */ private String createPath(final JSONObject json) { String uri = "/gotapi"; if (json.has(DConnectMessage.EXTRA_PROFILE)) { uri += "/"; uri += json.optString(DConnectMessage.EXTRA_PROFILE); } if (json.has(DConnectMessage.EXTRA_INTERFACE)) { uri += "/"; uri += json.optString(DConnectMessage.EXTRA_INTERFACE); } if (json.has(DConnectMessage.EXTRA_ATTRIBUTE)) { uri += "/"; uri += json.optString(DConnectMessage.EXTRA_ATTRIBUTE); } uri = uri.toLowerCase(); if (json.has(DConnectMessage.EXTRA_SERVICE_ID)) { uri += JOIN_SERVICE_ID; uri += json.optString(DConnectMessage.EXTRA_SERVICE_ID); } return uri; } /** * URI. * @param uri URI * @return */ private String convertUriToPath(final Uri uri) { return uri.getPath().toLowerCase() + JOIN_SERVICE_ID + uri.getQueryParameter(DConnectMessage.EXTRA_SERVICE_ID); } /** * WebSocket. */ void close() { if (mWebSocketClient != null) { mWebSocketClient.close(); mWebSocketClient = null; } isEstablishedWebSocket = false; } /** * . * * @param uri URI * @return truefalse */ boolean hasEventListener(final Uri uri) { String key = convertUriToPath(uri); synchronized (mListenerMap) { List<DConnectSDK.OnEventListener> listeners = mListenerMap.get(key); return listeners != null && !listeners.isEmpty(); } } /** * . * @param uri URI * @param listener */ void addEventListener(final Uri uri, final HttpDConnectSDK.OnEventListener listener) { String key = convertUriToPath(uri); synchronized (mListenerMap) { List<DConnectSDK.OnEventListener> listeners = mListenerMap.get(key); if (listeners == null) { listeners = new ArrayList<>(); mListenerMap.put(key, listeners); } listeners.add(listener); } } /** * . * @param uri URI */ void removeEventListener(final Uri uri) { String key = convertUriToPath(uri); synchronized (mListenerMap) { mListenerMap.remove(key); } } /** * . * * @param uri URI * @param listener */ void removeEventListener(final Uri uri, final HttpDConnectSDK.OnEventListener listener) { String key = convertUriToPath(uri); synchronized (mListenerMap) { List<DConnectSDK.OnEventListener> listeners = mListenerMap.get(key); if (listeners != null) { listeners.remove(listener); } } } /** * Device Connect Manager. * @param accessToken */ private void sendAccessToken(final String accessToken) { mWebSocketClient.send("{\"" + DConnectMessage.EXTRA_ACCESS_TOKEN + "\":\"" + accessToken + "\"}"); } /** * SSL. * * @return SSLSocketFactory * @throws NoSuchAlgorithmException SSL * @throws KeyManagementException */ private SSLSocketFactory createSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException { TrustManager[] transManagers = { new X509TrustManager() { @Override public void checkClientTrusted(final X509Certificate[] chain, final String authType) { } @Override public void checkServerTrusted(final X509Certificate[] chain, final String authType) { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }; SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(null, transManagers, new SecureRandom()); return sslcontext.getSocketFactory(); } }
package edu.cuny.citytech.foreachlooptolambda.ui.visitors; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.BooleanLiteral; import org.eclipse.jdt.core.dom.BreakStatement; import org.eclipse.jdt.core.dom.ContinueStatement; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.ReturnStatement; import org.eclipse.jdt.core.dom.SimpleName; public class EnhancedForStatementVisitor extends ASTVisitor { private boolean encounteredBreakStatement; private boolean encounteredContinueStatement; private boolean encounteredInvalidReturnStatement; private boolean encounteredThrownCheckedException; private boolean encounteredNonEffectivelyFinalVars; private int returnCount = 0; @Override public boolean visit(BreakStatement node) { this.encounteredBreakStatement = true; return super.visit(node); } @Override public boolean visit(ContinueStatement node) { this.encounteredContinueStatement = true; return super.visit(node); } @Override public boolean visit(MethodInvocation node) { SimpleName name = node.getName(); IBinding iBinding = name.resolveBinding(); System.out.println(name); System.out.println("This is ITypeBinding: "+iBinding); return super.visit(node); } /** * checking if returnStatement is boolean, not null and has only one return * * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.ReturnStatement) */ @Override public boolean visit(ReturnStatement node) { // one more return statement encountered. returnCount++; // examine what is being returned. ASTNode expression = node.getExpression(); // if there is a return statement, it must return a boolean literal. if (expression == null || !(expression instanceof BooleanLiteral)) { this.encounteredInvalidReturnStatement = true; } return super.visit(node); } public boolean containsBreak() { return this.encounteredBreakStatement; } public boolean containsContinue() { return encounteredContinueStatement; } public boolean containsInvalidReturn() { return encounteredInvalidReturnStatement; } public boolean containsMultipleReturn() { return returnCount > 1; } public boolean containsException() { return encounteredThrownCheckedException; } public boolean containsNEFS() { return encounteredNonEffectivelyFinalVars; } }
package org.javasimon.console; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.javasimon.Manager; import org.javasimon.utils.SimonUtils; /** * Front controller servlet of Simon Web console. * * @author gquintana */ @SuppressWarnings("UnusedDeclaration") public class SimonConsoleServlet extends HttpServlet { /** * Serial version UID since class is Serializable. */ public static final long serialVersionUID = 1L; /** * URL Prefix init parameter name. */ public static final String URL_PREFIX_INIT_PARAMETER = "url-prefix"; /** * Plugin classes init parameter name. */ public static final String PLUGIN_CLASSES_INIT_PARAMETER = "plugin-classes"; private SimonConsoleRequestProcessor requestProcessor; @Override public void init(ServletConfig config) throws ServletException { super.init(config); pickUpSharedManagerIfExists(config); String urlPrefix = config.getInitParameter(URL_PREFIX_INIT_PARAMETER); String pluginClasses = config.getInitParameter(PLUGIN_CLASSES_INIT_PARAMETER); initRequestProcessor(urlPrefix, pluginClasses); } public void initRequestProcessor(String urlPrefix, String pluginClasses) { if (urlPrefix == null) { urlPrefix = ""; } else { urlPrefix = urlPrefix.trim(); } requestProcessor = new SimonConsoleRequestProcessor(urlPrefix); if (pluginClasses != null) { requestProcessor.getPluginManager().addPlugins(pluginClasses); } requestProcessor.initActionBindings(); } public SimonConsoleRequestProcessor getRequestProcessor() { return requestProcessor; } private void pickUpSharedManagerIfExists(ServletConfig config) { Object managerObject = config.getServletContext().getAttribute(SimonUtils.MANAGER_SERVLET_CTX_ATTRIBUTE); if (managerObject != null && managerObject instanceof Manager) { requestProcessor.setManager((Manager) managerObject); } } /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { requestProcessor.processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { requestProcessor.processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; } }
package edu.cuny.citytech.foreachlooptolambda.ui.visitors; import java.util.Arrays; import java.util.List; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.BooleanLiteral; import org.eclipse.jdt.core.dom.BreakStatement; import org.eclipse.jdt.core.dom.CatchClause; import org.eclipse.jdt.core.dom.ContinueStatement; import org.eclipse.jdt.core.dom.EnhancedForStatement; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.ReturnStatement; import org.eclipse.jdt.core.dom.ThrowStatement; import org.eclipse.jdt.core.dom.TryStatement; public class EnhancedForStatementVisitor extends ASTVisitor { private boolean encounteredBreakStatement; private boolean encounteredContinueStatement; private boolean encounteredInvalidReturnStatement; private boolean encounteredThrownCheckedException; private boolean encounteredNonEffectivelyFinalVars; private int returnCount = 0; /** * The enhanced for statement that will be visited. */ private EnhancedForStatement enhancedForStatement; /** * Create a new visitor. * * @param enhancedForStatement * The enhanced for statement that will be visited. */ public EnhancedForStatementVisitor(EnhancedForStatement enhancedForStatement) { this.enhancedForStatement = enhancedForStatement; } // finding the TryStatement node public static ASTNode findTryAncestor(ASTNode node) { if (node == null || node instanceof TryStatement) { return node; } return findTryAncestor(node); } @Override public boolean visit(BreakStatement node) { this.encounteredBreakStatement = true; return super.visit(node); } @Override public boolean visit(ContinueStatement node) { this.encounteredContinueStatement = true; return super.visit(node); } private void handleException(ASTNode nodeContaingException) { // gets the top node. If it returns // null, there is no other top. ASTNode tryStatementParent = (nodeContaingException.getParent()).getParent(); ASTNode throwStatementParent = tryStatementParent.getParent(); if (throwStatementParent instanceof TryStatement) { System.out.println("this is throwStatementParent"); this.encounteredThrownCheckedException = false; } // findTryStatmaent if there is any catch block else if (tryStatementParent instanceof TryStatement) { TryStatement tryStatement = (TryStatement) tryStatementParent; List catchClauses = tryStatement.catchClauses(); // checking if there is any catchBlock catchClauses.stream().forEach(s -> System.out.println("this is catchBlock "+s)); if (catchClauses.size() >= 1) { this.encounteredThrownCheckedException = false; // TODO: Not sufficient condition. See algo. } else { //at this point, there are no catch clauses. this.encounteredThrownCheckedException = true; } } else { this.encounteredThrownCheckedException = true; } } @Override public boolean visit(MethodInvocation node) { IMethodBinding iMethodBinding = node.resolveMethodBinding(); ITypeBinding[] exceptionTypes = iMethodBinding.getExceptionTypes(); // if there are exceptions if (exceptionTypes.length >= 1) { handleException(node); } return super.visit(node); } @Override public boolean visit(ThrowStatement node) { handleException(node); return super.visit(node); } /** * checking if returnStatement is boolean, not null and has only one return * * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.ReturnStatement) */ @Override public boolean visit(ReturnStatement node) { // one more return statement encountered. returnCount++; // examine what is being returned. ASTNode expression = node.getExpression(); // if there is a return statement, it must return a boolean literal. if (expression == null || !(expression instanceof BooleanLiteral)) { this.encounteredInvalidReturnStatement = true; } return super.visit(node); } public boolean containsBreak() { return this.encounteredBreakStatement; } public boolean containsContinue() { return encounteredContinueStatement; } public boolean containsInvalidReturn() { return encounteredInvalidReturnStatement; } public boolean containsMultipleReturn() { return returnCount > 1; } public boolean containsException() { return encounteredThrownCheckedException; } public boolean containsNEFS() { return encounteredNonEffectivelyFinalVars; } }
package org.innovateuk.ifs.application.transactional; import lombok.extern.slf4j.Slf4j; import org.innovateuk.ifs.activitylog.domain.ActivityLog; import org.innovateuk.ifs.activitylog.repository.ActivityLogRepository; import org.innovateuk.ifs.application.domain.*; import org.innovateuk.ifs.application.repository.*; import org.innovateuk.ifs.assessment.repository.AssessmentRepository; import org.innovateuk.ifs.assessment.repository.AverageAssessorScoreRepository; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.finance.domain.ApplicationFinance; import org.innovateuk.ifs.finance.domain.ApplicationFinanceRow; import org.innovateuk.ifs.finance.repository.ApplicationFinanceRepository; import org.innovateuk.ifs.finance.repository.ApplicationFinanceRowRepository; import org.innovateuk.ifs.finance.repository.FinanceRowMetaValueRepository; import org.innovateuk.ifs.grant.domain.GrantProcess; import org.innovateuk.ifs.grant.repository.GrantProcessRepository; import org.innovateuk.ifs.granttransfer.repository.EuGrantTransferRepository; import org.innovateuk.ifs.horizon.repository.ApplicationHorizonWorkProgrammeRepository; import org.innovateuk.ifs.interview.repository.InterviewAssignmentRepository; import org.innovateuk.ifs.interview.repository.InterviewRepository; import org.innovateuk.ifs.invite.repository.ApplicationInviteRepository; import org.innovateuk.ifs.invite.repository.ApplicationKtaInviteRepository; import org.innovateuk.ifs.project.core.repository.ProjectRepository; import org.innovateuk.ifs.project.core.repository.ProjectToBeCreatedRepository; import org.innovateuk.ifs.review.repository.ReviewRepository; import org.innovateuk.ifs.supporter.repository.SupporterAssignmentRepository; import org.innovateuk.ifs.user.repository.ProcessRoleRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.ZonedDateTime; import java.util.Optional; import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError; import static org.innovateuk.ifs.util.EntityLookupCallbacks.find; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess; @Slf4j @Service public class ApplicationMigrationServiceImpl implements ApplicationMigrationService { @Autowired private ApplicationMigrationRepository applicationMigrationRepository; @Autowired private ApplicationRepository applicationRepository; @Autowired private ActivityLogRepository activityLogRepository; @Autowired private ApplicationFinanceRepository applicationFinanceRepository; @Autowired private ApplicationFinanceRowRepository applicationFinanceRowRepository; @Autowired private FinanceRowMetaValueRepository financeRowMetaValueRepository; @Autowired private ApplicationHiddenFromDashboardRepository applicationHiddenFromDashboardRepository; @Autowired private ApplicationOrganisationAddressRepository applicationOrganisationAddressRepository; @Autowired private AverageAssessorScoreRepository averageAssessorScoreRepository; @Autowired private EuGrantTransferRepository euGrantTransferRepository; @Autowired private FormInputResponseRepository formInputResponseRepository; @Autowired private ProcessRoleRepository processRoleRepository; @Autowired private ProjectRepository projectRepository; @Autowired private ProjectToBeCreatedRepository projectToBeCreatedRepository; @Autowired private QuestionStatusRepository questionStatusRepository; @Autowired private GrantProcessRepository grantProcessRepository; @Autowired private ApplicationProcessRepository applicationProcessRepository; @Autowired private AssessmentRepository assessmentRepository; @Autowired private InterviewRepository interviewRepository; @Autowired private InterviewAssignmentRepository interviewAssignmentRepository; @Autowired private ReviewRepository reviewRepository; @Autowired private SupporterAssignmentRepository supporterAssignmentRepository; @Autowired private ApplicationInviteRepository applicationInviteRepository; @Autowired private ApplicationKtaInviteRepository applicationKtaInviteRepository; @Autowired private ApplicationHorizonWorkProgrammeRepository applicationHorizonWorkProgrammeRepository; @Autowired private ApplicationExpressionOfInterestConfigRepository applicationExpressionOfInterestConfigRepository; @Autowired private ApplicationEoiEvidenceResponseRepository applicationEoiEvidenceResponseRepository; @Override public ServiceResult<Optional<ApplicationMigration>> findByApplicationIdAndStatus(long applicationId, MigrationStatus status) { return serviceSuccess(applicationMigrationRepository.findByApplicationIdAndStatus(applicationId, status)); } @Override @Transactional public ServiceResult<Void> migrateApplication(long applicationId) { return migrateApplication(applicationId, true) .andOnSuccessReturnVoid(); } @Override @Transactional public ServiceResult<Long> migrateApplication(long applicationId, boolean isDeleteApplication) { return find(applicationRepository.findById(applicationId), notFoundError(Application.class, applicationId)) .andOnSuccess(application -> { Application migratedApplication = migrateApplication(application); migrateApplicationExpressionOfInterestConfig(application, migratedApplication); migrateApplicationHorizonWorkProgramme(application, migratedApplication); migrateActivityLog(application, migratedApplication); migrateApplicationFinance(application, migratedApplication); migrateApplicationHiddenFromDashboard(application, migratedApplication); migrateApplicationOrganisationAddress(application, migratedApplication); migrateAverageAssessorScore(application, migratedApplication); migrateEuGrantTransfer(application, migratedApplication); migrateFormInputResponse(application, migratedApplication); migrateProcessRole(application, migratedApplication); migrateProject(application, migratedApplication); migrateProjectToBeCreated(application, migratedApplication); migrateQuestionStatus(application, migratedApplication); migrateGrantProcess(application, migratedApplication); migrateApplicationProcess(application, migratedApplication); migrateAssessmentProcess(application, migratedApplication); migrateInterviewProcess(application, migratedApplication); migrateInterviewAssignmentProcess(application, migratedApplication); migrateReviewProcess(application, migratedApplication); migrateSupporterAssignment(application, migratedApplication); migrateApplicationInvite(application, migratedApplication); migrateApplicationKtaInvite(application, migratedApplication); migrateApplicationEoiEvidence(application, migratedApplication); deleteApplicationDependency(application); if (isDeleteApplication) { deleteApplication(application); } return serviceSuccess(migratedApplication.getId()); }); } private void deleteApplication(Application application) { applicationRepository.delete(application); log.debug("Deleted application : " + application.getId()); } private void deleteApplicationDependency(Application application) { activityLogRepository.deleteByApplicationId(application.getId()); grantProcessRepository.deleteByApplicationId(application.getId()); applicationHiddenFromDashboardRepository.deleteByApplicationId(application.getId()); applicationExpressionOfInterestConfigRepository.deleteByApplicationId(application.getId()); log.debug("Deleted application dependency for application : " + application.getId()); } private void migrateApplicationEoiEvidence(Application application, Application migratedApplication) { applicationEoiEvidenceResponseRepository.findOneByApplicationId(application.getId()).ifPresent( applicationEoiEvidence -> { applicationEoiEvidence.setApplication(migratedApplication); applicationEoiEvidenceResponseRepository.save(applicationEoiEvidence); } ); log.debug("Migrated application eoi evidence for application : " + application.getId()); } private void migrateApplicationKtaInvite(Application application, Application migratedApplication) { applicationKtaInviteRepository.findByApplicationId(application.getId()).ifPresent( applicationKtaInvite -> { applicationKtaInvite.setTarget(migratedApplication); applicationKtaInviteRepository.save(applicationKtaInvite); } ); log.debug("Migrated application kta invite for application : " + application.getId()); } private void migrateApplicationInvite(Application application, Application migratedApplication) { applicationInviteRepository.findByApplicationId(application.getId()).stream() .forEach(applicationInvite -> { applicationInvite.setTarget(migratedApplication); applicationInviteRepository.save(applicationInvite); }); log.debug("Migrated application invite for application : " + application.getId()); } private void migrateSupporterAssignment(Application application, Application migratedApplication) { supporterAssignmentRepository.findByTargetId(application.getId()).stream() .forEach(supporterAssignmentProcess -> { supporterAssignmentProcess.setTarget(migratedApplication); supporterAssignmentRepository.save(supporterAssignmentProcess); }); log.debug("Migrated supporter assignment process for application : " + application.getId()); } private void migrateReviewProcess(Application application, Application migratedApplication) { reviewRepository.findByTargetId(application.getId()).stream() .forEach(reviewProcess -> { reviewProcess.setTarget(migratedApplication); reviewRepository.save(reviewProcess); }); log.debug("Migrated review process for application : " + application.getId()); } private void migrateInterviewAssignmentProcess(Application application, Application migratedApplication) { interviewAssignmentRepository.findByTargetId(application.getId()).stream() .forEach(interviewAssignmentProcess -> { interviewAssignmentProcess.setTarget(migratedApplication); interviewAssignmentRepository.save(interviewAssignmentProcess); }); log.debug("Migrated interview assignment process for application : " + application.getId()); } private void migrateInterviewProcess(Application application, Application migratedApplication) { interviewRepository.findByTargetId(application.getId()).stream() .forEach(interviewProcess -> { interviewProcess.setTarget(migratedApplication); interviewRepository.save(interviewProcess); }); log.debug("Migrated interview process for application : " + application.getId()); } private void migrateAssessmentProcess(Application application, Application migratedApplication) { assessmentRepository.findByTargetId(application.getId()).stream() .forEach(assessmentProcess -> { assessmentProcess.setTarget(migratedApplication); assessmentRepository.save(assessmentProcess); }); log.debug("Migrated assessment process for application : " + application.getId()); } private void migrateApplicationProcess(Application application, Application migratedApplication) { applicationProcessRepository.findByTargetId(application.getId()).stream() .forEach(applicationProcess -> { applicationProcess.setTarget(migratedApplication); applicationProcessRepository.save(applicationProcess); }); log.debug("Migrated application process for application : " + application.getId()); } private void migrateGrantProcess(Application application, Application migratedApplication) { serviceSuccess(grantProcessRepository.findOneByApplicationId(application.getId())) .andOnSuccessReturnVoid(grantProcess -> { if (grantProcess != null) { GrantProcess migratedGrantProcess = new GrantProcess(migratedApplication.getId(), grantProcess.isPending()); migratedGrantProcess.setMessage(grantProcess.getMessage()); migratedGrantProcess.setLastProcessed(grantProcess.getLastProcessed()); migratedGrantProcess.setSentRequested(grantProcess.getSentRequested()); migratedGrantProcess.setSentSucceeded(grantProcess.getSentSucceeded()); grantProcessRepository.save(migratedGrantProcess); } }); log.debug("Migrated grant process for application : " + application.getId()); } private void migrateQuestionStatus(Application application, Application migratedApplication) { questionStatusRepository.findByApplicationId(application.getId()).stream() .forEach(questionStatus -> { questionStatus.setApplication(migratedApplication); questionStatusRepository.save(questionStatus); }); log.debug("Migrated question status for application : " + application.getId()); } private void migrateProjectToBeCreated(Application application, Application migratedApplication) { projectToBeCreatedRepository.findByApplicationId(application.getId()).ifPresent( projectToBeCreated -> { projectToBeCreated.setApplication(migratedApplication); projectToBeCreatedRepository.save(projectToBeCreated); } ); log.debug("Migrated project to be created for application : " + application.getId()); } private void migrateProject(Application application, Application migratedApplication) { projectRepository.findByApplicationId(application.getId()).ifPresent( project -> { project.setApplication(migratedApplication); projectRepository.save(project); } ); log.debug("Migrated project for application : " + application.getId()); } private void migrateProcessRole(Application application, Application migratedApplication) { processRoleRepository.findByApplicationId(application.getId()).stream() .forEach(processRole -> { processRole.setApplicationId(migratedApplication.getId()); processRoleRepository.save(processRole); }); log.debug("Migrated process role for application : " + application.getId()); } private void migrateFormInputResponse(Application application, Application migratedApplication) { formInputResponseRepository.findByApplicationId(application.getId()).stream() .forEach(formInputResponse -> { formInputResponse.setApplication(migratedApplication); formInputResponseRepository.save(formInputResponse); }); log.debug("Migrated form input response for application : " + application.getId()); } private void migrateEuGrantTransfer(Application application, Application migratedApplication) { serviceSuccess(euGrantTransferRepository.findByApplicationId(application.getId())) .andOnSuccessReturnVoid(euGrantTransfer -> { if (euGrantTransfer != null) { euGrantTransfer.setApplication(migratedApplication); euGrantTransferRepository.save(euGrantTransfer); } }); log.debug("Migrated eu grant transfer for application : " + application.getId()); } private void migrateAverageAssessorScore(Application application, Application migratedApplication) { averageAssessorScoreRepository.findByApplicationId(application.getId()).ifPresent( averageAssessorScore -> { averageAssessorScore.setApplication(migratedApplication); averageAssessorScoreRepository.save(averageAssessorScore); }); log.debug("Migrated average assessor score for application : " + application.getId()); } private void migrateApplicationOrganisationAddress(Application application, Application migratedApplication) { applicationOrganisationAddressRepository.findByApplicationId(application.getId()).stream() .forEach(applicationOrganisationAddress -> { applicationOrganisationAddress.setApplication(migratedApplication); applicationOrganisationAddressRepository.save(applicationOrganisationAddress); }); log.debug("Migrated application organisation address for application : " + application.getId()); } private void migrateApplicationHiddenFromDashboard(Application application, Application migratedApplication) { applicationHiddenFromDashboardRepository.findByApplicationId(application.getId()).stream() .forEach(applicationHiddenFromDashboard -> { ApplicationHiddenFromDashboard migratedApplicationHiddenFromDashboard = new ApplicationHiddenFromDashboard(migratedApplication, applicationHiddenFromDashboard.getUser()); migratedApplicationHiddenFromDashboard.setCreatedOn(applicationHiddenFromDashboard.getCreatedOn()); applicationHiddenFromDashboardRepository.save(migratedApplicationHiddenFromDashboard); }); log.debug("Migrated application hidden from dashboard for application : " + application.getId()); } private void migrateApplicationFinance(Application application, Application migratedApplication) { applicationFinanceRepository.findByApplicationId(application.getId()).stream() .forEach(applicationFinance -> { Long applicationFinanceId = applicationFinance.getId(); applicationFinance.setApplication(migratedApplication); ApplicationFinance migratedApplicationFinance = applicationFinanceRepository.save(applicationFinance); applicationFinanceRowRepository.findByTargetId(applicationFinanceId).stream() .forEach(applicationFinanceRow -> { applicationFinanceRow.setTarget(migratedApplicationFinance); ApplicationFinanceRow savedClonedApplicationFinanceRow = applicationFinanceRowRepository.save(applicationFinanceRow); financeRowMetaValueRepository.financeRowId(applicationFinanceRow.getId()).stream() .forEach(financeRowMetaValue -> { financeRowMetaValue.setFinanceRowId(savedClonedApplicationFinanceRow.getId()); }); }); }); log.debug("Migrated application finance for application : " + application.getId()); } private void migrateActivityLog(Application application, Application migratedApplication) { activityLogRepository.findByApplicationId(application.getId()).stream() .forEach(activityLog -> { ActivityLog migratedActivityLog = new ActivityLog(migratedApplication, activityLog.getType(), activityLog.getOrganisation().orElse(null), activityLog.getCompetitionDocument().orElse(null), activityLog.getQuery().orElse(null), activityLog.getCreatedOn(), activityLog.getCreatedBy(), activityLog.getAuthor()); activityLogRepository.save(migratedActivityLog); }); log.debug("Migrated activity log for application : " + application.getId()); } private void migrateApplicationHorizonWorkProgramme(Application application, Application migratedApplication) { if (migratedApplication.getCompetition().isHorizonEuropeGuarantee()) { applicationHorizonWorkProgrammeRepository.findByApplicationId(application.getId()).stream() .forEach(applicationHorizonWorkProgramme -> { applicationHorizonWorkProgramme.setApplicationId(migratedApplication.getId()); applicationHorizonWorkProgrammeRepository.save(applicationHorizonWorkProgramme); }); log.debug("Migrated Horizon Work Programme for application : " + application.getId()); } } private void migrateApplicationExpressionOfInterestConfig(Application application, Application migratedApplication) { if (application.getApplicationExpressionOfInterestConfig() != null) { Long applicationExpressionOfInterestConfigId = application.getApplicationExpressionOfInterestConfig().getId(); applicationExpressionOfInterestConfigRepository.findById(applicationExpressionOfInterestConfigId).ifPresent( applicationExpressionOfInterestConfig -> { ApplicationExpressionOfInterestConfig migratedApplicationExpressionOfInterestConfig = ApplicationExpressionOfInterestConfig.builder() .application(migratedApplication) .enabledForExpressionOfInterest(applicationExpressionOfInterestConfig.isEnabledForExpressionOfInterest()) .build(); applicationExpressionOfInterestConfigRepository.save(migratedApplicationExpressionOfInterestConfig); migratedApplication.setApplicationExpressionOfInterestConfig(migratedApplicationExpressionOfInterestConfig); }); log.debug("Migrated application expression of interest config for application : " + application.getId()); } } private Application migrateApplication(Application application) { Application migratedApplication = applicationRepository.save(new Application(application)); log.debug("Migrated application : " + application.getId()); return migratedApplication; } @Override @Transactional public ServiceResult<ApplicationMigration> updateApplicationMigrationStatus(ApplicationMigration applicationMigration) { applicationMigration.setUpdatedOn(ZonedDateTime.now()); return serviceSuccess(applicationMigrationRepository.save(applicationMigration)); } }
package org.tweetwallfx.controls.steps; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import javafx.animation.FadeTransition; import javafx.animation.ParallelTransition; import javafx.animation.SequentialTransition; import javafx.animation.Transition; import javafx.geometry.BoundingBox; import javafx.geometry.Bounds; import javafx.geometry.Rectangle2D; import javafx.scene.SnapshotParameters; import javafx.scene.effect.GaussianBlur; import javafx.scene.image.ImageView; import javafx.scene.image.WritableImage; import javafx.scene.text.Text; import javafx.util.Duration; import org.tweetwallfx.controls.Word; import org.tweetwallfx.controls.WordleLayout; import org.tweetwallfx.controls.WordleSkin; import org.tweetwallfx.controls.dataprovider.TagCloudDataProvider; import org.tweetwallfx.stepengine.api.DataProvider; import org.tweetwallfx.stepengine.api.Step; import org.tweetwallfx.stepengine.api.StepEngine.MachineContext; import org.tweetwallfx.stepengine.api.config.AbstractConfig; import org.tweetwallfx.stepengine.api.config.StepEngineSettings; public class FadeInCloudStep implements Step { private final Config config; private FadeInCloudStep(Config config) { this.config = config; } @Override public java.time.Duration preferredStepDuration(final MachineContext context) { return java.time.Duration.ofMillis(config.getStepDuration()); } @Override public boolean shouldSkip(MachineContext context) { List<Word> sortedWords = context.getDataProvider(TagCloudDataProvider.class).getWords(); return sortedWords.isEmpty(); } @Override public void doStep(final MachineContext context) { WordleSkin wordleSkin = (WordleSkin) context.get("WordleSkin"); context.put("cloudConfig", config); List<Word> sortedWords = context.getDataProvider(TagCloudDataProvider.class).getWords(); List<Word> limitedWords = sortedWords.stream().limit(wordleSkin.getDisplayCloudTags()).toList(); List<Word> cutOfflLimitedWords = limitedWords.stream(). sorted(Comparator.reverseOrder()). map(w -> new Word(w.getText().substring(0, Math.min(config.tagLength, w.getText().length())), w.getWeight())).toList(); Bounds layoutBounds = new BoundingBox(1,1, config.width, config.height); WordleLayout.Configuration configuration = new WordleLayout.Configuration(cutOfflLimitedWords, wordleSkin.getFont(), wordleSkin.getFontSizeMax(), layoutBounds); if (null != wordleSkin.getLogo()) { configuration.setBlockedAreaBounds(wordleSkin.getLogo().getBoundsInParent()); } if (null != wordleSkin.getSecondLogo()) { configuration.setBlockedAreaBounds(wordleSkin.getSecondLogo().getBoundsInParent()); } WordleLayout cloudWordleLayout = WordleLayout.createWordleLayout(configuration); Duration defaultDuration = Duration.seconds(1.5); List<Transition> fadeOutTransitions = new ArrayList<>(); List<Transition> moveTransitions = new ArrayList<>(); List<Transition> fadeInTransitions = new ArrayList<>(); SnapshotParameters snapshotParameters = new SnapshotParameters(); snapshotParameters.setViewport(new Rectangle2D( config.layoutX, config.layoutY, config.width, config.height)); WritableImage writableImage = new WritableImage((int)config.width, (int) config.height); wordleSkin.getNode().snapshot(snapshotParameters, writableImage); ImageView snapCopy = new ImageView(writableImage); snapCopy.setLayoutX(config.layoutX); snapCopy.setLayoutY(config.layoutY); snapCopy.setEffect(new GaussianBlur()); snapCopy.setId("blurredCopy"); wordleSkin.getPane().getChildren().add(snapCopy); FadeTransition ftSnapCopy = new FadeTransition(defaultDuration, snapCopy); ftSnapCopy.setToValue(1); fadeInTransitions.add(ftSnapCopy); cloudWordleLayout.getWordLayoutInfo().entrySet().stream().forEach(entry -> { Word word = entry.getKey(); Bounds bounds = entry.getValue(); Text textNode = cloudWordleLayout.createTextNode(word); wordleSkin.word2TextMap.put(word, textNode); textNode.setLayoutX(config.layoutX + bounds.getMinX() + layoutBounds.getWidth() / 2d); textNode.setLayoutY(config.layoutY + bounds.getMinY() + layoutBounds.getHeight() / 2d + Math.abs(bounds.getHeight()) / 2d); textNode.setOpacity(0); wordleSkin.getPane().getChildren().add(textNode); FadeTransition ftTextNode = new FadeTransition(defaultDuration, textNode); ftTextNode.setToValue(1); fadeInTransitions.add(ftTextNode); }); ParallelTransition fadeOuts = new ParallelTransition(); fadeOuts.getChildren().addAll(fadeOutTransitions); ParallelTransition moves = new ParallelTransition(); moves.getChildren().addAll(moveTransitions); ParallelTransition fadeIns = new ParallelTransition(); fadeIns.getChildren().addAll(fadeInTransitions); SequentialTransition morph = new SequentialTransition(fadeOuts, moves, fadeIns); morph.setOnFinished(e -> context.proceed()); morph.play(); } /** * Implementation of {@link Step.Factory} as Service implementation creating * {@link FadeInCloudStep}. */ public static final class FactoryImpl implements Step.Factory { @Override public FadeInCloudStep create(final StepEngineSettings.StepDefinition stepDefinition) { return new FadeInCloudStep(stepDefinition.getConfig(Config.class)); } @Override public Class<FadeInCloudStep> getStepClass() { return FadeInCloudStep.class; } @Override public Collection<Class<? extends DataProvider>> getRequiredDataProviders(final StepEngineSettings.StepDefinition stepSettings) { return Arrays.asList(TagCloudDataProvider.class); } } private static class Config extends AbstractConfig { public double layoutX = 0; public double layoutY = 0; public double width = 0; public double height = 0; public int tagLength = 15; } }
package org.eclipse.persistence.internal.jpa.metadata.queries; import javax.persistence.ParameterMode; import org.eclipse.persistence.annotations.Direction; import org.eclipse.persistence.internal.helper.DatabaseField; import org.eclipse.persistence.internal.jpa.metadata.ORMetadata; import org.eclipse.persistence.internal.jpa.metadata.accessors.MetadataAccessor; import org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataAccessibleObject; import org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataAnnotation; import org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataClass; import org.eclipse.persistence.internal.jpa.metadata.xml.XMLEntityMappings; import org.eclipse.persistence.queries.StoredFunctionCall; import org.eclipse.persistence.queries.StoredProcedureCall; /** * INTERNAL: * Object to hold onto a stored procedure parameter metadata. * * Key notes: * - any metadata mapped from XML to this class must be compared in the * equals method. * - all metadata mapped from XML should be initialized in the initXMLObject * method. * - when loading from annotations, the constructor accepts the metadata * accessor this metadata was loaded from. Used it to look up any * 'companion' annotation needed for processing. * - methods should be preserved in alphabetical order. * * @author Guy Pelletier * @since TopLink 11g */ public class StoredProcedureParameterMetadata extends ORMetadata { private Boolean m_optional; private Integer m_jdbcType; private MetadataClass m_type; private String m_direction; private String m_mode; private String m_jdbcTypeName; private String m_name; private String m_queryParameter; private String m_typeName; /** * INTERNAL: * Used for XML loading. */ public StoredProcedureParameterMetadata() { super("<stored-procedure-parameter>"); } /** * INTERNAL: * Used for annotation loading. */ public StoredProcedureParameterMetadata(MetadataAnnotation storedProcedureParameter, MetadataAccessor accessor) { super(storedProcedureParameter, accessor); m_direction = (String) storedProcedureParameter.getAttribute("direction"); m_mode = (String) storedProcedureParameter.getAttribute("mode"); m_name = (String) storedProcedureParameter.getAttribute("name"); m_queryParameter = (String) storedProcedureParameter.getAttribute("queryParameter"); m_type = getMetadataClass((String) storedProcedureParameter.getAttributeClass("type")); m_jdbcType = (Integer) storedProcedureParameter.getAttribute("jdbcType"); m_jdbcTypeName = (String) storedProcedureParameter.getAttribute("jdbcTypeName"); m_optional = (Boolean) storedProcedureParameter.getAttribute("optional"); } /** * INTERNAL: */ @Override public boolean equals(Object objectToCompare) { if (objectToCompare instanceof StoredProcedureParameterMetadata) { StoredProcedureParameterMetadata parameter = (StoredProcedureParameterMetadata) objectToCompare; if (! valuesMatch(m_type, parameter.getType())) { return false; } if (! valuesMatch(m_direction, parameter.getDirection())) { return false; } if (! valuesMatch(m_mode, parameter.getMode())) { return false; } if (! valuesMatch(m_jdbcType, parameter.getJdbcType())) { return false; } if (! valuesMatch(m_jdbcTypeName, parameter.getJdbcTypeName())) { return false; } if (! valuesMatch(m_name, parameter.getName())) { return false; } if (! valuesMatch(m_optional, parameter.getOptional())) { return false; } return valuesMatch(m_queryParameter, parameter.getQueryParameter()); } return false; } /** * INTERNAL: * Used for OX mapping. */ public String getDirection() { return m_direction; } /** * INTERNAL: * Used for OX mapping. */ public Integer getJdbcType() { return m_jdbcType; } /** * INTERNAL: * Used for OX mapping. */ public String getJdbcTypeName() { return m_jdbcTypeName; } /** * INTERNAL: * Used for OX mapping. */ public String getMode() { return m_mode; } /** * INTERNAL: * Used for OX mapping. */ public String getName() { return m_name; } /** * INTERNAL: * Used for OX mapping. */ public Boolean getOptional() { return m_optional; } /** * INTERNAL: * Used for OX mapping. */ public String getQueryParameter() { return m_queryParameter; } /** * INTERNAL: */ public MetadataClass getType() { return m_type; } /** * INTERNAL: * Used for OX mapping. */ public String getTypeName() { return m_typeName; } /** * INTERNAL: */ protected boolean hasJdbcType() { return m_jdbcType != null && m_jdbcType.equals(-1); } /** * INTERNAL: */ protected boolean hasJdbcTypeName() { return m_jdbcTypeName != null && ! m_jdbcTypeName.equals(""); } /** * INTERNAL: */ protected boolean hasType() { return !m_type.isVoid(); } /** * INTERNAL: */ @Override public void initXMLObject(MetadataAccessibleObject accessibleObject, XMLEntityMappings entityMappings) { super.initXMLObject(accessibleObject, entityMappings); m_type = initXMLClassName(m_typeName); } /** * INTERNAL: */ public boolean isOutParameter() { String parameterMode = (m_direction == null) ? m_mode : m_direction; return parameterMode != null && ( parameterMode.equals(ParameterMode.OUT.name()) || parameterMode.equals(ParameterMode.INOUT.name()) || parameterMode.equals(ParameterMode.REF_CURSOR.name()) || parameterMode.equals(Direction.OUT_CURSOR.name())); } /** * INTERNAL: */ private boolean process(StoredProcedureCall call, int index) { boolean shouldCallByIndex = false; // Process the procedure parameter name, defaults to the argument field name. if (m_name == null || m_name.equals("")) { if (m_queryParameter == null || m_queryParameter.equals("")) { // JPA 2.1 make the query parameter positional shouldCallByIndex = true; m_queryParameter = String.valueOf(index); } else { // EclipseLink support, a query parameter is required to be specified. // TODO: Log a message when defaulting. m_name = m_queryParameter; } } // There is no such thing as queryParameter in JPA's version. if (m_queryParameter == null || m_queryParameter.equals("")) { m_queryParameter = m_name; } if ((m_optional != null) && m_optional) { call.addOptionalArgument(m_queryParameter); } if (m_mode == null) { if (m_direction == null) { // TODO: Log a defaulting message if parameterMode is null. m_mode = ParameterMode.IN.name(); } else { m_mode = m_direction; } } return shouldCallByIndex; } /** * INTERNAL: */ public void processArgument(StoredProcedureCall call, boolean callByIndex, int index) { boolean shouldCallByIndex = process(call, index); if (! callByIndex) { callByIndex = shouldCallByIndex; } if (m_mode.equals(ParameterMode.IN.name())) { if (hasType()) { if (callByIndex) { call.addUnamedArgument(m_queryParameter, getJavaClass(m_type)); } else { call.addNamedArgument(m_name, m_queryParameter, getJavaClass(m_type)); } } else if (hasJdbcType() && hasJdbcTypeName()) { if (callByIndex) { call.addUnamedArgument(m_queryParameter, m_jdbcType, m_jdbcTypeName); } else { call.addNamedArgument(m_name, m_queryParameter, m_jdbcType, m_jdbcTypeName); } } else if (hasJdbcType()) { if (callByIndex) { call.addUnamedArgument(m_queryParameter, m_jdbcType); } else { call.addNamedArgument(m_name, m_queryParameter, m_jdbcType); } } else { if (callByIndex) { call.addUnamedArgument(m_queryParameter); } else { call.addNamedArgument(m_name, m_queryParameter); } } } else if (m_mode.equals(ParameterMode.OUT.name())) { if (hasType()) { if (callByIndex) { call.addUnamedOutputArgument(m_queryParameter, getJavaClass(m_type)); } else { call.addNamedOutputArgument(m_name, m_queryParameter, getJavaClass(m_type)); } } else if (hasJdbcType() && hasJdbcTypeName()) { if (callByIndex) { call.addUnamedOutputArgument(m_queryParameter, m_jdbcType, m_jdbcTypeName); } else { call.addNamedOutputArgument(m_name, m_queryParameter, m_jdbcType, m_jdbcTypeName); } } else if (hasJdbcType()) { if (callByIndex) { call.addUnamedOutputArgument(m_queryParameter, m_jdbcType); } else { call.addNamedOutputArgument(m_name, m_queryParameter, m_jdbcType); } } else { if (callByIndex) { call.addUnamedOutputArgument(m_queryParameter); } else { call.addNamedOutputArgument(m_name, m_queryParameter); } } //set the project level settings on the argument's database fields setDatabaseFieldSettings((DatabaseField)call.getParameters().get(call.getParameters().size() - 1)); } else if (m_mode.equals(Direction.IN_OUT.name()) || m_mode.equals(ParameterMode.INOUT.name())) { if (hasType()) { if (callByIndex) { call.addUnamedInOutputArgument(m_queryParameter, m_queryParameter, getJavaClass(m_type)); } else { call.addNamedInOutputArgument(m_name, m_queryParameter, m_queryParameter, getJavaClass(m_type)); } } else if (hasJdbcType() && hasJdbcTypeName()) { if (callByIndex) { call.addUnamedInOutputArgument(m_queryParameter, m_queryParameter, m_jdbcType, m_jdbcTypeName); } else { call.addNamedInOutputArgument(m_name, m_queryParameter, m_queryParameter, m_jdbcType, m_jdbcTypeName); } } else if (hasJdbcType()) { if (callByIndex) { call.addUnamedInOutputArgument(m_queryParameter, m_queryParameter, m_jdbcType); } else { call.addNamedInOutputArgument(m_name, m_queryParameter, m_queryParameter, m_jdbcType); } } else { if (callByIndex) { call.addUnamedInOutputArgument(m_queryParameter); } else { call.addNamedInOutputArgument(m_name, m_queryParameter); } } //set the project level settings on the argument's out database field Object[] array = (Object[])call.getParameters().get(call.getParameters().size() - 1); if (array[0] == array[1]){ array[1] = ((DatabaseField)array[1]).clone(); } setDatabaseFieldSettings((DatabaseField) array[1]); } else if (m_mode.equals(Direction.OUT_CURSOR.name()) || m_mode.equals(ParameterMode.REF_CURSOR.name())) { boolean multipleCursors = call.getParameterTypes().contains(call.OUT_CURSOR); if (callByIndex) { call.useUnnamedCursorOutputAsResultSet(); } else { call.useNamedCursorOutputAsResultSet(m_queryParameter); } // There are multiple cursor output parameters, then do not use the // cursor as the result set. This will be set to true in the calls // above so we must do the multiple cursor call before hand. if (multipleCursors) { call.setIsCursorOutputProcedure(false); } } } /** * INTERNAL: */ public void processResult(StoredFunctionCall call, int index) { process(call, index); // Process the function parameter if (hasType()) { call.setResult(m_name, getJavaClass(m_type)); } else if (hasJdbcType() && hasJdbcTypeName()) { call.setResult(m_name, m_jdbcType, m_jdbcTypeName); } else if (hasJdbcType()) { call.setResult(m_name, m_jdbcType); } else { call.setResult(m_name); } } /** * INTERNAL: */ /* * SAVED public void process(StoredProcedureCall call, boolean callByIndex, boolean functionReturn, int index) { // Process the procedure parameter name, defaults to the argument field name. if (m_name == null || m_name.equals("")) { if (m_queryParameter == null || m_queryParameter.equals("")) { // JPA 2.1 make the query parameter positional callByIndex = true; m_queryParameter = String.valueOf(index); } else { // EclipseLink support, a query parameter is required to be specified. // TODO: Log a message when defaulting. m_name = m_queryParameter; } } // There is no such thing as queryParameter in JPA's version. if (m_queryParameter == null || m_queryParameter.equals("")) { m_queryParameter = m_name; } if ((m_optional != null) && m_optional) { call.addOptionalArgument(m_queryParameter); } String parameterMode = (m_direction == null) ? m_mode : m_direction; // Process the parameter mode if (functionReturn) { if (hasType()) { ((StoredFunctionCall)call).setResult(m_name, getJavaClass(m_type)); } else if (hasJdbcType() && hasJdbcTypeName()) { ((StoredFunctionCall)call).setResult(m_name, m_jdbcType, m_jdbcTypeName); } else if (hasJdbcType()) { ((StoredFunctionCall)call).setResult(m_name, m_jdbcType); } else { ((StoredFunctionCall)call).setResult(m_name); } } else if (parameterMode == null || parameterMode.equals(ParameterMode.IN.name())) { // TODO: Log a defaulting message if parameterMode is null. if (hasType()) { if (callByIndex) { call.addUnamedArgument(m_queryParameter, getJavaClass(m_type)); } else { call.addNamedArgument(m_name, m_queryParameter, getJavaClass(m_type)); } } else if (hasJdbcType() && hasJdbcTypeName()) { if (callByIndex) { call.addUnamedArgument(m_queryParameter, m_jdbcType, m_jdbcTypeName); } else { call.addNamedArgument(m_name, m_queryParameter, m_jdbcType, m_jdbcTypeName); } } else if (hasJdbcType()) { if (callByIndex) { call.addUnamedArgument(m_queryParameter, m_jdbcType); } else { call.addNamedArgument(m_name, m_queryParameter, m_jdbcType); } } else { if (callByIndex) { call.addUnamedArgument(m_queryParameter); } else { call.addNamedArgument(m_name, m_queryParameter); } } } else if (parameterMode.equals(ParameterMode.OUT.name())) { if (hasType()) { if (callByIndex) { call.addUnamedOutputArgument(m_queryParameter, getJavaClass(m_type)); } else { call.addNamedOutputArgument(m_name, m_queryParameter, getJavaClass(m_type)); } } else if (hasJdbcType() && hasJdbcTypeName()) { if (callByIndex) { call.addUnamedOutputArgument(m_queryParameter, m_jdbcType, m_jdbcTypeName); } else { call.addNamedOutputArgument(m_name, m_queryParameter, m_jdbcType, m_jdbcTypeName); } } else if (hasJdbcType()) { if (callByIndex) { call.addUnamedOutputArgument(m_queryParameter, m_jdbcType); } else { call.addNamedOutputArgument(m_name, m_queryParameter, m_jdbcType); } } else { if (callByIndex) { call.addUnamedOutputArgument(m_queryParameter); } else { call.addNamedOutputArgument(m_name, m_queryParameter); } } //set the project level settings on the argument's database fields setDatabaseFieldSettings((DatabaseField)call.getParameters().get(call.getParameters().size() - 1)); } else if (parameterMode.equals(Direction.IN_OUT.name()) || parameterMode.equals(ParameterMode.INOUT.name())) { if (hasType()) { if (callByIndex) { call.addUnamedInOutputArgument(m_queryParameter, m_queryParameter, getJavaClass(m_type)); } else { call.addNamedInOutputArgument(m_name, m_queryParameter, m_queryParameter, getJavaClass(m_type)); } } else if (hasJdbcType() && hasJdbcTypeName()) { if (callByIndex) { call.addUnamedInOutputArgument(m_queryParameter, m_queryParameter, m_jdbcType, m_jdbcTypeName); } else { call.addNamedInOutputArgument(m_name, m_queryParameter, m_queryParameter, m_jdbcType, m_jdbcTypeName); } } else if (hasJdbcType()) { if (callByIndex) { call.addUnamedInOutputArgument(m_queryParameter, m_queryParameter, m_jdbcType); } else { call.addNamedInOutputArgument(m_name, m_queryParameter, m_queryParameter, m_jdbcType); } } else { if (callByIndex) { call.addUnamedInOutputArgument(m_queryParameter); } else { call.addNamedInOutputArgument(m_name, m_queryParameter); } } //set the project level settings on the argument's out database field Object[] array = (Object[])call.getParameters().get(call.getParameters().size() - 1); if (array[0] == array[1]){ array[1] = ((DatabaseField)array[1]).clone(); } setDatabaseFieldSettings((DatabaseField) array[1]); } else if (parameterMode.equals(Direction.OUT_CURSOR.name()) || parameterMode.equals(ParameterMode.REF_CURSOR.name())) { boolean multipleCursors = call.getParameterTypes().contains(call.OUT_CURSOR); if (callByIndex) { call.useUnnamedCursorOutputAsResultSet(); } else { call.useNamedCursorOutputAsResultSet(m_queryParameter); } // There are multiple cursor output parameters, then do not use the // cursor as the result set. This will be set to true in the calls // above so we must do the multiple cursor call before hand. if (multipleCursors) { call.setIsCursorOutputProcedure(false); } } } */ /** * INTERNAL: * set the project level settings on the database fields */ protected void setDatabaseFieldSettings(DatabaseField field) { if (getProject().useDelimitedIdentifier()) { field.setUseDelimiters(true); } else if (getProject().getShouldForceFieldNamesToUpperCase() && !field.shouldUseDelimiters()) { field.useUpperCaseForComparisons(true); } } /** * INTERNAL: * Used for OX mapping. */ public void setDirection(String direction) { m_direction = direction; } /** * INTERNAL: * Used for OX mapping. */ public void setJdbcType(Integer jdbcType) { m_jdbcType = jdbcType; } /** * INTERNAL: * Used for OX mapping. */ public void setJdbcTypeName(String jdbcTypeName) { m_jdbcTypeName = jdbcTypeName; } /** * INTERNAL: * Used for OX mapping. */ public void setMode(String mode) { m_mode = mode; } /** * INTERNAL: * Used for OX mapping. */ public void setName(String name) { m_name = name; } /** * INTERNAL: * Used for OX mapping. */ public void setOptional(Boolean optional) { m_optional = optional; } /** * INTERNAL: * Used for OX mapping. */ public void setQueryParameter(String queryParameter) { m_queryParameter = queryParameter; } /** * INTERNAL: */ public void setType(MetadataClass type) { m_type = type; } /** * INTERNAL: * Used for OX mapping. */ public void setTypeName(String typeName) { m_typeName = typeName; } }
package com.verce.forwardmodelling; import java.io.PrintWriter; import java.io.IOException; import java.io.FileInputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.DataOutputStream; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.FileNotFoundException; import java.io.BufferedInputStream; import java.io.File; import java.net.*; import javax.net.ssl.HttpsURLConnection; import java.util.zip.*; import java.util.TimeZone; import java.util.Enumeration; import java.util.ArrayList; import java.util.HashMap; import java.util.Date; import java.util.Hashtable; import java.util.Vector; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.Properties; import java.text.SimpleDateFormat; import java.text.DateFormat; import java.text.Format; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletException; import javax.portlet.ResourceRequest; import javax.portlet.ResourceResponse; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletRequest; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItem; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.repository.model.Folder; import com.liferay.portal.kernel.repository.model.FileEntry; import com.liferay.portal.kernel.upload.UploadPortletRequest; import com.liferay.portal.kernel.util.CharPool; import com.liferay.portal.kernel.util.HttpUtil; import com.liferay.portal.kernel.util.HtmlUtil; import com.liferay.portal.kernel.util.FileUtil; import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.portal.kernel.servlet.ServletResponseUtil; import com.liferay.portal.model.User; import com.liferay.portal.service.ServiceContext; import com.liferay.portal.util.PortalUtil; import com.liferay.portlet.documentlibrary.model.DLFileEntry; import com.liferay.portlet.documentlibrary.model.DLFolderConstants; import com.liferay.portlet.documentlibrary.service.DLFileEntryLocalServiceUtil; import com.liferay.portlet.documentlibrary.service.DLAppServiceUtil; import com.liferay.portlet.documentlibrary.DuplicateFileException; import com.liferay.util.bridges.mvc.MVCPortlet; import hu.sztaki.lpds.pgportal.services.asm.ASMJob; import hu.sztaki.lpds.pgportal.services.asm.ASMService; import hu.sztaki.lpds.pgportal.services.asm.ASMWorkflow; import hu.sztaki.lpds.pgportal.services.asm.beans.ASMRepositoryItemBean; import hu.sztaki.lpds.pgportal.services.asm.beans.WorkflowInstanceBean; import hu.sztaki.lpds.pgportal.services.asm.beans.RunningJobDetailsBean; import hu.sztaki.lpds.pgportal.services.asm.constants.RepositoryItemTypeConstants; import hu.sztaki.lpds.pgportal.services.asm.constants.DownloadTypeConstants; import hu.sztaki.lpds.pgportal.service.base.data.WorkflowData; import hu.sztaki.lpds.pgportal.service.base.PortalCacheService; import hu.sztaki.lpds.dcibridge.client.ResourceConfigurationFace; import hu.sztaki.lpds.information.local.InformationBase; import hu.sztaki.lpds.pgportal.service.workflow.RealWorkflowUtils; import hu.sztaki.lpds.wfs.com.WorkflowConfigErrorBean; import hu.sztaki.lpds.pgportal.services.asm.constants.StatusConstants; import hu.sztaki.lpds.information.com.ServiceType; import hu.sztaki.lpds.wfs.com.RepositoryWorkflowBean; import hu.sztaki.lpds.repository.service.veronica.commons.RepositoryFileUtils; import hu.sztaki.lpds.wfs.inf.PortalWfsClient; import hu.sztaki.lpds.storage.inf.PortalStorageClient; import com.verce.forwardmodelling.Constants; import org.json.*; public class ForwardPortlet extends MVCPortlet{ ASMService asm_service = null; public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws PortletException, IOException { System.out.println(" if(resourceRequest.getResourceID().equals("uploadFile")) uploadFile(resourceRequest, resourceResponse); else if(resourceRequest.getResourceID().equals("submit")) submit(resourceRequest, resourceResponse); else if (resourceRequest.getResourceID().equals("downloadOutput")) downloadOutput(resourceRequest, resourceResponse); else if (resourceRequest.getResourceID().equals("deleteWorkflow")) deleteWorkflow(resourceRequest, resourceResponse); else if (resourceRequest.getResourceID().equals("meshVelocityModelUpload")) meshVelocityModelUpload(resourceRequest, resourceResponse); else if (resourceRequest.getResourceID().equals("downloadMeshDetails")) downloadMeshDetails(resourceRequest, resourceResponse); else if (resourceRequest.getResourceID().equals("downloadVelocityModelDetails")) downloadVelocityModelDetails(resourceRequest, resourceResponse); } public void getWorkflowList(ActionRequest req, ActionResponse res) { try{ asm_service = ASMService.getInstance(); ArrayList<ASMWorkflow> importedWfs = asm_service.getASMWorkflows(req.getRemoteUser()); // ConcurrentHashMap<String, WorkflowData> workflows = PortalCacheService.getInstance().getUser(req.getRemoteUser()).getWorkflows(); String jsWfArray = "{\"list\":["; for(ASMWorkflow wf : importedWfs) { // WorkflowData workflowData = workflows.get(wf.getWorkflowName()); // System.out.println(workflowData.getWorkflowID()); // System.out.println(workflowData.getGraf()); //wf.getWorkflowName() is formated: (submitedName+RandomID)_YYYY-MM-DD-TTTTTT //wfDate is YYYY-MM-DD //wfDate2 is YYYY-MM-DD-TTTTTT (used to sort the results) //wfName is submitedName+RandomID String wfDate = wf.getWorkflowName().substring(wf.getWorkflowName().lastIndexOf("_")+1, wf.getWorkflowName().lastIndexOf("-")); String wfDate2 = wf.getWorkflowName().substring(wf.getWorkflowName().lastIndexOf("_")+1); String wfName = wf.getWorkflowName().substring(0,wf.getWorkflowName().lastIndexOf("_")); String status = wf.getStatusbean().getStatus(); if (!status.equals("ERROR") && !status.equals("FINISHED")) { WorkflowInstanceBean wfIB = asm_service.getDetails(req.getRemoteUser(), wf.getWorkflowName()); if (wfIB == null) { continue; } HashMap<String,String> statuses = new HashMap(); StatusConstants statusConstants = new StatusConstants(); for (RunningJobDetailsBean job : wfIB.getJobs()) { if (job.getInstances().size() <= 0) { statuses.put(job.getName(), "UNKNOWN"); continue; } statuses.put(job.getName(), statusConstants.getStatus(job.getInstances().get(0).getStatus())); } System.out.println(statuses); String computeStatus = statuses.containsKey("COMPUTE") ? statuses.get("COMPUTE") : statuses.containsKey("Job0") ? statuses.get("Job0") : null; String stageOutStatus = statuses.containsKey("STAGEOUT") ? statuses.get("STAGEOUT") : statuses.containsKey("Job1") ? statuses.get("Job1") : null; if (statuses.containsValue("ERROR")) { status = "ERROR"; } else if (computeStatus == null || "UNKNOWN".equals(computeStatus)) { status = "INIT"; } else if ("PENDING".equals(computeStatus) || "INIT".equals(computeStatus)) { status = "PENDING"; } else if ("RUNNING".equals(stageOutStatus)) { status = "STAGE OUT"; } else if ("FINISHED".equals(stageOutStatus)) { status = "FINISHED"; } else if ("RUNNING".equals(computeStatus)) { status = "RUNNING"; } else { // Fallback to overall workflow status System.out.println("FALLBACK to workflow status"); } } jsWfArray += "{\"name\":\""+wfName+"\", \"desc\":\""+wf.getSubmissionText()+"\", \"status\":\""+status+ "\", \"date\":\""+wfDate+"\", \"date2\":\""+wfDate2+"\", \"workflowId\":\""+wf.getWorkflowName()+"\"},"; } jsWfArray.substring(0, jsWfArray.length()-1); jsWfArray +="]}"; HttpServletResponse response = PortalUtil.getHttpServletResponse(res); PrintWriter out = response.getWriter(); out.print(jsWfArray); out.flush(); out.close(); //System.out.println("[ForwardModellingPortlet.getWorkflowList] "+jsWfArray); } catch(Exception e) { e.printStackTrace(); System.out.println("[ForwardModellingPortlet.getWorkflowList] Could not update the workflow list"); } } public void updateWorkflowDescription(ActionRequest req, ActionResponse res) { asm_service = ASMService.getInstance(); String begName = ParamUtil.getString(req, "workflowId"); String newText = ParamUtil.getString(req, "newText"); ArrayList<ASMWorkflow> importedWfs; importedWfs = asm_service.getASMWorkflows(req.getRemoteUser()); for(ASMWorkflow wf : importedWfs) { if(wf.getWorkflowName().startsWith(begName)) { wf.setSubmissionText(newText); System.out.println("[ForwardModellingPortlet.updateWorkflowDescription] Description in workflow "+begName+" has been updated to "+newText+" by user "+req.getRemoteUser()); return; } } System.out.println("[ForwardModellingPortlet.updateWorkflowDescription] Error! Workflow "+begName+" could not be found"); } private void deleteWorkflow(ResourceRequest resourceRequest, ResourceResponse resourceResponse) { String userId = resourceRequest.getRemoteUser(); try{ asm_service = ASMService.getInstance(); String wfId = ParamUtil.getString(resourceRequest, "workflowId"); //String status = asm_service.getStatus(userId, wfId); //if(status.equals("RUNNING")||status.equals("INIT")||status.equals("INIT")) asm_service.abort(userId, wfId); //TODO: fixme! asm_service.DeleteWorkflow(userId, wfId); System.out.println("[ForwardModellingPortlet.delete] workflow "+wfId+" has been deleted by user "+userId); } catch(Exception e) { catchError(e, resourceResponse, "500", "[ForwardModellingPortlet.delete] Exception catched!! User :"+userId); } } private void submit(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws PortletException, IOException { try { asm_service = ASMService.getInstance(); User u = PortalUtil.getUser(resourceRequest); String userSN = u.getScreenName(); String userId = u.getUserId()+""; String solverType = ParamUtil.getString(resourceRequest, "solver"); String[] jsonContentArray = resourceRequest.getParameterValues("jsonObject"); String workflowId = ParamUtil.getString(resourceRequest, "workflowId"); String workflowName = ParamUtil.getString(resourceRequest, "workflowName"); String ownerId = ParamUtil.getString(resourceRequest, "ownerId"); String stationUrl = ParamUtil.getString(resourceRequest, "stationUrl"); String eventUrl = ParamUtil.getString(resourceRequest, "eventUrl"); String[] runIds = resourceRequest.getParameterValues("runId"); String stFileType = ParamUtil.getString(resourceRequest, "stationType"); String jobName = "Job0"; String submitMessage = ParamUtil.getString(resourceRequest, "submitMessage"); String nProc = ParamUtil.getString(resourceRequest, "nProc"); boolean eventDLFile = eventUrl.contains("documents"); boolean stationDLFile = stationUrl.contains("documents"); File stationFile = null; File eventFile = null; String stPublicPath; String evPublicPath; long groupId = PortalUtil.getScopeGroupId(resourceRequest); long repositoryId = DLFolderConstants.getDataRepositoryId(groupId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID); ServiceContext serviceContext = new ServiceContext(); serviceContext.setScopeGroupId(groupId); Format formatter = new SimpleDateFormat("yyyyMMddHHmm"); String portalUrl = PortalUtil.getPortalURL(resourceRequest); String currentURL = PortalUtil.getCurrentURL(resourceRequest); String portal = currentURL.substring(0, currentURL.substring(1).indexOf("/")+1); portalUrl += portal; String portalUrl2 = PortalUtil.getPortalURL(resourceRequest); //System.out.println("[ForwardModellingPortlet.submitSolver] Abans: "+portalUrl2); if(portalUrl2.equals("http: //System.out.println("[ForwardModellingPortlet.submitSolver] Despres (sencer): "+portalUrl2+stationUrl); System.out.println("Try to fetch workflow zip from repository for workflow with ID: " + workflowId); String job0bin = ""; Date job0binModified = new Date(0L); Hashtable hsh = new Hashtable(); ServiceType st = InformationBase.getI().getService("wfs", "portal", hsh, new Vector()); PortalWfsClient wfsClient = (PortalWfsClient) Class.forName(st.getClientObject()).newInstance(); wfsClient.setServiceURL(st.getServiceUrl()); wfsClient.setServiceID(st.getServiceID()); RepositoryWorkflowBean bean = new RepositoryWorkflowBean(); bean.setId(Long.parseLong(workflowId)); bean.setWorkflowType(RepositoryItemTypeConstants.Application); Vector wfList = wfsClient.getRepositoryItems(bean); if (wfList == null) { throw new Exception("Not valid wf list !"); } for (Object wfBeanObject : wfList) { RepositoryWorkflowBean wfBean = (RepositoryWorkflowBean) wfBeanObject; String relativePath = wfBean.getZipRepositoryPath(); String fullPath = new String(RepositoryFileUtils.getInstance().getRepositoryDir() + relativePath); ZipFile zipFile = new ZipFile(fullPath); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); System.out.println(entry.getName()); if (entry.getName().indexOf("Job0/execute.bin") >= 0) { job0bin = inputStreamToString(zipFile.getInputStream(entry)); job0binModified = new Date(entry.getTime()); // System.out.println(job0bin); break; } } zipFile.close(); } if(!stationDLFile) //1a. create StationFile and store it { stationFile = FileUtil.createTempFile(); URL wsUrl = new URL(portalUrl2+stationUrl); FileUtil.write(stationFile, wsUrl.openStream()); String stFileName = "stations_"+runIds[0]; stPublicPath = addFileToDL(stationFile, stFileName, groupId, userSN, Constants.WS_TYPE); stPublicPath = portalUrl + stPublicPath; System.out.println("[ForwardModellingPortlet.submitSolver] Stations file created in the document library by "+userSN+", accessible in: "+stPublicPath); stFileType = Constants.STXML_TYPE; } else //1b. Retrieve StationFile { String[] urlParts = stationUrl.split("/"); long folderId = Long.parseLong(urlParts[urlParts.length - 2]); String stFileName = urlParts[urlParts.length - 1]; FileEntry fileEntry = DLAppServiceUtil.getFileEntry(groupId, folderId, stFileName); stationFile = DLFileEntryLocalServiceUtil.getFile(fileEntry.getUserId(), fileEntry.getFileEntryId(), fileEntry.getVersion(), false); stPublicPath = stationUrl; } if(!eventDLFile) //2a. create EventFile and store it { eventFile = FileUtil.createTempFile(); URL wsUrl = new URL(portalUrl2+eventUrl); FileUtil.write(eventFile, wsUrl.openStream()); String evFileName = "events_"+runIds[0]; evPublicPath = addFileToDL(eventFile, evFileName, groupId, userSN, Constants.WS_TYPE); evPublicPath = portalUrl + evPublicPath; System.out.println("[ForwardModellingPortlet.submitSolver] Events file created in the document library by "+userSN+", accessible in: "+evPublicPath); } else //2b. Retrieve EventFile { String[] urlParts = eventUrl.split("/"); long folderId = Long.parseLong(urlParts[urlParts.length - 2]); String evFileName = urlParts[urlParts.length - 1]; FileEntry fileEntry = DLAppServiceUtil.getFileEntry(groupId, folderId, evFileName); eventFile = DLFileEntryLocalServiceUtil.getFile(fileEntry.getUserId(), fileEntry.getFileEntryId(), fileEntry.getVersion(), false); evPublicPath = eventUrl; } //3. Generate zip file String zipName = runIds[0]+".zip"; createZipFile("temp/"+zipName); File tempZipFile = new File("temp/"+zipName); String zipPublicPath = addFileToDL(tempZipFile, zipName, groupId, userSN, Constants.ZIP_TYPE); zipPublicPath = portalUrl + zipPublicPath; System.out.println("[ForwardModellingPortlet.submitSolver] Zip file created in the document library by "+userSN+", accessible in: "+zipPublicPath); // //4. Generate Mesh/Model zip file // String meshModelZipFileName = runIds[0]+"_meshmodel.zip"; // createMeshModelZipFile("temp/"+meshModelZipFileName, "data/mesh", "data/model"); // File meshModelZipFile = new File("temp/"+meshModelZipFileName); for(int i=0;i<jsonContentArray.length;i++) { String jsonContent = jsonContentArray[i]; //4. Import the workflow String importedWfId = importWorkflow(userId, ownerId, workflowId, runIds[i]); //5. Create the solver file and store it File solverFile = FileUtil.createTempFile(); FileUtil.write(solverFile, jsonContent); String fileName = solverType+"_"+runIds[i]+".json"; String publicPath = addFileToDL(solverFile, fileName, groupId, userSN, Constants.SOLVER_TYPE); publicPath = portalUrl + publicPath; System.out.println("[ForwardModellingPortlet.submitSolver] Solver file created in the document library by "+userSN+", accessible in: "+publicPath); //6. Upload files asm_service.placeUploadedFile(userId, stationFile, importedWfId, jobName, "0"); asm_service.placeUploadedFile(userId, eventFile, importedWfId, jobName, "1"); asm_service.placeUploadedFile(userId, solverFile, importedWfId, jobName, "2"); asm_service.placeUploadedFile(userId, tempZipFile, importedWfId, jobName, "3"); // asm_service.placeUploadedFile(userId, meshModelZipFile, importedWfId, jobName, "4"); //7. Check for credential errors //TODO: we should check just once WorkflowData wfData = PortalCacheService.getInstance().getUser(userId).getWorkflow(importedWfId); ResourceConfigurationFace rc=(ResourceConfigurationFace)InformationBase.getI().getServiceClient("resourceconfigure", "portal"); List resources = rc.get(); Vector<WorkflowConfigErrorBean> errorVector = (Vector<WorkflowConfigErrorBean>)RealWorkflowUtils.getInstance().getWorkflowConfigErrorVector(resources, userId, wfData); if(errorVector!=null && !errorVector.isEmpty()) { for (WorkflowConfigErrorBean er : errorVector) { System.out.println("[ForwardModellingPortlet.submitSolver] Alert '"+er.getErrorID()+"'! userSN: "+userSN+", runId: "+runIds[i]); if(er.getErrorID().contains("noproxy") || er.getErrorID().contains("proxyexpired")) { catchError(null, resourceResponse, "401", "[ForwardModellingPortlet.submitSolver] Credential Error! Submission stoped"); return; } } } //8. Change number of MPI nodes if(solverType.toLowerCase().contains(Constants.SPECFEM_TYPE)) { System.out.println("[ForwardModellingPortlet.submitSolver] Set number of processors to "+nProc+", by "+userSN); asm_service.setJobAttribute(userId, importedWfId, jobName, "gt5.keycount", nProc); } //9. Submit asm_service.submit(userId, importedWfId, submitMessage, "Never"); //10. Add run info in the Provenance Repository updateProvenanceRepository(userSN, runIds[i], submitMessage, workflowName, workflowId, importedWfId, stPublicPath, evPublicPath, publicPath, zipPublicPath, stFileType, job0bin, job0binModified); System.out.println("[ForwardModellingPortlet.submitSolver] Submission finished: "+userSN+", "+runIds[i]+", "+submitMessage+", "+workflowId+", "+importedWfId); } tempZipFile.delete(); } catch (Exception e) { catchError(e, resourceResponse, "500", "[ForwardModellingPortlet.submitSolver] Exception catched!"); } } public void downloadOutput(ResourceRequest resourceRequest, ResourceResponse resourceResponse) { asm_service = ASMService.getInstance(); String userId = resourceRequest.getRemoteUser(); String wfId = ParamUtil.getString(resourceRequest, "workflowId"); resourceResponse.setContentType("application/zip"); resourceResponse.setProperty("Content-Disposition", "attachment; filename=\"logs.zip\""); try{ asm_service.getWorkflowOutputs(userId, wfId, resourceResponse); } catch(Exception e) { System.out.println("[ForwardModellingPortlet.downloadOutput] Exception caught!!"); e.printStackTrace(); // TODO send error to client } } private void meshVelocityModelUpload(ResourceRequest resourceRequest, ResourceResponse resourceResponse) { try { UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(resourceRequest); String meshURL = uploadRequest.getParameter("mesh-link"); if (uploadRequest.getFileName("mesh-file") != null && uploadRequest.getFileName("mesh-file").length() > 0) { meshURL = saveFileUpload(resourceRequest, uploadRequest.getFileAsStream("mesh-file"), uploadRequest.getFileName("mesh-file"), "mesh"); } System.out.println(meshURL); if (meshURL == null || meshURL.equals("")) { resourceResponse.getWriter().write("{ success: false, errors: { \"mesh-file\": \"No mesh file or URL included or included file too large.\" } }"); return; } String velocityModelURL = uploadRequest.getParameter("velocity-model-link"); if (uploadRequest.getFileName("velocity-model-file") != null && uploadRequest.getFileName("velocity-model-file").length() > 0) { velocityModelURL = saveFileUpload(resourceRequest, uploadRequest.getFileAsStream("velocity-model-file"), uploadRequest.getFileName("velocity-model-file"), "velocitymodel"); } System.out.println(velocityModelURL); if (velocityModelURL == null || velocityModelURL.equals("")) { resourceResponse.getWriter().write("{ success: false, errors: { \"velocity-model-file\": \"No velocity model file or URL included or included file too large.\" } }"); return; } String minLat = uploadRequest.getParameter("min_lat"); String maxLat = uploadRequest.getParameter("max_lat"); String minLon = uploadRequest.getParameter("min_lon"); String maxLon = uploadRequest.getParameter("max_lon"); Properties props = new Properties(); props.put("mail.smtp.host", "localhost"); props.put("mail.smtp.port", "25"); Session session = Session.getInstance(props); try { Message message = new MimeMessage(session); message.setFrom(InternetAddress.parse("admin@verce.eu")[0]); // message.setReplyTo(InternetAddress.parse(PortalUtil.getUser(resourceRequest).getDisplayEmailAddress())); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("spinuso@knmi.nl, emanuele.casarotti@ingv.it, federica.magnoni@ingv.it, " + PortalUtil.getUser(resourceRequest).getDisplayEmailAddress())); message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse("jonas.matser@knmi.nl")); message.setSubject("VERCE: Mesh and velocity model submitted"); message.setText( "User " + PortalUtil.getUser(resourceRequest).getScreenName() + " has submitted a new mesh and velocity model for review.\n" + "\n" + "The mesh and velocity model are available at the following links.\n" + "Mesh: " + meshURL + "\n" + "Velocity Model: " + velocityModelURL + "\n" + "\n" + "The bounds for the mesh are:\n" + "Minimum latitude: " + minLat + "\n" + "Maximum latitude: " + maxLat + "\n" + "Minimum longitude: " + minLon + "\n" + "Maximum longitude: " + maxLon + "\n" + "\n" + "The user also added the following note:\n" + HtmlUtil.escape(uploadRequest.getParameter("note")) ); Transport.send(message); } catch (MessagingException e) { throw new RuntimeException(e); } resourceResponse.getWriter().write("{ success: true }"); } catch (Exception e) { System.out.println(e); catchError(e, resourceResponse, "500", e.getMessage()); } } private void uploadFile(ResourceRequest resourceRequest, ResourceResponse resourceResponse) { resourceResponse.setContentType("text/html"); try { UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(resourceRequest); InputStream inputStream = uploadRequest.getFileAsStream("form-file"); if(inputStream == null){ throw new Exception("[ForwardModellingPortlet.uploadFile] ERROR: FileInput \"form-file\" not found in request."); } String name = ParamUtil.getString(uploadRequest, "name"); String filetype = ParamUtil.getString(uploadRequest, "filetype"); String publicPath = saveFileUpload(resourceRequest, inputStream, name, filetype); String successString = " {'success':'true', 'path':'"+publicPath+"'}"; resourceResponse.getWriter().write(successString); } catch (Exception e) { catchError(e, resourceResponse, "500", e.getMessage()); } } private String saveFileUpload(ResourceRequest resourceRequest, InputStream inputStream, String name, String filetype) throws Exception { if(PortalUtil.getUser(resourceRequest)==null) throw new Exception("[ForwardModellingPortlet.uploadFile] No user logged in!"); String userSN = PortalUtil.getUser(resourceRequest).getScreenName(); long groupId = PortalUtil.getScopeGroupId(resourceRequest); File file = FileUtil.createTempFile(inputStream); if (file.length() < 1) { throw new Exception("[ForwardModellingPortlet.uploadFile] Failed!! The file is empty. User: "+userSN); } //try String publicPath = addFileToDL(file, name, groupId, userSN, filetype); String portalUrl = PortalUtil.getPortalURL(resourceRequest); String currentURL = PortalUtil.getCurrentURL(resourceRequest); String portal = currentURL.substring(0, currentURL.substring(1).indexOf("/")+1); portalUrl += portal; publicPath = portalUrl+publicPath; System.out.println("[ForwardModellingPortlet.uploadFile] File created in the document library by user "+userSN+", accessible in: "+publicPath); return publicPath; //catch (Exception e) // System.out.println(e.getStackTrace()); // throw new Exception("[ForwardModellingPortlet.uploadFile] ERROR: The file could not be saved in the DL. User: "+userSN, e); } private String inputStreamToString(InputStream inputStream) throws IOException { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); StringBuilder stringBuilder = new StringBuilder(); char[] buffer = new char[1024]; int charsRead = 0; while ((charsRead = inputStreamReader.read(buffer)) > 0) { stringBuilder.append(buffer, 0, charsRead); }; return stringBuilder.toString(); } private void downloadMeshDetails(ResourceRequest resourceRequest, ResourceResponse resourceResponse) { try { String solverName = ParamUtil.getString(resourceRequest, "solver"); String meshName = ParamUtil.getString(resourceRequest, "meshName"); URL url = new URL("http://localhost:8080/j2ep-1.0/prov/solver/" + solverName); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); if(con.getResponseCode()!=200) { System.out.println("[ForwardModellingPortlet.downloadMeshDetails] Error: " + con.getResponseCode()); return; } String input = inputStreamToString(con.getInputStream()); JSONObject jsonObject = new JSONObject(input); JSONArray meshes = jsonObject.getJSONArray("meshes"); JSONObject mesh = null; for (int ii = 0; ii < meshes.length(); ii++) { mesh = meshes.getJSONObject(ii); if (mesh.getString("name").equals(meshName)) { break; } } if (mesh == null) { System.out.println("[ForwardModellingPortlet.downloadMeshDetails] Error: Mesh " + meshName + " not found for solver " + solverName); return; } String details = mesh.getString("details"); resourceResponse.setContentType("application/text"); resourceResponse.setProperty("Content-Disposition", "attachment; filename=\"mesh-details.txt\""); resourceResponse.getWriter().write(details); } catch (Exception e) { System.out.println("[ForwardModellingPortlet.downloadMeshDetails] Error: " + e.getStackTrace()); } } private void downloadVelocityModelDetails(ResourceRequest resourceRequest, ResourceResponse resourceResponse) { try { String solverName = ParamUtil.getString(resourceRequest, "solver"); String meshName = ParamUtil.getString(resourceRequest, "meshName"); String velocityModelName = ParamUtil.getString(resourceRequest, "velocityModelName"); URL url = new URL("http://localhost:8080/j2ep-1.0/prov/solver/" + solverName); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); if(con.getResponseCode()!=200) System.out.println("[ForwardModellingPortlet.downloadVelocityModelDetails] Error: " + con.getResponseCode()); InputStreamReader inputStreamReader = new InputStreamReader(con.getInputStream()); StringBuilder stringBuilder = new StringBuilder(); char[] buffer = new char[1024]; int charsRead = 0; while ((charsRead = inputStreamReader.read(buffer)) > 0) { stringBuilder.append(buffer, 0, charsRead); }; JSONObject jsonObject = new JSONObject(stringBuilder.toString()); JSONArray meshes = jsonObject.getJSONArray("meshes"); JSONObject mesh = null; for (int ii = 0; ii < meshes.length(); ii++) { mesh = meshes.getJSONObject(ii); if (mesh.getString("name").equals(meshName)) { break; } } if (mesh == null) { System.out.println("[ForwardModellingPortlet.downloadVelocityModelDetails] Error: Mesh " + meshName + " not found for solver " + solverName); return; } JSONArray velocityModels = mesh.getJSONArray("velmod"); JSONObject velocityModel = null; for (int ii = 0; ii < velocityModels.length(); ii++) { velocityModel = velocityModels.getJSONObject(ii); if (velocityModel.getString("name").equals(velocityModelName)) { break; } } if (velocityModel == null) { System.out.println("[ForwardModellingPortlet.downloadVelocityModelDetails] Error: Velocity Model " + velocityModelName + " not found for Mesh " + meshName + " and solver " + solverName); return; } String details = velocityModel.getString("details"); resourceResponse.setContentType("application/text"); resourceResponse.setProperty("Content-Disposition", "attachment; filename=\"velocitymodel-details.txt\""); resourceResponse.getWriter().write(details); } catch (Exception e) { System.out.println("[ForwardModellingPortlet.downloadVelocityModelDetails] Error: " + e.getStackTrace()); } } private String addFileToDL(File file, String name, long groupId, String userSN, String filetype) throws SystemException, PortalException, Exception { long repositoryId = DLFolderConstants.getDataRepositoryId(groupId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID); String sourceFileName = file.getName(); String mimeType = "text/plain"; String description = Constants.DOC_DESC + userSN; String changeLog = "1.0"; ServiceContext serviceContext = new ServiceContext(); serviceContext.setScopeGroupId(groupId); long folderId = getFolderId(repositoryId, userSN, filetype, serviceContext); // Search for unused file number // Don't use recursion because of stack limit (although the algorithm shouldn't run that deep) // Two step algorithm // 1. Find the first n (2^m) that is not in use be an existing file // 2. Do a binary search between 2^(m-1) and 2^m for the first non-existing filename // Define lower and upper bounds for searching int lowerBound = 0; int upperBound = 0; // define midpoint for binary search part int mid = 0; // keep track of if we're search upwards or in binary search boolean up = true; String filename = name; do { try { if (up) { filename = name + (upperBound > 0 ? "_"+upperBound : ""); } else { filename = name + (mid > 0 ? "_"+mid : ""); } // try if file exists DLAppServiceUtil.getFileEntry(repositoryId, folderId, filename); } catch (PortalException e) { // File doesnt Exist if (up) { // lowest n = 2^m found that's not in use // start binary search up = false; continue; } else { // continue binary search in [lowerbound-mid] upperBound = mid; mid = lowerBound + (upperBound - lowerBound) / 2; continue; } } // File exists if (up) { // look at next n = 2^m if it's in use lowerBound = Math.max(upperBound, 1); upperBound = lowerBound * 2; } else { // continue binary search in [mid+1-lowerbound] lowerBound = mid + 1; mid = lowerBound + (upperBound - lowerBound) / 2; } } while (lowerBound != upperBound); // set final filename filename = name + (lowerBound > 0 ? "_"+lowerBound : ""); DLAppServiceUtil.addFileEntry(repositoryId, folderId, sourceFileName, mimeType, filename, description, changeLog, file, serviceContext); System.out.println("[ForwardModellingPortlet.addFileToDL] The file "+filename+" has been created."); return "/documents/" + groupId + "/" + folderId + "/" + HttpUtil.encodeURL(HtmlUtil.unescape(filename)); } /* * get the folderId for the specific user following the directory structure: * root/Forwar Modelling/userSN/station (XML) * if it doesn't exist it is created */ private long getFolderId(long repositoryId, String userSN, String filetype, ServiceContext serviceContext) throws SystemException, PortalException { Folder folder = null; String lastFolderName = ""; if(filetype.equals(Constants.EVENT_TYPE)) lastFolderName = Constants.EVENT_FOLDER_NAME; if(filetype.equals(Constants.STXML_TYPE)) lastFolderName = Constants.STXML_FOLDER_NAME; if(filetype.equals(Constants.STPOINTS_TYPE)) lastFolderName = Constants.STPOINTS_FOLDER_NAME; if(filetype.equals(Constants.SOLVER_TYPE)) lastFolderName = Constants.SOLVER_FOLDER_NAME; if(filetype.equals(Constants.WS_TYPE)) lastFolderName = Constants.WS_FOLDER_NAME; if(lastFolderName.equals("")) lastFolderName = filetype; try{ folder = DLAppServiceUtil.getFolder(repositoryId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, Constants.BASE_FOLDER_NAME); } catch (PortalException pe) { folder = DLAppServiceUtil.addFolder(repositoryId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, Constants.BASE_FOLDER_NAME, Constants.BASE_FOLDER_DESC, serviceContext); } try{ folder = DLAppServiceUtil.getFolder(repositoryId, folder.getFolderId(), userSN); } catch (PortalException pe) { folder = DLAppServiceUtil.addFolder(repositoryId, folder.getFolderId(), userSN, Constants.USER_FOLDER_DESC, serviceContext); } try{ folder = DLAppServiceUtil.getFolder(repositoryId, folder.getFolderId(), lastFolderName); } catch (PortalException pe) { folder = DLAppServiceUtil.addFolder(repositoryId, folder.getFolderId(), lastFolderName, "", serviceContext); } return folder.getFolderId(); } private String getFileAsString(File file) throws FileNotFoundException, IOException{ FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; StringBuffer sb = new StringBuffer(); fis = new FileInputStream(file); bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); while (dis.available() != 0) { sb.append(dis.readLine() + "\n"); } fis.close(); bis.close(); dis.close(); return sb.toString(); } private static final byte[] BUFFER = new byte[4096 * 1024]; private static void copy(InputStream input, OutputStream output) throws IOException { int bytesRead; while ((bytesRead = input.read(BUFFER))!= -1) { output.write(BUFFER, 0, bytesRead); } } private void createZipFile(String fileName) throws IOException { ZipFile zipFile = new ZipFile("data/verce-hpc-pe.zip"); ZipOutputStream append = new ZipOutputStream(new FileOutputStream(fileName)); // copy contents from existing war Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry e = entries.nextElement(); append.putNextEntry(e); if (!e.isDirectory()) { copy(zipFile.getInputStream(e), append); } append.closeEntry(); } // append new content //TODO: get new Files from iraklis WS ZipEntry e = new ZipEntry("newContent"); append.putNextEntry(e); append.write("This a simple example".getBytes()); append.closeEntry(); // close zipFile.close(); append.close(); System.out.println("[ForwardModellingPortlet.createZipFile] File created in the server file system: "+fileName); } private void createMeshModelZipFile(String fileName, String meshFileName, String modelFileName) throws IOException { ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(fileName)); zos.putNextEntry(new ZipEntry("meshfile")); copy(new FileInputStream(meshFileName), zos); zos.closeEntry(); zos.putNextEntry(new ZipEntry("modelfile")); copy(new FileInputStream(modelFileName), zos); zos.closeEntry(); zos.close(); } private void updateProvenanceRepository(String userSN, String runId, String submitMessage, String wfName, String wfId, String asmRunId, String stationUrl, String eventUrl, String solverUrl, String zipUrl, String stationFileType, String job0bin, Date job0binModified) { String runType = "workflow_run"; try{ //TODO: put the url in a properties file URL url = new URL("http://localhost:8080/j2ep-1.0/prov/workflow/insert"); //HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); con.setRequestProperty("Accept", "application/json"); TimeZone tz = TimeZone.getTimeZone("UTC"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ"); df.setTimeZone(tz); String nowAsISO = df.format(new Date()); if(stationFileType.equals(Constants.STPOINTS_TYPE)) stationFileType = Constants.MIMETYPE_PLAIN; if(stationFileType.equals(Constants.STXML_TYPE)) stationFileType = Constants.MIMETYPE_XML; JSONObject params = new JSONObject(); params.put("username", userSN) .put("_id", runId) .put("type", runType) .put("description", submitMessage) .put("workflowName", wfName) .put("workflowId", wfId) .put("system_id", asmRunId) .put("startTime", nowAsISO) .put("job0bin", job0bin) .put("job0binModified", new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ").format(job0binModified)); JSONArray input = new JSONArray(); input.put(new JSONObject().put("mime-type", stationFileType).put("name",Constants.ST_INPUT_NAME).put("url", stationUrl)) .put(new JSONObject().put("mime-type", Constants.MIMETYPE_XML).put("name",Constants.EVENT_INPUT_NAME).put("url", eventUrl)) .put(new JSONObject().put("mime-type", Constants.MIMETYPE_JSON).put("name",Constants.SOLVER_INPUT_NAME).put("url", solverUrl)) .put(new JSONObject().put("mime-type", Constants.MIMETYPE_ZIP).put("name",Constants.ZIP_INPUT_NAME).put("url", zipUrl)); params.put("input", input); // System.out.println("[updateProvenanceRepository] Params: "+params.toString()); String urlParameters = "prov="+URLEncoder.encode(params.toString(), "ISO-8859-1"); con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); if(con.getResponseCode()!=200) System.out.println("[ForwardModellingPortlet.updateProvenanceRepository] Error: " + con.getResponseCode()); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println("[ForwardModellingPortlet.updateProvenanceRepository] User: "+userSN+", Response: "+response.toString()); } catch(Exception e) { // We log the exception but continue the normal flow System.out.println("[ForwardModellingPortlet.updateProvenanceRepository] Exception catched!!"); e.printStackTrace(); } } private String importWorkflow(String userId, String ownerId, String repositoryEntryId, String importedWfName) throws Exception { try { //asm_service = ASMService.getInstance(); String wfName = asm_service.ImportWorkflow(userId, importedWfName, ownerId, RepositoryItemTypeConstants.Application, repositoryEntryId); System.out.println("[ForwardModellingPortlet.importWorkflow] Workflow "+repositoryEntryId+"("+ownerId+") with name "+importedWfName+" imported by user "+userId); return wfName; } catch (Exception e) { System.out.println("[ForwardModellingPortlet.importWorkflow] Exception catched! Could not import workflow "+repositoryEntryId+" from "+ownerId+", with name "+importedWfName); throw e; } } /* * Sends the error through the response. Writes logMessage through the logs * if e is not null prints the stackTrace through the logs */ private void catchError(Exception e, ResourceResponse res, String errorCode, String logMessage) { res.setContentType("text/html"); System.out.println("[ForwardModellingPortlet.catchError] Preparing response..."); try{ res.getWriter().write("{success: false, msg:\""+logMessage+"\"}"); //Submit call expects json success parameter }catch(Exception e2) { System.out.println("[ForwardModellingPortlet.catchError] Could not write in response..."); } res.setProperty(res.HTTP_STATUS_CODE, errorCode); //Ajax call expects status code //res.setProperty("success", "false"); //res.setProperty("msg", logMessage); //PrintWriter out = res.getWriter(); //out.println(failedString); //out.close(); System.out.println(logMessage); if(e!=null) e.printStackTrace(); } }
package io.subutai.core.hubmanager.impl.appscale; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.commons.lang3.StringUtils; import com.google.common.base.Preconditions; import io.subutai.common.command.CommandException; import io.subutai.common.command.CommandResult; import io.subutai.common.command.RequestBuilder; import io.subutai.common.peer.ContainerHost; import io.subutai.common.peer.HostNotFoundException; import io.subutai.common.peer.LocalPeer; import io.subutai.common.peer.ResourceHost; import io.subutai.core.peer.api.PeerManager; import io.subutai.hub.share.dto.AppScaleConfigDto; import static java.lang.String.format; /** * Dirty copy from io.subutai.plugin.appscale.impl.ClusterConfiguration. * Should be refactored. */ public class AppScaleManager { private final Logger log = LoggerFactory.getLogger( getClass() ); private final LocalPeer localPeer; public AppScaleManager( PeerManager peerManager ) { this.localPeer = peerManager.getLocalPeer(); } void installCluster( AppScaleConfigDto config ) { log.debug( "AppScale installation started" ); Preconditions.checkArgument( config != null, "Null config" ); Preconditions.checkArgument( !StringUtils.isEmpty( config.getUserDomain() ), "User domain is null" ); ContainerHost controllerHost = getContainerHost( config.getClusterName() ); execute( controllerHost, Commands.getCreateLogDir() ); appscaleInitCluster( controllerHost, config ); makeCleanUpPreviousInstallation( controllerHost ); runAfterInitCommands( controllerHost, config ); addKeyPairSH( controllerHost ); int envContainersCount = config.getContainerAddresses().size(); createRunSH ( controllerHost, envContainersCount ); String runShell = Commands.getRunShell() + " " + envContainersCount; execute( controllerHost, runShell ); createUpShell ( controllerHost ); runInRH ( controllerHost, config ); execute( controllerHost, "echo '127.0.1.1 appscale-image0' >> /etc/hosts" ); execute( controllerHost, Commands.backUpSSH () ); execute( controllerHost, Commands.backUpAppscale () ); log.debug( "AppScale installation done" ); } private void runInRH ( ContainerHost containerHost, AppScaleConfigDto config ) { String ipAddress = config.getContainerAddresses().get( config.getClusterName() ); try { ResourceHost resourceHostByContainerId = localPeer.getResourceHostByContainerId( containerHost.getId() ); CommandResult resultStr = resourceHostByContainerId .execute ( new RequestBuilder ( "grep vlan /mnt/lib/lxc/" + config.getClusterName() + "/config" ) ); String stdOut = resultStr.getStdOut (); String vlanString = stdOut.substring ( 11, 14 ); resourceHostByContainerId.execute ( new RequestBuilder ( "subutai proxy del " + vlanString + " -d" ) ); resourceHostByContainerId.execute ( new RequestBuilder ( "subutai proxy add " + vlanString + " -d \"*." + config.getUserDomain () + "\" -f /mnt/lib/lxc/" + config.getClusterName() + "/rootfs/etc/nginx/ssl.pem" ) ); resourceHostByContainerId .execute ( new RequestBuilder ( "subutai proxy add " + vlanString + " -h " + ipAddress ) ); } catch ( Exception e ) { log.error( "Error to set proxy settings: ", e ); } } private void createUpShell ( ContainerHost containerHost ) { String a = "#!/usr/bin/expect -f\n" + "set timeout -1\n" + "set num $argv\n" + "spawn /root/appscale-tools/bin/appscale up\n" + "\n" + "for {set i 1} {\"$i\" <= \"$num\"} {incr i} {\n" + "expect \"Enter your desired admin e-mail address:\"\n" + "send -- \"a@a.com\\n\"\n" + "expect \"Enter new password:\"\n" + "send -- \"aaaaaa\\n\"\n" + "expect \"Confirm password:\"\n" + "send -- \"aaaaaa\\n\"\n" + "\n" + "}\n" + "\n" + "expect EOD"; try { containerHost.execute ( new RequestBuilder ( "touch /root/up.sh" ) ); containerHost.execute ( new RequestBuilder ( "echo '" + a + "' > /root/up.sh" ) ); containerHost.execute ( new RequestBuilder ( "chmod +x /root/up.sh" ) ); } catch ( CommandException ex ) { log.error ( "Error on create up shell: " + ex ); } } private void createRunSH( ContainerHost containerHost, int envContainersCount ) { try { containerHost.execute ( new RequestBuilder ( "rm /root/run.sh " ) ); containerHost.execute ( new RequestBuilder ( "touch /root/run.sh" ) ); containerHost.execute ( new RequestBuilder ( "echo '" + returnRunSH( envContainersCount ) + "' > /root/run.sh" ) ); containerHost.execute ( new RequestBuilder ( "chmod +x /root/run.sh" ) ); } catch ( CommandException ex ) { log.error ( "createRunSSH error" + ex ); } } private String returnRunSH ( int envContainersCount ) { String sh = "#!/usr/bin/expect -f\n" + "set timeout -1\n" + "set num $argv\n" + "spawn /root/appscale-tools/bin/appscale up\n" + "\n"; if ( envContainersCount == 1 ) { // This works for environment with one container only. With several containers it fails. sh += "for {set i 1} {\"$i\" <= \"$num\"} {incr i} {\n" + " expect \"Are you sure you want to continue connecting (yes/no)?\"\n" + " send -- \"yes\\n\"\n" + " expect \" password:\"\n" + " send -- \"a\\n\"\n" + "}\n" + "\n"; } sh += "expect \"Enter your desired admin e-mail address:\"\n" + "send -- \"a@a.com\\n\"\n" + "expect \"Enter new password:\"\n" + "send -- \"aaaaaa\\n\"\n" + "expect \"Confirm password:\"\n" + "send -- \"aaaaaa\\n\"\n" + "\n" + "expect EOD"; return sh; } private void addKeyPairSH( ContainerHost containerHost ) { try { String add = "#!/usr/bin/expect -f\n" + "set timeout -1\n" + "set num argv\n" + "spawn /root/appscale-tools/bin/appscale-add-keypair --ips ips.yaml --keyname appscale\n" + "for {set i 1} {\"$i\" <= \"$num\"} {incr i} {\n" + " expect \"Are you sure you want to continue connecting (yes/no)?\"\n" + " send -- \"yes\\n\"\n" + " expect \" password:\"\n" + " send -- \"a\\n\"\n" + "}\n" + "expect EOD"; containerHost.execute( new RequestBuilder ( "mkdir .ssh" ) ); containerHost.execute( new RequestBuilder ( "rm /root/addKey.sh " ) ); containerHost.execute( new RequestBuilder ( "touch /root/addKey.sh" ) ); containerHost.execute( new RequestBuilder ( "echo '" + add + "' > /root/addKey.sh" ) ); containerHost.execute( new RequestBuilder ( "chmod +x /root/addKey.sh" ) ); } catch ( CommandException ex ) { log.error ( ex.toString () ); } } private void runAfterInitCommands( ContainerHost containerHost, AppScaleConfigDto config ) { execute( containerHost, "sed -i 's/{0}:{1}/{1}.{0}/g' /root/appscale/AppDashboard/lib/app_dashboard_data.py" ); execute( containerHost, "echo -e '127.0.0.1 " + config.getUserDomain () + "' >> /etc/hosts" ); execute( containerHost, "sed -i 's/127.0.0.1 localhost.localdomain localhost/127.0.0.1 localhost.localdomain localhost " + config.getUserDomain () + "/g' " + "/root/appscale/AppController/djinn.rb" ); execute( containerHost, "sed -i 's/127.0.0.1 localhost.localdomain localhost/127.0.0.1 localhost.localdomain localhost " + config.getUserDomain () + "/g' " + "/etc/hosts" ); execute( containerHost, "cat /etc/nginx/mykey.pem /etc/nginx/mycert.pem > /etc/nginx/ssl.pem" ); // Modify navigation.html String addButton = "<li align=\"center\" class=\"tab\"><a class=\"btn btn-info\" href=\"{{ flower_url }}\">TaskQueue Monitor<\\/a><\\/li>"; String replaceString = addButton + "<br><li align=\"center\" class=\"tab\"><a class=\"btn btn-info\" href=\"#\" onClick=\"growEnvironment()\">Add Appengine<\\/a><\\/li>"; execute( containerHost, "sed -i 's/ " + addButton + "/" + replaceString + "/g' /root/appscale/AppDashboard/templates/shared/navigation.html" ); String changeMonitURL = "sed -i 's/{{ monit_url }}/http:\\/\\/2812." + config.getUserDomain () + "/g' /root/appscale/AppDashboard/templates/shared/navigation.html"; execute( containerHost, changeMonitURL ); String changeFlowerURL = "sed -i 's/{{ flower_url }}/http:\\/\\/5555." + config.getUserDomain () + "/g' /root/appscale/AppDashboard/templates/shared/navigation.html"; execute( containerHost, changeFlowerURL ); String modUrl = "resturl?"; String modUrlChange = "1443." + config.getUserDomain () + "\\/rest\\/appscale\\/growenvironment?containerName=" + config.getClusterName () + "&"; execute( containerHost, "sed -i 's/" + modUrl + "/" + modUrlChange + "/g' /root/appscale/AppDashboard/templates/shared/navigation.html" ); // Modify ss_agent.py String modstr = "thispathtochange = \"\\/rest\\/appscale\\/growenvironment?clusterName=\\\""; String modstrchange = "thispathtochange = \"\\/rest\\/appscale\\/growenvironment?clusterName=\"" + config.getClusterName (); execute( containerHost, "sed -i 's/" + modstr + "/" + modstrchange + "/g' /root/appscale/InfrastructureManager/agents/ss_agent.py" ); String tokenUrl = "subutai:8443"; String tokenUrlChange = "1443." + config.getUserDomain (); execute( containerHost, "sed -i 's/" + tokenUrl + "/" + tokenUrlChange + "/g' /root/appscale/InfrastructureManager/agents/ss_agent.py" ); // Modify nginx String nginx = "echo 'server {\n" + " listen 80;\n" + " server_name ~^(?<port>.+)\\." + config .getUserDomain () + "$;\n" + "\n" + " set $appbackend \"127.0.0.1:${port}\";\n" + "\n" + " # proxy to AppScale over http\n" + " if ($port = 1443) {\n" + " set $appbackend \"appscaledashboard\";\n" + " }\n" + "\n" + " location / {\n" + " proxy_pass http://$appbackend;\n" + " proxy_set_header X-Real-IP $remote_addr;\n" + " proxy_set_header Host $http_host;\n" + " proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n" + "\n" + " }\n" + "}' > /etc/nginx/sites-enabled/default"; execute( containerHost, nginx ); } private void makeCleanUpPreviousInstallation( ContainerHost containerHost ) { try { CommandResult cr = containerHost.execute ( new RequestBuilder ( "ls /root/.ssh" ) ); if ( !cr.toString ().equals ( "" ) ) {
package org.safehaus.subutai.core.peer.ui.forms; import java.security.KeyStore; import java.util.Iterator; import java.util.List; import java.util.UUID; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.safehaus.subutai.common.environment.Environment; import org.safehaus.subutai.common.peer.ContainerHost; import org.safehaus.subutai.common.peer.Peer; import org.safehaus.subutai.common.peer.PeerException; import org.safehaus.subutai.common.peer.PeerInfo; import org.safehaus.subutai.common.peer.PeerStatus; import org.safehaus.subutai.common.security.crypto.keystore.KeyStoreData; import org.safehaus.subutai.common.security.crypto.keystore.KeyStoreManager; import org.safehaus.subutai.common.settings.ChannelSettings; import org.safehaus.subutai.common.settings.SecuritySettings; import org.safehaus.subutai.common.util.JsonUtil; import org.safehaus.subutai.common.util.RestUtil; import org.safehaus.subutai.core.peer.api.ContainerGroup; import org.safehaus.subutai.core.peer.api.ContainerGroupNotFoundException; import org.safehaus.subutai.core.peer.api.ResourceHost; import org.safehaus.subutai.core.peer.ui.PeerManagerPortalModule; import org.safehaus.subutai.server.ui.component.ConfirmationDialog; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.cxf.jaxrs.ext.form.Form; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.vaadin.annotations.AutoGenerated; import com.vaadin.data.Property; import com.vaadin.ui.AbsoluteLayout; import com.vaadin.ui.Button; import com.vaadin.ui.CustomComponent; import com.vaadin.ui.Label; import com.vaadin.ui.Notification; import com.vaadin.ui.Table; import com.vaadin.ui.TextField; /** * Registration process should be handled in save manner so no middleware attacks occur. In order to get there peers * need to exchange with public keys. This will create ssl layer by encrypting all traffic passing through their * connection. So first initial handshake will be one direction, to pass keys through encrypted channel and register * them in peers' trust stores. These newly saved keys will be used further for safe communication, with bidirectional * authentication. * * * TODO here still exists some issues concerned via registration/reject/approve requests. Some of them must pass through * secure channel such as unregister process. Which already must be in bidirectional auth completed stage. */ public class PeerRegisterForm extends CustomComponent { private static final Logger LOG = LoggerFactory.getLogger( PeerRegisterForm.class.getName() ); private final Gson gson = new GsonBuilder().setPrettyPrinting().create(); @AutoGenerated private AbsoluteLayout mainLayout; @AutoGenerated private Table peersTable; @AutoGenerated private Button showPeersButton; @AutoGenerated private Button registerRequestButton; @AutoGenerated private TextField ipTextField; private PeerManagerPortalModule module; PeerManageActionsComponent.PeerManagerActionsListener listener = new PeerManageActionsComponent.PeerManagerActionsListener() { @Override public void OnPositiveButtonTrigger( final PeerInfo peer, PeerManageActionsComponent.PeerManageUpdateViewListener updateViewListener ) { switch ( peer.getStatus() ) { case REQUESTED: PeerInfo selfPeer = module.getPeerManager().getLocalPeerInfo(); approvePeerRegistration( selfPeer, peer, updateViewListener ); break; case REGISTERED: break; case BLOCKED: break; default: throw new IllegalStateException( peer.getStatus().name(), new Throwable( "Invalid case." ) ); } } @Override public void OnNegativeButtonTrigger( final PeerInfo peer, PeerManageActionsComponent.PeerManageUpdateViewListener updateViewListener ) { PeerInfo selfPeer = module.getPeerManager().getLocalPeerInfo(); switch ( peer.getStatus() ) { case REJECTED: removeMeFromRemote( selfPeer, peer, updateViewListener ); break; case BLOCKED: case BLOCKED_PEER: case REQUESTED: case REQUEST_SENT: rejectPeerRegistration( selfPeer, peer, updateViewListener ); break; case APPROVED: unregisterMeFromRemote( selfPeer, peer, updateViewListener ); break; default: throw new TypeNotPresentException( peer.getStatus().name(), new Throwable( "Invalid case." ) ); } } }; /** * The constructor should first build the main layout, set the composition root and then do any custom * initialization. <p/> The constructor will not be automatically regenerated by the visual editor. */ public PeerRegisterForm( final PeerManagerPortalModule module ) { buildMainLayout(); setCompositionRoot( mainLayout ); this.module = module; showPeersButton.click(); } @AutoGenerated private AbsoluteLayout buildMainLayout() { // common part: create layout mainLayout = new AbsoluteLayout(); mainLayout.setImmediate( false ); mainLayout.setWidth( "100%" ); mainLayout.setHeight( "100%" ); // top-level component properties setWidth( "100.0%" ); setHeight( "100.0%" ); // peerRegisterLayout final AbsoluteLayout peerRegisterLayout = buildAbsoluteLayout(); mainLayout.addComponent( peerRegisterLayout, "top:20.0px;right:0.0px;bottom:-20.0px;left:0.0px;" ); return mainLayout; } @AutoGenerated private AbsoluteLayout buildAbsoluteLayout() { // common part: create layout AbsoluteLayout absoluteLayout = new AbsoluteLayout(); absoluteLayout.setImmediate( false ); absoluteLayout.setWidth( "100.0%" ); absoluteLayout.setHeight( "100.0%" ); // peerRegistration final Label peerRegistration = new Label(); peerRegistration.setImmediate( false ); peerRegistration.setWidth( "-1px" ); peerRegistration.setHeight( "-1px" ); peerRegistration.setValue( "Peer registration" ); absoluteLayout.addComponent( peerRegistration, "top:0.0px;left:20.0px;" ); final Label ip = new Label(); ip.setImmediate( false ); ip.setWidth( "-1px" ); ip.setHeight( "-1px" ); ip.setValue( "IP" ); absoluteLayout.addComponent( ip, "top:36.0px;left:20.0px;" ); // ipTextField ipTextField = new TextField(); ipTextField.setImmediate( false ); ipTextField.setWidth( "-1px" ); ipTextField.setHeight( "-1px" ); ipTextField.setMaxLength( 15 ); absoluteLayout.addComponent( ipTextField, "top:36.0px;left:150.0px;" ); // registerRequestButton registerRequestButton = createRegisterButton(); absoluteLayout.addComponent( registerRequestButton, "top:160.0px;left:20.0px;" ); registerRequestButton = createRegisterButton(); // showPeersButton showPeersButton = createShowPeersButton(); absoluteLayout.addComponent( showPeersButton, "top:234.0px;left:20.0px;" ); // peersTable peersTable = new Table(); peersTable.setCaption( "Peers" ); peersTable.setImmediate( false ); peersTable.setWidth( "1000px" ); peersTable.setHeight( "283px" ); absoluteLayout.addComponent( peersTable, "top:294.0px;left:20.0px;" ); return absoluteLayout; } private Button createShowPeersButton() { showPeersButton = new Button(); showPeersButton.setCaption( "Show peers" ); showPeersButton.setImmediate( false ); showPeersButton.setWidth( "-1px" ); showPeersButton.setHeight( "-1px" ); showPeersButton.addClickListener( new Button.ClickListener() { @Override public void buttonClick( final Button.ClickEvent clickEvent ) { populateData(); peersTable.refreshRowCache(); } } ); return showPeersButton; } private void populateData() { List<PeerInfo> peers = module.getPeerManager().peers(); peersTable.removeAllItems(); peersTable.addContainerProperty( "ID", UUID.class, null ); peersTable.addContainerProperty( "Name", String.class, null ); peersTable.addContainerProperty( "IP", String.class, null ); peersTable.addContainerProperty( "Status", PeerStatus.class, null ); peersTable.addContainerProperty( "ActionsAdvanced", PeerManageActionsComponent.class, null ); for ( final PeerInfo peer : peers ) { if ( peer == null || peer.getStatus() == null ) { continue; } /** * According to peer status perform sufficient action */ //TODO perform different actions on peer response PeerManageActionsComponent component = new PeerManageActionsComponent( module, peer, listener ); peersTable .addItem( new Object[] { peer.getId(), peer.getName(), peer.getIp(), peer.getStatus(), component }, peer.getId() ); } } /** * Send peer to register on remote peer. To construct secure connection. For now initializer peer doesn't send its * px2 (public key requiring bidirectional authentication). * * @param peerToRegister - initializer peer info for registration process * @param ip - target peer ip address */ private void registerMeToRemote( final PeerInfo peerToRegister, final String ip ) { new Thread( new Runnable() { @Override public void run() { String baseUrl = String.format( "https://%s:%s/cxf", ip, ChannelSettings.SECURE_PORT_X1 ); WebClient client = RestUtil.createTrustedWebClient( baseUrl );//WebClient.create( baseUrl ); client.type( MediaType.MULTIPART_FORM_DATA ).accept( MediaType.APPLICATION_JSON ); Form form = new Form(); form.set( "peer", gson.toJson( peerToRegister ) ); try { Response response = client.path( "peer/register" ).form( form ); if ( response.getStatus() == Response.Status.OK.getStatusCode() ) { Notification.show( String.format( "Request sent to %s!", ip ) ); String responseString = response.readEntity( String.class ); LOG.info( response.toString() ); PeerInfo remotePeerInfo = JsonUtil.from( responseString, new TypeToken<PeerInfo>() { }.getType() ); if ( remotePeerInfo != null ) { remotePeerInfo.setStatus( PeerStatus.REQUEST_SENT ); try { module.getPeerManager().register( remotePeerInfo ); } catch ( PeerException e ) { Notification.show( "Couldn't register peer. " + e.getMessage(), Notification.Type.WARNING_MESSAGE ); LOG.error( "Couldn't register peer", e ); } } } else if ( response.getStatus() == Response.Status.CONFLICT.getStatusCode() ) { String reason = response.readEntity( String.class ); Notification.show( reason, Notification.Type.WARNING_MESSAGE ); LOG.warn( reason ); } else { LOG.warn( "Response for registering peer: " + response.toString() ); } } catch ( Exception e ) { Notification.show( "Please check peer address for correctness", Notification.Type.WARNING_MESSAGE ); LOG.error( "error sending request", e ); } } } ).start(); } private void unregisterMeFromRemote( final PeerInfo peerToUnregister, final PeerInfo remotePeerInfo, final PeerManageActionsComponent.PeerManageUpdateViewListener updateViewListener ) { int relationExists = 0; for ( final Iterator<Environment> itEnv = module.getEnvironmentManager().getEnvironments().iterator(); itEnv.hasNext() && relationExists == 0; ) { Environment environment = itEnv.next(); for ( final Iterator<Peer> itPeer = environment.getPeers().iterator(); itPeer.hasNext() && relationExists == 0; ) { Peer peer = itPeer.next(); if ( peer.getPeerInfo().equals( remotePeerInfo ) ) { relationExists = 1; } } } for ( final Iterator<ResourceHost> itResource = module.getPeerManager().getLocalPeer().getResourceHosts().iterator(); itResource.hasNext() && relationExists == 0; ) { ResourceHost resourceHost = itResource.next(); for ( final Iterator<ContainerHost> itContainer = resourceHost.getContainerHosts().iterator(); itContainer.hasNext() && relationExists == 0; ) { ContainerHost containerHost = itContainer.next(); try { ContainerGroup containerGroup = module.getPeerManager().getLocalPeer() .findContainerGroupByContainerId( containerHost.getId() ); if ( containerGroup.getInitiatorPeerId().equals( remotePeerInfo.getId() ) ) { relationExists = 2; } } catch ( ContainerGroupNotFoundException ignore ) { // LOG.debug( "Couldn't get container group by container id", ignore ); } } } if ( relationExists != 0 ) { String msg = ""; switch ( relationExists ) { case 1: msg = "Please destroy all cross peer environments, before you proceed!!!"; break; case 2: msg = "You cannot unregister Peer, because you are a carrier of Peer's resources!!!" + " Contact with Peer to migrate all his data."; break; } ConfirmationDialog alert = new ConfirmationDialog( msg, "Ok", "" ); alert.getOk().addClickListener( new Button.ClickListener() { @Override public void buttonClick( Button.ClickEvent clickEvent ) { // unregisterPeer( peerToUnregister, remotePeerInfo ); } } ); getUI().addWindow( alert.getAlert() ); } else { unregisterPeer( peerToUnregister, remotePeerInfo, updateViewListener ); } } private void unregisterPeer( final PeerInfo peerToUnregister, final PeerInfo remotePeerInfo, final PeerManageActionsComponent.PeerManageUpdateViewListener updateViewListener ) { new Thread( new Runnable() { @Override public void run() { String baseUrl = String.format( "https://%s:%s/cxf", remotePeerInfo.getIp(), ChannelSettings.SECURE_PORT_X2 ); WebClient client = RestUtil.createTrustedWebClientWithAuth( baseUrl, SecuritySettings.KEYSTORE_PX2_ROOT_ALIAS );// WebClient.create( baseUrl ); try { Response response = client.path( "peer/unregister" ).type( MediaType.APPLICATION_JSON ) .accept( MediaType.APPLICATION_JSON ) .query( "peerId", gson.toJson( peerToUnregister.getId().toString() ) ) .delete(); if ( response.getStatus() == Response.Status.OK.getStatusCode() ) { LOG.info( response.toString() ); Notification.show( String.format( "Request sent to %s!", remotePeerInfo.getName() ) ); /** * Peer request rejection intented to be handled before they exchange with keys * * @param peerToUpdateOnRemote - local peer info to update/send to remote peer * @param remotePeer - remote peer whose request was rejected * @param updateViewListener - used to update peers table with relevant buttons captions */ private void rejectPeerRegistration( final PeerInfo peerToUpdateOnRemote, final PeerInfo remotePeer, final PeerManageActionsComponent.PeerManageUpdateViewListener updateViewListener ) { new Thread( new Runnable() { @Override public void run() { String baseUrl = String.format( "https://%s:%s/cxf", remotePeer.getIp(), ChannelSettings.SECURE_PORT_X1 ); WebClient client = RestUtil.createTrustedWebClient( baseUrl );// WebClient.create( baseUrl ); client.type( MediaType.APPLICATION_FORM_URLENCODED ).accept( MediaType.APPLICATION_JSON ); Form form = new Form(); form.set( "rejectedPeerId", peerToUpdateOnRemote.getId().toString() ); try { Response response = client.path( "peer/reject" ).put( form ); if ( response.getStatus() == Response.Status.NO_CONTENT.getStatusCode() ) { LOG.info( "Successfully reject peer request" ); Notification.show( String.format( "Request sent to %s!", remotePeer.getName() ) ); //TODO maybe will implement certificates exchange later on initial request, before peer approves // initializer' request /** * Send peer registration request for further handshakes. * * @return - vaadin button with request initializing click listener */ private Button createRegisterButton() { registerRequestButton = new Button(); registerRequestButton.setCaption( "Register" ); registerRequestButton.setImmediate( true ); registerRequestButton.setWidth( "-1px" ); registerRequestButton.setHeight( "-1px" ); registerRequestButton.addClickListener( new Button.ClickListener() { @Override public void buttonClick( final Button.ClickEvent clickEvent ) { getUI().access( new Runnable() { @Override public void run() { String ip = ipTextField.getValue(); LOG.warn( ip ); PeerInfo selfPeer = module.getPeerManager().getLocalPeerInfo(); registerMeToRemote( selfPeer, ip ); showPeersButton.click(); } } ); } } ); return registerRequestButton; } }
package test.Learning; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.sat4j.specs.TimeoutException; import automata.sfa.SFA; import automata.sfa.SFAInputMove; import automata.sfa.SFAMove; import learning.sfa.Learner; import learning.sfa.Oracle; import learning.sfa.SFAOracle; import learning_symbolic_ce.sfa.SymbolicLearner; import learning_symbolic_ce.sfa.SymbolicOracle; import learning_symbolic_ce.sfa.SinglePathSFAOracle; import theory.BooleanAlgebra; import theory.intervals.UnaryCharIntervalSolver; import theory.characters.CharConstant; import theory.characters.CharPred; import theory.ProductAlgebra; import theory.cartesian.CartesianProduct; import theory.intervals.BoundedIntegerSolver; import theory.intervals.IntPred; import utilities.Pair; public class TestSymbolicCE { @Test public void testSinglePathOracle() throws TimeoutException{ BooleanAlgebra<IntPred, Integer> ba = new BoundedIntegerSolver(0,null); Integer init = 0; List<Integer> fin = Arrays.asList(1); List<SFAMove<IntPred, Integer>> trans = new ArrayList<SFAMove<IntPred, Integer>>(); trans.add(new SFAInputMove<IntPred, Integer>(0, 1, new IntPred(null, null))); trans.add(new SFAInputMove<IntPred, Integer>(1, 1, new IntPred(1, null))); trans.add(new SFAInputMove<IntPred, Integer>(1, 0, new IntPred(null, 0))); SFA<IntPred, Integer> given = SFA.MkSFA(trans, init, fin, ba, false); SymbolicOracle<IntPred, Integer> o = new SinglePathSFAOracle<IntPred, Integer>(given, ba); Integer init2 = 0; List<Integer> fin2 = Arrays.asList(0); List<SFAMove<IntPred, Integer>> trans2 = new ArrayList<SFAMove<IntPred, Integer>>(); trans2.add(new SFAInputMove<IntPred, Integer>(0, 0, new IntPred(null, null))); SFA<IntPred, Integer> hyp = SFA.MkSFA(trans2, init2, fin2, ba, false); List<IntPred> ce = o.checkEquivalence(hyp); assertTrue(ce.equals(new ArrayList<IntPred>())); } @Test public void testSinglePathOracle2() throws TimeoutException{ BooleanAlgebra<IntPred, Integer> ba = new BoundedIntegerSolver(0,null); Integer init = 0; List<Integer> fin = Arrays.asList(0); List<SFAMove<IntPred, Integer>> trans = new ArrayList<SFAMove<IntPred, Integer>>(); trans.add(new SFAInputMove<IntPred, Integer>(0, 1, new IntPred(0, null))); trans.add(new SFAInputMove<IntPred, Integer>(1, 1, new IntPred(2, null))); trans.add(new SFAInputMove<IntPred, Integer>(1, 0, new IntPred(0, 1))); SFA<IntPred, Integer> given = SFA.MkSFA(trans, init, fin, ba, false); SymbolicOracle<IntPred, Integer> o = new SinglePathSFAOracle<IntPred, Integer>(given, ba); Integer init2 = 0; List<Integer> fin2 = Arrays.asList(0); List<SFAMove<IntPred, Integer>> trans2 = new ArrayList<SFAMove<IntPred, Integer>>(); trans2.add(new SFAInputMove<IntPred, Integer>(0, 1, new IntPred(10, null))); trans2.add(new SFAInputMove<IntPred, Integer>(0, 0, new IntPred(0, 9))); trans2.add(new SFAInputMove<IntPred, Integer>(1, 1, new IntPred(0, null))); SFA<IntPred, Integer> hyp = SFA.MkSFA(trans2, init2, fin2, ba, false); hyp = hyp.minimize(ba); List<IntPred> ce = o.checkEquivalence(hyp); assertTrue(ce.equals(Arrays.asList(new IntPred(0,9)))); } @Test public void testLearning1() throws TimeoutException { BooleanAlgebra<IntPred, Integer> ba = new BoundedIntegerSolver(0,null); Integer init = 1; List<Integer> fin = Arrays.asList(2); List<SFAMove<IntPred, Integer>> trans = new ArrayList<SFAMove<IntPred, Integer>>(); trans.add(new SFAInputMove<IntPred, Integer>(1, 2, new IntPred(0, null))); trans.add(new SFAInputMove<IntPred, Integer>(2, 2, new IntPred(10, null))); trans.add(new SFAInputMove<IntPred, Integer>(2, 1, new IntPred(0, 9))); SFA<IntPred, Integer> given = SFA.MkSFA(trans, init, fin, ba, false); SymbolicLearner<IntPred, Integer> ell = new SymbolicLearner<IntPred, Integer>(); SymbolicOracle<IntPred, Integer> o = new SinglePathSFAOracle<IntPred, Integer>(given, ba); SFA<IntPred, Integer> learned = ell.learn(o, ba); assertTrue(SFA.areEquivalent(given, learned, ba)); assertTrue(learned.getStates().size() <= given.getStates().size()); } @Test public void testLearning2() throws TimeoutException { BooleanAlgebra<IntPred, Integer> ba = new BoundedIntegerSolver(0,null); Integer init = 1; List<Integer> fin = Arrays.asList(2); List<SFAMove<IntPred, Integer>> trans = new ArrayList<SFAMove<IntPred, Integer>>(); trans.add(new SFAInputMove<IntPred, Integer>(1, 2, new IntPred(0, 5))); trans.add(new SFAInputMove<IntPred, Integer>(1, 2, new IntPred(6, null))); trans.add(new SFAInputMove<IntPred, Integer>(2, 2, new IntPred(10, null))); trans.add(new SFAInputMove<IntPred, Integer>(2, 1, new IntPred(0, 9))); SFA<IntPred, Integer> given = SFA.MkSFA(trans, init, fin, ba, false); SymbolicLearner<IntPred, Integer> ell = new SymbolicLearner<IntPred, Integer>(); SymbolicOracle<IntPred, Integer> o = new SinglePathSFAOracle<IntPred, Integer>(given, ba); SFA<IntPred, Integer> learned = ell.learn(o, ba); assertTrue(SFA.areEquivalent(given, learned, ba)); assertTrue(learned.getStates().size() <= given.getStates().size()); } /* @Test public void testLearningChar() throws TimeoutException { UnaryCharIntervalSolver ba = new UnaryCharIntervalSolver(); Integer init = 1; List<Integer> fin = Arrays.asList(3); List<SFAMove<CharPred, Character>> trans = new ArrayList<SFAMove<CharPred, Character>>(); trans.add(new SFAInputMove<CharPred, Character>(1, 2, new CharPred('a'))); trans.add(new SFAInputMove<CharPred, Character>(2, 3, new CharPred('b'))); trans.add(new SFAInputMove<CharPred, Character>(3, 1, new CharPred('c'))); SFA<CharPred, Character> given = SFA.MkSFA(trans, init, fin, ba, false); SymbolicLearner<CharPred, Character> ell = new SymbolicLearner<CharPred, Character>(); SymbolicOracle<CharPred, Character> o = new SinglePathSFAOracle<CharPred, Character>(given, ba); SFA<CharPred, Character> learned = ell.learn(o, ba); assertTrue(SFA.areEquivalent(given, learned, ba)); assertTrue(learned.getStates().size() <= given.getStates().size()); }*/ @Test public void testLearning3() throws TimeoutException { BooleanAlgebra<IntPred, Integer> ba = new BoundedIntegerSolver(0,null); Integer init = 1; List<Integer> fin = Arrays.asList(2); List<SFAMove<IntPred, Integer>> trans = new ArrayList<SFAMove<IntPred, Integer>>(); trans.add(new SFAInputMove<IntPred, Integer>(1, 2, new IntPred(0, null))); trans.add(new SFAInputMove<IntPred, Integer>(2, 2, new IntPred(10, null))); trans.add(new SFAInputMove<IntPred, Integer>(2, 1, new IntPred(0, 9))); SFA<IntPred, Integer> given = SFA.MkSFA(trans, init, fin, ba, false); SymbolicLearner<IntPred, Integer> ell = new SymbolicLearner<IntPred, Integer>(); SymbolicOracle<IntPred, Integer> o = new SinglePathSFAOracle<IntPred, Integer>(given, ba); SFA<IntPred, Integer> learned = ell.learn(o, ba); assertTrue(SFA.areEquivalent(given, learned, ba)); assertTrue(learned.getStates().size() <= given.getStates().size()); } @Test public void testPaperExample() throws TimeoutException { BooleanAlgebra<IntPred, Integer> ba = new BoundedIntegerSolver(0,null); Integer init = 1; List<Integer> fin = Arrays.asList(1); List<SFAMove<IntPred, Integer>> trans = new ArrayList<SFAMove<IntPred, Integer>>(); trans.add(new SFAInputMove<IntPred, Integer>(1, 1, new IntPred(0, 50))); trans.add(new SFAInputMove<IntPred, Integer>(1, 1, new IntPred(101, null))); trans.add(new SFAInputMove<IntPred, Integer>(1, 2, new IntPred(51, 100))); trans.add(new SFAInputMove<IntPred, Integer>(2, 3, new IntPred(21, null))); trans.add(new SFAInputMove<IntPred, Integer>(2, 4, new IntPred(0, 20))); trans.add(new SFAInputMove<IntPred, Integer>(3, 3, new IntPred(null, null))); trans.add(new SFAInputMove<IntPred, Integer>(4, 1, new IntPred(null, 20))); trans.add(new SFAInputMove<IntPred, Integer>(4, 3, new IntPred(21, null))); SFA<IntPred, Integer> given = SFA.MkSFA(trans, init, fin, ba, false); SymbolicLearner<IntPred, Integer> ell = new SymbolicLearner<IntPred, Integer>(); SinglePathSFAOracle<IntPred, Integer> o = new SinglePathSFAOracle<IntPred, Integer>(given, ba); SFA<IntPred, Integer> learned = ell.learn(o, ba); assertTrue(SFA.areEquivalent(given, learned, ba)); assertTrue(learned.getStates().size() <= given.getStates().size()); } @Test public void testMMExample() throws TimeoutException { BooleanAlgebra<IntPred, Integer> ba = new BoundedIntegerSolver(0,null); Integer init = 1; List<Integer> fin = Arrays.asList(2, 3); List<SFAMove<IntPred, Integer>> trans = new ArrayList<SFAMove<IntPred, Integer>>(); trans.add(new SFAInputMove<IntPred, Integer>(1, 2, new IntPred(null, 50))); trans.add(new SFAInputMove<IntPred, Integer>(1, 4, new IntPred(51, null))); trans.add(new SFAInputMove<IntPred, Integer>(2, 3, new IntPred(null, 30))); trans.add(new SFAInputMove<IntPred, Integer>(2, 4, new IntPred(31, null))); trans.add(new SFAInputMove<IntPred, Integer>(3, 4, new IntPred(null, null))); trans.add(new SFAInputMove<IntPred, Integer>(4, 1, new IntPred(null, 20))); trans.add(new SFAInputMove<IntPred, Integer>(4, 2, new IntPred(51, 80))); trans.add(new SFAInputMove<IntPred, Integer>(4, 3, new IntPred(21, 50))); trans.add(new SFAInputMove<IntPred, Integer>(4, 4, new IntPred(81, null))); SFA<IntPred, Integer> given = SFA.MkSFA(trans, init, fin, ba, false); Learner<IntPred, Integer> ell = new Learner<IntPred, Integer>(); Oracle<IntPred, Integer> o = new SFAOracle<IntPred, Integer>(given, ba); SFA<IntPred, Integer> learned = ell.learn(o, ba); assertTrue(SFA.areEquivalent(given, learned, ba)); assertTrue(learned.getStates().size() <= given.getStates().size()); } @Test public void testMMPartialOrderExample() throws TimeoutException { BooleanAlgebra<IntPred, Integer> ba = new BoundedIntegerSolver(0, 100); ProductAlgebra<IntPred, Integer, IntPred, Integer> prodmeta = new ProductAlgebra<IntPred, Integer, IntPred, Integer>(ba, ba); Integer init = 1; List<Integer> fin = Arrays.asList(2, 3); List<SFAMove<CartesianProduct<IntPred, IntPred>, Pair<Integer, Integer>>> trans = new ArrayList<SFAMove<CartesianProduct<IntPred, IntPred>, Pair<Integer, Integer>>>(); //transitions out of state 1 CartesianProduct<IntPred, IntPred> temp = new CartesianProduct<>(Arrays.asList( new Pair<>(new IntPred(null,45), new IntPred(null,70)), new Pair<>(new IntPred(null,60), new IntPred(null,50)))); temp.normalize(ba,ba); trans.add(new SFAInputMove<CartesianProduct<IntPred, IntPred>, Pair<Integer, Integer>>(1, 2, temp)); trans.add(new SFAInputMove<CartesianProduct<IntPred, IntPred>, Pair<Integer, Integer>>(1, 4, prodmeta.MkNot(temp))); //transitions out of state 2 temp = new CartesianProduct<>(Arrays.asList( new Pair<>(new IntPred(null,30), new IntPred(null,80)), new Pair<>(new IntPred(null,40), new IntPred(null,40)), new Pair<>(new IntPred(null,80), new IntPred(null,15)))); temp.normalize(ba,ba); trans.add(new SFAInputMove<CartesianProduct<IntPred, IntPred>, Pair<Integer, Integer>>(2, 3, temp)); trans.add(new SFAInputMove<CartesianProduct<IntPred, IntPred>, Pair<Integer, Integer>>(2, 4, prodmeta.MkNot(temp))); //transitions out of state 3 trans.add(new SFAInputMove<CartesianProduct<IntPred, IntPred>, Pair<Integer, Integer>>(3, 4, prodmeta.True())); //transitions out of state 4 temp = new CartesianProduct<>(new IntPred(null,20), new IntPred(null,30)); trans.add(new SFAInputMove<CartesianProduct<IntPred, IntPred>, Pair<Integer, Integer>>(4, 1, temp)); temp = new CartesianProduct<>(Arrays.asList( new Pair<>(new IntPred(null,55), new IntPred(31,50)), new Pair<>(new IntPred(21,70), new IntPred(null,35)))); temp.normalize(ba, ba); trans.add(new SFAInputMove<CartesianProduct<IntPred, IntPred>, Pair<Integer, Integer>>(4, 3, temp)); temp = new CartesianProduct<>(Arrays.asList( new Pair<>(new IntPred(null,60), new IntPred(51,90)), new Pair<>(new IntPred(56,70), new IntPred(36,70)), new Pair<>(new IntPred(71,90), new IntPred(null,50)))); temp.normalize(ba, ba); trans.add(new SFAInputMove<CartesianProduct<IntPred, IntPred>, Pair<Integer, Integer>>(4, 2, temp)); temp = new CartesianProduct<>(Arrays.asList( new Pair<>(new IntPred(null,null), new IntPred(91,null)), new Pair<>(new IntPred(61,null), new IntPred(71,null)), new Pair<>(new IntPred(71,null), new IntPred(51,null)), new Pair<>(new IntPred(91,null), new IntPred(null,null)))); temp.normalize(ba, ba); trans.add(new SFAInputMove<CartesianProduct<IntPred, IntPred>, Pair<Integer, Integer>>(4, 4, temp)); SFA<CartesianProduct<IntPred, IntPred>, Pair<Integer, Integer>> given = SFA.MkSFA(trans, init, fin, prodmeta, false); Learner<CartesianProduct<IntPred, IntPred>, Pair<Integer, Integer>> ell = new Learner<CartesianProduct<IntPred, IntPred>, Pair<Integer, Integer>>(); // test learning using our product algebra meta-separating-predicates Oracle<CartesianProduct<IntPred, IntPred>, Pair<Integer, Integer>> o1 = new SFAOracle<CartesianProduct<IntPred, IntPred>, Pair<Integer, Integer>>(given, prodmeta); SFA<CartesianProduct<IntPred, IntPred>, Pair<Integer, Integer>> learned1 = ell.learn(o1, prodmeta); assertTrue(SFA.areEquivalent(given, learned1, prodmeta)); assertTrue(learned1.getStates().size() <= given.getStates().size()); // test learning using MM-style cones for separating predicates ProductAlgebra<IntPred, Integer, IntPred, Integer> prodcone = new MMConeAlgebra(ba); Oracle<CartesianProduct<IntPred, IntPred>, Pair<Integer, Integer>> o2 = new SFAOracle<CartesianProduct<IntPred, IntPred>, Pair<Integer, Integer>>(given, prodcone); SFA<CartesianProduct<IntPred, IntPred>, Pair<Integer, Integer>> learned2 = ell.learn(o2, prodcone); assertTrue(SFA.areEquivalent(given, learned2, prodmeta)); assertTrue(learned2.getStates().size() <= given.getStates().size()); // for sanity, ensure that these did not give different results assertTrue(SFA.areEquivalent(learned1, learned2, prodmeta)); assertTrue(learned1.getStates().size() == learned2.getStates().size()); } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.net.URL; import javax.swing.*; import javax.swing.text.EditorKit; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.StyleSheet; public final class MainPanel extends JPanel { private MainPanel() { super(new GridLayout(2, 1)); String html = "<html><h2>H2</h2>text<ul><li>list: %s</li></ul></html>"; JEditorPane editor0 = makeEditorPane(); editor0.setText(String.format(html, "Default")); ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL url = cl.getResource("example/bullet.png"); JEditorPane editor1 = makeEditorPane(); EditorKit kit = editor1.getEditorKit(); if (kit instanceof HTMLEditorKit && url != null) { HTMLEditorKit htmlEditorKit = (HTMLEditorKit) kit; StyleSheet styleSheet = htmlEditorKit.getStyleSheet(); styleSheet.addRule(String.format("ul{list-style-image:url(%s);margin:0px 20px;}", url)); // styleSheet.addRule("ul{list-style-type:circle;margin:0px 20px;}"); // styleSheet.addRule("ul{list-style-type:disc;margin:0px 20px;}"); // styleSheet.addRule("ul{list-style-type:square;margin:0px 20px;}"); // styleSheet.addRule("ul{list-style-type:decimal;margin:0px 20px;}"); // Pseudo-element is not supported in javax.swing.text.html.CSS // styleSheet.addRule("ul{list-style-type:none;margin:0px 20px;}"); // styleSheet.addRule("ul li:before{content: "\u00BB";}"); } editor1.setText(String.format(html, "bullet.png")); add(new JScrollPane(editor0)); add(new JScrollPane(editor1)); setPreferredSize(new Dimension(320, 240)); } private static JEditorPane makeEditorPane() { JEditorPane editorPane = new JEditorPane(); editorPane.setContentType("text/html"); editorPane.setEditable(false); return editorPane; } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
package uk.ac.ebi.quickgo.client.service.loader.presets.evidence; import uk.ac.ebi.quickgo.client.service.loader.presets.ff.RawNamedPresetColumnsBuilder; import java.util.Comparator; import java.util.stream.Stream; /** * A specialisation of {@link RawEvidenceNamedPresetColumnsBuilder} used to create * {@link RawEvidenceNamedPresetColumnsImpl} * instances, which capture information about the column indices relating to a {@link RawEvidenceNamedPreset}. * * Created 05/03/18 * @author Tony Wardell */ class RawEvidenceNamedPresetColumnsBuilder extends RawNamedPresetColumnsBuilder { private int goEvidencePosition; private RawEvidenceNamedPresetColumnsBuilder(int namePosition) { super(namePosition); this.goEvidencePosition = UNINITIALIZED_POSITION; } @Override public RawEvidenceNamedPresetColumnsImpl build() { return new RawEvidenceNamedPresetColumnsImpl(this); } public RawEvidenceNamedPresetColumnsBuilder withGoEvidence(int goEvidencePosition) { checkColumnPosition(goEvidencePosition); this.goEvidencePosition = goEvidencePosition; return this; } @Override public RawEvidenceNamedPresetColumnsBuilder withIdPosition(int idPosition) { super.withIdPosition(idPosition); return this; } @Override public RawEvidenceNamedPresetColumnsBuilder withRelevancyPosition(int relevancyPosition) { super.withRelevancyPosition(relevancyPosition); return this; } static RawEvidenceNamedPresetColumnsBuilder createWithNamePosition(int namePosition) { return new RawEvidenceNamedPresetColumnsBuilder(namePosition); } protected static class RawEvidenceNamedPresetColumnsImpl extends RawNamedPresetColumnsImpl { private final int goEvidencePosition; RawEvidenceNamedPresetColumnsImpl(RawEvidenceNamedPresetColumnsBuilder builder) { super(builder); this.goEvidencePosition = builder.goEvidencePosition; } public int getGoEvidencePosition() { return goEvidencePosition; } @Override public int getMaxRequiredColumnCount() { if (maxRequiredColumnPosition == MAX_REQUIRED_COLUMN_POSITION_NOT_INITIALIZED) { maxRequiredColumnPosition = Stream.of( getDescriptionPosition(), getIdPosition(), getNamePosition(), getRelevancyPosition(), getAssociationPosition(), getGoEvidencePosition() ).max(Comparator.naturalOrder()) .map(columnPosition -> columnPosition + 1) .orElse(DEFAULT_COLUMN_POSITION_NOT_INITIALIZED); } return maxRequiredColumnPosition; } } }
package org.carlspring.strongbox.providers.storage; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.NoSuchAlgorithmException; import java.util.List; import javax.annotation.PostConstruct; import org.carlspring.commons.http.range.ByteRange; import org.carlspring.commons.io.reloading.ReloadableInputStreamHandler; import org.carlspring.strongbox.artifact.coordinates.ArtifactCoordinates; import org.carlspring.strongbox.io.RepositoryFileSystem; import org.carlspring.strongbox.io.RepositoryPath; import org.carlspring.strongbox.io.ArtifactInputStream; import org.carlspring.strongbox.io.ArtifactOutputStream; import org.carlspring.strongbox.io.ArtifactPath; import org.carlspring.strongbox.io.FileSystemWrapper; import org.carlspring.strongbox.storage.repository.Repository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * @author carlspring */ @Component("filesystemStorageProvider") public class FileSystemStorageProvider extends AbstractStorageProvider { private static final Logger logger = LoggerFactory.getLogger(FileSystemStorageProvider.class); private static final String ALIAS = "file-system"; @Autowired private StorageProviderRegistry storageProviderRegistry; @Override public String getAlias() { return ALIAS; } @PostConstruct @Override public void register() { storageProviderRegistry.addProvider(getAlias(), this); logger.info("Registered storage provider '" + getClass().getCanonicalName() + "' with alias '" + ALIAS + "'."); } @Override public ArtifactInputStream getInputStreamImplementation(ReloadableInputStreamHandler handler, List<ByteRange> byteRanges) throws IOException, NoSuchAlgorithmException { return new ArtifactInputStream(handler, byteRanges); } @Override public ArtifactInputStream getInputStreamImplementation(ReloadableInputStreamHandler handler, ByteRange byteRange) throws IOException, NoSuchAlgorithmException { return new ArtifactInputStream(handler, byteRange); } @Override public ArtifactInputStream getInputStreamImplementation(InputStream is) throws NoSuchAlgorithmException { return new ArtifactInputStream(is); } @Override public ArtifactOutputStream getOutputStreamImplementation(ArtifactPath artifactPath) throws IOException { OutputStream os = Files.newOutputStream(artifactPath); return new ArtifactOutputStream(os, artifactPath.getCoordinates()); } @Override public OutputStream getOutputStreamImplementation(RepositoryPath repositoryPath, String path) throws IOException { return Files.newOutputStream(repositoryPath.resolve(path)); } @Override public ArtifactInputStream getInputStreamImplementation(ArtifactPath artifactPath) throws IOException, NoSuchAlgorithmException { return new ArtifactInputStream(Files.newInputStream(artifactPath)); } @Override public ArtifactInputStream getInputStreamImplementation(InputStream is, String[] algorithms) throws NoSuchAlgorithmException { return new ArtifactInputStream(is, algorithms); } @Override public ArtifactInputStream getInputStreamImplementation(ArtifactCoordinates coordinates, InputStream is) throws NoSuchAlgorithmException { ArtifactInputStream ais = new ArtifactInputStream(is); ais.setArtifactCoordinates(coordinates); return ais; } @Override public ArtifactPath resolve(Repository repository, ArtifactCoordinates coordinates) throws IOException { Path targetPath = getArtifactPath(repository.getBasedir(), coordinates.toPath()); // Override FileSystem root to Repository base directory; return new ArtifactPath(coordinates, targetPath, getRepositoryFileSystem(repository)); } @Override public RepositoryPath resolve(Repository repository) throws IOException { Path path = Paths.get(repository.getBasedir()); return new RepositoryPath(path, getRepositoryFileSystem(repository)); } private RepositoryFileSystem getRepositoryFileSystem(Repository repository) { FileSystem storageFileSystem = new FileSystemWrapper(Paths.get(repository.getBasedir()).getFileSystem()) { @Override public Path getRootDirectory() { return Paths.get(repository.getBasedir()); } }; RepositoryFileSystem repoFileSystem = new RepositoryFileSystem(repository, storageFileSystem); return repoFileSystem; } private Path getArtifactPath(String basePath, String artifactPath) throws IOException { Path path = Paths.get(basePath).resolve(artifactPath); if (!Files.exists(path)) { Files.createDirectories(path); } return path; } }
package org.cytoscape.view.vizmap.gui.internal.editor.propertyeditor; import java.awt.Color; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.swing.JComboBox; import javax.swing.JList; import javax.swing.plaf.basic.BasicComboBoxRenderer; import org.cytoscape.application.CyApplicationManager; import org.cytoscape.model.CyIdentifiable; import org.cytoscape.model.CyNetwork; import org.cytoscape.model.CyNetworkManager; import org.cytoscape.view.vizmap.gui.editor.ListEditor; import org.cytoscape.view.vizmap.gui.internal.AttributeSet; import org.cytoscape.view.vizmap.gui.internal.AttributeSetManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Tracking the list of columns. By default, three instances of this should be * created (for NODE, EDGE, and NETWORK). * * Export this as an OSGi service! */ public final class AttributeComboBoxPropertyEditor extends CyComboBoxPropertyEditor implements ListEditor { private static final Logger logger = LoggerFactory.getLogger(AttributeComboBoxPropertyEditor.class); private final Class<? extends CyIdentifiable> graphObjectType; private final AttributeSetManager attrManager; private final CyNetworkManager networkManager; private Map<String, Class<?>> currentColumnMap; public AttributeComboBoxPropertyEditor(final Class<? extends CyIdentifiable> type, final AttributeSetManager attrManager, final CyApplicationManager appManager, final CyNetworkManager networkManager) { super(); this.attrManager = attrManager; this.graphObjectType = type; this.networkManager = networkManager; currentColumnMap = new HashMap<String, Class<?>>(); final JComboBox comboBox = (JComboBox) editor; comboBox.setRenderer(new AttributeComboBoxCellRenderer()); comboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { updateComboBox(appManager.getCurrentNetwork()); } }); } @Override public Class<?> getTargetObjectType() { return graphObjectType; } private void updateComboBox(final CyNetwork currentNetwork) { final JComboBox box = (JComboBox) editor; final Object selected = box.getSelectedItem(); box.removeAllItems(); if (currentNetwork == null) return; final AttributeSet compatibleColumns = attrManager.getAttributeSet(currentNetwork, graphObjectType); currentColumnMap = compatibleColumns.getAttrMap(); final AttributeSet targetSet = attrManager.getAttributeSet(currentNetwork, graphObjectType); if (targetSet == null) return; final SortedSet<String> sortedName = new TreeSet<String>(); final Set<CyNetwork> networks = networkManager.getNetworkSet(); for (CyNetwork net : networks) { final AttributeSet currentSet = this.attrManager.getAttributeSet(net, graphObjectType); for (Entry<String, Class<?>> entry: currentSet.getAttrMap().entrySet()) if (columnIsAllowed(entry.getKey(), entry.getValue())) sortedName.add(entry.getKey()); } for (final String attrName : sortedName) box.addItem(attrName); // Add new name if not in the list. box.setSelectedItem(selected); logger.debug(graphObjectType + " Column Name Combobox Updated: New Names = " + targetSet.getAttrMap().keySet()); } private boolean columnIsAllowed(String name, Class<?> type) { if (!Long.class.equals(type) && !List.class.equals(type)) { return true; } return !CyIdentifiable.SUID.equals(name) && !name.endsWith(".SUID"); } private final class AttributeComboBoxCellRenderer extends BasicComboBoxRenderer { private static final long serialVersionUID = 6828337202195089669L; @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value == null) return this; this.setText(value.toString()); if (isSelected) { this.setForeground(Color.RED); this.setBackground(list.getSelectionBackground()); } else { this.setForeground(Color.BLACK); this.setBackground(list.getBackground()); } final Set<String> keys = currentColumnMap.keySet(); String valueString = value.toString(); if (keys != null && keys.contains(valueString) == false) { this.setEnabled(false); this.setFocusable(false); this.setForeground(Color.LIGHT_GRAY); this.setToolTipText("This column does not exist in current network's table."); } else { this.setEnabled(true); this.setFocusable(true); this.setToolTipText("Column Data Type: " + currentColumnMap.get(valueString).getSimpleName()); } return this; } } }
package org.eclipse.birt.report.item.crosstab.internal.ui; import org.eclipse.birt.report.designer.core.DesignerConstants; import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; import org.eclipse.birt.report.designer.internal.ui.dialogs.DataColumnBindingDialog; import org.eclipse.birt.report.designer.internal.ui.dnd.DNDLocation; import org.eclipse.birt.report.designer.internal.ui.dnd.DNDService; import org.eclipse.birt.report.designer.internal.ui.dnd.IDropAdapter; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.ui.newelement.DesignElementFactory; import org.eclipse.birt.report.designer.util.DEUtil; import org.eclipse.birt.report.item.crosstab.core.ICrosstabCellConstants; import org.eclipse.birt.report.item.crosstab.core.de.CrosstabCellHandle; import org.eclipse.birt.report.item.crosstab.internal.ui.editors.editparts.CrosstabCellEditPart; import org.eclipse.birt.report.item.crosstab.internal.ui.editors.model.CrosstabCellAdapter; import org.eclipse.birt.report.item.crosstab.internal.ui.editors.model.ICrosstabCellAdapterFactory; import org.eclipse.birt.report.model.api.CellHandle; import org.eclipse.birt.report.model.api.CommandStack; import org.eclipse.birt.report.model.api.DataItemHandle; import org.eclipse.gef.EditPart; import org.eclipse.gef.commands.Command; import org.eclipse.gef.requests.CreateRequest; import org.eclipse.jface.window.Window; /** * AggregationDropAdapter */ public class AggregationDropAdapter implements IDropAdapter { public int canDrop( Object transfer, Object target, int operation, DNDLocation location ) { if ( transfer.equals( "DATA_AGG" ) //$NON-NLS-1$ && target instanceof CrosstabCellEditPart ) { CrosstabCellAdapter adapter = (CrosstabCellAdapter) ( (CrosstabCellEditPart) target ).getModel( ); if ( adapter.getCrosstabCellHandle( ) != null && DEUtil.isReferenceElement( adapter.getCrosstabCellHandle( ) .getCrosstabHandle( ) ) ) return DNDService.LOGIC_FALSE; String posType = adapter.getPositionType( ); if ( ICrosstabCellAdapterFactory.CELL_MEASURE_AGGREGATION.equals( posType ) || ICrosstabCellAdapterFactory.CELL_MEASURE.equals( posType ) ) { return DNDService.LOGIC_TRUE; } } return DNDService.LOGIC_UNKNOW; } public boolean performDrop( Object transfer, Object target, int operation, DNDLocation location ) { if(target instanceof EditPart) { EditPart editPart = (EditPart)target; CommandStack stack = SessionHandleAdapter.getInstance( ) .getCommandStack( ); stack.startTrans( "Add Aggregation" ); //$NON-NLS-1$ DataItemHandle dataHandle = DesignElementFactory.getInstance( ) .newDataItem( null ); CrosstabCellHandle cellHandle = ( (CrosstabCellAdapter) ( (CrosstabCellEditPart) target ).getModel( ) ).getCrosstabCellHandle( ); try { cellHandle.addContent( dataHandle, CellHandle.CONTENT_SLOT ); DataColumnBindingDialog dialog = new DataColumnBindingDialog( true ); dialog.setInput( dataHandle, null, cellHandle ); dialog.setAggreate( true ); if ( dialog.open( ) == Window.OK ) { CreateRequest request = new CreateRequest( ); request.getExtendedData( ) .put( DesignerConstants.KEY_NEWOBJECT, dataHandle ); request.setLocation( location.getPoint( ) ); Command command = editPart.getCommand( request ); if ( command != null && command.canExecute( ) ) { dataHandle.setResultSetColumn( dialog.getBindingColumn( ) .getName( ) ); editPart.getViewer( ) .getEditDomain( ) .getCommandStack( ) .execute( command ); stack.commit( ); }else { stack.rollback( ); } } else { stack.rollback( ); } } catch ( Exception e ) { stack.rollback( ); ExceptionHandler.handle( e ); } } return true; } // public boolean performDrop( Object transfer, Object target, int operation, // DNDLocation location ) // if(target instanceof EditPart) // EditPart editPart = (EditPart)target; // CommandStack stack = SessionHandleAdapter.getInstance( ) // .getCommandStack( ); // stack.startTrans( "Add Aggregation" ); //$NON-NLS-1$ // DataItemHandle dataHandle = DesignElementFactory.getInstance( ) // .newDataItem( null ); // CrosstabCellHandle cellHandle = ( (CrosstabCellAdapter) ( (CrosstabCellEditPart) target ).getModel( ) ).getCrosstabCellHandle( ); // try // cellHandle.addContent( dataHandle, CellHandle.CONTENT_SLOT ); // DataColumnBindingDialog dialog = new DataColumnBindingDialog( true ); // dialog.setInput( dataHandle, null, cellHandle ); // dialog.setAggreate( true ); // if ( dialog.open( ) == Window.OK ) // cellHandle.getModelHandle( ).getPropertyHandle( ICrosstabCellConstants.CONTENT_PROP ).removeItem( dataHandle ); // CreateRequest request = new CreateRequest( ); // request.getExtendedData( ) // .put( DesignerConstants.KEY_NEWOBJECT, dataHandle ); // request.setLocation( location.getPoint( ) ); // Command command = editPart.getCommand( request ); // if ( command != null && command.canExecute( ) ) // dataHandle.setResultSetColumn( dialog.getBindingColumn( ) // .getName( ) ); // editPart.getViewer( ) // .getEditDomain( ) // .getCommandStack( ) // .execute( command ); // stack.commit( ); // }else // stack.rollback( ); // else // stack.rollback( ); // catch ( Exception e ) // stack.rollback( ); // ExceptionHandler.handle( e ); // return true; }
package org.csstudio.config.ioconfig.editorparts; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Formatter; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.log4j.Logger; import org.csstudio.config.ioconfig.config.view.INodeConfig; import org.csstudio.config.ioconfig.config.view.helper.ConfigHelper; import org.csstudio.config.ioconfig.config.view.helper.DocumentationManageView; import org.csstudio.config.ioconfig.config.view.helper.GSDLabelProvider; import org.csstudio.config.ioconfig.config.view.helper.ShowFileSelectionListener; import org.csstudio.config.ioconfig.editorinputs.NodeEditorInput; import org.csstudio.config.ioconfig.model.AbstractNodeDBO; import org.csstudio.config.ioconfig.model.FacilityDBO; import org.csstudio.config.ioconfig.model.GSDFileTypes; import org.csstudio.config.ioconfig.model.IDocumentable; import org.csstudio.config.ioconfig.model.PersistenceException; import org.csstudio.config.ioconfig.model.Repository; import org.csstudio.config.ioconfig.model.pbmodel.GSDFileDBO; import org.csstudio.config.ioconfig.model.pbmodel.MasterDBO; import org.csstudio.config.ioconfig.model.pbmodel.SlaveDBO; import org.csstudio.config.ioconfig.view.MainView; import org.csstudio.config.ioconfig.view.ProfiBusTreeView; import org.csstudio.platform.logging.CentralLogger; import org.csstudio.platform.security.SecurityFacade; import org.csstudio.platform.security.User; import org.csstudio.platform.ui.util.CustomMediaFactory; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.TableColumnLayout; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Spinner; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.IViewSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.handlers.IHandlerService; import org.eclipse.ui.part.EditorPart; public abstract class AbstractNodeEditor extends EditorPart implements INodeConfig { private static final Logger LOG = CentralLogger.getInstance().getLogger( AbstractNodeEditor.class); private final class CancelSelectionListener implements SelectionListener { public CancelSelectionListener() { // Default Constructor } private void doCancle() { // if (getNode().isPersistent()) { if (!isNew()) { cancel(); DocumentationManageView documentationManageView = getDocumentationManageView(); if (documentationManageView != null) { documentationManageView.cancel(); } setSaveButtonSaved(); } else { AbstractNodeDBO node = getNode(); final boolean openQuestion = MessageDialog.openQuestion( getShell(), "Cancel", "You dispose this " + node.getClass().getSimpleName() + "?"); if (openQuestion) { setSaveButtonSaved(); // hrickens (01.10.2010): Beim Cancel einer neuen Facility // macht nur Perfrom close Sinn. AbstractNodeDBO parent = node.getParent(); if(parent!=null) { parent.removeChild(node); } perfromClose(); } } } @Override public void widgetDefaultSelected(@Nonnull final SelectionEvent e) { doCancle(); } @Override public void widgetSelected(@Nonnull final SelectionEvent e) { doCancle(); } } private final class GSDFileChangeListener implements ISelectionChangedListener { private final Button _fileSelect; /** * Constructor. * * @param fileSelect */ protected GSDFileChangeListener(@Nonnull final Button fileSelect) { _fileSelect = fileSelect; } @Override public void selectionChanged(@Nonnull final SelectionChangedEvent event) { final StructuredSelection selection = (StructuredSelection) event .getSelection(); if (selection == null || selection.isEmpty()) { _fileSelect.setEnabled(false); return; } final GSDFileDBO file = (GSDFileDBO) selection.getFirstElement(); _fileSelect .setEnabled(getNode().needGSDFile() == GSDFileTypes.Master == file .isMasterNonHN()); } } private final class GSDFileRemoveListener implements SelectionListener { private final TableViewer _tableViewer; /** * Constructor. * * @param tableViewer */ protected GSDFileRemoveListener(@Nonnull final TableViewer tableViewer) { _tableViewer = tableViewer; } @Override public void widgetDefaultSelected(@Nonnull final SelectionEvent e) { // TODO: } @Override public void widgetSelected(@Nonnull final SelectionEvent e) { final StructuredSelection selection = (StructuredSelection) _tableViewer.getSelection(); final GSDFileDBO removeFile = (GSDFileDBO) selection.getFirstElement(); if (removeFile != null) { if (MessageDialog.openQuestion(getShell(), "Lsche Datei aus der Datenbank", "Sind sie sicher das sie die Datei " + removeFile.getName() + " lschen mchten")) { Repository.removeGSDFiles(removeFile); List<GSDFileDBO> gsdFiles = getGsdFiles(); if (gsdFiles != null) { gsdFiles.remove(removeFile); } _tableViewer.setInput(gsdFiles); } } } } private final class GSDFileSelectionListener implements SelectionListener { private final TableViewer _tableViewer; private final Text _tSelected; /** * Constructor. * * @param tableViewer * @param tSelected */ protected GSDFileSelectionListener( @Nonnull final TableViewer tableViewer, @Nonnull final Text tSelected) { _tableViewer = tableViewer; _tSelected = tSelected; } private void doFileAdd() { setGsdFile((GSDFileDBO) ((StructuredSelection) _tableViewer .getSelection()).getFirstElement()); if (fill(getGsdFile())) { _tSelected.setText(getGsdFile().getName()); setSavebuttonEnabled("GSDFile", true); } } @Override public void widgetDefaultSelected(@Nullable final SelectionEvent e) { doFileAdd(); } @Override public void widgetSelected(@Nullable final SelectionEvent e) { doFileAdd(); } } private final class NodeConfigModifyListener implements ModifyListener { public NodeConfigModifyListener() { // Default Constructor. } @Override public void modifyText(@Nonnull final ModifyEvent e) { if (e.widget instanceof Text) { final Text text = (Text) e.widget; setSavebuttonEnabled("ModifyListenerText:" + text.hashCode(), !text.getText().equals(text.getData())); } else if (e.widget instanceof Combo) { final Combo combo = (Combo) e.widget; if (combo.getData() instanceof Integer) { final Integer value = (Integer) combo.getData(); if (value == null) { setSavebuttonEnabled( "ModifyListenerCombo" + combo.hashCode(), false); } else { setSavebuttonEnabled( "ModifyListenerCombo" + combo.hashCode(), value != combo.getSelectionIndex()); } } } else if (e.widget instanceof Spinner) { final Spinner spinner = (Spinner) e.widget; try { setSavebuttonEnabled( "ModifyListenerCombo" + spinner.hashCode(), (Short) spinner.getData() != spinner.getSelection()); } catch (final ClassCastException cce) { LOG.error(spinner.toString(), cce); } } } } private final class SaveSelectionListener implements SelectionListener { public SaveSelectionListener() { // Default Constructor } @Override public void widgetDefaultSelected(@Nonnull final SelectionEvent e) { getEditorSite().getActionBars() .getGlobalActionHandler("org.eclipse.ui.file.save").run(); // TODO:need a IProgressMonitor? Yes! doSave(null); } @Override public void widgetSelected(@Nonnull final SelectionEvent e) { perfromSave(); } } private final class ViewerSorterExtension extends ViewerSorter { public ViewerSorterExtension() { // default constructor } @Override public int compare(@Nullable final Viewer viewer, @Nullable final Object e1, @Nullable final Object e2) { if (e1 instanceof GSDFileDBO && e2 instanceof GSDFileDBO) { final GSDFileDBO file1 = (GSDFileDBO) e1; final GSDFileDBO file2 = (GSDFileDBO) e2; // sort wrong files to back. if (!(file1.isMasterNonHN() || file1.isSlaveNonHN()) && (file2.isMasterNonHN() || file2.isSlaveNonHN())) { return -1; } else if ((file1.isMasterNonHN() || file1.isSlaveNonHN()) && !(file2.isMasterNonHN() || file2.isSlaveNonHN())) { return 1; } // if master -> master file to top switch (getNode().needGSDFile()) { case Master: if (file1.isMasterNonHN() && !file2.isMasterNonHN()) { return -1; } else if (!file1.isMasterNonHN() && file2.isMasterNonHN()) { return 1; } break; case Slave: // if slave -> slave file to top if (file1.isSlaveNonHN() && !file2.isSlaveNonHN()) { return -1; } else if (!file1.isSlaveNonHN() && file2.isSlaveNonHN()) { return 1; } break; default: // do nothing } return file1.getName().compareToIgnoreCase(file2.getName()); } return super.compare(viewer, e1, e2); } } /** * The warn background color (SWT.COLOR_RED) of the index Spinner. */ protected static final Color WARN_BACKGROUND_COLOR = CustomMediaFactory .getInstance().getColor(CustomMediaFactory.COLOR_RED); private static Font _FONT; private static GridDataFactory _LABEL_GRID_DATA = GridDataFactory .fillDefaults(); private static GridDataFactory _TEXT_GRID_DATA = GridDataFactory .fillDefaults().grab(true, false); private static void createGSDFileActions(@Nonnull final TableViewer viewer) { final Menu menu = new Menu(viewer.getControl()); final MenuItem showItem = new MenuItem(menu, SWT.PUSH); showItem.addSelectionListener(new ShowFileSelectionListener(viewer)); showItem.setText("&Show"); showItem.setImage(PlatformUI.getWorkbench().getSharedImages() .getImage(ISharedImages.IMG_OBJ_FOLDER)); // MenuItem saveAsItem = new MenuItem(menu, SWT.PUSH); // saveAsItem.addSelectionListener(new SaveAsSelectionListener(viewer)); // saveAsItem.setText("&Show"); // saveAsItem.setImage(PlatformUI.getWorkbench().getSharedImages() // .getImage(ISharedImages.IMG_ETOOL_SAVEAS_EDIT)); viewer.getTable().setMenu(menu); } @Nonnull private static Label getNewLabel(@Nonnull final Composite header, @Nonnull final String string) { final Label newLabel = new Label(header, SWT.NONE); newLabel.setLayoutData(_LABEL_GRID_DATA.create()); newLabel.setText(string); return newLabel; } @Nonnull private static Text getNewText(@Nonnull final Composite header, @Nonnull final String text) { final Text newText = new Text(header, SWT.NONE); newText.setLayoutData(_TEXT_GRID_DATA.create()); newText.setEditable(false); newText.setText(text); return newText; } protected static void resetString(@Nonnull Text textField) { String text = (String) textField.getData(); if (text != null) { textField.setText(text); } } /** * A ModifyListener that set the save button enable to store the changes. * Works with {@link Text}, {@link Combo} and {@link Spinner}. */ private final ModifyListener _mLSB = new NodeConfigModifyListener(); /** * Contain all different events that have change a Value and the status of * the change. The status means is the new Value a differnt from the origin * Value. */ private final HashMap<String, Boolean> _saveButtonEvents = new HashMap<String, Boolean>(); private final Map<HeaderFields, Text> headerFields = new HashMap<HeaderFields, Text>(); /** * The Button to cancel Changes. */ private Button _cancelButton; private Text _descText; /** * The Tabview to Manage the documentation of Node. */ private DocumentationManageView _documentationManageView; // Node Editor View private GSDFileDBO _gsdFile; private List<GSDFileDBO> _gsdFiles; /** * The Spinner for the channel index. */ private Spinner _indexSpinner; /** * The text field for the name of the node. */ private Text _nameText; // Node Editor View /** * if true an new SubNet a created also modified _slave. */ private boolean _new = false; private AbstractNodeDBO _node; // Node Editor View private Composite _parent; /** * The Button to save Changes. */ private Button _saveButton; /** * The Tabfolder for a config view. */ private TabFolder _tabFolder; public AbstractNodeEditor() { // TODO Auto-generated constructor stub } public AbstractNodeEditor(final boolean nevv) { // super(parent, SWT.NONE); setNew(nevv); // ActionFactory.SAVE.create(this.get); // setGlobalActionHandler(IWorkbenchActionConstants., // goIntoAction); // setBackgroundComposite(headline, node); } // Node Editor View public void cancel() { Text descText = getDescText(); if (descText != null && descText.getData() != null && descText.getData() instanceof String) { setDesc((String) descText.getData()); } if (getNode() != null) { getNode().setDirty(false); } } @SuppressWarnings("unused") private void createButtonArea(@Nonnull final TabFolder tabFolder, @Nonnull final Composite comp, @Nonnull final Text selectedText, @Nonnull final TableViewer gsdFileTableViewer) { new Label(comp, SWT.NONE); final Button fileSelect = new Button(comp, SWT.PUSH); fileSelect.setText("Select"); fileSelect.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); fileSelect.addSelectionListener(new GSDFileSelectionListener( gsdFileTableViewer, selectedText)); new Label(comp, SWT.NONE); new Label(comp, SWT.NONE); final Button fileAdd = new Button(comp, SWT.PUSH); fileAdd.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); fileAdd.setText("Add File"); fileAdd.addSelectionListener(new GSDFileAddListener(this, tabFolder, gsdFileTableViewer, comp)); final Button fileRemove = new Button(comp, SWT.PUSH); fileRemove.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); fileRemove.setText("Remove File"); fileRemove.addSelectionListener(new GSDFileRemoveListener( gsdFileTableViewer)); gsdFileTableViewer .addSelectionChangedListener(new GSDFileChangeListener( fileSelect)); new Label(comp, SWT.NONE); } /** * @param columnNum * @param comp * @return */ @Nonnull private TableViewer createChooserArea(final int columnNum, @Nonnull final Composite comp) { final Group gAvailable = new Group(comp, SWT.NONE); gAvailable.setText("Available GSD File:"); gAvailable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, columnNum, 1)); gAvailable.setLayout(new GridLayout(1, false)); final TableColumnLayout tableColumnLayout = new TableColumnLayout(); final Composite tableComposite = new Composite(gAvailable, SWT.BORDER); GridDataFactory.fillDefaults().grab(true, true).applyTo(tableComposite); tableComposite.setLayout(tableColumnLayout); final TableViewer gsdFileTableViewer = new TableViewer(tableComposite, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION); gsdFileTableViewer.setContentProvider(new ArrayContentProvider()); gsdFileTableViewer.setSorter(new ViewerSorterExtension()); gsdFileTableViewer.setLabelProvider(new GSDLabelProvider(getNode() .needGSDFile())); gsdFileTableViewer.getTable().setHeaderVisible(false); gsdFileTableViewer.getTable().setLinesVisible(false); GridDataFactory.fillDefaults().grab(true, true) .applyTo(gsdFileTableViewer.getTable()); setGsdFiles(Repository.load(GSDFileDBO.class)); if (getGsdFiles() == null) { setGsdFiles(new ArrayList<GSDFileDBO>()); } else if (!getGsdFiles().isEmpty()) { gsdFileTableViewer.setInput(getGsdFiles().toArray( new GSDFileDBO[getGsdFiles().size()])); } return gsdFileTableViewer; } /** * (@inheritDoc) */ @Override public void createPartControl(@Nonnull final Composite parent) { _parent = parent; setBackgroundComposite(); if (getTabFolder() != null && getNode().needGSDFile() != GSDFileTypes.NONE) { makeGSDFileChooser(getTabFolder(), "GSD File List"); } documents(); } @Nonnull private Text createSelectionArea(final int columnNum, @Nonnull final Composite comp) { final Text tSelected; final Group gSelected = new Group(comp, SWT.NONE); gSelected.setText("Selected GSD File:"); gSelected.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, columnNum, 1)); gSelected.setLayout(new GridLayout(1, false)); tSelected = new Text(gSelected, SWT.SINGLE | SWT.BORDER); tSelected.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1)); if (getGsdFile() != null) { setGsdFile(getGsdFile()); tSelected.setText(getGsdFile().getName()); } return tSelected; } /** * * {@inheritDoc} */ @Override public void dispose() { super.dispose(); setSaveButton(null); if (_saveButtonEvents != null) { _saveButtonEvents.clear(); } getProfiBusTreeView().removeOpenEditor(this); } /** * set the documents and Icon tab item. */ private void documents() { final String head = "Documents"; final TabItem item = new TabItem(getTabFolder(), SWT.NO_SCROLL); item.setText(head); // TODO: refactor DocumentationManageView _documentationManageView = new DocumentationManageView(getTabFolder(), SWT.NONE, this); item.setControl(_documentationManageView); getTabFolder().addSelectionListener(new SelectionListener() { private void docTabSelectionAction(@Nonnull final SelectionEvent e) { if (e.item.equals(item)) { getDocumentationManageView().onActivate(); } } @Override public void widgetDefaultSelected(@Nonnull final SelectionEvent e) { docTabSelectionAction(e); } @Override public void widgetSelected(@Nonnull final SelectionEvent e) { docTabSelectionAction(e); } }); } @Override public void doSave(@Nullable final IProgressMonitor monitor) { // Header final Date now = new Date(); final SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.S"); final Text text = getHeaderField(HeaderFields.VERSION); int i = -1; try { i = Integer.valueOf(text.getText()); } catch (final NumberFormatException nfe) { i = 0; } getNode().setVersion(i); getNode().setUpdatedBy(ConfigHelper.getUserName()); getNode().setUpdatedOn(now); getNode().setDescription(getDesc()); if (getDescText() != null) { getDescText().setData(getDesc()); } // update Header getHeaderField(HeaderFields.MODIFIED_ON).setText(df.format(now)); getHeaderField(HeaderFields.MODIFIED_BY).setText( ConfigHelper.getUserName()); getHeaderField(HeaderFields.DB_ID).setText("" + getNode().getId()); // df = null; // now = null; } // Node Editor View /** * (@inheritDoc) */ @Override public void doSaveAs() { // save as not supported } /** * Fill the View whit data from GSDFile. * * @param gsdFile * the GSDFile whit the data. * @return true when set the data ok. */ public abstract boolean fill(@Nullable GSDFileDBO gsdFile); /** * @return the cancelButton */ @CheckForNull protected final Button getCancelButton() { return _cancelButton; } @Nonnull public String getDesc() { if (getDescText() == null || getDescText().getText() == null) { return ""; } return getDescText().getText(); } @CheckForNull protected Text getDescText() { return _descText; } // Node Editor View /** * * @return the node which was configured with this View. */ @Override @Nonnull public IDocumentable getDocumentableObject() { return _node; } /** * * @return The Documentation Manage View. */ @CheckForNull protected final DocumentationManageView getDocumentationManageView() { return _documentationManageView; } @CheckForNull protected List<GSDFileDBO> getGsdFiles() { return _gsdFiles; } @Nonnull public Text getHeaderField(@Nonnull final HeaderFields field) { return headerFields.get(field); } /** * @return the indexSpinner */ @CheckForNull protected final Spinner getIndexSpinner() { return _indexSpinner; } /** * A ModifyListener that set the save button enable to store the changes. * Works wiht {@link Text}, {@link Combo} and {@link Spinner}. * * @return the ModifyListener. */ @Nonnull public final ModifyListener getMLSB() { return _mLSB; } /** * * @return the Node Name description field. */ @CheckForNull protected final Text getNameWidget() { return _nameText; } /** * @param head * The Tab text. * @param rows * row number for the grid. * @return The Composite of the generated TabItem. */ @Nonnull protected final Composite getNewTabItem(@Nonnull final String head, final int rows) { final TabItem item = new TabItem(getTabFolder(), SWT.NONE, 0); item.setText(head); final Composite comp = new Composite(getTabFolder(), SWT.NONE); comp.setLayout(new GridLayout(rows, false)); item.setControl(comp); comp.setBackground(Display.getDefault().getSystemColor( SWT.COLOR_WIDGET_BACKGROUND)); return comp; } /** * {@inheritDoc} */ @Override @Nonnull public AbstractNodeDBO getNode() { return _node; } /** * @return the parent */ @CheckForNull protected Composite getParent() { return _parent; } /** * @return the profiBusTreeView */ @Nonnull protected final ProfiBusTreeView getProfiBusTreeView() { return ((MainView) getEditorSite().getPage().findView(MainView.ID)) .getProfiBusTreeView(); } @CheckForNull protected Button getSaveButton() { return _saveButton; } @CheckForNull protected Shell getShell() { if (this.getEditorSite() != null) { return this.getEditorSite().getShell(); } return null; } /** * @return the tabFolder */ @Nonnull protected final TabFolder getTabFolder() { assert _tabFolder != null : "Tab folder not avaible!"; return _tabFolder; } /** * (@inheritDoc) */ @Override public void init(@Nonnull final IEditorSite site, @Nonnull final IEditorInput input) throws PartInitException { setSite(site); setInput(input); // getProfiBusTreeView().closeOpenEditor(); _node = ((NodeEditorInput) input).getNode(); setNew(((NodeEditorInput) input).isNew()); setPartName(_node.getName()); getProfiBusTreeView().setOpenEditor(this); } /** * * @return only true when the node has on or more changes. */ @Override public final boolean isDirty() { if (getNode() != null) { return getNode().isDirty(); } return true; } @Override public boolean isSaveAsAllowed() { return false; // save as not supported } @Nonnull private Group makeBackgroundGroup(final int columnNum) { final Group header = new Group(getParent(), SWT.H_SCROLL); header.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, columnNum, 1)); header.setLayout(new GridLayout(7, false)); header.setText("General Information"); header.setTabList(new Control[0]); return header; } protected void makeDescGroup(@Nonnull final Composite comp, final int hSize) { final Group gDesc = new Group(comp, SWT.NONE); gDesc.setText("Description: "); final GridDataFactory gdf = GridDataFactory.fillDefaults() .grab(true, true).span(hSize, 1).minSize(200, 200); gDesc.setLayoutData(gdf.create()); gDesc.setLayout(new GridLayout(2, false)); final Label shortDescLabel = new Label(gDesc, SWT.NONE); shortDescLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false)); shortDescLabel.setText("Short Desc:"); final Text shortDescText = new Text(gDesc, SWT.BORDER | SWT.SINGLE | SWT.READ_ONLY); shortDescText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1)); shortDescText.setEditable(false); final Text descText = new Text(gDesc, SWT.BORDER | SWT.MULTI); descText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); descText.setEditable(true); descText.addModifyListener(new ModifyListener() { @Override public void modifyText(@Nonnull final ModifyEvent e) { final String text = descText.getText(); String string = ""; if (text != null) { final String[] split = text.split("[\r\n]"); if (split.length > 0) { if (string.length() > 40) { string = string.substring(0, 40); } else { string = split[0]; } } } shortDescText.setText(string); } }); setText(descText, getNode().getDescription(), 255); setDescWidget(descText); gDesc.setTabList(new Control[] {descText }); } /** * * @param tabFolder * The Tab Folder to add the Tab Item. * @param head * Headline for the Tab. * @return Tab Item Composite. */ @Nonnull public Composite makeGSDFileChooser(@Nonnull final TabFolder tabFolder, @Nonnull final String head) { final int columnNum = 7; final Composite comp = ConfigHelper.getNewTabItem(head, tabFolder, columnNum, 520, 200); final Text selectedText = createSelectionArea(columnNum, comp); final TableViewer gsdFileTableViewer = createChooserArea(columnNum, comp); createButtonArea(tabFolder, comp, selectedText, gsdFileTableViewer); createGSDFileActions(gsdFileTableViewer); return comp; } /** * Generate a new Node on his parent with a Name, creator and creation date. */ protected boolean newNode() { return newNode(""); } protected boolean newNode(@Nullable final String nameOffer) { final String nodeType = getNode().getClass().getSimpleName(); final InputDialog id = new InputDialog(getShell(), "Create new " + nodeType, "Enter the name of the " + nodeType, nameOffer, null); id.setBlockOnOpen(true); if (id.open() == Window.OK) { getNode().setName(id.getValue()); final User user = SecurityFacade.getInstance().getCurrentUser(); String name = "Unknown"; if (user != null) { name = user.getUsername(); } getNode().setCreatedBy(name); getNode().setCreatedOn(new Date()); getNode().setVersion(-2); id.close(); final Object obj = ((StructuredSelection) getProfiBusTreeView() .getTreeViewer().getSelection()).getFirstElement(); if (getNode() instanceof FacilityDBO || obj == null) { getProfiBusTreeView().getTreeViewer().setInput(getNode()); // TODO neue facility erstellen und speichern.. } else if (obj instanceof AbstractNodeDBO) { if (getNode().getParent() == null) { final AbstractNodeDBO nodeParent = (AbstractNodeDBO) obj; getNode() .moveSortIndex( nodeParent .getfirstFreeStationAddress(AbstractNodeDBO.MAX_STATION_ADDRESS)); nodeParent.addChild(getNode()); } } return true; } return false; } /** * @param exception * A exception to show in a Dialog, */ protected void openErrorDialog(@Nonnull final Exception exception) { LOG.error(exception); final Formatter f = new Formatter(); String message = exception.getLocalizedMessage(); if (message == null) { message = exception.getMessage(); if (message == null) { message = "Unknown Exception"; } } f.format("The Settings not saved!\n\nDataBase Failure:\n%s", message); final ErrorDialog errorDialog = new ErrorDialog(Display.getCurrent() .getActiveShell(), "Data Base Error", f.toString(), Status.CANCEL_STATUS, 0); errorDialog.open(); f.close(); } public void perfromClose() { final IViewSite site = getProfiBusTreeView().getSite(); site.getPage().closeEditor(this, false); } protected void perfromSave() { final IViewSite site = getProfiBusTreeView().getSite(); final IHandlerService handlerService = (IHandlerService) site .getService(IHandlerService.class); try { handlerService.executeCommand("org.eclipse.ui.file.save", null); } catch (final Exception ex) { LOG.error(ex); } } /** * Save or Update the Node to the Data Base. */ final void save() { try { if (getNode().getParent() == null) { getNode().localSave(); } else { getNode().getParent().localSave(); } } catch (final PersistenceException e) { openErrorDialog(e); } setSaveButtonSaved(); getSaveButton().setText("&Save"); if (isNew() && !getNode().isRootNode()) { getProfiBusTreeView().refresh(getNode().getParent()); } else if (isNew() && getNode().isRootNode()) { getProfiBusTreeView().addFacility(getNode()); getProfiBusTreeView().refresh(getNode()); getProfiBusTreeView().refresh(); } else { // refresh the View getProfiBusTreeView().refresh(getNode()); } setNew(false); } @SuppressWarnings("unused") private void setBackgroundComposite() { final int columnNum = 5; final AbstractNodeDBO node = getNode(); if (node == null) { return; } getParent().setLayout(new GridLayout(columnNum, true)); final Label headlineLabel = new Label(getParent(), SWT.NONE); if (_FONT == null) { _FONT = headlineLabel.getFont(); } headlineLabel.setText("Profibus " + node.getClass().getSimpleName() + " Configuration"); headlineLabel.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, false, columnNum, 1)); final GridDataFactory labelGridData = GridDataFactory.fillDefaults(); // - Header final Group header = makeBackgroundGroup(columnNum); // -- Create by getNewLabel(header, "Created by:"); /** The description field with the name of the User that make changes. */ String temp = ""; if (isNew()) { final SecurityFacade securityFacade = SecurityFacade.getInstance(); if (securityFacade != null && securityFacade.getCurrentUser() != null && securityFacade.getCurrentUser().getUsername() != null) { temp = securityFacade.getCurrentUser().getUsername(); } } else if (node != null && node.getCreatedBy() != null) { temp = node.getCreatedBy(); } final Text creatByText = getNewText(header, temp); getParent().setData("creatBy", creatByText); temp = ""; getNewLabel(header, "Created on:"); /** The description field with the name of the Date of the last change. */ Date now = new Date(); if (isNew()) { temp = ConfigHelper.getSimpleDateFormat().format(now); } else if (node != null && node.getCreatedOn() != null) { now = node.getCreatedOn(); temp = now.toString(); } final Text creatOnText = getNewText(header, temp); getParent().setData("date", now); getParent().setData("creatOn", creatOnText); temp = ""; // -- Version getNewLabel(header, "Version:"); /** The description field with the Version from GSD File. */ if (node != null) { temp = node.getVersion() + ""; } final Text versionText = getNewText(header, temp); setHeaderField(HeaderFields.VERSION, versionText); final Label iconButton = new Label(header, SWT.BORDER); iconButton.setLayoutData(GridDataFactory.swtDefaults().span(1, 3) .minSize(40, 40).create()); iconButton.setImage(ConfigHelper.getImageFromNode(node, 30, 60)); iconButton.addMouseListener(new MouseAdapter() { @Override public void mouseUp(@Nullable final MouseEvent e) { final IconChooserDialog chooseIconDialog = new IconChooserDialog( AbstractNodeEditor.this.getShell(), node); chooseIconDialog.setBlockOnOpen(true); if (chooseIconDialog.open() == 0 && node != null) { node.setIcon(chooseIconDialog.getImage()); } } }); getNewLabel(header, "Modified by:"); /** The description field with the name of the User that make changes. */ temp = ""; if (node != null && node.getUpdatedBy() != null) { temp = node.getUpdatedBy(); } final Text modifiedBy = getNewText(header, temp); setHeaderField(HeaderFields.MODIFIED_BY, modifiedBy); temp = ""; // -- Modifierd on getNewLabel(header, "Modified on:"); /** The description field with the name of the Date of the last change. */ if (node != null && node.getUpdatedOn() != null) { temp = node.getUpdatedOn().toString(); } final Text modifiedOn = getNewText(header, temp); setHeaderField(HeaderFields.MODIFIED_ON, modifiedOn); temp = ""; getNewLabel(header, "DataBase ID:"); /** The description field with the Version from GSD File. */ if (node != null) { temp = node.getId() + ""; } final Text dbIdText = getNewText(header, temp); setHeaderField(HeaderFields.DB_ID, dbIdText); /** * GSD Version. The description field with the Version from GSD File. * Only Master and Slave have a GSD File */ if (node instanceof MasterDBO || node instanceof SlaveDBO) { getNewLabel(header, "Version from GSD:"); if (node.getUpdatedOn() != null) { // TODO: GSD Versionsnummer setzen. temp = node.getVersion() + ""; } final Text version = getNewText(header, temp); getParent().setData("gsdVersion", version); } setTabFolder(new TabFolder(getParent(), SWT.H_SCROLL | SWT.V_SCROLL)); getTabFolder().setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, true, 5, 1)); getTabFolder().setBackgroundMode(SWT.INHERIT_DEFAULT); // -Footer new Label(getParent(), SWT.NONE); setSaveButton(new Button(getParent(), SWT.PUSH)); if (isNew()) { getSaveButton().setText("Create"); } else { getSaveButton().setText("&Save"); } setSavebuttonEnabled(null, !isNew()); getSaveButton().setLayoutData(labelGridData.create()); setSaveButtonSelectionListener(new SaveSelectionListener()); new Label(getParent(), SWT.NONE); setCancelButton(new Button(getParent(), SWT.PUSH)); getCancelButton().setText("&Cancel"); getCancelButton().setLayoutData(labelGridData.create()); getCancelButton().addSelectionListener(new CancelSelectionListener()); new Label(getParent(), SWT.NONE); header.setTabList(new Control[0]); } /** * @param cancelButton * the cancelButton to set */ protected final void setCancelButton(@Nullable final Button cancelButton) { _cancelButton = cancelButton; } /** * Select a text to a {@link Combo} and store the index into Data as origin * value. * * @param comboField * The Combo field to set the index * @param value * The value was select. */ final void setCombo(@Nonnull final Combo comboField, @Nullable final String value) { String tmp = value; if (tmp == null) { tmp = ""; } final int index = comboField.indexOf(value); comboField.select(index); comboField.setData(index); comboField.addModifyListener(getMLSB()); } public void setDesc(@CheckForNull final String desc) { String temp = desc != null ? desc : ""; getDescText().setText(temp); } protected void setDescText(@Nullable final Text descText) { _descText = descText; } /** * * @param descText * set the Node Name description field. */ protected final void setDescWidget(@Nonnull final Text descText) { setDescText(descText); getDescText().addKeyListener(new KeyAdapter() { @Override public void keyPressed(@Nonnull final KeyEvent e) { if (e.keyCode == SWT.CR || e.keyCode == SWT.KEYPAD_CR) { if (e.stateMask != SWT.MOD1) { e.doit = false; getSaveButton().setFocus(); } } } }); } @CheckForNull protected void setGsdFiles(@Nullable final List<GSDFileDBO> gsdFiles) { _gsdFiles = gsdFiles; } @Nonnull public Text setHeaderField(@Nonnull final HeaderFields field, @Nullable final Text text) { return headerFields.put(field, text); } /** * @param indexSpinner * the indexSpinner to set */ protected final void setIndexSpinner(@Nullable final Spinner indexSpinner) { _indexSpinner = indexSpinner; } public final void setName(@Nonnull final String name) { final TreeItem treeItem = getProfiBusTreeView().getTreeViewer() .getTree().getSelection()[0]; treeItem.setText(name); _nameText.setText(name); } /** * * @param nameText * set the Node Name description field. */ protected final void setNameWidget(@Nonnull final Text nameText) { _nameText = nameText; _nameText.addKeyListener(new KeyAdapter() { @Override public void keyReleased(@Nonnull final KeyEvent e) { if (e.keyCode == SWT.CR || e.keyCode == SWT.KEYPAD_CR) { getDescText().setFocus(); } } }); } protected void setSaveButton(@Nullable final Button saveButton) { _saveButton = saveButton; } /** * Give a change event and his save status.<br> * Have one or more events the status unsaved then the Save Button was set * to enable otherwise to disable. * * @param event * the Save Event Id. * @param enabled * the Save Enable status for the event. */ @Override public final void setSavebuttonEnabled(@Nullable final String event, final boolean enabled) { if (event != null) { _saveButtonEvents.put(event, enabled); } final boolean enab = !getNode().isPersistent() || _saveButtonEvents.containsValue(Boolean.valueOf(true)); final boolean changed = enab != getSaveButton().isEnabled(); getSaveButton().setEnabled(enab); getNode().setDirty(enab); if (changed) { firePropertyChange(IEditorPart.PROP_DIRTY); } } /** * Clear the dirty bit, delete all saveButton events and set the Button * disable. */ @Override public final void setSaveButtonSaved() { _saveButtonEvents.clear(); getSaveButton().setEnabled(false); if (getNode() != null) { getNode().setDirty(false); } firePropertyChange(PROP_DIRTY); } /** * * @param selectionListener */ public final void setSaveButtonSelectionListener( @Nonnull final SelectionListener selectionListener) { getSaveButton().addSelectionListener(selectionListener); } /** * @param tabFolder * the tabFolder to set */ protected final void setTabFolder(@Nullable final TabFolder tabFolder) { _tabFolder = tabFolder; } /** * Set a int as text to a {@link Text} and store the text into Data as * origin value. * * @param textField * The Text field to set the text * @param textValue * The int was set. */ final void setText(@Nonnull final Text textField, final int textValue, final int limit) { setText(textField, Integer.toString(textValue), limit); } /** * Set a text to a {@link Text} and store the text into Data as origin * value. * * @param textField * The Text-field to set the text * @param text * The text was set. * @param limit * The maximum text length for the Text-field. (Text.LIMIT for * maximum) */ final void setText(@Nonnull final Text textField, @Nullable final String text, final int limit) { String tmp = text; if (tmp == null) { tmp = ""; } textField.setText(tmp); textField.setData(tmp); textField.setTextLimit(limit); // Formatter f = new Formatter(); // f.format("The maximum text length is %s character", limit); textField.setToolTipText(""); textField.addModifyListener(getMLSB()); } protected void setGsdFile(@Nullable GSDFileDBO gsdFile) { _gsdFile = gsdFile; } @CheckForNull protected GSDFileDBO getGsdFile() { return _gsdFile; } protected static void resetSelection(@Nonnull Combo combo) { Integer index = (Integer) combo.getData(); if (index != null) { combo.select(index); } } protected void setNew(boolean nevv) { _new = nevv; } protected boolean isNew() { return _new; } }
package org.ovirt.engine.core.searchbackend; import org.ovirt.engine.core.common.AuditLogSeverity; import org.ovirt.engine.core.common.businessentities.DateEnumForSearch; import org.ovirt.engine.core.compat.StringHelper; public class AuditLogConditionFieldAutoCompleter extends BaseConditionFieldAutoCompleter { public AuditLogConditionFieldAutoCompleter() { super(); // Building the basic vervs Dict mVerbs.put("TYPE", "TYPE"); mVerbs.put("SEVERITY", "SEVERITY"); mVerbs.put("MESSAGE", "MESSAGE"); mVerbs.put("TIME", "TIME"); mVerbs.put("USRNAME", "USRNAME"); mVerbs.put("EVENT_HOST", "EVENT_HOST"); mVerbs.put("EVENT_VM", "EVENT_VM"); mVerbs.put("EVENT_TEMPLATE", "EVENT_TEMPLATE"); mVerbs.put("EVENT_STORAGE", "EVENT_STORAGE"); mVerbs.put("EVENT_DATACENTER", "EVENT_DATACENTER"); mVerbs.put("EVENT_VOLUME", "EVENT_VOLUME"); mVerbs.put("CORRELATION_ID", "CORRELATION_ID"); buildCompletions(); // These search options remain hidden from the autocompletion // but still available for the user interface mVerbs.put("_EVENT_VM_ID", "_EVENT_VM_ID"); mVerbs.put("_EVENT_TEMPLATE_ID", "_EVENT_TEMPLATE_ID"); mVerbs.put("_EVENT_STORAGE_ID", "_EVENT_STORAGE_ID"); mVerbs.put("_EVENT_HOST_ID", "_EVENT_HOST_ID"); mVerbs.put("_EVENT_DATACENTER_ID", "_EVENT_DATACENTER_ID"); mVerbs.put("_EVENT_QUOTA_ID", "_EVENT_QUOTA_ID"); mVerbs.put("USRID", "USRID"); // Building the autoCompletion Dict // Building the types dict getTypeDictionary().put("TYPE", Integer.class); getTypeDictionary().put("SEVERITY", AuditLogSeverity.class); getTypeDictionary().put("MESSAGE", String.class); getTypeDictionary().put("TIME", java.util.Date.class); getTypeDictionary().put("USRNAME", String.class); getTypeDictionary().put("EVENT_HOST", String.class); getTypeDictionary().put("EVENT_VM", String.class); getTypeDictionary().put("EVENT_TEMPLATE", String.class); getTypeDictionary().put("EVENT_STORAGE", String.class); getTypeDictionary().put("EVENT_DATACENTER", String.class); getTypeDictionary().put("USRID", String.class); getTypeDictionary().put("_EVENT_HOST_ID", String.class); getTypeDictionary().put("_EVENT_VM_ID", String.class); getTypeDictionary().put("_EVENT_TEMPLATE_ID", String.class); getTypeDictionary().put("_EVENT_STORAGE_ID", String.class); getTypeDictionary().put("_EVENT_DATACENTER_ID", String.class); getTypeDictionary().put("_EVENT_QUOTA_ID", String.class); getTypeDictionary().put("EVENT_VOLUME", String.class); getTypeDictionary().put("_EVENT_VOLUME_ID", String.class); getTypeDictionary().put("CORRELATION_ID", String.class); // building the ColumnName Dict mColumnNameDict.put("TYPE", "log_type"); mColumnNameDict.put("SEVERITY", "severity"); mColumnNameDict.put("MESSAGE", "message"); mColumnNameDict.put("TIME", "log_time"); mColumnNameDict.put("USRNAME", "user_name"); mColumnNameDict.put("USRID", "user_id::varchar"); mColumnNameDict.put("EVENT_HOST", "vds_name"); mColumnNameDict.put("_EVENT_HOST_ID", "vds_id::varchar"); mColumnNameDict.put("EVENT_VM", "vm_name"); mColumnNameDict.put("_EVENT_VM_ID", "vm_id::varchar"); mColumnNameDict.put("EVENT_TEMPLATE", "vm_template_name"); mColumnNameDict.put("_EVENT_TEMPLATE_ID", "vm_template_id::varchar"); mColumnNameDict.put("EVENT_STORAGE", "storage_domain_name"); mColumnNameDict.put("_EVENT_STORAGE_ID", "storage_domain_id::varchar"); mColumnNameDict.put("EVENT_DATACENTER", "storage_pool_name"); mColumnNameDict.put("_EVENT_DATACENTER_ID", "storage_pool_id::varchar"); mColumnNameDict.put("_EVENT_QUOTA_ID", "quota_id::varchar"); mColumnNameDict.put("EVENT_VOLUME", "gluster_volume_name"); mColumnNameDict.put("_EVENT_VOLUME_ID", "gluster_volume_id::varchar"); mColumnNameDict.put("CORRELATION_ID", "correlation_id::varchar"); // Building the validation dict buildBasicValidationTable(); } @Override public IAutoCompleter getFieldRelationshipAutoCompleter(final String fieldName) { if (StringHelper.EqOp(fieldName, "SEVERITY")) { return NumericConditionRelationAutoCompleter.INSTANCE; } else if (StringHelper.EqOp(fieldName, "TIME")) { return TimeConditionRelationAutoCompleter.INSTANCE; } else if (StringHelper.EqOp(fieldName, "TYPE") || StringHelper.EqOp(fieldName, "MESSAGE") || StringHelper.EqOp(fieldName, "USRNAME") || StringHelper.EqOp(fieldName, "EVENT_HOST") || StringHelper.EqOp(fieldName, "_EVENT_HOST_ID") || StringHelper.EqOp(fieldName, "EVENT_VM") || StringHelper.EqOp(fieldName, "_EVENT_VM_ID") || StringHelper.EqOp(fieldName, "EVENT_TEMPLATE") || StringHelper.EqOp(fieldName, "_EVENT_TEMPLATE_ID") || StringHelper.EqOp(fieldName, "EVENT_STORAGE") || StringHelper.EqOp(fieldName, "EVENT_DATACENTER") || StringHelper.EqOp(fieldName, "_EVENT_DATACENTER_ID") || StringHelper.EqOp(fieldName, "_EVENT_QUOTA_ID") || StringHelper.EqOp(fieldName, "EVENT_VOLUME") || StringHelper.EqOp(fieldName, "_EVENT_VOLUME_ID") || StringHelper.EqOp(fieldName, "CORRELATION_ID")) { return StringConditionRelationAutoCompleter.INSTANCE; } else { return null; } } @Override public IConditionValueAutoCompleter getFieldValueAutoCompleter(String fieldName) { if (StringHelper.EqOp(fieldName, "SEVERITY")) { return new EnumValueAutoCompleter(AuditLogSeverity.class); } else if (StringHelper.EqOp(fieldName, "TIME")) { return new DateEnumValueAutoCompleter(DateEnumForSearch.class); } else { return null; } } }
package net.safedata.springboot.training.d04.s01.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; @Service @SuppressWarnings("unused") public class ProductService { private static final Logger LOGGER = LoggerFactory.getLogger(ProductService.class); private final AsyncComponent asyncComponent; @Autowired public ProductService(final AsyncComponent asyncComponent) { this.asyncComponent = asyncComponent; } public void voidAsyncCall(final String firstParameter, final String secondParameter) { asyncComponent.voidAsyncCall(firstParameter, secondParameter); } public void getFuture() { final Future<String> future = asyncComponent.getFuture(); try { getAndDisplayValue(future, "Future"); } catch (final ExecutionException | InterruptedException e) { handleException(e); } } public void getCompletableFuture() { final CompletableFuture<String> completableFuture = asyncComponent.getCompletableFuture(); try { getAndDisplayValue(completableFuture, "CompletableFuture"); } catch (final ExecutionException | InterruptedException e) { handleException(e); } } private void getAndDisplayValue(final Future<String> futureValue, final String className) throws ExecutionException, InterruptedException { if (futureValue.isDone()) { LOGGER.info("The {} value is '{}'", className, futureValue.get()); } else { System.out.println(futureValue.isCancelled()); System.out.println(futureValue.get()); } } private void handleException(final Exception ex) { ex.printStackTrace(); } }
package org.eclipse.birt.report.engine.emitter.excel; import java.io.IOException; import java.io.OutputStream; import java.util.Collection; import java.util.Iterator; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.report.engine.api.EngineException; import org.eclipse.birt.report.engine.api.IExcelRenderOption; import org.eclipse.birt.report.engine.api.IHTMLActionHandler; import org.eclipse.birt.report.engine.api.IRenderOption; import org.eclipse.birt.report.engine.api.IReportRunnable; import org.eclipse.birt.report.engine.api.RenderOption; import org.eclipse.birt.report.engine.api.script.IReportContext; import org.eclipse.birt.report.engine.content.IAutoTextContent; import org.eclipse.birt.report.engine.content.ICellContent; import org.eclipse.birt.report.engine.content.IContainerContent; import org.eclipse.birt.report.engine.content.IContent; import org.eclipse.birt.report.engine.content.IDataContent; import org.eclipse.birt.report.engine.content.IForeignContent; import org.eclipse.birt.report.engine.content.IHyperlinkAction; import org.eclipse.birt.report.engine.content.IImageContent; import org.eclipse.birt.report.engine.content.ILabelContent; import org.eclipse.birt.report.engine.content.IListBandContent; import org.eclipse.birt.report.engine.content.IListContent; import org.eclipse.birt.report.engine.content.IPageContent; import org.eclipse.birt.report.engine.content.IReportContent; import org.eclipse.birt.report.engine.content.IRowContent; import org.eclipse.birt.report.engine.content.IStyle; import org.eclipse.birt.report.engine.content.ITableContent; import org.eclipse.birt.report.engine.content.ITextContent; import org.eclipse.birt.report.engine.css.engine.value.DataFormatValue; import org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter; import org.eclipse.birt.report.engine.emitter.EmitterUtil; import org.eclipse.birt.report.engine.emitter.IEmitterServices; import org.eclipse.birt.report.engine.emitter.excel.layout.ColumnsInfo; import org.eclipse.birt.report.engine.emitter.excel.layout.ContainerSizeInfo; import org.eclipse.birt.report.engine.emitter.excel.layout.ExcelContext; import org.eclipse.birt.report.engine.emitter.excel.layout.ExcelLayoutEngine; import org.eclipse.birt.report.engine.emitter.excel.layout.LayoutUtil; import org.eclipse.birt.report.engine.emitter.excel.layout.PageDef; import org.eclipse.birt.report.engine.ir.DataItemDesign; import org.eclipse.birt.report.engine.ir.DimensionType; import org.eclipse.birt.report.engine.ir.MapDesign; import org.eclipse.birt.report.engine.ir.SimpleMasterPageDesign; import org.eclipse.birt.report.engine.layout.pdf.util.HTML2Content; import org.eclipse.birt.report.engine.presentation.ContentEmitterVisitor; import com.ibm.icu.util.TimeZone; import com.ibm.icu.util.ULocale; public class ExcelEmitter extends ContentEmitterAdapter { protected static Logger logger = Logger.getLogger( ExcelEmitter.class .getName( ) ); protected IEmitterServices service = null; protected OutputStream out = null; protected ExcelLayoutEngine engine; ContentEmitterVisitor contentVisitor = new ContentEmitterVisitor( this ); protected IExcelWriter writer; public ExcelContext context = new ExcelContext( ); private String orientation = null; protected String pageHeader; protected String pageFooter; private boolean outputInMasterPage = false; protected boolean isRTLSheet = false; private int sheetIndex = 1; public String getOutputFormat( ) { return "xls"; } public void initialize( IEmitterServices service ) throws EngineException { this.service = service; if ( service != null ) { this.out = EmitterUtil.getOuputStream( service, "report." + getOutputFormat( ) ); } context.setTempFileDir( service.getReportEngine( ).getConfig( ) .getTempDir( ) ); IReportContext reportContext = service.getReportContext( ); if ( reportContext != null ) { Locale locale = reportContext.getLocale( ); if ( locale != null ) { context.setLocale( ULocale.forLocale( locale ) ); } else context.setLocale( ULocale.getDefault( ) ); } } public void start( IReportContent report ) { setupRenderOptions( ); // We can the page size from the design, maybe there is a better way // to get the page definition. String reportOrientation = report.getDesign( ).getReportDesign( ) .getBidiOrientation( ); if ( "rtl".equalsIgnoreCase( reportOrientation ) ) isRTLSheet = true; IStyle style = report.getRoot( ).getComputedStyle( ); SimpleMasterPageDesign master = (SimpleMasterPageDesign) report .getDesign( ).getPageSetup( ).getMasterPage( 0 ); engine = createLayoutEngine( context, this ); engine.initalize( new PageDef( master, style ) ); createWriter( ); } protected ExcelLayoutEngine createLayoutEngine( ExcelContext context, ExcelEmitter emitter ) { return new ExcelLayoutEngine( context, emitter ); } private void setupRenderOptions() { IRenderOption renderOptions = service.getRenderOption( ); Object textWrapping = renderOptions.getOption(IExcelRenderOption.WRAPPING_TEXT); if(textWrapping!=null && textWrapping instanceof Boolean) { context.setWrappingText((Boolean)textWrapping); } else { context.setWrappingText( ( Boolean )true); } Object officeVersion = renderOptions.getOption(IExcelRenderOption.OFFICE_VERSION); if(officeVersion!=null && officeVersion instanceof String) { if(officeVersion.equals( "office2007" )) { context.setOfficeVersion("office2007" ); } } else { context.setOfficeVersion( "office2003" ); } } public void startPage( IPageContent page ) throws BirtException { if ( orientation == null ) { orientation = capitalize( page.getOrientation( ) ); } if(needOutputInMasterPage(page.getPageHeader( ))&& needOutputInMasterPage(page.getPageFooter( ))) { outputInMasterPage = true; pageHeader = formatHeaderFooter( page.getPageHeader( ),true ); pageFooter = formatHeaderFooter( page.getPageFooter( ),false ); } if ( !outputInMasterPage && page.getPageHeader( ) != null ) { contentVisitor.visitChildren( page.getPageHeader( ), null ); } engine.setPageStyle( page.getComputedStyle( ) ); } public void endPage( IPageContent page ) throws BirtException { if(!outputInMasterPage && page.getPageFooter( ) != null) { contentVisitor.visitChildren( page.getPageFooter( ), null ); } } public void startTable( ITableContent table ) { ContainerSizeInfo sizeInfo = engine.getCurrentContainer( ).getSizeInfo( ); int width = sizeInfo.getWidth( ); int[] columns = LayoutUtil.createTable( table, LayoutUtil .getElementWidth( table, width ) ); ColumnsInfo info = new ColumnsInfo( columns ); String caption = table.getCaption( ); if(caption != null) { engine.addCaption( caption ); } engine.addTable( table, info, sizeInfo ); } public void startRow( IRowContent row ) { engine.addRow( row.getComputedStyle( ) ); } public void endRow( IRowContent row ) { DimensionType height = row.getHeight( ); double rowHeight = height != null ? ExcelUtil.covertDimensionType( height, 0 ) : 0; engine.endRow( rowHeight ); } public void startCell( ICellContent cell ) { IStyle style = cell.getComputedStyle( ); engine.addCell( cell, cell.getColumn( ), cell.getColSpan( ), cell .getRowSpan( ), style ); } public void endCell( ICellContent cell ) { engine.endCell( ); } public void endTable( ITableContent table ) { engine.endTable(); } public void startList( IListContent list ) { ContainerSizeInfo size = engine.getCurrentContainer( ).getSizeInfo( ); ColumnsInfo table = LayoutUtil.createTable( list, size.getWidth( ) ); engine.addTable( list, table, size ); if(list.getChildren( ) == null) { HyperlinkDef link = parseHyperLink(list); BookmarkDef bookmark = getBookmark( list ); engine.addData( ExcelLayoutEngine.EMPTY, list.getComputedStyle( ), link, bookmark ); } } public void startListBand( IListBandContent listBand ) { engine.addCell( 0, 1, 0, listBand.getComputedStyle( ) ); } public void endListBand( IListBandContent listBand ) { engine.endContainer( ); } public void endList( IListContent list ) { engine.endTable( ); } public void startForeign( IForeignContent foreign ) throws BirtException { if ( IForeignContent.HTML_TYPE.equalsIgnoreCase( foreign.getRawType( ) ) ) { HTML2Content.html2Content( foreign ); HyperlinkDef link = parseHyperLink(foreign); engine.addContainer( foreign.getComputedStyle( ), link ); contentVisitor.visitChildren( foreign, null ); engine.endContainer( ); } } public void startText( ITextContent text ) { HyperlinkDef url = parseHyperLink( text ); BookmarkDef bookmark = getBookmark( text ); engine.addData( text.getText( ), text.getComputedStyle( ), url, bookmark ); } public void startData( IDataContent data ) { addDataContent( data ); } protected Data addDataContent( IDataContent data ) { HyperlinkDef url = parseHyperLink( data ); BookmarkDef bookmark = getBookmark( data ); Data excelData = null; Object generateBy = data.getGenerateBy( ); IStyle style = data.getComputedStyle( ); DataFormatValue dataformat = style.getDataFormat( ); MapDesign map = null; if(generateBy instanceof DataItemDesign ) { DataItemDesign design = (DataItemDesign) generateBy; map = design.getMap( ); } if ( map != null && map.getRuleCount( ) > 0 && data.getLabelText( ) != null ) { excelData = engine.addData( data.getLabelText( ).trim( ), style, url, bookmark ); } else { String locale = null; int type = ExcelUtil.getType( data.getValue( ) ); if ( type == SheetData.STRING ) { if ( dataformat != null ) { locale = dataformat.getStringLocale( ); } excelData = engine.addData( data.getText( ), style, url, bookmark, locale ); } else if ( type == Data.NUMBER ) { if ( dataformat != null ) { locale = dataformat.getNumberLocale( ); } excelData = engine.addData( data.getValue( ), style, url, bookmark, locale ); } else { if ( dataformat != null ) { locale = dataformat.getDateTimeLocale( ); } excelData = engine.addDateTime( data, style, url, bookmark, locale ); } } return excelData; } public void startImage( IImageContent image ) { IStyle style = image.getComputedStyle( ); HyperlinkDef url = parseHyperLink( image ); BookmarkDef bookmark = getBookmark( image ); engine.addImageData( image, style, url, bookmark ); } public void startLabel( ILabelContent label ) { Object design = label.getGenerateBy( ); IContent container = label; while ( design == null ) { container = (IContent) container.getParent( ); design = ( (IContent) container ).getGenerateBy( ); } HyperlinkDef url = parseHyperLink( label ); BookmarkDef bookmark = getBookmark( label ); // If the text is BR and it generated by foreign, // ignore it if ( !( "\n".equalsIgnoreCase( label.getText( ) ) && container instanceof IForeignContent ) ) { engine.addData( label.getText( ), label.getComputedStyle( ), url, bookmark ); } } public void startAutoText( IAutoTextContent autoText ) { HyperlinkDef link = parseHyperLink( autoText ); BookmarkDef bookmark = getBookmark( autoText ); engine.addData( autoText.getText( ) , autoText.getComputedStyle( ), link, bookmark ); } public void outputSheet( ) { engine.cacheBookmarks( sheetIndex ); engine.complete( ); try { outputCacheData( ); } catch ( IOException e ) { logger.log( Level.SEVERE, e.getLocalizedMessage( ), e ); } sheetIndex++; } public void end( IReportContent report ) { // Make sure the engine already calculates all data in cache. engine.cacheBookmarks( sheetIndex ); engine.complete( ); try { writer.start( report, engine.getStyleMap( ), engine .getAllBookmarks( ) ); outputCacheData( ); writer.end( ); } catch ( IOException e ) { logger.log( Level.SEVERE, e.getLocalizedMessage( ), e ); } } protected void createWriter( ) { writer = new ExcelWriter( out, context, isRTLSheet ); } /** * @throws IOException * */ public void outputCacheData( ) throws IOException { writer.startSheet( engine.getCoordinates( ), pageHeader, pageFooter ); Iterator<RowData> it = engine.getIterator( ); while ( it.hasNext( ) ) { outputRowData( it.next( ) ); } writer.endSheet( orientation ); } protected void outputRowData( RowData rowData ) throws IOException { writer.startRow( rowData.getHeight( ) ); SheetData[] data = rowData.getRowdata( ); for ( int i = 0; i < data.length; i++ ) { writer.outputData( data[i] ); } writer.endRow( ); } public HyperlinkDef parseHyperLink( IContent content ) { HyperlinkDef hyperlink = null; IHyperlinkAction linkAction = content.getHyperlinkAction( ); if ( linkAction != null ) { String tooltip = linkAction.getTooltip( ); String bookmark = linkAction.getBookmark( ); IReportRunnable reportRunnable = service.getReportRunnable( ); IReportContext reportContext = service.getReportContext( ); IHTMLActionHandler actionHandler = (IHTMLActionHandler) service .getOption( RenderOption.ACTION_HANDLER ); switch ( linkAction.getType( ) ) { case IHyperlinkAction.ACTION_BOOKMARK : hyperlink = new HyperlinkDef( bookmark, IHyperlinkAction.ACTION_BOOKMARK, tooltip ); break; case IHyperlinkAction.ACTION_HYPERLINK : String url = EmitterUtil.getHyperlinkUrl( linkAction, reportRunnable, actionHandler, reportContext ); hyperlink = new HyperlinkDef( url, IHyperlinkAction.ACTION_HYPERLINK, tooltip ); break; case IHyperlinkAction.ACTION_DRILLTHROUGH : url = EmitterUtil.getHyperlinkUrl( linkAction, reportRunnable, actionHandler, reportContext ); hyperlink = new HyperlinkDef( url, IHyperlinkAction.ACTION_DRILLTHROUGH, tooltip ); break; } } return hyperlink; } protected BookmarkDef getBookmark( IContent content ) { String bookmarkName = content.getBookmark( ); if (bookmarkName == null) return null; BookmarkDef bookmark=new BookmarkDef(content.getBookmark( )); if ( !ExcelUtil.isValidBookmarkName( bookmarkName ) ) { bookmark.setGeneratedName( engine .getGenerateBookmark( bookmarkName ) ); } // !( content.getBookmark( ).startsWith( "__TOC" ) ) ) // bookmark starting with "__TOC" is not OK? return bookmark; } public String capitalize( String orientation ) { if ( orientation.equalsIgnoreCase( "landscape" ) ) { return "Landscape"; } if(orientation.equalsIgnoreCase( "portrait" )) { return "Portrait"; } return null; } public String formatHeaderFooter( IContent headerFooter, boolean isHeader ) { StringBuffer headfoot = new StringBuffer( ); if ( headerFooter != null ) { Collection list = headerFooter.getChildren( ); Iterator iter = list.iterator( ); while ( iter.hasNext( ) ) { Object child = iter.next( ); if ( child instanceof ITableContent ) { headfoot.append( getTableValue( (ITableContent) child ) ); } else processText( headfoot, child ); } return headfoot.toString( ); } return null; } private void processText( StringBuffer buffer, Object child ) { if ( child instanceof IAutoTextContent ) { buffer.append( getAutoText( (IAutoTextContent) child ) ); } else if ( child instanceof ITextContent ) { buffer.append( ( (ITextContent) child ).getText( ) ); } else if ( child instanceof IForeignContent ) { buffer.append( ( (IForeignContent) child ).getRawValue( ) ); } } public boolean needOutputInMasterPage( IContent headerFooter ) { if ( headerFooter != null ) { Collection list = headerFooter.getChildren( ); Iterator iter = list.iterator( ); while ( iter.hasNext( ) ) { Object child = iter.next( ); if ( child instanceof ITableContent ) { int columncount = ( (ITableContent) child ) .getColumnCount( ); int rowcount = ( (ITableContent) child ).getChildren( ) .size( ); if ( columncount > 3 || rowcount > 1 ) { logger .log( Level.WARNING, "Excel page header or footer only accept a table no more than 1 row and 3 columns." ); return false; } if ( isEmbededTable( (ITableContent) child ) ) { logger .log( Level.WARNING, "Excel page header and footer don't support embeded grid." ); return false; } } if ( isHtmlText( child ) ) { logger .log( Level.WARNING, "Excel page header and footer don't support html text." ); return false; } } } return true; } private boolean isHtmlText( Object child ) { return child instanceof IForeignContent && IForeignContent.HTML_TYPE .equalsIgnoreCase( ( (IForeignContent) child ) .getRawType( ) ); } public String getTableValue( ITableContent table ) { StringBuffer tableValue = new StringBuffer( ); Collection list = table.getChildren( ); Iterator iter = list.iterator( ); while ( iter.hasNext( ) ) { Object child = iter.next( ); tableValue.append( getRowValue( (IRowContent) child ) ); } return tableValue.toString( ); } public String getRowValue( IRowContent row ) { StringBuffer rowValue = new StringBuffer( ); Collection list = row.getChildren( ); Iterator iter = list.iterator( ); int cellCount = list.size( ); int currentCellCount = 0; while ( iter.hasNext( ) ) { currentCellCount++; Object child = iter.next( ); switch ( currentCellCount ) { case 1 : rowValue.append( "&L" ); break; case 2 : rowValue.append( "&C" ); break; case 3 : rowValue.append( "&R" ); break; default : break; } rowValue.append( getCellValue( (ICellContent) child ) ); } return rowValue.toString( ); } public String getCellValue( ICellContent cell ) { StringBuffer cellValue = new StringBuffer( ); Collection list = cell.getChildren( ); Iterator iter = list.iterator( ); while ( iter.hasNext( ) ) { processText( cellValue, iter.next( ) ); } return cellValue.toString( ); } private String getAutoText( IAutoTextContent autoText ) { String result = null; int type = autoText.getType( ); if ( type == IAutoTextContent.PAGE_NUMBER ) { result = "&P"; } else if ( type == IAutoTextContent.TOTAL_PAGE ) { result = "&N"; } return result; } private boolean isEmbededTable(ITableContent table) { boolean isEmbeded = false; Collection list = table.getChildren( ); Iterator iterRow = list.iterator( ); while ( iterRow.hasNext( ) ) { Object child = iterRow.next( ); Collection listCell = ( (IRowContent) child ).getChildren( ); Iterator iterCell = listCell.iterator( ); while ( iterCell.hasNext( ) ) { Object cellChild = iterCell.next( ); Collection listCellChild = ( (ICellContent) cellChild ) .getChildren( ); Iterator iterCellChild = listCellChild.iterator( ); while ( iterCellChild.hasNext( ) ) { Object cellchild = iterCellChild.next( ); if ( cellchild instanceof ITableContent ) { isEmbeded = true; } } } } return isEmbeded; } public TimeZone getTimeZone() { if ( service != null ) { IReportContext reportContext = service.getReportContext( ); if ( reportContext != null ) { return reportContext.getTimeZone( ); } } return TimeZone.getDefault( ); } public void endContainer( IContainerContent container ) { engine.removeContainerStyle( ); } public void startContainer( IContainerContent container ) { engine.addContainerStyle( container.getComputedStyle( ) ); } }
package org.eclipse.persistence.testing.tests.queries; import org.eclipse.persistence.testing.models.employee.domain.*; import org.eclipse.persistence.exceptions.DatabaseException; import org.eclipse.persistence.expressions.*; import org.eclipse.persistence.queries.*; import org.eclipse.persistence.testing.framework.*; import org.eclipse.persistence.sessions.server.*; /** * This test verifies if a transaction is committed while using read & write * connections in same client session with cursored stream used in read. */ public class CursoredStreamReadWriteClientSessionTest extends TestCase { protected Server serverSession; protected ClientSession clientSession; protected int addressId = 0; protected Exception caughtException = null; /** * CursoredStreamReadWriteClientSessionTest constructor. */ public CursoredStreamReadWriteClientSessionTest() { setDescription("Verifies if a transaction is committed while using read & write connections in same client session with cursored stream used in read."); } public void reset() { this.clientSession.release(); this.serverSession.logout(); } public void setup() { org.eclipse.persistence.sessions.Project proj = new org.eclipse.persistence.testing.models.employee.relational.EmployeeProject(); proj.setDatasourceLogin(getSession().getDatasourceLogin().clone()); // Set initial & min size of connection in pool to ZERO. this.serverSession = proj.createServerSession(0, 0, 1); this.serverSession.setSessionLog(getSession().getSessionLog()); this.serverSession.login(); this.clientSession = this.serverSession.acquireClientSession(); // Fetch a address Id from database. Employee emp = (Employee) getSession().readObject(Employee.class); this.addressId = emp.getAddress().getId().intValue(); } public void test() { clientSession.beginTransaction(); try { // Fetch Address object to update. ReadObjectQuery objquery = new ReadObjectQuery(); objquery.setReferenceClass(Address.class); ExpressionBuilder objquerybuilder = new ExpressionBuilder(); Expression objexpr = objquerybuilder.get("id").equal(this.addressId); objquery.setSelectionCriteria(objexpr); Address address = (Address) clientSession.executeQuery(objquery); // This seems to be a very bad test, it is corrupting the database state, // Changing the address is not required anyway as this test does no verify, // and since it is not using a UnitOfWork, the update will update verything anyway. //address.setStreet("Lawrence Street"); UpdateObjectQuery updateQuery = new UpdateObjectQuery(); updateQuery.setObject(address); clientSession.executeQuery(updateQuery); ReadAllQuery query = new ReadAllQuery(); query.setReferenceClass(Employee.class); query.useCursoredStream(1, 1); CursoredStream stream = (CursoredStream)clientSession.executeQuery(query); Object result = null; while (stream.hasNext()) { result = stream.next(); } clientSession.commitTransaction(); } catch(Exception ex) { caughtException = ex; } finally { try { clientSession.rollbackTransaction(); } catch (Exception ex) { // ignore } } } public void verify() { if (caughtException == null) { return; } if (caughtException instanceof DatabaseException) { throw new TestErrorException("incorrect if the exception is thrown due to a closed connection"); } } }
package com.excilys.liferay.gatling; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletException; import javax.portlet.ReadOnlyException; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.portlet.ResourceRequest; import javax.portlet.ResourceResponse; import javax.portlet.ValidatorException; import com.excilys.liferay.gatling.exception.EmptySimulation; import com.excilys.liferay.gatling.model.Request; import com.excilys.liferay.gatling.model.Scenario; import com.excilys.liferay.gatling.model.Simulation; import com.excilys.liferay.gatling.mustache.ScriptGeneratorGatling; import com.excilys.liferay.gatling.service.RequestLocalServiceUtil; import com.excilys.liferay.gatling.service.ScenarioLocalServiceUtil; import com.excilys.liferay.gatling.service.SimulationLocalServiceUtil; import com.excilys.liferay.gatling.util.DisplayItem; import com.excilys.liferay.gatling.util.DisplayItemUtil; import com.excilys.liferay.gatling.util.GatlingUtil; import com.github.mustachejava.DefaultMustacheFactory; import com.github.mustachejava.Mustache; import com.github.mustachejava.MustacheFactory; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.servlet.HttpHeaders; import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.portal.kernel.util.WebKeys; import com.liferay.portal.model.Group; import com.liferay.portal.model.Layout; import com.liferay.portal.model.PortletPreferences; import com.liferay.portal.service.GroupLocalServiceUtil; import com.liferay.portal.service.LayoutLocalServiceUtil; import com.liferay.portal.theme.ThemeDisplay; import com.liferay.util.bridges.mvc.MVCPortlet; /** * Portlet implementation class GatlingPortlet. */ public class GatlingPortlet extends MVCPortlet { /** * attribute mustacheFoctory. */ private MustacheFactory mf = new DefaultMustacheFactory(); /** * logging. */ private static final Log LOG = LogFactoryUtil.getLog(GatlingPortlet.class); /** * pages of portlet. */ protected String jspListSimulation, jspEditSimulation, jspEditScenario, jspFormFirstScenario, jspHelp; /** * get all name page * @throws PortletException */ @Override public void init() throws PortletException { jspListSimulation = getInitParameter("list-simulation-jsp"); jspEditSimulation = getInitParameter("edit-simulation-jsp"); jspEditScenario = getInitParameter("edit-scenario-jsp"); jspFormFirstScenario = getInitParameter("form-first-scenario-jsp"); jspHelp = getInitParameter("help-jsp"); super.init(); } /** * Adds a new Simulation to the database. * * @param request * @param response * @throws Exception */ public void addSimulation(final ActionRequest request, final ActionResponse response) throws Exception { Simulation simulation = SimulationLocalServiceUtil.addSimulationFromRequest(request); if (simulation != null) { response.setRenderParameter("simulationId", Long.toString(simulation.getSimulation_id())); // If new simulation the redirect to add First scenario page else edit simulation page LOG.info("Simulation added"); response.setRenderParameter("page", jspEditSimulation); } else { LOG.debug("Simulation fails to add"); response.setRenderParameter("page", jspListSimulation); } } /** * edit simulation method * * @param request * @param response * @throws Exception */ public void editSimulation(ActionRequest request, ActionResponse response) throws Exception { long simulationId = ParamUtil.getLong(request, "simulationId"); LOG.info("edit Simulation with id : " + simulationId); Simulation simulation = SimulationLocalServiceUtil.getSimulation(simulationId); simulation.setName(ParamUtil.getString(request, "simulationName")); String variable = GatlingUtil.createVariableName("Simulation", GatlingUtil.createVariableName("simulation", simulation.getName())); simulation.setVariableName(variable); SimulationLocalServiceUtil.updateSimulation(simulation); response.setRenderParameter("simulationId", Long.toString(simulationId)); response.setRenderParameter("page", jspEditSimulation); } /** * remove simulation method * * @param request * @param response * @throws Exception */ public void removeSimulation(ActionRequest request, ActionResponse response) throws Exception { long simulationId = ParamUtil.getLong(request, "simulationId"); if (LOG.isDebugEnabled()) { LOG.debug("remove Simulation with id : " + simulationId); } SimulationLocalServiceUtil.removeSimulationCascade(simulationId); response.setRenderParameter("page", jspListSimulation); } /** * Add a new Scenario to the database. * @param request * @param response * @throws Exception */ public void addScenario(final ActionRequest request, final ActionResponse response) throws Exception { Scenario scenario = ScenarioLocalServiceUtil.addScenarioFromRequest(request); String first = ParamUtil.getString(request, "first"); if (scenario != null) { // redirect to editScenario response.setRenderParameter("scenarioId", Long.toString(scenario.getScenario_id())); response.setRenderParameter("page", jspEditScenario); } else { response.setRenderParameter("simulationId", Long.toString(ParamUtil.getLong(request, "simulationId"))); response.setRenderParameter("page", !first.equals("") ? jspFormFirstScenario : jspEditSimulation); response.setRenderParameter("page", jspEditSimulation); } } /** * edit scenario. * * @param request * @param response * @throws SystemException * @throws PortalException */ public void editScenario(final ActionRequest request, final ActionResponse response) throws SystemException, PortalException { LOG.debug("edit scenario controler"); Scenario scenario = ScenarioLocalServiceUtil.editScenarioFromRequest(request); response.setRenderParameter("page", scenario != null ? jspEditSimulation : jspListSimulation); if (scenario != null) { response.setRenderParameter("simulationId", Long.toString(scenario.getSimulation_id())); } } /** * Remove scenario from database. * @param request * @param response * @throws PortalException * @throws SystemException */ public void removeScenario(final ActionRequest request, final ActionResponse response) throws PortalException, SystemException { long scenarioId = ParamUtil.getLong(request, "scenarioId"); long simulationId = ParamUtil.getLong(request, "simulationId"); if (LOG.isDebugEnabled()){ LOG.debug("remove Scenario with id : " + scenarioId); } // cascade delete ScenarioLocalServiceUtil.removeByIdCascade(scenarioId); response.setRenderParameter("simulationId", Long.toString(simulationId)); response.setRenderParameter("page", jspEditSimulation); } /** * Remove request from database. * @param request * @param response * @throws PortalException * @throws SystemException */ public void removeRequest(final ActionRequest request, final ActionResponse response) throws PortalException, SystemException { long requestId = Long.parseLong(request.getParameter("requestId")); RequestLocalServiceUtil.deleteRequest(requestId); LOG.debug("request deleted succefully "); } /** * get the scenario state, if completed or not yet. * @param scenario * @return */ private int scenarioState(Scenario scenario) { try { int count = RequestLocalServiceUtil.countByScenarioIdAndUsed(scenario.getScenario_id()); if (count != 0 && scenario.getDuration() != 0 && scenario.getUsers_per_seconds() != 0) { // completed scenario = case if all minimal information are // completed return 2; } else if (count != 0 && (scenario.getDuration() == 0 || scenario.getUsers_per_seconds() == 0)) { // incomplete scenario = case if one or more information detail of // scenario are not completed but there is request selected return 1; } } catch (SystemException e) { if (LOG.isErrorEnabled()){ LOG.error("enable to determine Scenario state " + e.getMessage()); } } // case if not request selected to that scenario = empty scenario return 0; } /** * get the simulation state, if all scenario are completed or not yet. * @param simulation * @return */ public int simulationState(final Simulation simulation) { try { List<Scenario> scenariosList = ScenarioLocalServiceUtil.findBySimulationId(simulation.getSimulation_id()); int checkNumberCompleted = 0; for (Scenario scenario : scenariosList) { if (scenarioState(scenario) == 2) { checkNumberCompleted++; } } if ((checkNumberCompleted == 0) || (scenariosList.size() == 0)) { //if no one scenario is completed = simulation empty return 0; } else if (checkNumberCompleted == scenariosList.size()) { //if all scenario completed = simulation complited return 2; } else { //other case = simulation incompleted return 1; } } catch (SystemException e) { if (LOG.isErrorEnabled()) { LOG.error("enable to determine Simulation state " + e.getMessage()); } return 0; } } /** * View method : redirect to requested page and send necessary parameters. */ @Override public void doView(final RenderRequest renderRequest, final RenderResponse renderResponse) throws IOException, PortletException { /* get the path for next jsp or by default jspListSimulation */ String page = ParamUtil.get(renderRequest, "page", jspListSimulation); //view.jsp => list of the simulations if (page.equals(jspListSimulation)) { LOG.debug("DoView : List Simulation"); List<Simulation> simulationList = new ArrayList<Simulation>(); Map<Simulation, Integer[]> simulationMap = new HashMap<Simulation, Integer[]>(); try { simulationList = SimulationLocalServiceUtil.getSimulations(0, SimulationLocalServiceUtil.getSimulationsCount()); for (Simulation simulation : simulationList) { Integer[] simulationInfos = new Integer[2]; simulationInfos[0] = ScenarioLocalServiceUtil.countBySimulationId(simulation.getSimulation_id()); simulationInfos[1] = simulationState(simulation); simulationMap.put(simulation, simulationInfos); } } catch (SystemException e) { throw new RuntimeException("error with getSimulation with localServiceUtil " + e.getMessage()); } String JSListName = GatlingUtil.createJSListOfSimulationName(simulationList); final javax.portlet.PortletPreferences prefs = renderRequest.getPreferences(); String gatlingVersionString; gatlingVersionString = prefs.getValue("gatlingVersion", null); renderRequest.setAttribute("gatlingVersion", gatlingVersionString); renderRequest.setAttribute("listOfSimulationName", JSListName); renderRequest.setAttribute("listSimulation", simulationList); renderRequest.setAttribute("MapSimulation", simulationMap); } else if (page.equals(jspEditSimulation) || page.equals(jspFormFirstScenario)) { /* * Edit simulation, get and send scenarios list to jsp page */ LOG.debug("DoView : Edit Simulation"); Long id = (Long) ParamUtil.getLong(renderRequest, "simulationId"); if(id==null) throw new NullPointerException("simulation id is null"); Simulation simulation; try { simulation = SimulationLocalServiceUtil.getSimulation(id); int scenarioListSize = ScenarioLocalServiceUtil.countBySimulationId(simulation.getSimulation_id()); renderRequest.setAttribute("simulation", simulation); // If empty go to form first scenario if(scenarioListSize == 0) throw new EmptySimulation(); // List of Scenario List<Scenario> scenarioList = ScenarioLocalServiceUtil.findBySimulationId(simulation.getSimulation_id()); // map <scenario, scenarioInfo> Map<Scenario, Number[]> scenariosMap = new HashMap<Scenario, Number[]>(); for (Scenario scenario : scenarioList) { Number[] info = new Number[3]; info[2] = scenarioState(scenario); info[0] = RequestLocalServiceUtil.countByScenarioIdAndUsed(scenario.getScenario_id()); info[1] = RequestLocalServiceUtil.countByScenarioId(scenario.getScenario_id()); scenariosMap.put(scenario, info); } String JSListName = GatlingUtil.createJSListOfScenarioName(scenarioList); renderRequest.setAttribute("listOfScenarioName", JSListName); /* * get list of simulation (for edit name) */ List<Simulation> listSimulations = SimulationLocalServiceUtil.getSimulations(0, SimulationLocalServiceUtil.getSimulationsCount()); String JSListSimName = GatlingUtil.createJSListOfSimulationName(listSimulations); renderRequest.setAttribute("listOfSimulationName", JSListSimName); renderRequest.setAttribute("listScenario", scenarioList); renderRequest.setAttribute("MapScenario", scenariosMap); } catch (SystemException | PortalException e) { throw new RuntimeException("error with get scenario list with localServiceUtil " + e.getMessage()); } catch (EmptySimulation e) { LOG.info("Empty simulation ... redirect"); page = jspFormFirstScenario; } // List of Sites List<Group> listGroups = GatlingUtil.getListOfSites(); renderRequest.setAttribute("listGroup", listGroups); }else if (page.equals(jspEditScenario)) { /* * Edit scenario -> request list send to jsp page */ LOG.debug("DoView : Edit Scenario"); if (ParamUtil.getLong(renderRequest, "scenarioId") == 0) { throw new NullPointerException("scenario id is null"); } try { // get scenario Scenario scenario = ScenarioLocalServiceUtil.getScenario(ParamUtil.getLong(renderRequest, "scenarioId")); Simulation simulation = SimulationLocalServiceUtil.getSimulation(scenario.getSimulation_id()); //update friendlyUrl of site if changed String oldFriendlyURL = scenario.getUrl_site(); final ThemeDisplay themeDisplay = (ThemeDisplay)renderRequest.getAttribute(WebKeys.THEME_DISPLAY); String currentFriendlyURL = GroupLocalServiceUtil.fetchGroup(scenario.getGroup_id()).getIconURL(themeDisplay); StringBuilder sb = new StringBuilder(currentFriendlyURL.split("/")[0]); sb.append("//").append(currentFriendlyURL.split("/")[2]).append("/web").append(GroupLocalServiceUtil.fetchGroup(scenario.getGroup_id()).getFriendlyURL()); currentFriendlyURL = sb.toString(); if (! oldFriendlyURL.equals(currentFriendlyURL)) { //update site url scenario.setUrl_site(currentFriendlyURL); ScenarioLocalServiceUtil.updateScenario(scenario); } //get public layout list long groupId = scenario.getGroup_id(); List<Layout> listPublicLayouts = LayoutLocalServiceUtil.getLayouts(groupId, false, 0); //get private layout list List<Layout> listPrivateLayouts = LayoutLocalServiceUtil.getLayouts(groupId, true, 0); //get site name String siteName = GroupLocalServiceUtil.getGroup(groupId).getName(); //create DisplayLayoutList with actuel layout of the site and old layout added from requests List<DisplayItem> displayLayoutList = new ArrayList<DisplayItem>(); DisplayItemUtil.addLayoutToDisplayItemList(displayLayoutList, listPublicLayouts); DisplayItemUtil.addLayoutToDisplayItemList(displayLayoutList, listPrivateLayouts ); //get list of request to add the old page to DisplayLayout List<Request> listRequests = RequestLocalServiceUtil.findByScenarioId(ParamUtil.get(renderRequest, "scenarioId", 0)); //Merge Layout and Request in DisplayLayout List displayLayoutList = DisplayItemUtil.addRequestToDisplayItemList(displayLayoutList, listRequests); // Get list of used names List<Scenario> scenariolist = ScenarioLocalServiceUtil.getScenarios(0, ScenarioLocalServiceUtil.getScenariosCount()); String JSListName = GatlingUtil.createJSListOfScenarioName(scenariolist); //add private and public url of site String publicURL = scenario.getUrl_site(); /* * create header list */ String[] headerList = new String[] {simulation.getName(), scenario.getName(), siteName}; renderRequest.setAttribute("headerList", headerList); //add request parameters renderRequest.setAttribute("scenario", scenario); renderRequest.setAttribute("listPages", displayLayoutList); renderRequest.setAttribute("siteName", siteName); renderRequest.setAttribute("publicURL", publicURL); renderRequest.setAttribute("listOfScenarioName", JSListName); } catch (SystemException | PortalException e) { throw new RuntimeException("connot get layout list: " + e.getMessage()); } } /* redirect to jsp page */ include(page, renderRequest, renderResponse); } @Override public void serveResource(final ResourceRequest request, final ResourceResponse response) { /* * Get template from version */ int gatlingVersion = ParamUtil.getInteger(request, "gatlingVersion"); //add user preference final PortletPreferences prefs = (PortletPreferences) request.getPreferences(); try { ((javax.portlet.PortletPreferences) prefs).setValue("gatlingVersion", Integer.toString(gatlingVersion)); ((javax.portlet.PortletPreferences) prefs).store(); } catch (ReadOnlyException | ValidatorException | IOException e) { throw new RuntimeException("connot add user preferences for gatling version " + e.getMessage()); } //scripting Gatling String template; switch (gatlingVersion) { case 1: template = "resources/templateGatling1.5.mustache"; break; case 2: template = "resources/templateGatling2.0.M3a.mustache"; break; case 3: template = "resources/templateGatling2.0.RC2.mustache"; break; default: template = "resources/templateGatling2.0.RC2.mustache"; break; } /* * Get simulations ids */ long[] simulationsIds = ParamUtil.getLongValues(request, "export"); Simulation simulation; Date date = new Date(); Mustache mustache = mf.compile(template); if (simulationsIds.length > 1) { response.setContentType("application/zip"); response.addProperty("Content-Disposition", "attachment; filename = GatlingSimulations" + date.getTime() + ".zip"); try { ZipOutputStream zipOutputStream = new ZipOutputStream(response.getPortletOutputStream()); for (long id : simulationsIds) { if (id > 0) { simulation = SimulationLocalServiceUtil.getSimulation(id); zipOutputStream.putNextEntry(new ZipEntry("Simulation" + simulation.getName() + date.getTime() + ".scala")); mustache.execute(new PrintWriter(zipOutputStream), new ScriptGeneratorGatling(id)).flush(); zipOutputStream.closeEntry(); } } zipOutputStream.close(); } catch (Exception e) { throw new RuntimeException("cannot export zip for scenario(s) " + e.getMessage()); } } else if (simulationsIds.length == 1 && simulationsIds[0] > 0) { //create and export only one file with scenario script for this simulation id response.setContentType("application/x-wais-source"); try { simulation = SimulationLocalServiceUtil.getSimulation(simulationsIds[0]); response.addProperty("Content-Disposition", "attachment; filename=Simulation" + simulation.getName() + date.getTime() + ".scala"); OutputStream out = response.getPortletOutputStream(); mustache.execute(new PrintWriter(out), new ScriptGeneratorGatling(simulationsIds[0])).flush(); out.close(); } catch (Exception e) { throw new RuntimeException("cannot export script file " + e.getMessage()); } } else { //if no one valide simulation id received then error throw new NullPointerException("nothing to export"); } response.addProperty(HttpHeaders.CACHE_CONTROL, "max-age=3600, must-revalidate"); } }
package org.example; import javax.ejb.ActivationConfigProperty; import javax.ejb.MessageDriven; import io.vertx.core.eventbus.Message; import io.vertx.resourceadapter.inflow.VertxListener; import org.jboss.ejb3.annotation.ResourceAdapter; @MessageDriven(name = "VertxMonitor", messageListenerInterface = VertxListener.class, activationConfig = { @ActivationConfigProperty(propertyName = "address", propertyValue = "tacos"), @ActivationConfigProperty(propertyName = "clusterHost", propertyValue = "localhost"), @ActivationConfigProperty(propertyName = "clusterPort", propertyValue = "0"), }) @ResourceAdapter("vertx-ra") public class MyListener implements VertxListener{ @Override public <String> void onMessage(Message<String> message) { System.out.println("MESSAGE: "+message.body()); } }
package gov.nih.nci.cacore.workbench.common; /** * Constants used in the caCORE Workbench Portal * * @author <A HREF="MAILTO:dumitrud@mail.nih.gov">Daniel Dumitru </A> * @author <A HREF="MAILTO:patelsat@mail.nih.gov">Satish Patel </A> */ public abstract class CacoreWorkbenchConstants { // Workbench specific constants public static final String WORKBENCH_VERSION_PROPERTY = "cacore.workbench.version"; public static final String WORKBENCH_ENGINE_PROPERTIES = "cacore.workbench.engine.properties"; public static final String WORKBENCH_HELP_URL = "cacore.workbench.help.url"; public static final String WORKBENCH_TOOLS_SITE_URL = "cacore.workbench.tools.site.url"; public static final String SDK_GUIDE_URL = "cacore.sdk.programmers.guide"; public static final String WORKBENCH_GUIDE_URL = "cacore.workbench.user.guide"; //Create Grid Service Workflow public static final String LAUNCH_INTRODUCE_URL = "cacore.workbench.launch.introduce.url"; //Create UML Model Workflow public static final String LAUNCH_ARGO_UML_WEB_START_URL = "cacore.workbench.launch.argo.uml.web.start.url"; public static final String DOWNLOAD_ENTERPRISE_ARCHITECT_URL = "cacore.workbench.download.ea.url"; //Semantic Integration Workflow public static final String LAUNCH_SIW_URL = "cacore.workbench.launch.siw.url"; public static final String LAUNCH_CDE_BROWSER_URL = "cacore.workbench.launch.cde.browser.url"; public static final String LAUNCH_UML_MODEL_BROWSER_URL = "cacore.workbench.launch.uml.model.browser.url"; public static final String LAUNCH_CDE_CURATION_TOOL_URL = "cacore.workbench.launch.cde.curation.tool.url"; //Model Mapping Workflow public static final String LAUNCH_CAADAPTER_URL = "cacore.workbench.launch.caadapter.url"; private CacoreWorkbenchConstants() { // prevents instantiation } }
package com.azure.messaging.eventhubs.implementation; import com.azure.core.amqp.AmqpEndpointState; import com.azure.core.amqp.AmqpRetryPolicy; import com.azure.core.amqp.implementation.AmqpReceiveLink; import com.azure.core.util.logging.ClientLogger; import org.apache.qpid.proton.message.Message; import org.reactivestreams.Subscription; import reactor.core.CoreSubscriber; import reactor.core.Disposable; import reactor.core.Disposables; import reactor.core.Exceptions; import reactor.core.publisher.FluxProcessor; import reactor.core.publisher.Mono; import reactor.core.publisher.Operators; import java.time.Duration; import java.util.Deque; import java.util.Objects; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLongFieldUpdater; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; /** * Processes AMQP receive links into a stream of AMQP messages. */ public class AmqpReceiveLinkProcessor extends FluxProcessor<AmqpReceiveLink, Message> implements Subscription { private final ClientLogger logger = new ClientLogger(AmqpReceiveLinkProcessor.class); private final Object lock = new Object(); private final AtomicBoolean isTerminated = new AtomicBoolean(); private final AtomicInteger retryAttempts = new AtomicInteger(); private final Deque<Message> messageQueue = new ConcurrentLinkedDeque<>(); private final AtomicBoolean hasFirstLink = new AtomicBoolean(); private final AtomicBoolean linkCreditsAdded = new AtomicBoolean(); private final AtomicReference<CoreSubscriber<? super Message>> downstream = new AtomicReference<>(); private final AtomicInteger wip = new AtomicInteger(); private final int prefetch; private final AmqpRetryPolicy retryPolicy; private final Disposable parentConnection; private volatile Throwable lastError; private volatile boolean isCancelled; private volatile AmqpReceiveLink currentLink; private volatile Disposable currentLinkSubscriptions; private volatile Disposable retrySubscription; // Opting to use AtomicReferenceFieldUpdater because Project Reactor provides utility methods that calculates // backpressure requests, sets the upstream correctly, and reports its state. private volatile Subscription upstream; private static final AtomicReferenceFieldUpdater<AmqpReceiveLinkProcessor, Subscription> UPSTREAM = AtomicReferenceFieldUpdater.newUpdater(AmqpReceiveLinkProcessor.class, Subscription.class, "upstream"); private volatile long requested; private static final AtomicLongFieldUpdater<AmqpReceiveLinkProcessor> REQUESTED = AtomicLongFieldUpdater.newUpdater(AmqpReceiveLinkProcessor.class, "requested"); public AmqpReceiveLinkProcessor(int prefetch, AmqpRetryPolicy retryPolicy, Disposable parentConnection) { this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null."); this.parentConnection = Objects.requireNonNull(parentConnection, "'parentConnection' cannot be null."); if (prefetch < 0) { throw logger.logExceptionAsError(new IllegalArgumentException("'prefetch' cannot be less than 0.")); } this.prefetch = prefetch; } /** * Gets the error associated with this processor. * * @return Error associated with this processor. {@code null} if there is no error. */ @Override public Throwable getError() { return lastError; } /** * Gets whether or not the processor is terminated. * * @return {@code true} if the processor has terminated; false otherwise. */ @Override public boolean isTerminated() { return isTerminated.get() || isCancelled; } /** * When a subscription is obtained from upstream publisher. * * @param subscription Subscription to upstream publisher. */ @Override public void onSubscribe(Subscription subscription) { Objects.requireNonNull(subscription, "'subscription' cannot be null"); if (!Operators.setOnce(UPSTREAM, this, subscription)) { throw logger.logExceptionAsError(new IllegalStateException("Cannot set upstream twice.")); } requestUpstream(); } @Override public int getPrefetch() { return prefetch; } /** * When the next AMQP link is fetched. * * @param next The next AMQP receive link. */ @Override public void onNext(AmqpReceiveLink next) { Objects.requireNonNull(next, "'next' cannot be null."); if (isTerminated()) { logger.warning("linkName[{}] entityPath[{}]. Got another link when we have already terminated processor.", next.getLinkName(), next.getEntityPath()); Operators.onNextDropped(next, currentContext()); return; } final String linkName = next.getLinkName(); final String entityPath = next.getEntityPath(); logger.info("linkName[{}] entityPath[{}]. Setting next AMQP receive link.", linkName, entityPath); final AmqpReceiveLink oldChannel; final Disposable oldSubscription; synchronized (lock) { oldChannel = currentLink; oldSubscription = currentLinkSubscriptions; currentLink = next; // The first time, add the prefetch to the link as credits. if (!hasFirstLink.getAndSet(true)) { linkCreditsAdded.set(true); next.addCredits(prefetch); } next.setEmptyCreditListener(() -> getCreditsToAdd()); currentLinkSubscriptions = Disposables.composite( next.getEndpointStates().subscribe( state -> { // Connection was successfully opened, we can reset the retry interval. if (state == AmqpEndpointState.ACTIVE) { retryAttempts.set(0); } }, error -> { currentLink = null; logger.warning("linkName[{}] entityPath[{}]. Error occurred in link.", linkName, entityPath); onError(error); }, () -> { if (parentConnection.isDisposed() || isTerminated() || upstream == Operators.cancelledSubscription()) { logger.info("Terminal state reached. Disposing of link processor."); dispose(); } else { logger.info("Receive link endpoint states are closed. Requesting another."); final AmqpReceiveLink existing = currentLink; currentLink = null; if (existing != null) { existing.dispose(); } requestUpstream(); } }), next.receive().subscribe(message -> { messageQueue.add(message); drain(); })); } if (oldChannel != null) { oldChannel.dispose(); } if (oldSubscription != null) { oldSubscription.dispose(); } } @Override public void subscribe(CoreSubscriber<? super Message> actual) { Objects.requireNonNull(actual, "'actual' cannot be null."); final boolean terminateSubscriber = isTerminated() || (currentLink == null && upstream == Operators.cancelledSubscription()); if (isTerminated()) { final AmqpReceiveLink link = currentLink; final String linkName = link != null ? link.getLinkName() : "n/a"; final String entityPath = link != null ? link.getEntityPath() : "n/a"; logger.info("linkName[{}] entityPath[{}]. AmqpReceiveLink is already terminated.", linkName, entityPath); } else if (currentLink == null && upstream == Operators.cancelledSubscription()) { logger.info("There is no current link and upstream is terminated."); } if (terminateSubscriber) { actual.onSubscribe(Operators.emptySubscription()); if (hasError()) { actual.onError(lastError); } else { actual.onComplete(); } return; } if (downstream.compareAndSet(null, actual)) { actual.onSubscribe(this); drain(); } else { Operators.error(actual, logger.logExceptionAsError(new IllegalStateException( "There is already one downstream subscriber.'"))); } } /** * When an error occurs from the upstream publisher. If the {@code throwable} is a transient failure, another AMQP * element is requested if the {@link AmqpRetryPolicy} allows. Otherwise, the processor closes. * * @param throwable Error that occurred in upstream publisher. */ @Override public void onError(Throwable throwable) { Objects.requireNonNull(throwable, "'throwable' is required."); if (isTerminated() || isCancelled) { logger.info("AmqpReceiveLinkProcessor is terminated. Cannot process another error.", throwable); Operators.onErrorDropped(throwable, currentContext()); return; } final int attempt = retryAttempts.incrementAndGet(); final Duration retryInterval = retryPolicy.calculateRetryDelay(throwable, attempt); final AmqpReceiveLink link = currentLink; final String linkName = link != null ? link.getLinkName() : "n/a"; final String entityPath = link != null ? link.getEntityPath() : "n/a"; if (retryInterval != null && !parentConnection.isDisposed() && upstream != Operators.cancelledSubscription()) { logger.warning("linkName[{}] entityPath[{}]. Transient error occurred. Attempt: {}. Retrying after {} ms.", linkName, entityPath, attempt, retryInterval.toMillis(), throwable); retrySubscription = Mono.delay(retryInterval).subscribe(i -> requestUpstream()); return; } if (parentConnection.isDisposed()) { logger.info("Parent connection is disposed. Not reopening on error."); } logger.warning("linkName[{}] entityPath[{}]. Non-retryable error occurred in AMQP receive link.", linkName, entityPath, throwable); lastError = throwable; isTerminated.set(true); final CoreSubscriber<? super Message> subscriber = downstream.get(); if (subscriber != null) { subscriber.onError(throwable); } onDispose(); } /** * When the upstream publisher has no more items to emit. */ @Override public void onComplete() { this.upstream = Operators.cancelledSubscription(); } @Override public void dispose() { if (isTerminated.getAndSet(true)) { return; } drain(); onDispose(); } /** * When downstream subscriber makes a back-pressure request. */ @Override public void request(long request) { if (!Operators.validate(request)) { logger.warning("Invalid request: {}", request); return; } Operators.addCap(REQUESTED, this, request); final AmqpReceiveLink link = currentLink; if (link != null && !linkCreditsAdded.getAndSet(true)) { int credits = getCreditsToAdd(); logger.verbose("Link credits not yet added. Adding: {}", credits); link.addCredits(credits); } drain(); } /** * When downstream subscriber cancels their subscription. */ @Override public void cancel() { if (isCancelled) { return; } isCancelled = true; drain(); } /** * Requests another receive link from upstream. */ private void requestUpstream() { if (isTerminated()) { logger.info("Processor is terminated. Not requesting another link."); return; } else if (upstream == null) { logger.info("There is no upstream. Not requesting another link."); return; } else if (upstream == Operators.cancelledSubscription()) { logger.info("Upstream is cancelled or complete. Not requesting another link."); return; } synchronized (lock) { if (currentLink != null) { logger.info("Current link exists. Not requesting another link."); return; } } logger.info("Requesting a new AmqpReceiveLink from upstream."); upstream.request(1L); } private void onDispose() { if (retrySubscription != null && !retrySubscription.isDisposed()) { retrySubscription.dispose(); } if (currentLink != null) { currentLink.dispose(); } currentLink = null; if (currentLinkSubscriptions != null) { currentLinkSubscriptions.dispose(); } Operators.onDiscardQueueWithClear(messageQueue, currentContext(), null); } private void drain() { // If someone is already in this loop, then we are already clearing the queue. if (!wip.compareAndSet(0, 1)) { return; } try { drainQueue(); } finally { if (wip.decrementAndGet() != 0) { logger.warning("There is another worker in drainLoop. But there should only be 1 worker."); } } } private void drainQueue() { final CoreSubscriber<? super Message> subscriber = downstream.get(); if (subscriber == null || checkAndSetTerminated()) { return; } long numberRequested = requested; boolean isEmpty = messageQueue.isEmpty(); while (numberRequested != 0L && !isEmpty) { if (checkAndSetTerminated()) { break; } long numberEmitted = 0L; while (numberRequested != numberEmitted) { if (isEmpty && checkAndSetTerminated()) { break; } Message message = messageQueue.poll(); if (message == null) { break; } if (isCancelled) { Operators.onDiscard(message, subscriber.currentContext()); Operators.onDiscardQueueWithClear(messageQueue, subscriber.currentContext(), null); return; } try { subscriber.onNext(message); } catch (Exception e) { logger.error("Exception occurred while handling downstream onNext operation.", e); throw logger.logExceptionAsError(Exceptions.propagate( Operators.onOperatorError(upstream, e, message, subscriber.currentContext()))); } numberEmitted++; isEmpty = messageQueue.isEmpty(); } if (requested != Long.MAX_VALUE) { numberRequested = REQUESTED.addAndGet(this, -numberEmitted); } } } private boolean checkAndSetTerminated() { if (!isTerminated()) { return false; } final CoreSubscriber<? super Message> subscriber = downstream.get(); final Throwable error = lastError; if (error != null) { subscriber.onError(error); } else { subscriber.onComplete(); } if (currentLink != null) { currentLink.dispose(); } messageQueue.clear(); return true; } private int getCreditsToAdd() { final CoreSubscriber<? super Message> subscriber = downstream.get(); final long r = requested; if (subscriber == null || r == 0) { logger.verbose("Not adding credits. No downstream subscribers or items requested."); linkCreditsAdded.set(false); return 0; } linkCreditsAdded.set(true); // If there is no back pressure, always add 1. Otherwise, add whatever is requested. return r == Long.MAX_VALUE ? 1 : Long.valueOf(r).intValue(); } }
import java.io.*; import java.util.Arrays; import java.util.Random; /** * This class loads the file corpus.txt, reads the file line by line up to the nr of lines provided in args[0]. * Each line is processed according to a set of rules, and the resuls are written to ppCorpus.txt, line by line. * After next it reads the following lines args[0]+1 to args[0]+args[1] and preprocesses them for testing, * saving the results in testSentences.txt * * * @author Jasmin Suljkic */ public class CorpusPreprocessUK { /** * No arguments are taken in account. * Statically configured file corpus.txt is read and ppCorpus.txt as well as testSentences.txt is created and written to. * @param args -> X Y, (X: lines to for learning, Y: lines for testing) */ public static void main(String[] args) { //args[0] -> Amount of lines to preprocess for learning //args[1] -> Amount of lines to preprocess for testing String corpusStringPath = "corpus.txt"; String testSentenceStringPath = "testSentences"; String testSentencesCorrectionStringPath = "testSentencesCorrection"; // TODO Auto-generated method stub BufferedReader br; BufferedWriter bufferedWriterCorpus; BufferedWriter bufferedWriterTest; BufferedWriter bufferedWriterTestCorrection; StringBuffer sb = new StringBuffer(); StringBuffer sbt = new StringBuffer(); int nrLines=0; int toLearn = Integer.MAX_VALUE>>3; int toTest = Integer.MAX_VALUE>>3; if(args.length>=2) { toLearn = Integer.parseInt(args[0]); toTest = Integer.parseInt(args[1]); } try { //br = new BufferedReader(new FileReader("corpus.txt")); //br = new BufferedReader(new InputStreamReader(new FileInputStream("corpus.txt"), "UTF-8")); br = new BufferedReader(new InputStreamReader(new FileInputStream(corpusStringPath))); //bufferedWriterCorpus = new BufferedWriter(new FileWriter("ppCorpus.txt")); bufferedWriterCorpus = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("ppCorpus.txt"), "UTF-16BE")); //bufferedWriterTest = new BufferedWriter(new FileWriter("testSentences.txt")); //bufferedWriterTestCorrection = new BufferedWriter(new FileWriter("testScentencesCorrect.txt")); String line; char[] lc; //Go trough the corpus and count the amount of lines present while ((line=br.readLine()) != null) { nrLines++; } br.close(); if((toLearn+toTest)>nrLines){ System.err.println("Request invalid: Number of lines requested > nr of lines available in corpus.\nThere are "+nrLines+" number of lines."); System.err.println("toLearn = "+toLearn); System.err.println("toTest = "+toTest); return; } br=new BufferedReader(new FileReader("corpus.txt")); //Read a line from file (as long as there are lines in the file) //Process the line //Write the result to output file. int current = 0; boolean testing = false; OutputStreamWriter writeToTest[] = new OutputStreamWriter[1]; OutputStreamWriter writeToTestCorrection[] = new OutputStreamWriter[1]; for(int i = 0; i < writeToTest.length; i++) { writeToTest[i] = new OutputStreamWriter(new FileOutputStream(testSentenceStringPath+i+".txt"), "UTF-16BE"); writeToTestCorrection[i] = new OutputStreamWriter(new FileOutputStream(testSentencesCorrectionStringPath+i+".txt"), "UTF-16BE"); //writeToTest[i] = new OutputStreamWriter(new FileOutputStream("testSentences"+i+".txt")); //writeToTestCorrection[i] = new OutputStreamWriter(new FileOutputStream("testSentencesCorrection"+i+".txt")); } int corpusSentences = 0; int trainingSentences = 0; int index = 0; int length = 0; String buffer[] = new String[10]; while ((line=br.readLine()) != null) { line = line.toLowerCase().replaceAll("[-,]", "").replaceAll("( )*[.!?]+( )*", " .PERIOD ").replaceAll("( )+", " ").replaceAll("(.PERIOD )+", ".PERIOD ").trim(); //System.err.println(line); int really = line.split(" ").length; int previous = length; if(really>1) { length+=really; System.err.println(length); } if(length<=10) { buffer[index]=line; System.err.println(line); index++; } else if(length>=3&&previous<=10) { if(toLearn>corpusSentences) { bufferedWriterCorpus.write("START "); for(int i = 0; i < index; i++) { //System.err.println(buffer[i]); bufferedWriterCorpus.write(buffer[i]); System.err.println(buffer[i]); } System.err.println(); bufferedWriterCorpus.append(" ¿EOL"); //bufferedWriterCorpus.newLine(); corpusSentences++; } else if(trainingSentences<toTest) { writeToTestCorrection[0].write("START "); writeToTest[0].write("START "); for(int i = 0; i < index; i++) { writeToTestCorrection[0].write(buffer[i]); writeToTest[0].write(buffer[i].replaceAll("( )*.PERIOD( )*", " ")); } writeToTestCorrection[0].write(" ¿EOL"); writeToTestCorrection[0].write('\n'); writeToTest[0].write(" ¿EOL"); writeToTest[0].write('\n'); trainingSentences++; } else { break; } index = 0; length = 0; } else { index = 0; length = 0; } } br.close(); bufferedWriterCorpus.close(); //bufferedWriterTest.close(); System.err.println("Using encoding: "+writeToTest[0].getEncoding()); System.err.println(corpusSentences+" sentences in corpus."); System.err.println(trainingSentences+" sentences in training."); for(int k = 0; k < writeToTest.length; k++) { writeToTest[k].close(); writeToTestCorrection[k].close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
package fr.imie.cdi13.dav.test; public class B extends A { private String a = "test a"; @Override public AInterface function1(String value) { // new commentaire return new B(); } @Override public String toString() { return this.a + ' ' + super.toString(); } }
package ch.idsia.benchmark.tasks; import ch.idsia.tools.EvaluationInfo; import ch.idsia.tools.MarioAIOptions; import java.text.DecimalFormat; public class GamePlayTask extends BasicTask implements Task { private static final DecimalFormat df = new DecimalFormat(" private EvaluationInfo localEvaluationInfo; public GamePlayTask(MarioAIOptions marioAIOptions) { super(marioAIOptions); localEvaluationInfo = new EvaluationInfo(); localEvaluationInfo.setTaskName("GamePlayTask"); localEvaluationInfo.distancePassedCells = 0; localEvaluationInfo.distancePassedPhys = 0; localEvaluationInfo.flowersDevoured = 0; localEvaluationInfo.killsTotal = 0; localEvaluationInfo.killsByFire = 0; localEvaluationInfo.killsByShell = 0; localEvaluationInfo.killsByStomp = 0; localEvaluationInfo.marioMode = 0; localEvaluationInfo.marioStatus = 0; localEvaluationInfo.mushroomsDevoured = 0; localEvaluationInfo.coinsGained = 0; localEvaluationInfo.timeLeft = 0; localEvaluationInfo.timeSpent = 0; localEvaluationInfo.hiddenBlocksFound = 0; localEvaluationInfo.totalNumberOfCoins = 0; localEvaluationInfo.totalNumberOfCreatures = 0; localEvaluationInfo.totalNumberOfFlowers = 0; localEvaluationInfo.totalNumberOfMushrooms = 0; localEvaluationInfo.totalNumberOfHiddenBlocks = 0; localEvaluationInfo.collisionsWithCreatures = 0; localEvaluationInfo.levelLength = 0; } private void updateEvaluationInfo(EvaluationInfo evInfo) { localEvaluationInfo.distancePassedCells += evInfo.distancePassedCells; localEvaluationInfo.distancePassedPhys += evInfo.distancePassedPhys; localEvaluationInfo.flowersDevoured += evInfo.flowersDevoured; localEvaluationInfo.killsTotal += evInfo.killsTotal; localEvaluationInfo.killsByFire += evInfo.killsByFire; localEvaluationInfo.killsByShell += evInfo.killsByShell; localEvaluationInfo.killsByStomp += evInfo.killsByStomp; localEvaluationInfo.marioMode += evInfo.marioMode; localEvaluationInfo.marioStatus += evInfo.marioStatus; localEvaluationInfo.mushroomsDevoured += evInfo.mushroomsDevoured; localEvaluationInfo.coinsGained += evInfo.coinsGained; localEvaluationInfo.timeLeft += evInfo.timeLeft; localEvaluationInfo.timeSpent += evInfo.timeSpent; localEvaluationInfo.hiddenBlocksFound += evInfo.hiddenBlocksFound; localEvaluationInfo.totalNumberOfCoins += evInfo.totalNumberOfCoins; localEvaluationInfo.totalNumberOfCreatures += evInfo.totalNumberOfCreatures; localEvaluationInfo.totalNumberOfFlowers += evInfo.totalNumberOfFlowers; localEvaluationInfo.totalNumberOfMushrooms += evInfo.totalNumberOfMushrooms; localEvaluationInfo.totalNumberOfHiddenBlocks += evInfo.totalNumberOfHiddenBlocks; localEvaluationInfo.collisionsWithCreatures += evInfo.collisionsWithCreatures; localEvaluationInfo.levelLength += evInfo.levelLength; } public void doEpisodes(final int amount, final boolean verbose, final int repetitionsOfSingleEpisode) { for (int i = 0; i < amount; ++i) { options.setLevelLength((200 + (i * 128) + (options.getLevelRandSeed() % (i + 1))) % 512); options.setLevelType(i % 3); options.setLevelRandSeed(options.getLevelRandSeed() + i); options.setLevelDifficulty(i % 10); options.setGapsCount(i % 3 == 0); options.setCannonsCount(i % 3 != 0); options.setCoinsCount(i % 5 != 0); options.setBlocksCount(i % 4 != 0); options.setHiddenBlocksCount(i % 6 != 0); options.setDeadEndsCount(i % 10 == 0); options.setLevelLadder(i % 10 == 2); options.setFrozenCreatures(i % 3 == 1); this.reset(); this.runSingleEpisode(repetitionsOfSingleEpisode); updateEvaluationInfo(environment.getEvaluationInfo()); if (verbose) System.out.println(environment.getEvaluationInfoAsString()); } } public EvaluationInfo getEvaluationInfo() { return localEvaluationInfo; } public void printStatistics() { System.out.println("\n[MarioAI] ~ Evaluation Results for Task: " + localEvaluationInfo.getTaskName() + "\n Weighted Fitness : " + df.format(localEvaluationInfo.computeWeightedFitness()) + "\n Mario Status : " + localEvaluationInfo.marioStatus + "\n Mario Mode : " + localEvaluationInfo.marioMode + "\nCollisions with creatures : " + localEvaluationInfo.collisionsWithCreatures + "\n Passed (Cells, Phys) : " + localEvaluationInfo.distancePassedCells + " of " + localEvaluationInfo.levelLength + ", " + df.format(localEvaluationInfo.distancePassedPhys) + " of " + df.format(localEvaluationInfo.levelLength * 16) + " (" + localEvaluationInfo.distancePassedCells * 100 / localEvaluationInfo.levelLength + "% passed)" + "\n Time Spent(marioseconds) : " + localEvaluationInfo.timeSpent + "\n Time Left(marioseconds) : " + localEvaluationInfo.timeLeft + "\n Coins Gained : " + localEvaluationInfo.coinsGained + " of " + localEvaluationInfo.totalNumberOfCoins + " (" + localEvaluationInfo.coinsGained * 100 / (localEvaluationInfo.totalNumberOfCoins == 0 ? 1 : localEvaluationInfo.totalNumberOfCoins) + "% collected)" + "\n Hidden Blocks Found : " + localEvaluationInfo.hiddenBlocksFound + " of " + localEvaluationInfo.totalNumberOfHiddenBlocks + " (" + localEvaluationInfo.hiddenBlocksFound * 100 / (localEvaluationInfo.totalNumberOfHiddenBlocks == 0 ? 1 : localEvaluationInfo.totalNumberOfHiddenBlocks) + "% found)" + "\n Mushrooms Devoured : " + localEvaluationInfo.mushroomsDevoured + " of " + localEvaluationInfo.totalNumberOfMushrooms + " found (" + localEvaluationInfo.mushroomsDevoured * 100 / (localEvaluationInfo.totalNumberOfMushrooms == 0 ? 1 : localEvaluationInfo.totalNumberOfMushrooms) + "% collected)" + "\n Flowers Devoured : " + localEvaluationInfo.flowersDevoured + " of " + localEvaluationInfo.totalNumberOfFlowers + " found (" + localEvaluationInfo.flowersDevoured * 100 / (localEvaluationInfo.totalNumberOfFlowers == 0 ? 1 : localEvaluationInfo.totalNumberOfFlowers) + "% collected)" + "\n kills Total : " + localEvaluationInfo.killsTotal + " of " + localEvaluationInfo.totalNumberOfCreatures + " found (" + localEvaluationInfo.killsTotal * 100 / (localEvaluationInfo.totalNumberOfCreatures == 0 ? 1 : localEvaluationInfo.totalNumberOfCreatures) + "%)" + "\n kills By Fire : " + localEvaluationInfo.killsByFire + "\n kills By Shell : " + localEvaluationInfo.killsByShell + "\n kills By Stomp : " + localEvaluationInfo.killsByStomp); // System.out.println(localEvaluationInfo.toString()); // System.out.println("Mario status sum: " + localEvaluationInfo.marioStatus); // System.out.println("Mario mode sum: " + localEvaluationInfo.marioMode); } }
package ch.minipowerpc.emulator.ui; import java.awt.BorderLayout; import java.awt.Container; import java.util.Observable; import java.util.Observer; import javax.swing.JFrame; import javax.swing.UIManager; import ch.minipowerpc.emulator.Emulator; public class MainWindow extends JFrame implements Observer { private static final long serialVersionUID = 6829224920697585349L; private IEmulatorModel model; // UI controls private InstructionMemoryPanel instructionMemoryPanel; private DataMemoryPanel dataMemoryPanel; private EmulatorControlPanel emulatorControlPanel; private ControlUnitPanel controlUnitPanel; public MainWindow(IEmulatorModel model) { this.model = model; ((Observable)model).addObserver(this); initialize(); } private void initialize() { setTitle("MiniPowerPC emulator"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); try { // Set System L&F UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception ex) { } Container content = getContentPane(); // Program memory /* programMemory = new ProgramMemory(emulator); content.add(programMemory, BorderLayout.CENTER); */ instructionMemoryPanel = new InstructionMemoryPanel(model); content.add(instructionMemoryPanel, BorderLayout.CENTER); dataMemoryPanel = new DataMemoryPanel(model); content.add(dataMemoryPanel, BorderLayout.LINE_END); /* JButton button = new JButton("Toggle base"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { base = (base == 2) ? 10 : 2; programMemory.setBase(base); programMemory.setPosition(programMemory.getPosition() + 2); tableModel.setBase(base); tableModel.fireTableDataChanged(); } }); content.add(button, BorderLayout.PAGE_END); */ emulatorControlPanel = new EmulatorControlPanel(model); content.add(emulatorControlPanel, BorderLayout.PAGE_END); // Registers and so on controlUnitPanel = new ControlUnitPanel(model); content.add(controlUnitPanel, BorderLayout.LINE_START); update(null, null); setSize(950, 500); } @Override public void update(Observable o, Object arg) { instructionMemoryPanel.refresh(); dataMemoryPanel.refresh(); emulatorControlPanel.refresh(); controlUnitPanel.refresh(); } public static void main(String[] args) { if(args.length != 1) System.exit(-1); Emulator emulator = new Emulator(); // HACK: Change configuration for special Aufgabe4 if(args[0].equals("Aufgabe4")) { emulator.getConfiguration().setInstructionRangeTo((short)199); emulator.getConfiguration().setDataRangeFrom((short)200); emulator.getConfiguration().setDataRangeTo((short)299); } try { emulator.loadProgram(args[0]); emulator.loadMemory(args[0]); } catch(Exception ex) { System.out.println(ex.getMessage()); System.exit(-2); } MainWindow window = new MainWindow(new EmulatorModel(emulator)); window.setVisible(true); } }
package org.csstudio.alarm.diirt.datasource; import static org.diirt.util.concurrent.Executors.namedPool; import java.net.URI; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; import org.csstudio.alarm.beast.client.AlarmTreeItem; import org.csstudio.alarm.beast.client.AlarmTreePV; import org.csstudio.alarm.beast.ui.clientmodel.AlarmClientModel; import org.csstudio.alarm.beast.ui.clientmodel.AlarmClientModelConfigListener; import org.csstudio.alarm.beast.ui.clientmodel.AlarmClientModelListener; import org.diirt.datasource.ChannelHandler; import org.diirt.datasource.DataSource; import org.diirt.datasource.vtype.DataTypeSupport; import org.eclipse.core.runtime.Platform; /** * @author Kunal Shroff * */ public class BeastDataSource extends DataSource implements AlarmClientModelConfigListener { private static final Logger log = Logger.getLogger(BeastDataSource.class.getName()); private static final String PREF_QUALIFIER = "org.csstudio.alarm.diirt.datasource"; private static final String PREF_KEY_COMPOSITE = "composite.model.name"; private static final String PREF_DEFAULT_COMPOSITE_MODEL_NAME = "Composite"; // The model, activeAlarms and acknowledgedAlarms is shared by the entire // datasource, the benefit of does this at the datasource level instead of // in each channel is that they need to be computed only once and only a single // copy needs to be maintained. private AlarmClientModel model; private Map<String, List<Consumer>> channelConsumers = Collections.synchronizedMap(new HashMap<String, List<Consumer>>()); private Map<String, AlarmClientModel> models = Collections.synchronizedMap(new HashMap<String, AlarmClientModel>()); private AtomicInteger loaded; private AtomicInteger toLoad; private Executor executor = Executors.newScheduledThreadPool(4); private final ExecutorService exec = Executors.newSingleThreadExecutor(namedPool("RemoveChannel " + getClass().getSimpleName() + " Worker ")); private BeastTypeSupport typeSupport; private BeastDataSourceConfiguration configuration; private BeastAlarmClientModelListener modelListener; private CompositeAlarmClientModel compositeModel; static { // Install type support for the types it generates. DataTypeSupport.install(); } private class BeastAlarmClientModelListener implements AlarmClientModelListener{ private BeastDataSource parent; BeastAlarmClientModelListener(BeastDataSource parent) { this.parent = parent; } @Override public void newAlarmConfiguration(AlarmClientModel model) { log.config("beast datasource: new alarm configuration --- " + model); // new model loaded parent.loaded.incrementAndGet(); if (!parent.compositeModel.equals(model)) parent.compositeModel.addAlarmClientModel(model); if (parent.loaded.get() == parent.toLoad.get()) { parent.compositeModel.setAllLoaded(true); log.log(Level.FINE, "All models loaded - notifying Composite model listeners."); parent.compositeModel.compositeModelsLoaded(); } synchronized (parent.channelConsumers) { for (String channelName : parent.channelConsumers.keySet()) { BeastChannelHandler channel = (BeastChannelHandler) getChannels() .get(channelHandlerLookupName(channelName)); channel.reconnect(); } } notifyCompositeBeastChannelListeners(); } @Override public void serverTimeout(AlarmClientModel model) { log.warning("beast datasource: server timeout (server alive: " + model.isServerAlive() + ")"); synchronized (parent.channelConsumers) { for (String channelName : parent.channelConsumers.keySet()) { BeastChannelHandler channel = (BeastChannelHandler) getChannels() .get(channelHandlerLookupName(channelName)); // notify the ChannelHandler that we lost connection // (causes ConnectionChanged event + Listeners' PVReader.isConnected() will return the correct state) channel.connectionStateChanged(false); } } } @Override public void serverModeUpdate(AlarmClientModel model, boolean maintenance_mode) { log.fine("beast datasource: server mode update"); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void newAlarmState(AlarmClientModel alarmModel, AlarmTreePV pv, boolean parent_changed) { if (pv != null) { log.fine(pv.getPathName()); synchronized (parent.channelConsumers) { parent.channelConsumers.forEach((key, pathHandlers) -> { if (BeastTypeSupport.getStrippedChannelName(key).equals(pv.getPathName().substring(1)) || BeastTypeSupport.getStrippedChannelName(key).equals(pv.getName())) { if (pathHandlers != null) { for (Consumer consumer : pathHandlers) { consumer.accept(pv); } } } }); } // Notify parent nodes (regardless of parent_changed - because the parents' AlarmPVsCount) AlarmTreeItem parent = pv.getParent(); while (parent != null) { final String parentPath = parent.getPathName(); synchronized (this.parent.channelConsumers) { this.parent.channelConsumers.forEach((key, pathHandlers) -> { if (BeastTypeSupport.getStrippedChannelName(key).equals(parentPath.substring(1))) { if (pathHandlers != null) { for (Consumer consumer : pathHandlers) { try { consumer.accept(getState(parentPath)); } catch (Exception e) { e.printStackTrace(); } } } } }); } parent = parent.getParent(); } } else { // The AlarmClientModel has recovered from a disconnection or is notifying us that the first // messages have been received after initial connection. synchronized (parent.channelConsumers) { for (String channelName : parent.channelConsumers.keySet()) { BeastChannelHandler channel = (BeastChannelHandler) getChannels() .get(channelHandlerLookupName(channelName)); if (channel!=null) channel.reconnect(); // will send connection state + current AlarmTreeItem state } } } notifyCompositeBeastChannelListeners(); } private void notifyCompositeBeastChannelListeners() { synchronized (parent.channelConsumers) { final BeastChannelHandler compositeChannel = (BeastChannelHandler) getChannels() .get(channelHandlerLookupName(parent.compositeModel.getConfigurationName())); if (compositeChannel != null) { // there is an actual connection to the composite root log.fine("Sending message to the composite tree channel."); parent.compositeModel.getConfigTree().maximizeSeverity(); compositeChannel.accept(parent.compositeModel.getConfigTree()); } } } } public BeastDataSource(BeastDataSourceConfiguration configuration) { super(true); this.configuration = configuration; loaded = new AtomicInteger(0); toLoad = new AtomicInteger(-1); final String compositeModelName = Platform.getPreferencesService(). getString(PREF_QUALIFIER, PREF_KEY_COMPOSITE, PREF_DEFAULT_COMPOSITE_MODEL_NAME, null); log.log(Level.CONFIG, () -> String.format("Using '%s' as the composite alarm model name.", compositeModelName)); compositeModel = new CompositeAlarmClientModel(compositeModelName); compositeModel.registerWithClientModels(); // one global listener for all models modelListener = new BeastAlarmClientModelListener(this); try { // Create an instance to the AlarmClientModel final CompletableFuture<Void> future = CompletableFuture .supplyAsync(() -> initialize(configuration), executor) .thenAccept((model) -> { this.model = model; this.models.put(model.getConfigurationName(), model); this.model.addListener(modelListener); }); typeSupport = new BeastTypeSupport(); compositeModel.addListener(modelListener); } catch (Exception e) { e.printStackTrace(); } } private AlarmClientModel initialize(BeastDataSourceConfiguration configuration) { AlarmClientModel alarmModel; try { if (configuration.getConfigName() != null && !configuration.getConfigName().isEmpty()) { alarmModel = AlarmClientModel.getInstance(configuration.getConfigName(), this); } else { alarmModel = AlarmClientModel.getInstance(this); } return alarmModel; } catch (Exception e) { return null; } } @Override protected ChannelHandler createChannel(String channelName) { return new BeastChannelHandler(channelName, BeastTypeSupport.getChannelType(channelName), this); } @Override public void close() { super.close(); if (!models.isEmpty()) { for (final AlarmClientModel aModel : models.values()) aModel.release(); } else { model.release(); } } /** * Override of default channelHandlerLookupName. * This implementation makes a leading and trailing forward slash ("/") optional. * All four of these will resolve to the same channel: * "/demo/test/", "/demo/test", "demo/test/" & "demo/test". * * @see org.diirt.datasource.DataSource#channelHandlerLookupName(java.lang.String) */ @Override protected String channelHandlerLookupName(String channelName) { String channel = channelName; if (channel != null && !channel.equals("/") && !channel.isEmpty()) { if (channel.endsWith("/")) channel = channel.substring(0, channel.length() - 1); if (channel.startsWith("/")) channel = channel.substring(1); } return channel; } @SuppressWarnings("rawtypes") protected void add(String channelName, Consumer beastChannelHandler) { exec.execute(new Runnable() { @Override public void run() { String beastChannel = channelHandlerLookupName(channelName); synchronized (channelConsumers) { List<Consumer> list = channelConsumers.get(beastChannel); if (list == null) { list = new ArrayList<>(); channelConsumers.put(beastChannel, list); } list.add(beastChannelHandler); } } }); } @SuppressWarnings("rawtypes") protected void remove(String channelName, Consumer beastChannelHandler) { exec.execute(new Runnable() { @Override public void run() { String beastChannel = channelHandlerLookupName(channelName); synchronized (channelConsumers) { if (channelConsumers.containsKey(beastChannel)) { channelConsumers.get(beastChannel).remove(beastChannelHandler); } } } }); } protected AlarmTreeItem getState(String channelName) throws Exception { URI uri = URI.create(URLEncoder.encode(BeastTypeSupport.getStrippedChannelName(channelName), "UTF-8")); String pvName = uri.getPath().substring(uri.getPath().lastIndexOf("/") + 1); AlarmClientModel aModel = selectModel(uri); int actualRetries = 0; final int maxRetries = 5; while (aModel == null && actualRetries < maxRetries) { log.warning("Waiting for model initialization of " + channelName + " (retrying: " + (actualRetries+1) + " of " + maxRetries + ")"); Thread.sleep(1000); aModel = selectModel(uri); actualRetries++; } if (aModel != null) { AlarmTreePV alarmTreePV = aModel.findPV(pvName); if (alarmTreePV != null) { return alarmTreePV; } else { String path = URLDecoder.decode(uri.getPath(), "UTF-8"); AlarmTreeItem alarmTreeItem = aModel.getConfigTree().getItemByPath(path); return alarmTreeItem; } } else { throw new Exception("Model hasn't been created yet: " + uri.getPath()); } } private AlarmClientModel selectModel(URI uri) throws Exception { if (model == null) { log.warning("No default model."); return null; } final String decodedUri = URLDecoder.decode(uri.getPath(), "UTF-8"); log.log(Level.FINE, () -> "decodedUri: " + decodedUri); if (uri.getPath().contains("/")) { // Alarm root defined final String lookupName = channelHandlerLookupName(decodedUri); //log.log(Level.INFO, "With root: " + lookupName); final String root; if (lookupName.contains("/")) root = lookupName.substring(0, lookupName.indexOf('/')); else root = lookupName; log.log(Level.FINE, () -> "root: " + root); if (model.getConfigurationName().equals(root)) { log.fine("Returning default model."); return model; } if (models.containsKey(root)) { log.fine("Returning named model."); return models.get(root); } if (root.equals(compositeModel.getConfigurationName())) { log.fine("Returning composite model."); return compositeModel; } log.log(Level.WARNING, () -> String.format("Root not found: %s", root)); return null; } else { // PV only - search models in the DIIRT defined order, but search default first. final String pvName = decodedUri.substring(decodedUri.lastIndexOf("/") + 1); //log.log(Level.INFO, "no root. pvName: " + pvName); if (model.findPV(pvName) != null) return model; for (final String configName : configuration.getConfigNames()) { final AlarmClientModel aModel = models.get(configName); if ((aModel != null) && (aModel.findPV(pvName) != null)) return aModel; } // PV not found anywhere!!! Return default. return model; } } protected boolean isConnected() { if (model != null) { return model.isServerAlive(); } else { return false; } } protected boolean isWriteAllowed() { // this is governed by the org.csstudio.alarm.beast.Preferences so it is the same for all models if (model != null) { return model.isServerAlive() && model.isWriteAllowed(); } else { return false; } } protected void acknowledge(String channelName, boolean acknowledge) throws Exception { getState(channelName).acknowledge(acknowledge); } // implementing the enable disable mechanism using the example of the DisableComponentAction protected void enable(String channelName, boolean enable) throws Exception { AlarmTreeItem item = getState(channelName); final List<AlarmTreePV> pvs = new ArrayList<>(); final CompletableFuture<Void> future = CompletableFuture .runAsync(() -> addPVs(pvs, item, enable), executor) .thenRun(() -> { for (AlarmTreePV alarmTreePV : pvs) { try { model.enable(alarmTreePV, enable); } catch (Exception e) { new Exception("Failed to enable/disable : " + ((AlarmTreePV) item).getName(), e); } } }); } /** @param pvs List where PVs to enable/disable will be added * @param item Item for which to locate PVs, recursively */ private void addPVs(final List<AlarmTreePV> pvs, final AlarmTreeItem item, boolean enable) { if (item instanceof AlarmTreePV) { final AlarmTreePV pv = (AlarmTreePV) item; if (pv.isEnabled() != enable) pvs.add(pv); } else { final int N = item.getChildCount(); for (int i=0; i<N; ++i) addPVs(pvs, item.getChild(i), enable); } } public BeastTypeSupport getTypeSupport() { return typeSupport; } @Override public void newAlarmConfiguration(AlarmClientModel model) { // initial model loaded // store the default model in a list of all models log.log(Level.CONFIG, () -> "Default alarm client model loaded: " + model.getConfigurationName()); // now obtain all roots from it, and then see if you have anything else in the DIIRT configuration final String[] confNames = model.getConfigurationNames(); toLoad.set(confNames.length); if (confNames.length == 1) compositeModel.setAllLoaded(true); // there is only one model, and that one was just loaded. final List<String> diirtConfNames = new ArrayList<>(configuration.getConfigNames()); // original is unmodifiable for (final String confName : confNames) { try { if (!models.containsKey(confName)) { log.log(Level.FINER, () -> "Loading model: " + confName); final AlarmClientModel aModel = AlarmClientModel.getInstance(confName, modelListener); models.put(confName, aModel); } diirtConfNames.remove(confName); } catch (final Exception e) { // Log warning if not debugging if (!log.isLoggable(Level.FINER)) log.log(Level.WARNING, "Error loading alarm Client Model: " + confName); log.log(Level.FINER, "Error loading alarm Client Model.", e); } } if (!diirtConfNames.isEmpty()) { log.log(Level.WARNING, "DIIRT beast configuration defines alarm models not configured in the database: " + diirtConfNames.toString()); } } }
package net.tomp2p.connection; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This is a soft limit, as there is no way to drop a connection before creating * a socket from Java. This handler counts the incoming connections and drops the * connection if a certain limit is reached. * * @author Thomas Bocek * */ @Sharable public class DropConnectionInboundHandler extends ChannelInboundHandlerAdapter { private static final Logger LOG = LoggerFactory.getLogger(DropConnectionInboundHandler.class); private final AtomicInteger counter = new AtomicInteger(); final int limit; public DropConnectionInboundHandler(int limit) { this.limit = limit; } @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { int current = -1; if ((current = counter.incrementAndGet()) > limit) { ctx.channel().close(); LOG.warn("dropped connection because: " + current +" > " + limit +" connections active"); } else { ctx.fireChannelRegistered(); } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { counter.decrementAndGet(); ctx.fireChannelInactive(); } }
package king.flow.net; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.AdaptiveRecvByteBufAllocator; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.FixedRecvByteBufAllocator; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.DelimiterBasedFrameDecoder; import io.netty.handler.codec.Delimiters; import io.netty.handler.codec.FixedLengthFrameDecoder; import io.netty.handler.codec.LengthFieldPrepender; import io.netty.handler.codec.MessageToByteEncoder; import io.netty.handler.codec.bytes.ByteArrayDecoder; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.bind.JAXBException; import king.flow.common.CommonConstants; import static king.flow.data.TLSResult.PRS_CODE; import king.flow.design.TLSProcessor; import king.flow.test.net.MockClientReq; /** * * @author Administrator */ public class P2PTunnel implements Tunnel { private final String host; private final int port; private final int timeout; private String responseMSG = null; public P2PTunnel(String hostName, int portNumber, int channelTimeout) { this.host = hostName; this.port = portNumber; this.timeout = channelTimeout; } @Override public String connect() { connectAndSend(null, null); return this.responseMSG; } @Override public String connect(int commmand, String message) { connectAndSend(commmand, message); return this.responseMSG; } private void connectAndSend(Integer command, String message) { EventLoopGroup workerGroup = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.option(ChannelOption.MAX_MESSAGES_PER_READ, CommonConstants.MAX_MESSAGES_PER_READ); // b.option(ChannelOption.RCVBUF_ALLOCATOR, // new FixedRecvByteBufAllocator(CommonConstants.MAX_RECEIVED_BUFFER_SIZE)); b.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator( CommonConstants.MIN_RECEIVED_BUFFER_SIZE, CommonConstants.RECEIVED_BUFFER_SIZE, CommonConstants.MAX_RECEIVED_BUFFER_SIZE)); if (command == null || message == null) { b.handler(new ChannelInitializerImpl()); } else { b.handler(new ChannelInitializerImpl(command, message)); } // Start the client. ChannelFuture f = b.connect(host, port).sync(); // Wait until the connection is closed. //f.channel().closeFuture().sync(); boolean completed = f.channel().closeFuture().await(timeout, TimeUnit.SECONDS); if (!completed) { String PRSCODE_PREFIX = "<" + PRS_CODE + ">"; String PRSCODE_AFFIX = "</" + PRS_CODE + ">"; String prsCode = "[Unkonwn prscode]"; if (message == null) { } else { int start = message.indexOf(PRSCODE_PREFIX); int end = message.indexOf(PRSCODE_AFFIX) + PRSCODE_AFFIX.length(); prsCode = (start == -1 || end == -1) ? prsCode : message.substring(start, end); } Logger.getLogger(P2PTunnel.class.getName()).log(Level.WARNING, "[{0}] operation exceeds {1}seconds and is timeout, channel is forcily closed", new Object[]{prsCode, timeout}); //forcily close channel to avoid connection leak //acutally if no forcible channel close calling, connection still will be closed. //but for comprehensive consideration, I call channel close again f.channel().close().sync(); } } catch (InterruptedException ex) { Logger.getLogger(P2PTunnel.class.getName()).log(Level.SEVERE, "channel management hits a problem, due to\n{0}", ex); } finally { workerGroup.shutdownGracefully(); } } private class MessageClientHandler extends ChannelInboundHandlerAdapter { private String message = null; private StringBuilder sb = null; public MessageClientHandler() { } public MessageClientHandler(String msg) { this.message = msg; this.sb = new StringBuilder(); } public MessageClientHandler setMessage(String message) { this.message = message; return this; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(this.message); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { Logger.getLogger(MessageClientHandler.class.getName()).log(Level.CONFIG, msg.toString()); sb.append(msg); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { P2PTunnel.this.responseMSG = sb.toString(); ctx.disconnect(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { Logger.getLogger(MessageClientHandler.class.getName()).log(Level.SEVERE, cause.getMessage(), cause); ctx.close(); } } private class ByteMessageClientHandler extends ChannelInboundHandlerAdapter { private String message = null; private byte[] content = null; public ByteMessageClientHandler() { } public ByteMessageClientHandler(String msg) { this.message = msg; } public ByteMessageClientHandler setMessage(String message) { this.message = message; return this; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(this.message); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { byte[] block = (byte[]) msg; if (content == null) { content = block; } else { byte[] enlarge = new byte[content.length + block.length]; System.arraycopy(content, 0, enlarge, 0, content.length); System.arraycopy(block, 0, enlarge, content.length, block.length); content = enlarge; } } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { P2PTunnel.this.responseMSG = new String((content == null ? new byte[0] : content), CommonConstants.UTF8); ctx.disconnect(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { Logger.getLogger(MessageClientHandler.class.getName()).log(Level.SEVERE, cause.getMessage(), cause); ctx.close(); } } public static void main(String... args) throws JAXBException { // Parse options. String host = "127.0.0.1"; int port = 8080; int code = 1; String msg = new TLSProcessor().init().createRegistryMsg("1", "sanlogin", "token"); if (args != null && args.length >= 2) { host = args[0]; port = Integer.parseInt(args[1]); if (args.length >= 4) { code = Integer.parseInt(args[2]); msg = args[3]; } } Tunnel tunnel = TunnelBuilder.getTunnelBuilder().setHostName(host).setPortNumber(port).createTunnel(); tunnel.connect(code, msg); System.out.println("0000000000000000 : " + ((P2PTunnel) tunnel).responseMSG); tunnel.connect(300, MockClientReq.mockBasicReq()); // System.out.println("33333333330000000 : " + ((P2PTunnel)tunnel).responseMSG); tunnel.connect(400, MockClientReq.mockBasicReq()); } private class ChannelInitializerImpl extends ChannelInitializer<SocketChannel> { private ChannelHandler[] handler_list = null; public ChannelInitializerImpl() { this.handler_list = new ChannelHandler[]{new CMDFieldPrepender(1), new LengthFieldPrepender(4), new StringEncoder(CommonConstants.UTF8), new StringDecoder(CommonConstants.UTF8), new MessageClientHandler("This is echo message")}; } public ChannelInitializerImpl(int command, String message) { this.handler_list = new ChannelHandler[]{new CMDFieldPrepender(command), new LengthFieldPrepender(4), //new StringEncoder(CommonConstants.UTF8), new StringDecoder(CommonConstants.UTF8), new StringEncoder(CommonConstants.UTF8), new ByteArrayDecoder(), //new MessageClientHandler(message)}; new ByteMessageClientHandler(message)}; //new DelimiterBasedFrameDecoder(2048, Delimiters.lineDelimiter()), } public ChannelInitializerImpl(ChannelHandler... ch) { this.handler_list = ch; } @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(handler_list); } } private class CMDFieldPrepender extends MessageToByteEncoder<ByteBuf> { private int command = -1; public CMDFieldPrepender(int commandCode) { this.command = commandCode; } @Override protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception { out.writeInt(this.command); out.writeBytes(msg, msg.readerIndex(), msg.readableBytes()); } } }
import javax.swing.JPanel; import javax.swing.JEditorPane; import javax.swing.event.HyperlinkListener; import java.net.URL; import javax.swing.event.HyperlinkEvent; import javax.swing.text.html.HTMLFrameHyperlinkEvent; public class Browser{ public JEditorPane displayEditorPane; public Browser(){ displayEditorPane = new JEditorPane(); displayEditorPane.setContentType("text/html"); displayEditorPane.setEditable(false); try{displayEditorPane.setPage(new URL("http://"+Repository.host+":"+Repository.getHTTPServerPort()+"/report"));} catch(Exception e){System.out.println("could not get "+Repository.host+":"+Repository.getHTTPServerPort());} displayEditorPane.addHyperlinkListener(new HyperlinkListener(){ public void hyperlinkUpdate(HyperlinkEvent e){ HyperlinkEvent.EventType eventType = e.getEventType(); if (eventType == HyperlinkEvent.EventType.ACTIVATED) { if (!(e instanceof HTMLFrameHyperlinkEvent)){ try{displayEditorPane.setPage(e.getURL());} catch(Exception ex){System.out.println("Could not get to:"+e.getURL());}}}}});}}
package org.apereo.cas.support.saml.web.idp.profile.builders; import org.apereo.cas.support.saml.services.SamlRegisteredService; import org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade; import org.apereo.cas.support.saml.util.AbstractSaml20ObjectBuilder; import org.jasig.cas.client.validation.Assertion; import org.apereo.cas.support.saml.SamlException; import org.opensaml.saml.saml2.core.AuthnRequest; import org.opensaml.saml.saml2.core.NameID; import org.opensaml.saml.saml2.core.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.stereotype.Component; import java.time.ZoneOffset; import java.time.ZonedDateTime; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * This is {@link SamlProfileSamlSubjectBuilder}. * * @author Misagh Moayyed * @since 5.0.0 */ @RefreshScope @Component("samlProfileSamlSubjectBuilder") public class SamlProfileSamlSubjectBuilder extends AbstractSaml20ObjectBuilder implements SamlProfileObjectBuilder<Subject> { private static final long serialVersionUID = 4782621942035583007L; @Autowired @Qualifier("samlProfileSamlNameIdBuilder") private SamlProfileSamlNameIdBuilder ssoPostProfileSamlNameIdBuilder; @Value("${cas.samlidp.response.skewAllowance:0}") private int skewAllowance; @Override public Subject build(final AuthnRequest authnRequest, final HttpServletRequest request, final HttpServletResponse response, final Assertion assertion, final SamlRegisteredService service, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor) throws SamlException { return buildSubject(request, response, authnRequest, assertion, service, adaptor); } private Subject buildSubject(final HttpServletRequest request, final HttpServletResponse response, final AuthnRequest authnRequest, final Assertion assertion, final SamlRegisteredService service, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor) throws SamlException { final NameID nameID = this.ssoPostProfileSamlNameIdBuilder.build(authnRequest, request, response, assertion, service, adaptor); final ZonedDateTime validFromDate = ZonedDateTime.ofInstant(assertion.getValidFromDate().toInstant(), ZoneOffset.UTC); final Subject subject = newSubject(nameID.getFormat(), nameID.getValue(), authnRequest.getAssertionConsumerServiceURL(), validFromDate.plusSeconds(this.skewAllowance), authnRequest.getID()); subject.setNameID(nameID); return subject; } }
package org.mskcc.cbio.oncokb.quest; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Node; import org.dom4j.io.SAXReader; import org.mskcc.cbio.oncokb.bo.GeneBo; import org.mskcc.cbio.oncokb.model.Alteration; import org.mskcc.cbio.oncokb.model.AlterationType; import org.mskcc.cbio.oncokb.model.Gene; import org.mskcc.cbio.oncokb.util.AlterationUtils; import org.mskcc.cbio.oncokb.util.ApplicationContextSingleton; import org.mskcc.cbio.oncokb.util.FileUtils; import org.mskcc.cbio.oncokb.util.GeneUtils; import org.mskcc.cbio.oncokb.util.TumorTypeUtils; import org.springframework.stereotype.Controller; /** * * @author jgao */ @Controller public final class VariantAnnotationXMLV2 { public static void main(String[] args) throws FileNotFoundException { String input = args[0]; InputStream is = new FileInputStream(input); String annotation = getVariantAnnotation(is); String output; if (args.length>1) { output = args[1]; } else { output = input.substring(0, input.length()-4)+".oncokb.xml"; } try (PrintWriter writer = new PrintWriter(output)) { writer.append(annotation); } } public static String getVariantAnnotation(InputStream isXml) { try { Map<Alteration, String> mapAlterationXml = new LinkedHashMap<Alteration, String>(); SAXReader reader = new SAXReader(); Document document = reader.read(isXml); // sample id String sampleId = document.selectSingleNode("//xml/sample_id").getText(); // test id String testId = document.selectSingleNode("//xml/test_id").getText(); // diagnosis String diagnosis = document.selectSingleNode("//xml/diagnosis").getText(); // Somatic variants List<Node> vcfNodes = document.selectNodes("//xml/somatic_variants/data"); if (!vcfNodes.isEmpty()) { runVcf2Maf(document.asXML(), mapAlterationXml, diagnosis); } // for (Node vcfNode : vcfNodes) { // handleSomaticVariants(vcfNode, alterations, alterationXmls, diagnosis); // Copy number alterations List<Node> cnaNodes = document.selectNodes("//xml/copy_number_alterations/copy_number_alteration"); for (Node cnaNode : cnaNodes) { handleCNA(cnaNode, mapAlterationXml, diagnosis); } // fusions List<Node> fusionNodes = document.selectNodes("//xml/fusion_genes/fusion_gene"); for (Node fusionNode : fusionNodes) { handleFusion(fusionNode, mapAlterationXml, diagnosis); } List<Node> entrezNodes = document.selectNodes("//xml/sequencing_panel/genes/gene/entrez_gene_id"); ArrayList<Gene> sequencedGenes = new ArrayList<Gene>(); //use entrezGeneID, which is more stable than hugoSymbol, to fetch Gene instance for(int i = 0;i < entrezNodes.size();i++){ sequencedGenes.add(GeneUtils.getGene(Integer.parseInt(entrezNodes.get(i).getText()), null)); } // identify other related variants such as KRAS wildtype identifyAdditionalVariants(mapAlterationXml, diagnosis, sequencedGenes); List<Alteration> alterations = getAlterationOrderByLevelOfEvidence(mapAlterationXml); // exporting StringBuilder sb = new StringBuilder(); // meta sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n"); sb.append("<document>\n"); sb.append("<date_generated>2015-01-09</date_generated>\n"); sb.append("<oncokb_api_version>0.2</oncokb_api_version>\n"); sb.append("<ensembl_version>79</ensembl_version>\n"); sb.append("<sample>\n"); sb.append("<sample_id>").append(sampleId).append("</sample_id>\n"); sb.append("<diagnosis>").append(diagnosis).append("</diagnosis>\n"); sb.append("<test>\n"); sb.append("<test_id>").append(testId).append("</test_id>\n"); // variants sb.append(exportVariants(alterations, mapAlterationXml)); // variant_interation // end sb.append("</test>\n"); sb.append("</sample>\n"); sb.append("</document>"); return sb.toString(); } catch (Exception ex) { ex.printStackTrace(); return "<document>Failed to upload file.</document>"; } } private static void handleSomaticVariants(Node vcfNode, Map<Alteration, String> mapAlterationXml, String diagnosis) { // do it here } /** * This is a hacky way to run VEP. We should switch to web service once that is ready. */ private static void runVcf2Maf(String inputXml, Map<Alteration, String> mapAlterationXml, String diagnosis) throws IOException, DocumentException, InterruptedException { File tmpFile = File.createTempFile("temp-oncokb-input-", ".xml"); tmpFile.deleteOnExit(); String inputPath = tmpFile.getAbsolutePath(); String outputPath = inputPath.substring(0,inputPath.length()-3) + "oncokb.xml"; FileWriter writer = new FileWriter(tmpFile); writer.append(inputXml); writer.close(); String vepMafXmlPl = System.getenv("VEP_MAF_XML_PL"); if (null==vepMafXmlPl) { throw new IOException("VEP_MAF_XML_PL was not defined"); } Process proc = Runtime.getRuntime().exec(new String[]{"perl",vepMafXmlPl,inputPath}); proc.waitFor(); InputStream stderr = proc.getErrorStream(); InputStreamReader isr = new InputStreamReader(stderr); BufferedReader br = new BufferedReader(isr); String line = null; System.out.println("<ERROR>"); while ( (line = br.readLine()) != null) System.out.println(line); System.out.println("</ERROR>"); int exitVal = proc.waitFor(); System.out.println("Process exitValue: " + exitVal); SAXReader reader = new SAXReader(); Document document = reader.read(outputPath); List<Node> variantNodes = document.selectNodes("//document/sample/test/variant"); for (Node node : variantNodes) { String alterationXml = "<variant_type>small_nucleotide_variant</variant_type>\n" + node.selectSingleNode("genomic_locus").asXML() + node.selectSingleNode("allele").asXML(); String geneSymbol = node.selectSingleNode("allele/transcript/hgnc_symbol").getText(); GeneBo geneBo = ApplicationContextSingleton.getGeneBo(); Gene gene = geneBo.findGeneByHugoSymbol(geneSymbol); String proteinChange = node.selectSingleNode("allele/transcript/hgvs_p_short").getText(); Alteration alteration = new Alteration(); alteration.setAlterationType(AlterationType.MUTATION); alteration.setGene(gene); alteration.setName(proteinChange); AlterationUtils.annotateAlteration(alteration, proteinChange); mapAlterationXml.put(alteration, alterationXml); } } private static void handleCNA(Node cnaNode, Map<Alteration, String> mapAlterationXml, String diagnosis) { Gene gene = parseGene(cnaNode, "gene"); if (gene==null) { return; } String type = cnaNode.selectSingleNode("type").getText(); Alteration alteration = new Alteration(); alteration.setGene(gene); alteration.setAlteration(type); alteration.setAlterationType(AlterationType.MUTATION); // TODO: this needs to be fixed StringBuilder sb = new StringBuilder(); sb.append("<variant_type>copy_number_alteration</variant_type>\n"); sb.append(cnaNode.asXML()).append("\n"); sb.append(VariantAnnotationXML.annotate(alteration, diagnosis)); mapAlterationXml.put(alteration, sb.toString()); } private static void handleFusion(Node fusionNode, Map<Alteration, String> mapAlterationXml, String diagnosis) { StringBuilder sb = new StringBuilder(); sb.append("<variant_type>fusion_gene</variant_type>\n"); sb.append(fusionNode.asXML()).append("\n"); Gene gene1 = parseGene(fusionNode, "gene_1"); Gene gene2 = parseGene(fusionNode, "gene_2"); // String type = fusionNode.selectSingleNode("type").getText(); String fusion = gene1.getHugoSymbol()+"-"+gene2.getHugoSymbol()+" fusion"; Alteration alteration = new Alteration(); alteration.setGene(gene2); alteration.setAlteration(fusion); alteration.setAlterationType(AlterationType.MUTATION); // TODO: this needs to be fixed sb.append(VariantAnnotationXML.annotate(alteration, diagnosis)); mapAlterationXml.put(alteration, sb.toString()); } private static void identifyAdditionalVariants(Map<Alteration, String> mapAlterationXml, String diagnosis, ArrayList<Gene> sequencedGenes) { List<String> lines; try { ArrayList<Alteration> alterations = new ArrayList<Alteration>(mapAlterationXml.keySet()); ArrayList<Gene> genesWithMutation = new ArrayList<Gene>(); for(int i = 0;i < alterations.size();i++){ genesWithMutation.add(alterations.get(i).getGene()); } lines = FileUtils.readTrimedLinesStream(TumorTypeUtils.class.getResourceAsStream("/data/wildtype-alterations.txt")); String[] parts = new String[2]; Alteration tempAlteration = new Alteration(); Gene tempGene = new Gene(); for (String line : lines) { if (line.startsWith(" continue; } parts = line.split("\t"); tempGene = GeneUtils.getGene(null, parts[0]); if(sequencedGenes.contains(tempGene) && diagnosis.equals(parts[1]) && !genesWithMutation.contains(tempGene)){ tempAlteration.setGene(tempGene); tempAlteration.setAlteration("Wildtype"); tempAlteration.setAlterationType(AlterationType.MUTATION); StringBuilder sb = new StringBuilder(); sb.append("<variant_type>wildtype</variant_type>\n"); sb.append(VariantAnnotationXML.annotate(tempAlteration, diagnosis)); mapAlterationXml.put(tempAlteration, sb.toString()); } } } catch (IOException e) { e.printStackTrace(); } } private static List<Alteration> getAlterationOrderByLevelOfEvidence(Map<Alteration, String> mapAlterationXml) { return new ArrayList<Alteration>(mapAlterationXml.keySet()); } private static Gene parseGene(Node node, String genePath) { GeneBo geneBo = ApplicationContextSingleton.getGeneBo(); Gene gene = null; Node entrezGeneIdNode = node.selectSingleNode(genePath+"/entrez_gene_id"); Node hugoSymbolNode = node.selectSingleNode(genePath+"/hgnc_symbol"); if (entrezGeneIdNode!=null) { int entrezId = Integer.parseInt(entrezGeneIdNode.getText()); gene = geneBo.findGeneByEntrezGeneId(entrezId); } if (gene==null && hugoSymbolNode!=null) { String symbol = hugoSymbolNode.getText(); gene = geneBo.findGeneByHugoSymbol(symbol); } if (gene==null) { // a gene not in system gene = new Gene(); gene.setEntrezGeneId(Integer.parseInt(entrezGeneIdNode.getText())); gene.setHugoSymbol(hugoSymbolNode.getText()); } return gene; } private static String exportVariants(List<Alteration> alterations, Map<Alteration, String> mapAlterationXml) { StringBuilder sb = new StringBuilder(); for (int i=0; i<alterations.size(); i++) { Alteration alt = alterations.get(i); String xml = mapAlterationXml.get(alt); sb.append("<variant no=\"").append(i+1).append("\">\n").append(xml).append("</variant>\n"); } return sb.toString(); } }
package org.openhealthtools.mdht.uml.ui.navigator.actions; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.command.Command; import org.eclipse.emf.common.command.IdentityCommand; import org.eclipse.emf.common.command.UnexecutableCommand; import org.eclipse.emf.edit.domain.EditingDomain; import org.eclipse.emf.edit.domain.IEditingDomainProvider; import org.eclipse.emf.edit.ui.EMFEditUIPlugin; import org.eclipse.emf.edit.ui.action.CommandActionHandler; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.uml2.common.edit.command.ChangeCommand; import org.eclipse.uml2.uml.Association; import org.eclipse.uml2.uml.Class; import org.eclipse.uml2.uml.Element; import org.eclipse.uml2.uml.NamedElement; import org.eclipse.uml2.uml.Property; import org.openhealthtools.mdht.uml.common.ui.saveable.ModelDocument; import org.openhealthtools.mdht.uml.common.ui.saveable.ModelManager; public class DeleteUMLAction extends CommandActionHandler { protected List<Element> elements; public DeleteUMLAction(EditingDomain domain) { super(domain, EMFEditUIPlugin.INSTANCE.getString("_UI_Delete_menu_item")); } public DeleteUMLAction(EditingDomain domain, String label) { super(domain, label); } public void setActiveWorkbenchPart(IWorkbenchPart workbenchPart) { if (workbenchPart instanceof IEditingDomainProvider) { domain = ((IEditingDomainProvider) workbenchPart).getEditingDomain(); } } @Override public Command createCommand(Collection<?> selection) { elements = new ArrayList<Element>(); for (Object object : selection) { if (object instanceof Element && ((Element) object).getOwner() != null) { if (object instanceof Class) { Class umlClass = (Class) object; // delete associations for owned attributes for (Property property : umlClass.getOwnedAttributes()) { if (property.getAssociation() != null) { elements.addAll(property.getAssociation().getMemberEnds()); elements.add(property.getAssociation()); } } // delete associations when umlClass is the target // List<DirectedRelationship> specializations = umlClass.getTargetDirectedRelationships(UMLPackage.Literals.ASSOCIATION); // for (DirectedRelationship relationship : specializations) { for (Association association : umlClass.getAssociations()) { elements.addAll(association.getMemberEnds()); elements.add(association); } // delete the class elements.add(umlClass); } else if (object instanceof Association) { Association association = (Association) object; elements.addAll(association.getMemberEnds()); elements.add(association); } else { elements.add((Element) object); } } } if (elements.size() > 0) { return IdentityCommand.INSTANCE; } return UnexecutableCommand.INSTANCE; } @Override public void run() { if (command != UnexecutableCommand.INSTANCE) { String label = elements.get(0) instanceof NamedElement && ((NamedElement) elements.get(0)).getName() != null ? "Delete " + ((NamedElement) elements.get(0)).getName() : "Delete Element"; if (elements.size() > 1) { label += " (+" + (elements.size() - 1) + ")"; } domain.getCommandStack().execute(new ChangeCommand(domain, new Runnable() { public void run() { for (Element element : elements) { if (element.eResource() != null) { // mark resource dirty so that it can be saved ModelDocument sourceDocument = ModelManager.getManager().manage(element.eResource()); if (sourceDocument != null) { sourceDocument.setDirty(true); } } element.destroy(); } } }, label)); } } }
package com.backendless; import com.backendless.commons.DeviceType; import com.backendless.exceptions.BackendlessException; import com.backendless.exceptions.ExceptionMessage; import java.util.Hashtable; import java.util.Map; class AndroidHeadersManager implements IHeadersManager { private static volatile AndroidHeadersManager instance; static AndroidHeadersManager getInstance() throws BackendlessException { if( instance == null ) synchronized( AndroidHeadersManager.class ) { if( instance == null ) { instance = new AndroidHeadersManager(); } } return instance; } protected final Object headersLock = new Object(); protected final Hashtable<String, String> headers = new Hashtable<>(); AndroidHeadersManager() { if( Backendless.getApplicationId() == null || Backendless.getSecretKey() == null ) { throw new IllegalStateException( ExceptionMessage.NOT_INITIALIZED ); } initialFill(); } private void initialFill() { addHeader( HeadersManager.HeadersEnum.APP_ID_NAME, Backendless.getApplicationId() ); addHeader( HeadersManager.HeadersEnum.SECRET_KEY_NAME, Backendless.getSecretKey() ); addHeader( HeadersManager.HeadersEnum.APP_TYPE_NAME, DeviceType.ANDROID.name() ); addHeader( HeadersManager.HeadersEnum.API_VERSION, "1.0" ); addHeaders( Backendless.getHeaders() ); } public void cleanHeaders() { synchronized( headersLock ) { headers.clear(); initialFill(); } } public void addHeader( HeadersManager.HeadersEnum headersEnum, String value ) { synchronized( headersLock ) { headers.put( headersEnum.getHeader(), value ); } } public void addHeaders( Map<String, String> headers ) { if( headers == null || headers.isEmpty() ) return; synchronized( headersLock ) { this.headers.putAll( headers ); } } public void removeHeader( HeadersManager.HeadersEnum headersEnum ) { synchronized( headersLock ) { headers.remove( headersEnum.getHeader() ); } } public Hashtable<String, String> getHeaders() throws BackendlessException { synchronized( headersLock ) { if( headers == null || headers.isEmpty() ) throw new IllegalStateException( ExceptionMessage.NOT_INITIALIZED ); return headers; } } public void setHeaders( Map<String, String> headers ) { synchronized( headersLock ) { this.headers.putAll( headers ); } } public String getHeader( HeadersManager.HeadersEnum headersEnum ) throws BackendlessException { synchronized( headersLock ) { if( headers == null || headers.isEmpty() ) throw new IllegalStateException( ExceptionMessage.NOT_INITIALIZED ); String header = headers.get( headersEnum ); if( header == null ) header = headers.get( headersEnum.getHeader() ); return header; } } }
package org.objectweb.proactive.ic2d.jmxmonitoring.data; import java.io.IOException; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import javax.management.AttributeNotFoundException; import javax.management.InstanceNotFoundException; import javax.management.MBeanException; import javax.management.MBeanServerInvocationHandler; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.ReflectionException; import org.objectweb.proactive.core.UniqueID; import org.objectweb.proactive.core.body.migration.MigrationException; import org.objectweb.proactive.core.debug.stepbystep.BreakpointType; import org.objectweb.proactive.core.debug.stepbystep.DebugInfo; import org.objectweb.proactive.core.jmx.mbean.BodyWrapperMBean; import org.objectweb.proactive.core.jmx.naming.FactoryName; import org.objectweb.proactive.core.jmx.util.JMXNotificationManager; import org.objectweb.proactive.ic2d.console.Console; import org.objectweb.proactive.ic2d.jmxmonitoring.Activator; import org.objectweb.proactive.ic2d.jmxmonitoring.data.listener.ActiveObjectListener; import org.objectweb.proactive.ic2d.jmxmonitoring.util.MVCNotification; import org.objectweb.proactive.ic2d.jmxmonitoring.util.MVCNotificationTag; import org.objectweb.proactive.ic2d.jmxmonitoring.util.State; /** * Class for the active object representation in the IC2D model. */ public final class ActiveObject extends AbstractData<ProActiveNodeObject, AbstractData<?, ?>> { public static final String ACTIVE_OBJECT_TYPE = "active object"; /** The parent object !! CAN CHANGE because of migration !! */ private ProActiveNodeObject parent; /** * Forwards methods in an MBean's management interface through the MBean * server to the BodyWrapperMBean. !! CAN CHANGE because of migration !! */ private BodyWrapperMBean proxyMBean; /** * ID used to identify the active object globally, even in case of * migration. */ private final UniqueID id; /** * A string version of the id that is used as a key */ private final String key; /** Name of the class used to created the active object. */ private final String className; /** The object's name (ex: ao#2) */ private final String name; /** * The JMX Notification listener that will be subscribed to the * JMXNotificationManager * */ private final NotificationListener listener; /** * State of the object defined as a constant of the enum * {@link org.objectweb.proactive.ic2d.jmxmonitoring.util.State} */ private State currentState = State.UNKNOWN; /** request queue length */ private int requestQueueLength = -1; // -1 = not known /** * List of outgoing communications such as for each communication in the * list, this active object is the source. */ protected final List<Communication> outgoingCommunications; /** * List of incoming communications such as for each communication in the * list, this active object is the target. */ protected final List<Communication> incomingCommunications; /** * The destination node url used during migration !! CAN CHANGE because of * migration !! */ private String destNodeURLOnMigration; /** * A volatile variable used to handle or not the communications concerned by * this active object. * <p> * This volatile variable is used to provide thread-safety since it can be * accessed by several threads at the same time during the reset * communications user action. */ protected volatile boolean canHandleCommunications = true; /** * Creates and returns new instance of ActiveObject from an ObjectName. All * operations related to the creation of an ActiveObject representation in * IC2D should be done in its class, NOT elsewhere ! * <p> * The parent NodeObject MUST NOT contain an active object with same key * (string of unique id) ! * * @param objectName * The JMX object name associated to this ActiveObject * @param parent * The parent NodeObject * @return A new instance of ActiveObject class */ public static ActiveObject createActiveObjectFrom(final ObjectName objectName, final ProActiveNodeObject parent) { // First create the mbean proxy to get all information about the active // object final BodyWrapperMBean proxyMBean = ActiveObject.createMBeanProxy(parent, objectName); // Since the id is already contained as a String in the ObjectName // the proxyMBean.getID() call can be avoid if the UniqueID can be built // from a string return new ActiveObject(parent, objectName, proxyMBean.getID(), proxyMBean.getName(), proxyMBean); } /** * Creates a new proxy to the possibly remote * {@link org.objectweb.proactive.core.jmx.mbean.BodyWrapperMBean} from a * connection provided by a NodeObject and the object name associated with * the mbean. * * @param parent * The connection with the remote mbean server * @param objectName * The name associated with the mbean * @return A new proxy to the possibly remote mbean. */ private static final BodyWrapperMBean createMBeanProxy(final ProActiveNodeObject parent, final ObjectName objectName) { return (BodyWrapperMBean) MBeanServerInvocationHandler.newProxyInstance(parent .getProActiveConnection(), objectName, BodyWrapperMBean.class, false); } /** * Creates and returns new instance of ActiveObject from an ObjectName. All * operations related to the creation of an ActiveObject representation in * IC2D should be done in its class, NOT elsewhere ! * <p> * The parent NodeObject MUST NOT contain an active object with same key * (string of unique id) ! * * @param id * The UniqueID of the ActiveObject * @param className * The name of the reified object class * @param parent * The parent NodeObject * @return A new instance of ActiveObject class */ public static ActiveObject createActiveObjectFrom(final UniqueID id, final String className, final ProActiveNodeObject parent) { // Create the ObjectName from the id final ObjectName objectName = FactoryName.createActiveObjectName(id); // From the ObjectName create the MBeanProxy final BodyWrapperMBean proxyMBean = ActiveObject.createMBeanProxy(parent, objectName); return new ActiveObject(parent, objectName, id, className, proxyMBean); } /** * Creates a new instance of ActiveObject from an ObjectName. Use static * methods to create an ActiveObject. * * @param parent * The parent NodeObject * @param objectName * The JMX object name associated to this ActiveObject * @param id * The UniqueID of the ActiveObject * @param className * The name of the reified object class * @param proxyMBean * The JMX proxy to the mbean of the body */ private ActiveObject(final ProActiveNodeObject parent, final ObjectName objectName, final UniqueID id, final String className, final BodyWrapperMBean proxyMBean) { super(objectName, null); this.parent = parent; this.proxyMBean = proxyMBean; this.id = id; this.key = id.toString(); this.className = className; this.name = NamesFactory.getInstance().associateName(this.id, this.className); this.listener = new ActiveObjectListener(this); this.subscribeListener(); // CopyOnWriteArrayList is used since traversal operations vastly // outnumbers mutations // See addInCommunication and addOutCommunication methods of this class this.outgoingCommunications = new CopyOnWriteArrayList<Communication>(); this.incomingCommunications = new CopyOnWriteArrayList<Communication>(); // // LOG TO REMOVE // System.out.println("ActiveObject.ActiveObject() --> creating ao : " + this.name ); // if (parent.containsChild(this.key) // || parent.getWorldObject().findActiveObject(key) != null) { // System.out // + this.name // + " on NODE : " // + this.getParent().getName() // + "Current Thread : " // + Thread.currentThread().getName()); // Thread.dumpStack(); // Used to have good performances. TODO : Check if the performances are // as good as its said this.getWorldObject().addActiveObject(this); } /** * Change the current state * * @param newState * The new state of this active object */ public synchronized void setState(final State newState) { if (newState.equals(currentState)) { return; } switch (newState) { case WAITING_BY_NECESSITY: if (currentState == State.SERVING_REQUEST) { currentState = State.WAITING_BY_NECESSITY_WHILE_SERVING; } else { currentState = State.WAITING_BY_NECESSITY_WHILE_ACTIVE; } break; case RECEIVED_FUTURE_RESULT: if (currentState == State.WAITING_BY_NECESSITY_WHILE_SERVING) { currentState = State.SERVING_REQUEST; } else { currentState = State.ACTIVE; } break; default: currentState = newState; break; } setChanged(); notifyObservers(new MVCNotification(MVCNotificationTag.STATE_CHANGED, this.currentState)); } /** * Returns the current state of this active object. * * @return The current state. */ public synchronized State getState() { return this.currentState; } /** * Returns true if this active object is migrating false otherwise. * * @return true if this active object is migrating false otherwise */ public synchronized boolean isMigrating() { return this.currentState == State.MIGRATING; } /** * Sends a migration request to this object to migrate to another node. This * method uses the mbean proxy to send an asynchronous request of migration. * * @param targetNode * The target node object * @return true if it has successfully migrated, false otherwise. */ public synchronized boolean migrateTo(final ProActiveNodeObject targetNode) { final Console console = Console.getInstance(Activator.CONSOLE_NAME); final String nodeTargetURL = targetNode.getUrl(); try { // Migrate this.proxyMBean.migrateTo(nodeTargetURL); } catch (Exception e) { console.err("Couldn't migrate " + this.getName() + " to " + nodeTargetURL + " Reason : " + e.getMessage()); return false; } console.log("Successfully sent a request of migration of " + this + " to " + nodeTargetURL); return true; } /** * Prepares this active object to migrate, sets the current state to * {@link org.objectweb.proactive.ic2d.jmxmonitoring.util.State.MIGRATING}. * * @param destinationNodeURL * The url of the destination node */ public void prepareToMigrate(final String destinationNodeURL) { this.destNodeURLOnMigration = destinationNodeURL; this.setState(State.MIGRATING); } /** * Finishes the migration. Refreshes current parent and the mbean proxy of * this active object. * <p> * This method is * <code>synchronized</p> because sometimes it can be called by 2 different threads * at the same time. * * @param destinationRuntimeURL * The <code>URL</code> of the destination runtime */ public synchronized void finishMigration(final String destinationRuntimeURL) { // First if its not a migrating object or destNodeURLOnMigration is null we can't finish migration if (this.currentState != State.MIGRATING || this.destNodeURLOnMigration == null) { return; } // Get the console for the output final Console console = Console.getInstance(Activator.CONSOLE_NAME); // Try to locate the destination runtime object from its url // First locate the destination host from the given URL // The next code extracts proto://addr:port/ from // proto://addr:port/runtime_name final String destHostURL = destinationRuntimeURL.substring(0, destinationRuntimeURL.lastIndexOf('/') + 1); final HostObject destHostObject = (HostObject) this.getParent().getWorldObject() .getChild(destHostURL); if (destHostObject == null) { console.log("Cannot finish migration of the active object : " + this.name + ". Trying to migrate to an unknown host : " + destHostURL); return; } // Second locate the destination runtime by its URL final RuntimeObject destRuntimeObject = (RuntimeObject) destHostObject .getChild(destinationRuntimeURL); if (destRuntimeObject == null) { console.log("Cannot finish migration of the active object : " + this.name + ". Trying to migrate to an unknown runtime : " + destinationRuntimeURL); return; } // Third locate the destination node by its URL final ProActiveNodeObject destNodeObject = (ProActiveNodeObject) destRuntimeObject .getChild(this.destNodeURLOnMigration); if (destNodeObject == null) { console.log("Cannot finish migration of the active object : " + this.name + ". Trying to migrate to an unknown node : " + this.destNodeURLOnMigration); return; } // Update the mbean proxy (recreate one from the ProActiveConnection // provided by // the new node object) this.proxyMBean = ActiveObject.createMBeanProxy(destNodeObject, this.objectName); // WARNING !!! DO NOT REMOVE COMMUNICATIONS HERE !!! // Communications are represented by outgoingCommunications and // incomingCommunications list attributes of this class. // Representation of a migration concerns only edit parts NOT MODELS ! // Since the active object model is NOT DELETED. // Remove this from current parent node this.parent.removeChild(this); // Update the new parent this.parent = destNodeObject; // Add this to new parent this.parent.addChild(this); // Restore a standard state this.setState(State.WAITING_FOR_REQUEST); this.destNodeURLOnMigration = null; } /** * Say to the model that a MigrationException occurred during a migration of * this active object. * * @param migrationException */ public void migrationFailed(MigrationException migrationException) { Console.getInstance(Activator.CONSOLE_NAME).logException( "The active object " + this + " didn't migrate!", migrationException); } /** * Returns the unique id of the active object. * * @return An unique id. */ public UniqueID getUniqueID() { return this.id; } /** * Returns the name of the class given in parameter to the constructor. * * @return The class name */ public String getClassName() { return this.className; } /** * Returns a JMX Notification listener. * * @return a JMX Notification listener. */ public NotificationListener getListener() { return this.listener; } /** * Returns a direct reference on the list of outgoing communications. * * @return A list of outgoing communications */ public List<Communication> getOutgoingCommunications() { return this.outgoingCommunications; } /** * Returns a direct reference on the list of incoming communications. * * @return A list of incoming communications */ public List<Communication> getIncomingCommunications() { return this.incomingCommunications; } /** * Adds a communication from this active object to another active object * Warning: This active object is the source of the communication. * * @param destinationID * The unique id of the destination of the communication. */ public void addOutCommunication(final UniqueID destinationID) { if (!this.canHandleCommunications) return; // First seek through all known outgoing communications for (final Communication c : this.outgoingCommunications) { if (c.getTarget().getUniqueID().equals(destinationID)) { c.addOneCall(); return; } } final ActiveObject destAO = getWorldObject().findActiveObject(destinationID.getCanonString()); // If the destination ao is not known or this has no observers return // silently if (destAO == null || this.countObservers() == 0 || destAO.countObservers() == 0) { return; } // If it's an unknown outgoing communication create one new Communication(this, destAO); } /** * Adds a communication to this active object from another active object * Warning: This active object is the target of the communication. * * @param sourceID * The unique id of the source of the communication. */ public void addInCommunication(final UniqueID sourceID) { if (!this.canHandleCommunications) return; // First seek through all known incoming communications for (final Communication c : this.incomingCommunications) { if (c.getSource().getUniqueID().equals(sourceID)) { c.addOneCall(); return; } } final ActiveObject srcAO = getWorldObject().findActiveObject(sourceID.getCanonString()); // If the source ao in not known or this has no observers return // silently if (srcAO == null || this.countObservers() == 0 || srcAO.countObservers() == 0) { return; } // If the communication was not found create one new Communication(srcAO, this); } /** * Removes all outgoing and incoming communications of this active object. * For each removed communication a notification is fired to the observers * of this active object. * * @param softly * If true then the communications will be removed soflty (ie * through * {@link org.objectweb.proactive.ic2d.jmxmonitoring.data.Communication#disconnect()}) * method that can slower otherwise a rough method that consists * of simply clearing the lists of communications is used. * */ public void removeAllCommunications(boolean softly) { // Soft method if (softly) { // Remove all outgoing for (Communication c : this.outgoingCommunications) { c.disconnect(); } // Remove all incoming for (Communication c : this.incomingCommunications) { c.disconnect(); } return; } this.outgoingCommunications.clear(); // Fire remove event this.setChanged(); notifyObservers(new MVCNotification( MVCNotificationTag.ACTIVE_OBJECT_REMOVE_ALL_OUTGOING_COMMUNICATION, null)); this.incomingCommunications.clear(); // Fire remove event this.setChanged(); notifyObservers(new MVCNotification( MVCNotificationTag.ACTIVE_OBJECT_REMOVE_ALL_INCOMING_COMMUNICATION, null)); } @Override public void destroy() { this.internalDestroy(); // The destroy method of the super-class will remove this object from // the parents children super.destroy(); } /** * Remove the jmx listener, removes this from world then removes communications */ protected void internalDestroy() { // First unsubscribe JMX listener this.unsubscribeListener(); // Remove this object from world super.getWorldObject().removeActiveObject(this.key); // Second remove all communications this.removeAllCommunications(true); } public boolean subscribeListener() { // Subscribe to the jmx listener try { JMXNotificationManager.getInstance().subscribe(super.objectName, this.listener, this.parent.getParent().getUrl()); return true; } catch (Exception e) { Console.getInstance(Activator.CONSOLE_NAME).log( "Cannot subscribe the JMX listener of " + getType() + " " + getName()); return false; } } public void unsubscribeListener() { try { // Remove the JMX Listener JMXNotificationManager.getInstance().unsubscribe(super.objectName, this.listener); } catch (Exception e) { Console.getInstance(Activator.CONSOLE_NAME).log( "Cannot unsubscribe the JMX listener of " + getType() + " " + getName()); } } /** * Adds an outgoing communication to this active object and fires an * {@link org.objectweb.proactive.ic2d.jmxmonitoring.util.MVCNotificationTag.ACTIVE_OBJECT_ADD_OUTGOING_COMMUNICATION} * WARNING ! This method MUST be called ONLY from * {@link org.objectweb.proactive.ic2d.jmxmonitoring.data.Communication#connect()} * method. * * @param outgoingCommunication * The outgoing communication to add */ void internalAddOutgoingCommunication(final Communication outgoingCommunication) { this.outgoingCommunications.add(outgoingCommunication); // Fire a notification this.setChanged(); notifyObservers(new MVCNotification(MVCNotificationTag.ACTIVE_OBJECT_ADD_OUTGOING_COMMUNICATION, outgoingCommunication)); } /** * Adds an incoming communication to this active object and fires an * {@link org.objectweb.proactive.ic2d.jmxmonitoring.util.MVCNotificationTag.ACTIVE_OBJECT_ADD_INCOMING_COMMUNICATION} * WARNING ! This method MUST be called ONLY from * {@link org.objectweb.proactive.ic2d.jmxmonitoring.data.Communication#connect()} * method. * * @param incomingCommunication * The incoming communication to add */ void internalAddIncomingCommunication(final Communication incomingCommunication) { this.incomingCommunications.add(incomingCommunication); // Fire a notification this.setChanged(); notifyObservers(new MVCNotification(MVCNotificationTag.ACTIVE_OBJECT_ADD_INCOMING_COMMUNICATION, incomingCommunication)); } /** * Removes an outgoing communication of this active object and fires an * {@link org.objectweb.proactive.ic2d.jmxmonitoring.util.MVCNotificationTag.ACTIVE_OBJECT_REMOVE_OUTGOING_COMMUNICATION} * WARNING ! This method MUST be called ONLY from * {@link org.objectweb.proactive.ic2d.jmxmonitoring.data.Communication#disconnect()} * method. * * @param outgoingCommunication * The outgoing communication to remove */ void internalRemoveOutgoingCommunication(final Communication outgoingCommunication) { // Fire a notification this.setChanged(); notifyObservers(new MVCNotification(MVCNotificationTag.ACTIVE_OBJECT_REMOVE_OUTGOING_COMMUNICATION, outgoingCommunication)); this.outgoingCommunications.remove(outgoingCommunication); } /** * Removes an incoming communication to this active object and fires an * {@link org.objectweb.proactive.ic2d.jmxmonitoring.util.MVCNotificationTag.ACTIVE_OBJECT_REMOVE_INCOMING_COMMUNICATION} * WARNING ! This method MUST be called ONLY from * {@link org.objectweb.proactive.ic2d.jmxmonitoring.data.Communication#disconnect()} * method. * * @param incomingCommunication * The incoming communication to remove */ void internalRemoveIncomingCommunication(final Communication incomingCommunication) { // Fire a notification this.setChanged(); notifyObservers(new MVCNotification(MVCNotificationTag.ACTIVE_OBJECT_REMOVE_INCOMING_COMMUNICATION, incomingCommunication)); this.incomingCommunications.remove(incomingCommunication); } /** * The monitored active object adds a request, increments the request queue * length. */ public void addRequest() { this.requestQueueLength++; setChanged(); notifyObservers(new MVCNotification(MVCNotificationTag.ACTIVE_OBJECT_REQUEST_QUEUE_LENGHT_CHANGED, requestQueueLength)); } /** * The monitored active object removes a request, decrements the request * queue length. */ public void removeRequest() { this.requestQueueLength setChanged(); notifyObservers(new MVCNotification(MVCNotificationTag.ACTIVE_OBJECT_REQUEST_QUEUE_LENGHT_CHANGED, requestQueueLength)); } public void setRequestQueueLength(int requestQueueLength) { if (this.requestQueueLength != requestQueueLength) { this.requestQueueLength = requestQueueLength; setChanged(); notifyObservers(new MVCNotification( MVCNotificationTag.ACTIVE_OBJECT_REQUEST_QUEUE_LENGHT_CHANGED, requestQueueLength)); } } /** * Returns the length of the monitored active object request queue. * * @return The length of the request queue */ public int getRequestQueueLength() { return this.requestQueueLength; } public String getJobId() { return this.getParent().getJobId(); } /** * Returns the name of this active object. (Example: ao#3) * * @return The name of this active object. */ @Override public String getName() { return this.name; } @SuppressWarnings("unchecked") @Override public ProActiveNodeObject getParent() { return this.parent; } @Override public String getKey() { return this.key; } @Override public String getType() { return ActiveObject.ACTIVE_OBJECT_TYPE; } @Override public void explore() { } @Override public String toString() { return this.name; } public void enableStepByStep() { setChanged(); proxyMBean.enableStepByStep(); } public void disableStepByStep() { setChanged(); proxyMBean.disableStepByStep(); } public void nextStep() { proxyMBean.nextStep(); } public void nextStep(long id) { proxyMBean.nextStep(id); } public void nextStep(Collection<Long> ids) { proxyMBean.nextStep(ids); } public DebugInfo getDebugInfo() { try { return (DebugInfo) getProActiveConnection().getAttribute(getObjectName(), "DebugInfo"); } catch (AttributeNotFoundException e) { e.printStackTrace(); } catch (InstanceNotFoundException e) { e.printStackTrace(); } catch (MBeanException e) { e.printStackTrace(); } catch (ReflectionException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public void slowMotion(long slowMotionDelay) { setChanged(); proxyMBean.slowMotion(slowMotionDelay); } public void initBreakpointTypes() { proxyMBean.initBreakpointTypes(); } public void enableBreakpointTypes(BreakpointType[] types) { proxyMBean.enableBreakpointTypes(types); } public void disableBreakpointTypes(BreakpointType[] types) { proxyMBean.disableBreakpointTypes(types); } public static final class ActiveObjectComparator implements Comparator<String> { /** * Compare two active objects. (For Example: ao#3 and ao#5 give -1 * because ao#3 has been discovered before ao#5.) * * @return -1, 0, or 1 as the first argument is less than, equal to, or * greater than the second. */ public int compare(final String ao1Name, final String ao2Name) { return -(ao1Name.compareTo(ao2Name)); } } }
package org.innovateuk.ifs.application; import org.innovateuk.ifs.BaseControllerMockMVCTest; import org.innovateuk.ifs.application.constant.ApplicationStatusConstants; import org.innovateuk.ifs.application.form.ApplicantInviteForm; import org.innovateuk.ifs.application.form.ApplicationTeamUpdateForm; import org.innovateuk.ifs.application.populator.ApplicationTeamManagementModelPopulator; import org.innovateuk.ifs.application.resource.ApplicationResource; import org.innovateuk.ifs.application.viewmodel.ApplicationTeamManagementApplicantRowViewModel; import org.innovateuk.ifs.application.viewmodel.ApplicationTeamManagementViewModel; import org.innovateuk.ifs.invite.resource.ApplicationInviteResource; import org.innovateuk.ifs.invite.resource.InviteOrganisationResource; import org.innovateuk.ifs.invite.resource.InviteResultsResource; import org.innovateuk.ifs.user.resource.OrganisationResource; import org.innovateuk.ifs.user.resource.UserResource; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.http.MediaType; import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.servlet.MvcResult; import org.springframework.validation.BindingResult; import java.util.List; import java.util.Map; import static java.lang.String.format; import static java.util.Arrays.asList; import static org.innovateuk.ifs.application.builder.ApplicationResourceBuilder.newApplicationResource; import static org.innovateuk.ifs.application.constant.ApplicationStatusConstants.OPEN; import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess; import static org.innovateuk.ifs.invite.builder.ApplicationInviteResourceBuilder.newApplicationInviteResource; import static org.innovateuk.ifs.invite.builder.InviteOrganisationResourceBuilder.newInviteOrganisationResource; import static org.innovateuk.ifs.invite.constant.InviteStatus.OPENED; import static org.innovateuk.ifs.invite.constant.InviteStatus.SENT; import static org.innovateuk.ifs.user.builder.OrganisationResourceBuilder.newOrganisationResource; import static org.innovateuk.ifs.user.builder.ProcessRoleResourceBuilder.newProcessRoleResource; import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource; import static org.innovateuk.ifs.util.CollectionFunctions.simpleToMap; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(MockitoJUnitRunner.class) @TestPropertySource(locations = "classpath:application.properties") public class ApplicationTeamManagementControllerTest extends BaseControllerMockMVCTest<ApplicationTeamManagementController> { @Spy @InjectMocks private ApplicationTeamManagementModelPopulator applicationTeamManagementModelPopulator; @Override protected ApplicationTeamManagementController supplyControllerUnderTest() { return new ApplicationTeamManagementController(); } @Test public void getUpdateLeadTeam_loggedInUserIsLead() throws Exception { Map<String, OrganisationResource> organisationsMap = setupOrganisationResources(); ApplicationResource applicationResource = setupApplicationResource(organisationsMap); Map<String, UserResource> usersMap = setupUserResources(); List<InviteOrganisationResource> inviteOrganisationList = setupOrganisationInvitesWithInviteForLeadOrg(applicationResource.getId(), usersMap, organisationsMap); Long applicationInviteId = inviteOrganisationList.get(2).getInviteResources().get(0).getId(); UserResource leadApplicant = setupLeadApplicant(applicationResource, usersMap); OrganisationResource expectedOrganisation = organisationsMap.get("Empire Ltd"); List<ApplicationTeamManagementApplicantRowViewModel> expectedApplicants = asList( new ApplicationTeamManagementApplicantRowViewModel("Steve Smith", "steve.smith@empire.com", true, false, false), new ApplicationTeamManagementApplicantRowViewModel(applicationInviteId,"Paul Davidson", "paul.davidson@empire.com", false, false, true)); ApplicationTeamManagementViewModel expectedViewModel = new ApplicationTeamManagementViewModel( applicationResource.getId(), "Application name", expectedOrganisation.getId(), expectedOrganisation.getName(), true, true, expectedApplicants); setLoggedInUser(leadApplicant); MvcResult mockResult = mockMvc.perform(get("/application/{applicationId}/team/update?organisation={organisationId}", applicationResource.getId(), expectedOrganisation.getId())) .andExpect(status().isOk()) .andExpect(model().attribute("model", expectedViewModel)) .andExpect(view().name("application-team/edit-org")) .andReturn(); ApplicationTeamManagementViewModel viewModelResult = (ApplicationTeamManagementViewModel) mockResult.getModelAndView().getModel().get("model"); InOrder inOrder = inOrder(applicationService, inviteRestService, userService); inOrder.verify(applicationService).getById(applicationResource.getId()); inOrder.verify(applicationService).getLeadOrganisation(applicationResource.getId()); inOrder.verify(inviteRestService).getInvitesByApplication(applicationResource.getId()); inOrder.verify(applicationService).getById(applicationResource.getId()); inOrder.verify(userService).getLeadApplicantProcessRoleOrNull(applicationResource); inOrder.verify(userService).findById(leadApplicant.getId()); inOrder.verifyNoMoreInteractions(); } @Test public void getUpdateNonLeadTeam_loggedInUserIsLead() throws Exception { Map<String, OrganisationResource> organisationsMap = setupOrganisationResources(); ApplicationResource applicationResource = setupApplicationResource(organisationsMap); Map<String, UserResource> usersMap = setupUserResources(); List<InviteOrganisationResource> inviteOrganisationList = setupOrganisationInvitesWithInviteForLeadOrg(applicationResource.getId(), usersMap, organisationsMap); Long applicationInviteId1 = inviteOrganisationList.get(0).getInviteResources().get(0).getId(); Long applicationInviteId2 = inviteOrganisationList.get(0).getInviteResources().get(1).getId(); UserResource leadApplicant = setupLeadApplicant(applicationResource, usersMap); OrganisationResource expectedOrganisation = organisationsMap.get("Ludlow"); List<ApplicationTeamManagementApplicantRowViewModel> expectedApplicants = asList( new ApplicationTeamManagementApplicantRowViewModel(applicationInviteId1,"Jessica Doe", "jessica.doe@ludlow.com", false, false, true), new ApplicationTeamManagementApplicantRowViewModel(applicationInviteId2,"Ryan Dell", "ryan.dell@ludlow.com", false, true, true)); ApplicationTeamManagementViewModel expectedViewModel = new ApplicationTeamManagementViewModel( applicationResource.getId(), "Application name", expectedOrganisation.getId(), expectedOrganisation.getName(), false, true, expectedApplicants); setLoggedInUser(leadApplicant); MvcResult mockResult = mockMvc.perform(get("/application/{applicationId}/team/update?organisation={organisationId}", applicationResource.getId(), expectedOrganisation.getId())) .andExpect(status().isOk()) .andExpect(model().attribute("model", expectedViewModel)) .andExpect(view().name("application-team/edit-org")) .andReturn(); ApplicationTeamManagementViewModel viewModelResult = (ApplicationTeamManagementViewModel) mockResult.getModelAndView().getModel().get("model"); InOrder inOrder = inOrder(applicationService, inviteRestService, userService); inOrder.verify(applicationService).getById(applicationResource.getId()); inOrder.verify(applicationService).getLeadOrganisation(applicationResource.getId()); inOrder.verify(inviteRestService).getInvitesByApplication(applicationResource.getId()); inOrder.verify(applicationService).getById(applicationResource.getId()); inOrder.verify(userService).getLeadApplicantProcessRoleOrNull(applicationResource); inOrder.verify(userService).findById(leadApplicant.getId()); inOrder.verifyNoMoreInteractions(); } @Test public void getUpdateNonLeadTeam_loggedInUserIsNonLead() throws Exception { Map<String, OrganisationResource> organisationsMap = setupOrganisationResources(); ApplicationResource applicationResource = setupApplicationResource(organisationsMap); Map<String, UserResource> usersMap = setupUserResources(); List<InviteOrganisationResource> inviteOrganisationList = setupOrganisationInvitesWithInviteForLeadOrg(applicationResource.getId(), usersMap, organisationsMap); Long applicationInviteId1 = inviteOrganisationList.get(0).getInviteResources().get(0).getId(); Long applicationInviteId2 = inviteOrganisationList.get(0).getInviteResources().get(1).getId(); UserResource leadApplicant = setupLeadApplicant(applicationResource, usersMap); OrganisationResource expectedOrganisation = organisationsMap.get("Ludlow"); List<ApplicationTeamManagementApplicantRowViewModel> expectedApplicants = asList( new ApplicationTeamManagementApplicantRowViewModel(applicationInviteId1,"Jessica Doe", "jessica.doe@ludlow.com", false, false, false), new ApplicationTeamManagementApplicantRowViewModel(applicationInviteId2,"Ryan Dell", "ryan.dell@ludlow.com", false, true, true)); ApplicationTeamManagementViewModel expectedViewModel = new ApplicationTeamManagementViewModel( applicationResource.getId(), "Application name", expectedOrganisation.getId(), expectedOrganisation.getName(), false, false, expectedApplicants); setLoggedInUser(usersMap.get("jessica.doe@ludlow.com")); MvcResult mockResult = mockMvc.perform(get("/application/{applicationId}/team/update?organisation={organisationId}", applicationResource.getId(), expectedOrganisation.getId())) .andExpect(status().isOk()) .andExpect(model().attribute("model", expectedViewModel)) .andExpect(view().name("application-team/edit-org")) .andReturn(); ApplicationTeamManagementViewModel viewModelResult = (ApplicationTeamManagementViewModel) mockResult.getModelAndView().getModel().get("model"); InOrder inOrder = inOrder(applicationService, inviteRestService, userService); inOrder.verify(applicationService).getById(applicationResource.getId()); inOrder.verify(applicationService).getLeadOrganisation(applicationResource.getId()); inOrder.verify(inviteRestService).getInvitesByApplication(applicationResource.getId()); inOrder.verify(applicationService).getById(applicationResource.getId()); inOrder.verify(userService).getLeadApplicantProcessRoleOrNull(applicationResource); inOrder.verify(userService).findById(leadApplicant.getId()); inOrder.verifyNoMoreInteractions(); } @Test public void getUpdateNewTeam_loggedInUserIsLead() throws Exception { Map<String, OrganisationResource> organisationsMap = setupOrganisationResources(); ApplicationResource applicationResource = setupApplicationResource(organisationsMap); Map<String, UserResource> usersMap = setupUserResources(); List<InviteOrganisationResource> inviteOrganisationList = setupOrganisationInvitesWithInviteForLeadOrg(applicationResource.getId(), usersMap, organisationsMap); Long applicationInviteId1 = inviteOrganisationList.get(0).getInviteResources().get(0).getId(); Long applicationInviteId2 = inviteOrganisationList.get(0).getInviteResources().get(1).getId(); UserResource leadApplicant = setupLeadApplicant(applicationResource, usersMap); OrganisationResource expectedOrganisation = organisationsMap.get("Ludlow"); List<ApplicationTeamManagementApplicantRowViewModel> expectedApplicants = asList( new ApplicationTeamManagementApplicantRowViewModel(applicationInviteId1, "Jessica Doe", "jessica.doe@ludlow.com", false, false, true), new ApplicationTeamManagementApplicantRowViewModel(applicationInviteId2,"Ryan Dell", "ryan.dell@ludlow.com", false, true, true)); ApplicationTeamManagementViewModel expectedViewModel = new ApplicationTeamManagementViewModel( applicationResource.getId(), "Application name", expectedOrganisation.getId(), expectedOrganisation.getName(), false, true, expectedApplicants); setLoggedInUser(leadApplicant); MvcResult mockResult = mockMvc.perform(get("/application/{applicationId}/team/update?organisationName={organisationName}", applicationResource.getId(), expectedOrganisation.getName())) .andExpect(status().isOk()) .andExpect(model().attribute("model", expectedViewModel)) .andExpect(view().name("application-team/edit-org")) .andReturn(); ApplicationTeamManagementViewModel viewModelResult = (ApplicationTeamManagementViewModel) mockResult.getModelAndView().getModel().get("model"); InOrder inOrder = inOrder(applicationService, inviteRestService, userService); inOrder.verify(applicationService).getById(applicationResource.getId()); inOrder.verify(applicationService).getLeadOrganisation(applicationResource.getId()); inOrder.verify(inviteRestService).getInvitesByApplication(applicationResource.getId()); inOrder.verify(applicationService).getById(applicationResource.getId()); inOrder.verify(userService).getLeadApplicantProcessRoleOrNull(applicationResource); inOrder.verify(userService).findById(leadApplicant.getId()); inOrder.verifyNoMoreInteractions(); } @Test public void submitUpdateLeadOrganisation_loggedInUserIsLead() throws Exception { Map<String, OrganisationResource> organisationsMap = setupOrganisationResources(); ApplicationResource applicationResource = setupApplicationResource(organisationsMap); Map<String, UserResource> usersMap = setupUserResources(); setupOrganisationInvitesWithInviteForLeadOrg(applicationResource.getId(), usersMap, organisationsMap); UserResource leadApplicant = setupLeadApplicant(applicationResource, usersMap); OrganisationResource organisation = organisationsMap.get("Empire Ltd"); ApplicationTeamUpdateForm expectedForm = new ApplicationTeamUpdateForm(); List<ApplicantInviteForm> applicants = asList( new ApplicantInviteForm("Fred Brown", "fred.brown@empire.com") ); expectedForm.setApplicants(applicants); ApplicationInviteResource applicationInvite = new ApplicationInviteResource(applicants.get(0).getName(), applicants.get(0).getEmail(), applicationResource.getId()); InviteResultsResource inviteResultsResource = new InviteResultsResource(); inviteResultsResource.setInvitesSendSuccess(1); when(inviteRestService.createInvitesByOrganisation(organisation.getId(), asList(applicationInvite))).thenReturn(restSuccess(inviteResultsResource)); setLoggedInUser(leadApplicant); MvcResult mockResult = mockMvc.perform(post("/application/{applicationId}/team/update?organisation={organisationId}", applicationResource.getId(), organisation.getId()) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("applicants[0].name", applicants.get(0).getName()) .param("applicants[0].email", applicants.get(0).getEmail())) .andExpect(model().attribute("form", expectedForm)) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(format("/application/%s/team", applicationResource.getId()))) .andReturn(); InOrder inOrder = inOrder(applicationService, inviteRestService); inOrder.verify(applicationService).getById(applicationResource.getId()); inOrder.verify(inviteRestService).createInvitesByOrganisation(organisation.getId(), asList(applicationInvite)); inOrder.verifyNoMoreInteractions(); } @Test public void submitUpdateNewOrganisation_loggedInUserIsLead() throws Exception { Map<String, OrganisationResource> organisationsMap = setupOrganisationResources(); ApplicationResource applicationResource = setupApplicationResource(organisationsMap); Map<String, UserResource> usersMap = setupUserResources(); setupOrganisationInvitesWithInviteForLeadOrg(applicationResource.getId(), usersMap, organisationsMap); UserResource leadApplicant = setupLeadApplicant(applicationResource, usersMap); OrganisationResource organisation = organisationsMap.get("Org X"); ApplicationTeamUpdateForm expectedForm = new ApplicationTeamUpdateForm(); List<ApplicantInviteForm> applicants = asList( new ApplicantInviteForm("Fred Brown", "fred.brown@orgx.com") ); expectedForm.setApplicants(applicants); ApplicationInviteResource applicationInvite = new ApplicationInviteResource(applicants.get(0).getName(), applicants.get(0).getEmail(), applicationResource.getId()); InviteResultsResource inviteResultsResource = new InviteResultsResource(); inviteResultsResource.setInvitesSendSuccess(1); when(inviteRestService.createInvitesByInviteOrganisation(organisation.getName(), asList(applicationInvite))).thenReturn(restSuccess(inviteResultsResource)); setLoggedInUser(leadApplicant); MvcResult mockResult = mockMvc.perform(post("/application/{applicationId}/team/update?organisationName={organisationName}", applicationResource.getId(), organisation.getName()) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("applicants[0].name", applicants.get(0).getName()) .param("applicants[0].email", applicants.get(0).getEmail())) .andExpect(model().attribute("form", expectedForm)) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(format("/application/%s/team", applicationResource.getId()))) .andReturn(); InOrder inOrder = inOrder(applicationService, inviteRestService); inOrder.verify(applicationService).getById(applicationResource.getId()); inOrder.verify(inviteRestService).createInvitesByInviteOrganisation(organisation.getName(), asList(applicationInvite)); inOrder.verifyNoMoreInteractions(); } @Test public void submitUpdateNonLeadOrganisation_loggedInUserIsLead() throws Exception { Map<String, OrganisationResource> organisationsMap = setupOrganisationResources(); ApplicationResource applicationResource = setupApplicationResource(organisationsMap); Map<String, UserResource> usersMap = setupUserResources(); setupOrganisationInvitesWithInviteForLeadOrg(applicationResource.getId(), usersMap, organisationsMap); UserResource leadApplicant = setupLeadApplicant(applicationResource, usersMap); OrganisationResource organisation = organisationsMap.get("Ludlow"); ApplicationTeamUpdateForm expectedForm = new ApplicationTeamUpdateForm(); List<ApplicantInviteForm> applicants = asList( new ApplicantInviteForm("Joe Smith", "joe.smith@empire.com") ); expectedForm.setApplicants(applicants); ApplicationInviteResource applicationInvite = new ApplicationInviteResource(applicants.get(0).getName(), applicants.get(0).getEmail(), applicationResource.getId()); InviteResultsResource inviteResultsResource = new InviteResultsResource(); inviteResultsResource.setInvitesSendSuccess(1); when(inviteRestService.createInvitesByOrganisation(organisation.getId(), asList(applicationInvite))).thenReturn(restSuccess(inviteResultsResource)); setLoggedInUser(leadApplicant); MvcResult mockResult = mockMvc.perform(post("/application/{applicationId}/team/update?organisation={organisationId}", applicationResource.getId(), organisation.getId()) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("applicants[0].name", applicants.get(0).getName()) .param("applicants[0].email", applicants.get(0).getEmail())) .andExpect(model().attribute("form", expectedForm)) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(format("/application/%s/team", applicationResource.getId()))) .andReturn(); InOrder inOrder = inOrder(applicationService, inviteRestService); inOrder.verify(applicationService).getById(applicationResource.getId()); inOrder.verify(inviteRestService).createInvitesByOrganisation(organisation.getId(), asList(applicationInvite)); inOrder.verifyNoMoreInteractions(); } @Test public void submitUpdateNonLeadOrganisation_loggedInUserIsNonLead() throws Exception { Map<String, OrganisationResource> organisationsMap = setupOrganisationResources(); ApplicationResource applicationResource = setupApplicationResource(organisationsMap); Map<String, UserResource> usersMap = setupUserResources(); setupOrganisationInvitesWithInviteForLeadOrg(applicationResource.getId(), usersMap, organisationsMap); OrganisationResource organisation = organisationsMap.get("Ludlow"); ApplicationTeamUpdateForm expectedForm = new ApplicationTeamUpdateForm(); List<ApplicantInviteForm> applicants = asList( new ApplicantInviteForm("Joe Smith", "joe.smith@empire.com") ); expectedForm.setApplicants(applicants); ApplicationInviteResource applicationInvite = new ApplicationInviteResource(applicants.get(0).getName(), applicants.get(0).getEmail(), applicationResource.getId()); InviteResultsResource inviteResultsResource = new InviteResultsResource(); inviteResultsResource.setInvitesSendSuccess(1); when(inviteRestService.createInvitesByOrganisation(organisation.getId(), asList(applicationInvite))).thenReturn(restSuccess(inviteResultsResource)); setLoggedInUser(usersMap.get("jessica.doe@ludlow.com")); MvcResult mockResult = mockMvc.perform(post("/application/{applicationId}/team/update?organisation={organisationId}", applicationResource.getId(), organisation.getId()) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("applicants[0].name", applicants.get(0).getName()) .param("applicants[0].email", applicants.get(0).getEmail())) .andExpect(model().attribute("form", expectedForm)) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(format("/application/%s/team", applicationResource.getId()))) .andReturn(); InOrder inOrder = inOrder(applicationService, inviteRestService); inOrder.verify(applicationService).getById(applicationResource.getId()); inOrder.verify(inviteRestService).createInvitesByOrganisation(organisation.getId(), asList(applicationInvite)); inOrder.verifyNoMoreInteractions(); } @Test public void submitUpdateLeadOrganisation_loggedInUserIsLead_invalid() throws Exception { Map<String, OrganisationResource> organisationsMap = setupOrganisationResources(); ApplicationResource applicationResource = setupApplicationResource(organisationsMap); Map<String, UserResource> usersMap = setupUserResources(); setupOrganisationInvitesWithInviteForLeadOrg(applicationResource.getId(), usersMap, organisationsMap); UserResource leadApplicant = setupLeadApplicant(applicationResource, usersMap); OrganisationResource organisation = organisationsMap.get("Empire Ltd"); List<ApplicantInviteForm> applicants = asList( new ApplicantInviteForm("Joe Smith", "joe.smith@empire.com") ); setLoggedInUser(leadApplicant); MvcResult result = mockMvc.perform(post("/application/{applicationId}/team/update?organisation={organisationId}", applicationResource.getId(), organisation.getId()) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("applicants[0].name", applicants.get(0).getName())) .andExpect(status().isOk()) .andExpect(model().hasErrors()) .andExpect(model().attributeHasFieldErrors("form", "applicants[0].email")) .andExpect(view().name("application-team/edit-org")) .andReturn(); ApplicationTeamUpdateForm form = (ApplicationTeamUpdateForm) result.getModelAndView().getModel().get("form"); BindingResult bindingResult = form.getBindingResult(); assertEquals(0, bindingResult.getGlobalErrorCount()); assertEquals(1, bindingResult.getFieldErrorCount()); assertTrue(bindingResult.hasFieldErrors("applicants[0].email")); assertEquals("Please enter an email address.", bindingResult.getFieldError("applicants[0].email").getDefaultMessage()); InOrder inOrder = inOrder(applicationService, userService); inOrder.verify(applicationService, times(3)).getById(applicationResource.getId()); inOrder.verify(userService).getLeadApplicantProcessRoleOrNull(applicationResource); inOrder.verify(userService).findById(leadApplicant.getId()); inOrder.verifyNoMoreInteractions(); } @Test public void addApplicantLeadOrganisation_loggedInUserIsLead() throws Exception { Map<String, OrganisationResource> organisationsMap = setupOrganisationResources(); ApplicationResource applicationResource = setupApplicationResource(organisationsMap); Map<String, UserResource> usersMap = setupUserResources(); setupOrganisationInvitesWithInviteForLeadOrg(applicationResource.getId(), usersMap, organisationsMap); UserResource leadApplicant = setupLeadApplicant(applicationResource, usersMap); OrganisationResource organisation = organisationsMap.get("Empire Ltd"); ApplicationTeamUpdateForm expectedForm = new ApplicationTeamUpdateForm(); List<ApplicantInviteForm> applicants = asList( new ApplicantInviteForm("Fred Brown", "fred.brown@empire.com") ); expectedForm.setApplicants(applicants); ApplicationInviteResource applicationInvite = new ApplicationInviteResource(applicants.get(0).getName(), applicants.get(0).getEmail(), applicationResource.getId()); InviteResultsResource inviteResultsResource = new InviteResultsResource(); inviteResultsResource.setInvitesSendSuccess(1); when(inviteRestService.createInvitesByOrganisation(organisation.getId(), asList(applicationInvite))).thenReturn(restSuccess(inviteResultsResource)); setLoggedInUser(leadApplicant); MvcResult mockResult = mockMvc.perform(post("/application/{applicationId}/team/update/?organisation={organisationId}&addApplicant=true", applicationResource.getId(), organisation.getId()) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("applicants[0].name", applicants.get(0).getName()) .param("applicants[0].email", applicants.get(0).getEmail())) .andExpect(status().isOk()) .andExpect(view().name("application-team/edit-org")) .andReturn(); InOrder inOrder = inOrder(applicationService); inOrder.verify(applicationService, times(3)).getById(applicationResource.getId()); inOrder.verifyNoMoreInteractions(); } @Test public void addApplicantNewOrganisation_loggedInUserIsLead() throws Exception { Map<String, OrganisationResource> organisationsMap = setupOrganisationResources(); ApplicationResource applicationResource = setupApplicationResource(organisationsMap); Map<String, UserResource> usersMap = setupUserResources(); setupOrganisationInvitesWithInviteForLeadOrg(applicationResource.getId(), usersMap, organisationsMap); UserResource leadApplicant = setupLeadApplicant(applicationResource, usersMap); OrganisationResource organisation = organisationsMap.get("Org X"); ApplicationTeamUpdateForm expectedForm = new ApplicationTeamUpdateForm(); List<ApplicantInviteForm> applicants = asList( new ApplicantInviteForm("Fred Brown", "fred.brown@orgx.com") ); expectedForm.setApplicants(applicants); ApplicationInviteResource applicationInvite = new ApplicationInviteResource(applicants.get(0).getName(), applicants.get(0).getEmail(), applicationResource.getId()); InviteResultsResource inviteResultsResource = new InviteResultsResource(); inviteResultsResource.setInvitesSendSuccess(1); when(inviteRestService.createInvitesByOrganisation(organisation.getId(), asList(applicationInvite))).thenReturn(restSuccess(inviteResultsResource)); setLoggedInUser(leadApplicant); MvcResult mockResult = mockMvc.perform(post("/application/{applicationId}/team/update/?organisationName={organisationName}&addApplicant=true", applicationResource.getId(), organisation.getName()) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("applicants[0].name", applicants.get(0).getName()) .param("applicants[0].email", applicants.get(0).getEmail())) .andExpect(status().isOk()) .andExpect(view().name("application-team/edit-org")) .andReturn(); InOrder inOrder = inOrder(applicationService); inOrder.verify(applicationService, times(3)).getById(applicationResource.getId()); inOrder.verifyNoMoreInteractions(); } @Test public void removeApplicantLeadOrganisation_loggedInUserIsLead() throws Exception { Map<String, OrganisationResource> organisationsMap = setupOrganisationResources(); ApplicationResource applicationResource = setupApplicationResource(organisationsMap); Map<String, UserResource> usersMap = setupUserResources(); setupOrganisationInvitesWithInviteForLeadOrg(applicationResource.getId(), usersMap, organisationsMap); UserResource leadApplicant = setupLeadApplicant(applicationResource, usersMap); OrganisationResource organisation = organisationsMap.get("Empire Ltd"); ApplicationTeamUpdateForm expectedForm = new ApplicationTeamUpdateForm(); List<ApplicantInviteForm> applicants = asList( new ApplicantInviteForm("Fred Brown", "fred.brown@empire.com") ); expectedForm.setApplicants(applicants); ApplicationInviteResource applicationInvite = new ApplicationInviteResource(applicants.get(0).getName(), applicants.get(0).getEmail(), applicationResource.getId()); InviteResultsResource inviteResultsResource = new InviteResultsResource(); inviteResultsResource.setInvitesSendSuccess(1); when(inviteRestService.createInvitesByOrganisation(organisation.getId(), asList(applicationInvite))).thenReturn(restSuccess(inviteResultsResource)); setLoggedInUser(leadApplicant); MvcResult mockResult = mockMvc.perform(post("/application/{applicationId}/team/update/?organisation={organisationId}&removeApplicant=0", applicationResource.getId(), organisation.getId()) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("applicants[0].name", applicants.get(0).getName()) .param("applicants[0].email", applicants.get(0).getEmail())) .andExpect(status().isOk()) .andExpect(view().name("application-team/edit-org")) .andReturn(); InOrder inOrder = inOrder(applicationService); inOrder.verify(applicationService, times(3)).getById(applicationResource.getId()); inOrder.verifyNoMoreInteractions(); } @Test public void removeApplicantNewOrganisation_loggedInUserIsLead() throws Exception { Map<String, OrganisationResource> organisationsMap = setupOrganisationResources(); ApplicationResource applicationResource = setupApplicationResource(organisationsMap); Map<String, UserResource> usersMap = setupUserResources(); setupOrganisationInvitesWithInviteForLeadOrg(applicationResource.getId(), usersMap, organisationsMap); UserResource leadApplicant = setupLeadApplicant(applicationResource, usersMap); OrganisationResource organisation = organisationsMap.get("Org X"); ApplicationTeamUpdateForm expectedForm = new ApplicationTeamUpdateForm(); List<ApplicantInviteForm> applicants = asList( new ApplicantInviteForm("Fred Brown", "fred.brown@orgx.com") ); expectedForm.setApplicants(applicants); ApplicationInviteResource applicationInvite = new ApplicationInviteResource(applicants.get(0).getName(), applicants.get(0).getEmail(), applicationResource.getId()); InviteResultsResource inviteResultsResource = new InviteResultsResource(); inviteResultsResource.setInvitesSendSuccess(1); when(inviteRestService.createInvitesByOrganisation(organisation.getId(), asList(applicationInvite))).thenReturn(restSuccess(inviteResultsResource)); setLoggedInUser(leadApplicant); MvcResult mockResult = mockMvc.perform(post("/application/{applicationId}/team/update/?organisationName={organisationName}&removeApplicant=0", applicationResource.getId(), organisation.getName()) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("applicants[0].name", applicants.get(0).getName()) .param("applicants[0].email", applicants.get(0).getEmail())) .andExpect(status().isOk()) .andExpect(view().name("application-team/edit-org")) .andReturn(); InOrder inOrder = inOrder(applicationService); inOrder.verify(applicationService, times(3)).getById(applicationResource.getId()); inOrder.verifyNoMoreInteractions(); } @Test public void markApplicantLeadOrganisation_loggedInUserIsLead() throws Exception { Map<String, OrganisationResource> organisationsMap = setupOrganisationResources(); ApplicationResource applicationResource = setupApplicationResource(organisationsMap); Map<String, UserResource> usersMap = setupUserResources(); List<InviteOrganisationResource> inviteOrganisationList = setupOrganisationInvitesWithInviteForLeadOrg(applicationResource.getId(), usersMap, organisationsMap); Long applicationInviteId = inviteOrganisationList.get(2).getInviteResources().get(0).getId(); UserResource leadApplicant = setupLeadApplicant(applicationResource, usersMap); OrganisationResource organisation = organisationsMap.get("Empire Ltd"); ApplicationTeamUpdateForm expectedForm = new ApplicationTeamUpdateForm(); List<ApplicantInviteForm> applicants = asList( new ApplicantInviteForm("Fred Brown", "fred.brown@empire.com") ); expectedForm.setApplicants(applicants); setLoggedInUser(leadApplicant); MvcResult mockResult = mockMvc.perform(post("/application/{applicationId}/team/update/?organisation={organisationId}&markForRemoval={applicationInviteId}", applicationResource.getId(), organisation.getId(), applicationInviteId) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("applicants[0].name", applicants.get(0).getName()) .param("applicants[0].email", applicants.get(0).getEmail())) .andExpect(status().isOk()) .andExpect(view().name("application-team/edit-org")) .andReturn(); InOrder inOrder = inOrder(applicationService); inOrder.verify(applicationService, times(3)).getById(applicationResource.getId()); inOrder.verifyNoMoreInteractions(); } @Test public void markApplicantNewOrganisation_loggedInUserIsLead() throws Exception { Map<String, OrganisationResource> organisationsMap = setupOrganisationResources(); ApplicationResource applicationResource = setupApplicationResource(organisationsMap); Map<String, UserResource> usersMap = setupUserResources(); List<InviteOrganisationResource> inviteOrganisationList = setupOrganisationInvitesWithAnUnconfirmedOrganisation(applicationResource.getId(), usersMap, organisationsMap); Long applicationInviteId = inviteOrganisationList.get(0).getInviteResources().get(0).getId(); UserResource leadApplicant = setupLeadApplicant(applicationResource, usersMap); OrganisationResource organisation = organisationsMap.get("Ludlow"); ApplicationTeamUpdateForm expectedForm = new ApplicationTeamUpdateForm(); List<ApplicantInviteForm> applicants = asList( new ApplicantInviteForm("Fred Brown", "fred.brown@ludlow.com") ); expectedForm.setApplicants(applicants); setLoggedInUser(leadApplicant); MvcResult mockResult = mockMvc.perform(post("/application/{applicationId}/team/update/?organisationName={organisationName}&markForRemoval={applicationInviteId}", applicationResource.getId(), organisation.getName(), applicationInviteId) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("applicants[0].name", applicants.get(0).getName()) .param("applicants[0].email", applicants.get(0).getEmail())) .andExpect(status().isOk()) .andExpect(view().name("application-team/edit-org")) .andReturn(); InOrder inOrder = inOrder(applicationService); inOrder.verify(applicationService, times(3)).getById(applicationResource.getId()); inOrder.verifyNoMoreInteractions(); } private ApplicationResource setupApplicationResource(Map<String, OrganisationResource> organisationsMap) { return setupApplicationResource(organisationsMap, OPEN); } private ApplicationResource setupApplicationResource(Map<String, OrganisationResource> organisationsMap, ApplicationStatusConstants applicationStatus) { ApplicationResource applicationResource = newApplicationResource() .withName("Application name") .withApplicationStatus(applicationStatus) .build(); when(applicationService.getById(applicationResource.getId())).thenReturn(applicationResource); when(applicationService.getLeadOrganisation(applicationResource.getId())).thenReturn(organisationsMap.get("Empire Ltd")); return applicationResource; } private Map<String, UserResource> setupUserResources() { List<UserResource> userResources = newUserResource() .withFirstName("Jessica", "Paul", "Steve", "Paul") .withLastName("Doe", "Tom", "Smith", "Davidson") .withEmail("jessica.doe@ludlow.com", "paul.tom@egg.com", "steve.smith@empire.com", "paul.davidson@empire.com") .build(4); return simpleToMap(userResources, UserResource::getEmail); } private UserResource setupLeadApplicant(ApplicationResource applicationResource, Map<String, UserResource> usersMap) { UserResource leadApplicant = usersMap.get("steve.smith@empire.com"); when(userService.getLeadApplicantProcessRoleOrNull(applicationResource)).thenReturn(newProcessRoleResource() .withUser(leadApplicant) .build()); when(userService.findById(leadApplicant.getId())).thenReturn(leadApplicant); return leadApplicant; } private Map<String, OrganisationResource> setupOrganisationResources() { List<OrganisationResource> organisationResources = newOrganisationResource() .withName("Ludlow", "EGGS", "Empire Ltd", "Org X") .build(4); return simpleToMap(organisationResources, OrganisationResource::getName); } private List<InviteOrganisationResource> setupOrganisationInvitesWithInviteForLeadOrg(long applicationId, Map<String, UserResource> usersMap, Map<String, OrganisationResource> organisationsMap) { UserResource user1 = usersMap.get("jessica.doe@ludlow.com"); UserResource user2 = usersMap.get("paul.tom@egg.com"); UserResource user3 = usersMap.get("paul.davidson@empire.com"); List<ApplicationInviteResource> invitesOrg1 = newApplicationInviteResource() .withUsers(user1.getId(), null) .withNameConfirmed(user1.getName(), null) .withName("Jess Doe", "Ryan Dell") .withEmail(user1.getEmail(), "ryan.dell@ludlow.com") .withStatus(OPENED, SENT) .build(2); List<ApplicationInviteResource> invitesOrg2 = newApplicationInviteResource() .withUsers(user2.getId()) .withNameConfirmed(user2.getName()) .withName(user2.getName()) .withEmail(user2.getEmail()) .withStatus(OPENED) .build(1); List<ApplicationInviteResource> invitesOrg3 = newApplicationInviteResource() .withUsers(user3.getId()) .withNameConfirmed(user3.getName()) .withName(user3.getName()) .withEmail(user3.getEmail()) .withStatus(OPENED) .build(1); OrganisationResource org1 = organisationsMap.get("Ludlow"); OrganisationResource org2 = organisationsMap.get("EGGS"); OrganisationResource org3 = organisationsMap.get("Empire Ltd"); OrganisationResource org4 = organisationsMap.get("Org X"); List<InviteOrganisationResource> inviteOrganisationResources = newInviteOrganisationResource() .withOrganisation(org1.getId(), org2.getId(), org3.getId(), org4.getId()) .withOrganisationName(org1.getName(), org2.getName(), org3.getName(), org4.getName()) .withOrganisationNameConfirmed(org1.getName(), org2.getName(), org3.getName(), org4.getName()) .withInviteResources(invitesOrg1, invitesOrg2, invitesOrg3, null) .build(4); when(inviteRestService.getInvitesByApplication(applicationId)).thenReturn(restSuccess(inviteOrganisationResources)); return inviteOrganisationResources; } private List<InviteOrganisationResource> setupOrganisationInvitesWithoutInvitesForLeadOrg(long applicationId, Map<String, UserResource> usersMap, Map<String, OrganisationResource> organisationsMap) { UserResource user1 = usersMap.get("jessica.doe@ludlow.com"); UserResource user2 = usersMap.get("paul.tom@egg.com"); List<ApplicationInviteResource> invitesOrg1 = newApplicationInviteResource() .withUsers(user1.getId(), null) .withNameConfirmed(user1.getName(), null) .withName("Jess Doe", "Ryan Dell") .withEmail(user1.getEmail(), "ryan.dell@ludlow.com") .withStatus(OPENED, SENT) .build(2); List<ApplicationInviteResource> invitesOrg2 = newApplicationInviteResource() .withUsers(user2.getId()) .withNameConfirmed(user2.getName()) .withName(user2.getName()) .withEmail(user2.getEmail()) .withStatus(OPENED) .build(1); OrganisationResource org1 = organisationsMap.get("Ludlow"); OrganisationResource org2 = organisationsMap.get("EGGS"); List<InviteOrganisationResource> inviteOrganisationResources = newInviteOrganisationResource() .withOrganisation(org1.getId(), org2.getId()) .withOrganisationName(org1.getName(), org2.getName()) .withOrganisationNameConfirmed(org1.getName(), org2.getName()) .withInviteResources(invitesOrg1, invitesOrg2) .build(2); when(inviteRestService.getInvitesByApplication(applicationId)).thenReturn(restSuccess(inviteOrganisationResources)); return inviteOrganisationResources; } private List<InviteOrganisationResource> setupOrganisationInvitesWithAnUnconfirmedOrganisation(long applicationId, Map<String, UserResource> usersMap, Map<String, OrganisationResource> organisationsMap) { UserResource user1 = usersMap.get("jessica.doe@ludlow.com"); UserResource user2 = usersMap.get("paul.tom@egg.com"); UserResource user3 = usersMap.get("paul.davidson@empire.com"); List<ApplicationInviteResource> invitesOrg1 = newApplicationInviteResource() .withUsers(user1.getId(), null) .withNameConfirmed(user1.getName(), null) .withName("Jess Doe", "Ryan Dell") .withEmail(user1.getEmail(), "ryan.dell@ludlow.com") .withStatus(SENT, SENT) .build(2); List<ApplicationInviteResource> invitesOrg2 = newApplicationInviteResource() .withUsers(user2.getId()) .withNameConfirmed(user2.getName()) .withName(user2.getName()) .withEmail(user2.getEmail()) .withStatus(OPENED) .build(1); List<ApplicationInviteResource> invitesOrg3 = newApplicationInviteResource() .withUsers(user3.getId()) .withNameConfirmed(user3.getName()) .withName(user3.getName()) .withEmail(user3.getEmail()) .withStatus(OPENED) .build(1); OrganisationResource org2 = organisationsMap.get("EGGS"); OrganisationResource org3 = organisationsMap.get("Empire Ltd"); List<InviteOrganisationResource> inviteOrganisationResources = newInviteOrganisationResource() .withOrganisation(null, org2.getId(), org3.getId()) .withOrganisationName("Ludlow", org2.getName(), org3.getName()) .withOrganisationNameConfirmed(null, org2.getName(), org3.getName()) .withInviteResources(invitesOrg1, invitesOrg2, invitesOrg3) .build(3); when(inviteRestService.getInvitesByApplication(applicationId)).thenReturn(restSuccess(inviteOrganisationResources)); return inviteOrganisationResources; } }
package org.collectionspace.chain.csp.schema; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.collectionspace.chain.csp.config.ReadOnlySection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author caret * * */ public class Record implements FieldParent { private static final Logger log=LoggerFactory.getLogger(Record.class); private String id; private Map<String,Structure> structure=new HashMap<String,Structure>(); private Map<String,Record> subrecords=new HashMap<String,Record>(); private Map<String,FieldSet> fields=new HashMap<String,FieldSet>(); private Map<String,FieldSet> servicefields=new HashMap<String,FieldSet>(); private Map<String,FieldSet> repeatfields=new HashMap<String,FieldSet>(); private Map<String,Instance> instances=new HashMap<String,Instance>(); private Map<String,FieldSet> summarylist=new HashMap<String,FieldSet>(); private Map<String, Map<String, FieldSet>> minidataset=new HashMap<String, Map<String,FieldSet>>(); private Spec spec; private FieldSet mini_summary,mini_number,display_name; private Set<String> type; /* UI Stuff */ private String web_url,terms_used_url,number_selector,row_selector,list_key,ui_url,tab_url,primaryfield; private boolean in_findedit=false; private boolean is_multipart=false; private boolean has_terms_used = false; private boolean has_refobj_used = true; private boolean has_delete_method = false; private String services_search_keyword = "kw"; /* Service stuff */ private String authorization_name,services_url,services_list_path,in_tag,urn_syntax,authority_vocab_type,services_instances_path,services_single_instance_path; private Set<String> authorization_includes; private Map<String,String> services_record_paths=new HashMap<String,String>(); private Map<String,Field> services_filter_param=new HashMap<String,Field>(); // XXX utility methods Record(Spec parent,ReadOnlySection section) { /* parameters */ // this is what the service layer id defaults to if not specified later // standard = singular form of the concept id=(String)section.getValue("/@id"); // record,authority,compute-displayname can have multiple types using commas type=Util.getSetOrDefault(section,"/@type",new String[]{"record"}); //specified that it is included in the findedit uispec in_findedit=Util.getBooleanOrDefault(section,"/@in-findedit",false); //config whether service layer needs call as multipart or not is_multipart=Util.getBooleanOrDefault(section,"/is-multipart",true); //config whether record type has termsUsed or not (returns empty array in Json if = false ) has_terms_used = Util.getBooleanOrDefault(section,"/terms-used",true); //config whether record type has relatedObj/procs or not (returns empty array in Json if = false ) has_refobj_used = Util.getBooleanOrDefault(section,"/refobj-used",true); //config the keyword to use for searching services_search_keyword = Util.getStringOrDefault(section,"/services-search-keyword","kw"); // Used to differentiate between authority and vocabulary on create in_tag=Util.getStringOrDefault(section,"/membership-tag","inAuthority"); /* UI Layer helpers */ //ui layer path web_url=Util.getStringOrDefault(section,"/web-url",id); // specify url if not nameAuthority terms_used_url=Util.getStringOrDefault(section,"/terms-used-url","nameAuthority"); //ui layer json row number_selector=Util.getStringOrDefault(section,"/number-selector",".csc-entry-number"); //ui layer json used in list views row_selector=Util.getStringOrDefault(section,"/row-selector",".csc-recordList-row:"); list_key=Util.getStringOrDefault(section,"/list-key","procedures"+id.substring(0,1).toUpperCase()+id.substring(1)); //ui layer path: defaults to web_url if not specified ui_url=Util.getStringOrDefault(section,"/ui-url",web_url+".html"); //ui layer path tab_url=Util.getStringOrDefault(section,"/tab-url",web_url+"-tab"); /* Service layer helpers */ //path that the service layer uses to access this record services_url=Util.getStringOrDefault(section,"/services-url",id); //authorization name authorization_name = Util.getStringOrDefault(section,"/authorization-name",id); if(type.contains("record")){ authorization_includes = Util.getSetOrDefault(section,"/authorization-includes",new String[]{services_url, "/"+services_url+"/*/authorityrefs/"}); } else if(type.contains("authority")){ authorization_includes = Util.getSetOrDefault(section,"/authorization-includes",new String[]{services_url,services_url+"/*/items/", "/"+services_url+"/*/items/*/authorityrefs/", "/"+services_url+"/*/items/*/refobjs/", "/"+services_url+"/*/items/*/contacts/"}); } else if(type.contains("id")){ authorization_includes = Util.getSetOrDefault(section,"/authorization-includes",new String[]{id,"idgenerators", "/idgenerators/*/ids/"}); } else { authorization_includes = Util.getSetOrDefault(section,"/authorization-includes",new String[]{}); } //service layer paths to list data for this record type services_list_path=Util.getStringOrDefault(section,"/services-list-path",services_url+"-common-list/"+services_url+"-list-item"); //used by service layer to construct authority names urn_syntax=Util.getStringOrDefault(section,"/urn-syntax","urn:cspace.org.collectionspace.demo."+id+":name({vocab}):"+id+":name({entry})'{display}'"); authority_vocab_type = Util.getStringOrDefault(section, "/authority-vocab-type", "PersonAuthority"); services_instances_path=Util.getStringOrDefault(section,"/services-instances-path", services_url+"_common:http://collectionspace.org/services/"+services_url+","+services_url+"-common-list/"+services_url+"-list-item"); services_single_instance_path=Util.getStringOrDefault(section,"/services-single-instance-path", services_url+"_common:http://collectionspace.org/services/"+services_url+","+services_url+"-common"); primaryfield = Util.getStringOrDefault(section, "/primaryfield",""); has_delete_method = Util.getBooleanOrDefault(section, "/hasdeletemethod", false); spec=parent; } public String getID() { return id; } public String getWebURL() { return web_url; } public String getUIURL() { return ui_url; } public String getTabURL() { return tab_url; } public boolean isType(String k) { return type.contains(k); } public Spec getSpec() { return spec; } public FieldSet[] getAllServiceFields() { return servicefields.values().toArray(new FieldSet[0]); } public FieldSet[] getAllFields() { return fields.values().toArray(new FieldSet[0]); } public FieldSet getField(String id) { return fields.get(id); } public FieldSet[] getAllRepeatFields() { return repeatfields.values().toArray(new FieldSet[0]); } /* * includes all the fields that are children of repeats as well as top level fields. */ public FieldSet getRepeatField(String id) { return repeatfields.get(id); } public Structure getStructure(String id) { return structure.get(id); } public Record getSubrecord(String id) { return subrecords.get(id); } public Record[] getAllSubRecords(){ if(subrecords.values().isEmpty()){ for(FieldSet fs : this.getAllRepeatFields()){ if(fs.usesRecord()){ this.addSubRecord(fs.usesRecordId()); } } } return subrecords.values().toArray(new Record[0]); } public String getPrimaryField(){ return primaryfield; }; public Boolean hasPrimaryField(){ if(primaryfield.equals("")){return false;} else {return true;}} public String getTermsUsedURL() { return terms_used_url; } public String getNumberSelector() { return number_selector; } public String getRowSelector() { return row_selector; } public String getListKey() { return list_key; } public boolean isInFindEdit() { return in_findedit; } public boolean isMultipart() { return is_multipart; } public boolean hasTermsUsed() { return has_terms_used; } public boolean hasRefObjUsed() { return has_refobj_used; } public boolean hasDeleteMethod() { return has_delete_method; } public String getServicesSearchKeyword(){ return services_search_keyword; } public String getInTag() { return in_tag; } public String getURNSyntax() { return urn_syntax; } public String getVocabType() {return authority_vocab_type; } public Instance[] getAllInstances() { return instances.values().toArray(new Instance[0]); } public Instance getInstance(String key) { return instances.get(key); } public String getServicesURL() { return services_url; } public String getServicesListPath() { return services_list_path; } public String getServicesInstancesPath() { return services_instances_path; } public String getServicesSingleInstancePath() { return services_single_instance_path; } public String[] getServicesRecordPaths() { return services_record_paths.keySet().toArray(new String[0]); } public String getServicesRecordPath(String name) { return services_record_paths.get(name); } void setMiniNumber(Field f) { mini_number=f; } void setMiniSummary(Field f) { mini_summary=f; } void setMiniNumber(Repeat f) { mini_number=f; } void setMiniSummary(Repeat f) { mini_summary=f; } void setDisplayName(Field f) { display_name=f; } void setServicesRecordPath(String section,String path) { services_record_paths.put(section,path); } void setServicesFilterParam(String param,Field field) { services_filter_param.put(param,field); } public FieldSet getMiniNumber() { return mini_number; } public FieldSet getMiniSummary() { return mini_summary; } public FieldSet[] getAllMiniSummaryList() { return summarylist.values().toArray(new FieldSet[0]); } public FieldSet getMiniSummaryList(String key) { return summarylist.get(key); } public FieldSet getDisplayNameField() { return display_name; } public Field getFieldByServicesFilterParam(String param) { return services_filter_param.get(param); } //authorization public String getAuthorizationName(){ return authorization_name; } public String[] getAllAuthorizationTypes(){ return authorization_includes.toArray(new String[0]) ; } public Boolean isAuthorizationType(String name){ return authorization_includes.contains(name); } public void addField(FieldSet f) { fields.put(f.getID(),f); if(f.isInServices()){ servicefields.put(f.getID(),f); } } public void addAllField(FieldSet f) { repeatfields.put(f.getID(),f); } public void addStructure(Structure s) { structure.put(s.getID(),s); } public void addSubRecord(Record r) { subrecords.put(r.getID(),r); } public void addInstance(Instance n) { instances.put(n.getID(),n); spec.addInstance(n); } //obsolete? public void addMiniSummaryList(FieldSet f){ summarylist.put(f.getID(), f); } public void addMiniDataSet(FieldSet f, String s){ //s:{ name: field, name: field, name: field } if(!minidataset.containsKey(s)){ Map<String,FieldSet> subdata=new HashMap<String,FieldSet>(); minidataset.put(s, subdata); } minidataset.get(s).put(f.getID(), f); } public void addMiniDataSet(Repeat r, String s){ //s:{ name: field, name: field, name: field } if(!minidataset.containsKey(s)){ Map<String,FieldSet> subdata=new HashMap<String,FieldSet>(); minidataset.put(s, subdata); } minidataset.get(s).put(r.getID(), r); } public FieldSet[] getMiniDataSetByName(String s){ if(minidataset.containsKey(s)){ return minidataset.get(s).values().toArray(new FieldSet[0]); } return new FieldSet[0]; } public String[] getAllMiniDataSets(){ if(minidataset.isEmpty()){ return new String[0]; } return minidataset.keySet().toArray(new String[0]); } void dump(StringBuffer out) { out.append(" record id="+id+"\n"); out.append(" web_url="+web_url+"\n"); out.append(" type="+type+"\n"); } public Record getRecord() { return this; } public void config_finish(Spec spec) { for(Instance n : instances.values()) n.config_finish(spec); for(FieldSet fs : fields.values()) fs.config_finish(spec); } }
package org.eclipse.persistence.testing.oxm.mappings.binarydatacollection; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Vector; import javax.activation.DataHandler; import org.eclipse.persistence.internal.helper.ConversionManager; import org.eclipse.persistence.internal.oxm.conversion.Base64; public class EmployeeWithByteArrayObject { public static final int DEFAULT_ID = 123; private int id; private Vector photos; public EmployeeWithByteArrayObject() { super(); } public EmployeeWithByteArrayObject(int id) { super(); this.id = id; } public EmployeeWithByteArrayObject(int id, Vector photos) { super(); this.id = id; this.photos = photos; } public static Employee example1() { Vector photos = new Vector(); byte[] bytes = MyAttachmentUnmarshaller.PHOTO_BASE64.getBytes(); Byte[] objectBytes = new Byte[bytes.length]; for (int index = 0; index < bytes.length; index++) { objectBytes[index] = new Byte(bytes[index]); } photos.addElement(objectBytes); photos.addElement(objectBytes); photos.addElement(objectBytes); return new Employee(DEFAULT_ID, photos); } public int getID() { return id; } public void setID(int newId) { id = newId; } public Vector getPhotos() { return photos; } public void setPhotos(Vector vectorOfPhotos) { photos = vectorOfPhotos; } public String toString() { String returnString = "Employee: " + this.getID() + " "; if (getPhotos() != null) { returnString += "Photos: "; for (int i = 0; i < getPhotos().size(); i++) { Object next = getPhotos().elementAt(i); if (next != null) { returnString += (next + "\n" + "-->" + new String(Base64.base64Encode(((byte[])ConversionManager.getDefaultManager().convertObject(next, byte[].class))))); } else { returnString += ("null_item" + " "); } } } return returnString; } public boolean equals(Object object) { if (!(object instanceof EmployeeWithByteArrayObject)) { return false; } EmployeeWithByteArrayObject employeeObject = (EmployeeWithByteArrayObject)object; if ((this.getPhotos() == null) && (employeeObject.getPhotos() != null)) { return false; } if ((employeeObject.getPhotos() == null) && (this.getPhotos() != null)) { return false; } /** * Note: do not use Vector.contains() for byte[] arrays since each .getBytes() will return * a different hash-value and will not pass the embedded (==) during the .contain check. * You must check each base64 byte in sequence */ if ((this.getID() == employeeObject.getID()) && (((this.getPhotos() == null) && (employeeObject.getPhotos() == null)) || (this.getPhotos().isEmpty() && employeeObject.getPhotos().isEmpty())) ) { return true; } boolean equal = true; // hash equality changes for (int i = 0; i < getPhotos().size(); i++) { try{ equal = equal && equalByteArrays((Byte[])getPhotos().get(i), (Byte[])employeeObject.getPhotos().get(i)); }catch(ClassCastException e){ equal = equal && equalDataHandlers((DataHandler)getPhotos().get(i), (DataHandler)employeeObject.getPhotos().get(i)); } } return equal; } private boolean equalDataHandlers(DataHandler data, DataHandler data2){ if(!data.getContentType().equals(data2.getContentType())){ return false; } try { Object obj1 = data.getContent(); Object obj2 = data2.getContent(); if(data.getContent() instanceof ByteArrayInputStream && data2.getContent() instanceof ByteArrayInputStream){ ByteArrayInputStream controlStream = ((ByteArrayInputStream)data.getContent()); ByteArrayInputStream testStream = ((ByteArrayInputStream)data2.getContent()); if(controlStream.available() != testStream.available()){ return false; } Byte[] controlBytes = new Byte[controlStream.available()]; Byte[] testBytes = new Byte[testStream.available()]; if(!equalByteArrays(controlBytes, testBytes)){ return false; } }else{ if(!data.getContent().equals(data2.getContent())){ return false; } } } catch (IOException e) { e.printStackTrace(); return false; } return true; } // override the contains check on a Vector of byte[] arrays - see TypeDirectMappingTestSuite private boolean equalByteArrays(Byte[] array1, Byte[] array2) { if (array1.length != array2.length) { return false; } // check each base64 byte in sequence for (int i = 0; i < array1.length; i++) { if (!(array1[i].equals(array2[i]))) { return false; } } return true; } }
package com.ethlo.dachs; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; @EntityListenerIgnore public class MutableEntityDataChangeSet implements EntityDataChangeSet { private final Collection<EntityDataChange> created; private final Collection<EntityDataChange> updated; private final Collection<EntityDataChange> deleted; public MutableEntityDataChangeSet() { this.created = new LinkedList<>(); this.updated = new LinkedList<>(); this.deleted = new LinkedList<>(); } public static EntityDataChangeSet clone(EntityDataChangeSet cs) { final MutableEntityDataChangeSet e = new MutableEntityDataChangeSet(); e.getCreated().addAll(clone(cs.getCreated())); e.getUpdated().addAll(clone(cs.getUpdated())); e.getDeleted().addAll(clone(cs.getDeleted())); return e; } private static Collection<? extends EntityDataChange> clone(Collection<EntityDataChange> l) { return l.stream().map(i->clone(i)).collect(Collectors.toList()); } private static EntityDataChange clone(EntityDataChange edc) { return new EntityDataChangeImpl(edc.getId(), edc.getEntity(), clonePropChanges(edc.getPropertyChanges())); } @SuppressWarnings({ "unchecked", "rawtypes" }) private static Collection<PropertyChange<?>> clonePropChanges(Collection<PropertyChange<?>> propertyChanges) { final List<PropertyChange<?>> r = new ArrayList<>(); propertyChanges .stream() .forEach(e->r.add(new PropertyChange(e.getPropertyName(), e.getPropertyType(), e.getOldValue(), e.getNewValue()))); return r; } @Override public Collection<EntityDataChange> getCreated() { return created; } @Override public Collection<EntityDataChange> getUpdated() { return updated; } @Override public Collection<EntityDataChange> getDeleted() { return deleted; } @Override public String toString() { return "ChangeSet [" + created.size() + " created=" + created + ", " + updated.size() + " updated=" + updated + ", " + deleted.size() + " deleted=" + deleted + "]"; } @Override public boolean isEmpty() { return created.isEmpty() && updated.isEmpty() && deleted.isEmpty(); } }
package com.x.organization.assemble.control.jaxrs.personcard; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.util.List; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import com.x.base.core.container.EntityManagerContainer; import com.x.base.core.container.factory.EntityManagerContainerFactory; import com.x.base.core.project.exception.ExceptionEntityNotExist; import com.x.base.core.project.exception.ExceptionPersonNotExist; import com.x.base.core.project.http.ActionResult; import com.x.base.core.project.http.EffectivePerson; import com.x.base.core.project.jaxrs.WoFile; import com.x.base.core.project.jaxrs.WoId; import com.x.base.core.project.tools.DateTools; import com.x.organization.assemble.control.Business; import com.x.organization.assemble.control.jaxrs.personcard.ActionCreateCode.Wo; import com.x.organization.assemble.control.staticconfig.FollowConfig; import com.x.organization.core.entity.Identity; import com.x.organization.core.entity.Identity_; import com.x.organization.core.entity.Person; import com.x.organization.core.entity.Unit; import com.x.organization.core.entity.UnitDuty; import com.x.organization.core.entity.UnitDuty_; import org.apache.commons.codec.binary.Base64; class ActionPersonCode extends BaseAction { ActionResult<Wo> personcode(EffectivePerson effectivePerson, String flag) throws Exception { try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { ActionResult<Wo> result = new ActionResult<>(); Business business = new Business(emc); Person personCard = emc.find(flag, Person.class); if (null == personCard) { throw new ExceptionPersonNotExist(flag); } String fname = personCard.getId()+".png"; String content = "BEGIN:VCARD\n" + "VERSION:3.0\n" + "N:"+personCard.getName()+"\n"; if(personCard.getOfficePhone()!=null && !personCard.getOfficePhone().equals("")){ content = content+"TEL:"+personCard.getOfficePhone()+"\n"; } if(personCard.getMobile()!=null && !personCard.getMobile().equals("")){ content = content+"TEL;CELL:"+personCard.getMobile()+"\n"; } /*if(!personCard.getAddress().equals("")){ content = content+"ADR;HOME;POSTAL:;;"+personCard.getAddress()+";;;;\n"; }*/ if(personCard.getMail()!=null && !personCard.getMail().equals("")){ content = content+"EMAIL:"+personCard.getMail()+"\n"; } if(personCard.getQq()!=null && !personCard.getQq().equals("")){ content = content+"X-QQ:"+personCard.getQq()+"\n"; } if(personCard.getWeixin()!=null && !personCard.getWeixin().equals("")){ content = content+"NOTE::"+personCard.getWeixin()+"\n"; } if(personCard.getBirthday()!=null && !personCard.getBirthday().equals("")){ content = content+"BDAY:"+DateTools.formatDate(personCard.getBirthday())+"\n"; } if(personCard.getId()!=null && !personCard.getId().equals("")){ List<Identity> identityList = referenceIdentity(business,flag); if(identityList.isEmpty()){ if(!personCard.getTopUnitList().isEmpty()){ String TopUnitId = personCard.getTopUnitList().get(0); Unit unit = emc.find(flag, Unit.class); if (null == unit) { throw new ExceptionEntityNotExist(flag); } content = content+"ORG:"+unit.getName()+"\n"; } }else{ String orgString = ""; String titleString = ""; for (Identity identity : identityList) { orgString = orgString.equals("")?identity.getUnitLevelName():orgString +";"+identity.getUnitLevelName(); List<UnitDuty> unitdutyList = referenceUnitduty(business,identity.getId()); if(!unitdutyList.isEmpty()){ for(UnitDuty unitduty : unitdutyList){ if(null != unitduty){ titleString = titleString.equals("")?unitduty.getName():titleString +";"+unitduty.getName(); } } } } if(!orgString.equals("")){ content = content+"ORG:"+orgString+"\n"; } if(!titleString.equals("")){ content = content+"TITLE:"+titleString+"\n"; } } } content = content+"END:VCARD"; /* File logoFile = null; if(personCard.getIconMdpi()!=null && !personCard.getIconMdpi().equals("")){ logoFile = CodeUtil.decoderBase64File(logopath,personCard.getIconMdpi()); } File QrCodeFile = new File(path); CodeUtil.drawLogoQRCode(logoFile, QrCodeFile, content, "");*/ BufferedImage logoFile = null; ByteArrayOutputStream QrCodeFile = new ByteArrayOutputStream(); if(personCard.getIconMdpi()!=null && !personCard.getIconMdpi().equals("")){ //byte[] buffer = new BASE64Decoder().decodeBuffer(personCard.getIconMdpi()); byte[] buffer = Base64.decodeBase64(personCard.getIconMdpi()); ByteArrayInputStream in = new ByteArrayInputStream(buffer); logoFile = ImageIO.read(in); //inimageinByteArrayInputStream(); } Wo wo = new Wo(CodeUtil.drawLogoQRCodeByte(logoFile, QrCodeFile, content, ""), this.contentType(false, fname), this.contentDisposition(false, fname)); result.setData(wo); return result; } } public static class Wo extends WoFile { public Wo(byte[] bytes, String contentType, String contentDisposition) { super(bytes, contentType, contentDisposition); } } public List<Identity> referenceIdentity(Business business,String flag) throws Exception { EntityManager em = business.entityManagerContainer().get(Identity.class); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Identity> cq = cb.createQuery(Identity.class); Root<Identity> root = cq.from(Identity.class); Predicate p = cb.equal(root.get(Identity_.person), flag); return em.createQuery(cq.select(root).where(p)).getResultList(); } public List<UnitDuty> referenceUnitduty(Business business,String flag) throws Exception { EntityManager em = business.entityManagerContainer().get(UnitDuty.class); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<UnitDuty> cq = cb.createQuery(UnitDuty.class); Root<UnitDuty> root = cq.from(UnitDuty.class); Predicate p = cb.isMember(flag, root.get(UnitDuty_.identityList)); return em.createQuery(cq.select(root).where(p)).getResultList(); } }
package com.irccloud.android; import java.util.Iterator; import java.util.Timer; import java.util.TimerTask; import java.util.Map.Entry; import org.json.JSONObject; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.util.Log; import com.google.android.gcm.GCMBaseIntentService; import com.google.android.gcm.GCMRegistrar; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class GCMIntentService extends GCMBaseIntentService { public static final String GCM_ID = ""; @Override protected void onError(Context context, String errorId) { Log.e("IRCCloud", "GCM Error: " + errorId); } @SuppressLint("NewApi") @Override protected void onMessage(Context context, Intent intent) { Log.i("IRCCloud", "Recieved GCM message!"); if(intent != null && intent.getExtras() != null) { Log.d("IRCCloud", "GCM K/V pairs: " + intent.getExtras().toString()); try { String type = intent.getStringExtra("type"); if(type.equalsIgnoreCase("heartbeat_echo")) { NetworkConnection conn = NetworkConnection.getInstance(); JsonParser parser = new JsonParser(); JsonObject seenEids = parser.parse(intent.getStringExtra("seenEids")).getAsJsonObject(); Iterator<Entry<String, JsonElement>> i = seenEids.entrySet().iterator(); while(i.hasNext()) { Entry<String, JsonElement> entry = i.next(); JsonObject eids = entry.getValue().getAsJsonObject(); Iterator<Entry<String, JsonElement>> j = eids.entrySet().iterator(); while(j.hasNext()) { Entry<String, JsonElement> eidentry = j.next(); String bid = eidentry.getKey(); long eid = eidentry.getValue().getAsLong(); if(conn.ready && conn.getState() != NetworkConnection.STATE_CONNECTED) BuffersDataSource.getInstance().updateLastSeenEid(Integer.valueOf(bid), eid); Notifications.getInstance().deleteOldNotifications(Integer.valueOf(bid), eid); Notifications.getInstance().updateLastSeenEid(Integer.valueOf(bid), eid); } } } else { int cid = Integer.valueOf(intent.getStringExtra("cid")); int bid = Integer.valueOf(intent.getStringExtra("bid")); long eid = Long.valueOf(intent.getStringExtra("eid")); if(Notifications.getInstance().getNotification(eid) != null) { Log.d("IRCCloud", "A notification for this event already exists in the db, ignoring"); return; } String from = intent.getStringExtra("from_nick"); String msg = ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(intent.getStringExtra("msg"))).toString(); String chan = intent.getStringExtra("chan"); if(chan == null) chan = ""; String buffer_type = intent.getStringExtra("buffer_type"); String server_name = intent.getStringExtra("server_name"); if(server_name == null || server_name.length() == 0) server_name = intent.getStringExtra("server_hostname"); String network = Notifications.getInstance().getNetwork(cid); if(network == null) Notifications.getInstance().addNetwork(cid, server_name); Notifications.getInstance().deleteNotification(cid, bid, eid); Notifications.getInstance().addNotification(cid, bid, eid, from, msg, chan, buffer_type, type); if(buffer_type.equals("channel")) Notifications.getInstance().showNotifications(chan + ": <" + from + "> " + msg); else Notifications.getInstance().showNotifications(from + ": " + msg); } } catch (Exception e) { e.printStackTrace(); Log.w("IRCCloud", "Unable to parse GCM message"); } } } public static void scheduleRegisterTimer(int delay) { final int retrydelay = delay; new Timer().schedule(new TimerTask() { @Override public void run() { if(!GCMRegistrar.isRegistered(IRCCloudApplication.getInstance().getApplicationContext()) || !IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences("prefs", 0).contains("session_key")) { Log.w("IRCCloud", "Not logged in, not posting GCM id"); return; } if(IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences("prefs", 0).contains("gcm_registered")) { Log.w("IRCCloud", "Already POSTed this ID"); return; } boolean success = false; try { JSONObject result = NetworkConnection.getInstance().registerGCM(GCMRegistrar.getRegistrationId(IRCCloudApplication.getInstance().getApplicationContext()), IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences("prefs", 0).getString("session_key", "")); if(result.has("success")) success = result.getBoolean("success"); } catch (Exception e) { e.printStackTrace(); } if(success) { SharedPreferences.Editor editor = IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences("prefs", 0).edit(); editor.putBoolean("gcm_registered", true); editor.commit(); } else { Log.e("IRCCloud", "Failed to register device ID, will retry in " + ((retrydelay*2)/1000) + " seconds"); scheduleRegisterTimer(retrydelay * 2); } } }, delay); } @Override protected void onRegistered(Context context, String regId) { Log.i("IRCCloud", "GCM registered, id: " + regId); scheduleRegisterTimer(30000); } @Override protected void onUnregistered(Context context, String regId) { Log.i("IRCCloud", "GCM unregistered, id: " + regId); SharedPreferences.Editor editor = getSharedPreferences("prefs", 0).edit(); editor.remove("gcm_registered"); editor.commit(); } }
package org.ihtsdo.buildcloud.dao; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.*; import com.hazelcast.core.IQueue; import org.ihtsdo.buildcloud.dao.helper.ExecutionS3PathHelper; import org.ihtsdo.buildcloud.entity.Build; import org.ihtsdo.buildcloud.entity.Execution; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Required; import org.springframework.util.FileCopyUtils; import org.springframework.util.StreamUtils; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ExecutionDAOImpl implements ExecutionDAO { @Autowired private AmazonS3Client s3Client; @Autowired private ExecutionS3PathHelper pathHelper; @Autowired private String executionS3BucketName; private IQueue<String> buildQueue; private static final String BLANK = ""; private static final Logger LOGGER = LoggerFactory.getLogger(ExecutionDAOImpl.class); @Override public void save(Execution execution, String jsonConfig) { saveToBucket(execution, jsonConfig); } @Override public ArrayList<Execution> findAll(Build build) { String buildDirectoryPath = pathHelper.getBuildPath(build).toString(); ArrayList<Execution> executions = findExecutions(buildDirectoryPath, build); return executions; } @Override public Execution find(Build build, String executionId) { String executionDirectoryPath = pathHelper.getExecutionPath(build, executionId).toString(); ArrayList<Execution> executions = findExecutions(executionDirectoryPath, build); if (!executions.isEmpty()) { return executions.get(0); } else { return null; } } @Override public String loadConfiguration(Execution execution) throws IOException { String configFilePath = pathHelper.getConfigFilePath(execution); S3Object s3Object = s3Client.getObject(executionS3BucketName, configFilePath); if (s3Object != null) { S3ObjectInputStream objectContent = s3Object.getObjectContent(); return FileCopyUtils.copyToString(new InputStreamReader(objectContent)); } else { return null; } } @Override public void saveBuildScripts(File sourceDirectory, Execution execution) { saveFiles(sourceDirectory, pathHelper.getBuildScriptsPath(execution)); } @Override public void streamBuildScriptsZip(Execution execution, OutputStream outputStream) throws IOException { StringBuffer buildScriptsPath = pathHelper.getBuildScriptsPath(execution); streamS3FilesAsZip(buildScriptsPath.toString(), outputStream); } @Override public void queueForBuilding(Execution execution) { execution.setStatus(Execution.Status.QUEUED); saveStatus(execution); String executionApiUrl = String.format("http://localhost/api/v1/builds/%s/executions/%s/", execution.getBuild().getId(), execution.getId()); buildQueue.add(executionApiUrl); } private void saveFiles(File sourceDirectory, StringBuffer targetDirectoryPath) { File[] files = sourceDirectory.listFiles(); for (File file : files) { StringBuffer filePath = new StringBuffer(targetDirectoryPath).append(file.getName()); if (file.isFile()) { s3Client.putObject(executionS3BucketName, filePath.toString(), file); } else if (file.isDirectory()) { filePath.append(pathHelper.SEPARATOR); saveFiles(file, filePath); } } } private ArrayList<Execution> findExecutions(String buildDirectoryPath, Build build) { ArrayList<Execution> executions = new ArrayList<>(); LOGGER.info("List s3 objects {}, {}", executionS3BucketName, buildDirectoryPath); ListObjectsRequest listObjectsRequest = new ListObjectsRequest(executionS3BucketName, buildDirectoryPath, null, null, 100); ObjectListing objectListing = s3Client.listObjects(listObjectsRequest); List<S3ObjectSummary> objectSummaries = objectListing.getObjectSummaries(); for (S3ObjectSummary objectSummary : objectSummaries) { String key = objectSummary.getKey(); LOGGER.debug("Found key {}", key); if (key.contains("/status:")) { String[] keyParts = key.split("/"); String dateString = keyParts[2]; String status = keyParts[3].split(":")[1]; Execution execution = new Execution(dateString, status, build); executions.add(execution); } } LOGGER.debug("Found {} Executions", executions.size()); return executions; } private void saveToBucket(Execution execution, String jsonConfig) { // Save config file String configPath = pathHelper.getConfigFilePath(execution); putFile(configPath, jsonConfig); // Save status file saveStatus(execution); } private void saveStatus(Execution execution) { String statusFilePath = pathHelper.getStatusFilePath(execution, execution.getStatus().toString()); putFile(statusFilePath, BLANK); } private PutObjectResult putFile(String filePath, String contents) { return s3Client.putObject(executionS3BucketName, filePath, new ByteArrayInputStream(contents.getBytes()), new ObjectMetadata()); } private void streamS3FilesAsZip(String buildScriptsPath, OutputStream outputStream) throws IOException { LOGGER.debug("Serving zip of files in {}", buildScriptsPath); ObjectListing objectListing = s3Client.listObjects(executionS3BucketName, buildScriptsPath); int buildScriptsPathLength = buildScriptsPath.length(); ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream); for (S3ObjectSummary summary : objectListing.getObjectSummaries()) { String key = summary.getKey(); String relativePath = key.substring(buildScriptsPathLength); LOGGER.debug("Zip entry. S3Key {}, Entry path {}", key, relativePath); zipOutputStream.putNextEntry(new ZipEntry(relativePath)); S3Object object = s3Client.getObject(executionS3BucketName, key); try (InputStream objectContent = object.getObjectContent()) { StreamUtils.copy(objectContent, zipOutputStream); } } zipOutputStream.close(); } @Required public void setBuildQueue(IQueue<String> buildQueue) { this.buildQueue = buildQueue; } public void setS3Client(AmazonS3Client s3Client) { this.s3Client = s3Client; } }
package io.oasp.gastronomy.restaurant.salesmanagement.logic.impl; import io.oasp.gastronomy.restaurant.general.common.AbstractSpringIntegrationTest; import io.oasp.gastronomy.restaurant.general.common.api.datatype.Money; import io.oasp.gastronomy.restaurant.salesmanagement.common.api.OrderPosition; import io.oasp.gastronomy.restaurant.salesmanagement.common.api.datatype.OrderPositionState; import io.oasp.gastronomy.restaurant.salesmanagement.common.api.datatype.ProductOrderState; import io.oasp.gastronomy.restaurant.salesmanagement.dataaccess.api.dao.OrderPositionDao; import io.oasp.gastronomy.restaurant.salesmanagement.logic.api.Salesmanagement; import io.oasp.gastronomy.restaurant.salesmanagement.logic.api.to.OrderEto; import io.oasp.gastronomy.restaurant.salesmanagement.logic.api.to.OrderPositionEto; import io.oasp.gastronomy.restaurant.tablemanagement.logic.api.to.TableEto; import io.oasp.module.configuration.common.api.ApplicationConfigurationConstants; import javax.inject.Inject; import org.junit.Test; import org.springframework.test.context.ContextConfiguration; /** * This is the test-case of {@link Salesmanagement}. * * @author hohwille */ @ContextConfiguration({ ApplicationConfigurationConstants.BEANS_LOGIC }) public class SalesManagementTest extends AbstractSpringIntegrationTest { @Inject private Salesmanagement salesManagement; @Inject private OrderPositionDao orderPositionDao; /** * Tests if a Bill is persisted correctly. Special focus is on the mapping of {@link Money} and furthermore the query * of one of the {@link Money} fields is tested. */ @Test public void testSalesmanagement() { TableEto table = new TableEto(); Long tableId = 1L; table.setId(tableId); OrderEto order = this.salesManagement.saveOrder(table); assertEquals(tableId, Long.valueOf(order.getTableId())); } /** * Tests if the {@link OrderPositionState} is persisted correctly. The test modifies the {@link OrderPositionState} * through modifying the drinkState {@link ProductOrderState} which is a sub-state of the {@link OrderPosition} * */ @Test public void testOrderPositionStateChange() { OrderPositionEto currentOrderPosition = new OrderPositionEto(); Long orderPositionId = 1L; currentOrderPosition.setId(orderPositionId); OrderPositionState newState = OrderPositionState.PAYED; ProductOrderState newDrinkState = ProductOrderState.PREPARED; this.salesManagement.markOrderPositionDrinkAs(currentOrderPosition, newState, newDrinkState); OrderPosition orderPosition = this.orderPositionDao.findOne(orderPositionId); assertEquals(orderPosition.getState(), newState); } }
package com.jefftharris.passwdsafe; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import org.pwsafe.lib.exception.InvalidPassphraseException; import org.pwsafe.lib.file.PwsRecord; import android.app.AlertDialog; import android.app.Dialog; import android.app.ExpandableListActivity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.DialogInterface.OnClickListener; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.SimpleExpandableListAdapter; import android.widget.TextView; public class PasswdSafe extends ExpandableListActivity { private static final String TAG = "PasswdSafe"; private static final int DIALOG_GET_PASSWD = 0; private static final int DIALOG_PROGRESS = 1; private static final int DIALOG_DETAILS = 2; private static final int DIALOG_CHANGE_PASSWD = 3; private static final int MENU_ADD_RECORD = 1; private static final int MENU_DETAILS = 2; private static final int MENU_CHANGE_PASSWD = 3; private static final String RECORD = "record"; private static final String TITLE = "title"; private static final String GROUP = "group"; private static final String NO_GROUP_GROUP = "Records"; private static final int RECORD_VIEW_REQUEST = 0; private static final int RECORD_ADD_REQUEST = 1; private File itsFile; private ActivityPasswdFile itsPasswdFile; private LoadTask itsLoadTask; private boolean itsGroupRecords = true; private boolean itsIsSortCaseSensitive = true; private final ArrayList<Map<String, String>> itsGroupData = new ArrayList<Map<String, String>>(); private final ArrayList<ArrayList<HashMap<String, Object>>> itsChildData = new ArrayList<ArrayList<HashMap<String, Object>>>(); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PasswdSafeApp.dbginfo(TAG, "onCreate intent:" + getIntent()); itsFile = new File(getIntent().getData().getPath()); PasswdSafeApp app = (PasswdSafeApp)getApplication(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); itsGroupRecords = PasswdSafeApp.getGroupRecordsPref(prefs); itsIsSortCaseSensitive = PasswdSafeApp.getSortCaseSensitivePref(prefs); itsPasswdFile = app.accessPasswdFile(itsFile, this); setTitle(PasswdSafeApp.getAppFileTitle(itsFile, this)); if (!itsPasswdFile.isOpen()) { showDialog(DIALOG_GET_PASSWD); } else { showFileData(); } } /* (non-Javadoc) * @see android.app.Activity#onDestroy() */ @Override protected void onDestroy() { PasswdSafeApp.dbginfo(TAG, "onDestroy"); super.onDestroy(); if (itsPasswdFile != null) { itsPasswdFile.release(); } } /* (non-Javadoc) * @see android.app.Activity#onPause() */ @Override protected void onPause() { super.onPause(); removeDialog(DIALOG_GET_PASSWD); if (itsLoadTask != null) itsLoadTask.cancel(true); } /* (non-Javadoc) * @see android.app.Activity#onResume() */ @Override protected void onResume() { super.onResume(); itsPasswdFile.touch(); } /* (non-Javadoc) * @see android.app.Activity#onSaveInstanceState(android.os.Bundle) */ @Override protected void onSaveInstanceState(Bundle outState) { removeDialog(DIALOG_GET_PASSWD); removeDialog(DIALOG_PROGRESS); super.onSaveInstanceState(outState); } /* (non-Javadoc) * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu) */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuItem mi = menu.add(0, MENU_ADD_RECORD, 0, R.string.add_record); mi.setIcon(android.R.drawable.ic_menu_add); mi = menu.add(0, MENU_DETAILS, 0, R.string.details); mi.setIcon(android.R.drawable.ic_menu_info_details); mi = menu.add(0, MENU_CHANGE_PASSWD, 0, R.string.change_password); mi.setIcon(android.R.drawable.ic_menu_edit); return true; } /* (non-Javadoc) * @see android.app.Activity#onPrepareOptionsMenu(android.view.Menu) */ @Override public boolean onPrepareOptionsMenu(Menu menu) { MenuItem mi = menu.findItem(MENU_ADD_RECORD); if (mi != null) { boolean enabled = false; if (itsPasswdFile != null) { PasswdFileData fileData = itsPasswdFile.getFileData(); enabled = (fileData != null) && fileData.canEdit(); } mi.setEnabled(enabled); } return super.onPrepareOptionsMenu(menu); } /* (non-Javadoc) * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) */ @Override public boolean onOptionsItemSelected(MenuItem item) { boolean rc = true; switch (item.getItemId()) { case MENU_ADD_RECORD: { startActivityForResult( new Intent(Intent.ACTION_INSERT, getIntent().getData(), this, RecordEditActivity.class), RECORD_ADD_REQUEST); break; } case MENU_DETAILS: { showDialog(DIALOG_DETAILS); break; } case MENU_CHANGE_PASSWD: { showDialog(DIALOG_CHANGE_PASSWD); break; } default: { rc = super.onOptionsItemSelected(item); break; } } return rc; } /* (non-Javadoc) * @see android.app.Activity#onActivityResult(int, int, android.content.Intent) */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { PasswdSafeApp.dbginfo(TAG, "onActivityResult req: " + requestCode + ", rc: " + resultCode); if (((requestCode == RECORD_VIEW_REQUEST) || (requestCode == RECORD_ADD_REQUEST)) && (resultCode == PasswdSafeApp.RESULT_MODIFIED)) { showFileData(); } else { super.onActivityResult(requestCode, resultCode, data); } } /* (non-Javadoc) * @see android.app.Activity#onCreateDialog(int) */ @Override protected Dialog onCreateDialog(int id) { Dialog dialog = null; switch (id) { case DIALOG_GET_PASSWD: { LayoutInflater factory = LayoutInflater.from(this); final View passwdView = factory.inflate(R.layout.passwd_entry, null); AbstractDialogClickListener dlgClick = new AbstractDialogClickListener() { @Override public void onOkClicked(DialogInterface dialog) { EditText passwdInput = (EditText) passwdView .findViewById(R.id.passwd_edit); openFile( new StringBuilder(passwdInput.getText().toString())); } @Override public void onCancelClicked(DialogInterface dialog) { cancelFileOpen(); } }; AlertDialog.Builder alert = new AlertDialog.Builder(this) .setTitle("Open " + itsFile.getPath()) .setMessage("Enter password:") .setView(passwdView) .setPositiveButton("Ok", dlgClick) .setNegativeButton("Cancel", dlgClick) .setOnCancelListener(dlgClick); dialog = alert.create(); break; } case DIALOG_PROGRESS: { ProgressDialog dlg = new ProgressDialog(this); dlg.setTitle(PasswdSafeApp.getAppTitle(this)); dlg.setMessage("Loading " + itsFile.getName() + "..."); dlg.setIndeterminate(true); dlg.setCancelable(true); dialog = dlg; break; } case DIALOG_DETAILS: { LayoutInflater factory = LayoutInflater.from(this); final View detailsView = factory.inflate(R.layout.file_details, null); AlertDialog.Builder alert = new AlertDialog.Builder(this) .setTitle(itsFile.getName()) .setView(detailsView) .setNeutralButton(R.string.close, new OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog = alert.create(); break; } case DIALOG_CHANGE_PASSWD: { LayoutInflater factory = LayoutInflater.from(this); View passwdView = factory.inflate(R.layout.change_passwd, null); final EditText passwdEdit = (EditText) passwdView.findViewById(R.id.password); final EditText confirmEdit = (EditText) passwdView.findViewById(R.id.password_confirm); AbstractDialogClickListener dlgClick = new AbstractDialogClickListener() { @Override public void onOkClicked(DialogInterface dialog) { StringBuilder passwdText = new StringBuilder(passwdEdit.getText().toString()); dialog.dismiss(); changePasswd(passwdText); } }; AlertDialog.Builder alert = new AlertDialog.Builder(this) .setTitle(itsFile.getName()) .setView(passwdView) .setPositiveButton("Ok", dlgClick) .setNegativeButton("Cancel", dlgClick) .setOnCancelListener(dlgClick); AlertDialog alertDialog = alert.create(); final Button okButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE); dialog = alertDialog; break; } } return dialog; } @Override protected void onPrepareDialog(int id, Dialog dialog) { super.onPrepareDialog(id, dialog); switch (id) { case DIALOG_DETAILS: { TextView tv; tv = (TextView)dialog.findViewById(R.id.file); tv.setText(itsFile.getPath()); PasswdFileData fileData = itsPasswdFile.getFileData(); tv = (TextView)dialog.findViewById(R.id.permissions); tv.setText(fileData.canEdit() ? R.string.read_write : R.string.read_only); tv = (TextView)dialog.findViewById(R.id.num_groups); tv.setText(Integer.toString(itsGroupData.size())); tv = (TextView)dialog.findViewById(R.id.num_records); tv.setText(Integer.toString(fileData.getRecords().size())); break; } default: { break; } } } /* (non-Javadoc) * @see android.app.ExpandableListActivity#onChildClick(android.widget.ExpandableListView, android.view.View, int, int, long) */ @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { PasswdFileData fileData = itsPasswdFile.getFileData(); PwsRecord rec = (PwsRecord) itsChildData.get(groupPosition). get(childPosition). get(RECORD); Uri.Builder builder = getIntent().getData().buildUpon(); String uuid = fileData.getUUID(rec); if (uuid != null) { builder.appendQueryParameter("rec", uuid.toString()); } Intent intent = new Intent(Intent.ACTION_VIEW, builder.build(), this, RecordView.class); startActivityForResult(intent, RECORD_VIEW_REQUEST); return true; } private final void openFile(StringBuilder passwd) { removeDialog(DIALOG_GET_PASSWD); showDialog(DIALOG_PROGRESS); itsLoadTask = new LoadTask(passwd); itsLoadTask.execute(); } private final void changePasswd(StringBuilder passwd) { // TODO fill... } private final void showFileData() { itsGroupData.clear(); itsChildData.clear(); PasswdFileData fileData = itsPasswdFile.getFileData(); ArrayList<PwsRecord> records = fileData.getRecords(); RecordMapComparator comp = new RecordMapComparator(itsIsSortCaseSensitive); if (itsGroupRecords) { TreeMap<String, ArrayList<PwsRecord>> recsByGroup; if (itsIsSortCaseSensitive) { recsByGroup = new TreeMap<String, ArrayList<PwsRecord>>(); } else { recsByGroup = new TreeMap<String, ArrayList<PwsRecord>>( String.CASE_INSENSITIVE_ORDER); } for (PwsRecord rec : records) { String group = fileData.getGroup(rec); if ((group == null) || (group.length() == 0)) { group = NO_GROUP_GROUP; } ArrayList<PwsRecord> groupList = recsByGroup.get(group); if (groupList == null) { groupList = new ArrayList<PwsRecord>(); recsByGroup.put(group, groupList); } groupList.add(rec); } for (Map.Entry<String, ArrayList<PwsRecord>> entry : recsByGroup.entrySet()) { Map<String, String> groupInfo = Collections.singletonMap(GROUP, entry.getKey()); itsGroupData.add(groupInfo); ArrayList<HashMap<String, Object>> children = new ArrayList<HashMap<String, Object>>(); for (PwsRecord rec : entry.getValue()) { HashMap<String, Object> recInfo = new HashMap<String, Object>(); String title = fileData.getTitle(rec); if (title == null) { title = "Untitled"; } recInfo.put(TITLE, title); recInfo.put(RECORD, rec); children.add(recInfo); } Collections.sort(children, comp); itsChildData.add(children); } } else { Map<String, String> groupInfo = Collections.singletonMap(GROUP, NO_GROUP_GROUP); itsGroupData.add(groupInfo); ArrayList<HashMap<String, Object>> children = new ArrayList<HashMap<String, Object>>(); for (PwsRecord rec : records) { HashMap<String, Object> recInfo = new HashMap<String, Object>(); String title = fileData.getTitle(rec); if (title == null) { title = "Untitled"; } recInfo.put(TITLE, title); recInfo.put(RECORD, rec); children.add(recInfo); } Collections.sort(children, comp); itsChildData.add(children); } ExpandableListAdapter adapter = new SimpleExpandableListAdapter(PasswdSafe.this, itsGroupData, android.R.layout.simple_expandable_list_item_1, new String[] { GROUP }, new int[] { android.R.id.text1 }, itsChildData, android.R.layout.simple_expandable_list_item_1, new String[] { TITLE }, new int[] { android.R.id.text1 }); setListAdapter(adapter); if (itsGroupData.size() == 1) { getExpandableListView().expandGroup(0); } } private final void cancelFileOpen() { removeDialog(DIALOG_PROGRESS); removeDialog(DIALOG_GET_PASSWD); finish(); } private final class LoadTask extends AsyncTask<Void, Void, Object> { private final StringBuilder itsPasswd; private LoadTask(StringBuilder passwd) { itsPasswd = passwd; } /* (non-Javadoc) * @see android.os.AsyncTask#doInBackground(Params[]) */ @Override protected Object doInBackground(Void... params) { try { return new PasswdFileData(itsFile, itsPasswd); } catch (Exception e) { return e; } } /* (non-Javadoc) * @see android.os.AsyncTask#onCancelled() */ @Override protected void onCancelled() { PasswdSafeApp.dbginfo(TAG, "LoadTask cancelled"); itsLoadTask = null; cancelFileOpen(); } /* (non-Javadoc) * @see android.os.AsyncTask#onPostExecute(java.lang.Object) */ @Override protected void onPostExecute(Object result) { if (isCancelled()) { onCancelled(); return; } PasswdSafeApp.dbginfo(TAG, "LoadTask post execute"); dismissDialog(DIALOG_PROGRESS); itsLoadTask = null; if (result instanceof PasswdFileData) { itsPasswdFile.setFileData((PasswdFileData)result); showFileData(); } else if (result instanceof Exception) { Exception e = (Exception)result; if (((e instanceof IOException) && e.getMessage().equals("Invalid password")) || (e instanceof InvalidPassphraseException)) PasswdSafeApp.showFatalMsg("Invalid password", PasswdSafe.this); else PasswdSafeApp.showFatalMsg(e, PasswdSafe.this); } } } private static final class RecordMapComparator implements Comparator<HashMap<String, Object>> { private boolean itsIsSortCaseSensitive; public RecordMapComparator(boolean sortCaseSensitive) { itsIsSortCaseSensitive = sortCaseSensitive; } public int compare(HashMap<String, Object> arg0, HashMap<String, Object> arg1) { String title0 = arg0.get(TITLE).toString(); String title1 = arg1.get(TITLE).toString(); if (itsIsSortCaseSensitive) { return title0.compareTo(title1); } else { return title0.compareToIgnoreCase(title1); } } } }
package com.google.training.cpd200.conference; import com.google.api.server.spi.Constant; /** * Contains the client IDs and scopes for allowed clients consuming the conference API. */ public class Constants { public static final String WEB_CLIENT_ID = "replace with your client id"; public static final String EMAIL_SCOPE = Constant.API_EMAIL_SCOPE; public static final String API_EXPLORER_CLIENT_ID = Constant.API_EXPLORER_CLIENT_ID; public static final String MEMCACHE_ANNOUNCEMENTS_KEY = "RECENT_ANNOUNCEMENTS"; }
package org.opennms.netmgt.provision.support; import java.net.BindException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import org.apache.mina.core.RuntimeIoException; import org.apache.mina.core.future.CloseFuture; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.future.IoFutureListener; import org.apache.mina.core.service.IoHandler; import org.apache.mina.core.service.IoProcessor; import org.apache.mina.core.service.SimpleIoProcessorPool; import org.apache.mina.core.session.IoSessionInitializer; import org.apache.mina.transport.socket.SocketConnector; import org.apache.mina.transport.socket.nio.NioProcessor; import org.apache.mina.transport.socket.nio.NioSession; import org.apache.mina.transport.socket.nio.NioSocketConnector; import org.opennms.core.utils.LogUtils; /** * <p>This {@link ConnectionFactory} type will create a new {@link NioSocketConnector} * for every call to {@link #connect(SocketAddress, SocketAddress, IoSessionInitializer)}. * This is a naive implementation that does not really take advantage of the asynchronous * operations in MINA since it is creating new threads for each socket operation.</p> * * @author Seth * @author ranger * @author Duncan Mackintosh */ public class ConnectionFactoryNewConnectorImpl extends ConnectionFactory { private static final Executor m_executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); private static final IoProcessor<NioSession> m_processor = new SimpleIoProcessorPool<NioSession>(NioProcessor.class, m_executor); private ThreadLocal<Integer> m_port = new ThreadLocal<Integer>(); private final Object m_portMutex = new Object(); /** * Create a new factory. Private because one should use {@link #getFactory(int)} */ protected ConnectionFactoryNewConnectorImpl(int timeoutInMillis) { super(timeoutInMillis); } private static final NioSocketConnector getSocketConnector(long timeout, IoHandler handler) { // Create a new NioSocketConnector NioSocketConnector connector = new NioSocketConnector(m_executor, m_processor); // Enable SO_REUSEADDR on the socket so that TIMED_WAIT connections that are bound on the // same port do not block new outgoing connections. If the connections are blocked, then // the following exception will be thrown under heavy load: // Caused by: java.net.SocketException: Invalid argument // at sun.nio.ch.Net.connect(Native Method) // at sun.nio.ch.SocketChannelImpl.connect(SocketChannelImpl.java:500) // at org.apache.mina.transport.socket.nio.NioSocketConnector.connect(NioSocketConnector.java:188) connector.getSessionConfig().setReuseAddress(true); // Setting SO_LINGER will prevent TIME_WAIT sockets altogether because TCP connections will be // forcefully terminated with RST packets. However, this doesn't seem to be necessary to maintain // performance of the outgoing connections. As long as SO_REUSEADDR is set, the operating system // and Java appear to recycle the ports effectively although some will remain in TIME_WAIT state. //connector.getSessionConfig().setSoLinger(0); connector.setHandler(handler); connector.setConnectTimeoutMillis(timeout); return connector; } /** * <p>Connect to a remote socket. If org.opennms.netmgt.provision.maxConcurrentConnections * is set, this may block until a connection slot is available.</p> * * <p>You must dispose both the {@link ConnectionFactoryNewConnectorImpl} and {@link ConnectFuture} when done * by calling {@link #dispose(ConnectionFactoryNewConnectorImpl, ConnectFuture)}.</p> * * @param remoteAddress * Destination address * @param init * Initialiser for the IoSession * @return * ConnectFuture from a Mina connect call */ @Override public ConnectFuture connect(SocketAddress remoteAddress, IoSessionInitializer<? extends ConnectFuture> init, IoHandler handler) { SocketConnector connector = getSocketConnector(getTimeout(), handler); InetSocketAddress localAddress = null; synchronized (m_portMutex) { if (m_port.get() == null) { // Fetch a new ephemeral port localAddress = new InetSocketAddress(0); m_port.set(localAddress.getPort()); } else { localAddress = new InetSocketAddress(m_port.get()); } } final ConnectFuture cf = connector.connect(remoteAddress, localAddress, init); cf.addListener(portSwitcher(connector, remoteAddress, init, handler)); cf.addListener(connectorDisposer(connector)); return cf; } private static IoFutureListener<ConnectFuture> connectorDisposer(final SocketConnector connector) { return new IoFutureListener<ConnectFuture>() { public void operationComplete(ConnectFuture future) { try { // Add a listener to the CloseFuture that will dispose of the connector once the // conversation is complete future.getSession().getCloseFuture().addListener(new IoFutureListener<CloseFuture>() { @Override public void operationComplete(CloseFuture future) { LogUtils.debugf(this, "Disposing of connector: %s", Thread.currentThread().getName()); connector.dispose(); } }); } catch (RuntimeIoException e) { LogUtils.debugf(this, e, "Exception of type %s caught, disposing of connector: %s", e.getClass().getName(), Thread.currentThread().getName()); // This will be thrown in the event of a ConnectException for example connector.dispose(); } } }; } private IoFutureListener<ConnectFuture> portSwitcher(final SocketConnector connector, final SocketAddress remoteAddress, final IoSessionInitializer<? extends ConnectFuture> init, final IoHandler handler) { return new IoFutureListener<ConnectFuture>() { public void operationComplete(ConnectFuture future) { try { Throwable e = future.getException(); // If we failed to bind to the outgoing port... if (e != null && e instanceof BindException) { synchronized(m_portMutex) { // ... then reset the port LogUtils.warnf(this, "Resetting outgoing TCP port, value was %d", m_port.get()); m_port.set(null); } // and reattempt the connection connect(remoteAddress, init, handler); } } catch (RuntimeIoException e) { LogUtils.debugf(this, e, "Exception of type %s caught, disposing of connector: %s", e.getClass().getName(), Thread.currentThread().getName()); // This will be thrown in the event of a ConnectException for example connector.dispose(); } } }; } /** * Delegates completely to {@link #connect(SocketAddress, SocketAddress, IoSessionInitializer, IoHandler)} * since we are recreating connectors during each invocation. * * @param remoteAddress * @param localAddress * @param init * @param handler */ @Override public ConnectFuture reConnect(SocketAddress remoteAddress, IoSessionInitializer<? extends ConnectFuture> init, IoHandler handler) { return connect(remoteAddress, init, handler); } @Override protected void dispose() { // Do nothing; we dispose of every NioSocketConnector as soon as a session is complete } }
package com.google.zxing.client.android; import java.io.ByteArrayOutputStream; import java.util.Map; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import com.google.zxing.BinaryBitmap; import com.google.zxing.DecodeHintType; import com.google.zxing.MultiFormatReader; import com.google.zxing.PlanarYUVLuminanceSource; import com.google.zxing.ReaderException; import com.google.zxing.Result; import com.google.zxing.common.HybridBinarizer; /** * * * @author lijian * @date 2017-8-27 4:41:36 */ final class DecodeHandler extends Handler { private static final String TAG = DecodeHandler.class.getSimpleName(); private final CaptureActivity activity; private final MultiFormatReader multiFormatReader; private boolean running = true; /** * * * @param activity * @param hints * */ DecodeHandler(CaptureActivity activity, Map<DecodeHintType, Object> hints) { multiFormatReader = new MultiFormatReader(); multiFormatReader.setHints(hints); this.activity = activity; } @Override public void handleMessage(Message message) { if (!running) { return; } switch (message.what) { case R.id.decode:// (CaptureActivityHandlerhandleMessage)-(cameraManager.requestPreviewFrame) decode((byte[]) message.obj, message.arg1, message.arg2); break; case R.id.quit:// CaptureActivityHandler.quitSynchronously() running = false; Looper.myLooper().quit(); break; } } /** * * * @param data * YUV * @param width * * @param height * */ private void decode(byte[] data, int width, int height) { long start = System.currentTimeMillis(); Result rawResult = null; // YUV PlanarYUVLuminanceSource source = activity.getCameraManager() .buildLuminanceSource(data, width, height); if (source != null) { // BinaryBitmap;HybridBinarizer BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); try { rawResult = multiFormatReader.decodeWithState(bitmap); } catch (ReaderException re) { // continue } finally { multiFormatReader.reset(); } } Handler handler = activity.getHandler(); if (rawResult != null) { // log long end = System.currentTimeMillis(); Log.d(TAG, " " + (end - start) + " ms"); if (handler != null) { Message message = Message.obtain(handler, R.id.decode_succeeded, rawResult); Bundle bundle = new Bundle(); bundleThumbnail(source, bundle); message.setData(bundle); message.sendToTarget(); } } else { if (handler != null) { Message message = Message.obtain(handler, R.id.decode_failed); message.sendToTarget(); } } } /** * * * @param source * * @param bundle */ private static void bundleThumbnail(PlanarYUVLuminanceSource source, Bundle bundle) { int[] pixels = source.renderThumbnail(); int width = source.getThumbnailWidth(); int height = source.getThumbnailHeight(); Bitmap bitmap = Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.ARGB_8888); ByteArrayOutputStream out = new ByteArrayOutputStream(); // boolean compress(Bitmap.CompressFormat format, int quality, // OutputStream stream) // trueBitmapFactory.decodeStream() // BitmapFactoryalpha(JPEG) // (color // depth),(bitdePth),,2n,8bit28 // format // quality 0-100 // 0100PNGquality // stream // true bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out); bundle.putByteArray(DecodeThread.BARCODE_BITMAP, out.toByteArray()); bundle.putFloat(DecodeThread.BARCODE_SCALED_FACTOR, (float) width / source.getWidth()); } }
package org.osgi.test.cases.deploymentadmin.tc1.tb1.DeploymentAdmin; import org.osgi.service.deploymentadmin.DeploymentException; import org.osgi.service.deploymentadmin.DeploymentPackage; import org.osgi.test.cases.deploymentadmin.tc1.tbc.DeploymentConstants; import org.osgi.test.cases.deploymentadmin.tc1.tbc.DeploymentTestControl; import org.osgi.test.cases.deploymentadmin.tc1.tbc.util.TestingDeploymentPackage; public class InstallPackageThread extends Thread { private DeploymentTestControl tbc; private TestingDeploymentPackage testDP; DeploymentPackage dp = null; private boolean installed=false;//true if the DP is already installed private boolean uninstalled=false;//true if the DP is already uninstalled private boolean uninstall=false;//true if you want to uninstall the DP private boolean uninstalling=false;//true if the DP is uninstalling private boolean running=false;//true if this Thread is running public static final int EXCEPTION_NOT_THROWN = -1; private int exceptionCodeInstall = EXCEPTION_NOT_THROWN; private int exceptionCodeUninstall = EXCEPTION_NOT_THROWN; protected InstallPackageThread(DeploymentTestControl tbc, TestingDeploymentPackage testDP) { this.tbc = tbc; this.testDP = testDP; } public void uninstallDP(boolean blockDP) { if (isAlive()) { uninstall=true; //If a blocked DP is being uninstalled, you cannot wait until this Thread die, otherwise it waits forever if (!blockDP) { try { this.join(DeploymentConstants.SHORT_TIMEOUT); } catch (InterruptedException e) { } } } } public boolean isInstalled() { return installed; } public boolean isRunning() { return running; } public boolean isUninstalled() { return uninstalled; } public int getDepExceptionCodeInstall() { return exceptionCodeInstall; } public int getDepExceptionCodeUninstall() { return exceptionCodeUninstall; } public DeploymentPackage getDeploymentPackage() { return dp; } public boolean isUninstalling() { return uninstalling; } public synchronized void run() { try { try { running=true; dp = tbc.installDeploymentPackage(tbc.getWebServer() + testDP.getFilename()); installed=(dp==null?false:true); } catch (Exception e) { if (e instanceof DeploymentException) { exceptionCodeInstall = ((DeploymentException)e).getCode(); } } } finally { while (!uninstall) { try { this.wait(100); } catch (InterruptedException e) { } } if (isInstalled()) { try { uninstalling = true; dp.uninstall(); uninstalled=true; } catch (Exception e) { if (e instanceof DeploymentException) { exceptionCodeUninstall = ((DeploymentException)e).getCode(); } } } } } }
package com.oakesville.mythling; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.Calendar; import java.util.Map; import java.util.TimeZone; import java.util.Timer; import java.util.TimerTask; import org.json.JSONException; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.NavUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Toast; import com.oakesville.mythling.app.AppData; import com.oakesville.mythling.app.AppSettings; import com.oakesville.mythling.app.BadSettingsException; import com.oakesville.mythling.media.Item; import com.oakesville.mythling.media.LiveStreamInfo; import com.oakesville.mythling.media.MediaList; import com.oakesville.mythling.media.MediaSettings; import com.oakesville.mythling.media.MediaSettings.MediaType; import com.oakesville.mythling.media.MediaSettings.SortType; import com.oakesville.mythling.media.MediaSettings.ViewType; import com.oakesville.mythling.media.Movie; import com.oakesville.mythling.media.Recording; import com.oakesville.mythling.media.StorageGroup; import com.oakesville.mythling.media.TunerInUseException; import com.oakesville.mythling.media.TvShow; import com.oakesville.mythling.prefs.PrefsActivity; import com.oakesville.mythling.util.FrontendPlayer; import com.oakesville.mythling.util.HttpHelper; import com.oakesville.mythling.util.MediaListParser; import com.oakesville.mythling.util.MythTvParser; import com.oakesville.mythling.util.Recorder; import com.oakesville.mythling.util.ServiceFrontendPlayer; import com.oakesville.mythling.util.SocketFrontendPlayer; import com.oakesville.mythling.util.Transcoder; /** * Base class for the two different ways to view collections of MythTV media. */ public abstract class MediaActivity extends Activity { private static final String TAG = MediaActivity.class.getSimpleName(); protected MediaList mediaList; private static AppData appData; public static AppData getAppData() { return appData; } public static void setAppData(AppData data) { appData = data; } private AppSettings appSettings; public AppSettings getAppSettings() { return appSettings; } private MediaType mediaType; protected MediaType getMediaType() { return mediaType; } protected void setMediaType(MediaType mt) { this.mediaType = mt; } public String getCharSet() { return "UTF-8"; } private MenuItem mediaMenuItem; protected MenuItem getMediaMenuItem() { return mediaMenuItem; } private MenuItem searchMenuItem; private MenuItem viewMenuItem; private MenuItem sortMenuItem; private MenuItem moviesMenuItem; private MenuItem tvSeriesMenuItem; private MenuItem musicMenuItem; private MenuItem mythwebMenuItem; private static MediaPlayer mediaPlayer; private ProgressBar progressBar; private ProgressDialog countdownDialog; private int count; private Timer timer; public abstract void refresh() throws BadSettingsException; public abstract ListView getListView(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); appSettings = new AppSettings(getApplicationContext()); } protected ProgressBar createProgressBar() { progressBar = (ProgressBar)findViewById(R.id.progress); progressBar.setVisibility(View.GONE); progressBar.setIndeterminate(true); progressBar.setScaleX(0.20f); progressBar.setScaleY(0.20f); return progressBar; } @Override public boolean onPrepareOptionsMenu(Menu menu) { MediaSettings mediaSettings = appSettings.getMediaSettings(); mediaMenuItem = menu.findItem(R.id.menu_media); if (mediaMenuItem != null) { mediaMenuItem.setTitle(mediaSettings.getTitle()); if (mediaSettings.isMusic()) mediaMenuItem.getSubMenu().findItem(R.id.media_music).setChecked(true); else if (mediaSettings.isLiveTv()) mediaMenuItem.getSubMenu().findItem(R.id.media_tv).setChecked(true); else if (mediaSettings.isMovies()) mediaMenuItem.getSubMenu().findItem(R.id.media_movies).setChecked(true); else if (mediaSettings.isTvSeries()) mediaMenuItem.getSubMenu().findItem(R.id.media_tv_series).setChecked(true); else if (mediaSettings.isVideos()) mediaMenuItem.getSubMenu().findItem(R.id.media_videos).setChecked(true); else mediaMenuItem.getSubMenu().findItem(R.id.media_recordings).setChecked(true); moviesMenuItem = mediaMenuItem.getSubMenu().findItem(R.id.media_movies); showMoviesMenuItem(supportsMovies()); tvSeriesMenuItem = mediaMenuItem.getSubMenu().findItem(R.id.media_tv_series); showTvSeriesMenuItem(supportsTvSeries()); musicMenuItem = mediaMenuItem.getSubMenu().findItem(R.id.media_music); showMusicMenuItem(supportsMusic()); } searchMenuItem = menu.findItem(R.id.menu_search); showSearchMenu(supportsSearch()); sortMenuItem = menu.findItem(R.id.menu_sort); showSortMenu(supportsSort()); viewMenuItem = menu.findItem(R.id.menu_view); showViewMenu(supportsViewMenu()); mythwebMenuItem = menu.findItem(R.id.menu_mythweb); showMythwebMenu(supportsMythwebMenu()); return super.onPrepareOptionsMenu(menu); } protected void showSearchMenu(boolean show) { if (searchMenuItem != null) { searchMenuItem.setEnabled(show); searchMenuItem.setVisible(show); } } protected void showMoviesMenuItem(boolean show) { if (moviesMenuItem != null) { moviesMenuItem.setEnabled(show); moviesMenuItem.setVisible(show); } } protected void showTvSeriesMenuItem(boolean show) { if (tvSeriesMenuItem != null) { tvSeriesMenuItem.setEnabled(show); tvSeriesMenuItem.setVisible(show); } } protected void showMusicMenuItem(boolean show) { if (musicMenuItem != null) { musicMenuItem.setEnabled(show); musicMenuItem.setVisible(show); } } protected void showViewMenu(boolean show) { if (viewMenuItem != null) { MediaSettings mediaSettings = appSettings.getMediaSettings(); if (show) { viewMenuItem.setTitle(""); viewMenuItem.setIcon(mediaSettings.getViewIcon()); if (mediaSettings.getViewType() == ViewType.detail) viewMenuItem.getSubMenu().findItem(R.id.view_detail).setChecked(true); else viewMenuItem.getSubMenu().findItem(R.id.view_list).setChecked(true); } else { mediaSettings.setViewType(ViewType.list); } viewMenuItem.setEnabled(show); viewMenuItem.setVisible(show); } } protected void showMythwebMenu(boolean show) { if (mythwebMenuItem != null) { mythwebMenuItem.setEnabled(show); mythwebMenuItem.setVisible(show); } } protected void showSortMenu(boolean show) { if (sortMenuItem != null) { if (show) { MediaSettings mediaSettings = appSettings.getMediaSettings(); sortMenuItem.setTitle(mediaSettings.getSortTypeTitle()); if (mediaSettings.getSortType() == SortType.byDate) sortMenuItem.getSubMenu().findItem(R.id.sort_byDate).setChecked(true); else if (mediaSettings.getSortType() == SortType.byRating) sortMenuItem.getSubMenu().findItem(R.id.sort_byRating).setChecked(true); else sortMenuItem.getSubMenu().findItem(R.id.sort_byTitle).setChecked(true); } sortMenuItem.setEnabled(show); sortMenuItem.setVisible(show); } } protected boolean supportsSearch() { return getAppSettings().isMythlingMediaServices(); } protected boolean supportsSort() { return mediaList != null && mediaList.supportsSort(); } protected boolean supportsViewMenu() { return mediaList != null && mediaList.canHaveArtwork(); } protected boolean supportsMovies() { return getAppSettings().isVideosCategorization(); } protected boolean supportsTvSeries() { return getAppSettings().isVideosCategorization(); } protected boolean supportsMusic() { return getAppSettings().isMythlingMediaServices(); } protected boolean supportsMythwebMenu() { return getAppSettings().isMythWebAccessEnabled(); } protected boolean isListView() { return !isDetailView(); } protected boolean isDetailView() { return false; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { NavUtils.navigateUpFromSameTask(this); return true; } try { if (sortMenuItem != null) sortMenuItem.setTitle(appSettings.getMediaSettings().getSortTypeTitle()); if (viewMenuItem != null) viewMenuItem.setIcon(appSettings.getMediaSettings().getViewIcon()); if (item.getItemId() == R.id.media_music) { appSettings.setMediaType(MediaType.music); item.setChecked(true); mediaMenuItem.setTitle(MediaSettings.getMediaTitle(MediaType.music)); showViewMenu(supportsViewMenu()); showSortMenu(supportsSort()); refresh(); return true; } else if (item.getItemId() == R.id.media_videos) { appSettings.setMediaType(MediaType.videos); item.setChecked(true); mediaMenuItem.setTitle(MediaSettings.getMediaTitle(MediaType.videos)); showViewMenu(supportsViewMenu()); showSortMenu(supportsSort()); refresh(); return true; } else if (item.getItemId() == R.id.media_recordings) { appSettings.setMediaType(MediaType.recordings); item.setChecked(true); mediaMenuItem.setTitle(MediaSettings.getMediaTitle(MediaType.recordings)); showViewMenu(supportsViewMenu()); showSortMenu(supportsSort()); refresh(); return true; } else if (item.getItemId() == R.id.media_tv) { appSettings.setMediaType(MediaType.liveTv); item.setChecked(true); mediaMenuItem.setTitle(MediaSettings.getMediaTitle(MediaType.liveTv)); showViewMenu(supportsViewMenu()); showSortMenu(supportsSort()); refresh(); return true; } else if (item.getItemId() == R.id.media_movies) { appSettings.setMediaType(MediaType.movies); item.setChecked(true); mediaMenuItem.setTitle(MediaSettings.getMediaTitle(MediaType.movies)); showViewMenu(supportsViewMenu()); showSortMenu(supportsSort()); refresh(); return true; } else if (item.getItemId() == R.id.media_tv_series) { appSettings.setMediaType(MediaType.tvSeries); item.setChecked(true); mediaMenuItem.setTitle(MediaSettings.getMediaTitle(MediaType.tvSeries)); showViewMenu(supportsViewMenu()); showSortMenu(supportsSort()); refresh(); return true; } else if (item.getItemId() == R.id.sort_byTitle) { appSettings.setSortType(SortType.byTitle); item.setChecked(true); sortMenuItem.setTitle(R.string.menu_byTitle); sort(); return true; } else if (item.getItemId() == R.id.sort_byDate) { appSettings.setSortType(SortType.byDate); item.setChecked(true); sortMenuItem.setTitle(R.string.menu_byDate); sort(); return true; } else if (item.getItemId() == R.id.sort_byRating) { appSettings.setSortType(SortType.byRating); item.setChecked(true); sortMenuItem.setTitle(R.string.menu_byRating); sort(); return true; } else if (item.getItemId() == R.id.view_list) { appSettings.setViewType(ViewType.list); item.setChecked(true); viewMenuItem.setIcon(R.drawable.ic_menu_list); goListView(); return true; } else if (item.getItemId() == R.id.view_detail) { appSettings.setViewType(ViewType.detail); item.setChecked(true); viewMenuItem.setIcon(R.drawable.ic_menu_detail); goDetailView(); return true; } else if (item.getItemId() == R.id.menu_refresh) { refresh(); return true; } else if (item.getItemId() == R.id.menu_settings) { startActivity(new Intent(this, PrefsActivity.class)); return true; } else if (item.getItemId() == R.id.menu_search) { return onSearchRequested(); } else if (item.getItemId() == R.id.menu_mythweb) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(appSettings.getMythWebUrl()))); return true; } else if (item.getItemId() == R.id.menu_help) { String url = getResources().getString(R.string.url_help); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url), getApplicationContext(), WebViewActivity.class)); return true; } } catch (BadSettingsException ex) { stopProgress(); Toast.makeText(getApplicationContext(), "Bad or missing setting:\n" + ex.getMessage(), Toast.LENGTH_LONG).show(); } catch (Exception ex) { if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); stopProgress(); Toast.makeText(getApplicationContext(), "Error: " + ex.toString(), Toast.LENGTH_LONG).show(); } return super.onOptionsItemSelected(item); } protected void playItem(final Item item) { try { AppSettings appSettings = getAppSettings(); if (appSettings.isDevicePlayback()) { if (getListView() != null) // TODO what about pager activity? { String msg = (item.isMusic() ? "Playing: '" : "Loading: '") + item.getTitle() + "'"; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, new String[]{msg}); getListView().setAdapter(adapter); } startProgress(); stopMediaPlayer(); // music if (item.isMusic()) { if (mediaPlayer == null) { mediaPlayer = new MediaPlayer(); mediaPlayer.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { mediaPlayer.reset(); onResume(); } }); } String musicUrl = appSettings.getMythTvServicesBaseUrlWithCredentials() + "/Content/GetMusic?Id=" + item.getId(); mediaPlayer.setDataSource(appSettings.getAppContext(), Uri.parse(musicUrl)); // TODO async? mediaPlayer.prepare(); mediaPlayer.start(); stopProgress(); } else { if (item.isLiveTv() || item.isMovie()) { if (item.isLiveTv() && ((TvShow)item).getEndTime().compareTo(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime()) < 0) { new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Live TV") .setMessage("Show has already ended: " + ((TvShow)item).getShowInfo()) .setPositiveButton("OK", null) .show(); stopProgress(); onResume(); return; } String msg = null; if (item.isLiveTv()) msg = ((TvShow)item).getShowInfo() + "\n\nRecording will be scheduled if necessary."; else msg = ((Movie)item).getShowInfo(); new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle(item.getTitle()) .setMessage(msg) .setPositiveButton("Watch", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { try { if (item.isLiveTv()) new StreamTvTask((TvShow)item).execute(getAppSettings().getMythTvServicesBaseUrl()); else new StreamVideoTask(item).execute(getAppSettings().getMythTvServicesBaseUrl()); } catch (MalformedURLException ex) { stopProgress(); if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); Toast.makeText(getApplicationContext(), "Error: " + ex.toString(), Toast.LENGTH_LONG).show(); } } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { stopProgress(); onResume(); } }) .show(); } else { new StreamVideoTask(item).execute(appSettings.getMythTvServicesBaseUrl()); } } } else // frontend playback { final FrontendPlayer player; if (item.isMusic() || mediaList.getStorageGroup() == null) // frontend services require storage groups player = new SocketFrontendPlayer(appSettings, mediaList.getBasePath(), item, getCharSet()); else player = new ServiceFrontendPlayer(appSettings, item); if (player.checkIsPlaying()) { new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Interrupt") .setMessage("Stop current playback?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { player.stop(); startPlayback(item, player); } }) .setNegativeButton("No", null) .show(); } else { startPlayback(item, player); } } } catch (Exception ex) { if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); Toast.makeText(getApplicationContext(), "Error: " + ex.toString(), Toast.LENGTH_LONG).show(); } } private void stopMediaPlayer() { if (mediaPlayer != null) { if (mediaPlayer.isPlaying()) { mediaPlayer.stop(); mediaPlayer.release(); } mediaPlayer.reset(); } } protected void goDetailView() { // default does nothing } protected void goListView() { // default does nothing } public void sort() throws IOException, JSONException, ParseException { startProgress(); refreshMediaList(); } private void startPlayback(Item item, final FrontendPlayer player) { if (item.isLiveTv()) { new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(item.getTitle()) .setMessage("TODO: Frontend Live TV playback not yet supported.") .setPositiveButton("OK", null) .show(); } else if (item.isRecording()) { new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(item.getTitle()) .setMessage(((Recording)item).getShowInfo()) .setPositiveButton("Play", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { player.play(); } }) .setNegativeButton("Cancel", null) .show(); } else { try { player.play(); // reset progress count = 0; // prepare for a progress bar dialog countdownDialog = new ProgressDialog(this); countdownDialog.setCancelable(true); countdownDialog.setMessage("Playing " + MediaSettings.getMediaLabel(item.getType()) + ": " + item.getLabel()); countdownDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); countdownDialog.setProgressPercentFormat(null); countdownDialog.setProgressNumberFormat(null); countdownDialog.setMax(10); countdownDialog.setCancelable(true); countdownDialog.setButton(Dialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); stopTimer(); } }); countdownDialog.setButton(Dialog.BUTTON_NEGATIVE, "Stop", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { player.stop(); dialog.dismiss(); stopTimer(); } }); countdownDialog.setCanceledOnTouchOutside(true); countdownDialog.show(); countdownDialog.setProgress(10); tick(); } catch (Exception ex) { if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); stopTimer(); } } } @Override protected void onStop() { if (countdownDialog != null && countdownDialog.isShowing()) countdownDialog.dismiss(); stopTimer(); super.onStop(); } private void stopTimer() { if (timer != null) timer.cancel(); count = 0; } private void tick() { if (timer != null) timer.cancel(); timer = new Timer(); timer.schedule(new TimerTask() { public void run() { countdownDialog.setProgress(10 - count); if (count == 10) { countdownDialog.dismiss(); stopTimer(); } else { count++; tick(); } } }, 1000); } protected void refreshMediaList() { try { getAppSettings().clearMediaSettings(); // in case prefs changed if (getAppSettings().getMediaSettings().getType() == MediaType.movies && !supportsMovies()) getAppSettings().setMediaType(MediaType.valueOf(AppSettings.DEFAULT_MEDIA_TYPE)); if (getAppSettings().getMediaSettings().getType() == MediaType.tvSeries && !supportsTvSeries()) getAppSettings().setMediaType(MediaType.valueOf(AppSettings.DEFAULT_MEDIA_TYPE)); if (getAppSettings().getMediaSettings().getType() == MediaType.music && !supportsMusic()) getAppSettings().setMediaType(MediaType.valueOf(AppSettings.DEFAULT_MEDIA_TYPE)); new RefreshTask().execute(getAppSettings().getUrls(getAppSettings().getMediaListUrl())); } catch (Exception ex) { throw new RuntimeException(ex.getMessage(), ex); } } protected void populate() throws IOException, JSONException, ParseException, BadSettingsException { // default does nothing } protected Transcoder getTranscoder(Item item) { if (mediaList.getStorageGroup() == null) return new Transcoder(getAppSettings(), mediaList.getBasePath()); else return new Transcoder(getAppSettings(), mediaList.getStorageGroup()); } /** * must be run in background thread */ protected Map<String,StorageGroup> retrieveStorageGroups() throws IOException, JSONException { URL baseUrl = getAppSettings().getMythTvServicesBaseUrl(); HttpHelper downloader = getAppSettings().getMediaListDownloader(getAppSettings().getUrls(new URL(baseUrl + "/Myth/GetStorageGroupDirs"))); String sgJson = new String(downloader.get()); return new MythTvParser(sgJson, getAppSettings()).parseStorageGroups(); } private class RefreshTask extends AsyncTask<URL,Integer,Long> { private String mediaListJson; private Exception ex; protected Long doInBackground(URL... urls) { try { MediaSettings mediaSettings = getAppSettings().getMediaSettings(); HttpHelper downloader = getAppSettings().getMediaListDownloader(urls); byte[] bytes = downloader.get(); mediaListJson = new String(bytes, downloader.getCharSet()); if (mediaListJson.startsWith("<")) { // just display html ex = new IOException(mediaListJson); return -1L; } MediaListParser mediaListParser = getAppSettings().getMediaListParser(mediaListJson); if (getAppSettings().isMythlingMediaServices()) { mediaList = mediaListParser.parseMediaList(mediaSettings.getType()); if (mediaList.getBasePath() == null) // otherwise can avoid retrieving storage groups at least until MythTV 0.28 { mediaList.setStorageGroup(retrieveStorageGroups().get(getAppSettings().getStorageGroup())); } } else { Map<String,StorageGroup> storageGroups = retrieveStorageGroups(); StorageGroup mediaStorageGroup = storageGroups.get(getAppSettings().getStorageGroup()); if (mediaStorageGroup != null) { mediaList = ((MythTvParser)mediaListParser).parseMediaList(mediaSettings.getType(), mediaStorageGroup, null, null); } else { // no storage group for media type URL baseUrl = getAppSettings().getMythTvServicesBaseUrl(); String basePath = null; if (mediaSettings.getType() == MediaType.videos || mediaSettings.getType() == MediaType.movies || mediaSettings.getType() == MediaType.tvSeries) { // handle videos by getting the base path setting downloader = getAppSettings().getMediaListDownloader(getAppSettings().getUrls(new URL(baseUrl + "/Myth/GetHostName"))); String hostName = new MythTvParser(new String(downloader.get()), getAppSettings()).parseString(); String key = "VideoStartupDir"; downloader = getAppSettings().getMediaListDownloader(getAppSettings().getUrls(new URL(baseUrl + "/Myth/GetSetting?Key=" + key + "&HostName=" + hostName))); basePath = new MythTvParser(new String(downloader.get()), getAppSettings()).parseMythTvSetting(key); if (basePath == null) { // try without host name downloader = getAppSettings().getMediaListDownloader(getAppSettings().getUrls(new URL(baseUrl + "/Myth/GetSetting?Key=" + key))); basePath = new MythTvParser(new String(downloader.get()), getAppSettings()).parseMythTvSetting(key); } } StorageGroup artworkStorageGroup = storageGroups.get(getAppSettings().getArtworkStorageGroup()); mediaList = ((MythTvParser)mediaListParser).parseMediaList(mediaSettings.getType(), null, basePath, artworkStorageGroup); } } mediaList.setArtworkStorageGroup(getAppSettings().getArtworkStorageGroup(mediaSettings.getType())); mediaList.setCharSet(downloader.getCharSet()); getAppSettings().clearPagerCurrentPosition(mediaList.getMediaType(), ""); return 0L; } catch (Exception ex) { this.ex = ex; if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); return -1L; } } protected void onPostExecute(Long result) { if (result != 0L) { stopProgress(); if (ex != null) Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show(); } else { AppData appData = new AppData(getApplicationContext()); appData.setMediaList(mediaList); setAppData(appData); setMediaType(appData.getMediaList().getMediaType()); getAppSettings().setLastLoad(System.currentTimeMillis()); try { appData.writeMediaList(mediaListJson); ViewType viewType = getAppSettings().getMediaSettings().getViewType(); if (viewType == ViewType.list && isDetailView()) { goListView(); } else if (viewType == ViewType.detail && isListView()) { goDetailView(); } else { stopProgress(); populate(); } } catch (Exception ex) { stopProgress(); if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); } } } } private class StreamVideoTask extends AsyncTask<URL,Integer,Long> { private Item item; private LiveStreamInfo streamInfo; private Exception ex; public StreamVideoTask(Item item) { this.item = item; } protected Long doInBackground(URL... urls) { try { Transcoder transcoder = getTranscoder(item); // TODO: do this retry for tv playback int ct = 0; int maxTries = 3; // empty relative url i think means myth has not started transcoding while ((streamInfo == null || streamInfo.getRelativeUrl().isEmpty()) && ct < maxTries ) { transcoder.beginTranscode(item); streamInfo = transcoder.getStreamInfo(); ct++; Thread.sleep(1000); } if (streamInfo == null || streamInfo.getRelativeUrl().isEmpty()) throw new IOException("Transcoding does not seem to have started"); transcoder.waitAvailable(); return 0L; } catch (Exception ex) { this.ex = ex; if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); return -1L; } } protected void onPostExecute(Long result) { if (result != 0L) { stopProgress(); if (ex != null) Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show(); onResume(); } else { try { playLiveStream(streamInfo); } catch (Exception ex) { if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show(); } } } } protected class TranscodeVideoTask extends AsyncTask<URL,Integer,Long> { private Item item; private Exception ex; public TranscodeVideoTask(Item item) { this.item = item; } protected Long doInBackground(URL... urls) { try { Transcoder transcoder = getTranscoder(item); transcoder.beginTranscode(item); return 0L; } catch (Exception ex) { this.ex = ex; if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); return -1L; } } protected void onPostExecute(Long result) { stopProgress(); if (result != 0L) { if (ex != null) Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show(); onResume(); } } } protected class StreamTvTask extends AsyncTask<URL,Integer,Long> { private TvShow tvShow; private Recording recordingToDelete; private LiveStreamInfo streamInfo; private Exception ex; public StreamTvTask(TvShow tvShow) { this.tvShow = tvShow; } public StreamTvTask(TvShow tvShow, Recording recordingToDelete) { this.tvShow = tvShow; this.recordingToDelete = recordingToDelete; } protected Long doInBackground(URL... urls) { try { Recorder recorder = new Recorder(getAppSettings()); if (recordingToDelete != null) recorder.deleteRecording(recordingToDelete); boolean recordAvail = recorder.scheduleRecording(tvShow); if (!recordAvail) recorder.waitAvailable(); Transcoder transcoder = getTranscoder(tvShow); boolean streamAvail = transcoder.beginTranscode(recorder.getRecording()); streamInfo = transcoder.getStreamInfo(); if (!streamAvail) transcoder.waitAvailable(); return 0L; } catch (Exception ex) { this.ex = ex; if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); return -1L; } } protected void onPostExecute(Long result) { stopProgress(); if (result != 0L) { if (ex instanceof TunerInUseException) { new AlertDialog.Builder(MediaActivity.this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Recording Conflict") .setMessage("Tuner already in use recording:\n" + ex.getMessage() + "\nDelete this recording and proceed?") .setPositiveButton("Delete", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { final Recording inProgressRecording = ((TunerInUseException)ex).getRecording(); new AlertDialog.Builder(MediaActivity.this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Confirm Delete") .setMessage("Delete in-progress recording?\n" + inProgressRecording) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { try { startProgress(); new StreamTvTask(tvShow, inProgressRecording).execute(getAppSettings().getMythTvServicesBaseUrl()); } catch (MalformedURLException ex) { stopProgress(); if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); Toast.makeText(getApplicationContext(), "Error: " + ex.toString(), Toast.LENGTH_LONG).show(); } } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { stopProgress(); onResume(); } }) .show(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { stopProgress(); onResume(); } }) .show(); } else { if (ex != null) Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show(); onResume(); } } else { try { playLiveStream(streamInfo); } catch (Exception ex) { if (BuildConfig.DEBUG) Log.e(TAG, ex.getMessage(), ex); Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show(); } } } } protected void playLiveStream(LiveStreamInfo streamInfo) throws IOException { String streamUrl = appSettings.getMythTvServicesBaseUrlWithCredentials() + streamInfo.getRelativeUrl(); // avoid retrieving unnecessary audio-only streams int lastDot = streamUrl.lastIndexOf('.'); streamUrl = streamUrl.substring(0, lastDot) + ".av" + streamUrl.substring(lastDot); stopProgress(); if (appSettings.isExternalPlayer()) { Intent toStart = new Intent(Intent.ACTION_VIEW);
package edu.chalmers.sankoss.desktop; import edu.chalmers.sankoss.core.core.Coordinate; import edu.chalmers.sankoss.core.core.Ship; import edu.chalmers.sankoss.desktop.mvc.placement.PlacementModel; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * Description of class. * More detailed description. * * @author Mikael Malmqvist * @modified Fredrik Thune */ public class PlacementModelTest { @Test public void testAddShip() throws Exception { PlacementModel testModel = new PlacementModel(); Ship myShip = new Ship(new Coordinate(2,2), new Coordinate(2,5)); testModel.addShip(myShip); assertTrue(testModel.getFleet().getShip(0).equals(myShip)); assertFalse(testModel.addShip(new Ship(new Coordinate(2,2), new Coordinate(2,5)))); assertFalse(testModel.addShip(new Ship(new Coordinate(2,2), new Coordinate(5,2)))); assertFalse(testModel.addShip(new Ship(new Coordinate(-1,2), new Coordinate(2,2)))); assertFalse(testModel.addShip(new Ship(new Coordinate(2,-1), new Coordinate(2,5)))); assertFalse(testModel.addShip(new Ship(new Coordinate(12,2), new Coordinate(2,2)))); assertFalse(testModel.addShip(new Ship(new Coordinate(2,12), new Coordinate(2,5)))); assertFalse(testModel.addShip(new Ship(new Coordinate(2,2), new Coordinate(-1,2)))); assertFalse(testModel.addShip(new Ship(new Coordinate(2,2), new Coordinate(2,-1)))); assertFalse(testModel.addShip(new Ship(new Coordinate(2,2), new Coordinate(12,2)))); assertFalse(testModel.addShip(new Ship(new Coordinate(2,2), new Coordinate(2,12)))); } @Test public void testValidate() throws Exception { // TODO: Test stuff } @Test public void testUpdateNationality() throws Exception { // This could not be tested due to network coding. // There is no instance of SankossClient.. assertTrue(true); } }
package org.springsource.ide.eclipse.commons.quicksearch.util; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField.ColumnsDescription; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.ControlListener; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; /** * Resizes table columns such that columns fit the table width. The table is * initially resized when the resize is enabled, and its columns continue being * resized automatically as the user resizes the table. * */ public class TableResizeHelper { private final TableViewer tableViewer; public TableResizeHelper(TableViewer tableViewer) { this.tableViewer = tableViewer; } public void enableResizing() { ControlListener resizeListener = new ControlListener() { public void controlResized(ControlEvent e) { resizeTable(); } public void controlMoved(ControlEvent e) { } }; tableViewer.getTable().addControlListener(resizeListener); TableColumn[] cols = tableViewer.getTable().getColumns(); if (cols!=null) { for (int i = 0; i < cols.length-1; i++) { cols[i].addControlListener(resizeListener); } } // Initial resize of the columns resizeTable(); } protected void resizeTable() { Composite tableComposite = tableViewer.getTable();//.getParent(); Rectangle tableCompositeArea = tableComposite.getClientArea(); int width = tableCompositeArea.width; // ScrollBar sb = tableViewer.getTable().getVerticalBar(); // if (sb!=null && sb.isVisible()) { // width = width - sb.getSize().x; resizeTableColumns(width, tableViewer.getTable()); } protected void resizeTableColumns(int tableWidth, Table table) { TableColumn[] tableColumns = table.getColumns(); if (tableColumns.length == 0) { return; } int total = 0; for (TableColumn column : tableColumns) { total += column.getWidth(); } TableColumn lastColumn = tableColumns[tableColumns.length - 1]; int newWidth = (tableWidth - total) + lastColumn.getWidth(); if (newWidth>0) { lastColumn.setWidth(newWidth); } } }
package fr.openwide.core.commons.util.functional; import java.io.Serializable; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; /** * More useful suppliers. * * <p>All methods return serializable suppliers as long as they're given * serializable parameters. * * <p>Methods named xAsY ({@link #linkedListAsList()}, {@link #treeSetAsSet(Comparator)}, and so on) are just here to * make your like easy when you want to use the diamond operator on a method that receives your supplier as a parameter. * For instance: * <code><pre> * public MyType&lt;T, C extends Collection&lt;T&gt;&gt; { * public MyType(Supplier&lt;C&gt; supplier) { * // ... * } * } * * // With the original method * ... = new MyType&lt;&gt;((Supplier&lt;? extends List&lt;T&gt;&gt;)Suppliers2.&lt;T&gt;arrayList()); * * // With xAsY * ... = new MyType&lt;&gt;(Suppliers2.&lt;T&gt;arrayListAsList()); * // ... which is a tad shorter * </pre></code> * * @see Suppliers * */ public final class Suppliers2 { private Suppliers2() { } public static <T> Supplier<T> constant(T value) { return new ConstantSupplier<T>(value); } private static class ConstantSupplier<T> implements Supplier<T>, Serializable { private static final long serialVersionUID = 6476238745119640079L; private final T value; public ConstantSupplier(T value) { super(); this.value = value; } @Override public T get() { return value; } } @SuppressWarnings({ "unchecked", "rawtypes" }) // LinkedListSupplier works for any T public static <T> Supplier<LinkedList<T>> linkedList() { return (Supplier) LinkedListSupplier.INSTANCE; } public static <T> Supplier<? extends List<T>> linkedListAsList() { return linkedList(); } private static enum LinkedListSupplier implements Supplier<LinkedList<?>> { INSTANCE; @Override public LinkedList<?> get() { return Lists.newLinkedList(); } } @SuppressWarnings({ "unchecked", "rawtypes" }) // ArrayListSupplier works for any T public static <T> Supplier<ArrayList<T>> arrayList() { return (Supplier) ArrayListSupplier.INSTANCE; } public static <T> Supplier<? extends List<T>> arrayListAsList() { return arrayList(); } private static enum ArrayListSupplier implements Supplier<ArrayList<?>> { INSTANCE; @Override public ArrayList<?> get() { return Lists.newArrayList(); } } @SuppressWarnings({ "unchecked", "rawtypes" }) // HashSetSupplier works for any T public static <T> Supplier<HashSet<T>> hashSet() { return (Supplier) HashSetSupplier.INSTANCE; } public static <T> Supplier<? extends Set<T>> hashSetAsSet() { return hashSet(); } private static enum HashSetSupplier implements Supplier<HashSet<?>> { INSTANCE; @Override public HashSet<?> get() { return Sets.newHashSet(); } } @SuppressWarnings({ "unchecked", "rawtypes" }) // HashSetSupplier works for any T public static <T> Supplier<LinkedHashSet<T>> linkedHashSet() { return (Supplier) LinkedHashSetSupplier.INSTANCE; } public static <T> Supplier<? extends Set<T>> linkedHashSetAsSet() { return linkedHashSet(); } private static enum LinkedHashSetSupplier implements Supplier<LinkedHashSet<?>> { INSTANCE; @Override public LinkedHashSet<?> get() { return Sets.newLinkedHashSet(); } } @SuppressWarnings({ "unchecked", "rawtypes" }) // NaturalOrderTreeSetSupplier works for any T public static <T extends Comparable> Supplier<TreeSet<T>> treeSet() { return (Supplier) NaturalOrderTreeSetSupplier.INSTANCE; } @SuppressWarnings("rawtypes") public static <T extends Comparable> Supplier<? extends Set<T>> treeSetAsSet() { return treeSet(); } @SuppressWarnings("rawtypes") public static <T extends Comparable> Supplier<? extends SortedSet<T>> treeSetAsSortedSet() { return treeSet(); } private static enum NaturalOrderTreeSetSupplier implements Supplier<TreeSet<?>> { INSTANCE; @Override @SuppressWarnings("rawtypes") public TreeSet<?> get() { return (TreeSet) Sets.newTreeSet(); } } public static <T> Supplier<TreeSet<T>> treeSet(Comparator<? super T> comparator) { return new ComparatorTreeSetSupplier<T>(comparator); } public static <T> Supplier<? extends Set<T>> treeSetAsSet(Comparator<? super T> comparator) { return treeSet(comparator); } public static <T> Supplier<? extends SortedSet<T>> treeSetAsSortedSet(Comparator<? super T> comparator) { return treeSet(comparator); } private static class ComparatorTreeSetSupplier<T> implements Supplier<TreeSet<T>>, Serializable { private static final long serialVersionUID = 6476238745119640079L; private final Comparator<? super T> comparator; public ComparatorTreeSetSupplier(Comparator<? super T> comparator) { super(); this.comparator = comparator; } @Override public TreeSet<T> get() { return Sets.newTreeSet(comparator); } } @SuppressWarnings({ "unchecked", "rawtypes" }) // HashMapSupplier works for any K and V public static <K, V> Supplier<HashMap<K, V>> hashMap() { return (Supplier) HashMapSupplier.INSTANCE; } public static <K, V> Supplier<? extends Map<K, V>> hashMapAsMap() { return hashMap(); } private static enum HashMapSupplier implements Supplier<HashMap<?, ?>> { INSTANCE; @Override public HashMap<?, ?> get() { return Maps.newHashMap(); } } @SuppressWarnings({ "unchecked", "rawtypes" }) // HashMapSupplier works any K and V public static <K, V> Supplier<LinkedHashMap<K, V>> linkedHashMap() { return (Supplier) LinkedHashMapSupplier.INSTANCE; } public static <K, V> Supplier<? extends Map<K, V>> linkedHashMapAsMap() { return linkedHashMap(); } private static enum LinkedHashMapSupplier implements Supplier<LinkedHashMap<?, ?>> { INSTANCE; @Override public LinkedHashMap<?, ?> get() { return Maps.newLinkedHashMap(); } } @SuppressWarnings({ "unchecked", "rawtypes" }) // NaturalOrderTreeMapSupplier works for any K and V public static <K extends Comparable, V> Supplier<TreeMap<K, V>> treeMap() { return (Supplier) NaturalOrderTreeMapSupplier.INSTANCE; } @SuppressWarnings("rawtypes") public static <K extends Comparable, V> Supplier<? extends Map<K, V>> treeMapAsMap() { return treeMap(); } @SuppressWarnings("rawtypes") public static <K extends Comparable, V> Supplier<? extends SortedMap<K, V>> treeMapAsSortedMap() { return treeMap(); } private static enum NaturalOrderTreeMapSupplier implements Supplier<TreeMap<?, ?>> { INSTANCE; @Override @SuppressWarnings("rawtypes") public TreeMap<?, ?> get() { return (TreeMap) Maps.newTreeMap(); } } public static <K, V> Supplier<TreeMap<K, V>> treeMap(Comparator<? super K> comparator) { return new ComparatorTreeMapSupplier<K, V>(comparator); } public static <K, V> Supplier<? extends Map<K, V>> treeMapAsMap(Comparator<? super K> comparator) { return treeMap(comparator); } public static <K, V> Supplier<? extends SortedMap<K, V>> treeMapAsSortedMap(Comparator<? super K> comparator) { return treeMap(comparator); } private static class ComparatorTreeMapSupplier<K, V> implements Supplier<TreeMap<K, V>>, Serializable { private static final long serialVersionUID = 6476238745119640079L; private final Comparator<? super K> comparator; public ComparatorTreeMapSupplier(Comparator<? super K> comparator) { super(); this.comparator = comparator; } @Override public TreeMap<K, V> get() { return Maps.newTreeMap(comparator); } } }
package nl.tudelft.ewi.dea.dao; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static org.apache.commons.lang3.StringUtils.isNotEmpty; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.persist.Transactional; public abstract class AbstractDaoBase<T> implements Dao<T> { private static final Logger LOG = LoggerFactory.getLogger(AbstractDaoBase.class); private final EntityManager em; private final Class<T> entityClass; private final String entityName; protected AbstractDaoBase(final EntityManager em, final Class<T> clazz) { this.em = em; entityClass = clazz; entityName = entityClass.getSimpleName(); } @Override @Transactional public final List<T> findAll() { LOG.trace("{}: Find all...", getEntityName()); final TypedQuery<T> query = createQuery("FROM " + getEntityName()); return query.getResultList(); } @Override @Transactional public final T findById(final long id) { LOG.trace("{}: Find by id: {}", getEntityName(), id); final T result = em.find(entityClass, id); if (result == null) { throw new NoResultException("No result found for id: " + id); } return result; } @Override @Transactional public final void persist(final T object) { LOG.trace("{}: Persist: {}", getEntityName(), object); checkNotNull(object, "object must be non-null"); em.persist(object); LOG.trace("{}: Persisted: {}", getEntityName(), object); } @Override @Transactional public final void persist(final Object... objects) { LOG.trace("{}: Persist: {}", getEntityName(), objects); checkNotNull(objects, "objects must be non-null"); for (final Object object : objects) { em.persist(object); } } @Override @Transactional public void detach(final T entity) { checkNotNull(entity, "entity must be non-null"); em.detach(entity); } @Override @Transactional public final T merge(final T entity) { checkNotNull(entity, "entity must be non-null"); return em.merge(entity); } @Override @Transactional public final void remove(final T object) { LOG.trace("{}: Remove: {}", getEntityName(), object); checkNotNull(object, "object must be non-null"); em.remove(object); } @Override @Transactional public final void remove(final Object... objects) { LOG.trace("{}: Remove: {}", getEntityName(), objects); checkNotNull(objects, "objects must be non-null"); for (final Object object : objects) { em.remove(object); } } @Transactional protected final CriteriaBuilder getCriteriaBuilder() { return em.getCriteriaBuilder(); } @Transactional protected final TypedQuery<T> createQuery(final String query) { checkArgument(isNotEmpty(query), "query must be non-empty"); return em.createQuery(query, entityClass); } @Transactional protected final TypedQuery<T> createQuery(CriteriaQuery<T> criteria) { checkNotNull(criteria, "query must be non-empty"); return em.createQuery(criteria); } public String getEntityName() { return entityName; } }
package com.redhat.ceylon.common; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.PushbackReader; import java.io.Reader; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.util.InvalidPropertiesFormatException; public class ConfigReader { private ConfigReaderListener listener; private InputStream in; private LineNumberReader counterdr; private MemoPushbackReader reader; private String section; private enum Token { section, option, assign, comment, eol, error, eof }; public ConfigReader(InputStream in, ConfigReaderListener listener) { this.in = in; this.listener = listener; } public void process() throws IOException { section = null; try { counterdr = new LineNumberReader(new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")))); reader = new MemoPushbackReader(counterdr); Token tok; skipWhitespace(true); flushWhitespace(); while ((tok = peekToken()) != Token.eof) { switch (tok) { case section: handleSection(); break; case option: if (section != null) { handleOption(); } else { throw new InvalidPropertiesFormatException("Option without section in configuration file at line " + (counterdr.getLineNumber() + 1)); } break; case comment: skipToNextLine(); listener.onComment(reader.getAndClearMemo()); break; case eol: skipToNextLine(); listener.onWhitespace(reader.getAndClearMemo()); break; default: throw new InvalidPropertiesFormatException("Unexpected token in configuration file at line " + (counterdr.getLineNumber() + 1)); } skipWhitespace(true); flushWhitespace(); } } finally { if (reader != null) { reader.close(); } } } private void handleSection() throws IOException { expect('['); section = readName(true).toLowerCase(); if (!section.matches("[\\p{L}\\p{Nd}]+(\\.[\\p{L}\\p{Nd}]+)*")) { throw new InvalidPropertiesFormatException("Invalid section name in configuration file at line " + (counterdr.getLineNumber() + 1)); } skipWhitespace(false); if (reader.peek() == '\"') { String subSection = readString(); expect('"'); section += "." + subSection; skipWhitespace(false); } expect(']'); listener.onSection(section, reader.getAndClearMemo()); } private void handleOption() throws IOException { String option = readName(false); String optName = section + "." + option; String value; skipWhitespace(false); Token tok = peekToken(); if (tok == Token.assign) { expect('='); value = readValue(); } else if (tok == Token.error) { throw new InvalidPropertiesFormatException("Unexpected token in configuration file at line " + (counterdr.getLineNumber() + 1)); } else { value = "true"; } listener.onOption(optName, value, reader.getAndClearMemo()); } private String readName(boolean forSection) throws IOException { StringBuilder str = new StringBuilder(); int c; while ((c = reader.read()) != -1) { if ((!forSection && isOptionNameChar(c)) || (forSection && isSectionNameChar(c))) { str.append((char)c); } else { reader.unread(c); break; } } return str.toString(); } private String readString() throws IOException { StringBuilder str = new StringBuilder(); gobble('\"'); int c; while ((c = reader.read()) != -1) { if (c == '"') { reader.unread(c); break; } else if (c == '\\') { int c2 = reader.read(); if (c2 == '\\') { // Do nothing } else if (c2 == '\"') { c = c2; } else { throw new InvalidPropertiesFormatException("Illegal escape character in configuration file at line " + (counterdr.getLineNumber() + 1)); } } str.append((char)c); } return str.toString(); } private String readValue() throws IOException { StringBuilder str = new StringBuilder(); skipWhitespace(false); boolean hasQuote = gobble('\"'); int c; while ((c = reader.read()) != -1) { if (c == '"') { reader.unread(c); break; } else if (isNewLineChar(c)) { reader.unread(c); break; } else if (isCommentChar(c) && !hasQuote) { break; } else if (c == '\\') { int c2 = reader.read(); if (c2 == '\\') { // Do nothing } else if (c2 == '\"') { c = c2; } else if (c2 == 't') { c = '\t'; } else if (c2 == 'n') { c = '\n'; } else if (isNewLineChar(c2)) { skipNewLine(c2); c = '\n'; } else { throw new InvalidPropertiesFormatException("Illegal escape character in configuration file at line " + (counterdr.getLineNumber() + 1)); } } str.append((char)c); } if (hasQuote) { expect('\"'); return str.toString(); } else { return str.toString().trim(); } } private void expect(int expected) throws IOException { int c; if ((c = reader.read()) != expected) { throw new InvalidPropertiesFormatException("Unexpected token in configuration file at line " + (counterdr.getLineNumber() + 1) + ", expected '" + Character.valueOf((char)expected) + "' but got '" + Character.valueOf((char)c) + "'"); } } private void skipWhitespace(boolean multiline) throws IOException { int c; while ((c = reader.read()) != -1) { if (!Character.isWhitespace(c) || (!multiline && isNewLineChar(c))) { reader.unread(c); break; } } } private void skipToNextLine() throws IOException { int c; while ((c = reader.read()) != -1) { if (isNewLineChar(c)) { skipNewLine(c); break; } } } private Token peekToken() throws IOException { int c = reader.peek(); if (isCommentChar(c)) { return Token.comment; } else if (c == '[') { return Token.section; } else if (c == '=') { return Token.assign; } else if (isNewLineChar(c)) { return Token.eol; } else if (isOptionNameChar(c)) { return Token.option; } else if (c == -1) { return Token.eof; } else { return Token.error; } } private boolean gobble(int chr) throws IOException { int c = reader.read(); if (c != chr) { reader.unread(c); return false; } return true; } private void skipNewLine(int c) throws IOException { if (c == '\r') { c = reader.read(); if (c != '\n') { reader.unread(c); } } } private void flushWhitespace() { String ws = reader.getAndClearMemo(); if (!ws.isEmpty()) { listener.onWhitespace(ws); } } private boolean isOptionNameChar(int c) { return Character.isLetterOrDigit(c) || c == '-'; } private boolean isSectionNameChar(int c) { return isOptionNameChar(c) || c == '.'; } private boolean isCommentChar(int c) { return c == ';' || c == ' } private boolean isNewLineChar(int c) { return c == '\n' || c == '\r'; } } class MemoPushbackReader extends PushbackReader { private StringBuilder memo; public MemoPushbackReader(Reader in) { super(in); memo = new StringBuilder(1024); } @Override public int read() throws IOException { int c = super.read(); if (c != -1) { memo.append((char)c); } return c; } @Override public void unread(int c) throws IOException { super.unread(c); memo.setLength(memo.length() - 1); } public int peek() throws IOException { int c = super.read(); if (c != -1) { super.unread(c); } return c; } @Override public void reset() throws IOException { super.reset(); memo.setLength(0); } public String getAndClearMemo() { String result = memo.toString(); memo.setLength(0); return result; } // All the following methods we don't really need so they aren't implemented // to prevent anybody from accidentally using them they throw an error @Override public int read(char[] cbuf, int off, int len) throws IOException { throw new UnsupportedOperationException(); } @Override public long skip(long n) throws IOException { throw new UnsupportedOperationException(); } @Override public void unread(char[] cbuf, int off, int len) throws IOException { throw new UnsupportedOperationException(); } @Override public void unread(char[] cbuf) throws IOException { throw new UnsupportedOperationException(); } @Override public int read(char[] cbuf) throws IOException { throw new UnsupportedOperationException(); } @Override public int read(CharBuffer target) throws IOException { throw new UnsupportedOperationException(); } }
package fr.openwide.core.jpa.business.generic.dao; import java.util.Arrays; import java.util.List; import java.util.ListIterator; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceException; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Order; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.persistence.metamodel.SingularAttribute; import org.hibernate.Session; public class JpaDaoSupport { @PersistenceContext private EntityManager entityManager; protected <T> TypedQuery<T> buildTypedQuery(CriteriaQuery<T> criteria, Integer limit, Integer offset) { TypedQuery<T> query = getEntityManager().createQuery(criteria); if (offset != null) { query.setFirstResult(offset); } if (limit != null) { query.setMaxResults(limit); } return query; } protected void filterCriteriaQuery(CriteriaQuery<?> criteria, Expression<Boolean> filter) { if (filter != null) { Predicate currentFilter = criteria.getRestriction(); if (currentFilter != null) { filter = getEntityManager().getCriteriaBuilder().and(currentFilter, filter); } criteria.where(filter); } } protected <T> Root<T> rootCriteriaQuery(CriteriaBuilder builder, CriteriaQuery<?> criteria, Class<T> objectClass) { return criteria.from(objectClass); } public <T, K> T getEntity(Class<T> clazz, K id) { return getEntityManager().find(clazz, id); } @SuppressWarnings("unchecked") public <T> T getEntityByNaturalId(Class<T> clazz, String naturalId) { if (naturalId == null) { throw new IllegalArgumentException("Natural id may not be null"); } Session session = getEntityManager().unwrap(Session.class); return (T) session.bySimpleNaturalId(clazz).load(naturalId); } public <T, V> T getEntityByField(Class<T> clazz, SingularAttribute<? super T, V> attribute, V fieldValue) { CriteriaBuilder builder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<T> criteria = builder.createQuery(clazz); Root<T> root = criteria.from(clazz); criteria.where(builder.equal(root.get(attribute), fieldValue)); try { return buildTypedQuery(criteria, null, null).getSingleResult(); } catch (NoResultException e) { return null; } } public <T> T getEntityByFieldIgnoreCase(Class<T> clazz, SingularAttribute<? super T, String> attribute, String fieldValue) { CriteriaBuilder builder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<T> criteria = builder.createQuery(clazz); Root<T> root = criteria.from(clazz); criteria.where(builder.equal( builder.lower(root.get(attribute)), builder.lower(builder.literal(fieldValue)) )); try { return buildTypedQuery(criteria, null, null).getSingleResult(); } catch (NoResultException e) { return null; } } protected <T> void update(T entity) { if (!getEntityManager().contains(entity)) { throw new PersistenceException("Updated entity must be attached"); } } protected <T> void save(T entity) { getEntityManager().persist(entity); } protected <T> void delete(T entity) { getEntityManager().remove(entity); } protected <T> T refresh(T entity) { getEntityManager().refresh(entity); return entity; } public void flush() { getEntityManager().flush(); } public void clear() { getEntityManager().clear(); } protected <T> List<T> listEntity(Class<T> objectClass, Expression<Boolean> filter, Integer limit, Integer offset, Order... orders) { CriteriaBuilder builder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<T> criteria = builder.createQuery(objectClass); rootCriteriaQuery(builder, criteria, objectClass); if (filter != null) { filterCriteriaQuery(criteria, filter); } if (orders != null && orders.length > 0) { criteria.orderBy(orders); } TypedQuery<T> query = buildTypedQuery(criteria, limit, offset); List<T> entities = query.getResultList(); if (orders == null || orders.length == 0) { sort(entities); } return entities; } protected <T> List<T> listEntity(Class<T> objectClass) { return listEntity(objectClass, null, null, null); } protected <T> List<T> listEntity(Class<T> objectClass, Expression<Boolean> filter) { return listEntity(objectClass, filter, null, null); } protected <T, V> List<T> listEntityByField(Class<T> objectClass, SingularAttribute<? super T, V> attribute, V fieldValue) { CriteriaBuilder builder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<T> criteria = builder.createQuery(objectClass); Root<T> root = rootCriteriaQuery(builder, criteria, objectClass); criteria.where(builder.equal(root.get(attribute), fieldValue)); List<T> entities = buildTypedQuery(criteria, null, null).getResultList(); sort(entities); return entities; } protected <T> Long countEntity(Class<T> clazz) { CriteriaBuilder builder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<Long> criteria = builder.createQuery(Long.class); Root<T> root = rootCriteriaQuery(builder, criteria, clazz); criteria.select(builder.count(root)); return buildTypedQuery(criteria, null, null).getSingleResult(); } protected <T, V> Long countEntityByField(Class<T> clazz, SingularAttribute<? super T, V> attribute, V fieldValue) { CriteriaBuilder builder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<Long> criteria = builder.createQuery(Long.class); Root<T> root = rootCriteriaQuery(builder, criteria, clazz); criteria.select(builder.count(root)); Expression<Boolean> filter = builder.equal(root.get(attribute), fieldValue); filterCriteriaQuery(criteria, filter); return buildTypedQuery(criteria, null, null).getSingleResult(); } protected <T> Long countEntity(Class<T> clazz, Expression<Boolean> filter) { CriteriaBuilder builder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<Long> criteria = builder.createQuery(Long.class); Root<T> root = rootCriteriaQuery(builder, criteria, clazz); criteria.select(builder.count(root)); filterCriteriaQuery(criteria, filter); return buildTypedQuery(criteria, null, null).getSingleResult(); } protected <E> E getSingleResultOrNull(CriteriaQuery<E> cq) { try { return getEntityManager().createQuery(cq).getSingleResult(); } catch (NoResultException e) { return null; } } protected <E> E getSingleResultOrNull(TypedQuery<E> tq) { try { return tq.getSingleResult(); } catch (NoResultException e) { return null; } } protected EntityManager getEntityManager() { return entityManager; } @SuppressWarnings("unchecked") protected <T> void sort(List<T> entities) { Object[] a = entities.toArray(); Arrays.sort(a); ListIterator<T> i = entities.listIterator(); for (int j = 0; j < a.length; j++) { i.next(); i.set((T) a[j]); } } }
package com.robrua.orianna.type.dto.team; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import com.robrua.orianna.type.dto.OriannaDto; @Entity(name = "team.Team") @Table(name = "team") public class Team extends OriannaDto { private static final long serialVersionUID = 7937264447395600368L; private Long createDate, lastGameDate, lastJoinDate, lastJoinedRankedTeamQueueDate, modifyDate, secondLastJoinDate, thirdLastJoinDate; @Id private String fullId; @OneToMany(cascade = CascadeType.ALL) private List<MatchHistorySummary> matchHistory; private String name, status, tag; @OneToOne(cascade = CascadeType.ALL) private Roster roster; @OneToMany(cascade = CascadeType.ALL) private List<TeamStatDetail> teamStatDetails; /* * (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object obj) { if(this == obj) { return true; } if(obj == null) { return false; } if(!(obj instanceof Team)) { return false; } final Team other = (Team)obj; if(fullId == null) { if(other.fullId != null) { return false; } } else if(!fullId.equals(other.fullId)) { return false; } return true; } /** * @return the createDate */ public Long getCreateDate() { return createDate; } @Override public String getDataStoreIndexField(final Class<?> keyType) { if(keyType.equals(String.class)) { return "fullId"; } return null; } /** * @return the fullId */ public String getFullId() { return fullId; } /** * @return the lastGameDate */ public Long getLastGameDate() { return lastGameDate; } /** * @return the lastJoinDate */ public Long getLastJoinDate() { return lastJoinDate; } /** * @return the lastJoinedRankedTeamQueueDate */ public Long getLastJoinedRankedTeamQueueDate() { return lastJoinedRankedTeamQueueDate; } /** * @return the matchHistory */ public List<MatchHistorySummary> getMatchHistory() { return matchHistory; } /** * @return the modifyDate */ public Long getModifyDate() { return modifyDate; } /** * @return the name */ public String getName() { return name; } /** * @return the roster */ public Roster getRoster() { return roster; } /** * @return the secondLastJoinDate */ public Long getSecondLastJoinDate() { return secondLastJoinDate; } /** * @return the status */ public String getStatus() { return status; } /** * Gets all stored summoner IDs for batch lookup * * @return the summoner IDs */ public Set<Long> getSummonerIDs() { final Set<Long> set = new HashSet<>(); set.add(roster.getOwnerId()); if(roster.getMemberList() != null) { for(final TeamMemberInfo member : roster.getMemberList()) { set.add(member.getPlayerId()); } } return set; } /** * @return the tag */ public String getTag() { return tag; } /** * @return the teamStatDetails */ public List<TeamStatDetail> getTeamStatDetails() { return teamStatDetails; } /** * @return the thirdLastJoinDate */ public Long getThirdLastJoinDate() { return thirdLastJoinDate; } /* * (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (fullId == null ? 0 : fullId.hashCode()); return result; } /** * @param createDate * the createDate to set */ public void setCreateDate(final Long createDate) { this.createDate = createDate; } /** * @param fullId * the fullId to set */ public void setFullId(final String fullId) { this.fullId = fullId; } /** * @param lastGameDate * the lastGameDate to set */ public void setLastGameDate(final Long lastGameDate) { this.lastGameDate = lastGameDate; } /** * @param lastJoinDate * the lastJoinDate to set */ public void setLastJoinDate(final Long lastJoinDate) { this.lastJoinDate = lastJoinDate; } /** * @param lastJoinedRankedTeamQueueDate * the lastJoinedRankedTeamQueueDate to set */ public void setLastJoinedRankedTeamQueueDate(final Long lastJoinedRankedTeamQueueDate) { this.lastJoinedRankedTeamQueueDate = lastJoinedRankedTeamQueueDate; } /** * @param matchHistory * the matchHistory to set */ public void setMatchHistory(final List<MatchHistorySummary> matchHistory) { this.matchHistory = matchHistory; } /** * @param modifyDate * the modifyDate to set */ public void setModifyDate(final Long modifyDate) { this.modifyDate = modifyDate; } /** * @param name * the name to set */ public void setName(final String name) { this.name = name; } /** * @param roster * the roster to set */ public void setRoster(final Roster roster) { this.roster = roster; } /** * @param secondLastJoinDate * the secondLastJoinDate to set */ public void setSecondLastJoinDate(final Long secondLastJoinDate) { this.secondLastJoinDate = secondLastJoinDate; } /** * @param status * the status to set */ public void setStatus(final String status) { this.status = status; } /** * @param tag * the tag to set */ public void setTag(final String tag) { this.tag = tag; } /** * @param teamStatDetails * the teamStatDetails to set */ public void setTeamStatDetails(final List<TeamStatDetail> teamStatDetails) { this.teamStatDetails = teamStatDetails; } /** * @param thirdLastJoinDate * the thirdLastJoinDate to set */ public void setThirdLastJoinDate(final Long thirdLastJoinDate) { this.thirdLastJoinDate = thirdLastJoinDate; } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "Team [createDate=" + createDate + ", lastGameDate=" + lastGameDate + ", lastJoinDate=" + lastJoinDate + ", lastJoinedRankedTeamQueueDate=" + lastJoinedRankedTeamQueueDate + ", modifyDate=" + modifyDate + ", secondLastJoinDate=" + secondLastJoinDate + ", thirdLastJoinDate=" + thirdLastJoinDate + ", fullId=" + fullId + ", name=" + name + ", status=" + status + ", tag=" + tag + ", matchHistory=" + matchHistory + ", roster=" + roster + ", teamStatDetails=" + teamStatDetails + "]"; } }