answer
stringlengths
17
10.2M
package org.openstreetmap.josm.plugins.notes.gui; import static org.openstreetmap.josm.tools.I18n.tr; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.Action; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JToggleButton; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.openstreetmap.josm.Main; import org.openstreetmap.josm.gui.MapView; import org.openstreetmap.josm.gui.MapView.LayerChangeListener; import org.openstreetmap.josm.gui.dialogs.ToggleDialog; import org.openstreetmap.josm.gui.layer.Layer; import org.openstreetmap.josm.plugins.notes.ConfigKeys; import org.openstreetmap.josm.plugins.notes.Note; import org.openstreetmap.josm.plugins.notes.NotesObserver; import org.openstreetmap.josm.plugins.notes.NotesPlugin; import org.openstreetmap.josm.plugins.notes.gui.action.ActionQueue; import org.openstreetmap.josm.plugins.notes.gui.action.AddCommentAction; import org.openstreetmap.josm.plugins.notes.gui.action.CloseNoteAction; import org.openstreetmap.josm.plugins.notes.gui.action.NotesAction; import org.openstreetmap.josm.plugins.notes.gui.action.NotesActionObserver; import org.openstreetmap.josm.plugins.notes.gui.action.PointToNewNoteAction; import org.openstreetmap.josm.plugins.notes.gui.action.PopupFactory; import org.openstreetmap.josm.plugins.notes.gui.action.ToggleConnectionModeAction; import org.openstreetmap.josm.tools.OsmUrlToBounds; import org.openstreetmap.josm.tools.Shortcut; public class NotesDialog extends ToggleDialog implements NotesObserver, ListSelectionListener, LayerChangeListener, MouseListener, NotesActionObserver { private static final long serialVersionUID = 1L; private JPanel bugListPanel, queuePanel; private DefaultListModel bugListModel; private JList bugList; private JList queueList; private NotesPlugin notesPlugin; private boolean fireSelectionChanged = true; private JButton refresh; private JButton addComment; private JButton closeIssue; private JButton processQueue = new JButton(tr("Process queue")); private JToggleButton newIssue = new JToggleButton(); private JToggleButton toggleConnectionMode; private JTabbedPane tabbedPane = new JTabbedPane(); private boolean queuePanelVisible = false; private final ActionQueue actionQueue = new ActionQueue(); private boolean buttonLabels = Main.pref.getBoolean(ConfigKeys.NOTES_BUTTON_LABELS); public NotesDialog(final NotesPlugin plugin) { super(tr("OpenStreetMap Notes"), "icon_error24", tr("Opens the OpenStreetMap Notes window and activates the automatic download"), Shortcut.registerShortcut( "view:osmnotes", tr("Toggle: {0}", tr("Open OpenStreetMap Notes")), KeyEvent.VK_B, Shortcut.ALT_SHIFT), 150); notesPlugin = plugin; bugListPanel = new JPanel(new BorderLayout()); bugListPanel.setName(tr("Bug list")); add(bugListPanel, BorderLayout.CENTER); bugListModel = new DefaultListModel(); bugList = new JList(bugListModel); bugList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); bugList.addListSelectionListener(this); bugList.addMouseListener(this); bugList.setCellRenderer(new NotesBugListCellRenderer()); bugListPanel.add(new JScrollPane(bugList), BorderLayout.CENTER); // create dialog buttons GridLayout layout = buttonLabels ? new GridLayout(3, 2) : new GridLayout(1, 5); JPanel buttonPanel = new JPanel(layout); refresh = new JButton(tr("Refresh")); refresh.setToolTipText(tr("Refresh")); refresh.setIcon(NotesPlugin.loadIcon("view-refresh22.png")); refresh.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int zoom = OsmUrlToBounds.getZoom(Main.map.mapView.getRealBounds()); // check zoom level if (zoom > 15 || zoom < 9) { JOptionPane.showMessageDialog(Main.parent, tr("The visible area is either too small or too big to download data from OpenStreetMap Notes"), tr("Warning"), JOptionPane.INFORMATION_MESSAGE); return; } plugin.updateData(); } }); bugListPanel.add(buttonPanel, BorderLayout.SOUTH); Action toggleConnectionModeAction = new ToggleConnectionModeAction(this, notesPlugin); toggleConnectionMode = new JToggleButton(toggleConnectionModeAction); toggleConnectionMode.setToolTipText(ToggleConnectionModeAction.MSG_OFFLINE); boolean offline = Main.pref.getBoolean(ConfigKeys.NOTES_API_OFFLINE); toggleConnectionMode.setIcon(NotesPlugin.loadIcon("online22.png")); toggleConnectionMode.setSelectedIcon(NotesPlugin.loadIcon("offline22.png")); if(offline) { // inverse the current value and then do a click, so that // we are offline and the gui represents the offline state, too Main.pref.put(ConfigKeys.NOTES_API_OFFLINE, false); toggleConnectionMode.doClick(); } AddCommentAction addCommentAction = new AddCommentAction(this); addComment = new JButton(addCommentAction); addComment.setEnabled(false); addComment.setToolTipText((String) addComment.getAction().getValue(Action.NAME)); addComment.setIcon(NotesPlugin.loadIcon("add_comment22.png")); CloseNoteAction closeIssueAction = new CloseNoteAction(this); closeIssue = new JButton(closeIssueAction); closeIssue.setEnabled(false); closeIssue.setToolTipText((String) closeIssue.getAction().getValue(Action.NAME)); closeIssue.setIcon(NotesPlugin.loadIcon("icon_valid22.png")); PointToNewNoteAction nia = new PointToNewNoteAction(newIssue, notesPlugin); newIssue.setAction(nia); newIssue.setToolTipText((String) newIssue.getAction().getValue(Action.NAME)); newIssue.setIcon(NotesPlugin.loadIcon("icon_error_add22.png")); buttonPanel.add(toggleConnectionMode); buttonPanel.add(refresh); buttonPanel.add(newIssue); buttonPanel.add(addComment); buttonPanel.add(closeIssue); queuePanel = new JPanel(new BorderLayout()); queuePanel.setName(tr("Queue")); queueList = new JList(getActionQueue()); queueList.setCellRenderer(new NotesQueueListCellRenderer()); queuePanel.add(new JScrollPane(queueList), BorderLayout.CENTER); queuePanel.add(processQueue, BorderLayout.SOUTH); processQueue.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Main.pref.put(ConfigKeys.NOTES_API_OFFLINE, "false"); setConnectionMode(false); try { getActionQueue().processQueue(); // refresh, if the api is enabled if(!Main.pref.getBoolean(ConfigKeys.NOTES_API_DISABLED)) { plugin.updateData(); } } catch (Exception e1) { System.err.println("Couldn't process action queue"); e1.printStackTrace(); } } }); tabbedPane.add(queuePanel); if (buttonLabels) { toggleConnectionMode.setHorizontalAlignment(SwingConstants.LEFT); refresh.setHorizontalAlignment(SwingConstants.LEFT); addComment.setHorizontalAlignment(SwingConstants.LEFT); closeIssue.setHorizontalAlignment(SwingConstants.LEFT); newIssue.setHorizontalAlignment(SwingConstants.LEFT); } else { toggleConnectionMode.setText(null); refresh.setText(null); addComment.setText(null); closeIssue.setText(null); newIssue.setText(null); } addCommentAction.addActionObserver(this); closeIssueAction.addActionObserver(this); setConnectionMode(offline); MapView.addLayerChangeListener(this); } @Override public void destroy() { super.destroy(); MapView.removeLayerChangeListener(this); } public synchronized void update(final Collection<Note> dataset) { // create a new list model bugListModel = new DefaultListModel(); List<Note> sortedList = new ArrayList<Note>(dataset); Collections.sort(sortedList, new BugComparator()); for (Note note : sortedList) { bugListModel.addElement(note); } bugList.setModel(bugListModel); } public void valueChanged(ListSelectionEvent e) { if (bugList.getSelectedValues().length == 0) { addComment.setEnabled(false); closeIssue.setEnabled(false); return; } List<Note> selected = new ArrayList<Note>(); for (Object listItem : bugList.getSelectedValues()) { Note note = (Note) listItem; selected.add(note); switch(note.getState()) { case closed: addComment.setEnabled(false); closeIssue.setEnabled(false); case open: addComment.setEnabled(true); closeIssue.setEnabled(true); } scrollToSelected(note); } // CurrentDataSet may be null if there is no normal, edible map // If so, a temporary DataSet is created because it's the simplest way // to fire all necessary events so OSB updates its popups. List<Note> ds = notesPlugin.getLayer().getDataSet(); if (fireSelectionChanged) { if(ds == null) ds = new ArrayList<Note>(); } } private void scrollToSelected(Note node) { for (int i = 0; i < bugListModel.getSize(); i++) { Note current = (Note) bugListModel.get(i); if (current.getId()== node.getId()) { bugList.scrollRectToVisible(bugList.getCellBounds(i, i)); bugList.setSelectedIndex(i); return; } } } public void activeLayerChange(Layer oldLayer, Layer newLayer) { } public void layerAdded(Layer newLayer) { if (newLayer == notesPlugin.getLayer()) { update(notesPlugin.getDataSet()); Main.map.mapView.moveLayer(newLayer, 0); } } public void layerRemoved(Layer oldLayer) { if (oldLayer == notesPlugin.getLayer()) { bugListModel.removeAllElements(); } } public void zoomToNote(Note node) { Main.map.mapView.zoomTo(node.getLatLon()); } public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { Note selectedNote = getSelectedNote(); if(selectedNote != null) { notesPlugin.getLayer().replaceSelection(selectedNote); if (e.getClickCount() == 2) { zoomToNote(selectedNote); } } } } public void mousePressed(MouseEvent e) { mayTriggerPopup(e); } public void mouseReleased(MouseEvent e) { mayTriggerPopup(e); } private void mayTriggerPopup(MouseEvent e) { if (e.isPopupTrigger()) { int selectedRow = bugList.locationToIndex(e.getPoint()); bugList.setSelectedIndex(selectedRow); Note selectedNote = getSelectedNote(); if(selectedNote != null) { PopupFactory.createPopup(selectedNote, this).show(e.getComponent(), e.getX(), e.getY()); } } } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void actionPerformed(NotesAction action) { if (action instanceof AddCommentAction || action instanceof CloseNoteAction) { update(notesPlugin.getDataSet()); } } private static class BugComparator implements Comparator<Note> { public int compare(Note o1, Note o2) { Note.State state1 = o1.getState(); Note.State state2 = o2.getState(); if (state1.equals(state2)) { return o1.getFirstComment().getText().compareTo(o2.getFirstComment().getText()); } return state1.compareTo(state2); } } private boolean downloaded = false; protected void initialDownload() { Main.worker.execute(new Runnable() { public void run() { notesPlugin.updateData(); } }); } @Override public void showDialog() { if (!downloaded) { initialDownload(); downloaded = true; } super.showDialog(); } public void showQueuePanel() { if(!queuePanelVisible) { remove(bugListPanel); tabbedPane.add(bugListPanel, 0); add(tabbedPane, BorderLayout.CENTER); tabbedPane.setSelectedIndex(0); queuePanelVisible = true; invalidate(); repaint(); } } public void hideQueuePanel() { if(queuePanelVisible) { tabbedPane.remove(bugListPanel); remove(tabbedPane); add(bugListPanel, BorderLayout.CENTER); queuePanelVisible = false; invalidate(); repaint(); } } public Note getSelectedNote() { if(bugList.getSelectedValue() != null) { return (Note) bugList.getSelectedValue(); } else { return null; } } public void setSelectedNote(Note note) { if(note == null) { bugList.clearSelection(); } else { bugList.setSelectedValue(note, true); } } public void setConnectionMode(boolean offline) { refresh.setEnabled(!offline); setTitle(tr("OpenStreetMap Notes ({0})", (offline ? tr("offline") : tr("online")))); toggleConnectionMode.setSelected(offline); } public void selectionChanged(Collection<Note> newSelection) { if(newSelection.size() == 1) { Note selectedNote = newSelection.iterator().next(); if(notesPlugin.getLayer() != null && notesPlugin.getLayer().getDataSet() != null && notesPlugin.getLayer().getDataSet() != null && notesPlugin.getLayer().getDataSet().contains(selectedNote)) { setSelectedNote(selectedNote); } else { bugList.clearSelection(); } } else { bugList.clearSelection(); } } public ActionQueue getActionQueue() { return actionQueue; } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); bugList.setEnabled(enabled); queueList.setEnabled(enabled); addComment.setEnabled(enabled); closeIssue.setEnabled(enabled); } }
package com.rtg.relation; import java.io.File; import java.io.IOException; import com.rtg.util.diagnostic.Diagnostic; import com.rtg.util.io.MemoryPrintStream; import com.rtg.util.io.TestDirectory; import com.rtg.util.test.FileHelper; import com.rtg.util.test.NanoRegression; import com.rtg.vcf.header.PedigreeField; import com.rtg.vcf.header.VcfHeader; import junit.framework.TestCase; public class VcfPedigreeParserTest extends TestCase { private NanoRegression mNano = null; @Override public void setUp() throws Exception { super.setUp(); mNano = new NanoRegression(this.getClass()); } @Override public void tearDown() throws Exception { super.tearDown(); try { mNano.finish(); } finally { mNano = null; } } public void testParsing() throws IOException { try (final TestDirectory dir = new TestDirectory()) { final File vcfFile = FileHelper.resourceToFile("com/rtg/relation/resources/vcfheader.vcf", new File(dir, "header.vcf")); final GenomeRelationships ped2 = VcfPedigreeParser.loadFile(vcfFile); mNano.check("pedfromvcf", PedFileParser.toString(ped2)); } } public void testPedConversion() throws IOException { try (final TestDirectory dir = new TestDirectory()) { final File pedFile = FileHelper.resourceToFile("com/rtg/relation/resources/pop.ped", new File(dir, "pop.ped")); final GenomeRelationships ped = PedFileParser.loadFile(pedFile); final VcfHeader header = new VcfHeader(); header.addLine(VcfHeader.VERSION_LINE); VcfPedigreeParser.addPedigreeFields(header, ped); for (String sample : ped.filterByGenomes(new GenomeRelationships.PrimaryGenomeFilter(ped)).genomes()) { header.addSampleName(sample); } mNano.check("vcffromped.vcf", header.toString()); } } public void testFullCircle() throws IOException { try (final TestDirectory dir = new TestDirectory()) { final File vcfFile = FileHelper.resourceToFile("com/rtg/relation/resources/vcffromped.vcf", new File(dir, "pop.vcf")); final GenomeRelationships ped = VcfPedigreeParser.loadFile(vcfFile); final VcfHeader header = new VcfHeader(); header.addLine(VcfHeader.VERSION_LINE); VcfPedigreeParser.addPedigreeFields(header, ped); for (String sample : ped.filterByGenomes(new GenomeRelationships.PrimaryGenomeFilter(ped)).genomes()) { header.addSampleName(sample); } mNano.check("vcffromped.vcf", header.toString()); } } public void testFullCircleWithCellLine() throws IOException { try (final TestDirectory dir = new TestDirectory()) { final File vcfFile = FileHelper.resourceToFile("com/rtg/relation/resources/derived.vcf", new File(dir, "pop.vcf")); final GenomeRelationships ped = VcfPedigreeParser.loadFile(vcfFile); final VcfHeader header = new VcfHeader(); header.addLine(VcfHeader.VERSION_LINE); VcfPedigreeParser.addPedigreeFields(header, ped); for (String sample : ped.filterByGenomes(new GenomeRelationships.PrimaryGenomeFilter(ped)).genomes()) { header.addSampleName(sample); } mNano.check("derived.vcf", header.toString()); } } public void testNoInformationWarning() throws IOException { final GenomeRelationships ped = new GenomeRelationships(); final PedigreeField f = new PedigreeField("##PEDIGREE=<Sibling=>"); final MemoryPrintStream mps = new MemoryPrintStream(); Diagnostic.setLogStream(mps.printStream()); VcfPedigreeParser.parsePedLine(ped, f); assertTrue(mps.toString().contains("Pedigree line contains no pedigree information: ##PEDIGREE=<Sibling=>")); Diagnostic.setLogStream(); } }
package grok.core; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Multimaps; import com.google.common.collect.SetMultimap; @AutoValue public abstract class ClimbingGrade implements Comparable<ClimbingGrade> { public enum Country { USA, FRANCE, AUSTRALIA, SOUTH_AFRICA, GERMANY, UNITED_KINGDOM; } public static ClimbingGrade usa(String value) { return of(Country.USA, value); } public static ClimbingGrade of(Country country, String value) { for (ClimbingGrade maybe : KNOWN) { if (maybe.matches(country, value)) { return maybe; } } throw new IllegalArgumentException(value + " does not exist for " + country); } // TODO(achaphiv): expose? @JsonCreator static ClimbingGrade of(Map<Country, Set<String>> values) { for (ClimbingGrade maybe : KNOWN) { if (maybe.valuesMap().equals(values)) { return maybe; } } throw new IllegalArgumentException(values + " is not a valid combination"); } //@formatter:off private static final List<ClimbingGrade> KNOWN = Arrays.asList( known("5.1 ", "2 ", "7 ", "8 ", "III- ", "M "), known("5.2 ", "2+ ", "8 ", "9 ", "III ", "D "), known("5.3 ", "3 ", "9/10 ", "10 ", "III+ ", "VD 3a "), known("5.4 ", "3+ ", "11 ", "12 ", "IV- ", "VD/HVD 3b"), known("5.5 ", "4 ", "12 ", "13 ", "IV ", "HVD/S 3c "), known("5.6 ", "4+ ", "13 ", "14 ", "IV+/V- ", "MS 4a "), known("5.7 ", "5a ", "14/15", "15 ", "V-/V ", "S/HS 4b "), known("5.8 ", "5b ", "15/16", "16 ", "V+/VI- ", "HS/VS 4b "), known("5.9 ", "5c ", "17 ", "17/18", "VI-/VI ", "HVS 4c "), known("5.10a", "6a ", "18 ", "19 ", "VI/VI+ ", "HVS 5a "), known("5.10b", "6a+ ", "19 ", "20 ", "VII- ", "E1 5a "), known("5.10c", "6b ", "20 ", "21 ", "VII-/VII ", "E1 5b "), known("5.10d", "6b+ ", "20/21", "22 ", "VII/VII+ ", "E2 5b "), known("5.11a", "6c ", "21 ", "22/23", "VII+ ", "E2 5c "), known("5.11b", "6c/6c+", "22 ", "23/24", "VIII- ", "E3 5c "), known("5.11c", "6c+ ", "22/23", "24 ", "VIII ", "E3 6a "), known("5.11d", "7a ", "23 ", "25 ", "VIII/VIII+", "E4 6a "), known("5.12a", "7a+ ", "24 ", "26 ", "VIII+ ", "E4 6b "), known("5.12b", "7b ", "25 ", "27 ", "IX- ", "E5 6b "), known("5.12c", "7b+ ", "26 ", "28 ", "IX-/IX ", "E5/E6 6b "), known("5.12d", "7c ", "27 ", "29 ", "IX/IX+ ", "E6 6b "), known("5.13a", "7c+ ", "28 ", "30 ", "IX+ ", "E6 6c "), known("5.13b", "8a ", "29 ", "31 ", "X- ", "E7 6c "), known("5.13c", "8a+ ", "30 ", "32 ", "X-/X ", "E7 7a "), known("5.13d", "8b ", "31 ", "33 ", "X/X+ ", "E8 7a "), known("5.14a", "8b+ ", "32 ", "34 ", "X+ ", "E8 7b "), known("5.14b", "8c ", "33 ", "35 ", "XI- ", "E9 7b "), known("5.14c", "8c+ ", "34 ", "36 ", "XI ", "E10 7b "), known("5.14d", "9a ", "35 ", "37 ", "XI+ ", "E10 7c "), known("5.15a", "9a+ ", "36 ", "38 ", "XI+/XII- ", "E11 7c "), known("5.15b", "9b ", "37 ", "39 ", "XII-/XII ", "E11 8a "), known("5.15c", "9b+ ", "38 ", "40 ", "XII ", "E11 8b "), known("5.15d", "9c ", "39 ", "41 ", "XII+ ", "E11 8c ")); //@formatter:on private static ClimbingGrade known(String usa, String france, String australia, String southAfrica, String germany, String uk) { return new AutoValue_ClimbingGrade(ImmutableSetMultimap.<Country, String> builder() .putAll(Country.USA, split(usa)) .putAll(Country.FRANCE, split(france)) .putAll(Country.AUSTRALIA, split(australia)) .putAll(Country.SOUTH_AFRICA, split(southAfrica)) .putAll(Country.GERMANY, split(germany)) .putAll(Country.UNITED_KINGDOM, split(uk)) .build()); } private static String[] split(String value) { return value.trim().split("/"); } ClimbingGrade() {} abstract SetMultimap<Country, String> values(); // TODO(achaphiv): expose? @JsonValue Map<Country, Set<String>> valuesMap() { return Multimaps.asMap(values()); } private boolean matches(Country country, String value) { return values().get(country).contains(value); } @Override public int compareTo(ClimbingGrade other) { return Integer.compare(KNOWN.indexOf(this), KNOWN.indexOf(other)); } }
package gillespieSSAjava; import graph.Graph; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.PriorityQueue; import java.util.Random; import main.Gui; import org.sbml.libsbml.*; import java.awt.BorderLayout; import java.io.*; import java.lang.Math; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; public class GillespieSSAJavaSingleStep { // SpeciesIndex maps from each species to a column index. // ReactionsIndex maps from each reaction to a row index. // The state change vector is a 2-D array with reactions as rows and species as columns. // The amount of molecules for reactant j in Reaction i is indexed as SateChangeVetor[i][j]. private HashMap<String, Integer> SpeciesToIndex = new HashMap<String, Integer>(); private HashMap<Integer, String> IndexToSpecies = new HashMap<Integer, String>(); private HashMap<String, Integer> ReactionsToIndex = new HashMap<String, Integer>(); private HashMap<Integer, String> IndexToReactions = new HashMap<Integer, String>(); private HashMap<String, Double> SpeciesList = new HashMap<String, Double>(); private HashMap<String, Double> GlobalParamsList = new HashMap<String, Double>(); // static HashMap<String, Double> GlobalParamsChangeList = new HashMap<String, Double>(); // static HashMap<String, Double> CompartmentList = new HashMap<String, Double>(); private HashMap<String, Double> PropensityFunctionList = new HashMap<String, Double>(); private HashMap<String, Boolean> EnoughMolecules = new HashMap<String, Boolean>(); private String SpeciesID; private String GlobalParamID; // private String CompartmentID; private double SpeciesInitAmount; private double GlobalParamValue; // private double ComparmentSize; private double PropensityFunctionValue = 0; private double PropensitySum=0.0; private double PropensityFunctionValueFW = 0; private double PropensityFunctionValueRV = 0; private double[][] StateChangeVector; private JTextField tNext; private JComboBox nextReactionsList; private double tau=0.0; private int miu=0; private double time = 0; private double t_next = 0; private double maxTime = 0; private double nextEventTime = 0; private int NumIrreversible = 0; private int NumReversible = 0; private int NumReactions = 0; private FileOutputStream output; private PrintStream outTSD; private double runUntil = 0; private boolean[] prevTriggerValArray = null; public GillespieSSAJavaSingleStep() { } public void PerformSim (String SBMLFileName,String outDir, double timeLimit, double timeStep, Graph graph) throws FileNotFoundException{ int optionValue = -1; // System.out.println("outDir = " + outDir); String outTSDName = outDir + "/run-1.tsd"; output = new FileOutputStream(outTSDName); outTSD = new PrintStream(output); SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(SBMLFileName); Model model = document.getModel(); outTSD.print("("); for (int i=0; i < model.getNumReactions(); i++){ Reaction reaction = model.getReaction(i); if (reaction.getReversible()) NumReversible ++; else NumIrreversible ++; } NumReactions = 2*NumReversible + NumIrreversible; StateChangeVector=new double[(int) NumReactions][(int) model.getNumSpecies()]; // 1. Initialize time (t) and states (x) time = 0.0; // get the species and the associated initial values for (int i=0;i<model.getNumSpecies();i++){ SpeciesID= model.getListOfSpecies().get(i).getId(); SpeciesInitAmount = model.getListOfSpecies().get(i).getInitialAmount(); SpeciesList.put(SpeciesID, SpeciesInitAmount); SpeciesToIndex.put(SpeciesID,i); IndexToSpecies.put(i,SpeciesID); } // for (int i=0;i<SpeciesList.size();i++){ // System.out.println(SpeciesList.keySet().toArray()[i] + " = " + SpeciesList.get(SpeciesList.keySet().toArray()[i])); outTSD.print("(\"time\","); for (int i=0;i<SpeciesList.size();i++){ if (i<SpeciesList.size()-1) outTSD.print("\"" + SpeciesList.keySet().toArray()[i] + "\"" + ","); else outTSD.print("\"" + SpeciesList.keySet().toArray()[i] + "\"),"); } outTSD.print("(" + time + ", "); for (int i=0;i<SpeciesList.size();i++){ if (i<SpeciesList.size()-1) outTSD.print(SpeciesList.get(SpeciesList.keySet().toArray()[i]) + ", "); else outTSD.print(SpeciesList.get(SpeciesList.keySet().toArray()[i]) + "),"); } // get the global parameters // System.out.println("GlobalParameters:"); if(model.getNumParameters() != 0){ for (int i=0;i<model.getNumParameters();i++){ GlobalParamID= model.getListOfParameters().get(i).getId(); GlobalParamValue = model.getListOfParameters().get(i).getValue(); GlobalParamsList.put(GlobalParamID,GlobalParamValue); // GlobalParamsChangeList.put(GlobalParamID, (double) 0); } } //Currently, we assume only one compartment in one SBML file // get compartments and their sizes. // if (model.getNumCompartments() !=0){ // for (int i=0;i<model.getNumCompartments();i++){ // CompartmentID = model.getListOfCompartments().get(i).getId(); // ComparmentSize = model.getListOfCompartments().get(i).getSize(); //// CompartmentList.put(CompartmentID, ComparmentSize); //// System.out.println("Compartment " + i + "=" + CompartmentID); //// System.out.println("CompartmentSize = " + ComparmentSize); // initialize state change vector int index = 0; int l = 0; while (index<NumReactions){ Reaction currentReaction = model.getListOfReactions().get(l); // System.out.println("currentReaction = " + currentReaction.getId()); // irreversible reaction if (!currentReaction.getReversible()){ String currentReactionID = currentReaction.getId(); ReactionsToIndex.put(currentReactionID, index); IndexToReactions.put(index, currentReactionID); for (int j=0; j < currentReaction.getNumReactants(); j++){ String SpeciesAsReactant = currentReaction.getReactant(j).getSpecies(); StateChangeVector[index][SpeciesToIndex.get(SpeciesAsReactant)] = -currentReaction.getReactant(j).getStoichiometry(); } for (int j=0; j < currentReaction.getNumProducts(); j++){ String SpeciesAsProduct = currentReaction.getProduct(j).getSpecies(); StateChangeVector[index][SpeciesToIndex.get(SpeciesAsProduct)] = currentReaction.getProduct(j).getStoichiometry(); } index++; } else { // reversible reaction String currentReactionID = currentReaction.getId(); ReactionsToIndex.put(currentReactionID, index); ReactionsToIndex.put(currentReactionID + "_rev", index+1); IndexToReactions.put(index, currentReactionID); IndexToReactions.put(index+1, currentReactionID+ "_rev"); for (int j=0; j < currentReaction.getNumReactants(); j++){ String SpeciesAsReactant = currentReaction.getReactant(j).getSpecies(); StateChangeVector[index][SpeciesToIndex.get(SpeciesAsReactant)] = -currentReaction.getReactant(j).getStoichiometry(); StateChangeVector[index+1][SpeciesToIndex.get(SpeciesAsReactant)] = currentReaction.getReactant(j).getStoichiometry(); } for (int j=0; j < currentReaction.getNumProducts(); j++){ String SpeciesAsProduct = currentReaction.getProduct(j).getSpecies(); StateChangeVector[index][SpeciesToIndex.get(SpeciesAsProduct)] = currentReaction.getProduct(j).getStoichiometry(); StateChangeVector[index+1][SpeciesToIndex.get(SpeciesAsProduct)] = -currentReaction.getProduct(j).getStoichiometry(); } index = index + 2; } l++; } // Initialize events. // if model does not include any events, both eventList and eventQueue are set to null ListOfEvents eventList = null; PriorityQueue<EventQueueElement> eventQueue = null; int initEventQueueCap = 20; if (model.getListOfEvents().size() >0) { eventList = model.getListOfEvents(); prevTriggerValArray = new boolean[(int) eventList.size()]; for(int i=0; i< eventList.size();i++){ Event event = eventList.get(i); Trigger trigger = event.getTrigger(); // TODO add the feature for persistent event and event that uses values from trigger time. if (trigger.getPersistent() | event.getUseValuesFromTriggerTime()) { JOptionPane.showMessageDialog(Gui.frame, "The simulator does not currently support persistent triggers or UseValuesFromTriggerTime.", "Error in trigger", JOptionPane.ERROR_MESSAGE); break; } if (trigger.getInitialValue()) { prevTriggerValArray[i] = true; } else { prevTriggerValArray[i] = false; } } // Initialize event queue EventQueueComparator comparator = new EventQueueComparator(); eventQueue = new PriorityQueue<EventQueueElement>(initEventQueueCap, comparator); } graph.editGraph(); // // Create a table to hold the results // DefaultTableModel tableModel = new DefaultTableModel(); // tableModel.addColumn("t"); // tableModel.addColumn("tau"); // tableModel.addColumn("Next Reaction"); // SimResultsTable simResultsTbl = new SimResultsTable(tableModel); // JFrame tableFrame = new JFrame("Simulation Results"); // simResultsTbl.showTable(tableFrame, simResultsTbl); // while (time<=timeLimit) { // 2. Update and fire events; evaluate propensity functions if (timeStep == Double.MAX_VALUE) { maxTime = Double.MAX_VALUE; } else { maxTime = maxTime + timeStep; } boolean eventDelayNegative = false; if (model.getListOfEvents().size() >0) { do { eventDelayNegative = updateEventQueue(eventList, eventQueue); if (!eventDelayNegative && eventQueue.size() > 0) { nextEventTime = fireEvent(eventQueue, initEventQueueCap, eventList); } } while (eventQueue.size() > 0 && time == eventQueue.peek().getScheduledTime()); } if (eventDelayNegative) { JOptionPane.showMessageDialog(Gui.frame, "Delay expression evaluates to a negative number.", "Error in piecewise function", JOptionPane.ERROR_MESSAGE); break; } if (nextEventTime < maxTime) { maxTime = nextEventTime; } // TODO evaluate rule, constraints // Evaluate propensity functions InitializeEnoughMolecules(); PropensitySum = 0.0; // get the reactions for (int i=0;i<model.getNumReactions();i++){ Reaction currentReaction = model.getListOfReactions().get(i); //outTXT.println("Reactions" + i + ": " + currentReaction.getId()); boolean ModifierNotEmpty = true; if (currentReaction.getNumModifiers()>0){ for (int k=0; k<currentReaction.getNumModifiers();k++){ if (SpeciesList.get(currentReaction.getModifier(k).getSpecies())==0.0){ ModifierNotEmpty = false; //break; } } } String currentReactionID = currentReaction.getId(); // System.out.println("Reaction" + i + ": " + currentReactionID); // get current kinetic law KineticLaw currentKineticLaw = currentReaction.getKineticLaw(); // System.out.println("currentKineticLaw= " + currentKineticLaw.getFormula()); // get the abstract syntax tree of the current kinetic law ASTNode currentAST=currentKineticLaw.getMath(); // Start evaluation from the top AST node: index 0 of ListOfNodes ASTNode currentASTNode = currentAST.getListOfNodes().get(0); // get the list of local parameters ListOfLocalParameters currentListOfLocalParams = currentKineticLaw.getListOfLocalParameters(); HashMap<String, Double> LocalParamsList = new HashMap<String, Double>(); if (currentListOfLocalParams.size() > 0){ for (int j=0; j<currentListOfLocalParams.size(); j++){ LocalParamsList.put(currentListOfLocalParams.get(j).getId(), currentListOfLocalParams.get(j).getValue()); //System.out.println("Local Param " + currentListOfLocalParams.get(j).getId()+ " = " + currentListOfLocalParams.get(j).getValue()); } } // calculate propensity function. // For irreversible reaction, propensity function = kinetic law if (!currentReaction.getReversible()){ // enzymatic reaction with no reactants if (currentReaction.getNumReactants() == 0 && currentReaction.getNumProducts()>0 && currentReaction.getNumModifiers()>0){ boolean EnoughMoleculesCond = ModifierNotEmpty; if(!EnoughMoleculesCond){ PropensityFunctionValue = 0; EnoughMolecules.put(currentReactionID, false); } if (EnoughMolecules.get(currentReactionID)){ PropensityFunctionValue = Double.parseDouble(evaluatePropensityFunction(currentASTNode, LocalParamsList)); } } // other reactions if (currentReaction.getNumReactants() > 0){ for (int j=0; j < currentReaction.getNumReactants(); j++){ // not enough reactant Molecules boolean EnoughMoleculesCond = SpeciesList.get(currentReaction.getReactant(j).getSpecies()) >= currentReaction.getReactant(j).getStoichiometry(); if(!EnoughMoleculesCond){ PropensityFunctionValue = 0; EnoughMolecules.put(currentReactionID, false); // outTXT.println("EnoughMolecules: " + currentReactionID + " = " + EnoughMolecules.get(currentReactionID)); break; } } if (EnoughMolecules.get(currentReactionID)){ PropensityFunctionValue = Double.parseDouble(evaluatePropensityFunction(currentASTNode,LocalParamsList)); } } PropensitySum = PropensitySum + PropensityFunctionValue; PropensityFunctionList.put(currentReactionID, PropensityFunctionValue); } else { // reversible reaction // For reversible, the root node should be a minus operation // Evaluate kinetic law for the forward reaction // Check that there are enough Molecules for the reaction to happen for (int j=0; j < currentReaction.getNumReactants(); j++){ // not enough reactant Molecules boolean EnoughMoleculesCondFW = SpeciesList.get(currentReaction.getReactant(j).getSpecies()) >= currentReaction.getReactant(j).getStoichiometry(); if(!EnoughMoleculesCondFW){ PropensityFunctionValueFW = 0; EnoughMolecules.put(currentReactionID, false); break; } } if (EnoughMolecules.get(currentReactionID)) { // System.out.println("FW current AST Node = " + currentASTNode.getType()); // System.out.println("FW current left child = " + currentASTNode.getLeftChild().getType()); PropensityFunctionValueFW = Double.parseDouble(evaluatePropensityFunction(currentASTNode.getLeftChild(), LocalParamsList)); // System.out.println("PropensityFunctionValueFW = " + PropensityFunctionValueFW); } PropensitySum = PropensitySum + PropensityFunctionValueFW; PropensityFunctionList.put(currentReactionID, PropensityFunctionValueFW); // Evaluate kinetic law for the reverse reaction // Check that there are enough Molecules for the reaction to happen for (int j=0; j < currentReaction.getNumProducts(); j++){ // not enough reactant Molecules boolean EnoughMoleculesCondRV = SpeciesList.get(currentReaction.getProduct(j).getSpecies()) >= currentReaction.getProduct(j).getStoichiometry(); if(!EnoughMoleculesCondRV){ PropensityFunctionValueRV = 0; EnoughMolecules.put(currentReactionID+"_rev", false); break; } } if (EnoughMolecules.get(currentReactionID+"_rev")){ PropensityFunctionValueRV = Double.parseDouble(evaluatePropensityFunction(currentASTNode.getRightChild(),LocalParamsList)); } PropensitySum = PropensitySum + PropensityFunctionValueRV; PropensityFunctionList.put(currentReactionID+"_rev", PropensityFunctionValueRV); } } // TODO PropensitySum == 0 if (PropensitySum == 0){ time = maxTime; System.out.println("propensity = 0"); System.out.println("time = " + time); // continue; break; } // 3. Determine the time, tau, until the next reaction. // Detect if user specifies the time increment tau. Random generator = new Random(); // Draw one uniform(0,1) random numbers r1. double r1 = generator.nextDouble(); // Determine randomly the time, tau, until the next reaction. tau = (1/PropensitySum)*Math.log(1/r1); // 5. Determine the next reaction: (miu is the row index of state change vector array) double SumLeft = 0.0; int count; double r2 = generator.nextDouble(); for (count=0; SumLeft <= r2*PropensitySum; count++){ SumLeft = SumLeft + PropensityFunctionList.get(IndexToReactions.get(count)); if (SumLeft > r2*PropensitySum) break; } miu = count; // Pop up the interactive menu and asks the user to specify tau and miu String[] CustomParams=new String[3]; // optionValue: 0=step, 1=run, 2=terminate boolean hasRunModeStarted = false; boolean isRunMode = (optionValue == 1) && time < runUntil; if (!isRunMode) { CustomParams = openInteractiveMenu(time,tau,miu); t_next = Double.parseDouble(CustomParams[0]); while (t_next < time){ JOptionPane.showMessageDialog(Gui.frame, "The value of t_next needs to be greater than current time", "Error in next simulation time", JOptionPane.ERROR_MESSAGE); CustomParams = openInteractiveMenu(time,tau,miu); t_next = Double.parseDouble(CustomParams[0]); } optionValue = Integer.parseInt(CustomParams[2]); if (optionValue == 0) { tau = t_next - time; miu = ReactionsToIndex.get(CustomParams[1]); } else if(optionValue == 1 && time >= runUntil){ runUntil = Double.parseDouble(CustomParams[0]); miu = ReactionsToIndex.get(CustomParams[1]); hasRunModeStarted = true; // String[] CustomParamsRun = openRunMenu(); // int runUntil_optVal = Integer.parseInt(CustomParamsRun[1]); // // runUntil_optVal: 0=Run, 1=Cancel // if (runUntil_optVal == 0) { // runUntil = t + Double.parseDouble(CustomParamsRun[0]); // hasRunModeStarted = true; // else { // runUntil_optVal == 1 (Cancel) // continue; } else { break; } } // 6. Determine the new state: t = t + tau and x = x + v[miu] double t_current = time; if (maxTime <= time+tau) time = maxTime; else time = time + tau; // Determine the next reaction to fire, in row miu of StateChangeVector. // Update the species amounts according to the state-change-vector in row miu. for (int i=0; i < model.getNumSpecies(); i++){ if (StateChangeVector[miu][i]!=0){ String SpeciesToUpdate = IndexToSpecies.get(i); // System.out.println("SpeciesToUpdate = " + SpeciesToUpdate); if (EnoughMolecules.get(IndexToReactions.get(miu))){ double SpeciesToUpdateAmount = SpeciesList.get(SpeciesToUpdate) + StateChangeVector[miu][i]; SpeciesList.put(SpeciesToUpdate, SpeciesToUpdateAmount); } } } // System.out.println("t_current = " + t_current); // System.out.println("t = " + t); // System.out.println("t_next = " + t_next); //// System.out.println("tau = " + tau); //// System.out.println("miu = " + miu); //// System.out.println("Next reaction is " + IndexToReactions.get(miu)); // // Print results to a table and display it. // if ((!isRunMode && !hasRunModeStarted) || (isRunMode && t >= runUntil)){ // tableModel.addRow(new Object[]{t_current, tau, IndexToReactions.get(miu)}); // simResultsTbl.showTable(tableFrame, simResultsTbl); outTSD.print("(" + time + ", "); for (int i=0;i<SpeciesList.size();i++){ if (i<SpeciesList.size()-1) outTSD.print(SpeciesList.get(SpeciesList.keySet().toArray()[i]) + ", "); else outTSD.print(SpeciesList.get(SpeciesList.keySet().toArray()[i]) + "),"); } if ((!isRunMode && !hasRunModeStarted) || (isRunMode && time >= runUntil)) { graph.refresh(); } } outTSD.print(")"); } static { try { System.loadLibrary("sbmlj"); } catch (Exception e) { System.err.println("Could not load libSBML library:" + e.getMessage()); } } public boolean updateEventQueue(ListOfEvents eventList, PriorityQueue<EventQueueElement> eventQueue){ boolean delayNegative = false; for(int i=0; i< eventList.size();i++){ Event currEvent = eventList.get(i); Trigger trigger = currEvent.getTrigger(); // TODO if trigger is not specified ASTNode triggerTopASTNode = trigger.getMath().getListOfNodes().get(0); boolean currTriggerVal = Boolean.parseBoolean(evaluateAST(triggerTopASTNode)); boolean prevTriggerVal = prevTriggerValArray[i]; // update the event queue if (!prevTriggerVal && currTriggerVal) { // TODO if delay/priority is not specified ASTNode delayTopASTNode = currEvent.getDelay().getMath().getListOfNodes().get(0); double delayVal = Double.parseDouble(evaluateAST(delayTopASTNode)); ASTNode priorityTopASTNode = currEvent.getPriority().getMath().getListOfNodes().get(0); double priorityVal = Double.parseDouble(evaluateAST(priorityTopASTNode)); if (delayVal < 0) { delayNegative = true; break; } // Assume event assignment evaluates at firing time // add newly triggered event to the event queue EventQueueElement currEventQueueElement = new EventQueueElement(time, currEvent.getId(), delayVal, priorityVal); eventQueue.add(currEventQueueElement); prevTriggerValArray[i] = currTriggerVal; } if (prevTriggerVal && !currTriggerVal && eventQueue.contains(currEvent)) { // remove event from event queue eventQueue.remove(currEvent); prevTriggerValArray[i] = currTriggerVal; } } return delayNegative; } private double fireEvent(PriorityQueue<EventQueueElement> eventQueue, int initEventQueueCap, ListOfEvents eventList) { // Assume event assignments are evaluated at fire time if (time == eventQueue.peek().getScheduledTime()) { ArrayList<EventQueueElement> eventsReadyArray = new ArrayList<EventQueueElement>(); EventQueueElement eventReady = eventQueue.poll(); // check if multiple events are ready to fire while(time == eventQueue.peek().getScheduledTime()){ eventsReadyArray.add(eventReady); eventReady = eventQueue.poll(); } // TODO Create GUI to let user to choose a event to fire Random generator = new Random(); int randomIndex = generator.nextInt(eventsReadyArray.size()); Event eventToFire = eventList.get(eventsReadyArray.get(randomIndex).getEventId()); ListOfEventAssignments eventToFireAssignList = eventToFire.getListOfEventAssignments(); for (int i = 0; i < eventToFireAssignList.size(); i ++){ double assignment = Double.parseDouble(evaluateAST(eventToFireAssignList.get(i).getMath().getListOfNodes().get(0))); String variable = eventToFireAssignList.get(i).getVariable(); if(SpeciesList.containsKey(variable)) { SpeciesList.put(variable, assignment); } else if(GlobalParamsList.containsKey(variable)){ GlobalParamsList.put(variable, assignment); } } // Put the all events in eventsReadyArray (except eventToFire) back to the event queue. eventsReadyArray.remove(eventToFire); for (int i = 0; i < eventsReadyArray.size() - 1; i++){ eventQueue.add(eventsReadyArray.get(i)); } return eventQueue.peek().getScheduledTime(); } else if (time < eventQueue.peek().getScheduledTime()){ return eventQueue.peek().getScheduledTime(); } else { JOptionPane.showMessageDialog(Gui.frame, "Event time has passed.", "Error in event firing", JOptionPane.ERROR_MESSAGE); return -1; } } private String evaluateAST(ASTNode currentASTNode) { String retStr = null; if(isLeafNode(currentASTNode)){ retStr = evaluateLeafNode(currentASTNode); } else{ // internal node with left and right children int type_const=currentASTNode.getType(); switch (type_const) { // arithmetic operators case libsbml.AST_PLUS: retStr = Double.toString(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())) + Double.parseDouble(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_MINUS: retStr = Double.toString(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())) - Double.parseDouble(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_TIMES: retStr = Double.toString(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())) * Double.parseDouble(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_DIVIDE:retStr = Double.toString(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())) / Double.parseDouble(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_FUNCTION_POWER: retStr = Double.toString(Math.pow(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())), Double.parseDouble(evaluateAST(currentASTNode.getRightChild())))); break; // logical operators case libsbml.AST_LOGICAL_AND: retStr = Boolean.toString(Boolean.parseBoolean(evaluateAST(currentASTNode.getLeftChild())) && Boolean.parseBoolean(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_LOGICAL_OR: retStr = Boolean.toString(Boolean.parseBoolean(evaluateAST(currentASTNode.getLeftChild())) || Boolean.parseBoolean(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_LOGICAL_NOT: retStr = Boolean.toString(!Boolean.parseBoolean(evaluateAST(currentASTNode.getLeftChild()))); break; case libsbml.AST_LOGICAL_XOR: retStr = Boolean.toString(Boolean.parseBoolean(evaluateAST(currentASTNode.getLeftChild())) ^ Boolean.parseBoolean(evaluateAST(currentASTNode.getRightChild()))); break; // relational operators // TODO EQ, NEQ can have boolean arguments case libsbml.AST_RELATIONAL_EQ: retStr = Boolean.toString(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())) == Double.parseDouble(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_RELATIONAL_GEQ: retStr = Boolean.toString(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())) >= Double.parseDouble(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_RELATIONAL_GT: retStr = Boolean.toString(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())) > Double.parseDouble(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_RELATIONAL_LEQ: retStr = Boolean.toString(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())) <= Double.parseDouble(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_RELATIONAL_LT: retStr = Boolean.toString(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())) < Double.parseDouble(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_RELATIONAL_NEQ: retStr = Boolean.toString(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())) != Double.parseDouble(evaluateAST(currentASTNode.getRightChild()))); break; // other operators case libsbml.AST_FUNCTION_PIECEWISE: { //Currently, the evaluator only accepts piecewise(arg0, arg1, arg2). arg0 and arg2 are real, and arg1 is boolean System.out.println("currentASTNode.getNumChildren() = " + currentASTNode.getNumChildren()); if (currentASTNode.getNumChildren() == 3) { if (Boolean.parseBoolean(evaluateAST(currentASTNode.getChild(1)))){ retStr = Double.toString(Double.parseDouble(evaluateAST(currentASTNode.getChild(2)))); } else { retStr = Double.toString(Double.parseDouble(evaluateAST(currentASTNode.getChild(0)))); } } else { JOptionPane.showMessageDialog(Gui.frame, "The piecewise function only accepts 3 children.", "Error in piecewise function", JOptionPane.ERROR_MESSAGE); break; } break; } // TODO MOD, BITNOT, BITOR, BITAND, BITXOR, idiv } } return retStr; } public boolean isLeafNode(ASTNode node){ boolean ret = false; ret = node.isConstant() || node.isInteger() || node.isReal() || node.isName() || node.isRational(); return ret; } public String evaluateLeafNode(ASTNode currentASTNode){ double node_val=0; if(currentASTNode.isInteger()){ node_val = currentASTNode.getInteger(); } else if(currentASTNode.isReal()){ node_val = currentASTNode.getReal(); } else if(currentASTNode.isName()){ if (SpeciesToIndex.containsKey(currentASTNode.getName())){ node_val = SpeciesList.get(currentASTNode.getName()); } else if (GlobalParamsList.containsKey(currentASTNode.getName())){ node_val = GlobalParamsList.get(currentASTNode.getName()); } } return Double.toString(node_val); } public void InitializeEnoughMolecules(){ for (int i = 0; i < ReactionsToIndex.size(); i++){ EnoughMolecules.put((String)ReactionsToIndex.keySet().toArray()[i], true); } } public String[] openInteractiveMenu(double t, double tau, int miu) { String[] tNext_miu_optVal = new String[3]; JPanel tNextPanel = new JPanel(); JPanel nextReactionsListPanel = new JPanel(); JPanel mainPanel = new JPanel(new BorderLayout()); tNextPanel.add(new JLabel("t_next:")); tNext = new JTextField(10); double t_next_deft = t + tau; tNext.setText("" + t_next_deft); tNextPanel.add(tNext); nextReactionsListPanel.add(new JLabel("Next reaction:")); // l = number of possible reactions that can fire at t_next int l = 0; for (int i=0; i<NumReactions; i++){ // Check if a reaction has enough molecules to fire if (EnoughMolecules.get(IndexToReactions.get(i))){ l++; } } // create a drop-down list of next possible firing reactions String[] nextReactionsArray = new String[l]; if (EnoughMolecules.get(IndexToReactions.get(miu))){ nextReactionsArray[0] = IndexToReactions.get(miu); } int k = 1; for (int i=0; i<NumReactions; i++){ // Check if a reaction has enough molecules to fire if (EnoughMolecules.get(IndexToReactions.get(i)) && (i!=miu)){ nextReactionsArray[k] = IndexToReactions.get(i); k++; } } nextReactionsList = new JComboBox(nextReactionsArray); nextReactionsListPanel.add(nextReactionsList); mainPanel.add(tNextPanel, "North"); mainPanel.add(nextReactionsListPanel, "Center"); Object[] options = {"Step", "Run", "Terminate"}; int optionValue; optionValue = JOptionPane.showOptionDialog(Gui.frame, mainPanel, "Next Simulation Time", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); tNext_miu_optVal[0]= tNext.getText().trim(); tNext_miu_optVal[1]=(String) nextReactionsList.getSelectedItem(); tNext_miu_optVal[2]="" + optionValue; return tNext_miu_optVal; } // public String[] openRunMenu(){ // int optlVal; // String[] runTimeLimit_optVal = new String[2]; // JPanel runTimeLimitPanel = new JPanel(); // runTimeLimitPanel.add(new JLabel("Time limit to run:")); // JTextField runTimeLimit = new JTextField(10); // runTimeLimitPanel.add(runTimeLimit); // Object[] options = {"Run", "Cancel"}; // optlVal = JOptionPane.showOptionDialog(BioSim.frame, runTimeLimitPanel, "Specify Run Time Limit", // JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); // runTimeLimit_optVal[0] = runTimeLimit.getText().trim(); // runTimeLimit_optVal[1] = "" + optlVal; //// System.out.println("runUntil_optVal[0] = " + runUntil_optVal[0]); // if (optlVal == 0 && runTimeLimit_optVal[0].equals("")) { // JOptionPane.showMessageDialog(BioSim.frame, "Please specify a time limit.", // "Error in Run", JOptionPane.ERROR_MESSAGE); // if (optlVal == 1) { // break; // while (optlVal == 0 && runTimeLimit_optVal[0].equals("")); // return runTimeLimit_optVal; public String evaluatePropensityFunction(ASTNode currentASTNode, HashMap<String, Double>ListOfLocalParameters) { String retStr = null; if(isLeafNode(currentASTNode)){ retStr = evaluatePropensityLeafNode(currentASTNode, ListOfLocalParameters); } else{ // internal node with left and right children int type_const=currentASTNode.getType(); switch (type_const) { // arithmetic operators case libsbml.AST_PLUS: retStr = Double.toString(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())) + Double.parseDouble(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_MINUS: retStr = Double.toString(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())) - Double.parseDouble(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_TIMES: retStr = Double.toString(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())) * Double.parseDouble(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_DIVIDE:retStr = Double.toString(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())) / Double.parseDouble(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_FUNCTION_POWER: retStr = Double.toString(Math.pow(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())), Double.parseDouble(evaluateAST(currentASTNode.getRightChild())))); break; // logical operators case libsbml.AST_LOGICAL_AND: retStr = Boolean.toString(Boolean.parseBoolean(evaluateAST(currentASTNode.getLeftChild())) && Boolean.parseBoolean(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_LOGICAL_OR: retStr = Boolean.toString(Boolean.parseBoolean(evaluateAST(currentASTNode.getLeftChild())) || Boolean.parseBoolean(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_LOGICAL_NOT: retStr = Boolean.toString(!Boolean.parseBoolean(evaluateAST(currentASTNode.getLeftChild()))); break; case libsbml.AST_LOGICAL_XOR: retStr = Boolean.toString(Boolean.parseBoolean(evaluateAST(currentASTNode.getLeftChild())) ^ Boolean.parseBoolean(evaluateAST(currentASTNode.getRightChild()))); break; // relational operators // TODO EQ, NEQ can have boolean arguments case libsbml.AST_RELATIONAL_EQ: retStr = Boolean.toString(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())) == Double.parseDouble(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_RELATIONAL_GEQ: retStr = Boolean.toString(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())) >= Double.parseDouble(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_RELATIONAL_GT: retStr = Boolean.toString(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())) > Double.parseDouble(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_RELATIONAL_LEQ: retStr = Boolean.toString(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())) <= Double.parseDouble(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_RELATIONAL_LT: retStr = Boolean.toString(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())) < Double.parseDouble(evaluateAST(currentASTNode.getRightChild()))); break; case libsbml.AST_RELATIONAL_NEQ: retStr = Boolean.toString(Double.parseDouble(evaluateAST(currentASTNode.getLeftChild())) > Double.parseDouble(evaluateAST(currentASTNode.getRightChild()))); break; // other operators case libsbml.AST_FUNCTION_PIECEWISE: { //Currently, the evaluator only accepts piecewise(arg0, arg1, arg2). arg0 and arg2 are real, and arg1 is boolean if (currentASTNode.getNumChildren() == 3) { if (Boolean.parseBoolean(evaluatePropensityFunction(currentASTNode.getChild(1),ListOfLocalParameters))){ retStr = Double.toString(Double.parseDouble(evaluatePropensityFunction(currentASTNode.getChild(2),ListOfLocalParameters))); } else { retStr = Double.toString(Double.parseDouble(evaluatePropensityFunction(currentASTNode.getChild(0),ListOfLocalParameters))); } } else { JOptionPane.showMessageDialog(Gui.frame, "The piecewise function only accepts 3 children.", "Error in piecewise function", JOptionPane.ERROR_MESSAGE); } break; } // TODO MOD, BITNOT, BITOR, BITAND, BITXOR, idiv } } return retStr; } public String evaluatePropensityLeafNode(ASTNode currentASTNode, HashMap<String, Double> currentListOfLocalParams){ double node_val=0; if(currentASTNode.isInteger()){ node_val = currentASTNode.getInteger(); } else if(currentASTNode.isReal()){ node_val = currentASTNode.getReal(); } else if(currentASTNode.isName()){ if (SpeciesToIndex.containsKey(currentASTNode.getName())){ node_val = SpeciesList.get(currentASTNode.getName()); } else if (GlobalParamsList.containsKey(currentASTNode.getName()) & !currentListOfLocalParams.containsKey(currentASTNode.getName())){ node_val = GlobalParamsList.get(currentASTNode.getName()); } else if (currentListOfLocalParams.containsKey(currentASTNode.getName())){ node_val =currentListOfLocalParams.get(currentASTNode.getName()); } } return Double.toString(node_val); } }
package verification.platu.partialOrders; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import verification.platu.main.Options; import lpn.parser.ExprTree; import lpn.parser.LhpnFile; import lpn.parser.Place; import lpn.parser.Transition; public class StaticSets { private Transition curTran; private HashMap<Integer, Transition[]> allTransitions; private HashSet<LpnTransitionPair> disableSet; private HashSet<LpnTransitionPair> disableByStealingToken; private HashSet<LpnTransitionPair> enableSet; private HashSet<LpnTransitionPair> curTranDisableOtherTranFailEnablingCond; // A set of transitions (with associated LPNs) whose enabling condition can become false due to executing curTran's assignments. private HashSet<LpnTransitionPair> otherTranDisableCurTranFailEnablingCond; // A set of transitions (with associated LPNs) whose enabling condition can become false due to executing curTran's assignments. private HashSet<LpnTransitionPair> modifyAssignment; public StaticSets(Transition curTran, HashMap<Integer,Transition[]> allTransitions) { this.curTran = curTran; this.allTransitions = allTransitions; disableSet = new HashSet<LpnTransitionPair>(); disableByStealingToken = new HashSet<LpnTransitionPair>(); curTranDisableOtherTranFailEnablingCond = new HashSet<LpnTransitionPair>(); otherTranDisableCurTranFailEnablingCond = new HashSet<LpnTransitionPair>(); enableSet = new HashSet<LpnTransitionPair>(); modifyAssignment = new HashSet<LpnTransitionPair>(); } /** * Build a set of transitions that curTran can disable. * @param curLpnIndex */ public void buildCurTranDisableOtherTransSet(int curLpnIndex) { // Test if curTran can disable other transitions by stealing their tokens. if (curTran.hasConflictSet()) { if (!tranFormsSelfLoop()) { Set<Integer> conflictSet = curTran.getConflictSetTransIndices(); conflictSet.remove(curTran.getIndex()); for (Integer i : conflictSet) { LpnTransitionPair lpnTranPair = new LpnTransitionPair(curLpnIndex, i); disableByStealingToken.add(lpnTranPair); } } } // Test if curTran can disable other transitions by executing its assignments if (!curTran.getAssignments().isEmpty()) { for (Integer lpnIndex : allTransitions.keySet()) { Transition[] allTransInOneLpn = allTransitions.get(lpnIndex); for (int i = 0; i < allTransInOneLpn.length; i++) { if (curTran.equals(allTransInOneLpn[i])) continue; Transition anotherTran = allTransInOneLpn[i]; ExprTree anotherTranEnablingTree = anotherTran.getEnablingTree(); if (anotherTranEnablingTree != null && (anotherTranEnablingTree.getChange(curTran.getAssignments())=='F' || anotherTranEnablingTree.getChange(curTran.getAssignments())=='f' || anotherTranEnablingTree.getChange(curTran.getAssignments())=='X')) { if (Options.getDebugMode()) { System.out.println(curTran.getName() + " can disable " + anotherTran.getName() + ". " + anotherTran.getName() + "'s enabling condition, which is " + anotherTranEnablingTree + ", may become false due to firing of " + curTran.getName() + "."); if (anotherTranEnablingTree.getChange(curTran.getAssignments())=='F') System.out.println("Reason is " + anotherTran.getName() + "_enablingTree.getChange(" + curTran.getName() + ".getAssignments()) = F."); if (anotherTranEnablingTree.getChange(curTran.getAssignments())=='f') System.out.println("Reason is " + anotherTran.getName() + "_enablingTree.getChange(" + curTran.getName() + ".getAssignments()) = f."); if (anotherTranEnablingTree.getChange(curTran.getAssignments())=='X') System.out.println("Reason is " + anotherTran.getName() + "_enablingTree.getChange(" + curTran.getName() + ".getAssignments()) = X."); } curTranDisableOtherTranFailEnablingCond.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); } } } } disableSet.addAll(disableByStealingToken); disableSet.addAll(curTranDisableOtherTranFailEnablingCond); //buildModifyAssignSet(); disableSet.addAll(modifyAssignment); // printIntegerSet(disableByStealingToken, "disableByStealingToken"); // printIntegerSet(disableByFailingEnableCond, "disableByFailingEnableCond"); } /** * Build a set of transitions that disable curTran. * @param curLpnIndex */ public void buildOtherTransDisableCurTranSet(int curLpnIndex) { // Test if other transition(s) can disable curTran by stealing their tokens. if (curTran.hasConflictSet()) { if (!tranFormsSelfLoop()) { Set<Integer> conflictSet = curTran.getConflictSetTransIndices(); conflictSet.remove(curTran.getIndex()); for (Integer i : conflictSet) { LpnTransitionPair lpnTranPair = new LpnTransitionPair(curLpnIndex, i); disableByStealingToken.add(lpnTranPair); } } } // Test if other transitions can disable curTran by executing their assignments if (!curTran.isPersistent()) { for (Integer lpnIndex : allTransitions.keySet()) { Transition[] allTransInOneLpn = allTransitions.get(lpnIndex); for (int i = 0; i < allTransInOneLpn.length; i++) { if (curTran.equals(allTransInOneLpn[i])) continue; Transition anotherTran = allTransInOneLpn[i]; if (!anotherTran.getAssignments().isEmpty()) { ExprTree curTranEnablingTree = curTran.getEnablingTree(); if (curTranEnablingTree != null && (curTranEnablingTree.getChange(anotherTran.getAssignments())=='F' || curTranEnablingTree.getChange(anotherTran.getAssignments())=='f' || curTranEnablingTree.getChange(anotherTran.getAssignments())=='X')) { if (Options.getDebugMode()) { System.out.println(curTran.getName() + " can be disabled by " + anotherTran.getName() + ". " + curTran.getName() + "'s enabling condition, which is " + curTranEnablingTree + ", may become false due to firing of " + anotherTran.getName() + "."); if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='F') System.out.println("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = F."); if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='f') System.out.println("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = f."); if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='X') System.out.println("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = X."); } otherTranDisableCurTranFailEnablingCond.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); } } } } } disableSet.addAll(disableByStealingToken); disableSet.addAll(otherTranDisableCurTranFailEnablingCond); } private boolean tranFormsSelfLoop() { boolean isSelfLoop = false; Place[] curPreset = curTran.getPreset(); Place[] curPostset = curTran.getPostset(); for (Place preset : curPreset) { for (Place postset : curPostset) { if (preset == postset) { isSelfLoop = true; break; } } if (isSelfLoop) break; } return isSelfLoop; } /** * Construct a set of transitions that can make the enabling condition of curTran true, by firing their assignments. * @param lpnIndex */ public void buildEnableSet() { for (Integer lpnIndex : allTransitions.keySet()) { Transition[] allTransInOneLpn = allTransitions.get(lpnIndex); for (int i = 0; i < allTransInOneLpn.length; i++) { if (curTran.equals(allTransInOneLpn[i])) continue; Transition anotherTran = allTransInOneLpn[i]; ExprTree curTranEnablingTree = curTran.getEnablingTree(); if (curTranEnablingTree != null && (curTranEnablingTree.getChange(anotherTran.getAssignments())=='T' || curTranEnablingTree.getChange(anotherTran.getAssignments())=='t' || curTranEnablingTree.getChange(anotherTran.getAssignments())=='X')) { enableSet.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); } } } } public void buildModifyAssignSet() { // modifyAssignment contains transitions (T) that satisfy at least one of the conditions below: for every t in T, // (1) intersection(VA(curTran), supportA(t)) != empty // (2) intersection(VA(t), supportA(curTran)) != empty // (3) intersection(VA(t), VA(curTran) != empty // VA(t) : set of variables being assigned in transition t. // supportA(t): set of variables appearing in the expressions assigned to the variables of t (r.h.s of the assignment). for (Integer lpnIndex : allTransitions.keySet()) { Transition[] allTransInOneLpn = allTransitions.get(lpnIndex); for (int i = 0; i < allTransInOneLpn.length; i++) { if (curTran.equals(allTransInOneLpn[i])) continue; Transition anotherTran = allTransInOneLpn[i]; for (String v : curTran.getAssignTrees().keySet()) { for (ExprTree anotherTranAssignTree : anotherTran.getAssignTrees().values()) { if (anotherTranAssignTree != null && anotherTranAssignTree.containsVar(v)) { modifyAssignment.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); } } } for (ExprTree exprTree : curTran.getAssignTrees().values()) { for (String v : anotherTran.getAssignTrees().keySet()) { if (exprTree != null && exprTree.containsVar(v)) { modifyAssignment.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); } } } for (String v1 : curTran.getAssignTrees().keySet()) { for (String v2 : anotherTran.getAssignTrees().keySet()) { if (v1.equals(v2)) { modifyAssignment.add(new LpnTransitionPair(lpnIndex, anotherTran.getIndex())); } } } } } } public HashSet<LpnTransitionPair> getModifyAssignSet() { return modifyAssignment; } public HashSet<LpnTransitionPair> getDisableSet() { return disableSet; } public HashSet<LpnTransitionPair> getOtherTransDisableCurTranSet() { return otherTranDisableCurTranFailEnablingCond; } public HashSet<LpnTransitionPair> getDisableByStealingToken() { return disableByStealingToken; } public HashSet<LpnTransitionPair> getEnable() { return enableSet; } public Transition getTran() { return curTran; } // private void printIntegerSet(HashSet<Integer> integerSet, String setName) { // if (!setName.isEmpty()) // System.out.print(setName + ": "); // if (integerSet == null) { // System.out.println("null"); // else if (integerSet.isEmpty()) { // System.out.println("empty"); // else { // for (Iterator<Integer> curTranDisableIter = integerSet.iterator(); curTranDisableIter.hasNext();) { // Integer tranInDisable = curTranDisableIter.next(); // System.out.print(lpn.getAllTransitions()[tranInDisable] + " "); // System.out.print("\n"); }
package org.apache.jmeter.util; import java.awt.Dimension; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Collection; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Locale; import java.util.MissingResourceException; import java.util.Properties; import java.util.Random; import java.util.ResourceBundle; import java.util.StringTokenizer; import java.util.Vector; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JOptionPane; import javax.xml.parsers.SAXParserFactory; import org.apache.jmeter.gui.GuiPackage; import org.apache.jorphan.logging.LoggingManager; import org.apache.jorphan.test.UnitTestManager; import org.apache.log.Logger; import org.apache.oro.text.PatternCacheLRU; import org.apache.oro.text.regex.Perl5Compiler; import org.apache.oro.text.regex.Perl5Matcher; import org.xml.sax.XMLReader; /** * This class contains the static utility methods used by JMeter. * *@author <a href="mailto://stefano@apache.org">Stefano Mazzocchi</a> *Created June 28, 2001 *@version $Revision$ $Date$ */ public class JMeterUtils implements UnitTestManager { private static PatternCacheLRU patternCache = new PatternCacheLRU(1000, new Perl5Compiler()); transient private static Logger log = LoggingManager.getLoggerForClass(); private static final SAXParserFactory xmlFactory; static { SAXParserFactory temp = null; try { temp = SAXParserFactory.newInstance(); } catch (Exception e) { log.error("", e); temp = null; } xmlFactory = temp; } private static Properties appProperties; private static Collection localeChangeListeners = new HashSet(); private static Locale locale; private static ResourceBundle resources; private static ThreadLocal localMatcher = new ThreadLocal() { protected Object initialValue() { return new Perl5Matcher(); } }; //Provide Random numbers to whomever wants one private static Random rand = new Random(); /** * Gets Perl5Matcher for this thread. */ public static Perl5Matcher getMatcher() { return (Perl5Matcher) localMatcher.get(); } /** * This method is used by the init method to load the property file that * may even reside in the user space, or in the classpath under * org.apache.jmeter.jmeter.properties. * *@param file the file to load *@return the Properties from the file */ public static Properties getProperties(String file) { Properties p = new Properties(System.getProperties()); try { File f = new File(file); p.load(new FileInputStream(f)); } catch (Exception e) { try { InputStream is = ClassLoader.getSystemResourceAsStream( "org/apache/jmeter/jmeter.properties"); if (is == null) throw new RuntimeException("Could not read JMeter properties file"); p.load(is); } catch (IOException ex) { // JMeter.fail("Could not read internal resource. " + // "Archive is broken."); } } appProperties = p; LoggingManager.initializeLogging(appProperties); log = LoggingManager.getLoggerForClass(); String loc = appProperties.getProperty("language"); if (loc != null) { setLocale(new Locale(loc, "")); } else { setLocale(Locale.getDefault()); } return p; } public static PatternCacheLRU getPatternCache() { return patternCache; } public void initializeProperties(String file) { System.out.println("Initializing Properties: " + file); getProperties(file); String home; int pathend=file.lastIndexOf("/"); if (pathend == -1){// No path separator found, must be in current directory home = "."; } else { home = file.substring(0, pathend); } home = new File(home + "/..").getAbsolutePath(); System.out.println("Setting JMeter home: " + home); setJMeterHome(home); } public static String[] getSearchPaths() { String p= JMeterUtils.getPropDefault("search_paths", null); String[] result= new String[1]; if (p!=null) { String[] paths= p.split(";"); result= new String[paths.length+1]; for (int i=1; i<result.length; i++) { result[i]= paths[i-1]; } } result[0]= getJMeterHome() + "/lib/ext"; return result; } /** * Provide random numbers * @param r - the upper bound (exclusive) */ public static int getRandomInt(int r) { return rand.nextInt(r); } /** * Changes the current locale: re-reads resource strings and notifies * listeners. * * author Oliver Rossmueller * @param loc - new locale */ public static void setLocale(Locale loc) { locale = loc; resources = ResourceBundle.getBundle( "org.apache.jmeter.resources.messages", locale); notifyLocaleChangeListeners(); } /** * Gets the current locale. * * author Oliver Rossmueller * @return current locale */ public static Locale getLocale() { return locale; } /** * author Oliver Rossmueller */ public static void addLocaleChangeListener(LocaleChangeListener listener) { localeChangeListeners.add(listener); } /** * author Oliver Rossmueller */ public static void removeLocaleChangeListener(LocaleChangeListener listener) { localeChangeListeners.remove(listener); } /** * Notify all listeners interested in locale changes. * * author Oliver Rossmueller */ private static void notifyLocaleChangeListeners() { LocaleChangeEvent event = new LocaleChangeEvent(JMeterUtils.class, locale); Iterator iterator = localeChangeListeners.iterator(); while (iterator.hasNext()) { LocaleChangeListener listener = (LocaleChangeListener) iterator.next(); listener.localeChanged(event); } } /** * Gets the resource string for this key. * * If the resource is not found, a warning is logged * * @param key the key in the resource file * @return the resource string if the key is found; otherwise, return * "[res_key="+key+"]" */ public static String getResString(String key) { return getResStringDefault(key,"[res_key="+key+"]"); } /** * Gets the resource string for this key. * * If the resource is not found, a warning is logged * * @param key the key in the resource file * @param defaultValue - the default value * * @return the resource string if the key is found; * otherwise, return the default * @deprecated Only intended for use in development; use getResString(String) normally */ public static String getResString(String key, String defaultValue) { return getResStringDefault(key,defaultValue); } /* * Helper method to do the actual work of fetching resources; * allows getResString(S,S) to be deprecated without affecting getResString(S); */ private static String getResStringDefault(String key, String defaultValue) { if (key == null) { return null; } key = key.replace(' ', '_'); key = key.toLowerCase(); String resString = null; try { resString = resources.getString(key); } catch (MissingResourceException mre) { log.warn("ERROR! Resource string not found: [" + key + "]"); resString = defaultValue; } return resString; } /** * This gets the currently defined appProperties. It can only be called * after the {@link #getProperties(String)} method is called. * * @return The JMeterProperties value */ public static Properties getJMeterProperties() { return appProperties; } /** * This looks for the requested image in the classpath under * org.apache.jmeter.images. <name> * * @param name Description of Parameter * @return The Image value */ public static ImageIcon getImage(String name) { try { return new ImageIcon( JMeterUtils.class.getClassLoader().getResource( "org/apache/jmeter/images/" + name.trim())); } catch (NullPointerException e) { log.warn("no icon for " + name); return null; } } public static String getResourceFileAsText(String name) { try { String lineEnd = System.getProperty("line.separator"); BufferedReader fileReader = new BufferedReader( new InputStreamReader( JMeterUtils.class.getClassLoader().getResourceAsStream( name))); StringBuffer text = new StringBuffer(); String line = "NOTNULL"; while (line != null) { line = fileReader.readLine(); if (line != null) { text.append(line); text.append(lineEnd); } } return text.toString(); } catch (NullPointerException e) // Cannot find file { return ""; } catch (IOException e) { return ""; } } /** * Creates the vector of Timers plugins. * *@param properties Description of Parameter *@return The Timers value */ public static Vector getTimers(Properties properties) { return instantiate( getVector(properties, "timer."), "org.apache.jmeter.timers.Timer"); } /** * Creates the vector of visualizer plugins. * *@param properties Description of Parameter *@return The Visualizers value */ public static Vector getVisualizers(Properties properties) { return instantiate( getVector(properties, "visualizer."), "org.apache.jmeter.visualizers.Visualizer"); } /** * Creates a vector of SampleController plugins. * *@param properties The properties with information about the samplers *@return The Controllers value */ //TODO - does not appear to be called directly public static Vector getControllers(Properties properties) { String name = "controller."; Vector v = new Vector(); Enumeration names = properties.keys(); while (names.hasMoreElements()) { String prop = (String) names.nextElement(); if (prop.startsWith(name)) { Object o = instantiate( properties.getProperty(prop), "org.apache.jmeter.control.SamplerController"); v.addElement(o); } } return v; } /** * Create a string of class names for a particular SamplerController * *@param properties The properties with info about the samples. *@param name The name of the sampler controller. *@return The TestSamples value */ public static String[] getTestSamples(Properties properties, String name) { return (String[]) getVector(properties, name + ".testsample").toArray( new String[0]); } /** * Create an instance of an org.xml.sax.Parser * * @deprecated use the plain version instead. We are using JAXP! *@param properties The properties file containing the parser's class name *@return The XMLParser value */ public static XMLReader getXMLParser(Properties properties) { return getXMLParser(); } /** * Create an instance of an org.xml.sax.Parser based on the default props. * *@return The XMLParser value */ public static XMLReader getXMLParser() { XMLReader reader = null; try { reader = (XMLReader) instantiate(getPropDefault("xml.parser", "org.apache.xerces.parsers.SAXParser"), "org.xml.sax.XMLReader"); //reader = xmlFactory.newSAXParser().getXMLReader(); } catch (Exception e) { reader = (XMLReader) instantiate(getPropDefault("xml.parser", "org.apache.xerces.parsers.SAXParser"), "org.xml.sax.XMLReader"); } return reader; } /** * Creates the vector of alias strings. * *@param properties Description of Parameter *@return The Alias value */ public static Hashtable getAlias(Properties properties) { return getHashtable(properties, "alias."); } /** * Creates a vector of strings for all the properties that start with a * common prefix. * * @param properties Description of Parameter * @param name Description of Parameter * @return The Vector value */ public static Vector getVector(Properties properties, String name) { Vector v = new Vector(); Enumeration names = properties.keys(); while (names.hasMoreElements()) { String prop = (String) names.nextElement(); if (prop.startsWith(name)) { v.addElement(properties.getProperty(prop)); } } return v; } /** * Creates a table of strings for all the properties that start with a * common prefix. * * @param properties Description of Parameter * @param name Description of Parameter * @return The Hashtable value */ public static Hashtable getHashtable(Properties properties, String name) { Hashtable t = new Hashtable(); Enumeration names = properties.keys(); while (names.hasMoreElements()) { String prop = (String) names.nextElement(); if (prop.startsWith(name)) { t.put( prop.substring(name.length()), properties.getProperty(prop)); } } return t; } /** * Get a int value with default if not present. * *@param propName the name of the property. *@param defaultVal the default value. *@return The PropDefault value */ public static int getPropDefault(String propName, int defaultVal) { int ans; try { ans = (Integer .valueOf( appProperties .getProperty(propName, Integer.toString(defaultVal)) .trim())) .intValue(); } catch (Exception e) { ans = defaultVal; } return ans; } /** * Get a boolean value with default if not present. * *@param propName the name of the property. *@param defaultVal the default value. *@return The PropDefault value */ public static boolean getPropDefault(String propName, boolean defaultVal) { boolean ans; try { String strVal = appProperties .getProperty(propName, (Boolean.valueOf(defaultVal)).toString()) .trim(); if (strVal.equalsIgnoreCase("true") || strVal.equalsIgnoreCase("t")) { ans = true; } else if ( strVal.equalsIgnoreCase("false") || strVal.equalsIgnoreCase("f")) { ans = false; } else { ans = ((Integer.valueOf(strVal)).intValue() == 1); } } catch (Exception e) { ans = defaultVal; } return ans; } /** * Get a long value with default if not present. * *@param propName the name of the property. *@param defaultVal the default value. *@return The PropDefault value */ public static long getPropDefault(String propName, long defaultVal) { long ans; try { ans = (Long .valueOf( appProperties .getProperty(propName, Long.toString(defaultVal)) .trim())) .longValue(); } catch (Exception e) { ans = defaultVal; } return ans; } /** * Get a String value with default if not present. * *@param propName the name of the property. *@param defaultVal the default value. *@return The PropDefault value */ public static String getPropDefault(String propName, String defaultVal) { String ans; try { ans = appProperties.getProperty(propName, defaultVal).trim(); } catch (Exception e) { ans = defaultVal; } return ans; } /** * Sets the selection of the JComboBox to the Object 'name' from the list * in namVec. */ public static void selJComboBoxItem( Properties properties, JComboBox combo, Vector namVec, String name) { int idx = namVec.indexOf(name); combo.setSelectedIndex(idx); // Redisplay. combo.updateUI(); return; } /** * Instatiate an object and guarantee its class. * *@param className The name of the class to instantiate. *@param impls The name of the class it subclases. *@return Description of the Returned Value */ public static Object instantiate(String className, String impls) { if (className != null) { className.trim();//TODO does nothing - presumably should be s=className.trim() } if (impls != null) { // FIXME: Shouldn't this be impls.trim()? className.trim();//TODO does nothing!! } try { Class c = Class.forName(impls); try { Class o = Class.forName(className); Object res = o.newInstance(); if (c.isInstance(res)) { return res; } else { throw new IllegalArgumentException( className + " is not an instance of " + impls); } } catch (ClassNotFoundException e) { log.error( "Error loading class " + className + ": class is not found"); } catch (IllegalAccessException e) { log.error( "Error loading class " + className + ": does not have access"); } catch (InstantiationException e) { log.error( "Error loading class " + className + ": could not instantiate"); } catch (NoClassDefFoundError e) { log.error( "Error loading class " + className + ": couldn't find class " + e.getMessage()); } } catch (ClassNotFoundException e) { log.error("Error loading class " + impls + ": was not found."); } return null; } /** * Instantiate a vector of classes * *@param v Description of Parameter *@param className Description of Parameter *@return Description of the Returned Value */ public static Vector instantiate(Vector v, String className) { Vector i = new Vector(); try { Class c = Class.forName(className); Enumeration elements = v.elements(); while (elements.hasMoreElements()) { String name = (String) elements.nextElement(); try { Object o = Class.forName(name).newInstance(); if (c.isInstance(o)) { i.addElement(o); } } catch (ClassNotFoundException e) { log.error( "Error loading class " + name + ": class is not found"); } catch (IllegalAccessException e) { log.error( "Error loading class " + name + ": does not have access"); } catch (InstantiationException e) { log.error( "Error loading class " + name + ": could not instantiate"); } catch (NoClassDefFoundError e) { log.error( "Error loading class " + name + ": couldn't find class " + e.getMessage()); } } } catch (ClassNotFoundException e) { log.error( "Error loading class " + className + ": class is not found"); } return i; } /** * Tokenize a string into a vector of tokens * *@param string Description of Parameter *@param separator Description of Parameter *@return Description of the Returned Value */ public static Vector tokenize(String string, String separator) { Vector v = new Vector(); StringTokenizer s = new StringTokenizer(string, separator); while (s.hasMoreTokens()) { v.addElement(s.nextToken()); } return v; } /** * Create a button with the netscape style * *@param name Description of Parameter *@param listener Description of Parameter *@return Description of the Returned Value */ public static JButton createButton(String name, ActionListener listener) { JButton button = new JButton(getImage(name + ".on.gif")); button.setDisabledIcon(getImage(name + ".off.gif")); button.setRolloverIcon(getImage(name + ".over.gif")); button.setPressedIcon(getImage(name + ".down.gif")); button.setActionCommand(name); button.addActionListener(listener); button.setRolloverEnabled(true); button.setFocusPainted(false); button.setBorderPainted(false); button.setOpaque(false); button.setPreferredSize(new Dimension(24, 24)); return button; } /** * Create a button with the netscape style * *@param name Description of Parameter *@param listener Description of Parameter *@return Description of the Returned Value */ public static JButton createSimpleButton( String name, ActionListener listener) { JButton button = new JButton(getImage(name + ".gif")); button.setActionCommand(name); button.addActionListener(listener); button.setFocusPainted(false); button.setBorderPainted(false); button.setOpaque(false); button.setPreferredSize(new Dimension(25, 25)); return button; } /** * Takes a String and a tokenizer character, and returns a new array of * strings of the string split by the tokenizer character. * * @param splittee String to be split * @param splitChar Character to split the string on * @param def Default value to place between two split chars that * have nothing between them * @return Array of all the tokens. */ public static String[] split(String splittee, String splitChar, String def) { if (splittee == null || splitChar == null) { return new String[0]; } int spot; while ((spot = splittee.indexOf(splitChar + splitChar)) != -1) { splittee = splittee.substring(0, spot + splitChar.length()) + def + splittee.substring( spot + 1 * splitChar.length(), splittee.length()); } Vector returns = new Vector(); int start = 0; int length = splittee.length(); spot = 0; while (start < length && (spot = splittee.indexOf(splitChar, start)) > -1) { if (spot > 0) { returns.addElement(splittee.substring(start, spot)); } start = spot + splitChar.length(); } if (start < length) { returns.add(splittee.substring(start)); } String[] values = new String[returns.size()]; returns.copyInto(values); return values; } /** * Report an error through a dialog box. * *@param errorMsg the error message. */ public static void reportErrorToUser(String errorMsg) { if (errorMsg == null) { errorMsg = "Unknown error - see log file"; log.warn("Unknown error", new Throwable("errorMsg == null")); } JOptionPane.showMessageDialog( GuiPackage.getInstance().getMainFrame(), errorMsg, "Error", JOptionPane.ERROR_MESSAGE); } /** * Finds a string in an array of strings and returns the * *@param array Array of strings. *@param value String to compare to array values. *@return Index of value in array, or -1 if not in array. */ public static int findInArray(String[] array, String value) { int count = -1; int index = -1; if (array != null && value != null) { while (++count < array.length) { if (array[count] != null && array[count].equals(value)) { index = count; break; } } } return index; } /** * Takes an array of strings and a tokenizer character, and returns a * string of all the strings concatenated with the tokenizer string in * between each one. * * @param splittee Array of Objects to be concatenated. * @param splitChar Object to unsplit the strings with. * @return Array of all the tokens. */ public static String unsplit(Object[] splittee, Object splitChar) { StringBuffer retVal = new StringBuffer(""); int count = -1; while (++count < splittee.length) { if (splittee[count] != null) { retVal.append(splittee[count]); } if (count + 1 < splittee.length && splittee[count + 1] != null) { retVal.append(splitChar); } } return retVal.toString(); } // End Method /** * Takes an array of strings and a tokenizer character, and returns a * string of all the strings concatenated with the tokenizer string in * between each one. * * @param splittee Array of Objects to be concatenated. * @param splitChar Object to unsplit the strings with. * @param def Default value to replace null values in array. * @return Array of all the tokens. */ public static String unsplit( Object[] splittee, Object splitChar, String def) { StringBuffer retVal = new StringBuffer(""); int count = -1; while (++count < splittee.length) { if (splittee[count] != null) { retVal.append(splittee[count]); } else { retVal.append(def); } if (count + 1 < splittee.length) { retVal.append(splitChar); } } return retVal.toString(); } // End Method public static String getJMeterHome() { return jmDir; } public static void setJMeterHome(String home) { jmDir = home; } private static String jmDir; public static final String JMETER = "jmeter"; public static final String ENGINE = "jmeter.engine"; public static final String ELEMENTS = "jmeter.elements"; public static final String GUI = "jmeter.gui"; public static final String UTIL = "jmeter.util"; public static final String CLASSFINDER = "jmeter.util.classfinder"; public static final String TEST = "jmeter.test"; public static final String HTTP = "jmeter.protocol.http"; public static final String JDBC = "jmeter.protocol.jdbc"; public static final String FTP = "jmeter.protocol.ftp"; public static final String JAVA = "jmeter.protocol.java"; public static final String PROPERTIES = "jmeter.elements.properties"; /** * Gets the JMeter Version. * @return the JMeter version string */ public static String getJMeterVersion() { return JMeterVersion.VERSION; } }
// HSSource //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: //all copies or substantial portions of the Software. //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //THE SOFTWARE. package com.tenmiles.helpstack.logic; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Build; import android.text.Html; import android.text.SpannableString; import android.util.Log; import com.android.volley.RequestQueue; import com.android.volley.Response.ErrorListener; import com.android.volley.VolleyError; import com.google.gson.Gson; import com.tenmiles.helpstack.HSHelpStack; import com.tenmiles.helpstack.activities.HSActivityManager; import com.tenmiles.helpstack.fragments.HSFragmentParent; import com.tenmiles.helpstack.model.HSAttachment; import com.tenmiles.helpstack.model.HSDraft; import com.tenmiles.helpstack.model.HSCachedTicket; import com.tenmiles.helpstack.model.HSCachedUser; import com.tenmiles.helpstack.model.HSKBItem; import com.tenmiles.helpstack.model.HSTicket; import com.tenmiles.helpstack.model.HSTicketUpdate; import com.tenmiles.helpstack.model.HSUploadAttachment; import com.tenmiles.helpstack.model.HSUser; import org.xmlpull.v1.XmlPullParserException; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.Calendar; public class HSSource { private static final String TAG = HSSource.class.getSimpleName(); private static final String HELPSTACK_DIRECTORY = "helpstack"; private static final String HELPSTACK_TICKETS_FILE_NAME = "tickets"; private static final String HELPSTACK_TICKETS_USER_DATA = "user_credential"; private static final String HELPSTACK_DRAFT = "draft"; private static HSSource singletonInstance = null; /** * * @param context * @return singleton instance of this class. */ public static HSSource getInstance(Context context) { if (singletonInstance == null) { synchronized (HSSource.class) { if (singletonInstance == null) { Log.d(TAG, "New Instance"); singletonInstance = new HSSource( context.getApplicationContext()); } } } // As this singleton can be called even before gear is set, refreshing it singletonInstance.setGear(HSHelpStack.getInstance(context).getGear()); return singletonInstance; } private HSGear gear; private Context mContext; private RequestQueue mRequestQueue; private HSCachedTicket cachedTicket; private HSCachedUser cachedUser; private HSDraft draftObject; private HSSource(Context context) { this.mContext = context; setGear(HSHelpStack.getInstance(context).getGear()); mRequestQueue = HSHelpStack.getInstance(context).getRequestQueue(); refreshFieldsFromCache(); } public void requestKBArticle(String cancelTag, HSKBItem section, OnFetchedArraySuccessListener success, ErrorListener errorListener ) { if (gear.haveImplementedKBFetching()) { gear.fetchKBArticle(cancelTag, section,mRequestQueue, new SuccessWrapper(success) { @Override public void onSuccess(Object[] successObject) { assert successObject != null : "It seems requestKBArticle was not implemented in gear" ; // Do your work here, may be caching, data validation etc. super.onSuccess(successObject); } }, new ErrorWrapper("Fetching KB articles", errorListener)); } else { try { HSArticleReader reader = new HSArticleReader(gear.getLocalArticleResourceId()); success.onSuccess(reader.readArticlesFromResource(mContext)); } catch (XmlPullParserException e) { e.printStackTrace(); throwError(errorListener, "Unable to parse local article XML"); } catch (IOException e) { e.printStackTrace(); throwError(errorListener, "Unable to read local article XML"); } } } public void requestAllTickets(OnFetchedArraySuccessListener success, ErrorListener error ) { if (cachedTicket == null) { success.onSuccess(new HSTicket[0]); } else { success.onSuccess(cachedTicket.getTickets()); } } public void checkForUserDetailsValidity(String cancelTag, String firstName, String lastName, String email,OnFetchedSuccessListener success, ErrorListener errorListener) { gear.registerNewUser(cancelTag, firstName, lastName, email, mRequestQueue, success, new ErrorWrapper("Registering New User", errorListener)); } public void createNewTicket(String cancelTag, HSUser user, String subject, String message, HSAttachment[] attachment, OnNewTicketFetchedSuccessListener successListener, ErrorListener errorListener) { HSUploadAttachment[] upload_attachments = convertAttachmentArrayToUploadAttachment(attachment); message = message + getDeviceInformation(mContext); if (gear.canUplaodMessageAsHtmlString()) { message = Html.toHtml(new SpannableString(message)); } gear.createNewTicket(cancelTag, user, subject, message, upload_attachments, mRequestQueue, new NewTicketSuccessWrapper(successListener) { @Override public void onSuccess(HSUser udpatedUserDetail, HSTicket ticket) { // Save ticket and user details in cache // Save properties also later. doSaveNewTicketPropertiesForGearInCache(ticket); doSaveNewUserPropertiesForGearInCache(udpatedUserDetail); super.onSuccess(udpatedUserDetail, ticket); } }, new ErrorWrapper("Creating New Ticket", errorListener)); } public void requestAllUpdatesOnTicket(String cancelTag, HSTicket ticket, OnFetchedArraySuccessListener success, ErrorListener errorListener ) { gear.fetchAllUpdateOnTicket(cancelTag, ticket, cachedUser.getUser(), mRequestQueue, success, new ErrorWrapper("Fetching updates on Ticket", errorListener)); } public void addReplyOnATicket(String cancelTag, String message, HSAttachment[] attachments, HSTicket ticket, OnFetchedSuccessListener success, ErrorListener errorListener) { if (gear.canUplaodMessageAsHtmlString()) { message = Html.toHtml(new SpannableString(message)); } gear.addReplyOnATicket(cancelTag, message, convertAttachmentArrayToUploadAttachment(attachments), ticket, getUser(), mRequestQueue, new OnFetchedSuccessListenerWrapper(success, message, attachments) { @Override public void onSuccess(Object successObject) { if (gear.canIgnoreTicketUpdateInformationAfterAddingReply()) { HSTicketUpdate update = HSTicketUpdate.createUpdateByUser(null, null, this.message, Calendar.getInstance().getTime(), this.attachments); super.onSuccess(update); } else { super.onSuccess(successObject); } } }, new ErrorWrapper("Adding reply to a ticket", errorListener)); } public HSGear getGear() { return gear; } private void setGear(HSGear gear) { this.gear = gear; } public boolean isNewUser() { return cachedUser.getUser() == null; } public void refreshUser() { doReadUserFromCache(); } public HSUser getUser() { return cachedUser.getUser(); } public String getDraftSubject() { if(draftObject != null) { return draftObject.getSubject(); } return null; } public String getDraftMessage() { if(draftObject != null) { return draftObject.getMessage(); } return null; } public HSUser getDraftUser() { if(draftObject != null) { return draftObject.getDraftUser(); } return null; } public HSAttachment[] getDraftAttachments() { if(draftObject != null) { return draftObject.getAttachments(); } return null; } public String getDraftReplyMessage() { if(draftObject != null) { return draftObject.getDraftReplyMessage(); } return null; } public HSAttachment[] getDraftReplyAttachments() { if(draftObject != null) { return draftObject.getDraftReplyAttachments(); } return null; } public void saveTicketDetailsInDraft(String subject, String message, HSAttachment[] attachmentsArray) { doSaveTicketDraftForGearInCache(subject, message, attachmentsArray); } public void saveUserDetailsInDraft(HSUser user) { doSaveUserDraftForGearInCache(user); } public void saveReplyDetailsInDraft(String message, HSAttachment[] attachmentsArray) { doSaveReplyDraftForGearInCache(message, attachmentsArray); } public boolean haveImplementedTicketFetching() { return gear.haveImplementedTicketFetching(); } public String getSupportEmailAddress() { return gear.getCompanySupportEmailAddress(); } /*** * * Depending on the setting set on gear, it launches new ticket activity. * * if email : launches email [Done] * else: * if user logged in : launches user details [Done] * else: launches new ticket [Done] * * @param fragment * @param requestCode */ public void launchCreateNewTicketScreen(HSFragmentParent fragment, int requestCode) { if (haveImplementedTicketFetching()) { if(isNewUser()) { HSActivityManager.startNewIssueActivity(fragment, null, requestCode); }else { HSActivityManager.startNewIssueActivity(fragment, getUser(), requestCode); } } else { launchEmailAppWithEmailAddress(fragment.getActivity()); } } public void launchEmailAppWithEmailAddress(Activity activity) { Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); emailIntent.setType("plain/text"); emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ getSupportEmailAddress()}); emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, ""); emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, getDeviceInformation(activity)); activity.startActivity(Intent.createChooser(emailIntent, "Email")); } private static String getDeviceInformation(Context activity) { StringBuilder builder = new StringBuilder(); builder.append("\n\n\n"); builder.append("========"); builder.append("\nDevice Android version : "); builder.append(Build.VERSION.SDK_INT); builder.append("\nDevice brand : "); builder.append(Build.MODEL); builder.append("\nApplication package :"); try { builder.append(activity.getPackageManager().getPackageInfo(activity.getPackageName(),0).packageName); } catch (NameNotFoundException e) { builder.append("NA"); } builder.append("\nApplication version :"); try { builder.append(activity.getPackageManager().getPackageInfo(activity.getPackageName(),0).versionCode); } catch (NameNotFoundException e) { builder.append("NA"); } return builder.toString(); } public void cancelOperation(String cancelTag) { mRequestQueue.cancelAll(cancelTag); } //////// Utility Functions ///////////////// public void refreshFieldsFromCache() { // read the ticket data from cache and maintain here doReadTicketsFromCache(); doReadUserFromCache(); doReadDraftFromCache(); } /** * Opens a file and read its content. Return null if any error occured or file not found * @param file * @return */ private String readJsonFromFile(File file) { if (!file.exists()) { return null; } String json = null; FileInputStream inputStream; try { StringBuilder datax = new StringBuilder(); inputStream = new FileInputStream(file); InputStreamReader isr = new InputStreamReader ( inputStream ) ; BufferedReader buffreader = new BufferedReader ( isr ) ; String readString = buffreader.readLine ( ) ; while ( readString != null ) { datax.append(readString); readString = buffreader.readLine ( ) ; } isr.close ( ) ; json = datax.toString(); return json; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } private void writeJsonIntoFile (File file, String json) { FileOutputStream outputStream; try { outputStream = new FileOutputStream(file); outputStream.write(json.getBytes()); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } } protected void doSaveNewTicketPropertiesForGearInCache(HSTicket ticket) { cachedTicket.addTicketAtStart(ticket); Gson gson = new Gson(); String ticketsgson = gson.toJson(cachedTicket); File ticketFile = new File(getProjectDirectory(), HELPSTACK_TICKETS_FILE_NAME); writeJsonIntoFile(ticketFile, ticketsgson); } protected void doSaveNewUserPropertiesForGearInCache(HSUser user) { cachedUser.setUser(user); Gson gson = new Gson(); String userjson = gson.toJson(cachedUser); File userFile = new File(getProjectDirectory(), HELPSTACK_TICKETS_USER_DATA); writeJsonIntoFile(userFile, userjson); } protected void doReadTicketsFromCache() { File ticketFile = new File(getProjectDirectory(), HELPSTACK_TICKETS_FILE_NAME); String json = readJsonFromFile(ticketFile); if (json == null) { cachedTicket = new HSCachedTicket(); } else { Gson gson = new Gson(); cachedTicket = gson.fromJson(json, HSCachedTicket.class); } } protected void doReadUserFromCache() { File userFile = new File(getProjectDirectory(), HELPSTACK_TICKETS_USER_DATA); String json = readJsonFromFile(userFile); if (json == null) { cachedUser = new HSCachedUser(); } else { Gson gson = new Gson(); cachedUser = gson.fromJson(json, HSCachedUser.class); } } protected void doReadDraftFromCache() { File draftFile = new File(getProjectDirectory(), HELPSTACK_DRAFT); String json = readJsonFromFile(draftFile); if (json == null) { draftObject = new HSDraft(); } else { Gson gson = new Gson(); draftObject = gson.fromJson(json, HSDraft.class); } } protected void doSaveTicketDraftForGearInCache(String subject, String message, HSAttachment[] attachmentsArray) { draftObject.setDraftSubject(subject); draftObject.setDraftMessage(message); draftObject.setDraftAttachments(attachmentsArray); writeDraftIntoFile(); } protected void doSaveUserDraftForGearInCache(HSUser user) { draftObject.setDraftUSer(user); writeDraftIntoFile(); } protected void doSaveReplyDraftForGearInCache(String message, HSAttachment[] attachmentsArray) { draftObject.setDraftReplyMessage(message); draftObject.setDraftReplyAttachments(attachmentsArray); writeDraftIntoFile(); } private void writeDraftIntoFile() { Gson gson = new Gson(); String draftJson = gson.toJson(draftObject); File draftFile = new File(getProjectDirectory(), HELPSTACK_DRAFT); writeJsonIntoFile(draftFile, draftJson); } protected File getProjectDirectory() { File projDir = new File(mContext.getFilesDir(), HELPSTACK_DIRECTORY); if (!projDir.exists()) projDir.mkdirs(); return projDir; } public void clearTicketDraft() { saveTicketDetailsInDraft("", "", null); } public void clearReplyDraft() { saveReplyDetailsInDraft("", null); } private class NewTicketSuccessWrapper implements OnNewTicketFetchedSuccessListener { private OnNewTicketFetchedSuccessListener lastListner; public NewTicketSuccessWrapper(OnNewTicketFetchedSuccessListener lastListner) { this.lastListner = lastListner; } @Override public void onSuccess(HSUser udpatedUserDetail, HSTicket ticket) { if (lastListner != null) lastListner.onSuccess(udpatedUserDetail, ticket); } } protected HSUploadAttachment[] convertAttachmentArrayToUploadAttachment(HSAttachment[] attachment) { HSUploadAttachment[] upload_attachments = new HSUploadAttachment[0]; if (attachment != null && attachment.length > 0) { int attachmentCount = gear.getNumberOfAttachmentGearCanHandle(); assert attachmentCount >= attachment.length : "Gear cannot handle more than "+attachmentCount+" attachmnets"; upload_attachments = new HSUploadAttachment[attachment.length]; for (int i = 0; i < upload_attachments.length; i++) { upload_attachments[i] = new HSUploadAttachment(mContext, attachment[i]); } } return upload_attachments; } private class SuccessWrapper implements OnFetchedArraySuccessListener { private OnFetchedArraySuccessListener lastListner; public SuccessWrapper(OnFetchedArraySuccessListener lastListner) { this.lastListner = lastListner; } @Override public void onSuccess(Object[] successObject) { if (lastListner != null) lastListner.onSuccess(successObject); } } private class OnFetchedSuccessListenerWrapper implements OnFetchedSuccessListener { private OnFetchedSuccessListener listener; protected String message; protected HSAttachment[] attachments; private OnFetchedSuccessListenerWrapper(OnFetchedSuccessListener listener, String message, HSAttachment[] attachments) { this.listener = listener; this.message = message; this.attachments = attachments; } @Override public void onSuccess(Object successObject) { if (this.listener != null) { this.listener.onSuccess(successObject); } } } private class ErrorWrapper implements ErrorListener { private ErrorListener errorListener; private String methodName; public ErrorWrapper(String methodName, ErrorListener errorListener) { this.errorListener = errorListener; this.methodName = methodName; } @Override public void onErrorResponse(VolleyError error) { printErrorDescription(methodName, error); this.errorListener.onErrorResponse(error); } } public static void throwError(ErrorListener errorListener, String error) { VolleyError volleyError = new VolleyError(error); printErrorDescription(null, volleyError); errorListener.onErrorResponse(volleyError); } private static void printErrorDescription (String methodName, VolleyError error) { if (methodName == null) { Log.e(HSHelpStack.LOG_TAG, "Error occurred in HelpStack"); } else { Log.e(HSHelpStack.LOG_TAG, "Error occurred when executing " + methodName); } Log.e(HSHelpStack.LOG_TAG, error.toString()); if (error.getMessage() != null) { Log.e(HSHelpStack.LOG_TAG, error.getMessage()); } if (error.networkResponse != null && error.networkResponse.data != null) { try { Log.e(HSHelpStack.LOG_TAG, new String(error.networkResponse.data, "utf-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } error.printStackTrace(); } }
package lombok.ast.grammar; import static org.junit.Assert.assertEquals; import java.util.List; import lombok.ast.BinaryExpression; import lombok.ast.BinaryOperator; import lombok.ast.Block; import lombok.ast.CharLiteral; import lombok.ast.Comment; import lombok.ast.EmptyDeclaration; import lombok.ast.For; import lombok.ast.ForwardingAstVisitor; import lombok.ast.Node; import lombok.ast.Position; import lombok.ast.StringLiteral; import lombok.ast.TypeBody; import lombok.ast.TypeReference; import lombok.ast.VariableDeclaration; import lombok.ast.VariableDefinition; import lombok.ast.VariableDefinitionEntry; import lombok.ast.ecj.EcjTreeConverter; import lombok.ast.printer.SourcePrinter; import lombok.ast.printer.StructureFormatter; import org.eclipse.jdt.internal.compiler.CompilationResult; import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.batch.CompilationUnit; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.eclipse.jdt.internal.compiler.parser.Parser; import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; import org.eclipse.jdt.internal.compiler.problem.ProblemReporter; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(RunForEachFileInDirRunner.class) public class EcjToLombokTest extends TreeBuilderRunner<Node> { public EcjToLombokTest() { super(false); } @Test public boolean testEcjTreeConverter(Source source) throws Exception { return testCompiler(source); } protected CompilerOptions ecjCompilerOptions() { CompilerOptions options = new CompilerOptions(); options.complianceLevel = ClassFileConstants.JDK1_6; options.sourceLevel = ClassFileConstants.JDK1_6; options.targetJDK = ClassFileConstants.JDK1_6; options.parseLiteralExpressionsAsConstants = true; return options; } protected String convertToString(Source source, Node tree) { deleteEmptyDeclarations(tree); foldStringConcats(tree); splitVariableDefinitionEntries(tree); simplifyArrayDecls(tree); deleteComments(tree); StructureFormatter formatter = StructureFormatter.formatterWithoutPositions(); formatter.skipProperty(CharLiteral.class, "value"); formatter.skipProperty(StringLiteral.class, "value"); tree.accept(new SourcePrinter(formatter)); return formatter.finish(); } private static void deleteComments(Node tree) { tree.accept(new ForwardingAstVisitor() { @Override public boolean visitComment(Comment node) { node.unparent(); return false; } }); } private void splitVariableDefinitionEntries(Node node) { node.accept(new ForwardingAstVisitor() { @Override public boolean visitVariableDefinition(VariableDefinition node) { if (node.astVariables().size() == 1) { return true; } Node parent = node.getParent(); if (!(parent instanceof VariableDeclaration || parent instanceof For)) { return true; } if (parent instanceof VariableDeclaration) { splitVariableDeclaration((VariableDeclaration)parent); } if (parent instanceof For) { splitFor((For)parent, node); } return true; } private void splitVariableDeclaration(VariableDeclaration varDecl) { VariableDefinition varDef = varDecl.astDefinition(); Node upFromDecl = varDecl.getParent(); if (!(upFromDecl instanceof Block || upFromDecl instanceof TypeBody)) { return; } for (VariableDefinitionEntry varDefEntry : varDef.astVariables()) { if (upFromDecl instanceof Block) { VariableDeclaration splitDecl = new VariableDeclaration().astDefinition(splitAndUnparentVariableDeclaration(varDef, varDefEntry)); ((Block)upFromDecl).astContents().addBefore(varDecl, splitDecl); } else if (upFromDecl instanceof TypeBody) { VariableDeclaration splitDecl = new VariableDeclaration().astDefinition(splitAndUnparentVariableDeclaration(varDef, varDefEntry)); ((TypeBody)upFromDecl).astMembers().addBefore(varDecl, splitDecl); } } varDecl.unparent(); } private void splitFor(For forStat, VariableDefinition varDef) { for (VariableDefinitionEntry varDefEntry : varDef.astVariables()) { VariableDefinition splitVarDef = splitAndUnparentVariableDeclaration(varDef, varDefEntry); /* * TODO: The way the convertor adds multiple varDefs in a * for is mimiced, though it does not seem to be a correct * AST. Verify this and rewrite both the convertor and * the normalizer */ forStat.rawExpressionInits().addToEnd(splitVarDef); } forStat.astVariableDeclaration().unparent(); } private VariableDefinition splitAndUnparentVariableDeclaration(VariableDefinition def, VariableDefinitionEntry varDefEntry) { varDefEntry.unparent(); VariableDefinition copy = def.copy(); copy.astVariables().clear(); copy.astVariables().addToEnd(varDefEntry); return copy; } }); } /* * Dependant on splitVariableDefinitionEntries(). */ private void simplifyArrayDecls(Node node) { node.accept(new ForwardingAstVisitor() { @Override public boolean visitVariableDefinition(VariableDefinition node) { VariableDefinitionEntry varDefEntry = node.astVariables().first(); int arrayDimensions = varDefEntry.astArrayDimensions(); if (arrayDimensions == 0) { return true; } varDefEntry.astArrayDimensions(0); TypeReference typeRef = node.astTypeReference(); typeRef.astArrayDimensions(typeRef.astArrayDimensions() + arrayDimensions); return true; } }); } private static void deleteEmptyDeclarations(Node node) { node.accept(new ForwardingAstVisitor() { @Override public boolean visitEmptyDeclaration(EmptyDeclaration node) { node.unparent(); return true; } }); } private static void foldStringConcats(Node tree) { tree.accept(new ForwardingAstVisitor() { @Override public boolean visitBinaryExpression(BinaryExpression node) { if (node.rawLeft() != null) node.rawLeft().accept(this); if (node.rawRight() != null) node.rawRight().accept(this); String left = null, right = null; if (node.astOperator() != BinaryOperator.PLUS || node.getParent() == null) return false; boolean leftIsChar = false; if (node.rawLeft() instanceof StringLiteral) left = ((StringLiteral) node.rawLeft()).astValue(); if (node.rawLeft() instanceof CharLiteral) { left = "" + ((CharLiteral) node.rawLeft()).astValue(); leftIsChar = true; } if (node.rawRight() instanceof StringLiteral) right = ((StringLiteral) node.rawRight()).astValue(); if (!leftIsChar && node.rawRight() instanceof CharLiteral) right = "" + ((CharLiteral) node.rawRight()).astValue(); if (left == null || right == null) return false; int start = node.rawLeft().getPosition().getStart(); int end = node.rawRight().getPosition().getEnd(); node.getParent().replaceChild(node, new StringLiteral().astValue(left + right).setPosition(new Position(start, end))); return false; } }); } protected Node parseWithLombok(Source source) { List<Node> nodes = source.getNodes(); assertEquals(1, nodes.size()); return nodes.get(0); } protected Node parseWithTargetCompiler(Source source) { CompilerOptions compilerOptions = ecjCompilerOptions(); Parser parser = new Parser(new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, new DefaultProblemFactory() ), compilerOptions.parseLiteralExpressionsAsConstants); parser.javadocParser.checkDocComment = true; CompilationUnit sourceUnit = new CompilationUnit(source.getRawInput().toCharArray(), source.getName(), "UTF-8"); CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, 0); CompilationUnitDeclaration cud = parser.parse(sourceUnit, compilationResult); if (cud.hasErrors()) return null; return EcjTreeConverter.convert(cud); } }
package org.broad.igv.ui; import com.google.common.eventbus.Subscribe; import org.broad.igv.feature.AminoAcidManager; import org.broad.igv.feature.genome.GenomeManager; import org.broad.igv.ui.action.SearchCommand; import org.broad.igv.ui.event.ViewChange; import org.broad.igv.ui.panel.FrameManager; import org.fest.swing.fixture.FrameFixture; import org.fest.swing.fixture.JComboBoxFixture; import org.fest.swing.fixture.JTextComponentFixture; import org.junit.*; import javax.swing.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class IGVCommandBarTest extends AbstractHeadedTest { private static FrameFixture frame; //We use asynchronous events, and there are asserts in there //Here we check that the events were actually dispatched and handled private int expectedEvents = 0; private int actualEvents = expectedEvents; /** * Because loading IGV takes so long, we only load it once per class. * We reset the session in between tests * * @throws Exception */ @BeforeClass public static void setUpClass() throws Exception { AbstractHeadedTest.setUpClass(); frame = new FrameFixture(IGV.getMainFrame()); //FrameFixture frame = new FrameFixture(IGV.getMainFrame()); //JPanelFixture contentFixture = frame.panel("contentPane"); //JPanelFixture commandBar = frame.panel("igvCommandBar"); //JComboBoxFixture chromoBox = frame.comboBox("chromosomeComboBox"); } @Before public void setUp() throws Exception{ super.setUp(); this.actualEvents = 0; this.expectedEvents = 0; } @After public void tearDown() throws Exception{ System.out.println("Expected Events: " + expectedEvents + " Actual Events: " + actualEvents); assertTrue("Event handler not triggered properly", actualEvents >= expectedEvents); super.tearDown(); } /** * Basic test showing usage of FEST and checking combo box */ @Test public void testChromoBoxContents() throws Exception { String[] chromos = frame.comboBox("chromosomeComboBox").contents(); assertEquals(26, chromos.length); } @Test public void testChromoNav() throws Exception { tstChromoNav("chr1"); tstChromoNav("chr20"); } //Tacky state variable, but eh, it's just a test private String enterText = null; private void tstChromoNav(String chromoText) throws Exception { registerEventHandler(2); JTextComponentFixture searchFixture = frame.textBox("searchTextField"); searchFixture.deleteText(); enterText = chromoText; //Make sure search box has focus searchFixture.focus(); searchFixture.requireFocused(); searchFixture.requireEmpty(); searchFixture.enterText(enterText); frame.button("goButton").click(); } private void registerEventHandler(int expectedEvents) { this.expectedEvents += expectedEvents; FrameManager.getDefaultFrame().getEventBus().register(this); } /** * This is a little funny, we are actually responding to a spurious ChromosomeChangeCause * sent when the dropdown changes * @param e */ @Subscribe public void receiveChromoChange(ViewChange.ChromosomeChangeCause e){ if(e.source instanceof JComboBox){ actualEvents++; JComboBoxFixture comboBox = frame.comboBox("chromosomeComboBox"); comboBox.requireSelection(enterText); }else if(e.source instanceof SearchCommand){ actualEvents++; assertEquals(enterText, e.chrName); }else{ actualEvents = Integer.MIN_VALUE; throw new AssertionError("Got a ChromosomeChangeCause event from unexpected source: " + e.source); } } @Test public void testChromoNav_CodonTable() throws Exception { //Make sure that translation table DOES NOT change when we change chromosomes Assume.assumeTrue("hg18".equals(GenomeManager.getInstance().getGenomeId())); tstChromoNav("chr1"); assertEquals(1, AminoAcidManager.getInstance().getCodonTable().getId()); tstChromoNav("chrM"); assertEquals(1, AminoAcidManager.getInstance().getCodonTable().getId()); } }
package de.measite.contactmerger; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map.Entry; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.core.KeywordAnalyzer; import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.LongField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.Term; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanClause.Occur; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.FuzzyQuery; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.SimpleFSDirectory; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.NumericUtils; import org.apache.lucene.util.Version; import android.content.ContentProviderClient; import android.content.Context; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Nickname; import android.provider.ContactsContract.CommonDataKinds.Note; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Photo; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.CommonDataKinds.Website; import android.util.Log; import de.measite.contactmerger.contacts.Contact; import de.measite.contactmerger.contacts.ContactDataMapper; import de.measite.contactmerger.contacts.ImMetadata; import de.measite.contactmerger.contacts.Metadata; import de.measite.contactmerger.contacts.RawContact; import de.measite.contactmerger.graph.GraphIO; import de.measite.contactmerger.graph.UndirectedGraph; import de.measite.contactmerger.ui.GraphConverter; import de.measite.contactmerger.ui.model.MergeContact; import de.measite.contactmerger.ui.model.ModelIO; public class AnalyzerThread extends Thread { protected static Thread runner; protected static float PHASE1 = 0.09f; protected static float PHASE2 = 0.9f; protected final static String LOGTAG = "contactmerger.AnalyzerThread"; protected final File path; protected Context context; protected PerFieldAnalyzerWrapper analyzer; protected Directory dir; protected ContactDataMapper mapper; protected ArrayList<ProgressListener> listeners = new ArrayList<ProgressListener>(2); private boolean stop = false; public AnalyzerThread(Context context) { super(); this.context = context; HashMap<String, Analyzer> fieldAnalyzers = new HashMap<String, Analyzer>(); fieldAnalyzers.put("id", new KeywordAnalyzer()); fieldAnalyzers.put("key_contact", new KeywordAnalyzer()); analyzer = new PerFieldAnalyzerWrapper( new StandardAnalyzer(Version.LUCENE_47), fieldAnalyzers); dir = null; path = context.getDatabasePath("contactsindex"); while (!path.exists()) { path.mkdirs(); if (!path.exists()) { try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } try { dir = new SimpleFSDirectory(path); dir.clearLock(IndexWriter.WRITE_LOCK_NAME); ContentProviderClient provider = context.getContentResolver().acquireContentProviderClient( ContactsContract.AUTHORITY_URI); mapper = new ContactDataMapper(provider); } catch (IOException e) { e.printStackTrace(); } } public void addListener(ProgressListener listener) { synchronized (listeners) { listeners.remove(listener); listeners.add(listener); } } public void removeListener(ProgressListener listener) { synchronized (listeners) { listeners.remove(listener); } } public void reportProgress(float progress) { synchronized (listeners) { for (ProgressListener listener : listeners) { listener.update(progress); } } } @Override public void run() { try { reportProgress(0f); phaseIndex(); if (stop) return; reportProgress(PHASE1); UndirectedGraph<Long, Double> graph = phaseAnalyze(); if (stop) return; reportProgress(0.99f); File path = context.getDatabasePath("contactsgraph"); if (!path.exists()) path.mkdirs(); GraphIO.store(graph, new File(path, "graph.kryo.gz")); if (stop) return; reportProgress(0.991f); File modelFile = new File(path, "model.kryo.gz"); ContentProviderClient provider = context.getContentResolver().acquireContentProviderClient( ContactsContract.AUTHORITY_URI); ArrayList<MergeContact> model = GraphConverter.convert(graph, provider); if (stop) return; reportProgress(0.996f); try { ModelIO.store(model, modelFile); if (stop) return; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } catch (IOException e) { stop = true; e.printStackTrace(); } catch (Exception e) { // we should never fail stop = true; e.printStackTrace(); } finally { if (dir != null) { try { dir.close(); dir = null; } catch (IOException e) { } catch (Exception e) { } } if (!stop) reportProgress(1f); } } private UndirectedGraph<Long, Double> phaseAnalyze() throws IOException { Log.d(LOGTAG, "All contacts indexed"); try { Thread.yield(); } catch (Exception e) { /* not critical */ } // ok, everything is indexed, now let's build a graph to see // how similar the various contacts are.... int ids[] = mapper.getContactIDs(); DirectoryReader reader = DirectoryReader.open(dir); IndexSearcher search = new IndexSearcher(reader); Log.d(LOGTAG, "Indexed docs: " + reader.numDocs()); UndirectedGraph<Long, Double> graph = new UndirectedGraph<Long, Double>(); BytesRef bytes = new BytesRef(NumericUtils.BUF_SIZE_LONG); int done = 0; HashMap<String, Integer> words = new HashMap<String, Integer>(); for (int i = 0; i < reader.maxDoc(); i++) { // go through all accounts, again, and check what accounts // should be merged if (stop) return null; Document doc = reader.document(i); if (doc == null) continue; long id = Long.parseLong(doc.getValues("id")[0]); Log.d(LOGTAG, "Analyzing document " + i + " contact " + id + " " + done + "/" + ids.length); // try to find dups based on the "all" field try { BooleanQuery root = new BooleanQuery(); TokenStream stream = doc.getField("all").tokenStream(analyzer); CharTermAttribute term = stream.getAttribute(CharTermAttribute.class); stream.reset(); words.clear(); int wordCount = 0; while (stream.incrementToken()) { wordCount++; String sterm = term.toString(); Integer count = words.get(sterm); if (count == null) { words.put(sterm, 1); } else { words.put(sterm, count + 1); } } stream.close(); for (Entry<String, Integer> entry : words.entrySet()) { double frequency = ((double) entry.getValue()) / wordCount; String t = entry.getKey(); Query q = null; if (t.length() <= 3) { q = new TermQuery(new Term("all", t)); } else if (t.length() <= 6) { q = new FuzzyQuery(new Term("all", t), 1, 2); } else { q = new FuzzyQuery(new Term("all", t), 2, 2); } q.setBoost((float) frequency); root.add(new BooleanClause(q, Occur.SHOULD)); } root.setMinimumNumberShouldMatch(Math.min( words.size(), 1 + words.size() * 2 / 3 )); float boost = (float) ( 0.1 + 0.9 * (words.size() - 1) / words.size() ); root.setBoost(boost); NumericUtils.longToPrefixCoded(id, 0, bytes); root.add(new BooleanClause(new TermQuery( new Term("id", bytes)), Occur.MUST_NOT )); TopDocs docs = search.search(root, 20); if (docs.scoreDocs.length > 0) { Log.d(LOGTAG, "Reference " + Arrays.toString(doc.getValues("display_name"))); } for (ScoreDoc otherDoc : docs.scoreDocs) { Document other = reader.document(otherDoc.doc); long otherId = Long.parseLong(other.getValues("id")[0]); String log = "Hit: doc " + otherDoc.doc + " / contact " + otherId + " / score " + otherDoc.score + " " + Arrays.toString(other.getValues("display_name")); Log.d(LOGTAG, log); Double d = graph.getEdge(id, otherId); if (d == null) { d = 0d; } graph.setEdge(id, otherId, d + otherDoc.score); } } catch (BooleanQuery.TooManyClauses e) { e.printStackTrace(); } try { // try to find dups based on the contact field BooleanQuery root = new BooleanQuery(); String contacts[] = doc.getValues("key_contact"); for (String contact : contacts) { if (contact.length() == 0) continue; Query q = null; if (contact.length() <= 3) { q = new TermQuery(new Term("key_contact", contact)); } else if (contact.length() <= 6) { q = new FuzzyQuery(new Term("key_contact", contact), 1, 2); } else { q = new FuzzyQuery(new Term("key_contact", contact), 2, 2); } q.setBoost((contact.length() - 1f) / contact.length()); root.add(new BooleanClause(q, Occur.SHOULD)); } root.setMinimumNumberShouldMatch(1); root.setBoost(root.clauses().size()); if (root.getClauses().length > 0) { root.add(new BooleanClause(new TermQuery( new Term("id", bytes)), Occur.MUST_NOT )); TopDocs docs = search.search(root, 10); if (docs.scoreDocs.length > 0) { Log.d(LOGTAG, "Reference [contact methods] " + Arrays.toString(contacts)); } for (ScoreDoc otherDoc : docs.scoreDocs) { Document other = reader.document(otherDoc.doc); long otherId = Long.parseLong(other.getValues("id")[0]); String log = "Hit: doc " + otherDoc.doc + " / contact " + otherId + " / score " + otherDoc.score + " " + Arrays.toString(other.getValues("display_name")); Log.d(LOGTAG, log); Double d = graph.getEdge(id, otherId); if (d == null) { d = 0d; } graph.setEdge(id, otherId, d + otherDoc.score); } } } catch (BooleanQuery.TooManyClauses e) { e.printStackTrace(); } done++; reportProgress(PHASE1 + ((PHASE2 - 0.001f) * Math.min(done, ids.length)) / ids.length); try { Thread.yield(); } catch (Exception e) { /* not critical */ } } return graph; } private void phaseIndex() throws IOException { IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig( Version.LUCENE_47, analyzer)); writer.deleteAll(); try { int[] ids = mapper.getContactIDs(); Log.d(LOGTAG, "Got " + ids.length + " contacts to index"); int done = 0; for (int i : ids) { if (stop) return; Contact contact = mapper.getContactById(i, true, true); if (contact == null) continue; // modified as we read it :-S Document doc = new Document(); done++; doc.add(new LongField("id", contact.getId(), Store.YES)); String all = ""; if (!empty(contact.getDisplayName())) { doc.add(new TextField( "display_name", contact.getDisplayName(), Store.YES)); all = all + " " + contact.getDisplayName(); } if (!empty(contact.getDisplayNameAlternative())) { doc.add(new TextField( "display_name_alternative", contact.getDisplayNameAlternative(), Store.YES)); all = all + " " + contact.getDisplayNameAlternative(); } if (!empty(contact.getDisplayNamePrimary())) { doc.add(new TextField( "display_name_primary", contact.getDisplayNamePrimary(), Store.YES)); all = all + " " + contact.getDisplayNameAlternative(); } if (!empty(contact.getPhoneticName())) { doc.add(new TextField( "phonetic_name", contact.getPhoneticName(), Store.YES)); all = all + " " + contact.getPhoneticName(); } if (!empty(contact.getSortKeyPrimary())) { doc.add(new TextField( "sort_key_primary", contact.getSortKeyPrimary(), Store.YES)); all = all + " " + contact.getSortKeyPrimary(); } if (!empty(contact.getSortKeyAlternative())) { doc.add(new TextField( "sort_key_alternative", contact.getSortKeyAlternative(), Store.YES)); all = all + " " + contact.getSortKeyAlternative(); } RawContact[] raws = contact.getRawContacts(); if (raws == null) continue; for (RawContact raw : raws) { if (!empty(raw.getAccountType()) && !empty(raw.getAccountName())) { doc.add(new TextField( "account_type_" + raw.getAccountType(), raw.getAccountName(), Store.YES)); doc.add(new TextField( "account_type", raw.getAccountType(), Store.YES)); doc.add(new TextField( "account_name", raw.getAccountName(), Store.YES)); } for (Metadata data : raw.getMetadata().values()) { if (data.getMimetype().equals(ImMetadata.MIMETYPE)) { if (!empty(data.getData(0))) { doc.add(new TextField( "im", data.getData(0), Store.YES)); doc.add(new TextField( "key_contact", data.getData(0), Store.YES)); all = all + " " + data.getData(2); } if (!empty(data.getData(2))) { doc.add(new TextField( "im", data.getData(2), Store.YES)); doc.add(new TextField( "key_contact", data.getData(2), Store.YES)); all = all + " " + data.getData(2); } continue; } if (data.getMimetype().equals(StructuredName.CONTENT_ITEM_TYPE)) { if (!empty(data.getData(0))) { doc.add(new TextField( "display_name", data.getData(0), Store.YES)); all = all + " " + data.getData(0); } if (!empty(data.getData(1))) { doc.add(new TextField( "given_name", data.getData(1), Store.YES)); all = all + " " + data.getData(1); } if (!empty(data.getData(2))) { doc.add(new TextField( "family_name", data.getData(2), Store.YES)); all = all + " " + data.getData(2); } if (!empty(data.getData(4))) { doc.add(new TextField( "middle_name", data.getData(4), Store.YES)); all = all + " " + data.getData(4); } if (!empty(data.getData(6))) { doc.add(new TextField( "phonetic_given_name", data.getData(6), Store.YES)); all = all + " " + data.getData(6); } if (!empty(data.getData(8))) { doc.add(new TextField( "phonetic_family_name", data.getData(8), Store.YES)); all = all + " " + data.getData(8); } if (!empty(data.getData(7))) { doc.add(new TextField( "phonetic_middle_name", data.getData(7), Store.YES)); all = all + " " + data.getData(7); } if (!empty(data.getData(3))) { doc.add(new TextField( "name_prefix", data.getData(3), Store.YES)); all = all + " " + data.getData(3); } if (!empty(data.getData(5))) { doc.add(new TextField( "name_suffix", data.getData(5), Store.YES)); all = all + " " + data.getData(5); } continue; } if (data.getMimetype().equals(StructuredPostal.CONTENT_ITEM_TYPE)) { if (!empty(data.getData(0))) { doc.add(new TextField( "postal", data.getData(0), Store.YES)); all = all + " " + data.getData(0); } continue; } if (data.getMimetype().equals(Phone.CONTENT_ITEM_TYPE)) { if (!empty(data.getData(0))) { String str = data.getData(0); doc.add(new TextField( "phonenumber", str, Store.YES)); doc.add(new TextField( "key_contact", str, Store.YES)); all = all + " " + data.getData(0); } continue; } if (data.getMimetype().equals(Email.CONTENT_ITEM_TYPE)) { if (!empty(data.getData(0))) { doc.add(new TextField( "email", data.getData(0), Store.YES)); doc.add(new TextField( "key_contact", data.getData(0), Store.YES)); all = all + " " + data.getData(0); } continue; } if (data.getMimetype().equals(Nickname.CONTENT_ITEM_TYPE)) { if (!empty(data.getData(0))) { doc.add(new TextField( "nickname", data.getData(0), Store.YES)); all = all + " " + data.getData(0); } continue; } if (data.getMimetype().equals(Website.CONTENT_ITEM_TYPE)) { if (!empty(data.getData(0))) { doc.add(new TextField( "website", data.getData(0), Store.YES)); doc.add(new TextField( "key_contact", data.getData(0), Store.YES)); all = all + " " + data.getData(0); } continue; } if (data.getMimetype().equals(Note.CONTENT_ITEM_TYPE)) continue; if (data.getMimetype().equals(Photo.CONTENT_ITEM_TYPE)) continue; Log.d(LOGTAG, "MIME " + data.getMimetype()); } } doc.add(new TextField( "all", all.trim(), Store.YES)); writer.addDocument(doc, analyzer); Log.d(LOGTAG, "Got contact " + i + " " + done + "/" + ids.length); reportProgress(((PHASE1 - 0.001f) * (Math.min(done, ids.length)) / ids.length)); try { Thread.yield(); } catch (Exception e) { /* not critical */ } } writer.forceMerge(1); writer.commit(); } finally { try { writer.close(true); } catch (Exception e) {} } } private final static boolean empty(String s) { return s == null || s.trim().isEmpty(); } public void doStop() { this.stop = true; try { dir.clearLock(IndexWriter.WRITE_LOCK_NAME); dir.close(); dir = null; } catch (Exception e) { e.printStackTrace(); } File lock = new File(path, "write.lock"); if (lock.exists()) { try { lock.delete(); } catch (Exception e) { e.printStackTrace(); } } synchronized (listeners) { for (ProgressListener listener : listeners) { listener.update(0f); listener.abort(); } } } }
package dr.app.tools; import dr.app.beagle.evomodel.parsers.GammaSiteModelParser; import dr.app.beagle.evomodel.sitemodel.SiteRateModel; import dr.app.beast.BeastVersion; import dr.app.util.Arguments; import dr.app.util.Utils; import dr.evolution.alignment.Alignment; import dr.evolution.alignment.ConvertAlignment; import dr.evolution.alignment.PatternList; import dr.evolution.alignment.SimpleAlignment; //import dr.evolution.datatype.AminoAcids; //import dr.evolution.datatype.GeneralDataType; import dr.evolution.datatype.*; import dr.evolution.io.Importer; import dr.evolution.io.NexusImporter; import dr.evolution.io.TreeExporter; import dr.evolution.io.TreeImporter; import dr.evolution.sequence.Sequence; import dr.evolution.tree.*; import dr.evolution.util.Taxon; import dr.evolution.util.TaxonList; import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.branchratemodel.StrictClockBranchRates; //import dr.evomodel.sitemodel.GammaSiteModel; //import dr.evomodel.sitemodel.SiteModel; //import dr.evomodel.substmodel.*; import dr.evomodel.substmodel.JTT; import dr.evomodel.substmodel.WAG; import dr.evomodel.tree.TreeModel; import dr.evomodel.treelikelihood.AncestralStateTreeLikelihood; import dr.evomodelxml.substmodel.GeneralSubstitutionModelParser; import dr.inference.model.Parameter; import dr.stats.DiscreteStatistics; import dr.util.HeapSort; import dr.util.Version; import dr.app.beagle.evomodel.sitemodel.GammaSiteRateModel; import dr.app.beagle.evomodel.substmodel.*; import dr.app.beagle.evomodel.sitemodel.HomogenousBranchSubstitutionModel; import dr.app.beagle.evomodel.treelikelihood.PartialsRescalingScheme; import dr.app.beagle.evomodel.treelikelihood.AncestralStateBeagleTreeLikelihood; import java.io.*; import java.util.*; import java.util.logging.Logger; /* * @author Marc A. Suchard * @author Wai Lok Sibon Li */ public class AncestralSequenceAnnotator { private final static Version version = new BeastVersion(); public final static int MAX_CLADE_CREDIBILITY = 0; public final static int MAX_SUM_CLADE_CREDIBILITY = 1; public final static int USER_TARGET_TREE = 2; public final static int KEEP_HEIGHTS = 0; public final static int MEAN_HEIGHTS = 1; public final static int MEDIAN_HEIGHTS = 2; public final String[] GENERAL_MODELS_LIST = {"EQU"}; public final String[] NUCLEOTIDE_MODELS_LIST = {"HKY", "TN", "GTR"}; public final String[] AMINO_ACID_MODELS_LIST = {"JTT1992", "WAG2001", "LG2008", "Empirical\\(.+\\)"}; public final String[] TRIPLET_MODELS_LIST = {"HKYx3", "TNx3", "GTRx3"}; public final String[] CODON_MODELS_LIST = {"M0HKY", "M0TN", "M0GTR"};//"M0", "M0\\[.+\\]", ""}; public AncestralSequenceAnnotator(int burnin, int heightsOption, double posteriorLimit, int targetOption, String targetTreeFileName, String inputFileName, String outputFileName, String clustalExecutable ) throws IOException { this.posteriorLimit = posteriorLimit; this.clustalExecutable = clustalExecutable; attributeNames.add("height"); attributeNames.add("length"); System.out.println("Reading trees and simulating internal node states..."); CladeSystem cladeSystem = new CladeSystem(); boolean firstTree = true; FileReader fileReader = new FileReader(inputFileName); TreeImporter importer = new NexusImporter(fileReader); TreeExporter exporter; if (outputFileName != null) exporter = new NexusExporter(new PrintStream(new FileOutputStream(outputFileName))); else exporter = new NexusExporter(System.out); TreeExporter simulationResults = new NexusExporter(new PrintStream(new FileOutputStream(inputFileName + ".out"))); List<Tree> simulatedTree = new ArrayList<Tree>(); // burnin = 0; // java.util.logging.Logger.getLogger("dr.evomodel"). try { while (importer.hasTree()) { Tree tree = importer.importNextTree(); if (firstTree) { Tree unprocessedTree = tree; tree = processTree(tree); setupTreeAttributes(tree); setupAttributes(tree); tree = unprocessedTree; //This actually does nothing since unprocessedTree was a reference to processedTree in the first place firstTree = false; } if (totalTrees >= burnin) { addTreeAttributes(tree); // Tree savedTree = tree; tree = processTree(tree); // System.err.println(Tree.Utils.newick(tree)); exporter.exportTree(tree); // simulationResults.exportTree(tree); // System.exit(-1); simulatedTree.add(tree); cladeSystem.add(tree); totalTreesUsed += 1; } totalTrees += 1; } } catch (Importer.ImportException e) { System.err.println("Error Parsing Input Tree: " + e.getMessage()); return; } fileReader.close(); cladeSystem.calculateCladeCredibilities(totalTreesUsed); System.out.println("\tTotal trees read: " + totalTrees); if (burnin > 0) { System.out.println("\tIgnoring first " + burnin + " trees."); } simulationResults.exportTrees(simulatedTree.toArray(new Tree[simulatedTree.size()])); MutableTree targetTree; if (targetOption == USER_TARGET_TREE) { if (targetTreeFileName != null) { System.out.println("Reading user specified target tree, " + targetTreeFileName); importer = new NexusImporter(new FileReader(targetTreeFileName)); try { targetTree = new FlexibleTree(importer.importNextTree()); } catch (Importer.ImportException e) { System.err.println("Error Parsing Target Tree: " + e.getMessage()); return; } } else { System.err.println("No user target tree specified."); return; } } else if (targetOption == MAX_CLADE_CREDIBILITY) { System.out.println("Finding maximum credibility tree..."); targetTree = new FlexibleTree(summarizeTrees(burnin, cladeSystem, inputFileName, false)); } else if (targetOption == MAX_SUM_CLADE_CREDIBILITY) { System.out.println("Finding maximum sum clade credibility tree..."); targetTree = new FlexibleTree(summarizeTrees(burnin, cladeSystem, inputFileName, true)); } else { throw new RuntimeException("Unknown target tree option"); } System.out.println("Annotating target tree... (this may take a long time)"); // System.out.println("Starting processing...."); // System.out.println("calling annotateTree"); // System.out.println("targetTree has "+targetTree.getNodeCount()+" nodes."); cladeSystem.annotateTree(targetTree, targetTree.getRoot(), null, heightsOption); System.out.println("Processing ended."); // System.exit(-1); System.out.println("Writing annotated tree...."); if (outputFileName != null) { exporter = new NexusExporter(new PrintStream(new FileOutputStream(outputFileName))); exporter.exportTree(targetTree); } else { exporter = new NexusExporter(System.out); exporter.exportTree(targetTree); } } private abstract class SubstitutionModelLoader { public final char[] AA_ORDER = AminoAcids.AMINOACID_CHARS; //"ACDEFGHIKLMNPQRSTVWY"; //public static final String AA_ORDER = "ACDEFGHIKLMNPQRSTVWY"; public final char[] NUCLEOTIDE_ORDER = Nucleotides.NUCLEOTIDE_CHARS; //"ACGU"; public final String[] CODON_ORDER = Codons.CODON_TRIPLETS; protected SubstitutionModel substModel; protected FrequencyModel freqModel; private String modelType; protected String substModelName; protected String[] charList; protected DataType dataType; SubstitutionModelLoader(Tree tree, String modelType, DataType dataType) { this.dataType = dataType; this.modelType = modelType; load(tree, modelType); } /* An artifact of old code? */ SubstitutionModelLoader(String name) { this.substModelName = name; } public SubstitutionModel getSubstitutionModel() { return substModel; } public FrequencyModel getFrequencyModel() { return freqModel; } public String getModelType() { return modelType; } public String getSubstModel() { return substModelName; } public String[] getCharList() { return charList; } public void setCharList(String[] cl) { System.arraycopy(cl, 0, charList, 0, cl.length); //charList = cl.clone(); } public abstract DataType getDataType(); protected abstract void modelSpecifics(Tree tree, String modelType); public void load(Tree tree, String modelType) { substModelName = modelType.replaceFirst("\\*.+","").replaceFirst("\\+.+","").trim(); loadFrequencyModel(tree); //System.out.println("Frequency model datatype: " + getDataType()); //dd modelSpecifics(tree, modelType); printLogLikelihood(tree); } private void loadFrequencyModel(Tree tree) { final String[] AA_ORDER = {"A","C","D","E","F","G","H","I","K","L","M","N","P","Q","R", "S","T","V","W","Y"}; //"ACDEFGHIKLMNPQRSTVWY".split("");//AminoAcids.AMINOACID_CHARS; final String[] DNA_NUCLEOTIDE_ORDER = {"A", "C", "G", "T"};//"ACGT".split(""); //Nucleotides.NUCLEOTIDE_CHARS; final String[] RNA_NUCLEOTIDE_ORDER = {"A", "C", "G", "U"};//"ACGU".split(""); //Nucleotides.NUCLEOTIDE_CHARS; // final String[] CODON_ORDER = {"AAA", "AAC", "AAG", "AAT", "ACA", "ACC", "ACG", "ACT", // "AGA", "AGC", "AGG", "AGT", "ATA", "ATC", "ATG", "ATT", // "CAA", "CAC", "CAG", "CAT", "CCA", "CCC", "CCG", "CCT", // "CGA", "CGC", "CGG", "CGT", "CTA", "CTC", "CTG", "CTT", // "GAA", "GAC", "GAG", "GAT", "GCA", "GCC", "GCG", "GCT", // "GGA", "GGC", "GGG", "GGT", "GTA", "GTC", "GTG", "GTT", // "TAA", "TAC", "TAG", "TAT", "TCA", "TCC", "TCG", "TCT", // "TGA", "TGC", "TGG", "TGT", "TTA", "TTC", "TTG", "TTT"};// Codons.CODON_TRIPLETS; final String[] DNA_CODON_ORDER = {"AAA", "AAC", "AAG", "AAT", "ACA", "ACC", "ACG", "ACT", "AGA", "AGC", "AGG", "AGT", "ATA", "ATC", "ATG", "ATT", "CAA", "CAC", "CAG", "CAT", "CCA", "CCC", "CCG", "CCT", "CGA", "CGC", "CGG", "CGT", "CTA", "CTC", "CTG", "CTT", "GAA", "GAC", "GAG", "GAT", "GCA", "GCC", "GCG", "GCT", "GGA", "GGC", "GGG", "GGT", "GTA", "GTC", "GTG", "GTT", /*"TAA",*/ "TAC", /*"TAG",*/ "TAT", "TCA", "TCC", "TCG", "TCT", /* Minus the stop and start codons */ /*"TGA",*/ "TGC", "TGG", "TGT", "TTA", "TTC", "TTG", "TTT"};// Codons.CODON_TRIPLETS; final String[] RNA_CODON_ORDER = {"AAA", "AAC", "AAG", "AAU", "ACA", "ACC", "ACG", "ACU", "AGA", "AGC", "AGG", "AGU", "AUA", "AUC", "AUG", "AUU", "CAA", "CAC", "CAG", "CAU", "CCA", "CCC", "CCG", "CCU", "CGA", "CGC", "CGG", "CGU", "CUA", "CUC", "CUG", "CUU", "GAA", "GAC", "GAG", "GAU", "GCA", "GCC", "GCG", "GCU", "GGA", "GGC", "GGG", "GGU", "GUA", "GUC", "GUG", "GUU", /*"UAA",*/ "UAC", /*"UAG",*/ "UAU", "UCA", "UCC", "UCG", "UCU", /* Minus the stop and start codons */ /*"UGA",*/ "UGC", "UGG", "UGU", "UUA", "UUC", "UUG", "UUU"};// Codons.CODON_TRIPLETS; /* For BAli-Phy, even if F=constant, you can still extract the frequencies this way. */ /* Obtain the equilibrium base frequencies for the model */ double[] freq = new double[0]; String[] charOrder = new String[0]; if(getDataType().getClass().equals(GeneralDataType.class)) { ArrayList<String> tempCharOrder = new ArrayList<String>(freq.length); for (Iterator<String> i = tree.getAttributeNames(); i.hasNext();) { String name = i.next(); if (name.startsWith("pi")) { /* the pi in the output files contains the frequencies */ String character = name.substring(2, name.length()); tempCharOrder.add(character); } } charOrder = tempCharOrder.toArray(new String[tempCharOrder.size()]); //this.charList = tempCharOrder.toArray(new String[tempCharOrder.size()]); freq = new double[charOrder.length]; } else if(getDataType().getClass().equals(Nucleotides.class)) { if(tree.getAttribute("piT") != null) { charOrder = DNA_NUCLEOTIDE_ORDER; freq = new double[charOrder.length]; } else if(tree.getAttribute("piU") != null) { charOrder = RNA_NUCLEOTIDE_ORDER; freq = new double[charOrder.length]; } else { throw new RuntimeException("Not proper nucleotide data"); } } else if(getDataType().getClass().equals(AminoAcids.class)) { charOrder = AA_ORDER; freq = new double[charOrder.length]; } else if(getDataType().getClass().equals(Codons.class)) { if(tree.getAttribute("piAAT") != null) { charOrder = DNA_CODON_ORDER; freq = new double[charOrder.length]; } else if(tree.getAttribute("piAAU") != null) { charOrder = RNA_CODON_ORDER; freq = new double[charOrder.length]; } else{ throw new RuntimeException("Base frequencies do not fit those for a codon model or not proper nucleotide data for codons\n" + "If you are using F=nucleotides models for codon models, they are currently not supported in BEAST"); } } else { throw new RuntimeException("Datatype unknown! (This error message should never be seen, contact Sibon)"); } // // This if statement is reserved for triplet data // else if(getDataType().getClass().equals(Nucleotides.class)) { // // This is wrong because for triplets // freq = new double[Nucleotides.NUCLEOTIDE_CHARS.length]; int cnt = 0; double sum = 0; //charList = ""; ArrayList<String> tempCharList = new ArrayList<String>(freq.length); for (Iterator<String> i = tree.getAttributeNames(); i.hasNext();) { String name = i.next(); if (name.startsWith("pi")) { /* the pi in the output files contains the frequencies */ String character = name.substring(2, name.length()); tempCharList.add(character); //charList = charList.concat(character); Double value = (Double) tree.getAttribute(name); freq[cnt++] = value; sum += value; } } charList = tempCharList.toArray(new String[tempCharList.size()]); // for(int j=0; j<charList.length; j++) { // System.out.println("charizard lists " + charList[j]); /* Order the frequencies correctly */ double[] freqOrdered = new double[freq.length]; for (int i = 0; i < freqOrdered.length; i++) { int index = -5; search: for (int j = 0; j < charList.length; j++) { if(charList[j].equals(charOrder[i])) { index = j; break search; } } freqOrdered[i] = freq[index] / sum; //System.out.println(" no fried " + freqOrdered.length + "\t" + freq.length + "\t" + charOrder[i] + "\t" + freqOrdered[i]); //ddd } this.freqModel = new FrequencyModel(getDataType(), new Parameter.Default(freqOrdered)); } protected boolean doPrint = false; private void printLogLikelihood(Tree tree) { if (doPrint) { Double logLikelihood = Double.parseDouble(tree.getAttribute(LIKELIHOOD).toString()); if (logLikelihood != null) System.err.printf("%5.1f", logLikelihood); } } } private class GeneralSubstitutionModelLoader extends SubstitutionModelLoader { private final String EQU_TEXT = "EQU"; private GeneralSubstitutionModelLoader(Tree tree, String modelType) { super(tree, modelType, new GeneralDataType(new String[0])); setGeneralDataType(); throw new RuntimeException("General substitution model is currently not stable and should not be used"); } protected void modelSpecifics(Tree tree, String modelType) { if(substModelName.equals(EQU_TEXT)) { if(freqModel.getFrequencyCount() != charList.length) { System.err.println("Frequency model length does not match character list length, " + "GeneralSubstitutionModelLoader"); System.exit(-1); } /* Equivalent to a JC model but for all states */ //TODO CHECK IF THIS IS CORRECT double[] rates = new double[(charList.length * (charList.length - 1)) / 2]; for(int i=0; i<rates.length; i++) { rates[i] = 1.0; } System.out.println("Number of site transition rate categories (debuggin): " + rates.length); //substModel = new GeneralSubstitutionModel(freqModel.getDataType(), freqModel, new Parameter.Default(rates), 1); substModel = new GeneralSubstitutionModel(GeneralSubstitutionModelParser.GENERAL_SUBSTITUTION_MODEL, freqModel.getDataType(), freqModel, new Parameter.Default(rates), 1, null); } } public DataType getDataType() { setGeneralDataType(); return dataType; } public void setGeneralDataType() { if(charList!=null && dataType.getStateCount()!=charList.length) { GeneralDataType gdt = new GeneralDataType(charList); gdt.addAmbiguity("-", charList); gdt.addAmbiguity("X", charList); gdt.addAmbiguity("?", charList); dataType = gdt; } } } private class NucleotideSubstitutionModelLoader extends SubstitutionModelLoader { protected static final String HKY_TEXT = "HKY"; protected static final String TN_TEXT = "TN"; protected static final String GTR_TEXT = "GTR"; private NucleotideSubstitutionModelLoader(Tree tree, String modelType) { super(tree, modelType, Nucleotides.INSTANCE); } protected void modelSpecifics(Tree tree, String modelType) { if(substModelName.equals(HKY_TEXT)) { double kappa = Double.parseDouble(tree.getAttribute("HKY_kappa").toString()); //double kappa = (Double) tree.getAttribute("HKY_kappa"); //double kappa = (Double) tree.getAttribute("HKY\\:\\:kappa"); //double kappa = (Double) tree.getAttribute("HKY::kappa"); //double kappa = (Double) tree.getAttribute("kappa"); substModel = new HKY(new Parameter.Default(kappa), freqModel); } if(substModelName.equals(TN_TEXT)) { double kappa1 = Double.parseDouble(tree.getAttribute("TN_kappa(pur)").toString()); double kappa2 = Double.parseDouble(tree.getAttribute("TN_kappa(pyr)").toString()); //double kappa1 = (Double) tree.getAttribute("TN_kappa(pur)"); //double kappa2 = (Double) tree.getAttribute("TN_kappa(pyr)"); System.err.println("Sorry, TN substitution model is not yet implemented in BEAST-Beagle"); System.exit(0); //TODO Tamura-Nei model //substModel = new TN93(new Parameter.Default(kappa1), new Parameter.Default(kappa2), freqModel); } if(substModelName.equals(GTR_TEXT)) { /* It should be noted that BAli-Phy uses TC instead of CT and GC instead of CG */ //double rateACValue = (Double) tree.getAttribute("GTR_AC"); //double rateAGValue = (Double) tree.getAttribute("GTR_AG"); //double rateATValue = (Double) tree.getAttribute("GTR_AT"); //double rateCGValue = (Double) tree.getAttribute("GTR_GC"); //double rateCTValue = (Double) tree.getAttribute("GTR_TC"); //double rateGTValue = (Double) tree.getAttribute("GTR_GT"); double rateACValue = Double.parseDouble(tree.getAttribute("GTR_AC").toString()); double rateAGValue = Double.parseDouble(tree.getAttribute("GTR_AG").toString()); double rateATValue = Double.parseDouble(tree.getAttribute("GTR_AT").toString()); double rateCGValue = Double.parseDouble(tree.getAttribute("GTR_GC").toString()); double rateCTValue = Double.parseDouble(tree.getAttribute("GTR_TC").toString()); double rateGTValue = Double.parseDouble(tree.getAttribute("GTR_GT").toString()); substModel = new GTR(new Parameter.Default(rateACValue), new Parameter.Default(rateAGValue), new Parameter.Default(rateATValue), new Parameter.Default(rateCGValue), new Parameter.Default(rateCTValue), new Parameter.Default(rateGTValue), freqModel); } } public DataType getDataType() { return dataType; //Potential } } private class AminoAcidSubstitutionModelLoader extends SubstitutionModelLoader { protected final String JTT_TEXT = "JTT1992"; protected final String WAG_TEXT = "WAG2001"; protected final String LG_TEXT = "LG2008"; protected final String Empirical_TEXT = "Empirical(.+).+"; private AminoAcidSubstitutionModelLoader(Tree tree, String modelType) { super(tree, modelType, AminoAcids.INSTANCE); } protected void modelSpecifics(Tree tree, String modelType) { if(substModelName.equals(JTT_TEXT)) { substModel = new EmpiricalAminoAcidModel(JTT.INSTANCE, freqModel); } if(substModelName.equals(WAG_TEXT)) { substModel = new EmpiricalAminoAcidModel(WAG.INSTANCE, freqModel); } if(substModelName.equals(LG_TEXT)) { //todo Implement Le Gascuel (2008) model System.err.println("Sorry, LG substitution model is not yet implemented in BEAST"); System.exit(0); //substModel = new EmpiricalAminoAcidModel(JTT.INSTANCE, freqModel); } //todo Allow proper file input of Empirical amino-acid models if(substModelName.matches(Empirical_TEXT)) { String empiricalModelFileName = substModelName.replaceFirst("Empirical\\(", "").replaceFirst("\\).*",""); if(empiricalModelFileName.equals("wag.dat")) { substModel = new EmpiricalAminoAcidModel(WAG.INSTANCE, freqModel); } else if(empiricalModelFileName.equals("jtt.dat")) { substModel = new EmpiricalAminoAcidModel(JTT.INSTANCE, freqModel); } else { System.err.println("Sorry, AncestralSequenceAnnotator does not currently support other files"); System.err.println("Soon, we will allow users to enter a file"); System.exit(0); } } } public DataType getDataType() { return dataType; //Potential } } private class TripletSubstitutionModelLoader extends SubstitutionModelLoader { protected final String HKYx3_TEXT = "HKYx3"; protected final String TNx3_TEXT = "TNx3"; protected final String GTRx3_TEXT = "GTRx3"; private TripletSubstitutionModelLoader(Tree tree, String modelType) { super(tree, modelType, Nucleotides.INSTANCE); } protected void modelSpecifics(Tree tree, String modelType) { if(substModelName.equals(HKYx3_TEXT)) { System.err.println("Sorry, HKYx3 substitution model is not yet implemented in BEAST"); System.exit(0); //substModel = new HKY(); } if(substModelName.equals(TNx3_TEXT)) { System.err.println("Sorry, TNx3 substitution model is not yet implemented in BEAST"); System.exit(0); //substModel = new TN93(); } if(substModelName.equals(GTRx3_TEXT)) { System.err.println("Sorry, GTRx3 substitution model is not yet implemented in BEAST"); System.exit(0); //substModel = new GTR(); } } public DataType getDataType() { return dataType; // Is this right? } } private class CodonSubstitutionModelLoader extends SubstitutionModelLoader { // private final String M0_TEXT = "M0"; // Not necessary since this never actually shows up in BAli-Phy output protected final String M0_NUC_TEXT = "M0\\w+"; //private final String HKY_TEXT = "HKY"; //private final String TN_TEXT = "TN"; //private final String GTR_TEXT = "GTR"; private CodonSubstitutionModelLoader(Tree tree, String modelType) { super(tree, modelType, Codons.UNIVERSAL); //Potential } protected void modelSpecifics(Tree tree, String modelType) { //String codonNucleotideModel = substModelName.substring(substModelName.indexOf("\\\\[")+1, substModelName.indexOf("\\\\]")); String codonNucleotideModel = substModelName.substring(substModelName.indexOf("M0")+2, substModelName.length()); // if(substModelName.equals(M0_TEXT)) { // /* HKY is default */ // codonNucleotideModel = NucleotideSubstitutionModelLoader.HKY_TEXT; if(substModelName.matches(M0_NUC_TEXT)) { /* M0_omega may be *M0_omega, depending on whether M2 etc. are used */ double omega = Double.parseDouble(tree.getAttribute("M0_omega").toString()); //omega = (Double) tree.getAttribute("\\M0_omega"); if(codonNucleotideModel.equals(NucleotideSubstitutionModelLoader.HKY_TEXT)) { //double kappa = (Double) tree.getAttribute("HKY_kappa"); double kappa = Double.parseDouble(tree.getAttribute("HKY_kappa").toString()); //substModel = new YangCodonModel(Codons.UNIVERSAL, new Parameter.Default(omega), //new Parameter.Default(kappa), freqModel); substModel = new GY94CodonModel(Codons.UNIVERSAL, new Parameter.Default(omega), new Parameter.Default(kappa), freqModel); } if(codonNucleotideModel.equals(NucleotideSubstitutionModelLoader.TN_TEXT)) { //double kappa1 = (Double) tree.getAttribute("TN_kappa(pur)"); //double kappa2 = (Double) tree.getAttribute("TN_kappa(pyr)"); double kappa1 = Double.parseDouble(tree.getAttribute("TN_kappa(pur)").toString()); double kappa2 = Double.parseDouble(tree.getAttribute("TN_kappa(pyr)").toString()); System.err.println("Sorry, M0[TN] substitution model is not yet implemented in BEAST"); System.exit(0); } if(codonNucleotideModel.equals(NucleotideSubstitutionModelLoader.GTR_TEXT)) { double rateACValue = Double.parseDouble(tree.getAttribute("GTR_AC").toString()); double rateAGValue = Double.parseDouble(tree.getAttribute("GTR_AG").toString()); double rateATValue = Double.parseDouble(tree.getAttribute("GTR_AT").toString()); double rateCGValue = Double.parseDouble(tree.getAttribute("GTR_GC").toString()); double rateCTValue = Double.parseDouble(tree.getAttribute("GTR_TC").toString()); double rateGTValue = Double.parseDouble(tree.getAttribute("GTR_GT").toString()); //double rateACValue = (Double) tree.getAttribute("GTR_AC"); //double rateAGValue = (Double) tree.getAttribute("GTR_AG"); //double rateATValue = (Double) tree.getAttribute("GTR_AT"); //double rateCGValue = (Double) tree.getAttribute("GTR_GC"); //double rateCTValue = (Double) tree.getAttribute("GTR_TC"); //double rateGTValue = (Double) tree.getAttribute("GTR_GT"); System.err.println("Sorry, M0[GTR] substitution model is not yet implemented in BEAST"); System.exit(0); } // If +m2 then *M0 } } public DataType getDataType() { return dataType; // Is this right too? Just use the universal codon table? } } /* * This method is equivalent to the SubstitutionModelLoader without having to * be object orientated and can be much more flexible. */ private GammaSiteRateModel loadSiteModel(Tree tree) { String modelType = (String) tree.getAttribute(SUBST_MODEL); /* Identify the datatype and substitution model. Load the model */ SubstitutionModelLoader sml = null; String substModelName = modelType.replaceFirst("\\*.+","").replaceFirst("\\+.+","").trim(); System.out.println("Basic Substitution Model is " + substModelName); for(int i = 0; i<GENERAL_MODELS_LIST.length; i++) { if(substModelName.matches(GENERAL_MODELS_LIST[i])) { sml = new GeneralSubstitutionModelLoader(tree, modelType); } } for(int i = 0; i<NUCLEOTIDE_MODELS_LIST.length; i++) { if(substModelName.matches(NUCLEOTIDE_MODELS_LIST[i])) { sml = new NucleotideSubstitutionModelLoader(tree, modelType); } } for(int i = 0; i<AMINO_ACID_MODELS_LIST.length; i++) { if(substModelName.matches(AMINO_ACID_MODELS_LIST[i])) { sml = new AminoAcidSubstitutionModelLoader(tree, modelType); } } for(int i = 0; i<TRIPLET_MODELS_LIST.length; i++) { if(substModelName.matches(TRIPLET_MODELS_LIST[i])) { sml = new TripletSubstitutionModelLoader(tree, modelType); } } for(int i = 0; i<CODON_MODELS_LIST.length; i++) { if(substModelName.matches(CODON_MODELS_LIST[i])) { sml = new CodonSubstitutionModelLoader(tree, modelType); } } if (sml.getSubstitutionModel() == null) { System.err.println("Substitution model type '" + modelType + "' not implemented"); System.exit(-1); } //SiteModel siteModel = new GammaSiteModel(sml.getSubstitutionModel(), new Parameter.Default(1.0), null, 0, null); //SiteModel siteModel = new GammaSiteModel(sml.getSubstitutionModel(), null, null, 0, null); String siteRatesModels = modelType.substring(modelType.indexOf("+")+1, modelType.length()); //String[] siteRatesModels = siteRatesParameters.split(" + "); System.out.println("Site rate models: " + siteRatesModels); if(sml.getSubstitutionModel().getDataType().getClass().equals(Codons.class) && siteRatesModels.length() > 0) { /* For codon site models */ if(siteRatesModels.indexOf("+M2") >= 0) { System.out.println("Site model - M2 Codon site model used"); Parameter m2FrequencyAAInv = new Parameter.Default(Double.parseDouble(tree.getAttribute("M2_f[AA INV]").toString())); Parameter m2FrequencyNeutral = new Parameter.Default(Double.parseDouble(tree.getAttribute("M2_f[Neutral]").toString())); Parameter m2FrequencySelected = new Parameter.Default(Double.parseDouble(tree.getAttribute("M2_f[Selected]").toString())); Parameter m2Omega = new Parameter.Default(Double.parseDouble(tree.getAttribute("M2_omega").toString())); //Parameter m2FrequencyAAInv = new Parameter.Default((Double) tree.getAttribute("M2_f[AA INV]")); //Parameter m2FrequencyNeutral = new Parameter.Default((Double) tree.getAttribute("M2_f[Neutral]")); //Parameter m2FrequencySelected = new Parameter.Default((Double) tree.getAttribute("M2_f[Selected]")); //Parameter m2Omega = new Parameter.Default((Double) tree.getAttribute("M2_omega")); System.err.println("Sorry, M2 substitution model is not yet implemented in BEAST"); System.exit(0); } else if(siteRatesModels.indexOf("+M3") >= 0) { System.out.println("Site model - M3 Codon site model used"); int numberOfBins = Integer.parseInt(siteRatesModels.replaceFirst(".+M3\\[","").replaceFirst("\\].+", "")); System.out.println(" + M3 n value: " + numberOfBins); Parameter[] m3Frequencies = new Parameter[numberOfBins]; Parameter[] m3Omegas = new Parameter[numberOfBins]; for(int i=1; i<=numberOfBins; i++) { m3Frequencies[i-1] = new Parameter.Default(Double.parseDouble(tree.getAttribute("M3_f"+i).toString())); m3Omegas[i-1] = new Parameter.Default(Double.parseDouble(tree.getAttribute("M3_omega"+i).toString())); //m3Frequencies[i-1] = new Parameter.Default((Double) tree.getAttribute("M3_f"+i)); //m3Omegas[i-1] = new Parameter.Default((Double) tree.getAttribute("M3_omega"+i)); } System.err.println("Sorry, M3 substitution model is not yet implemented in BEAST"); System.exit(0); } else if(siteRatesModels.indexOf("+M0_omega~Beta(") >= 0) { System.out.println("Site model - M7 Codon site model used"); int numberOfBins = Integer.parseInt(siteRatesModels.replaceFirst("M0_omega~Beta\\(","").replaceFirst("\\)", "")); System.out.println(" + M7 n value: " + numberOfBins); Parameter m7BetaMu = new Parameter.Default(Double.parseDouble(tree.getAttribute("beta_mu").toString())); Parameter m7BetaVarMu = new Parameter.Default(Double.parseDouble(tree.getAttribute("beta_Var/mu").toString())); //Parameter m7BetaMu = new Parameter.Default((Double) tree.getAttribute("beta_mu")); //Parameter m7BetaVarMu = new Parameter.Default((Double) tree.getAttribute("beta_Var/mu")); System.err.println("Sorry, M7 substitution model is not yet implemented in BEAST"); System.exit(0); } } else if(siteRatesModels.length() > 0) { /* i.e. for other data types. */ /* Do gamma/lognormal + pinv */ Parameter pInvParameter = null; int categories = -1; Parameter alphaParameter = null; //System.out.println("Greatest story ever told! " + siteRatesModels); if(siteRatesModels.indexOf("+INV") >= 0) { System.out.println("Site model - proportion of invariable sites used"); //pInvParameter = new Parameter.Default(((Double) tree.getAttribute("INV_p")).doubleValue()); pInvParameter = new Parameter.Default(Double.parseDouble(tree.getAttribute("INV_p").toString())); } if(siteRatesModels.indexOf("+rate~Gamma(") >= 0) { System.out.println("Site model - gamma site rate heterogeneity used"); categories = Integer.parseInt(siteRatesModels.replaceFirst(".+rate~Gamma\\(", "").replaceFirst("\\).*","")); //double sigmaMu = (Double) tree.getAttribute("gamma_sigma/mu"); double sigmaMu = Double.parseDouble(tree.getAttribute("gamma_sigma/mu").toString()); sigmaMu = (1.0/sigmaMu) * (1.0/sigmaMu); /* BAli-Phy is parameterised by sigma/mu instead of alpha */ alphaParameter = new Parameter.Default(sigmaMu); } else if(siteRatesModels.indexOf("+rate~LogNormal(") >= 0) { // TODO implement lognormal site model System.out.println("Site model - lognormal site rate heterogeneity used"); System.err.println("Sorry, lognormal site rates are not yet implemented in BEAST"); System.exit(0); categories = Integer.parseInt(siteRatesModels.replaceFirst(".+rate~LogNormal\\(", "").replaceFirst("\\).*","")); //double sigmaMu = (Double) tree.getAttribute("log-normal_sigma/mu"); double sigmaMu = Double.parseDouble(tree.getAttribute("log-normal_sigma/mu").toString()); sigmaMu = (1.0/sigmaMu) * (1.0/sigmaMu); /* BAli-Phy is parameterised by sigma/mu instead of alpha */ alphaParameter = new Parameter.Default(sigmaMu); } else if(siteRatesModels.indexOf("+GAMMA(") >= 0) { /* For BEAST output */ System.out.println("Site model - gamma site rate heterogeneity used"); categories = Integer.parseInt(siteRatesModels.replaceFirst(".+GAMMA\\(", "").replaceFirst("\\).*","")); //double sigmaMu = (Double) tree.getAttribute("gamma_sigma/mu"); double alpha = Double.parseDouble(tree.getAttribute("alpha").toString()); alphaParameter = new Parameter.Default(alpha); } //System.out.println("alpha and pinv parameters: " + alphaParameter.getParameterValue(0) + "\t" + pInvParameter.getParameterValue(0)); //GammaSiteRateModel siteModel = new GammaSiteRateModel(sml.getSubstitutionModel(), new Parameter.Default(1.0), alphaParameter, categories, pInvParameter); GammaSiteRateModel siteModel = new GammaSiteRateModel(GammaSiteModelParser.SITE_MODEL, new Parameter.Default(1.0), alphaParameter, categories, pInvParameter); siteModel.setSubstitutionModel(sml.getSubstitutionModel()); //SiteModel siteModel = new GammaSiteModel(sml.getSubstitutionModel(), new Parameter.Default(1.0), new Parameter.Default(1.0), 1, new Parameter.Default(0.5)); //SiteModel siteModel = new GammaSiteModel(sml.getSubstitutionModel(), null, null, 0, null); return siteModel; } /* Default with no gamma or pinv */ //SiteRateModel siteModel = new GammaSiteRateModel(sml.getSubstitutionModel()); GammaSiteRateModel siteModel = new GammaSiteRateModel(GammaSiteModelParser.SITE_MODEL); siteModel.setSubstitutionModel(sml.getSubstitutionModel()); return siteModel; } public static final String KAPPA_STRING = "kappa"; //public static final String SEQ_STRING = "states"; // For BEAST input files public static String SEQ_STRING = "seq"; public static final String NEW_SEQ = "newSeq"; public static final String TAG = "tag"; public static final String LIKELIHOOD = "lnL"; public static final String SUBST_MODEL = "subst"; // public static final String WAG_STRING = "Empirical(Data/wag.dat)*pi"; private final int die = 0; private Tree processTree(Tree tree) { // Remake tree to fix node ordering - Marc GammaSiteRateModel siteModel = loadSiteModel(tree); SimpleAlignment alignment = new SimpleAlignment(); alignment.setDataType(siteModel.getSubstitutionModel().getDataType()); if(siteModel.getSubstitutionModel().getDataType().getClass().equals(Codons.class)) { //System.out.println("trololo"); alignment.setDataType(Nucleotides.INSTANCE); } //System.out.println("BOO BOO " + siteModel.getSubstitutionModel().getDataType().getClass().getName()+"\t" + Codons.UNIVERSAL.getClass().getName() + "\t" + alignment.getDataType().getClass().getName()); // Get sequences String[] sequence = new String[tree.getNodeCount()]; for (int i = 0; i < tree.getNodeCount(); i++) { NodeRef node = tree.getNode(i); sequence[i] = (String) tree.getNodeAttribute(node, SEQ_STRING); if (tree.isExternal(node)) { Taxon taxon = tree.getNodeTaxon(node); alignment.addSequence(new Sequence(taxon, sequence[i])); } } // Make evolutionary model BranchRateModel rateModel = new StrictClockBranchRates(new Parameter.Default(1.0)); FlexibleTree flexTree; if(siteModel.getSubstitutionModel().getDataType().getClass().equals(Codons.class)) { ConvertAlignment convertAlignment = new ConvertAlignment(siteModel.getSubstitutionModel().getDataType(), ((Codons) siteModel.getSubstitutionModel().getDataType()).getGeneticCode(), alignment); flexTree = sampleTree(tree, convertAlignment, siteModel, rateModel); //flexTree = sampleTree(tree, alignment, siteModel, rateModel); } else { flexTree = sampleTree(tree, alignment, siteModel, rateModel); } introduceGaps(flexTree, tree); return flexTree; } private void introduceGaps(FlexibleTree flexTree, Tree gapTree) { // I forget what this function was supposed to do. - Marc } public static final char GAP = '-'; boolean[] bit = null; private FlexibleTree sampleTree(Tree tree, PatternList alignment, GammaSiteRateModel siteModel, BranchRateModel rateModel) { FlexibleTree flexTree = new FlexibleTree(tree, true); flexTree.adoptTreeModelOrdering(); FlexibleTree finalTree = new FlexibleTree(tree); finalTree.adoptTreeModelOrdering(); TreeModel treeModel = new TreeModel(tree); // Turn off noisy logging by TreeLikelihood constructor Logger logger = Logger.getLogger("dr.evomodel"); boolean useParentHandlers = logger.getUseParentHandlers(); logger.setUseParentHandlers(false); // AncestralStateTreeLikelihood likelihood = new AncestralStateTreeLikelihood( // alignment, // treeModel, // siteModel, // rateModel, // false, true, // alignment.getDataType(), // TAG, // false); AncestralStateBeagleTreeLikelihood likelihood = new AncestralStateBeagleTreeLikelihood( alignment, treeModel, new HomogenousBranchSubstitutionModel(siteModel.getSubstitutionModel(), siteModel.getSubstitutionModel().getFrequencyModel()), siteModel, rateModel, false, PartialsRescalingScheme.DEFAULT, null, alignment.getDataType(), TAG, siteModel.getSubstitutionModel(), false, true ); // PatternList patternList, TreeModel treeModel, // BranchSiteModel branchSiteModel, // SiteRateModel siteRateModel, // BranchRateModel branchRateModel, // boolean useAmbiguities, // PartialsRescalingScheme scalingScheme, // Map<Set<String>, Parameter> partialsRestrictions, // final DataType dataType, // final String tag, // SubstitutionModel substModel, // boolean useMAP, // boolean returnML) { // PatternList patternList, TreeModel treeModel, // SiteModel siteModel, BranchRateModel branchRateModel, // boolean useAmbiguities, boolean storePartials, // final DataType dataType, // final String tag, // boolean forceRescaling, // boolean useMAP, // boolean returnML) { logger.setUseParentHandlers(useParentHandlers); // Sample internal nodes likelihood.makeDirty(); double logLikelihood = likelihood.getLogLikelihood(); System.out.println("The new and old Likelihood (this value should be roughly the same, debug?): " + logLikelihood + ", " + Double.parseDouble(tree.getAttribute(LIKELIHOOD).toString())); if(Double.parseDouble(tree.getAttribute(LIKELIHOOD).toString()) != logLikelihood) { /* Newly written check, not sure if this is correct. May need to round values at least */ //throw new RuntimeException("The values of likelihood are not identical"); } // System.err.printf("New logLikelihood = %4.1f\n", logLikelihood); flexTree.setAttribute(LIKELIHOOD, logLikelihood); TreeTrait ancestralStates = likelihood.getTreeTrait(TAG); for (int i = 0; i < treeModel.getNodeCount(); i++) { NodeRef node = treeModel.getNode(i); //System.out.println(treeModel.toString() + " booyaka " + node.toString()); //dd String sample = ancestralStates.getTraitString(treeModel, node); //System.out.println("ittebayo " + sample); //dd String oldSeq = (String) flexTree.getNodeAttribute(flexTree.getNode(i), SEQ_STRING); if (oldSeq != null) { char[] seq = (sample.substring(1, sample.length() - 1)).toCharArray(); int length = oldSeq.length(); for (int j = 0; j < length; j++) { if (oldSeq.charAt(j) == GAP) seq[j] = GAP; } String newSeq = new String(seq); // if( newSeq.contains("MMMMMMM") ) { // System.err.println("bad = "+newSeq); // System.exit(-1); finalTree.setNodeAttribute(finalTree.getNode(i), NEW_SEQ, newSeq); } // Taxon taxon = finalTree.getNodeTaxon(finalTree.getNode(i)); // System.err.println("node: "+(taxon == null ? "null" : taxon.getId())+" "+ // finalTree.getNodeAttribute(finalTree.getNode(i),NEW_SEQ)); } return finalTree; } private void setupAttributes(Tree tree) { for (int i = 0; i < tree.getNodeCount(); i++) { NodeRef node = tree.getNode(i); Iterator iter = tree.getNodeAttributeNames(node); if (iter != null) { while (iter.hasNext()) { String name = (String) iter.next(); if (!attributeNames.contains(name)) attributeNames.add(name); } } } } private void setupTreeAttributes(Tree tree) { Iterator<String> iter = tree.getAttributeNames(); if (iter != null) { while (iter.hasNext()) { String name = iter.next(); treeAttributeNames.add(name); } } } private void addTreeAttributes(Tree tree) { if (treeAttributeNames != null) { if (treeAttributeLists == null) { treeAttributeLists = new List[treeAttributeNames.size()]; for (int i = 0; i < treeAttributeNames.size(); i++) { treeAttributeLists[i] = new ArrayList(); } } for (int i = 0; i < treeAttributeNames.size(); i++) { String attributeName = treeAttributeNames.get(i); Object value = tree.getAttribute(attributeName); if (value != null) { treeAttributeLists[i].add(value); } } } } private Tree summarizeTrees(int burnin, CladeSystem cladeSystem, String inputFileName, boolean useSumCladeCredibility) throws IOException { Tree bestTree = null; double bestScore = Double.NEGATIVE_INFINITY; // System.out.println("Analyzing " + totalTreesUsed + " trees..."); // System.out.println("0 25 50 75 100"); int stepSize = totalTrees / 60; if (stepSize < 1) stepSize = 1; int counter = 0; TreeImporter importer = new NexusImporter(new FileReader(inputFileName)); try { while (importer.hasTree()) { Tree tree = importer.importNextTree(); if (counter >= burnin) { double score = scoreTree(tree, cladeSystem, useSumCladeCredibility); // System.out.println(score); if (score > bestScore) { bestTree = tree; bestScore = score; } } if (counter > 0 && counter % stepSize == 0) { // System.out.print("*"); // System.out.flush(); } counter++; } } catch (Importer.ImportException e) { System.err.println("Error Parsing Input Tree: " + e.getMessage()); return null; } // System.out.println(); // System.out.println(); if (useSumCladeCredibility) { System.out.println("\tHighest Sum Clade Credibility: " + bestScore); } else { System.out.println("\tHighest Log Clade Credibility: " + bestScore); } return bestTree; } private double scoreTree(Tree tree, CladeSystem cladeSystem, boolean useSumCladeCredibility) { if (useSumCladeCredibility) { return cladeSystem.getSumCladeCredibility(tree, tree.getRoot(), null); } else { return cladeSystem.getLogCladeCredibility(tree, tree.getRoot(), null); } } private class CladeSystem { // Public stuff public CladeSystem() { } /** * adds all the clades in the tree */ public void add(Tree tree) { if (taxonList == null) { taxonList = tree; } // Recurse over the tree and add all the clades (or increment their // frequency if already present). The root clade is added too (for // annotation purposes). addClades(tree, tree.getRoot(), null); addTreeAttributes(tree); } public Map<BitSet, Clade> getCladeMap() { return cladeMap; } public Clade getClade(NodeRef node) { return null; } private void addClades(Tree tree, NodeRef node, BitSet bits) { BitSet bits2 = new BitSet(); if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits2.set(index); } else { for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); addClades(tree, node1, bits2); } } addClade(bits2, tree, node); if (bits != null) { bits.or(bits2); } } private void addClade(BitSet bits, Tree tree, NodeRef node) { Clade clade = cladeMap.get(bits); if (clade == null) { clade = new Clade(bits); cladeMap.put(bits, clade); } clade.setCount(clade.getCount() + 1); if (attributeNames != null) { if (clade.attributeLists == null) { clade.attributeLists = new List[attributeNames.size()]; for (int i = 0; i < attributeNames.size(); i++) { clade.attributeLists[i] = new ArrayList(); } } for (int i = 0; i < attributeNames.size(); i++) { String attributeName = attributeNames.get(i); Object value; if (attributeName.equals("height")) { value = tree.getNodeHeight(node); } else if (attributeName.equals("length")) { value = tree.getBranchLength(node); } else { value = tree.getNodeAttribute(node, attributeName); } //if (value == null) { // System.out.println("attribute " + attributeNames[i] + " is null."); if (value != null) { clade.attributeLists[i].add(value); } } } } public void calculateCladeCredibilities(int totalTreesUsed) { for (Clade clade : cladeMap.values()) { clade.setCredibility(((double) clade.getCount()) / totalTreesUsed); } } public double getSumCladeCredibility(Tree tree, NodeRef node, BitSet bits) { double sum = 0.0; if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits.set(index); } else { BitSet bits2 = new BitSet(); for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); sum += getSumCladeCredibility(tree, node1, bits2); } sum += getCladeCredibility(bits2); if (bits != null) { bits.or(bits2); } } return sum; } public double getLogCladeCredibility(Tree tree, NodeRef node, BitSet bits) { double logCladeCredibility = 0.0; if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits.set(index); } else { BitSet bits2 = new BitSet(); for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); logCladeCredibility += getLogCladeCredibility(tree, node1, bits2); } logCladeCredibility += Math.log(getCladeCredibility(bits2)); if (bits != null) { bits.or(bits2); } } return logCladeCredibility; } private double getCladeCredibility(BitSet bits) { Clade clade = cladeMap.get(bits); if (clade == null) { return 0.0; } return clade.getCredibility(); } public void annotateTree(MutableTree tree, NodeRef node, BitSet bits, int heightsOption) { BitSet bits2 = new BitSet(); if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits2.set(index); annotateNode(tree, node, bits2, true, heightsOption); } else { for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); annotateTree(tree, node1, bits2, heightsOption); } annotateNode(tree, node, bits2, false, heightsOption); } if (bits != null) { bits.or(bits2); } } private void annotateNode(MutableTree tree, NodeRef node, BitSet bits, boolean isTip, int heightsOption) { Clade clade = cladeMap.get(bits); if (clade == null) { throw new RuntimeException("Clade missing"); } // System.err.println("annotateNode new: "+bits.toString()+" size = "+attributeNames.size()); // for(String string : attributeNames) { // System.err.println(string); // System.exit(-1); boolean filter = false; if (!isTip) { double posterior = clade.getCredibility(); tree.setNodeAttribute(node, "posterior", posterior); if (posterior < posteriorLimit) { filter = true; } } for (int i = 0; i < attributeNames.size(); i++) { String attributeName = attributeNames.get(i); // System.err.println(attributeName); double[] values = new double[clade.attributeLists[i].size()]; HashMap<String, Integer> hashMap = new HashMap<String, Integer>(clade.attributeLists[i].size()); // Hashtable hashMap = new Hashtable(clade.attributeLists[i].size()); if (values.length > 0) { Object v = clade.attributeLists[i].get(0); boolean isHeight = attributeName.equals("height"); boolean isBoolean = v instanceof Boolean; boolean isDiscrete = v instanceof String; double minValue = Double.MAX_VALUE; double maxValue = -Double.MAX_VALUE; for (int j = 0; j < clade.attributeLists[i].size(); j++) { if (isDiscrete) { String value = (String) clade.attributeLists[i].get(j); if (value.startsWith("\"")) { value = value.replaceAll("\"", ""); } if (attributeName.equals(NEW_SEQ)) { // Strip out gaps before storing value = value.replaceAll("-", ""); } if (hashMap.containsKey(value)) { int count = hashMap.get(value); hashMap.put(value, count + 1); } else { hashMap.put(value, 1); } // if( tree.getNodeTaxon(node) != null && // tree.getNodeTaxon(node).getId().compareTo("Calanus") == 0) { // System.err.println(value); } else if (isBoolean) { values[j] = (((Boolean) clade.attributeLists[i].get(j)) ? 1.0 : 0.0); } else { values[j] = ((Number) clade.attributeLists[i].get(j)).doubleValue(); if (values[j] < minValue) minValue = values[j]; if (values[j] > maxValue) maxValue = values[j]; } } if (isHeight) { if (heightsOption == MEAN_HEIGHTS) { double mean = DiscreteStatistics.mean(values); tree.setNodeHeight(node, mean); } else if (heightsOption == MEDIAN_HEIGHTS) { double median = DiscreteStatistics.median(values); tree.setNodeHeight(node, median); } else { // keep the existing height } } if (!filter) { if (!isDiscrete) annotateMeanAttribute(tree, node, attributeName, values); else annotateModeAttribute(tree, node, attributeName, hashMap); // if( tree.getNodeTaxon(node) != null && // tree.getNodeTaxon(node).getId().compareTo("Calanus") == 0) { // System.err.println("size = "+hashMap.keySet().size()); // System.err.println("count = "+hashMap.get(hashMap.keySet().toArray()[0])); // System.err.println(); if (!isBoolean && minValue < maxValue && !isDiscrete) { // Basically, if it is a boolean (0, 1) then we don't need the distribution information // Likewise if it doesn't vary. annotateMedianAttribute(tree, node, attributeName + "_median", values); annotateHPDAttribute(tree, node, attributeName + "_95%_HPD", 0.95, values); annotateRangeAttribute(tree, node, attributeName + "_range", values); } } } } } private void annotateMeanAttribute(MutableTree tree, NodeRef node, String label, double[] values) { double mean = DiscreteStatistics.mean(values); tree.setNodeAttribute(node, label, mean); } private void annotateMedianAttribute(MutableTree tree, NodeRef node, String label, double[] values) { double median = DiscreteStatistics.median(values); tree.setNodeAttribute(node, label, median); } public static final String fileName = "junk"; // public static final String execName = "/sw/bin/clustalw"; private int externalCalls = 0; private void annotateModeAttribute(MutableTree tree, NodeRef node, String label, HashMap<String, Integer> values) { if (label.equals(NEW_SEQ)) { // if( tree.isExternal(node) ) { // return; String consensusSeq = null; double[] support = null; int numElements = values.keySet().size(); // System.err.println("size = "+numElements); if (numElements > 1) { try { PrintWriter pw = new PrintWriter(new PrintStream(new FileOutputStream(fileName))); int i = 0; int[] weight = new int[numElements]; // Iterator iter = values.keySet().iterator(); for (String key : values.keySet()) { int thisCount = values.get(key); weight[i] = thisCount; pw.write(">" + i + " " + thisCount + "\n"); pw.write(key + "\n"); i++; } pw.close(); Process p = Runtime.getRuntime().exec(clustalExecutable + " " + fileName + " -OUTPUT=NEXUS"); BufferedReader input = new BufferedReader (new InputStreamReader(p.getInputStream())); { //String line; while ((/*line = */input.readLine()) != null) { // System.out.println(line); } } input.close(); externalCalls++; // System.err.println("clustal call #" + externalCalls); NexusImporter importer = new NexusImporter(new FileReader(fileName + ".nxs")); Alignment alignment = importer.importAlignment(); // build index int[] index = new int[numElements]; for (int j = 0; j < numElements; j++) index[j] = alignment.getTaxonIndex("" + j); StringBuffer sb = new StringBuffer(); support = new double[alignment.getPatternCount()]; // System.err.println(new dr.math.matrixAlgebra.Vector(weight)); for (int j = 0; j < alignment.getPatternCount(); j++) { int[] pattern = alignment.getPattern(j); // support[j] = appendNextConsensusCharacter(alignment,j,sb); // System.err.println(new dr.math.matrixAlgebra.Vector(pattern)); int[] siteWeight = new int[30]; // + 2 to handle ambiguous and gap int maxWeight = -1; int totalWeight = 0; int maxChar = -1; for (int k = 0; k < pattern.length; k++) { int whichChar = pattern[k]; if (whichChar < 30) { int addWeight = weight[index[k]]; siteWeight[whichChar] += addWeight; totalWeight += addWeight; // if( k >= alignment.getDataType().getStateCount()+2 ) { // System.err.println("k = "+k); // System.err.println("pattern = "+new dr.math.matrixAlgebra.Vector(pattern)); if (siteWeight[whichChar] > maxWeight) { maxWeight = siteWeight[whichChar]; maxChar = whichChar; } } else { System.err.println("BUG"); System.err.println("k = " + k); System.err.println("whichChar = " + whichChar); System.err.println("pattern = " + new dr.math.matrixAlgebra.Vector(pattern)); } } sb.append(alignment.getDataType().getChar(maxChar)); support[j] = (double) maxWeight / (double) totalWeight; } // System.err.println("cSeq = " + sb.toString()); consensusSeq = sb.toString(); // System.exit(-1); } catch (FileNotFoundException e) { System.err.println(e.getMessage()); System.exit(-1); } catch (Importer.ImportException e) { System.err.println(e.getMessage()); System.exit(-1); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(-1); } } else { consensusSeq = (String) values.keySet().toArray()[0]; support = new double[consensusSeq.length()]; for (int i = 0; i < support.length; i++) support[i] = 1.0; } // Trim out gaps from consensus and support // ArrayList<Double> newSupport = new ArrayList<Double>(support.length); boolean noComma = true; StringBuffer newSupport = new StringBuffer("{"); StringBuffer newSeq = new StringBuffer(); if (consensusSeq.length() != support.length) { System.err.println("What happened here?"); System.exit(-1); } for (int i = 0; i < support.length; i++) { if (consensusSeq.charAt(i) != GAP) { newSeq.append(consensusSeq.charAt(i)); if (noComma) noComma = false; else newSupport.append(","); newSupport.append(String.format("%1.3f", support[i])); } } newSupport.append("}"); tree.setNodeAttribute(node, label, newSeq); // String num = Str tree.setNodeAttribute(node, label + ".prob", newSupport); } else { String mode = null; int maxCount = 0; int totalCount = 0; for (String key : (String[]) values.keySet().toArray()) { int thisCount = values.get(key); if (thisCount == maxCount) mode = mode.concat("+" + key); else if (thisCount > maxCount) { mode = key; maxCount = thisCount; } totalCount += thisCount; } double freq = (double) maxCount / (double) totalCount; tree.setNodeAttribute(node, label, mode); tree.setNodeAttribute(node, label + ".prob", freq); } } // private double appendNextConsensusCharacter(Alignment alignment, int j, StringBuffer sb, int[] weight) { // int[] pattern = alignment.getPattern(j); // int[] siteWeight = new int[alignment.getDataType().getStateCount()]; // int maxWeight = -1; // int totalWeight = 0; // int maxChar = -1; // for (int k = 0; k < pattern.length; k++) { // int whichChar = pattern[k]; // if (whichChar < alignment.getDataType().getStateCount()) { // int addWeight = weight[index[k]]; // siteWeight[whichChar] += addWeight; // totalWeight += addWeight; // if (siteWeight[k] > maxWeight) { // maxWeight = siteWeight[k]; // maxChar = k; // sb.append(alignment.getDataType().getChar(maxChar)); // return (double) maxWeight / (double) totalWeight; private void annotateRangeAttribute(MutableTree tree, NodeRef node, String label, double[] values) { double min = DiscreteStatistics.min(values); double max = DiscreteStatistics.max(values); tree.setNodeAttribute(node, label, new Object[]{min, max}); } private void annotateHPDAttribute(MutableTree tree, NodeRef node, String label, double hpd, double[] values) { int[] indices = new int[values.length]; HeapSort.sort(values, indices); double minRange = Double.MAX_VALUE; int hpdIndex = 0; int diff = (int) Math.round(hpd * (double) values.length); for (int i = 0; i <= (values.length - diff); i++) { double minValue = values[indices[i]]; double maxValue = values[indices[i + diff - 1]]; double range = Math.abs(maxValue - minValue); if (range < minRange) { minRange = range; hpdIndex = i; } } double lower = values[indices[hpdIndex]]; double upper = values[indices[hpdIndex + diff - 1]]; tree.setNodeAttribute(node, label, new Object[]{lower, upper}); } class Clade { public Clade(BitSet bits) { this.bits = bits; count = 0; credibility = 0.0; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public double getCredibility() { return credibility; } public void setCredibility(double credibility) { this.credibility = credibility; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final Clade clade = (Clade) o; return !(bits != null ? !bits.equals(clade.bits) : clade.bits != null); } public int hashCode() { return (bits != null ? bits.hashCode() : 0); } int count; double credibility; BitSet bits; List[] attributeLists = null; } // Private stuff TaxonList taxonList = null; Map<BitSet, Clade> cladeMap = new HashMap<BitSet, Clade>(); } int totalTrees = 0; int totalTreesUsed = 0; double posteriorLimit = 0.0; String clustalExecutable = null; List<String> attributeNames = new ArrayList<String>(); List<String> treeAttributeNames = new ArrayList<String>(); List[] treeAttributeLists = null; TaxonList taxa = null; public static void printTitle() { System.out.println(); centreLine("Ancestral Sequence Annotator " + "v0.1" + ", " + "2008", 60); // version.getVersionString() + ", " + version.getDateString(), 60); System.out.println(); centreLine("by", 60); System.out.println(); centreLine("Marc A. Suchard, Wai Lok Sibon Li", 60); System.out.println(); centreLine("Departments of Biomathematics,", 60); centreLine("Biostatistics and Human Genetics", 60); centreLine("UCLA", 60); centreLine("msuchard@ucla.edu", 60); System.out.println(); System.out.println(); System.out.println("NB: I stole a substantial portion of this code from Andrew Rambaut."); System.out.println(" Please also give him due credit."); System.out.println(); } public static void centreLine(String line, int pageWidth) { int n = pageWidth - line.length(); int n1 = n / 2; for (int i = 0; i < n1; i++) { System.out.print(" "); } System.out.println(line); } public static void printUsage(Arguments arguments) { arguments.printUsage("ancestralsequenceannotator", "<input-file-name> <output-file-name>"); System.out.println(); System.out.println(" Example: ancestralsequenceannotator test.trees out.txt"); System.out.println(); } //Main method public static void main(String[] args) throws IOException { String targetTreeFileName = null; String inputFileName = null; String outputFileName = null; printTitle(); Arguments arguments = new Arguments( new Arguments.Option[]{ //new Arguments.StringOption("target", new String[] { "maxclade", "maxtree" }, false, "an option of 'maxclade' or 'maxtree'"), new Arguments.StringOption("heights", new String[]{"keep", "median", "mean"}, false, "an option of 'keep', 'median' or 'mean'"), new Arguments.IntegerOption("burnin", "the number of states to be considered as 'burn-in'"), new Arguments.StringOption("beastInput", new String[]{"true", "false"}, false, "If the input is taken from BEAST rather than BAli-Phy"), new Arguments.RealOption("limit", "the minimum posterior probability for a node to be annotated"), new Arguments.StringOption("target", "target_file_name", "specifies a user target tree to be annotated"), new Arguments.Option("help", "option to print this message"), new Arguments.StringOption("clustal", "full_path_to_clustal", "specifies full path to the clustal executable file") }); try { arguments.parseArguments(args); } catch (Arguments.ArgumentException ae) { System.out.println(ae); printUsage(arguments); System.exit(1); } if (arguments.hasOption("help")) { printUsage(arguments); System.exit(0); } int heights = KEEP_HEIGHTS; if (arguments.hasOption("heights")) { String value = arguments.getStringOption("heights"); if (value.equalsIgnoreCase("mean")) { heights = MEAN_HEIGHTS; } else if (value.equalsIgnoreCase("median")) { heights = MEDIAN_HEIGHTS; } } int burnin = -1; if (arguments.hasOption("burnin")) { burnin = arguments.getIntegerOption("burnin"); } double posteriorLimit = 0.0; if (arguments.hasOption("limit")) { posteriorLimit = arguments.getRealOption("limit"); } boolean beastInput = false; if(arguments.hasOption("beastInput") && arguments.getStringOption("beastInput").equals("true")) { SEQ_STRING = "states"; } int target = MAX_CLADE_CREDIBILITY; if (arguments.hasOption("target")) { target = USER_TARGET_TREE; targetTreeFileName = arguments.getStringOption("target"); } String clustalExecutable = "/usr/local/bin/clustalw"; if (arguments.hasOption("clustal")) { clustalExecutable = arguments.getStringOption("clustal"); } String[] args2 = arguments.getLeftoverArguments(); if (args2.length > 2) { System.err.println("Unknown option: " + args2[2]); System.err.println(); printUsage(arguments); System.exit(1); } if (args2.length == 2) { targetTreeFileName = null; inputFileName = args2[0]; outputFileName = args2[1]; } else { if (inputFileName == null) { // No input file name was given so throw up a dialog box... inputFileName = Utils.getLoadFileName("AncestralSequenceAnnotator " + version.getVersionString() + " - Select input file file to analyse"); } if (outputFileName == null) { outputFileName = Utils.getSaveFileName("AncestralSequenceAnnotator " + version.getVersionString() + " - Select output file"); } } if(inputFileName == null || outputFileName == null) { System.err.println("Missing input or output file name"); printUsage(arguments); System.exit(1); } new AncestralSequenceAnnotator(burnin, heights, posteriorLimit, target, targetTreeFileName, inputFileName, outputFileName, clustalExecutable); System.exit(0); } }
package edu.ucla.cens.awserver.util; /** * A collection of methods for manipulating or validating strings. * * @author selsky */ public final class StringUtils { private StringUtils() { } /** * Checks for a null or empty (zero-length or all whitespace) String. * * A method with the same signature and behavior as this one exists in the MySQL JDBC code. That method is not used outside * of the data layer of this application in order to avoid unnecessary dependencies i.e., AW utility classes should not * depend on a third-party data access lib. * * @return true if the String is null, empty, or all whitespace * false otherwise */ public static boolean isEmptyOrWhitespaceOnly(String string) { return null == string || "".equals(string.trim()); } public static String retrieveSubdomainFromUrlString(String url) { if(isEmptyOrWhitespaceOnly(url)) { throw new IllegalArgumentException("cannot retrieve subdomain from a null or empty URL String"); } String urlStart = url.split("\\.")[0]; String subdomain = null; if(urlStart.startsWith("http: subdomain = urlStart.substring(7); // enable https support when we enable it in the app server config // subdomain = urlStart.substring(8); } else { // if this happens, the application server is configured to support an unknown protocol // and this method needs updating throw new IllegalArgumentException("unknown protocol: " + url); } return subdomain; } public static String retrieveServerNameFromUrlString(String url) { if(isEmptyOrWhitespaceOnly(url)) { throw new IllegalArgumentException("cannot retrieve server name from a null or empty URL String"); } return url.split("\\.")[1]; } /** * Converts an array of ints to a string of the form {n,n,n}. A null array will return the string null. * * TODO replace calls to this method with Arrays.toString() */ public static String intArrayToString(int[] array) { StringBuilder builder = new StringBuilder(); if(null == array) { builder.append("null"); } else { builder.append("{"); for(int i = 0; i < array.length; i++) { builder.append(array[i]); if(i < array.length - 1) { builder.append(","); } } builder.append("}"); } return builder.toString(); } }
package edu.wustl.xipHost.application; import java.awt.Color; import java.awt.Dimension; import java.util.UUID; import javax.swing.Icon; import javax.swing.JButton; /** * @author Jaroslaw Krych * */ public class AppButton extends JButton{ Color xipColor = new Color(51, 51, 102); public AppButton(String text, Icon icon){ super(text, icon); setBackground(xipColor); setPreferredSize(); } UUID appUUID; public void setApplicationUUID(UUID uuid){ appUUID = uuid; } public UUID getApplicationUUID(){ return appUUID; } public void setAppButtonTextAndIcon(String text, Icon icon){ setText(text); setIcon(icon); setPreferredSize(); } void setPreferredSize(){ double preferredWidth = getPreferredSize().getWidth(); if(preferredWidth < 100){ setPreferredSize(new Dimension(100, 25)); } else { setPreferredSize(new Dimension((int)preferredWidth, 25)); } } }
package enterpriseapp.ui.reports; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.Collection; import java.util.List; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRExporter; import net.sf.jasperreports.engine.JRExporterParameter; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.export.JRCsvExporter; import net.sf.jasperreports.engine.export.JRHtmlExporter; import net.sf.jasperreports.engine.export.JRHtmlExporterParameter; import net.sf.jasperreports.engine.export.JRPdfExporter; import net.sf.jasperreports.engine.export.JRRtfExporter; import net.sf.jasperreports.engine.export.JRXhtmlExporter; import net.sf.jasperreports.engine.export.JRXmlExporter; import net.sf.jasperreports.engine.export.oasis.JROdsExporter; import net.sf.jasperreports.engine.export.oasis.JROdtExporter; import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter; import net.sf.jasperreports.engine.export.ooxml.JRPptxExporter; import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter; import net.sf.jasperreports.j2ee.servlets.ImageServlet; import org.vaadin.hene.popupbutton.PopupButton; import org.vaadin.hene.splitbutton.SplitButton; import org.vaadin.hene.splitbutton.SplitButton.SplitButtonClickEvent; import org.vaadin.hene.splitbutton.SplitButton.SplitButtonClickListener; import ar.com.fdvs.dj.core.DynamicJasperHelper; import ar.com.fdvs.dj.core.layout.ClassicLayoutManager; import ar.com.fdvs.dj.domain.Style; import ar.com.fdvs.dj.domain.builders.ColumnBuilder; import ar.com.fdvs.dj.domain.builders.ColumnBuilderException; import ar.com.fdvs.dj.domain.builders.DynamicReportBuilder; import ar.com.fdvs.dj.domain.builders.FastReportBuilder; import ar.com.fdvs.dj.domain.builders.GroupBuilder; import ar.com.fdvs.dj.domain.builders.StyleBuilder; import ar.com.fdvs.dj.domain.constants.Font; import ar.com.fdvs.dj.domain.constants.GroupLayout; import ar.com.fdvs.dj.domain.constants.HorizontalAlign; import ar.com.fdvs.dj.domain.constants.Page; import ar.com.fdvs.dj.domain.entities.columns.AbstractColumn; import ar.com.fdvs.dj.domain.entities.columns.PropertyColumn; import ar.com.fdvs.dj.domain.entities.conditionalStyle.ConditionalStyle; import com.vaadin.terminal.StreamResource; import com.vaadin.terminal.UserError; import com.vaadin.terminal.gwt.server.WebApplicationContext; import com.vaadin.ui.Accordion; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.CheckBox; import com.vaadin.ui.Component; import com.vaadin.ui.CustomComponent; import com.vaadin.ui.GridLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.HorizontalSplitPanel; import com.vaadin.ui.Label; import com.vaadin.ui.Panel; import com.vaadin.ui.TextField; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.themes.BaseTheme; import enterpriseapp.Utils; import enterpriseapp.ui.Constants; /** * @author Alejandro Duarte * */ public abstract class AbstractReport extends CustomComponent implements ClickListener, SplitButtonClickListener { private static final long serialVersionUID = 1L; protected HorizontalSplitPanel layout; protected VerticalLayout leftLayout = new VerticalLayout(); protected HorizontalLayout displayLayout; protected Button refreshButton; protected PopupButton columnsButton; protected PopupButton groupingButton; protected SplitButton exportButton; protected Button pdfButton; protected Button excelButton; protected Button wordButton; protected Button powerPointButton; protected Button odsButton; protected Button odtButton; protected Button rtfButton; protected Button htmlButton; protected Button csvButton; protected Button xmlButton; protected Accordion accordion; protected CheckBox printBackgroundOnOddRowsCheckBox; protected CheckBox printColumnNamesCheckBox; protected CheckBox stretchWithOverflowCheckBox; protected TextField columnsPerPageTextField; protected TextField pageWidthTextField; protected TextField pageHeightTextField; protected TextField marginTopTextField; protected TextField marginBottomTextField; protected TextField marginLeftTextField; protected TextField marginRightTextField; protected CheckBox[] columnsCheckBoxes; protected CheckBox[] groupingCheckBoxes; protected VerticalLayout observationsLayout; protected Label observationsLabel; protected boolean showObservations = false; public AbstractReport() { } @Override public void attach() { super.attach(); initLayout(); build(); } public abstract void updateReport() throws UnsupportedEncodingException; /** * @return property names that correspond to the objects returned by getData(). Each instance returned by * getData() must have a getter for each property returned by this method. */ public abstract String[] getColumnProperties(); /** * @return property classes that correspond to the objects returned by getData() according to getColumnProperties(). */ public abstract Class<?>[] getColumnClasses(); /** * @return titles to use on the table. */ public abstract String[] getColumnTitles(); /** * Collection of rows to show on the table. Each object in the collection must define a getter for each String returned * in getColumnProperties(). */ public abstract Collection<?> getData(); /** * @return A custom component to add to the accordion component. You can use it to add custom filtering or configuration * to the report. Return null if no component is needed. */ public abstract Component getParametersComponent(); public Integer[] getColumnWidths() { return null; }; public String getFileName() { return "report"; }; public void configureColumn(String property, AbstractColumn column, DynamicReportBuilder reportBuilder) {}; public void configureColumnBuilder(String property, ColumnBuilder columnBuilder, DynamicReportBuilder reportBuilder) {}; public boolean getDefalutColumnCheckBox(String property) { return true; }; public String getColumnPattern(String property) { return null; }; public Style getColumnStyle(String property) { return null; }; public List<ConditionalStyle> getColumnConditionalStyle(String property) { return null; }; public static int mmToPoints(float f) { return Math.round(f / 25.4f * 72); // 1in = 25.4mm = 72pt } public DynamicReportBuilder getReportBuilder() { FastReportBuilder reportBuilder = new FastReportBuilder(); reportBuilder.setWhenNoData(Constants.uiEmptyReport, null); reportBuilder.setPrintBackgroundOnOddRows((Boolean) printBackgroundOnOddRowsCheckBox.getValue()); reportBuilder.setPrintColumnNames((Boolean) printColumnNamesCheckBox.getValue()); reportBuilder.setUseFullPageWidth(true); try { Integer top = mmToPoints(new Float(marginTopTextField.getValue().toString())); Integer bottom = mmToPoints(new Float(marginBottomTextField.getValue().toString())); Integer left = mmToPoints(new Float(marginLeftTextField.getValue().toString())); Integer right = mmToPoints(new Float(marginRightTextField.getValue().toString())); Page page = new Page(); page.setWidth(mmToPoints(new Float(pageWidthTextField.getValue().toString()))); page.setHeight(mmToPoints(new Float(pageHeightTextField.getValue().toString()))); if(page.getHeight() < 140 + top + bottom || page.getWidth() < left + right || page.getHeight() < 1 || page.getWidth() < 1 || top < 0 || bottom < 0 || left < 0 || right < 0) { throw new NumberFormatException(); } reportBuilder.setPageSizeAndOrientation(page); reportBuilder.setColumnsPerPage(new Integer(columnsPerPageTextField.getValue().toString())); reportBuilder.setMargins(top, bottom, left, right); } catch(NumberFormatException e) { refreshButton.setComponentError(new UserError(Constants.uiReportConfigurationError)); } return reportBuilder; } public void buildColumns(DynamicReportBuilder reportBuilder) { try { String[] title = getColumnTitles(); String[] property = getColumnProperties(); Class<?>[] clazz = getColumnClasses(); Integer[] width = getColumnWidths(); for(int i = 0; i < property.length; i++) { if(columnsCheckBoxes[i].booleanValue()) { ColumnBuilder columnBuilder = ColumnBuilder.getNew(); columnBuilder.setColumnProperty(property[i], clazz[i]); columnBuilder.setTitle(title[i]); if(width != null && width[i] != null) { columnBuilder.setWidth(width[i]); } String columnPattern = getColumnPattern(property[i]); if(columnPattern != null) { columnBuilder.setPattern(columnPattern); } Style columnStyle = null; if(groupingCheckBoxes[i].booleanValue()) { columnStyle = new StyleBuilder(true).setHorizontalAlign(HorizontalAlign.LEFT).setFont(Font.ARIAL_MEDIUM_BOLD).setPaddingBottom(mmToPoints(5)).setPaddingTop(mmToPoints(10)).build(); } else { columnStyle = getColumnStyle(property[i]); } if(columnStyle == null) { columnStyle = new StyleBuilder(true).setStretchWithOverflow(stretchWithOverflowCheckBox.booleanValue()).build(); columnBuilder.setTruncateSuffix("..."); } columnBuilder.setStyle(columnStyle); List<ConditionalStyle> conditionalStyle = getColumnConditionalStyle(property[i]); if(conditionalStyle != null) { columnBuilder.addConditionalStyles(conditionalStyle); } configureColumnBuilder(property[i], columnBuilder, reportBuilder); AbstractColumn column = columnBuilder.build(); reportBuilder.addColumn(column); configureColumn(property[i], column, reportBuilder); if(groupingCheckBoxes[i].booleanValue()) { GroupBuilder groupBuilder = new GroupBuilder(); groupBuilder.setCriteriaColumn((PropertyColumn) column); groupBuilder.setGroupLayout(GroupLayout.VALUE_IN_HEADER); reportBuilder.addGroup(groupBuilder.build()); } } } } catch (ColumnBuilderException e) { throw new RuntimeException(e); } } public String getLastVisiblePropertyName() { String[] columnProperties = getColumnProperties(); for(int i = columnProperties.length - 1; i >= 0; i if(columnsCheckBoxes[i].booleanValue()) { return columnProperties[i]; } } return null; } protected JRHtmlExporter getHtmlExporter() { JRHtmlExporter exporter = new JRHtmlExporter(); String random = "" + Math.random() * 1000.0; random = random.replace('.', '0').replace(',', '0'); exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, Utils.getWebContextPath(getApplication()) + "/image?r=" + random + "&image="); return exporter; } protected void build() { try { refreshButton.setComponentError(null); setObservations(""); layout.setFirstComponent(leftLayout); updateReport(); if(!getObservations().isEmpty()) { refreshButton.setComponentError(new UserError(Constants.uiSeeObservationsOnTheReport)); } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } protected ByteArrayOutputStream getOutputStream(JRExporter exporter) { ByteArrayOutputStream outputStream = null; try { DynamicReportBuilder reportBuilder = getReportBuilder(); buildColumns(reportBuilder); Collection<?> data = getData(); JasperPrint jasperPrint = DynamicJasperHelper.generateJasperPrint(reportBuilder.build(), new ClassicLayoutManager(), data); outputStream = new ByteArrayOutputStream(); WebApplicationContext context = (WebApplicationContext) getApplication().getContext(); context.getHttpSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream); exporter.exportReport(); outputStream.flush(); outputStream.close(); } catch (JRException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } return outputStream; } public void initLayout() { refreshButton = new Button(Constants.uiRefresh); pdfButton = new Button(Constants.uiPdf); excelButton = new Button(Constants.uiExcel); wordButton = new Button(Constants.uiWord); powerPointButton = new Button(Constants.uiPowerPoint); odsButton = new Button(Constants.uiOds); odtButton = new Button(Constants.uiOdt); rtfButton = new Button(Constants.uiRtf); htmlButton = new Button(Constants.uiHtml); csvButton = new Button(Constants.uiCsv); xmlButton = new Button(Constants.uiXml); pdfButton.setStyleName(BaseTheme.BUTTON_LINK); excelButton.setStyleName(BaseTheme.BUTTON_LINK); wordButton.setStyleName(BaseTheme.BUTTON_LINK); powerPointButton.setStyleName(BaseTheme.BUTTON_LINK); odsButton.setStyleName(BaseTheme.BUTTON_LINK); odtButton.setStyleName(BaseTheme.BUTTON_LINK); rtfButton.setStyleName(BaseTheme.BUTTON_LINK); htmlButton.setStyleName(BaseTheme.BUTTON_LINK); csvButton.setStyleName(BaseTheme.BUTTON_LINK); xmlButton.setStyleName(BaseTheme.BUTTON_LINK); refreshButton.addListener(this); pdfButton.addListener(this); excelButton.addListener(this); wordButton.addListener(this); powerPointButton.addListener(this); odsButton.addListener(this); odtButton.addListener(this); rtfButton.addListener(this); htmlButton.addListener(this); csvButton.addListener(this); xmlButton.addListener(this); VerticalLayout exportOptionsLayout = new VerticalLayout(); exportOptionsLayout.setSizeUndefined(); exportOptionsLayout.setSpacing(true); exportOptionsLayout.addComponent(pdfButton); exportOptionsLayout.addComponent(excelButton); exportOptionsLayout.addComponent(wordButton); exportOptionsLayout.addComponent(powerPointButton); exportOptionsLayout.addComponent(odsButton); exportOptionsLayout.addComponent(odtButton); exportOptionsLayout.addComponent(rtfButton); exportOptionsLayout.addComponent(htmlButton); exportOptionsLayout.addComponent(csvButton); exportOptionsLayout.addComponent(xmlButton); exportButton = new SplitButton(Constants.uiPdf); exportButton.setComponent(exportOptionsLayout); exportButton.addClickListener(this); String[] columnTitles = getColumnTitles(); columnsCheckBoxes = new CheckBox[columnTitles.length]; groupingCheckBoxes = new CheckBox[columnTitles.length]; VerticalLayout columnsLayout = new VerticalLayout(); columnsLayout.setSizeUndefined(); columnsLayout.setSpacing(true); VerticalLayout groupingLayout = new VerticalLayout(); groupingLayout.setSizeUndefined(); groupingLayout.setSpacing(true); for(int i = 0; i < columnTitles.length; i++) { CheckBox columnCheckBox = new CheckBox(columnTitles[i], true); columnCheckBox.setValue(getDefalutColumnCheckBox(getColumnProperties()[i])); columnsLayout.addComponent(columnCheckBox); columnsCheckBoxes[i] = columnCheckBox; CheckBox groupingCheckBox = new CheckBox(columnTitles[i], false); groupingLayout.addComponent(groupingCheckBox); groupingCheckBoxes[i] = groupingCheckBox; } columnsButton = new PopupButton(Constants.uiColumns); columnsButton.setComponent(columnsLayout); groupingButton = new PopupButton(Constants.uiGrouping); groupingButton.setComponent(groupingLayout); displayLayout = new HorizontalLayout(); displayLayout.setSpacing(true); displayLayout.addComponent(refreshButton); displayLayout.addComponent(columnsButton); displayLayout.addComponent(groupingButton); displayLayout.addComponent(exportButton); Panel exportPanel = new Panel(); exportPanel.addComponent(displayLayout); printBackgroundOnOddRowsCheckBox = new CheckBox(Constants.uiPrintBackgroundOnOddRows, true); printColumnNamesCheckBox = new CheckBox(Constants.uiPrintColumnNames); stretchWithOverflowCheckBox = new CheckBox(Constants.uiStretchWithOverflow); printColumnNamesCheckBox.setValue(true); columnsPerPageTextField = new TextField(Constants.uiColumnsPerPage); columnsPerPageTextField.setValue("1"); pageWidthTextField = new TextField(Constants.uiPageWidth); pageWidthTextField.setValue(Constants.reportPageWidth); pageHeightTextField = new TextField(Constants.uiPageHeight); pageHeightTextField.setValue(Constants.reportPageHeight); marginTopTextField = new TextField(Constants.uiMarginTop); marginTopTextField.setValue(Constants.reportMarginTop); marginTopTextField.setWidth("115px"); marginBottomTextField = new TextField(Constants.uiMarginBottom); marginBottomTextField.setValue(Constants.reportMarginBottom); marginBottomTextField.setWidth("115px"); marginLeftTextField = new TextField(Constants.uiMarginLeft); marginLeftTextField.setValue(Constants.reportMarginLeft); marginLeftTextField.setWidth("115px"); marginRightTextField = new TextField(Constants.uiMarginRight); marginRightTextField.setValue(Constants.reportMarginRight); marginRightTextField.setWidth("115px"); Button reverseButton = new Button(Constants.uiReverse); reverseButton.addListener(new Button.ClickListener() { private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { Object height = pageHeightTextField.getValue(); pageHeightTextField.setValue(pageWidthTextField.getValue()); pageWidthTextField.setValue(height); } }); HorizontalLayout pageLayout = new HorizontalLayout(); pageLayout.setSpacing(true); pageLayout.addComponent(pageWidthTextField); pageLayout.addComponent(pageHeightTextField); pageLayout.addComponent(reverseButton); pageLayout.setComponentAlignment(reverseButton, Alignment.BOTTOM_LEFT); GridLayout marginLayout = new GridLayout(3, 3); marginLayout.addComponent(marginTopTextField, 1, 0); marginLayout.addComponent(marginBottomTextField, 1, 2); marginLayout.addComponent(marginLeftTextField, 0, 1); marginLayout.addComponent(marginRightTextField, 2, 1); Panel marginPanel = new Panel(); marginPanel.setSizeUndefined(); marginPanel.addComponent(marginLayout); VerticalLayout reportConfigurationLayout = new VerticalLayout(); reportConfigurationLayout.setWidth("100%"); reportConfigurationLayout.setMargin(true); reportConfigurationLayout.setSpacing(true); reportConfigurationLayout.addComponent(printBackgroundOnOddRowsCheckBox); reportConfigurationLayout.addComponent(printColumnNamesCheckBox); reportConfigurationLayout.addComponent(stretchWithOverflowCheckBox); reportConfigurationLayout.addComponent(new Label()); reportConfigurationLayout.addComponent(columnsPerPageTextField); reportConfigurationLayout.addComponent(new Label()); reportConfigurationLayout.addComponent(pageLayout); reportConfigurationLayout.addComponent(new Label()); reportConfigurationLayout.addComponent(marginPanel); Component parametersComponent = getParametersComponent(); VerticalLayout parametersLayout = new VerticalLayout(); parametersLayout.setMargin(true); if(parametersComponent != null) { parametersLayout.addComponent(parametersComponent); } observationsLabel = new Label("", Label.CONTENT_XHTML); if(showObservations) { observationsLayout = new VerticalLayout(); observationsLayout.setMargin(true); observationsLayout.addComponent(observationsLabel); } accordion = new Accordion(); accordion.setSizeFull(); accordion.addTab(parametersLayout, Constants.uiParameters, null); accordion.addTab(reportConfigurationLayout, Constants.uiConfiguration, null); accordion.addTab(observationsLayout, Constants.uiObservations, null); VerticalLayout rightLayout = new VerticalLayout(); rightLayout.setSizeFull(); rightLayout.setMargin(true); rightLayout.addComponent(exportPanel); rightLayout.addComponent(accordion); rightLayout.setExpandRatio(accordion, 1); layout = new HorizontalSplitPanel(); layout.setSplitPosition(65); layout.setSizeFull(); layout.setSecondComponent(rightLayout); setCompositionRoot(layout); } public void addObservation(String text) { String currentText = observationsLabel.getValue().toString(); if(currentText.isEmpty()) { setObservations("- " + text); } else { setObservations(currentText + "<br/><br/>- " + text); } } public void setObservations(String text) { observationsLabel.setValue(text); } public String getObservations() { return (String) observationsLabel.getValue(); } @Override public void splitButtonClick(SplitButtonClickEvent event) { exportToPdf(); } @Override public void buttonClick(ClickEvent event) { if(event.getButton().equals(refreshButton)) { build(); } else if(event.getButton().equals(pdfButton)) { exportToPdf(); } else if(event.getButton().equals(excelButton)) { exportToExcel(); } else if(event.getButton().equals(wordButton)) { exportToWord(); } else if(event.getButton().equals(powerPointButton)) { exportToPowerPoint(); } else if(event.getButton().equals(odsButton)) { exportToOds(); } else if(event.getButton().equals(odtButton)) { exportToOdt(); } else if(event.getButton().equals(rtfButton)) { exportToRtf(); } else if(event.getButton().equals(htmlButton)) { exportToHtml(); } else if(event.getButton().equals(csvButton)) { exportToCsv(); } else if(event.getButton().equals(xmlButton)) { exportToXml(); } } public void exportToPdf() { download(getFileName() + ".pdf", new JRPdfExporter()); } public void exportToExcel() { download(getFileName() + ".xlsx", new JRXlsxExporter()); } public void exportToWord() { download(getFileName() + ".docx", new JRDocxExporter()); } public void exportToPowerPoint() { download(getFileName() + ".pptx", new JRPptxExporter()); } public void exportToOds() { download(getFileName() + ".ods", new JROdsExporter()); } public void exportToOdt() { download(getFileName() + ".odf", new JROdtExporter()); } public void exportToRtf() { download(getFileName() + ".rtf", new JRRtfExporter()); } public void exportToHtml() { download(getFileName() + ".html", new JRXhtmlExporter()); } public void exportToCsv() { download(getFileName() + ".csv", new JRCsvExporter()); } public void exportToXml() { download(getFileName() + ".xml", new JRXmlExporter()); } protected void download(String filename, final JRExporter exporter) { StreamResource resource = new StreamResource(new StreamResource.StreamSource() { private static final long serialVersionUID = 1L; @Override public InputStream getStream() { return new ByteArrayInputStream(getOutputStream(exporter).toByteArray()); } }, filename, getApplication()); getApplication().getMainWindow().open(resource, "_blank", 700, 350, 0); } }
package com.exedio.cope.instrument; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.lang.reflect.Modifier; import java.text.MessageFormat; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import com.exedio.cope.lib.AttributeValue; import com.exedio.cope.lib.LengthViolationException; import com.exedio.cope.lib.NestingRuntimeException; import com.exedio.cope.lib.NotNullViolationException; import com.exedio.cope.lib.ReadOnlyViolationException; import com.exedio.cope.lib.Type; import com.exedio.cope.lib.UniqueViolationException; import com.exedio.cope.lib.util.ReactivationConstructorDummy; // TODO use jspm final class Generator { private static final String THROWS_NULL = "if {0} is null."; private static final String THROWS_UNIQUE = "if {0} is not unique."; private static final String THROWS_LENGTH = "if {0} violates its length constraint."; private static final String CONSTRUCTOR_INITIAL = "Creates a new {0} with all the attributes initially needed."; private static final String CONSTRUCTOR_INITIAL_PARAMETER = "the initial value for attribute {0}."; private static final String CONSTRUCTOR_GENERIC = "Creates a new {0} and sets the given attributes initially."; private static final String CONSTRUCTOR_GENERIC_CALLED = "This constructor is called by {0}."; private static final String CONSTRUCTOR_REACTIVATION = "Reactivation constructor. Used for internal purposes only."; private static final String GETTER = "Returns the value of the persistent attribute {0}."; private static final String CHECKER = "Returns whether the given value corresponds to the hash in {0}."; private static final String SETTER = "Sets a new value for the persistent attribute {0}."; private static final String SETTER_DATA = "Sets the new data for the data attribute {0}."; private static final String SETTER_DATA_IOEXCEPTION = "if accessing {0} throws an IOException."; private static final String GETTER_DATA_URL = "Returns a URL the data of the data attribute {0} is available under."; private static final String GETTER_DATA_VARIANT = "Returns a URL the data of the {1} variant of the data attribute {0} is available under."; private static final String GETTER_DATA_MAJOR = "Returns the major mime type of the data attribute {0}."; private static final String GETTER_DATA_MINOR = "Returns the minor mime type of the data attribute {0}."; private static final String GETTER_DATA_DATA = "Returns the data of the data attribute {0}."; private static final String TOUCHER = "Sets the current date for the date attribute {0}."; private static final String FINDER_UNIQUE = "Finds a {0} by it''s unique attributes."; private static final String FINDER_UNIQUE_PARAMETER = "shall be equal to attribute {0}."; private static final String QUALIFIER = "Returns the qualifier."; private static final String QUALIFIER_GETTER = "Returns the qualifier."; private static final String QUALIFIER_SETTER = "Sets the qualifier."; private static final String TYPE = "The persistent type information for {0}."; private final Writer o; private final String lineSeparator; Generator(final Writer output) { this.o=output; final String systemLineSeparator = System.getProperty("line.separator"); if(systemLineSeparator==null) { System.out.println("warning: property \"line.separator\" is null, using LF (unix style)."); lineSeparator = "\n"; } else lineSeparator = systemLineSeparator; } public static final String toCamelCase(final String name) { final char first = name.charAt(0); if (Character.isUpperCase(first)) return name; else return Character.toUpperCase(first) + name.substring(1); } private static final String lowerCamelCase(final String s) { final char first = s.charAt(0); if(Character.isLowerCase(first)) return s; else return Character.toLowerCase(first) + s.substring(1); } private static final String getShortName(final Class aClass) { final String name = aClass.getName(); final int pos = name.lastIndexOf('.'); return name.substring(pos+1); } private void writeThrowsClause(final Collection exceptions) throws IOException { if(!exceptions.isEmpty()) { o.write("\t\t\tthrows"); boolean first = true; for(final Iterator i = exceptions.iterator(); i.hasNext(); ) { if(first) first = false; else o.write(','); o.write(lineSeparator); o.write("\t\t\t\t"); o.write(((Class)i.next()).getName()); } o.write(lineSeparator); } } private final void writeCommentHeader() throws IOException { o.write("/**"); o.write(lineSeparator); o.write(lineSeparator); o.write("\t **"); o.write(lineSeparator); } private final void writeCommentGenerated() throws IOException { o.write("\t * <p><small>"+Instrumentor.GENERATED+"</small>"); o.write(lineSeparator); } private final void writeCommentFooter() throws IOException { o.write("\t *"); o.write(lineSeparator); o.write(" */"); } private static final String link(final String target) { return "{@link #" + target + '}'; } private static final String link(final String target, final String name) { return "{@link #" + target + ' ' + name + '}'; } private static final String format(final String pattern, final String parameter1) { return MessageFormat.format(pattern, new Object[]{ parameter1 }); } private static final String format(final String pattern, final String parameter1, final String parameter2) { return MessageFormat.format(pattern, new Object[]{ parameter1, parameter2 }); } private void writeInitialConstructor(final CopeClass copeClass) throws IOException { if(!copeClass.hasInitialConstructor()) return; final List initialAttributes = copeClass.getInitialAttributes(); final SortedSet constructorExceptions = copeClass.getConstructorExceptions(); writeCommentHeader(); o.write("\t * "); o.write(format(CONSTRUCTOR_INITIAL, copeClass.getName())); o.write(lineSeparator); writeCommentGenerated(); for(Iterator i = initialAttributes.iterator(); i.hasNext(); ) { final CopeAttribute initialAttribute = (CopeAttribute)i.next(); o.write("\t * @param initial"); o.write(toCamelCase(initialAttribute.getName())); o.write(' '); o.write(format(CONSTRUCTOR_INITIAL_PARAMETER, link(initialAttribute.getName()))); o.write(lineSeparator); } for(Iterator i = constructorExceptions.iterator(); i.hasNext(); ) { final Class constructorException = (Class)i.next(); o.write("\t * @throws "); o.write(constructorException.getName()); o.write(' '); boolean first = true; final StringBuffer initialAttributesBuf = new StringBuffer(); for(Iterator j = initialAttributes.iterator(); j.hasNext(); ) { final CopeAttribute initialAttribute = (CopeAttribute)j.next(); if(!initialAttribute.getSetterExceptions().contains(constructorException)) continue; if(first) first = false; else initialAttributesBuf.append(", "); initialAttributesBuf.append("initial"); initialAttributesBuf.append(toCamelCase(initialAttribute.getName())); } final String pattern; if(NotNullViolationException.class.equals(constructorException)) pattern = THROWS_NULL; else if(UniqueViolationException.class.equals(constructorException)) pattern = THROWS_UNIQUE; else if(LengthViolationException.class.equals(constructorException)) pattern = THROWS_LENGTH; else throw new RuntimeException(constructorException.getName()); o.write(format(pattern, initialAttributesBuf.toString())); o.write(lineSeparator); } writeCommentFooter(); final String modifier = Modifier.toString(copeClass.getInitialConstructorModifier()); if(modifier.length()>0) { o.write(modifier); o.write(' '); } o.write(copeClass.getName()); o.write('('); boolean first = true; for(Iterator i = initialAttributes.iterator(); i.hasNext(); ) { if(first) first = false; else o.write(','); final CopeAttribute initialAttribute = (CopeAttribute)i.next(); o.write(lineSeparator); o.write("\t\t\t\tfinal "); o.write(initialAttribute.getBoxedType()); o.write(" initial"); o.write(toCamelCase(initialAttribute.getName())); } o.write(')'); o.write(lineSeparator); writeThrowsClause(constructorExceptions); o.write("\t{"); o.write(lineSeparator); o.write("\t\tthis(new "+AttributeValue.class.getName()+"[]{"); o.write(lineSeparator); for(Iterator i = initialAttributes.iterator(); i.hasNext(); ) { final CopeAttribute initialAttribute = (CopeAttribute)i.next(); o.write("\t\t\tnew "+AttributeValue.class.getName()+"("); o.write(initialAttribute.getName()); o.write(','); writePrefixedAttribute("initial", initialAttribute); o.write("),"); o.write(lineSeparator); } o.write("\t\t});"); o.write(lineSeparator); for(Iterator i = copeClass.getConstructorExceptions().iterator(); i.hasNext(); ) { final Class exception = (Class)i.next(); o.write("\t\tthrowInitial"); o.write(getShortName(exception)); o.write("();"); o.write(lineSeparator); } o.write("\t}"); } private void writeGenericConstructor(final CopeClass copeClass) throws IOException { final Option option = copeClass.genericConstructorOption; if(!option.exists) return; writeCommentHeader(); o.write("\t * "); o.write(format(CONSTRUCTOR_GENERIC, copeClass.getName())); o.write(lineSeparator); o.write("\t * "); o.write(format(CONSTRUCTOR_GENERIC_CALLED, "{@link " + Type.class.getName() + "#newItem Type.newItem}")); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write( Modifier.toString( option.getModifier(copeClass.isAbstract() ? Modifier.PROTECTED : Modifier.PRIVATE) ) ); o.write(' '); o.write(copeClass.getName()); o.write("(final "+AttributeValue.class.getName()+"[] initialAttributes)"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\tsuper(initialAttributes);"); o.write(lineSeparator); o.write("\t}"); } private void writeReactivationConstructor(final CopeClass copeClass) throws IOException { writeCommentHeader(); o.write("\t * "); o.write(CONSTRUCTOR_REACTIVATION); o.write(lineSeparator); writeCommentGenerated(); o.write("\t * @see Item#Item(" + ReactivationConstructorDummy.class.getName() + ",int)"); o.write(lineSeparator); writeCommentFooter(); o.write( copeClass.isAbstract() ? "protected " : "private " ); o.write(copeClass.getName()); o.write("("+ReactivationConstructorDummy.class.getName()+" d,final int pk)"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\tsuper(d,pk);"); o.write(lineSeparator); o.write("\t}"); } private void writeAccessMethods(final CopeAttribute copeAttribute) throws IOException { final String type = copeAttribute.getBoxedType(); // getter if(copeAttribute.getterOption.exists) { writeCommentHeader(); o.write("\t * "); o.write(format(GETTER, link(copeAttribute.getName()))); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write(Modifier.toString(copeAttribute.getGeneratedGetterModifier())); o.write(' '); o.write(type); if(copeAttribute.hasIsGetter()) o.write(" is"); else o.write(" get"); o.write(toCamelCase(copeAttribute.getName())); o.write("()"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); writeGetterBody(copeAttribute); o.write("\t}"); } // setter if(copeAttribute.hasGeneratedSetter()) { writeCommentHeader(); o.write("\t * "); o.write(format(SETTER, link(copeAttribute.getName()))); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write(Modifier.toString(copeAttribute.getGeneratedSetterModifier())); o.write(" void set"); o.write(toCamelCase(copeAttribute.getName())); o.write("(final "); o.write(type); o.write(' '); o.write(copeAttribute.getName()); o.write(')'); o.write(lineSeparator); writeThrowsClause(copeAttribute.getSetterExceptions()); o.write("\t{"); o.write(lineSeparator); writeSetterBody(copeAttribute); o.write("\t}"); // touch for date attributes if(copeAttribute instanceof CopeNativeAttribute && ((CopeNativeAttribute)copeAttribute).touchable) { writeCommentHeader(); o.write("\t * "); o.write(format(TOUCHER, link(copeAttribute.getName()))); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write(Modifier.toString(copeAttribute.getGeneratedSetterModifier())); o.write(" void touch"); o.write(toCamelCase(copeAttribute.getName())); o.write("()"); o.write(lineSeparator); writeThrowsClause(copeAttribute.getToucherExceptions()); o.write("\t{"); o.write(lineSeparator); writeToucherBody(copeAttribute); o.write("\t}"); } } for(Iterator i = copeAttribute.getHashes().iterator(); i.hasNext(); ) { final CopeHash hash = (CopeHash)i.next(); writeHash(hash); } } private void writeHash(final CopeHash hash) throws IOException { // checker writeCommentHeader(); o.write("\t * "); o.write(format(CHECKER, link(hash.name))); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write(Modifier.toString(hash.storageAttribute.getGeneratedGetterModifier())); o.write(" boolean check"); o.write(toCamelCase(hash.name)); o.write("(final "); o.write(hash.storageAttribute.getBoxedType()); o.write(' '); o.write(hash.name); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); writeCheckerBody(hash); o.write("\t}"); // setter final CopeAttribute storageAttribute = hash.storageAttribute; writeCommentHeader(); o.write("\t * "); o.write(format(SETTER, link(hash.name))); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write(Modifier.toString(storageAttribute.getGeneratedSetterModifier())); o.write(" void set"); o.write(toCamelCase(hash.name)); o.write("(final "); o.write(storageAttribute.getBoxedType()); o.write(' '); o.write(hash.name); o.write(')'); o.write(lineSeparator); writeThrowsClause(storageAttribute.getSetterExceptions()); o.write("\t{"); o.write(lineSeparator); writeSetterBody(hash); o.write("\t}"); } private void writeDataGetterMethod(final CopeDataAttribute attribute, final Class returnType, final String part, final CopeDataVariant variant, final String commentPattern) throws IOException { writeCommentHeader(); o.write("\t * "); o.write(variant==null ? format(commentPattern, link(attribute.getName())) : format(commentPattern, link(attribute.getName()), link(variant.name, variant.shortName))); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write(Modifier.toString(attribute.getGeneratedGetterModifier())); o.write(' '); o.write(returnType.getName()); o.write(" get"); o.write(toCamelCase(attribute.getName())); o.write(part); if(variant!=null) o.write(variant.shortName); o.write("()"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn get"); o.write(part); o.write('('); o.write(attribute.copeClass.getName()); o.write('.'); if(variant!=null) o.write(variant.name); else o.write(attribute.getName()); o.write(");"); o.write(lineSeparator); o.write("\t}"); } private void writeDataAccessMethods(final CopeDataAttribute attribute) throws IOException { final String mimeMajor = attribute.mimeMajor; final String mimeMinor = attribute.mimeMinor; // getters writeDataGetterMethod(attribute, String.class, "URL", null, GETTER_DATA_URL); final List variants = attribute.getVariants(); if(variants!=null) { for(Iterator i = variants.iterator(); i.hasNext(); ) writeDataGetterMethod(attribute, String.class, "URL", (CopeDataVariant)i.next(), GETTER_DATA_VARIANT); } writeDataGetterMethod(attribute, String.class, "MimeMajor", null, GETTER_DATA_MAJOR); writeDataGetterMethod(attribute, String.class, "MimeMinor", null, GETTER_DATA_MINOR); writeDataGetterMethod(attribute, InputStream.class, "Data", null, GETTER_DATA_DATA); // setters if(attribute.hasGeneratedSetter()) { writeCommentHeader(); o.write("\t * "); o.write(format(SETTER_DATA, link(attribute.getName()))); o.write(lineSeparator); writeCommentGenerated(); o.write("\t * @throws "); o.write(IOException.class.getName()); o.write(' '); o.write(format(SETTER_DATA_IOEXCEPTION, "<code>data</code>")); o.write(lineSeparator); writeCommentFooter(); o.write(Modifier.toString(attribute.getGeneratedSetterModifier())); o.write(" void set"); o.write(toCamelCase(attribute.getName())); o.write("Data(final " + InputStream.class.getName() + " data"); if(mimeMajor==null) o.write(",final "+String.class.getName()+" mimeMajor"); if(mimeMinor==null) o.write(",final "+String.class.getName()+" mimeMinor"); o.write(')'); final SortedSet setterExceptions = attribute.getSetterExceptions(); writeThrowsClause(setterExceptions); if(setterExceptions.isEmpty()) o.write("throws "); o.write(IOException.class.getName()); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); final SortedSet exceptionsToCatch = new TreeSet(attribute.getExceptionsToCatchInSetter()); exceptionsToCatch.remove(ReadOnlyViolationException.class); exceptionsToCatch.remove(LengthViolationException.class); exceptionsToCatch.remove(UniqueViolationException.class); writeTryCatchClausePrefix(exceptionsToCatch); o.write("\t\tsetData("); o.write(attribute.copeClass.getName()); o.write('.'); o.write(attribute.getName()); o.write(",data"); o.write(mimeMajor==null ? ",mimeMajor" : ",null"); o.write(mimeMinor==null ? ",mimeMinor" : ",null"); o.write(");"); o.write(lineSeparator); writeTryCatchClausePostfix(exceptionsToCatch); o.write("\t}"); } } private void writeUniqueFinder(final CopeUniqueConstraint constraint) throws IOException { final CopeAttribute[] copeAttributes = constraint.copeAttributes; final String className = copeAttributes[0].getParent().name; writeCommentHeader(); o.write("\t * "); o.write(format(FINDER_UNIQUE, lowerCamelCase(className))); o.write(lineSeparator); writeCommentGenerated(); for(int i=0; i<copeAttributes.length; i++) { o.write("\t * @param searched"); o.write(toCamelCase(copeAttributes[i].getName())); o.write(' '); o.write(format(FINDER_UNIQUE_PARAMETER, link(copeAttributes[i].getName()))); o.write(lineSeparator); } writeCommentFooter(); o.write(Modifier.toString((constraint.modifier & (Modifier.PRIVATE|Modifier.PROTECTED|Modifier.PUBLIC)) | (Modifier.STATIC|Modifier.FINAL) )); o.write(' '); o.write(className); o.write(" findBy"); o.write(toCamelCase(constraint.name)); o.write('('); final Set qualifiers = new HashSet(); for(int i=0; i<copeAttributes.length; i++) { if(i>0) o.write(','); final CopeAttribute copeAttribute = copeAttributes[i]; o.write("final "); o.write(copeAttribute.getBoxedType()); o.write(" searched"); o.write(toCamelCase(copeAttribute.getName())); } o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn ("); o.write(className); o.write(')'); if(copeAttributes.length==1) { o.write(copeAttributes[0].getName()); o.write(".searchUnique("); writePrefixedAttribute("searched", copeAttributes[0]); } else { o.write(constraint.name); o.write(".searchUnique(new Object[]{"); writePrefixedAttribute("searched", copeAttributes[0]); for(int i = 1; i<copeAttributes.length; i++) { o.write(','); writePrefixedAttribute("searched", copeAttributes[i]); } o.write('}'); } o.write(");"); o.write(lineSeparator); o.write("\t}"); } private void writePrefixedAttribute(final String prefix, final CopeAttribute attribute) throws IOException { if(attribute.isBoxed()) o.write(attribute.getBoxingPrefix()); o.write(prefix); o.write(toCamelCase(attribute.getName())); if(attribute.isBoxed()) o.write(attribute.getBoxingPostfix()); } private void writeQualifierParameters(final CopeQualifier qualifier) throws IOException { final CopeAttribute[] keys = qualifier.keyAttributes; for(int i = 0; i<keys.length; i++) { if(i>0) o.write(','); o.write("final "); o.write(keys[i].persistentType); o.write(' '); o.write(keys[i].javaAttribute.name); } } private void writeQualifierCall(final CopeQualifier qualifier) throws IOException { final CopeAttribute[] keys = qualifier.keyAttributes; for(int i = 0; i<keys.length; i++) { o.write(','); o.write(keys[i].javaAttribute.name); } } private void writeQualifier(final CopeQualifier qualifier) throws IOException { writeCommentHeader(); o.write("\t * "); o.write(QUALIFIER); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write("public final "); // TODO: obey attribute visibility o.write(qualifier.qualifierClassString); o.write(" get"); o.write(toCamelCase(qualifier.name)); o.write('('); writeQualifierParameters(qualifier); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn ("); o.write(qualifier.qualifierClassString); o.write(")"); o.write(qualifier.name); o.write(".getQualifier(new Object[]{this"); writeQualifierCall(qualifier); o.write("});"); o.write(lineSeparator); o.write("\t}"); final List qualifierAttributes = Arrays.asList(qualifier.uniqueConstraint.copeAttributes); for(Iterator i = qualifier.qualifierClass.getCopeAttributes().iterator(); i.hasNext(); ) { final CopeAttribute attribute = (CopeAttribute)i.next(); if(qualifierAttributes.contains(attribute)) continue; writeQualifierGetter(qualifier, attribute); writeQualifierSetter(qualifier, attribute); } } private void writeQualifierGetter(final CopeQualifier qualifier, final CopeAttribute attribute) throws IOException { writeCommentHeader(); o.write("\t * "); o.write(QUALIFIER_GETTER); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); final String resultType = attribute.persistentType; o.write("public final "); // TODO: obey attribute visibility o.write(resultType); o.write(" get"); o.write(toCamelCase(attribute.getName())); o.write('('); writeQualifierParameters(qualifier); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn ("); o.write(resultType); o.write(')'); o.write(qualifier.name); o.write(".getQualified(new Object[]{this"); writeQualifierCall(qualifier); o.write("},"); o.write(qualifier.qualifierClassString); o.write('.'); o.write(attribute.getName()); o.write(");"); o.write(lineSeparator); o.write("\t}"); } private void writeQualifierSetter(final CopeQualifier qualifier, final CopeAttribute attribute) throws IOException { writeCommentHeader(); o.write("\t * "); o.write(QUALIFIER_SETTER); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); final String resultType = attribute.persistentType; o.write("public final void set"); // TODO: obey attribute visibility o.write(toCamelCase(attribute.getName())); o.write('('); writeQualifierParameters(qualifier); o.write(",final "); o.write(resultType); o.write(' '); o.write(attribute.getName()); o.write(')'); o.write(lineSeparator); writeThrowsClause(Arrays.asList(new Class[]{ NotNullViolationException.class, LengthViolationException.class, ReadOnlyViolationException.class, ClassCastException.class})); o.write("\t{"); o.write(lineSeparator); o.write("\t\t"); o.write(qualifier.name); o.write(".setQualified(new Object[]{this"); writeQualifierCall(qualifier); o.write("},"); o.write(qualifier.qualifierClassString); o.write('.'); o.write(attribute.getName()); o.write(','); o.write(attribute.getName()); o.write(");"); o.write(lineSeparator); o.write("\t}"); } private final void writeType(final CopeClass copeClass) throws IOException { final Option option = copeClass.typeOption; if(option.exists) { writeCommentHeader(); o.write("\t * "); o.write(format(TYPE, lowerCamelCase(copeClass.getName()))); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write(Modifier.toString(option.getModifier(Modifier.PUBLIC) | Modifier.STATIC | Modifier.FINAL)); // TODO obey class visibility o.write(" "+Type.class.getName()+" TYPE = "); o.write(lineSeparator); o.write("\t\tnew "+Type.class.getName()+"("); o.write(copeClass.getName()); o.write(".class)"); o.write(lineSeparator); o.write(";"); } } void writeClassFeatures(final CopeClass copeClass) throws IOException, InjectorParseException { if(!copeClass.isInterface()) { //System.out.println("onClassEnd("+jc.getName()+") writing"); writeInitialConstructor(copeClass); writeGenericConstructor(copeClass); writeReactivationConstructor(copeClass); for(final Iterator i = copeClass.getCopeAttributes().iterator(); i.hasNext(); ) { // write setter/getter methods final CopeAttribute copeAttribute = (CopeAttribute)i.next(); //System.out.println("onClassEnd("+jc.getName()+") writing attribute "+copeAttribute.getName()); if(copeAttribute instanceof CopeDataAttribute) writeDataAccessMethods((CopeDataAttribute)copeAttribute); else writeAccessMethods(copeAttribute); } for(final Iterator i = copeClass.getUniqueConstraints().iterator(); i.hasNext(); ) { // write unique finder methods final CopeUniqueConstraint constraint = (CopeUniqueConstraint)i.next(); writeUniqueFinder(constraint); } for(final Iterator i = copeClass.getQualifiers().iterator(); i.hasNext(); ) { final CopeQualifier qualifier = (CopeQualifier)i.next(); writeQualifier(qualifier); } writeType(copeClass); } } /** * Identation contract: * This methods is called, when o stream is immediately after a line break, * and it should return the o stream after immediately after a line break. * This means, doing nothing fullfils the contract. */ private void writeGetterBody(final CopeAttribute attribute) throws IOException { o.write("\t\treturn "); if(attribute.isBoxed()) o.write(attribute.getUnBoxingPrefix()); o.write('('); o.write(attribute.persistentType); o.write(")getAttribute("); o.write(attribute.copeClass.getName()); o.write('.'); o.write(attribute.getName()); o.write(')'); if(attribute.isBoxed()) o.write(attribute.getUnBoxingPostfix()); o.write(';'); o.write(lineSeparator); } /** * Identation contract: * This methods is called, when o stream is immediately after a line break, * and it should return the o stream after immediately after a line break. * This means, doing nothing fullfils the contract. */ private void writeSetterBody(final CopeAttribute attribute) throws IOException { final SortedSet exceptionsToCatch = attribute.getExceptionsToCatchInSetter(); writeTryCatchClausePrefix(exceptionsToCatch); o.write("\t\tsetAttribute("); o.write(attribute.copeClass.getName()); o.write('.'); o.write(attribute.getName()); o.write(','); if(attribute.isBoxed()) o.write(attribute.getBoxingPrefix()); o.write(attribute.getName()); if(attribute.isBoxed()) o.write(attribute.getBoxingPostfix()); o.write(");"); o.write(lineSeparator); writeTryCatchClausePostfix(exceptionsToCatch); } /** * Identation contract: * This methods is called, when o stream is immediately after a line break, * and it should return the o stream after immediately after a line break. * This means, doing nothing fullfils the contract. */ private void writeToucherBody(final CopeAttribute attribute) throws IOException { final SortedSet exceptionsToCatch = attribute.getExceptionsToCatchInToucher(); writeTryCatchClausePrefix(exceptionsToCatch); o.write("\t\ttouchAttribute("); o.write(attribute.copeClass.getName()); o.write('.'); o.write(attribute.getName()); o.write(");"); o.write(lineSeparator); writeTryCatchClausePostfix(exceptionsToCatch); } /** * Identation contract: * This methods is called, when o stream is immediately after a line break, * and it should return the o stream after immediately after a line break. * This means, doing nothing fullfils the contract. */ private void writeCheckerBody(final CopeHash hash) throws IOException { o.write("\t\treturn "); o.write(hash.storageAttribute.copeClass.getName()); o.write('.'); o.write(hash.name); o.write(".checkHash(this,"); o.write(hash.name); o.write(");"); o.write(lineSeparator); } /** * Identation contract: * This methods is called, when o stream is immediately after a line break, * and it should return the o stream after immediately after a line break. * This means, doing nothing fullfils the contract. */ private void writeSetterBody(final CopeHash hash) throws IOException { final CopeAttribute attribute = hash.storageAttribute; final SortedSet exceptionsToCatch = attribute.getExceptionsToCatchInSetter(); writeTryCatchClausePrefix(exceptionsToCatch); o.write("\t\t"); o.write(attribute.copeClass.getName()); o.write('.'); o.write(hash.name); o.write(".setHash(this,"); o.write(hash.name); o.write(");"); o.write(lineSeparator); writeTryCatchClausePostfix(exceptionsToCatch); } private void writeTryCatchClausePrefix(final SortedSet exceptionsToCatch) throws IOException { if(!exceptionsToCatch.isEmpty()) { o.write("\t\ttry"); o.write(lineSeparator); o.write("\t\t{"); o.write(lineSeparator); o.write('\t'); } } private void writeTryCatchClausePostfix(final SortedSet exceptionsToCatch) throws IOException { if(!exceptionsToCatch.isEmpty()) { o.write("\t\t}"); o.write(lineSeparator); for(Iterator i = exceptionsToCatch.iterator(); i.hasNext(); ) { final Class exceptionClass = (Class)i.next(); o.write("\t\tcatch("+exceptionClass.getName()+" e)"); o.write(lineSeparator); o.write("\t\t{"); o.write(lineSeparator); o.write("\t\t\tthrow new "+NestingRuntimeException.class.getName()+"(e);"); o.write(lineSeparator); o.write("\t\t}"); o.write(lineSeparator); } } } }
package com.exedio.cope.instrument; import static java.lang.reflect.Modifier.FINAL; import static java.lang.reflect.Modifier.PRIVATE; import static java.lang.reflect.Modifier.PROTECTED; import static java.lang.reflect.Modifier.PUBLIC; import static java.lang.reflect.Modifier.STATIC; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import java.util.zip.CRC32; import java.util.zip.CheckedOutputStream; import com.exedio.cope.BooleanField; import com.exedio.cope.Feature; import com.exedio.cope.Item; import com.exedio.cope.LengthViolationException; import com.exedio.cope.MandatoryViolationException; import com.exedio.cope.RangeViolationException; import com.exedio.cope.SetValue; import com.exedio.cope.Type; import com.exedio.cope.UniqueViolationException; import com.exedio.cope.Wrapper; import com.exedio.cope.util.ReactivationConstructorDummy; final class Generator { private static final String STRING = String.class.getName(); private static final String COLLECTION = Collection.class.getName(); private static final String LIST = List.class.getName(); private static final String IO_EXCEPTION = IOException.class.getName(); private static final String SET_VALUE = SetValue.class.getName(); private static final String ITEM = Item.class.getName(); private static final String TYPE_NAME = Type.class.getName(); private static final String REACTIVATION = ReactivationConstructorDummy.class.getName(); private static final String THROWS_MANDATORY = "if {0} is null."; private static final String THROWS_UNIQUE = "if {0} is not unique."; private static final String THROWS_RANGE = "if {0} violates its range constraint."; private static final String THROWS_LENGTH = "if {0} violates its length constraint."; private static final String CONSTRUCTOR_INITIAL = "Creates a new {0} with all the fields initially needed."; private static final String CONSTRUCTOR_INITIAL_PARAMETER = "the initial value for field {0}."; private static final String CONSTRUCTOR_INITIAL_CUSTOMIZE = "It can be customized with the tags " + "<tt>@" + CopeType.TAG_INITIAL_CONSTRUCTOR + ' ' + Option.TEXT_VISIBILITY_PUBLIC + '|' + Option.TEXT_VISIBILITY_PACKAGE + '|' + Option.TEXT_VISIBILITY_PROTECTED + '|' + Option.TEXT_VISIBILITY_PRIVATE + '|' + Option.TEXT_NONE + "</tt> " + "in the class comment and " + "<tt>@" + CopeFeature.TAG_INITIAL + "</tt> in the comment of fields."; private static final String CONSTRUCTOR_GENERIC = "Creates a new {0} and sets the given fields initially."; private static final String CONSTRUCTOR_GENERIC_CALLED = "This constructor is called by {0}."; private static final String CONSTRUCTOR_GENERIC_CUSTOMIZE = "It can be customized with the tag " + "<tt>@" + CopeType.TAG_GENERIC_CONSTRUCTOR + ' ' + Option.TEXT_VISIBILITY_PUBLIC + '|' + Option.TEXT_VISIBILITY_PACKAGE + '|' + Option.TEXT_VISIBILITY_PROTECTED + '|' + Option.TEXT_VISIBILITY_PRIVATE + '|' + Option.TEXT_NONE + "</tt> " + "in the class comment."; private static final String CONSTRUCTOR_REACTIVATION = "Reactivation constructor. Used for internal purposes only."; private static final String FINDER_UNIQUE = "Finds a {0} by it''s unique fields."; private static final String FINDER_UNIQUE_PARAMETER = "shall be equal to field {0}."; private static final String FINDER_UNIQUE_RETURN = "null if there is no matching item."; private static final String QUALIFIER = "Returns the qualifier."; private static final String QUALIFIER_GETTER = "Returns the qualifier."; private static final String QUALIFIER_SETTER = "Sets the qualifier."; private static final String RELATION_GETTER = "Returns the items associated to this item by the relation."; private static final String RELATION_ADDER = "Adds an item to the items associated to this item by the relation."; private static final String RELATION_REMOVER = "Removes an item from the items associated to this item by the relation."; private static final String RELATION_SETTER = "Sets the items associated to this item by the relation."; private static final String TYPE = "The persistent type information for {0}."; private static final String TYPE_CUSTOMIZE = "It can be customized with the tag " + "<tt>@" + CopeType.TAG_TYPE + ' ' + Option.TEXT_VISIBILITY_PUBLIC + '|' + Option.TEXT_VISIBILITY_PACKAGE + '|' + Option.TEXT_VISIBILITY_PROTECTED + '|' + Option.TEXT_VISIBILITY_PRIVATE + '|' + Option.TEXT_NONE + "</tt> " + "in the class comment."; private static final String GENERATED = "This feature has been generated by the cope instrumentor and will be overwritten by the build process."; /** * All generated class features get this doccomment tag. */ static final String TAG_GENERATED = CopeFeature.TAG_PREFIX + "generated"; private final JavaFile javaFile; private final Writer o; private final CRC32 outputCRC = new CRC32(); private final String lineSeparator; private final boolean longJavadoc; private static final String localFinal = "final "; // TODO make switchable from ant target Generator(final JavaFile javaFile, final ByteArrayOutputStream outputStream, final boolean longJavadoc) { this.javaFile = javaFile; this.o = new OutputStreamWriter(new CheckedOutputStream(outputStream, outputCRC)); final String systemLineSeparator = System.getProperty("line.separator"); if(systemLineSeparator==null) { System.out.println("warning: property \"line.separator\" is null, using LF (unix style)."); lineSeparator = "\n"; } else lineSeparator = systemLineSeparator; this.longJavadoc = longJavadoc; } void close() throws IOException { if(o!=null) o.close(); } long getCRC() { return outputCRC.getValue(); } private static final String toCamelCase(final String name) { final char first = name.charAt(0); if (Character.isUpperCase(first)) return name; else return Character.toUpperCase(first) + name.substring(1); } private static final String lowerCamelCase(final String s) { final char first = s.charAt(0); if(Character.isLowerCase(first)) return s; else return Character.toLowerCase(first) + s.substring(1); } private void writeThrowsClause(final Collection<Class> exceptions) throws IOException { if(!exceptions.isEmpty()) { o.write("\t\t\tthrows"); boolean first = true; for(final Class e : exceptions) { if(first) first = false; else o.write(','); o.write(lineSeparator); o.write("\t\t\t\t"); o.write(e.getName()); } o.write(lineSeparator); } } private void writeCommentHeader() throws IOException { o.write("/**"); o.write(lineSeparator); if(longJavadoc) { o.write(lineSeparator); o.write("\t **"); o.write(lineSeparator); } } private void writeCommentFooter() throws IOException { writeCommentFooter(null); } private void writeCommentFooter(final String extraComment) throws IOException { o.write("\t * @" + TAG_GENERATED + ' '); o.write(GENERATED); o.write(lineSeparator); if(extraComment!=null) { o.write("\t * "); o.write(extraComment); o.write(lineSeparator); } o.write("\t */"); o.write(lineSeparator); o.write('\t'); // TODO put this into calling methods } private static final String link(final String target) { return "{@link #" + target + '}'; } private static final String link(final String target, final String name) { return "{@link #" + target + ' ' + name + '}'; } private static final String format(final String pattern, final Object... arguments) { return MessageFormat.format(pattern, arguments); } private void writeInitialConstructor(final CopeType type) throws IOException { if(!type.hasInitialConstructor()) return; final List<CopeFeature> initialFeatures = type.getInitialFeatures(); final SortedSet<Class> constructorExceptions = type.getConstructorExceptions(); writeCommentHeader(); o.write("\t * "); o.write(format(CONSTRUCTOR_INITIAL, type.name)); o.write(lineSeparator); for(final CopeFeature feature : initialFeatures) { o.write("\t * @param "); o.write(feature.name); o.write(' '); o.write(format(CONSTRUCTOR_INITIAL_PARAMETER, link(feature.name))); o.write(lineSeparator); } for(final Class constructorException : constructorExceptions) { o.write("\t * @throws "); o.write(constructorException.getName()); o.write(' '); boolean first = true; final StringBuffer initialAttributesBuf = new StringBuffer(); for(final CopeFeature feature : initialFeatures) { if(!feature.getSetterExceptions().contains(constructorException)) continue; if(first) first = false; else initialAttributesBuf.append(", "); initialAttributesBuf.append(feature.name); } final String pattern; if(MandatoryViolationException.class.equals(constructorException)) pattern = THROWS_MANDATORY; else if(UniqueViolationException.class.equals(constructorException)) pattern = THROWS_UNIQUE; else if(RangeViolationException.class.equals(constructorException)) pattern = THROWS_RANGE; else if(LengthViolationException.class.equals(constructorException)) pattern = THROWS_LENGTH; else throw new RuntimeException(constructorException.getName()); o.write(format(pattern, initialAttributesBuf.toString())); o.write(lineSeparator); } writeCommentFooter(CONSTRUCTOR_INITIAL_CUSTOMIZE); writeModifier(type.getInitialConstructorModifier()); o.write(type.name); o.write('('); boolean first = true; for(final CopeFeature feature : initialFeatures) { if(first) first = false; else o.write(','); o.write(lineSeparator); o.write("\t\t\t\tfinal "); o.write(feature.getBoxedType()); o.write(' '); o.write(feature.name); } o.write(')'); o.write(lineSeparator); writeThrowsClause(constructorExceptions); o.write("\t{"); o.write(lineSeparator); o.write("\t\tthis(new " + SET_VALUE + "[]{"); o.write(lineSeparator); for(final CopeFeature feature : initialFeatures) { o.write("\t\t\t"); o.write(type.name); o.write('.'); o.write(feature.name); o.write(".map("); o.write(feature.name); o.write("),"); o.write(lineSeparator); } o.write("\t\t});"); o.write(lineSeparator); o.write("\t}"); } private void writeGenericConstructor(final CopeType type) throws IOException { final Option option = type.genericConstructorOption; if(!option.exists) return; writeCommentHeader(); o.write("\t * "); o.write(format(CONSTRUCTOR_GENERIC, type.name)); o.write(lineSeparator); o.write("\t * "); o.write(format(CONSTRUCTOR_GENERIC_CALLED, "{@link " + TYPE_NAME + "#newItem Type.newItem}")); o.write(lineSeparator); writeCommentFooter(CONSTRUCTOR_GENERIC_CUSTOMIZE); writeModifier(option.getModifier(type.allowSubTypes() ? PROTECTED : PRIVATE)); o.write(type.name); o.write('('); o.write(localFinal); o.write(SET_VALUE + "... setValues)"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\tsuper(setValues);"); o.write(lineSeparator); o.write("\t}"); } private void writeReactivationConstructor(final CopeType type) throws IOException { final Option option = type.reactivationConstructorOption; if(!option.exists) return; writeCommentHeader(); o.write("\t * "); o.write(CONSTRUCTOR_REACTIVATION); o.write(lineSeparator); o.write("\t * @see " + ITEM + "#Item(" + REACTIVATION + ",int)"); o.write(lineSeparator); writeCommentFooter(); writeModifier(option.getModifier(type.allowSubTypes() ? PROTECTED : PRIVATE)); o.write(type.name); o.write('('); o.write(localFinal); o.write(REACTIVATION + " d,"); o.write(localFinal); o.write("int pk)"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\tsuper(d,pk);"); o.write(lineSeparator); o.write("\t}"); } private void writeFeature(final CopeFeature feature) throws InjectorParseException, IOException { final Feature instance = feature.getInstance(); for(final Wrapper wrapper : instance.getWrappers()) { final String modifierTag = wrapper.getModifier(); final Option option = modifierTag!=null ? new Option(Injector.findDocTagLine( feature.docComment, CopeFeature.TAG_PREFIX + modifierTag), true) : null; if(option!=null && !option.exists) continue; final String methodName = wrapper.getMethodName(); final java.lang.reflect.Type methodReturnType = wrapper.getMethodReturnType(); final List<java.lang.reflect.Type> parameterTypes = wrapper.getParameterTypes(); final List<String> parameterNames = wrapper.getParameterNames(); final String featureNameCamelCase = toCamelCase(feature.name); final boolean isStatic = wrapper.isStatic(); final int modifier = feature.modifier; final boolean useIs = instance instanceof BooleanField && methodName.startsWith("get"); { writeCommentHeader(); final Object[] arguments = new String[]{ link(feature.name), feature.name, lowerCamelCase(feature.parent.name)}; o.write("\t * "); o.write(format(wrapper.getComment(), arguments)); o.write(lineSeparator); for(final String comment : wrapper.getComments()) { o.write("\t * "); o.write(format(comment, arguments)); o.write(lineSeparator); } writeCommentFooter( modifierTag!=null ? "It can be customized with the tag " + "<tt>@" + CopeFeature.TAG_PREFIX + modifierTag + ' ' + Option.TEXT_VISIBILITY_PUBLIC + '|' + Option.TEXT_VISIBILITY_PACKAGE + '|' + Option.TEXT_VISIBILITY_PROTECTED + '|' + Option.TEXT_VISIBILITY_PRIVATE + '|' + Option.TEXT_NONE + '|' + Option.TEXT_NON_FINAL + (useIs ? '|' + Option.TEXT_BOOLEAN_AS_IS : "") + "</tt> " + "in the comment of the field." : null); } writeModifier( ( option!=null ? option.getModifier(modifier) : ((modifier & (PUBLIC|PROTECTED|PRIVATE)) | FINAL) ) | (isStatic ? STATIC : 0) ); o.write(toString(methodReturnType, feature)); if(option!=null && useIs && option.booleanAsIs) { o.write(" is"); o.write(featureNameCamelCase); } else { o.write(' '); final String pattern = wrapper.getMethodWrapperPattern(); if(pattern!=null) o.write(MessageFormat.format(pattern, featureNameCamelCase, feature.name)); else writeName(methodName, featureNameCamelCase); } if(option!=null) o.write(option.suffix); o.write('('); boolean first = true; final Iterator<String> parameterNameIter = parameterNames.iterator(); for(final java.lang.reflect.Type parameter : parameterTypes) { if(first) first = false; else o.write(','); o.write(localFinal); o.write(toString(parameter, feature)); o.write(' '); final String name = parameterNameIter.next(); o.write(name!=null ? name : feature.name); } o.write(')'); o.write(lineSeparator); { final SortedSet<Class> exceptions = new TreeSet<Class>(CopeType.CLASS_COMPARATOR); exceptions.addAll(wrapper.getThrowsClause()); writeThrowsClause(exceptions); } o.write("\t{"); o.write(lineSeparator); o.write("\t\t"); if(!methodReturnType.equals(void.class)) o.write("return "); o.write(feature.parent.name); o.write('.'); o.write(feature.name); o.write('.'); o.write(methodName); o.write('('); first = true; if(isStatic) { if(first) first = false; else o.write(','); o.write(feature.parent.name); o.write(".class"); } else { first = false; o.write("this"); } for(final String name : parameterNames) { if(first) first = false; else o.write(','); o.write(name!=null ? name : feature.name); } o.write(')'); o.write(';'); o.write(lineSeparator); o.write("\t}"); } } private void writeName(final String methodName, final String featureName) throws IOException { for(int i = 0; i<methodName.length(); i++) if(Character.isUpperCase(methodName.charAt(i))) { o.write(methodName.substring(0, i)); o.write(featureName); o.write(methodName.substring(i)); return; } o.write(methodName); o.write(featureName); } private static final String toString(final Class c, final CopeFeature feature) { if(c.isArray()) return c.getComponentType().getName() + "[]"; else if(Wrapper.ClassVariable.class.equals(c)) return feature.parent.name; else if(Wrapper.TypeVariable0.class.equals(c)) return Injector.getGenerics(feature.javaAttribute.type).get(0); else if(Wrapper.TypeVariable1.class.equals(c)) return Injector.getGenerics(feature.javaAttribute.type).get(1); else return c.getCanonicalName(); } private static final String toString(final ParameterizedType t, final CopeFeature feature) { final StringBuffer bf = new StringBuffer(toString(t.getRawType(), feature)); bf.append('<'); boolean first = true; for(final java.lang.reflect.Type a : t.getActualTypeArguments()) { bf.append(toString(a, feature)); if(first) first = false; else bf.append(','); } bf.append('>'); return bf.toString(); } private static final String toString(final Wrapper.ExtendsType t, final CopeFeature feature) { final StringBuffer bf = new StringBuffer(toString(t.getRawType(), feature)); bf.append('<'); boolean first = true; for(final java.lang.reflect.Type a : t.getActualTypeArguments()) { bf.append("? extends "); bf.append(toString(a, feature)); if(first) first = false; else bf.append(','); } bf.append('>'); return bf.toString(); } private static final String toString(final java.lang.reflect.Type t, final CopeFeature feature) { if(t instanceof Class) return toString((Class)t, feature); else if(t instanceof ParameterizedType) return toString((ParameterizedType)t, feature); else if(t instanceof Wrapper.ExtendsType) return toString((Wrapper.ExtendsType)t, feature); else throw new RuntimeException(t.toString()); } private void writeUniqueFinder(final CopeUniqueConstraint constraint) throws IOException, InjectorParseException { final CopeAttribute[] attributes = constraint.getAttributes(); final String className = attributes[0].getParent().name; writeCommentHeader(); o.write("\t * "); o.write(format(FINDER_UNIQUE, lowerCamelCase(className))); o.write(lineSeparator); for(int i=0; i<attributes.length; i++) { o.write("\t * @param "); o.write(attributes[i].name); o.write(' '); o.write(format(FINDER_UNIQUE_PARAMETER, link(attributes[i].name))); o.write(lineSeparator); } o.write("\t * @return "); o.write(FINDER_UNIQUE_RETURN); o.write(lineSeparator); writeCommentFooter(); writeModifier((constraint.modifier & (PRIVATE|PROTECTED|PUBLIC)) | (STATIC|FINAL) ); o.write(className); o.write(" findBy"); o.write(toCamelCase(constraint.name)); o.write('('); for(int i=0; i<attributes.length; i++) { if(i>0) o.write(','); final CopeAttribute attribute = attributes[i]; o.write(localFinal); o.write(attribute.getBoxedType()); o.write(' '); o.write(attribute.name); } o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn "); o.write(attributes[0].parent.name); o.write('.'); o.write(constraint.name); o.write(".searchUnique("); o.write(className); o.write(".class,"); o.write(attributes[0].name); for(int i = 1; i<attributes.length; i++) { o.write(','); o.write(attributes[i].name); } o.write(");"); o.write(lineSeparator); o.write("\t}"); } private void writeSerialVersionUID() throws IOException { // TODO make disableable { writeCommentHeader(); writeCommentFooter(null); writeModifier(PRIVATE|STATIC|FINAL); o.write("long serialVersionUID = 1l;"); } } private void writeType(final CopeType type) throws IOException { final Option option = type.typeOption; if(option.exists) { writeCommentHeader(); o.write("\t * "); o.write(format(TYPE, lowerCamelCase(type.name))); o.write(lineSeparator); writeCommentFooter(TYPE_CUSTOMIZE); writeModifier(option.getModifier(PUBLIC) | STATIC|FINAL); // TODO obey class visibility o.write(TYPE_NAME + '<'); o.write(type.name); o.write("> TYPE = newType("); o.write(type.name); o.write(".class)"); o.write(lineSeparator); o.write(';'); } } void write() throws IOException, InjectorParseException { final String buffer = javaFile.buffer.toString(); int previousClassEndPosition = 0; for(final JavaClass javaClass : javaFile.getClasses()) { final CopeType type = CopeType.getCopeType(javaClass); final int classEndPosition = javaClass.getClassEndPosition(); if(type!=null) { assert previousClassEndPosition<=classEndPosition; if(previousClassEndPosition<classEndPosition) o.write(buffer, previousClassEndPosition, classEndPosition-previousClassEndPosition); writeClassFeatures(type); previousClassEndPosition = classEndPosition; } } o.write(buffer, previousClassEndPosition, buffer.length()-previousClassEndPosition); } private void writeClassFeatures(final CopeType type) throws IOException, InjectorParseException { if(!type.isInterface()) { writeInitialConstructor(type); writeGenericConstructor(type); writeReactivationConstructor(type); for(final CopeFeature feature : type.getFeatures()) { writeFeature(feature); if(feature instanceof CopeAttribute) ; // TODO remove CopeAttribute else if(feature instanceof CopeUniqueConstraint) writeUniqueFinder((CopeUniqueConstraint)feature); else if(feature instanceof CopeAttributeList) ; // TODO remove CopeAttributeList else if(feature instanceof CopeAttributeMap) ; // TODO remove CopeAttributeMap else if(feature instanceof CopeMedia) ; // TODO remove CopeMedia else if(feature instanceof CopeHash) ; // TODO remove CopeHash else if(feature instanceof CopeRelation || feature instanceof CopeQualifier) ; // is handled below else throw new RuntimeException(feature.getClass().getName()); } for(final CopeQualifier qualifier : sort(type.getQualifiers())) writeQualifier(qualifier); for(final CopeRelation relation : sort(type.getRelations(true))) writeRelation(relation, false); for(final CopeRelation relation : sort(type.getRelations(false))) writeRelation(relation, true); writeSerialVersionUID(); writeType(type); } } private static final <X extends CopeFeature> List<X> sort(final List<X> l) { final ArrayList<X> result = new ArrayList<X>(l); Collections.sort(result, new Comparator<X>() { public int compare(final X a, final X b) { return a.parent.javaClass.getFullName().compareTo(b.parent.javaClass.getFullName()); } }); return result; } private void writeModifier(final int modifier) throws IOException { final String modifierString = Modifier.toString(modifier); if(modifierString.length()>0) { o.write(modifierString); o.write(' '); } } private void writeQualifierParameters(final CopeQualifier qualifier) throws IOException, InjectorParseException { final CopeAttribute[] keys = qualifier.getKeyAttributes(); for(int i = 0; i<keys.length; i++) { if(i>0) o.write(','); o.write(localFinal); o.write(keys[i].persistentType); o.write(' '); o.write(keys[i].name); } } private void writeQualifierCall(final CopeQualifier qualifier) throws IOException, InjectorParseException { final CopeAttribute[] keys = qualifier.getKeyAttributes(); for(int i = 0; i<keys.length; i++) { o.write(','); o.write(keys[i].name); } } private void writeQualifier(final CopeQualifier qualifier) throws IOException, InjectorParseException { final String qualifierClassName = qualifier.parent.javaClass.getFullName(); writeCommentHeader(); o.write("\t * "); o.write(QUALIFIER); o.write(lineSeparator); writeCommentFooter(); o.write("public final "); // TODO: obey attribute visibility o.write(qualifierClassName); o.write(" get"); o.write(toCamelCase(qualifier.name)); o.write('('); writeQualifierParameters(qualifier); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn ("); o.write(qualifierClassName); o.write(')'); o.write(qualifierClassName); o.write('.'); o.write(qualifier.name); o.write(".getQualifier(this"); writeQualifierCall(qualifier); o.write(");"); o.write(lineSeparator); o.write("\t}"); final List<CopeAttribute> qualifierAttributes = Arrays.asList(qualifier.getAttributes()); for(final CopeFeature feature : qualifier.parent.getFeatures()) { if(feature instanceof CopeAttribute) { final CopeAttribute attribute = (CopeAttribute)feature; if(qualifierAttributes.contains(attribute)) continue; writeQualifierGetter(qualifier, attribute); writeQualifierSetter(qualifier, attribute); } } } private void writeQualifierGetter(final CopeQualifier qualifier, final CopeAttribute attribute) throws IOException, InjectorParseException { if(attribute.getterOption.exists) { final String qualifierClassName = qualifier.parent.javaClass.getFullName(); writeCommentHeader(); o.write("\t * "); o.write(QUALIFIER_GETTER); o.write(lineSeparator); writeCommentFooter(); writeModifier(attribute.getGeneratedGetterModifier()); o.write(attribute.persistentType); o.write(" get"); o.write(toCamelCase(attribute.name)); o.write(attribute.getterOption.suffix); o.write('('); writeQualifierParameters(qualifier); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn "); o.write(qualifierClassName); o.write('.'); o.write(qualifier.name); o.write(".get("); o.write(qualifierClassName); o.write('.'); o.write(attribute.name); o.write(",this"); writeQualifierCall(qualifier); o.write(");"); o.write(lineSeparator); o.write("\t}"); } } private void writeQualifierSetter(final CopeQualifier qualifier, final CopeAttribute attribute) throws IOException, InjectorParseException { if(attribute.setterOption.exists) { final String qualifierClassName = qualifier.parent.javaClass.getFullName(); writeCommentHeader(); o.write("\t * "); o.write(QUALIFIER_SETTER); o.write(lineSeparator); writeCommentFooter(); writeModifier(attribute.getGeneratedSetterModifier()); o.write("void set"); o.write(toCamelCase(attribute.name)); o.write(attribute.setterOption.suffix); o.write('('); writeQualifierParameters(qualifier); o.write(','); o.write(localFinal); o.write(attribute.getBoxedType()); o.write(' '); o.write(attribute.name); o.write(')'); o.write(lineSeparator); writeThrowsClause(attribute.getSetterExceptions()); o.write("\t{"); o.write(lineSeparator); o.write("\t\t"); o.write(qualifierClassName); o.write('.'); o.write(qualifier.name); o.write(".set("); o.write(qualifierClassName); o.write('.'); o.write(attribute.name); o.write(','); o.write(attribute.name); o.write(",this"); writeQualifierCall(qualifier); o.write(");"); o.write(lineSeparator); o.write("\t}"); } } private void writeRelation(final CopeRelation relation, final boolean source) throws IOException { final boolean vector = relation.vector; final String endType = relation.getEndType(source); final String endName = relation.getEndName(source); final String endNameCamel = toCamelCase(endName); final String methodName = source ? "Sources" : "Targets"; final String className = relation.parent.javaClass.getFullName(); // getter if(!vector || !source) { writeCommentHeader(); o.write("\t * "); o.write(RELATION_GETTER); o.write(lineSeparator); writeCommentFooter(); o.write("public final " + LIST + '<'); // TODO: obey attribute visibility o.write(endType); o.write("> get"); o.write(endNameCamel); o.write("()"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn "); o.write(className); o.write('.'); o.write(relation.name); o.write(".get"); o.write(methodName); o.write("(this);"); o.write(lineSeparator); o.write("\t}"); } // adder if(!vector) { writeCommentHeader(); o.write("\t * "); o.write(RELATION_ADDER); o.write(lineSeparator); writeCommentFooter(); o.write("public final boolean addTo"); // TODO: obey attribute visibility o.write(endNameCamel); o.write('('); o.write(localFinal); o.write(endType); o.write(' '); o.write(endName); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn "); o.write(className); o.write('.'); o.write(relation.name); o.write(".addTo"); o.write(methodName); o.write("(this,"); o.write(endName); o.write(");"); o.write(lineSeparator); o.write("\t}"); } // remover if(!vector) { writeCommentHeader(); o.write("\t * "); o.write(RELATION_REMOVER); o.write(lineSeparator); writeCommentFooter(); o.write("public final boolean removeFrom"); // TODO: obey attribute visibility o.write(endNameCamel); o.write('('); o.write(localFinal); o.write(endType); o.write(' '); o.write(endName); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn "); o.write(className); o.write('.'); o.write(relation.name); o.write(".removeFrom"); o.write(methodName); o.write("(this,"); o.write(endName); o.write(");"); o.write(lineSeparator); o.write("\t}"); } // setter if(!vector || !source) { writeCommentHeader(); o.write("\t * "); o.write(RELATION_SETTER); o.write(lineSeparator); writeCommentFooter(); o.write("public final void set"); // TODO: obey attribute visibility o.write(endNameCamel); o.write('('); o.write(localFinal); o.write(COLLECTION + "<? extends "); o.write(endType); o.write("> "); o.write(endName); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\t"); o.write(className); o.write('.'); o.write(relation.name); o.write(".set"); o.write(methodName); o.write("(this,"); o.write(endName); o.write(");"); o.write(lineSeparator); o.write("\t}"); } } }
package org.pystructure.tests; import org.pystructure.PyStructure; import junit.framework.TestCase; public class PyStructureTest extends TestCase { private PyStructure obj; protected void setUp() throws Exception { obj = new PyStructure(); } public void testAdd() { assertEquals(1 + 2, obj.add(1, 2)); assertEquals(1 + 2, obj.add(2, 1)); } public void testAdd2() { assertEquals(1 + 3, obj.add(2, 1)); } }
package jade.domain.persistence; import jade.content.AgentAction; import jade.core.ContainerID; /** This class represents the <code>delete-container</code> action of the <code>JADE-Persistence</code> ontology. This action can be requested to the JADE AMS to create a new agent on a given container. @author Giovanni Rimassa - FRAMeTech s.r.l. */ public class DeleteContainer implements AgentAction { public DeleteContainer() { } public void setContainer(ContainerID id) { container = id; } public ContainerID getContainer() { return container; } public void setWhere(ContainerID id) { where = id; } public ContainerID getWhere() { return where; } public void setRepository(String r) { repository = r; } public String getRepository() { return repository; } private ContainerID container; private ContainerID where; private String repository; }
package net.sf.jabref.groups; import java.util.*; import javax.swing.undo.AbstractUndoableEdit; import net.sf.jabref.*; /** * @author zieren * * TODO To change the template for this generated type comment go to Window - * Preferences - Java - Code Style - Code Templates */ public class ExplicitGroup extends AbstractGroup implements SearchRule { public static final String ID = "ExplicitGroup:"; private final Set m_entries; private final BibtexDatabase m_database; public ExplicitGroup(String name, BibtexDatabase db) { super(name); m_entries = new HashSet(); m_database = db; } public static AbstractGroup fromString(String s, BibtexDatabase db) throws Exception { if (!s.startsWith(ID)) throw new Exception( "Internal error: ExplicitGroup cannot be created from \"" + s + "\""); QuotedStringTokenizer tok = new QuotedStringTokenizer(s.substring(ID .length()), SEPARATOR, QUOTE_CHAR); ExplicitGroup newGroup = new ExplicitGroup(tok.nextToken(), db); BibtexEntry[] entries; while (tok.hasMoreTokens()) { entries = db.getEntriesByKey(Util.unquote(tok.nextToken(), QUOTE_CHAR)); for (int i = 0; i < entries.length; ++i) newGroup.m_entries.add(entries[i]); } return newGroup; } public SearchRule getSearchRule() { return this; } public boolean supportsAdd() { return true; } public boolean supportsRemove() { return true; } public AbstractUndoableEdit addSelection(BasePanel basePanel) { BibtexEntry[] bes = basePanel.getSelectedEntries(); if (bes.length == 0) return null; // nothing to do HashSet entriesBeforeEdit = new HashSet(m_entries); for (int i = 0; i < bes.length; ++i) m_entries.add(bes[i]); return new UndoableChangeAssignment(entriesBeforeEdit, m_entries); } public AbstractUndoableEdit removeSelection(BasePanel basePanel) { BibtexEntry[] bes = basePanel.getSelectedEntries(); if (bes.length == 0) return null; // nothing to do HashSet entriesBeforeEdit = new HashSet(m_entries); for (int i = 0; i < bes.length; ++i) m_entries.remove(bes[i]); return new UndoableChangeAssignment(entriesBeforeEdit, m_entries); } public boolean contains(Map searchOptions, BibtexEntry entry) { return m_entries.contains(entry); } public int applyRule(Map searchStrings, BibtexEntry bibtexEntry) { return contains(searchStrings, bibtexEntry) ? 1 : 0; } public AbstractGroup deepCopy() { ExplicitGroup copy = new ExplicitGroup(m_name, m_database); copy.m_entries.addAll(m_entries); return copy; } public boolean equals(Object o) { if (!(o instanceof ExplicitGroup)) return false; ExplicitGroup other = (ExplicitGroup) o; return other.m_name.equals(m_name) && other.m_entries.equals(m_entries) && other.m_database == m_database; } /** * Returns a String representation of this group and its entries. Entries * are referenced by their Bibtexkey. Entries that do not have a Bibtexkey * are not included in the representation and will thus not be available * upon recreation. */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append(ID + Util.quote(m_name, SEPARATOR, QUOTE_CHAR) + SEPARATOR); String s; for (Iterator it = m_entries.iterator(); it.hasNext();) { s = ((BibtexEntry) it.next()).getCiteKey(); if (s != null && !s.equals("")) sb.append(Util.quote(s, SEPARATOR, QUOTE_CHAR) + SEPARATOR); } return sb.toString(); } }
package org.apache.lucene.search; import java.io.IOException; import org.apache.lucene.index.Term; import org.apache.lucene.index.TermDocs; import org.apache.lucene.index.IndexReader; /** A Query that matches documents containing a term. This may be combined with other terms with a {@link BooleanQuery}. */ public class TermQuery extends Query { private Term term; private class TermWeight implements Weight { private Searcher searcher; private float value; private float idf; private float queryNorm; public TermWeight(Searcher searcher) { this.searcher = searcher; } public Query getQuery() { return TermQuery.this; } public float getValue() { return value; } public float sumOfSquaredWeights() throws IOException { idf = searcher.getSimilarity().idf(term, searcher); value = idf * getBoost(); return value * value; // square term weights } public void normalize(float norm) { queryNorm = norm; queryNorm *= idf; // factor from document value *= queryNorm; // normalize for query } public Scorer scorer(IndexReader reader) throws IOException { TermDocs termDocs = reader.termDocs(term); if (termDocs == null) return null; return new TermScorer(this, termDocs, searcher.getSimilarity(), reader.norms(term.field())); } public Explanation explain() throws IOException { Query q = getQuery(); Explanation result = new Explanation(); result.setDescription("weight(" + getQuery() + "), product of:"); Explanation boostExpl = new Explanation(getBoost(), "boost"); if (getBoost() != 1.0f) result.addDetail(boostExpl); Explanation idfExpl = new Explanation(idf, "idf(docFreq=" + searcher.docFreq(term) + ")"); result.addDetail(idfExpl); Explanation normExpl = new Explanation(queryNorm,"queryNorm"); result.addDetail(normExpl); result.setValue(boostExpl.getValue() * idfExpl.getValue() * normExpl.getValue()); return result; } } /** Constructs a query for the term <code>t</code>. */ public TermQuery(Term t) { term = t; } /** Returns the term of this query. */ public Term getTerm() { return term; } protected Weight createWeight(Searcher searcher) { return new TermWeight(searcher); } /** Prints a user-readable version of this query. */ public String toString(String field) { StringBuffer buffer = new StringBuffer(); if (!term.field().equals(field)) { buffer.append(term.field()); buffer.append(":"); } buffer.append(term.text()); if (getBoost() != 1.0f) { buffer.append("^"); buffer.append(Float.toString(getBoost())); } return buffer.toString(); } /** Returns true iff <code>o</code> is equal to this. */ public boolean equals(Object o) { if (!(o instanceof TermQuery)) return false; TermQuery other = (TermQuery)o; return (this.getBoost() == other.getBoost()) && this.term.equals(other.term); } /** Returns a hash code value for this object.*/ public int hashCode() { return Float.floatToIntBits(getBoost()) ^ term.hashCode(); } }
package org.opentdc.service; import java.lang.reflect.Constructor; import javax.servlet.ServletContext; public abstract class GenericService<T> { // query: a semicolon-separated list of query verbs. e.g. modifiedAt();lessThan(3);orderByFirstName();ascending() protected static final String DEFAULT_QUERY = ""; // queryType: specifies the type of objects to be returned // TODO: how to make queryTypes generic, i.e. independent of serviceProviders ? protected static final String DEFAULT_QUERY_TYPE = ""; // position: the result set starts from the given position. // Increasing the position by a batch size allows to iterate the result set. // hasMore=false indicates that there are no more objects to be returned protected static final String DEFAULT_POSITION = "0"; // size: specifies the batch size, i.e. the amount of records returned starting from position. protected static final String DEFAULT_SIZE = "25"; /** * Return service provider implementation configured on context. * * @param serviceType * @param context * @return * @throws ReflectiveOperationException */ public T getServiceProvider( Class<? extends GenericService<?>> serviceProviderClass, ServletContext context ) throws ReflectiveOperationException { String serviceProviderName = context.getInitParameter(serviceProviderClass.getSimpleName() + ".serviceProvider"); @SuppressWarnings("unchecked") Class<T> clazz = (Class<T>) Class.forName(serviceProviderName); Constructor<T> c = clazz.getConstructor( ServletContext.class, String.class ); return c.newInstance( context, serviceProviderClass.getSimpleName() ); } }
package org.jgrapes.net; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.ExtendedSSLSession; import javax.net.ssl.SNIServerName; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLEngineResult.Status; import javax.net.ssl.SSLException; import org.jgrapes.core.Channel; import org.jgrapes.core.ClassChannel; import org.jgrapes.core.Component; import org.jgrapes.core.Components; import org.jgrapes.core.annotation.Handler; import org.jgrapes.core.annotation.HandlerDefinition.ChannelReplacements; import org.jgrapes.io.IOSubchannel; import org.jgrapes.io.events.Close; import org.jgrapes.io.events.Closed; import org.jgrapes.io.events.IOError; import org.jgrapes.io.events.Input; import org.jgrapes.io.events.Output; import org.jgrapes.io.util.LinkedIOSubchannel; import org.jgrapes.io.util.ManagedBuffer; import org.jgrapes.io.util.ManagedBufferPool; import org.jgrapes.net.events.Accepted; /** * A component that receives and send byte buffers on an * encrypted channel and sends and receives the corresponding * decrypted data on its own channel. */ public class SslServer extends Component { private static final Logger logger = Logger.getLogger(SslServer.class.getName()); private class EncryptedChannel extends ClassChannel {} private SSLContext sslContext; /** * @param plainChannel the component's channel * @param encryptedChannel the channel with the encrypted data * @param sslContext the SSL context to use */ public SslServer(Channel plainChannel, Channel encryptedChannel, SSLContext sslContext) { super(plainChannel, ChannelReplacements.create() .add(EncryptedChannel.class, encryptedChannel)); this.sslContext = sslContext; } /** * Creates a new downstream connection as {@link LinkedIOSubchannel} * of the network connection together with an {@link SSLEngine}. * * @param event * the accepted event */ @Handler(channels=EncryptedChannel.class) public void onAccepted(Accepted event, IOSubchannel encryptedChannel) { new PlainChannel(event, encryptedChannel); } /** * Handles encrypted data from upstream (the network). The data is * send through the {@link SSLEngine} and events are sent downstream * (and in the initial phases upstream) according to the conversion * results. * * @param event the event * @param encryptedChannel the channel for exchanging the encrypted data * @throws InterruptedException * @throws SSLException * @throws ExecutionException */ @Handler(channels=EncryptedChannel.class) public void onInput( Input<ByteBuffer> event, IOSubchannel encryptedChannel) throws InterruptedException, SSLException, ExecutionException { @SuppressWarnings("unchecked") final Optional<PlainChannel> plainChannel = (Optional<PlainChannel>) LinkedIOSubchannel.downstreamChannel(this, encryptedChannel); if (plainChannel.isPresent()) { plainChannel.get().sendDownstream(event); } } /** * Handles a close event from the encrypted channel (client). * * @param event the event * @param encryptedChannel the channel for exchanging the encrypted data * @throws InterruptedException * @throws SSLException */ @Handler(channels=EncryptedChannel.class) public void onClosed(Closed event, IOSubchannel encryptedChannel) throws SSLException, InterruptedException { @SuppressWarnings("unchecked") final Optional<PlainChannel> plainChannel = (Optional<PlainChannel>) LinkedIOSubchannel.downstreamChannel(this, encryptedChannel); if (plainChannel.isPresent()) { plainChannel.get().upstreamClosed(); } } /** * Handles an {@link IOError} event from the encrypted channel (client) * by sending it downstream. * * @param event the event * @param encryptedChannel the channel for exchanging the encrypted data * @throws InterruptedException * @throws SSLException */ @Handler(channels=EncryptedChannel.class) public void onIOError(IOError event, IOSubchannel encryptedChannel) throws SSLException, InterruptedException { @SuppressWarnings("unchecked") final Optional<PlainChannel> plainChannel = (Optional<PlainChannel>) LinkedIOSubchannel.downstreamChannel(this, encryptedChannel); plainChannel.ifPresent(channel -> fire(new IOError(event), channel)); } /** * Sends decrypted data through the engine and then upstream. * * @param event * the event with the data * @throws InterruptedException if the execution was interrupted * @throws SSLException if some SSL related problem occurs */ @Handler public void onOutput(Output<ByteBuffer> event, PlainChannel plainChannel) throws InterruptedException, SSLException { if (plainChannel.hub() != this) { return; } plainChannel.sendUpstream(event); } /** * Handles a close event from downstream. * * @param event * the close event * @throws SSLException if an SSL related problem occurs * @throws InterruptedException if the execution was interrupted */ @Handler public void onClose(Close event, PlainChannel plainChannel) throws InterruptedException, SSLException { if (plainChannel.hub() != this) { return; } plainChannel.close(event); } private class PlainChannel extends LinkedIOSubchannel { public SocketAddress localAddress; public SocketAddress remoteAddress; public SSLEngine sslEngine; private ManagedBufferPool<ManagedBuffer<ByteBuffer>, ByteBuffer> downstreamPool; private boolean isInputClosed = false; private ByteBuffer carryOver = null; public PlainChannel(Accepted event, IOSubchannel upstreamChannel) { super(SslServer.this, channel(), upstreamChannel, newEventPipeline()); localAddress = event.localAddress(); remoteAddress = event.remoteAddress(); if (remoteAddress instanceof InetSocketAddress) { sslEngine = sslContext.createSSLEngine( ((InetSocketAddress)remoteAddress).getAddress().getHostAddress(), ((InetSocketAddress)remoteAddress).getPort()); } else { sslEngine = sslContext.createSSLEngine(); } sslEngine.setUseClientMode(false); String channelName = Components.objectName(SslServer.this) + "." + Components.objectName(this); // Create buffer pools, adding 50 to application buffer size, see int decBufSize = sslEngine.getSession() .getApplicationBufferSize() + 50; downstreamPool = new ManagedBufferPool<>(ManagedBuffer::new, () -> { return ByteBuffer.allocate(decBufSize); }, 2) .setName(channelName + ".downstream.buffers"); int encBufSize = sslEngine.getSession().getPacketBufferSize(); setByteBufferPool(new ManagedBufferPool<>(ManagedBuffer::new, () -> { return ByteBuffer.allocate(encBufSize); }, 2) .setName(channelName + ".upstream.buffers")); } public void sendDownstream(Input<ByteBuffer> event) throws SSLException, InterruptedException, ExecutionException { ManagedBuffer<ByteBuffer> unwrapped = downstreamPool.acquire(); ByteBuffer input = event.buffer().duplicate(); if (carryOver != null) { if (carryOver.remaining() < input.remaining()) { // Shouldn't happen with carryOver having packet size // bytes left, have seen it happen nevertheless. carryOver.flip(); ByteBuffer extCarryOver = ByteBuffer.allocate( carryOver.remaining() + input.remaining()); extCarryOver.put(carryOver); carryOver = extCarryOver; } carryOver.put(input); carryOver.flip(); input = carryOver; carryOver = null; } SSLEngineResult unwrapResult; while (true) { unwrapResult = sslEngine.unwrap( input, unwrapped.backingBuffer()); // Handle any handshaking procedures switch (unwrapResult.getHandshakeStatus()) { case NEED_TASK: while (true) { Runnable runnable = sslEngine.getDelegatedTask(); if (runnable == null) { break; } // Having this handled by the response thread is // probably not really necessary, but as the delegated // task usually includes sending upstream... FutureTask<Boolean> task = new FutureTask<>(runnable, true); upstreamChannel().responsePipeline() .executorService().submit(task); task.get(); } continue; case NEED_WRAP: ManagedBuffer<ByteBuffer> feedback = upstreamChannel().byteBufferPool().acquire(); SSLEngineResult wrapResult = sslEngine.wrap( ManagedBuffer.EMPTY_BYTE_BUFFER .backingBuffer(), feedback.backingBuffer()); upstreamChannel().respond(Output.fromSink(feedback, false)); if (wrapResult.getHandshakeStatus() == HandshakeStatus.FINISHED) { fireAccepted(); } continue; case FINISHED: fireAccepted(); // fall through case NEED_UNWRAP: // sslEngine.unwrap sometimes return NEED_UNWRAP in // combination with CLOSED, though this doesn't really // make sense. if (unwrapResult.getStatus() != Status.BUFFER_UNDERFLOW && unwrapResult.getStatus() != Status.CLOSED) { continue; } break; default: break; } // Just to make sure... if (unwrapResult.getStatus() == Status.BUFFER_OVERFLOW) { unwrapped.replaceBackingBuffer(ByteBuffer.allocate( sslEngine.getSession() .getApplicationBufferSize() + 50)); } // If we get here, handshake has completed or no input is left if (unwrapResult.getStatus() != Status.OK) { // Underflow, overflow or closed break; } } if (unwrapped.position() == 0) { // Was only handshake unwrapped.unlockBuffer(); } else { // forward data received fire(Input.fromSink(unwrapped, sslEngine.isInboundDone()), this); } // final message? if (unwrapResult.getStatus() == Status.CLOSED && ! isInputClosed) { Closed evt = new Closed(); newEventPipeline().fire(evt, this); evt.get(); isInputClosed = true; return; } // Check if data from incomplete packet remains in input buffer if (input.hasRemaining()) { // Actually, packet buffer size should be sufficient, // but since this is hard to test and doesn't really matter... carryOver = ByteBuffer.allocate(input.remaining() + sslEngine.getSession().getPacketBufferSize() + 50); carryOver.put(input); } } public void sendUpstream(Output<ByteBuffer> event) throws SSLException, InterruptedException { ByteBuffer output = event.buffer().backingBuffer().duplicate(); while (output.hasRemaining() && !sslEngine.isInboundDone()) { ManagedBuffer<ByteBuffer> out = upstreamChannel().byteBufferPool().acquire(); sslEngine.wrap(output, out.backingBuffer()); upstreamChannel().respond( Output.fromSink(out, event.isEndOfRecord() && !output.hasRemaining())); } } public void close(Close event) throws InterruptedException, SSLException { sslEngine.closeOutbound(); while (!sslEngine.isOutboundDone()) { ManagedBuffer<ByteBuffer> feedback = upstreamChannel().byteBufferPool().acquire(); sslEngine.wrap(ManagedBuffer.EMPTY_BYTE_BUFFER .backingBuffer(), feedback.backingBuffer()); upstreamChannel().respond(Output.fromSink(feedback, false)); } upstreamChannel().respond(new Close()); } private void fireAccepted() { List<SNIServerName> snis = Collections.emptyList(); if (sslEngine.getSession() instanceof ExtendedSSLSession) { snis = ((ExtendedSSLSession)sslEngine.getSession()) .getRequestedServerNames(); } fire(new Accepted( localAddress, remoteAddress, true, snis), this); } public void upstreamClosed() throws SSLException, InterruptedException { if (!isInputClosed) { // was not properly closed on SSL layer Closed evt = new Closed(); newEventPipeline().fire(evt, this); evt.get(); } try { sslEngine.closeInbound(); while (!sslEngine.isOutboundDone()) { ManagedBuffer<ByteBuffer> feedback = upstreamChannel().byteBufferPool().acquire(); sslEngine.wrap(ManagedBuffer.EMPTY_BYTE_BUFFER .backingBuffer(),feedback.backingBuffer()); upstreamChannel().respond(Output.fromSink(feedback, false)); } } catch (SSLException e) { // Several clients (notably chromium, see // don't close the connection properly. So nobody is really // interested in this message logger.log(Level.FINEST, e.getMessage(), e); } } } }
package polytheque.model.pojos; public class Jeu { private String nom; private String description; private int ageMini; private String edition; private boolean disponibilite; private String etat; private String status; private String anneeParution; private int nbExemplaires; private int nbReserves; private int nbJoueurs; public Jeu(String nom, String description, int ageMini, String edition, boolean disponibilite, String etat, String statut, String anneeParution, int nbExemplaires, int nbReserves, int nbJoueurs) { this.setNom(nom); this.setDescription(description); this.setAgeMini(ageMini); this.setEdition(edition); this.setDisponibilite(disponibilite); this.setEtat(etat); this.setStatus(statut); this.setAnneeParution(anneeParution); this.setNbExemplaires(nbExemplaires); this.setNbReserves(nbReserves); this.setNbJoueurs(nbJoueurs); } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getAgeMini() { return ageMini; } public void setAgeMini(int ageMini) { this.ageMini = ageMini; } public String getEdition() { return edition; } public void setEdition(String edition) { this.edition = edition; } public boolean isDisponibilite() { return disponibilite; } public void setDisponibilite(boolean disponibilite) { this.disponibilite = disponibilite; } public String getEtat() { return etat; } public void setEtat(String etat) { this.etat = etat; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getAnneeParution() { return anneeParution; } public void setAnneeParution(String anneeParution) { this.anneeParution = anneeParution; } public int getNbExemplaires() { return nbExemplaires; } public void setNbExemplaires(int nbExemplaires) { this.nbExemplaires = nbExemplaires; } public int getNbReserves() { return nbReserves; } public void setNbReserves(int nbReserves) { this.nbReserves = nbReserves; } public int getNbJoueurs() { return nbJoueurs; } public void setNbJoueurs(int nbJoueurs) { this.nbJoueurs = nbJoueurs; } }
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; /** * @return the ActFolderId */ public static String getActFolderId() { return ActFolderId; } private PDFolders FoldAct=null; private static final String List=PDFolders.fACL+"/"+PDFolders.fFOLDTYPE+"/"+PDFolders.fPARENTID+"/"+PDFolders.fPDID+"/"+PDFolders.fTITLE+"/"+PDFolders.fPDAUTOR+"/"+PDFolders.fPDDATE; private static final HashSet ExecFiles=new HashSet(); static protected java.awt.Cursor DefCur=new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR); static protected final java.awt.Cursor WaitCur=new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR); private static String IO_OSFolder=System.getProperty("java.io.tmpdir"); /** * @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(); TreeFolder.setSelectionRow(0); try { setTitle(getTitle()+" @"+getSession().getUser().getName()+" ( "+getSession().getUser().getDescription()+" )"); } catch (Exception ex) {} } /** 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(); ReportsFold = 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(); jSeparator7 = new javax.swing.JPopupMenu.Separator(); ImportExtRIS = new javax.swing.JMenuItem(); jSeparator8 = new javax.swing.JPopupMenu.Separator(); ReportsDoc = new javax.swing.JMenuItem(); OtherMenu = new javax.swing.JMenu(); PaperBin = new javax.swing.JMenuItem(); ChangePass = new javax.swing.JMenuItem(); Thesaur = 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(); TaskCronMenuItem = new javax.swing.JMenuItem(); TaskEvenMenuItem = new javax.swing.JMenuItem(); TaskExecMenuItem = new javax.swing.JMenuItem(); TaskEndedMenuItem = new javax.swing.JMenuItem(); TraceMenuItem = 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); ReportsFold.setFont(getFontMenu()); ReportsFold.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/Report.png"))); // NOI18N ReportsFold.setText("Reports"); ReportsFold.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ReportsFoldActionPerformed(evt); } }); FolderMenu.add(ReportsFold); 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); DocMenu.add(jSeparator7); ImportExtRIS.setFont(getFontMenu()); ImportExtRIS.setText(TT("Import_RIS")); ImportExtRIS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ImportExtRISActionPerformed(evt); } }); DocMenu.add(ImportExtRIS); DocMenu.add(jSeparator8); ReportsDoc.setFont(getFontMenu()); ReportsDoc.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/Report.png"))); // NOI18N ReportsDoc.setText("Reports"); ReportsDoc.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ReportsDocActionPerformed(evt); } }); DocMenu.add(ReportsDoc); 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); Thesaur.setFont(getFontMenu()); Thesaur.setLabel("Thesaurus"); Thesaur.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ThesaurActionPerformed(evt); } }); OtherMenu.add(Thesaur); 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); TaskCronMenuItem.setFont(getFontMenu()); TaskCronMenuItem.setText(TT("Task_Cron")); TaskCronMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { TaskCronMenuItemActionPerformed(evt); } }); AdminMenu.add(TaskCronMenuItem); TaskEvenMenuItem.setFont(getFontMenu()); TaskEvenMenuItem.setText(TT("Task_Events")); TaskEvenMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { TaskEvenMenuItemActionPerformed(evt); } }); AdminMenu.add(TaskEvenMenuItem); TaskExecMenuItem.setFont(getFontMenu()); TaskExecMenuItem.setText(TT("Pending_Task_log")); TaskExecMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { TaskExecMenuItemActionPerformed(evt); } }); AdminMenu.add(TaskExecMenuItem); TaskEndedMenuItem.setFont(getFontMenu()); TaskEndedMenuItem.setText(TT("Ended_Tasks_Logs")); TaskEndedMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { TaskEndedMenuItemActionPerformed(evt); } }); AdminMenu.add(TaskEndedMenuItem); TraceMenuItem.setFont(getFontMenu()); TraceMenuItem.setText(TT("Trace_Logs")); TraceMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { TraceMenuItemActionPerformed(evt); } }); AdminMenu.add(TraceMenuItem); 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; setCursor(WaitCur); ExpandFold(TreeFold); setCursor(DefCur); }//GEN-LAST:event_TreeFolderTreeExpanded private void TreeFolderValueChanged(javax.swing.event.TreeSelectionEvent evt)//GEN-FIRST:event_TreeFolderValueChanged {//GEN-HEADEREND:event_TreeFolderValueChanged try { setCursor(WaitCur); DefaultMutableTreeNode TreeFold = (DefaultMutableTreeNode) evt.getPath().getLastPathComponent(); FoldAct= ((TreeFolder) TreeFold.getUserObject()).getFold(); SelFolderDesc.setText(HtmlDesc(FoldAct)); ActFolderId=FoldAct.getPDId(); RefreshDocs(); setCursor(DefCur); } catch (Exception ex) { setCursor(DefCur); 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(getActFolderId()); 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(getActFolderId()); 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 DialogEditFold DEF; PDFolders Fold; try { DEF = new DialogEditFold(this, true); DEF.setLocationRelativeTo(null); DEF.AddMode(); DEF.setAcl(FoldAct.getACL()); Fold=new PDFolders(Session); DEF.setParentPath(Fold.getPathId(FoldAct.getPDId())); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); return; } while (true) { try { DEF.setVisible(true); if (DEF.isCancel()) return; Fold=new PDFolders(Session); Fold.assignValues(DEF.getRecord()); Fold.setParentId(getActFolderId()); Fold.insert(); TreePath ActualPath = TreeFolder.getSelectionPath(); ExpandFold((DefaultMutableTreeNode)ActualPath.getLastPathComponent()); TreeFolder.setSelectionPath(ActualPath); return; } 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 DialogEditFold DEF; PDFolders Fold; TreePath selectionPath = TreeFolder.getSelectionPath(); try { DefaultMutableTreeNode TreeFold = (DefaultMutableTreeNode) selectionPath.getLastPathComponent(); Fold= ((TreeFolder) TreeFold.getUserObject()).getFold(); DEF = new DialogEditFold(this, true); DEF.setLocationRelativeTo(null); DEF.EditMode(); Fold.LoadFull(Fold.getPDId()); DEF.setRecord(Fold.getRecord()); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); return; } while (true) { try { DEF.setVisible(true); if (DEF.isCancel()) return; DEF.getRecord().CheckDef(); Fold.assignValues(DEF.getRecord()); Fold.update(); TreePath ParentFold = (TreePath) TreeFolder.getSelectionPath().getParentPath(); ExpandFold((DefaultMutableTreeNode)ParentFold.getLastPathComponent()); TreeFolder.setSelectionPath(selectionPath); return; } 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(); PDFolders Fold=new PDFolders(Session); MD.setParentPath(Fold.getPathId(FoldAct.getPDId())); 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.getPath()!=null) Doc.setFile(MD.getPath()); else throw new PDException("Error_retrieving_file"); Doc.setParentId(getActFolderId()); 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.setParentPath(Fold.getPathId(FoldAct.getPDId())); 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(getActFolderId()); Doc.insert(); RefreshDocs(); return; } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); RefreshDocs(); } } }//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; MD.getRecord().CheckDef(); 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(getActFolderId()); 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(getActFolderId()); 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()+DriverGeneric.getHelpLang(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, getActFolderId()); 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 { if (FoldAct.getPDId().equals(PDFolders.ROOTFOLDER)) PDExceptionFunc.GenPDException("Exporting_RootFolder_not_allowed", ""); ExpFolds=0; ExpDocs=0; DialogExportFolders ExpFold = new DialogExportFolders(this,true); ExpFold.setLocationRelativeTo(null); ExpFold.setVisible(true); if (ExpFold.isCancel()) return; setCursor(WaitCur); Export(FoldAct, getIO_OSFolder(), 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, getIO_OSFolder(), ImpFold.IsOneLevel(), ImpFold.IncludeMetadata(), ImpFold.IncludeDocs(), ImpFold.FoldType(), ImpFold.DocType(), ImpFold.IsStrict()); 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?usp=drive_web&formkey=dEpsRzZzSmlaQVZET0g2NDdsM0ZRaEE6MA#gid=0"); }//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, getIO_OSFolder(), 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 private void ThesaurActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_ThesaurActionPerformed {//GEN-HEADEREND:event_ThesaurActionPerformed MainThes MTW=new MainThes(this, false, Session); MTW.setLocationRelativeTo(null); MTW.setVisible(true); }//GEN-LAST:event_ThesaurActionPerformed private void TaskCronMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_TaskCronMenuItemActionPerformed {//GEN-HEADEREND:event_TaskCronMenuItemActionPerformed try { ListTaskCron LC = new ListTaskCron(this, true, new PDTasksCron(getSession())); LC.setLocationRelativeTo(null); LC.setVisible(true); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_TaskCronMenuItemActionPerformed private void TaskEvenMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_TaskEvenMenuItemActionPerformed {//GEN-HEADEREND:event_TaskEvenMenuItemActionPerformed try { ListTaskEvents LC = new ListTaskEvents(this, true, new PDTasksDefEvent(getSession())); LC.setLocationRelativeTo(null); LC.setVisible(true); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_TaskEvenMenuItemActionPerformed private void TaskExecMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_TaskExecMenuItemActionPerformed {//GEN-HEADEREND:event_TaskExecMenuItemActionPerformed try { ListTask LC = new ListTask(this, true, new PDTasksExec(getSession())); LC.setLocationRelativeTo(null); LC.setVisible(true); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_TaskExecMenuItemActionPerformed private void TaskEndedMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_TaskEndedMenuItemActionPerformed {//GEN-HEADEREND:event_TaskEndedMenuItemActionPerformed try { ListTaskEnded LC = new ListTaskEnded(this, true, new PDTasksExecEnded(getSession())); LC.setLocationRelativeTo(null); LC.setVisible(true); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_TaskEndedMenuItemActionPerformed private void TraceMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_TraceMenuItemActionPerformed {//GEN-HEADEREND:event_TraceMenuItemActionPerformed try { ListTrace LT = new ListTrace(this, true, new PDTrace(getSession())); LT.setLocationRelativeTo(null); LT.setVisible(true); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_TraceMenuItemActionPerformed private void ReportsFoldActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_ReportsFoldActionPerformed {//GEN-HEADEREND:event_ReportsFoldActionPerformed try { SelectReport SR = new SelectReport(this, true); SR.setLocationRelativeTo(null); SR.setVisible(true); if (SR.isCancel()) return; setCursor(WaitCur); PDFolders Fold=new PDFolders(Session); Conditions Conds=new Conditions(); Condition Cond=new Condition(PDFolders.fPARENTID, Condition.cEQUAL, getActFolderId()); Conds.addCondition(Cond); Cursor Cur=Fold.Search(PDFolders.getTableName(), Conds, true, false, null, null); PDReport Rep=new PDReport(Session); Rep.setPDId(SR.getSelectedRep()); ArrayList<String> GeneratedRep = Rep.GenerateRep(getActFolderId(), Cur, null, SR.getDocsPerPage(), SR.getPagesPerFile(), getIO_OSFolder()); setCursor(DefCur); ListReports LR = new ListReports(this, true); LR.setLocationRelativeTo(null); LR.setRepList(GeneratedRep); LR.setVisible(true); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_ReportsFoldActionPerformed private void ReportsDocActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_ReportsDocActionPerformed {//GEN-HEADEREND:event_ReportsDocActionPerformed try { SelectReport SR = new SelectReport(this, true); SR.setLocationRelativeTo(null); SR.setVisible(true); if (SR.isCancel()) return; setCursor(WaitCur); PDDocs Doc=new PDDocs(Session); PDReport Rep=new PDReport(Session); Rep.setPDId(SR.getSelectedRep()); ArrayList<String> GeneratedRep = Rep.GenerateRep(getActFolderId(), Doc.getListContainedDocs(getActFolderId()), null, SR.getDocsPerPage(), SR.getPagesPerFile(), getIO_OSFolder()); setCursor(DefCur); ListReports LR = new ListReports(this, true); LR.setLocationRelativeTo(null); LR.setRepList(GeneratedRep); LR.setVisible(true); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_ReportsDocActionPerformed private void ImportExtRISActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_ImportExtRISActionPerformed {//GEN-HEADEREND:event_ImportExtRISActionPerformed try { DialogImportRIS ImpRIS = new DialogImportRIS(this,true); ImpRIS.setLocationRelativeTo(null); ImpRIS.setVisible(true); if (ImpRIS.isCancel()) return; PDDocsRIS D=new PDDocsRIS(getSession(), ImpRIS.DefaultRISDocType()); D.ImportFileRIS(getActFolderId(), ImpRIS.GetFilePath()); RefreshDocs(); } catch (Exception ex) { Message(DrvTT(ex.getLocalizedMessage())); } }//GEN-LAST:event_ImportExtRISActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { String PropertiesFile; if (args.length==0) PropertiesFile="Prodoc.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 ImportExtRIS; 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 ReportsDoc; private javax.swing.JMenuItem ReportsFold; 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.JMenuItem TaskCronMenuItem; private javax.swing.JMenuItem TaskEndedMenuItem; private javax.swing.JMenuItem TaskEvenMenuItem; private javax.swing.JMenuItem TaskExecMenuItem; private javax.swing.JMenuItem Thesaur; private javax.swing.JMenuItem TraceMenuItem; 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.JPopupMenu.Separator jSeparator7; private javax.swing.JPopupMenu.Separator jSeparator8; 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 */ static public void Report(String pMessage) { DialogReport DR=new DialogReport(null, true); DR.SetMessage(DrvTT(pMessage)); DR.setLocationRelativeTo(null); DR.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); } /** * Returns the path of a selected file. * @param RecomFileName default name * @param Ext Default extension for the type * @param Save indicates if selecting an existing file or destination for saving a new one. * @return */ static public String SelectDestination(String RecomFileName, String Ext, boolean Save) { JFileChooser fc = new JFileChooser(getIO_OSFolder()); 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(""); } setIO_OSFolder(fc.getSelectedFile().getParent()); return(fc.getSelectedFile().getAbsolutePath()); } /** * * @param RecomFileName * @return */ static public String SelectFolderDestination(String RecomFileName) { //gfgfgf 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(""); setIO_OSFolder(fc.getSelectedFile().getAbsolutePath()); 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 { setCursor(WaitCur); 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); setCursor(DefCur); } catch (PDException ex) { setCursor(DefCur); 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 Ic=new ImageIcon( ); ImageIcon PDIcon=new ImageIcon(Ic.getClass().getResource("/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(getActFolderId()); PDDocs Doc = new PDDocs(getSession()); Record R1=Doc.getRecordStruct(); 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 protected int Execute(String Doc) { try { String Orders[]= {"xdg-open", Doc}; String OS=System.getProperty("os.name"); if (OS.contains("Win")) { Orders[0]="explorer"; Orders[1]="\""+Doc+"\""; } 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>"); if (Attr.getType()==Attribute.tTHES) { PDThesaur Term=new PDThesaur(Session); if (Attr.getValue()!=null) { Term.Load((String)Attr.getValue()); Html.append(Term.getName()); } } else 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; } static protected String getLang() { try { return(getSession().getPDCust().getLanguage()); } catch (PDException ex) { return("EN"); } } static protected 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("1.2.1"); } /** * Exports a full tree recursively * @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, boolean Strict) throws PDException { PDFolders NewFold=new PDFolders(FoldAct.getDrv(), FoldType); boolean FoldExist=false; if (!Strict) { String Name=OriginPath.substring(OriginPath.lastIndexOf(File.separatorChar)+1); try { String IdFold=NewFold.GetIdChild(FoldAct.getPDId(), Name); NewFold.Load(IdFold); FoldExist=true; } catch( PDException ex) { // don't exits } } if (Strict || (!Strict && !FoldExist)) { 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 (File ListElement : ListOrigin) { if (ListElement.isDirectory()) { if (!IsOneLevel) DirList.add(ListElement); continue; } if (IncludeDocs) { if (ListElement.getName().endsWith(".opd")) { if (IncludeMetadata) { try { ExpDocs+=getSession().ProcessXML(ListElement, NewFold.getPDId()); } catch (PDException ex) { throw new PDException(ex.getLocalizedMessage()+"->"+ListElement.getAbsolutePath()); } } } 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, Strict); } } 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 (File ListElement : ListOrigin) { if (ListElement.isDirectory()) { DirList.add(ListElement); continue; } if (ListElement.getName().toLowerCase().endsWith(".xml") && Format.equals("Abby")) { ExpDocs++; try { ImageFile=PDDocs.ProcessXMLAbby(getSession(), ListElement, NewFold.getPDId(), DateFormat, TimeStampFormat); } catch (PDException ex) { throw new PDException(ex.getLocalizedMessage()+"->"+ListElement.getAbsolutePath()); } if (DeleteAfter) { if (ImageFile!=null) ImageFile.delete(); ListElement.delete(); } } else if (ListElement.getName().toLowerCase().endsWith(".txt") && Format.equals("Kofax")) { ExpDocs++; try { ImageFile=PDDocs.ProcessXMLKofax(getSession(), ListElement, NewFold.getPDId(), DateFormat, TimeStampFormat); } catch (PDException ex) { throw new PDException(ex.getLocalizedMessage()+"->"+ListElement.getAbsolutePath()); } if (DeleteAfter) { if (ImageFile!=null) ImageFile.delete(); ListElement.delete(); } } } ListOrigin=null; // to help gc and save memory during recursivity for (Object DirList1 : DirList) { File SubDir = (File) DirList1; 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()); TaskCronMenuItem.setVisible(R.isAllowCreateTask() || R.isAllowMaintainTask()); TaskEvenMenuItem.setVisible(R.isAllowCreateTask() || R.isAllowMaintainTask()); TaskExecMenuItem.setVisible(R.isAllowCreateTask() || R.isAllowMaintainTask()); TaskEndedMenuItem.setVisible(R.isAllowCreateTask() || R.isAllowMaintainTask()); this.TraceMenuItem.setVisible(R.isAllowCreateObject() || R.isAllowMaintainObject()); 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()); ImportExtFold.setVisible(R.isAllowCreateFolder() && R.isAllowCreateDoc()); ImportExtRIS.setVisible(R.isAllowCreateDoc()); } catch (Exception ex) { Message(ex.getLocalizedMessage()); } } /** * @return the IO_OSFolder */ public static String getIO_OSFolder() { return IO_OSFolder; } /** * @param aIO_OSFolder the IO_OSFolder to set */ public static void setIO_OSFolder(String aIO_OSFolder) { IO_OSFolder = aIO_OSFolder; } }
package js.rbuddy.test; import static org.junit.Assert.*; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; import java.util.Set; import org.junit.*; import js.basic.IOSnapshot; //import static org.junit.Assert.*; import js.rbuddy.JSDate; import js.rbuddy.Receipt; import static js.basic.Tools.*; public class ReceiptTest extends js.testUtils.MyTest { private void verifySummary(String input, String expOutput) { Receipt r = new Receipt(42); r.setSummary(input); assertStringsMatch(r.getSummary(), expOutput); } @Test public void testSummaryLeadSpaces() { verifySummary(" leading spaces", "leading spaces"); } @Test public void testSummaryTrailingSpaces() { verifySummary("trailing spaces ", "trailing spaces"); } @Test public void testSummaryReplaceLinefeedsWithSpaces() { verifySummary("linefeeds\n\n\nembedded", "linefeeds embedded"); verifySummary("linefeeds \t\n\n embedded aaa \n\n \n bbb ", "linefeeds embedded aaa bbb"); verifySummary(" \n\n \n ", ""); } @Test public void testConstructorStartsWithCurrentDate() { Receipt r = new Receipt(42); assertStringsMatch(JSDate.currentDate(), r.getDate()); } @Test(expected = IllegalArgumentException.class) public void testAttemptToAssignIllegalUniqueIdentifier() { new Receipt(0); } @Test(expected = IllegalArgumentException.class) public void testAttemptToAssignIllegalUniqueIdentifier2() { new Receipt(-1); } @Test public void testEncode() { { Receipt r = new Receipt(72); r.setSummary("\n\nA long summary\n\n\n \n\n with several linefeeds, \"quotes\", and | some other characters | ... \n\n"); r.setTags("alpha,beta,gamma"); CharSequence s = r.encode(); Receipt r2 = Receipt.decode(s); assertStringsMatch(s, r2.encode()); } { Receipt r = new Receipt(72); CharSequence s = r.encode(); Receipt r2 = Receipt.decode(s); assertStringsMatch(s, r2.encode()); } } @Test public void testTags() { Receipt r = new Receipt(72); r.setTags("alpha,beta,gamma"); Set<String> tags = r.getTags(); assertTrue(tags.size() == 3); assertTrue(tags.contains("alpha")); assertFalse(tags.contains("delta")); } @Test public void testTagParserTrimsWhitespace() { Receipt r = new Receipt(72); r.setTags(" , aaaa , , , bbbb\nccc cccc "); Set<String> tags = r.getTags(); assertTrue(tags.size() == 3); assertTrue(tags.contains("aaaa")); assertTrue(tags.contains("bbbb")); assertTrue(tags.contains("ccc cccc")); } @Test public void testTagParserEmpty() { Receipt r = new Receipt(72); r.setTags(" , , "); Set<String> tags = r.getTags(); assertTrue(tags.size() == 0); } @Test public void testTagParserMaxItemsRespected() { Receipt r = new Receipt(72); r.setTags("a,b, c, d, e, f, g, h, i, j, k"); assertTrue(r.getTags().size() == Receipt.MAX_TAGS); } private static String[] scripts = { "a,b, c, d, e, f, g, h, i, j, k", "", "aaa aaaa", " bb, aaa aaa, aaa aaa", }; @Test public void testTagsString() { IOSnapshot.open(); Receipt r = new Receipt(72); for (int i = 0; i < scripts.length; i++) { r.setTags(scripts[i]); pr(r.getTagsString()); } IOSnapshot.close(); } @Test public void testTagsStringParseSymmetry() { Receipt r = new Receipt(72); for (int i = 0; i < scripts.length; i++) { r.setTags(scripts[i]); String s = r.getTagsString(); Receipt r2 = new Receipt(73); r2.setTags(s); String s2 = r2.getTagsString(); assertStringsMatch(s, s2); } } @Test public void testCurrencyFormatterVariousCountries() { double value = 1323.526; NumberFormat[] fmts = { NumberFormat.getCurrencyInstance(Locale.US), NumberFormat.getCurrencyInstance(Locale.FRENCH), NumberFormat.getCurrencyInstance(Locale.JAPAN), }; System.out.println("value=" + value); for (int i = 0; i < fmts.length; i++) { NumberFormat f = fmts[i]; pr("\n" + f.getCurrency()); String s = f.format(value); pr(" format()= '" + s + "'"); Number n = null; try { n = f.parse(s); pr(" parse()= " + n); } catch (ParseException e) { pr(" parse failed: " + e); } } } @Test public void testCurrencyFormatterSloppyParseInput() { NumberFormat f = NumberFormat.getCurrencyInstance(Locale.US); String[] script = { "$123", "123", "123.30", "$123.3", "$123.", "$5000", "$5000.2", }; for (int i = 0; i < script.length; i++) { String s = script[i]; pr("Parsing '" + s + "'"); Number n = null; try { n = f.parse(s); pr(" yields " + n); } catch (ParseException e) { pr(" parse failed: " + e); warning("If the user omits '$', parsing fails. We could then tack on a '$' and try the parsing again, but this " + "add-hoc approach has problems, since the user may be in another Locale (i.e. Euros). One possible approach " + "is to put a fixed amount like 1234.56 through a formatter for the user's Locale and see what it produces, and" + " use the result to infer an appropriate preprocessing to apply to the user's string before attempting to parse it." + " There may exist some utilities that do this already... more research is required."); } } } }
package com.cloud.vm; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.ejb.Local; import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.AgentManager.OnError; import com.cloud.agent.Listener; import com.cloud.agent.api.AgentControlAnswer; import com.cloud.agent.api.AgentControlCommand; import com.cloud.agent.api.Answer; import com.cloud.agent.api.CheckVirtualMachineAnswer; import com.cloud.agent.api.CheckVirtualMachineCommand; import com.cloud.agent.api.Command; import com.cloud.agent.api.MigrateAnswer; import com.cloud.agent.api.MigrateCommand; import com.cloud.agent.api.PingRoutingCommand; import com.cloud.agent.api.PrepareForMigrationAnswer; import com.cloud.agent.api.PrepareForMigrationCommand; import com.cloud.agent.api.RebootAnswer; import com.cloud.agent.api.RebootCommand; import com.cloud.agent.api.StartAnswer; import com.cloud.agent.api.StartCommand; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupRoutingCommand; import com.cloud.agent.api.StartupRoutingCommand.VmState; import com.cloud.agent.api.StopAnswer; import com.cloud.agent.api.StopCommand; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.api.ClusterSyncAnswer; import com.cloud.agent.api.ClusterSyncCommand; import com.cloud.agent.manager.Commands; import com.cloud.agent.manager.allocator.HostAllocator; import com.cloud.alert.AlertManager; import com.cloud.capacity.CapacityManager; import com.cloud.cluster.ClusterManager; import com.cloud.cluster.StackMaid; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.consoleproxy.ConsoleProxyManager; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.DataCenterVO; import com.cloud.dc.HostPodVO; import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.HostPodDao; import com.cloud.deploy.DataCenterDeployment; import com.cloud.deploy.DeployDestination; import com.cloud.deploy.DeploymentPlan; import com.cloud.deploy.DeploymentPlanner; import com.cloud.deploy.DeploymentPlanner.ExcludeList; import com.cloud.domain.dao.DomainDao; import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ConnectionException; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InsufficientServerCapacityException; import com.cloud.exception.InsufficientVirtualNetworkCapcityException; import com.cloud.exception.ManagementServerException; import com.cloud.exception.OperationTimedoutException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.exception.VirtualMachineMigrationException; import com.cloud.ha.HighAvailabilityManager; import com.cloud.ha.HighAvailabilityManager.WorkType; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.Status; import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.HypervisorGuru; import com.cloud.hypervisor.HypervisorGuruManager; import com.cloud.network.Network; import com.cloud.network.NetworkManager; import com.cloud.network.NetworkVO; import com.cloud.offering.ServiceOffering; import com.cloud.org.Cluster; import com.cloud.resource.ResourceManager; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.StorageManager; import com.cloud.storage.StoragePool; import com.cloud.storage.StoragePoolVO; import com.cloud.storage.VMTemplateVO; import com.cloud.storage.Volume; import com.cloud.storage.Volume.Type; import com.cloud.storage.VolumeVO; import com.cloud.storage.dao.GuestOSCategoryDao; import com.cloud.storage.dao.GuestOSDao; import com.cloud.storage.dao.StoragePoolDao; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.User; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserDao; import com.cloud.uservm.UserVm; import com.cloud.utils.DateUtil; import com.cloud.utils.Journal; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.Ternary; import com.cloud.utils.component.Adapters; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Inject; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.ExecutionException; import com.cloud.utils.fsm.NoTransitionException; import com.cloud.utils.fsm.StateMachine2; import com.cloud.vm.ItWorkVO.Step; import com.cloud.vm.VirtualMachine.Event; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.dao.ConsoleProxyDao; import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.NicDao; import com.cloud.vm.dao.SecondaryStorageVmDao; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; @Local(value = VirtualMachineManager.class) public class VirtualMachineManagerImpl implements VirtualMachineManager, Listener { private static final Logger s_logger = Logger.getLogger(VirtualMachineManagerImpl.class); String _name; @Inject protected StorageManager _storageMgr; @Inject protected NetworkManager _networkMgr; @Inject protected AgentManager _agentMgr; @Inject protected VMInstanceDao _vmDao; @Inject protected ServiceOfferingDao _offeringDao; @Inject protected VMTemplateDao _templateDao; @Inject protected UserDao _userDao; @Inject protected AccountDao _accountDao; @Inject protected DomainDao _domainDao; @Inject protected ClusterManager _clusterMgr; @Inject protected ItWorkDao _workDao; @Inject protected UserVmDao _userVmDao; @Inject protected DomainRouterDao _routerDao; @Inject protected ConsoleProxyDao _consoleDao; @Inject protected SecondaryStorageVmDao _secondaryDao; @Inject protected NicDao _nicsDao; @Inject protected AccountManager _accountMgr; @Inject protected HostDao _hostDao; @Inject protected AlertManager _alertMgr; @Inject protected GuestOSCategoryDao _guestOsCategoryDao; @Inject protected GuestOSDao _guestOsDao; @Inject protected VolumeDao _volsDao; @Inject protected ConsoleProxyManager _consoleProxyMgr; @Inject protected ConfigurationManager _configMgr; @Inject protected CapacityManager _capacityMgr; @Inject protected HighAvailabilityManager _haMgr; @Inject protected HostPodDao _podDao; @Inject protected DataCenterDao _dcDao; @Inject protected StoragePoolDao _storagePoolDao; @Inject protected HypervisorGuruManager _hvGuruMgr; @Inject(adapter = DeploymentPlanner.class) protected Adapters<DeploymentPlanner> _planners; @Inject(adapter = HostAllocator.class) protected Adapters<HostAllocator> _hostAllocators; @Inject protected ResourceManager _resourceMgr; Map<VirtualMachine.Type, VirtualMachineGuru<? extends VMInstanceVO>> _vmGurus = new HashMap<VirtualMachine.Type, VirtualMachineGuru<? extends VMInstanceVO>>(); protected StateMachine2<State, VirtualMachine.Event, VirtualMachine> _stateMachine; ScheduledExecutorService _executor = null; protected int _operationTimeout; protected int _retry; protected long _nodeId; protected long _cleanupWait; protected long _cleanupInterval; protected long _cancelWait; protected long _opWaitInterval; protected int _lockStateRetry; protected boolean _forceStop; @Override public <T extends VMInstanceVO> void registerGuru(VirtualMachine.Type type, VirtualMachineGuru<T> guru) { synchronized (_vmGurus) { _vmGurus.put(type, guru); } } @Override @DB public <T extends VMInstanceVO> T allocate(T vm, VMTemplateVO template, ServiceOfferingVO serviceOffering, Pair<? extends DiskOfferingVO, Long> rootDiskOffering, List<Pair<DiskOfferingVO, Long>> dataDiskOfferings, List<Pair<NetworkVO, NicProfile>> networks, Map<VirtualMachineProfile.Param, Object> params, DeploymentPlan plan, HypervisorType hyperType, Account owner) throws InsufficientCapacityException { if (s_logger.isDebugEnabled()) { s_logger.debug("Allocating entries for VM: " + vm); } VirtualMachineProfileImpl<T> vmProfile = new VirtualMachineProfileImpl<T>(vm, template, serviceOffering, owner, params); vm.setDataCenterId(plan.getDataCenterId()); if (plan.getPodId() != null) { vm.setPodId(plan.getPodId()); } assert (plan.getClusterId() == null && plan.getPoolId() == null) : "We currently don't support cluster and pool preset yet"; @SuppressWarnings("unchecked") VirtualMachineGuru<T> guru = (VirtualMachineGuru<T>) _vmGurus.get(vm.getType()); Transaction txn = Transaction.currentTxn(); txn.start(); vm = guru.persist(vm); if (s_logger.isDebugEnabled()) { s_logger.debug("Allocating nics for " + vm); } try { _networkMgr.allocate(vmProfile, networks); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Concurrent operation while trying to allocate resources for the VM", e); } if (dataDiskOfferings == null) { dataDiskOfferings = new ArrayList<Pair<DiskOfferingVO, Long>>(0); } if (s_logger.isDebugEnabled()) { s_logger.debug("Allocaing disks for " + vm); } if (template.getFormat() == ImageFormat.ISO) { _storageMgr.allocateRawVolume(Type.ROOT, "ROOT-" + vm.getId(), rootDiskOffering.first(), rootDiskOffering.second(), vm, owner); } else if (template.getFormat() == ImageFormat.BAREMETAL) { // Do nothing } else { _storageMgr.allocateTemplatedVolume(Type.ROOT, "ROOT-" + vm.getId(), rootDiskOffering.first(), template, vm, owner); } for (Pair<DiskOfferingVO, Long> offering : dataDiskOfferings) { _storageMgr.allocateRawVolume(Type.DATADISK, "DATA-" + vm.getId(), offering.first(), offering.second(), vm, owner); } txn.commit(); if (s_logger.isDebugEnabled()) { s_logger.debug("Allocation completed for VM: " + vm); } return vm; } @Override public <T extends VMInstanceVO> T allocate(T vm, VMTemplateVO template, ServiceOfferingVO serviceOffering, Long rootSize, Pair<DiskOfferingVO, Long> dataDiskOffering, List<Pair<NetworkVO, NicProfile>> networks, DeploymentPlan plan, HypervisorType hyperType, Account owner) throws InsufficientCapacityException { List<Pair<DiskOfferingVO, Long>> diskOfferings = new ArrayList<Pair<DiskOfferingVO, Long>>(1); if (dataDiskOffering != null) { diskOfferings.add(dataDiskOffering); } return allocate(vm, template, serviceOffering, new Pair<DiskOfferingVO, Long>(serviceOffering, rootSize), diskOfferings, networks, null, plan, hyperType, owner); } @Override public <T extends VMInstanceVO> T allocate(T vm, VMTemplateVO template, ServiceOfferingVO serviceOffering, List<Pair<NetworkVO, NicProfile>> networks, DeploymentPlan plan, HypervisorType hyperType, Account owner) throws InsufficientCapacityException { return allocate(vm, template, serviceOffering, new Pair<DiskOfferingVO, Long>(serviceOffering, null), null, networks, null, plan, hyperType, owner); } @SuppressWarnings("unchecked") private <T extends VMInstanceVO> VirtualMachineGuru<T> getVmGuru(T vm) { return (VirtualMachineGuru<T>) _vmGurus.get(vm.getType()); } @SuppressWarnings("unchecked") private <T extends VMInstanceVO> VirtualMachineGuru<T> getBareMetalVmGuru(T vm) { return (VirtualMachineGuru<T>) _vmGurus.get(VirtualMachine.Type.UserBareMetal); } @Override public <T extends VMInstanceVO> boolean expunge(T vm, User caller, Account account) throws ResourceUnavailableException { try { if (advanceExpunge(vm, caller, account)) { // Mark vms as removed remove(vm, caller, account); return true; } else { s_logger.info("Did not expunge " + vm); return false; } } catch (OperationTimedoutException e) { throw new CloudRuntimeException("Operation timed out", e); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Concurrent operation ", e); } } @Override public <T extends VMInstanceVO> boolean advanceExpunge(T vm, User caller, Account account) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException { if (vm == null || vm.getRemoved() != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find vm or vm is destroyed: " + vm); } return true; } if (!this.advanceStop(vm, false, caller, account)) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to stop the VM so we can't expunge it."); } } try { if (!stateTransitTo(vm, VirtualMachine.Event.ExpungeOperation, vm.getHostId())) { s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm); return false; } } catch (NoTransitionException e) { s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm); return false; } if (s_logger.isDebugEnabled()) { s_logger.debug("Destroying vm " + vm); } VirtualMachineProfile<T> profile = new VirtualMachineProfileImpl<T>(vm); _networkMgr.cleanupNics(profile); // Clean up volumes based on the vm's instance id _storageMgr.cleanupVolumes(vm.getId()); VirtualMachineGuru<T> guru = getVmGuru(vm); guru.finalizeExpunge(vm); if (s_logger.isDebugEnabled()) { s_logger.debug("Expunged " + vm); } return true; } @Override public boolean start() { _executor.scheduleAtFixedRate(new CleanupTask(), _cleanupInterval, _cleanupInterval, TimeUnit.SECONDS); cancelWorkItems(_nodeId); return true; } @Override public boolean stop() { return true; } @Override public boolean configure(String name, Map<String, Object> xmlParams) throws ConfigurationException { _name = name; ComponentLocator locator = ComponentLocator.getCurrentLocator(); ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); Map<String, String> params = configDao.getConfiguration(xmlParams); _retry = NumbersUtil.parseInt(params.get(Config.StartRetry.key()), 10); ReservationContextImpl.setComponents(_userDao, _domainDao, _accountDao); VirtualMachineProfileImpl.setComponents(_offeringDao, _templateDao, _accountDao); _cancelWait = NumbersUtil.parseLong(params.get(Config.VmOpCancelInterval.key()), 3600); _cleanupWait = NumbersUtil.parseLong(params.get(Config.VmOpCleanupWait.key()), 3600); _cleanupInterval = NumbersUtil.parseLong(params.get(Config.VmOpCleanupInterval.key()), 86400) * 1000; _opWaitInterval = NumbersUtil.parseLong(params.get(Config.VmOpWaitInterval.key()), 120) * 1000; _lockStateRetry = NumbersUtil.parseInt(params.get(Config.VmOpLockStateRetry.key()), 5); _operationTimeout = NumbersUtil.parseInt(params.get(Config.Wait.key()), 1800) * 2; _forceStop = Boolean.parseBoolean(params.get(Config.VmDestroyForcestop.key())); _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Vm-Operations-Cleanup")); _nodeId = _clusterMgr.getManagementNodeId(); _agentMgr.registerForHostEvents(this, true, true, true); return true; } @Override public String getName() { return _name; } protected VirtualMachineManagerImpl() { setStateMachine(); } @Override public <T extends VMInstanceVO> T start(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException, ResourceUnavailableException { return start(vm, params, caller, account, null); } @Override public <T extends VMInstanceVO> T start(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account, DeploymentPlan planToDeploy) throws InsufficientCapacityException, ResourceUnavailableException { try { return advanceStart(vm, params, caller, account, planToDeploy); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Unable to start a VM due to concurrent operation", e); } } protected boolean checkWorkItems(VMInstanceVO vm, State state) throws ConcurrentOperationException { while (true) { ItWorkVO vo = _workDao.findByOutstandingWork(vm.getId(), state); if (vo == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find work for VM: " + vm + " and state: " + state); } return true; } if (vo.getStep() == Step.Done) { if (s_logger.isDebugEnabled()) { s_logger.debug("Work for " + vm + " is " + vo.getStep()); } return true; } if (vo.getSecondsTaskIsInactive() > _cancelWait) { s_logger.warn("The task item for vm " + vm + " has been inactive for " + vo.getSecondsTaskIsInactive()); return false; } try { Thread.sleep(_opWaitInterval); } catch (InterruptedException e) { s_logger.info("Waiting for " + vm + " but is interrupted"); throw new ConcurrentOperationException("Waiting for " + vm + " but is interrupted"); } s_logger.debug("Waiting some more to make sure there's no activity on " + vm); } } @DB protected <T extends VMInstanceVO> Ternary<T, ReservationContext, ItWorkVO> changeToStartState(VirtualMachineGuru<T> vmGuru, T vm, User caller, Account account) throws ConcurrentOperationException { long vmId = vm.getId(); ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Starting, vm.getType(), vm.getId()); int retry = _lockStateRetry; while (retry Transaction txn = Transaction.currentTxn(); Ternary<T, ReservationContext, ItWorkVO> result = null; txn.start(); try { Journal journal = new Journal.LogJournal("Creating " + vm, s_logger); work = _workDao.persist(work); ReservationContextImpl context = new ReservationContextImpl(work.getId(), journal, caller, account); if (stateTransitTo(vm, Event.StartRequested, null, work.getId())) { if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully transitioned to start state for " + vm + " reservation id = " + work.getId()); } result = new Ternary<T, ReservationContext, ItWorkVO>(vmGuru.findById(vmId), context, work); txn.commit(); return result; } } catch (NoTransitionException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to transition into Starting state due to " + e.getMessage()); } } finally { if (result == null) { txn.rollback(); } } VMInstanceVO instance = _vmDao.findById(vmId); if (instance == null) { throw new ConcurrentOperationException("Unable to acquire lock on " + vm); } if (s_logger.isDebugEnabled()) { s_logger.debug("Determining why we're unable to update the state to Starting for " + instance + ". Retry=" + retry); } State state = instance.getState(); if (state == State.Running) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM is already started: " + vm); } return null; } if (state.isTransitional()) { if (!checkWorkItems(vm, state)) { throw new ConcurrentOperationException("There are concurrent operations on " + vm); } else { continue; } } if (state != State.Stopped) { s_logger.debug("VM " + vm + " is not in a state to be started: " + state); return null; } } throw new ConcurrentOperationException("Unable to change the state of " + vm); } protected <T extends VMInstanceVO> boolean changeState(T vm, Event event, Long hostId, ItWorkVO work, Step step) throws NoTransitionException { // FIXME: We should do this better. Step previousStep = work.getStep(); _workDao.updateStep(work, step); boolean result = false; try { result = stateTransitTo(vm, event, hostId); return result; } finally { if (!result) { _workDao.updateStep(work, previousStep); } } } @Override public <T extends VMInstanceVO> T advanceStart(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { return advanceStart(vm, params, caller, account, null); } @Override public <T extends VMInstanceVO> T advanceStart(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account, DeploymentPlan planToDeploy) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { long vmId = vm.getId(); VirtualMachineGuru<T> vmGuru; if (vm.getHypervisorType() == HypervisorType.BareMetal) { vmGuru = getBareMetalVmGuru(vm); } else { vmGuru = getVmGuru(vm); } vm = vmGuru.findById(vm.getId()); Ternary<T, ReservationContext, ItWorkVO> start = changeToStartState(vmGuru, vm, caller, account); if (start == null) { return vmGuru.findById(vmId); } vm = start.first(); ReservationContext ctx = start.second(); ItWorkVO work = start.third(); T startedVm = null; ServiceOfferingVO offering = _offeringDao.findById(vm.getServiceOfferingId()); VMTemplateVO template = _templateDao.findById(vm.getTemplateId()); if (s_logger.isDebugEnabled()) { s_logger.debug("Trying to deploy VM, vm has dcId: " + vm.getDataCenterIdToDeployIn() + " and podId: " + vm.getPodIdToDeployIn()); } DataCenterDeployment plan = new DataCenterDeployment(vm.getDataCenterIdToDeployIn(), vm.getPodIdToDeployIn(), null, null, null); if (planToDeploy != null && planToDeploy.getDataCenterId() != 0) { if (s_logger.isDebugEnabled()) { s_logger.debug("advanceStart: DeploymentPlan is provided, using dcId:" + planToDeploy.getDataCenterId() + ", podId: " + planToDeploy.getPodId() + ", clusterId: " + planToDeploy.getClusterId() + ", hostId: " + planToDeploy.getHostId() + ", poolId: " + planToDeploy.getPoolId()); } plan = (DataCenterDeployment) planToDeploy; } HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType()); boolean canRetry = true; try { Journal journal = start.second().getJournal(); ExcludeList avoids = null; if (planToDeploy != null) { avoids = planToDeploy.getAvoids(); } if (avoids == null) { avoids = new ExcludeList(); } if (s_logger.isDebugEnabled()) { s_logger.debug("Deploy avoids pods: " + avoids.getPodsToAvoid() + ", clusters: " + avoids.getClustersToAvoid() + ", hosts: " + avoids.getHostsToAvoid()); } // edit plan if this vm's ROOT volume is in READY state already List<VolumeVO> vols = _volsDao.findReadyRootVolumesByInstance(vm.getId()); boolean planChangedByVolume = false; boolean rootVolumeisRecreatable = false; DataCenterDeployment originalPlan = plan; for (VolumeVO vol : vols) { // make sure if the templateId is unchanged. If it is changed, // let planner // reassign pool for the volume even if it ready. Long volTemplateId = vol.getTemplateId(); if (volTemplateId != null && volTemplateId.longValue() != template.getId()) { if (s_logger.isDebugEnabled()) { s_logger.debug(vol + " of " + vm + " is READY, but template ids don't match, let the planner reassign a new pool"); } continue; } StoragePoolVO pool = _storagePoolDao.findById(vol.getPoolId()); if (!pool.isInMaintenance()) { if (s_logger.isDebugEnabled()) { s_logger.debug("Root volume is ready, need to place VM in volume's cluster"); } long rootVolDcId = pool.getDataCenterId(); Long rootVolPodId = pool.getPodId(); Long rootVolClusterId = pool.getClusterId(); if (planToDeploy != null && planToDeploy.getDataCenterId() != 0) { Long clusterIdSpecified = planToDeploy.getClusterId(); if (clusterIdSpecified != null && rootVolClusterId != null) { if (rootVolClusterId.longValue() != clusterIdSpecified.longValue()) { // cannot satisfy the plan passed in to the // planner if (s_logger.isDebugEnabled()) { s_logger.debug("Cannot satisfy the deployment plan passed in since the ready Root volume is in different cluster. volume's cluster: " + rootVolClusterId + ", cluster specified: " + clusterIdSpecified); } throw new ResourceUnavailableException("Root volume is ready in different cluster, Deployment plan provided cannot be satisfied, unable to create a deployment for " + vm, Cluster.class, clusterIdSpecified); } } plan = new DataCenterDeployment(planToDeploy.getDataCenterId(), planToDeploy.getPodId(), planToDeploy.getClusterId(), planToDeploy.getHostId(), vol.getPoolId()); } else { plan = new DataCenterDeployment(rootVolDcId, rootVolPodId, rootVolClusterId, null, vol.getPoolId()); if (s_logger.isDebugEnabled()) { s_logger.debug(vol + " is READY, changing deployment plan to use this pool's dcId: " + rootVolDcId + " , podId: " + rootVolPodId + " , and clusterId: " + rootVolClusterId); } planChangedByVolume = true; if (vol.isRecreatable()) { rootVolumeisRecreatable = true; } } } } int retry = _retry; while (retry-- != 0) { // It's != so that it can match -1. VirtualMachineProfileImpl<T> vmProfile = new VirtualMachineProfileImpl<T>(vm, template, offering, account, params); DeployDestination dest = null; for (DeploymentPlanner planner : _planners) { if (planner.canHandle(vmProfile, plan, avoids)) { dest = planner.plan(vmProfile, plan, avoids); } else { continue; } if (dest != null) { avoids.addHost(dest.getHost().getId()); journal.record("Deployment found ", vmProfile, dest); break; } } if (dest == null) { if (planChangedByVolume) { if (rootVolumeisRecreatable) { plan = originalPlan; planChangedByVolume = false; continue; } } throw new InsufficientServerCapacityException("Unable to create a deployment for " + vmProfile, DataCenter.class, plan.getDataCenterId()); } long destHostId = dest.getHost().getId(); vm.setPodId(dest.getPod().getId()); try { if (!changeState(vm, Event.OperationRetry, destHostId, work, Step.Prepare)) { throw new ConcurrentOperationException("Unable to update the state of the Virtual Machine"); } } catch (NoTransitionException e1) { throw new ConcurrentOperationException(e1.getMessage()); } try { if (s_logger.isDebugEnabled()) { s_logger.debug("VM is being started in podId: " + vm.getPodIdToDeployIn()); } _networkMgr.prepare(vmProfile, dest, ctx); if (vm.getHypervisorType() != HypervisorType.BareMetal) { _storageMgr.prepare(vmProfile, dest); } vmGuru.finalizeVirtualMachineProfile(vmProfile, dest, ctx); VirtualMachineTO vmTO = hvGuru.implement(vmProfile); Commands cmds = new Commands(OnError.Stop); cmds.addCommand(new StartCommand(vmTO)); vmGuru.finalizeDeployment(cmds, vmProfile, dest, ctx); work = _workDao.findById(work.getId()); if (work == null || work.getStep() != Step.Prepare) { throw new ConcurrentOperationException("Work steps have been changed: " + work); } _workDao.updateStep(work, Step.Starting); _agentMgr.send(destHostId, cmds); _workDao.updateStep(work, Step.Started); StartAnswer startAnswer = cmds.getAnswer(StartAnswer.class); if (startAnswer != null && startAnswer.getResult()) { String host_guid = startAnswer.getHost_guid(); if( host_guid != null ) { HostVO finalHost = _resourceMgr.findHostByGuid(host_guid); if ( finalHost == null ) { throw new CloudRuntimeException("Host Guid " + host_guid + " doesn't exist in DB, something wrong here"); } destHostId = finalHost.getId(); } if (vmGuru.finalizeStart(vmProfile, destHostId, cmds, ctx)) { if (!changeState(vm, Event.OperationSucceeded, destHostId, work, Step.Done)) { throw new ConcurrentOperationException("Unable to transition to a new state."); } startedVm = vm; if (s_logger.isDebugEnabled()) { s_logger.debug("Start completed for VM " + vm); } return startedVm; } else { if (s_logger.isDebugEnabled()) { s_logger.info("The guru did not like the answers so stopping " + vm); } StopCommand cmd = new StopCommand(vm.getInstanceName()); StopAnswer answer = (StopAnswer) _agentMgr.easySend(destHostId, cmd); if (answer == null || !answer.getResult()) { s_logger.warn("Unable to stop " + vm + " due to " + (answer != null ? answer.getDetails() : "no answers")); canRetry = false; _haMgr.scheduleStop(vm, destHostId, WorkType.ForceStop); throw new ExecutionException("Unable to stop " + vm + " so we are unable to retry the start operation"); } } } s_logger.info("Unable to start VM on " + dest.getHost() + " due to " + (startAnswer == null ? " no start answer" : startAnswer.getDetails())); } catch (OperationTimedoutException e) { s_logger.debug("Unable to send the start command to host " + dest.getHost()); if (e.isActive()) { _haMgr.scheduleStop(vm, destHostId, WorkType.CheckStop); } canRetry = false; throw new AgentUnavailableException("Unable to start " + vm.getHostName(), destHostId, e); } catch (ResourceUnavailableException e) { s_logger.info("Unable to contact resource.", e); if (!avoids.add(e)) { if (e.getScope() == Volume.class || e.getScope() == Nic.class) { throw e; } else { s_logger.warn("unexpected ResourceUnavailableException : " + e.getScope().getName(), e); throw e; } } } catch (InsufficientCapacityException e) { s_logger.info("Insufficient capacity ", e); if (!avoids.add(e)) { if (e.getScope() == Volume.class || e.getScope() == Nic.class) { throw e; } else { s_logger.warn("unexpected InsufficientCapacityException : " + e.getScope().getName(), e); } } } catch (Exception e) { s_logger.error("Failed to start instance " + vm, e); throw new AgentUnavailableException("Unable to start instance", destHostId, e); } finally { if (startedVm == null && canRetry) { _workDao.updateStep(work, Step.Release); cleanup(vmGuru, vmProfile, work, Event.OperationFailed, false, caller, account); } } } } finally { if (startedVm == null) { if (canRetry) { try { changeState(vm, Event.OperationFailed, null, work, Step.Done); } catch (NoTransitionException e) { throw new ConcurrentOperationException(e.getMessage()); } } } } return startedVm; } @Override public <T extends VMInstanceVO> boolean stop(T vm, User user, Account account) throws ResourceUnavailableException { try { return advanceStop(vm, false, user, account); } catch (OperationTimedoutException e) { throw new AgentUnavailableException("Unable to stop vm because the operation to stop timed out", vm.getHostId(), e); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Unable to stop vm because of a concurrent operation", e); } } protected <T extends VMInstanceVO> boolean sendStop(VirtualMachineGuru<T> guru, VirtualMachineProfile<T> profile, boolean force) { VMInstanceVO vm = profile.getVirtualMachine(); StopCommand stop = new StopCommand(vm, vm.getInstanceName(), null); try { Answer answer = _agentMgr.send(vm.getHostId(), stop); if (!answer.getResult()) { s_logger.debug("Unable to stop VM due to " + answer.getDetails()); return false; } guru.finalizeStop(profile, (StopAnswer) answer); } catch (AgentUnavailableException e) { if (!force) { return false; } } catch (OperationTimedoutException e) { if (!force) { return false; } } return true; } protected <T extends VMInstanceVO> boolean cleanup(VirtualMachineGuru<T> guru, VirtualMachineProfile<T> profile, ItWorkVO work, Event event, boolean force, User user, Account account) { T vm = profile.getVirtualMachine(); State state = vm.getState(); s_logger.debug("Cleaning up resources for the vm " + vm + " in " + state + " state"); if (state == State.Starting) { Step step = work.getStep(); if (step == Step.Starting && !force) { s_logger.warn("Unable to cleanup vm " + vm + "; work state is incorrect: " + step); return false; } if (step == Step.Started || step == Step.Starting) { if (vm.getHostId() != null) { if (!sendStop(guru, profile, force)) { s_logger.warn("Failed to stop vm " + vm + " in " + State.Starting + " state as a part of cleanup process"); return false; } } } if (step != Step.Release && step != Step.Prepare && step != Step.Started && step != Step.Starting) { s_logger.debug("Cleanup is not needed for vm " + vm + "; work state is incorrect: " + step); return true; } } else if (state == State.Stopping) { if (vm.getHostId() != null) { if (!sendStop(guru, profile, force)) { s_logger.warn("Failed to stop vm " + vm + " in " + State.Stopping + " state as a part of cleanup process"); return false; } } } else if (state == State.Migrating) { if (vm.getHostId() != null) { if (!sendStop(guru, profile, force)) { s_logger.warn("Failed to stop vm " + vm + " in " + State.Migrating + " state as a part of cleanup process"); return false; } } if (vm.getLastHostId() != null) { if (!sendStop(guru, profile, force)) { s_logger.warn("Failed to stop vm " + vm + " in " + State.Migrating + " state as a part of cleanup process"); return false; } } } else if (state == State.Running) { if (!sendStop(guru, profile, force)) { s_logger.warn("Failed to stop vm " + vm + " in " + State.Running + " state as a part of cleanup process"); return false; } } _networkMgr.release(profile, force); _storageMgr.release(profile); s_logger.debug("Successfully cleanued up resources for the vm " + vm + " in " + state + " state"); return true; } @Override public <T extends VMInstanceVO> boolean advanceStop(T vm, boolean forced, User user, Account account) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { State state = vm.getState(); if (state == State.Stopped) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM is already stopped: " + vm); } return true; } if (state == State.Destroyed || state == State.Expunging || state == State.Error) { if (s_logger.isDebugEnabled()) { s_logger.debug("Stopped called on " + vm + " but the state is " + state); } return true; } // grab outstanding work item if any ItWorkVO work = _workDao.findByOutstandingWork(vm.getId(), vm.getState()); if (work != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Found an outstanding work item for this vm " + vm + " with state:" + vm.getState() + ", work id:" + work.getId()); } } Long hostId = vm.getHostId(); if (hostId == null) { if (!forced) { if (s_logger.isDebugEnabled()) { s_logger.debug("HostId is null but this is not a forced stop, cannot stop vm " + vm + " with state:" + vm.getState()); } return false; } try { stateTransitTo(vm, Event.AgentReportStopped, null, null); } catch (NoTransitionException e) { s_logger.warn(e.getMessage()); } // mark outstanding work item if any as done if (work != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Updating work item to Done, id:" + work.getId()); } work.setStep(Step.Done); _workDao.update(work.getId(), work); } return true; } VirtualMachineGuru<T> vmGuru = getVmGuru(vm); VirtualMachineProfile<T> profile = new VirtualMachineProfileImpl<T>(vm); try { if (!stateTransitTo(vm, Event.StopRequested, vm.getHostId())) { throw new ConcurrentOperationException("VM is being operated on."); } } catch (NoTransitionException e1) { if (!forced) { throw new CloudRuntimeException("We cannot stop " + vm + " when it is in state " + vm.getState()); } boolean doCleanup = false; if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to transition the state but we're moving on because it's forced stop"); } if (state == State.Starting || state == State.Migrating) { if (work != null) { doCleanup = true; } else { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to cleanup VM: " + vm + " ,since outstanding work item is not found"); } throw new CloudRuntimeException("Work item not found, We cannot stop " + vm + " when it is in state " + vm.getState()); } } else if (state == State.Stopping) { doCleanup = true; } if (doCleanup) { if (cleanup(vmGuru, new VirtualMachineProfileImpl<T>(vm), work, Event.StopRequested, forced, user, account)) { try { if (s_logger.isDebugEnabled()) { s_logger.debug("Updating work item to Done, id:" + work.getId()); } return changeState(vm, Event.AgentReportStopped, null, work, Step.Done); } catch (NoTransitionException e) { s_logger.warn("Unable to cleanup " + vm); return false; } } else { if (s_logger.isDebugEnabled()) { s_logger.debug("Failed to cleanup VM: " + vm); } throw new CloudRuntimeException("Failed to cleanup " + vm + " , current state " + vm.getState()); } } } if (vm.getState() != State.Stopping) { throw new CloudRuntimeException("We cannot proceed with stop VM " + vm + " since it is not in 'Stopping' state, current state: " + vm.getState()); } String routerPrivateIp = null; if (vm.getType() == VirtualMachine.Type.DomainRouter) { routerPrivateIp = vm.getPrivateIpAddress(); } StopCommand stop = new StopCommand(vm, vm.getInstanceName(), null, routerPrivateIp); boolean stopped = false; StopAnswer answer = null; try { answer = (StopAnswer) _agentMgr.send(vm.getHostId(), stop); stopped = answer.getResult(); if (!stopped) { throw new CloudRuntimeException("Unable to stop the virtual machine due to " + answer.getDetails()); } vmGuru.finalizeStop(profile, answer); } catch (AgentUnavailableException e) { } catch (OperationTimedoutException e) { } finally { if (!stopped) { if (!forced) { s_logger.warn("Unable to stop vm " + vm); try { stateTransitTo(vm, Event.OperationFailed, vm.getHostId()); } catch (NoTransitionException e) { s_logger.warn("Unable to transition the state " + vm); } return false; } else { s_logger.warn("Unable to actually stop " + vm + " but continue with release because it's a force stop"); vmGuru.finalizeStop(profile, answer); } } } if (s_logger.isDebugEnabled()) { s_logger.debug(vm + " is stopped on the host. Proceeding to release resource held."); } try { _networkMgr.release(profile, forced); s_logger.debug("Successfully released network resources for the vm " + vm); } catch (Exception e) { s_logger.warn("Unable to release some network resources.", e); } try { if (vm.getHypervisorType() != HypervisorType.BareMetal) { _storageMgr.release(profile); s_logger.debug("Successfully released storage resources for the vm " + vm); } } catch (Exception e) { s_logger.warn("Unable to release storage resources.", e); } try { if (work != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Updating the outstanding work item to Done, id:" + work.getId()); } work.setStep(Step.Done); _workDao.update(work.getId(), work); } return stateTransitTo(vm, Event.OperationSucceeded, null, null); } catch (NoTransitionException e) { s_logger.warn(e.getMessage()); return false; } } private void setStateMachine() { _stateMachine = VirtualMachine.State.getStateMachine(); } protected boolean stateTransitTo(VMInstanceVO vm, VirtualMachine.Event e, Long hostId, String reservationId) throws NoTransitionException { vm.setReservationId(reservationId); return _stateMachine.transitTo(vm, e, new Pair<Long, Long>(vm.getHostId(), hostId), _vmDao); } @Override public boolean stateTransitTo(VMInstanceVO vm, VirtualMachine.Event e, Long hostId) throws NoTransitionException { State oldState = vm.getState(); if (oldState == State.Starting) { if (e == Event.OperationSucceeded) { vm.setLastHostId(hostId); } } else if (oldState == State.Stopping) { if (e == Event.OperationSucceeded) { vm.setLastHostId(vm.getHostId()); } } return _stateMachine.transitTo(vm, e, new Pair<Long, Long>(vm.getHostId(), hostId), _vmDao); } @Override public <T extends VMInstanceVO> boolean remove(T vm, User user, Account caller) { // expunge the corresponding nics VirtualMachineProfile<T> profile = new VirtualMachineProfileImpl<T>(vm); _networkMgr.expungeNics(profile); s_logger.trace("Nics of the vm " + vm + " are expunged successfully"); return _vmDao.remove(vm.getId()); } @Override public <T extends VMInstanceVO> boolean destroy(T vm, User user, Account caller) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { if (s_logger.isDebugEnabled()) { s_logger.debug("Destroying vm " + vm); } if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging || vm.getRemoved() != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find vm or vm is destroyed: " + vm); } return true; } if (!advanceStop(vm, _forceStop, user, caller)) { s_logger.debug("Unable to stop " + vm); return false; } try { if (!stateTransitTo(vm, VirtualMachine.Event.DestroyRequested, vm.getHostId())) { s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm); return false; } } catch (NoTransitionException e) { s_logger.debug(e.getMessage()); return false; } return true; } protected boolean checkVmOnHost(VirtualMachine vm, long hostId) throws AgentUnavailableException, OperationTimedoutException { CheckVirtualMachineAnswer answer = (CheckVirtualMachineAnswer) _agentMgr.send(hostId, new CheckVirtualMachineCommand(vm.getInstanceName())); if (!answer.getResult() || answer.getState() == State.Stopped) { return false; } return true; } @Override public <T extends VMInstanceVO> T storageMigration(T vm, StoragePool destPool) { VirtualMachineGuru<T> vmGuru = getVmGuru(vm); long vmId = vm.getId(); vm = vmGuru.findById(vmId); try { stateTransitTo(vm, VirtualMachine.Event.StorageMigrationRequested, null); } catch (NoTransitionException e) { s_logger.debug("Unable to migrate vm: " + e.toString()); throw new CloudRuntimeException("Unable to migrate vm: " + e.toString()); } VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm); boolean migrationResult = false; try { migrationResult = _storageMgr.StorageMigration(profile, destPool); if (migrationResult) { //if the vm is migrated to different pod in basic mode, need to reallocate ip if (vm.getPodIdToDeployIn() != destPool.getPodId()) { DataCenterDeployment plan = new DataCenterDeployment(vm.getDataCenterIdToDeployIn(), destPool.getPodId(), null, null, null); VirtualMachineProfileImpl<T> vmProfile = new VirtualMachineProfileImpl<T>(vm, null, null, null, null); _networkMgr.reallocate(vmProfile, plan); } //when start the vm next time, don;'t look at last_host_id, only choose the host based on volume/storage pool vm.setLastHostId(null); vm.setPodId(destPool.getPodId()); } else { s_logger.debug("Storage migration failed"); } } catch (ConcurrentOperationException e) { s_logger.debug("Failed to migration: " + e.toString()); throw new CloudRuntimeException("Failed to migration: " + e.toString()); } catch (InsufficientVirtualNetworkCapcityException e) { s_logger.debug("Failed to migration: " + e.toString()); throw new CloudRuntimeException("Failed to migration: " + e.toString()); } catch (InsufficientAddressCapacityException e) { s_logger.debug("Failed to migration: " + e.toString()); throw new CloudRuntimeException("Failed to migration: " + e.toString()); } catch (InsufficientCapacityException e) { s_logger.debug("Failed to migration: " + e.toString()); throw new CloudRuntimeException("Failed to migration: " + e.toString()); } finally { try { stateTransitTo(vm, VirtualMachine.Event.AgentReportStopped, null); } catch (NoTransitionException e) { s_logger.debug("Failed to change vm state: " + e.toString()); throw new CloudRuntimeException("Failed to change vm state: " + e.toString()); } } return vm; } @Override public <T extends VMInstanceVO> T migrate(T vm, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException { s_logger.info("Migrating " + vm + " to " + dest); long dstHostId = dest.getHost().getId(); Host fromHost = _hostDao.findById(srcHostId); if (fromHost == null) { s_logger.info("Unable to find the host to migrate from: " + srcHostId); throw new CloudRuntimeException("Unable to find the host to migrate from: " + srcHostId); } if (fromHost.getClusterId().longValue() != dest.getCluster().getId()) { s_logger.info("Source and destination host are not in same cluster, unable to migrate to host: " + dest.getHost().getId()); throw new CloudRuntimeException("Source and destination host are not in same cluster, unable to migrate to host: " + dest.getHost().getId()); } VirtualMachineGuru<T> vmGuru = getVmGuru(vm); long vmId = vm.getId(); vm = vmGuru.findById(vmId); if (vm == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find the vm " + vm); } throw new ManagementServerException("Unable to find a virtual machine with id " + vmId); } if (vm.getState() != State.Running) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM is not Running, unable to migrate the vm " + vm); } throw new VirtualMachineMigrationException("VM is not Running, unable to migrate the vm currently " + vm + " , current state: " + vm.getState().toString()); } short alertType = AlertManager.ALERT_TYPE_USERVM_MIGRATE; if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) { alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE; } else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) { alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY_MIGRATE; } VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm); _networkMgr.prepareNicForMigration(profile, dest); _storageMgr.prepareForMigration(profile, dest); HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType()); VirtualMachineTO to = hvGuru.implement(profile); PrepareForMigrationCommand pfmc = new PrepareForMigrationCommand(to); ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Migrating, vm.getType(), vm.getId()); work.setStep(Step.Prepare); work.setResourceType(ItWorkVO.ResourceType.Host); work.setResourceId(dstHostId); work = _workDao.persist(work); PrepareForMigrationAnswer pfma = null; try { pfma = (PrepareForMigrationAnswer) _agentMgr.send(dstHostId, pfmc); if (!pfma.getResult()) { String msg = "Unable to prepare for migration due to " + pfma.getDetails(); pfma = null; throw new AgentUnavailableException(msg, dstHostId); } } catch (OperationTimedoutException e1) { throw new AgentUnavailableException("Operation timed out", dstHostId); } finally { if (pfma == null) { work.setStep(Step.Done); _workDao.update(work.getId(), work); } } vm.setLastHostId(srcHostId); try { if (vm == null || vm.getHostId() == null || vm.getHostId() != srcHostId || !changeState(vm, Event.MigrationRequested, dstHostId, work, Step.Migrating)) { s_logger.info("Migration cancelled because state has changed: " + vm); throw new ConcurrentOperationException("Migration cancelled because state has changed: " + vm); } } catch (NoTransitionException e1) { s_logger.info("Migration cancelled because " + e1.getMessage()); throw new ConcurrentOperationException("Migration cancelled because " + e1.getMessage()); } boolean migrated = false; try { boolean isWindows = _guestOsCategoryDao.findById(_guestOsDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows"); MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows); mc.setHostGuid(dest.getHost().getGuid()); try { MigrateAnswer ma = (MigrateAnswer) _agentMgr.send(vm.getLastHostId(), mc); if (!ma.getResult()) { s_logger.error("Unable to migrate due to " + ma.getDetails()); return null; } } catch (OperationTimedoutException e) { if (e.isActive()) { s_logger.warn("Active migration command so scheduling a restart for " + vm); _haMgr.scheduleRestart(vm, true); } throw new AgentUnavailableException("Operation timed out on migrating " + vm, dstHostId); } try { if (!changeState(vm, VirtualMachine.Event.OperationSucceeded, dstHostId, work, Step.Started)) { throw new ConcurrentOperationException("Unable to change the state for " + vm); } } catch (NoTransitionException e1) { throw new ConcurrentOperationException("Unable to change state due to " + e1.getMessage()); } try { if (!checkVmOnHost(vm, dstHostId)) { s_logger.error("Unable to complete migration for " + vm); try { _agentMgr.send(srcHostId, new Commands(cleanup(vm.getInstanceName())), null); } catch (AgentUnavailableException e) { s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId); } cleanup(vmGuru, new VirtualMachineProfileImpl<T>(vm), work, Event.AgentReportStopped, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount()); return null; } } catch (OperationTimedoutException e) { } migrated = true; return vm; } finally { if (!migrated) { s_logger.info("Migration was unsuccessful. Cleaning up: " + vm); _alertMgr.sendAlert(alertType, fromHost.getDataCenterId(), fromHost.getPodId(), "Unable to migrate vm " + vm.getInstanceName() + " from host " + fromHost.getName() + " in zone " + dest.getDataCenter().getName() + " and pod " + dest.getPod().getName(), "Migrate Command failed. Please check logs."); try { _agentMgr.send(dstHostId, new Commands(cleanup(vm.getInstanceName())), null); } catch (AgentUnavailableException ae) { s_logger.info("Looks like the destination Host is unavailable for cleanup"); } try { stateTransitTo(vm, Event.OperationFailed, srcHostId); } catch (NoTransitionException e) { s_logger.warn(e.getMessage()); } } work.setStep(Step.Done); _workDao.update(work.getId(), work); } } protected void cancelWorkItems(long nodeId) { GlobalLock scanLock = GlobalLock.getInternLock("vmmgr.cancel.workitem"); try { if (scanLock.lock(3)) { try { List<ItWorkVO> works = _workDao.listWorkInProgressFor(nodeId); for (ItWorkVO work : works) { s_logger.info("Handling unfinished work item: " + work); try { VMInstanceVO vm = _vmDao.findById(work.getInstanceId()); if (vm != null) { if (work.getType() == State.Starting) { _haMgr.scheduleRestart(vm, true); work.setManagementServerId(_nodeId); _workDao.update(work.getId(), work); } else if (work.getType() == State.Stopping) { _haMgr.scheduleStop(vm, vm.getHostId(), WorkType.CheckStop); work.setManagementServerId(_nodeId); _workDao.update(work.getId(), work); } else if (work.getType() == State.Migrating) { _haMgr.scheduleMigration(vm); work.setStep(Step.Done); _workDao.update(work.getId(), work); } } } catch (Exception e) { s_logger.error("Error while handling " + work, e); } } } finally { scanLock.unlock(); } } } finally { scanLock.releaseRef(); } } @Override public boolean migrateAway(VirtualMachine.Type vmType, long vmId, long srcHostId) throws InsufficientServerCapacityException, VirtualMachineMigrationException { VirtualMachineGuru<? extends VMInstanceVO> vmGuru = _vmGurus.get(vmType); VMInstanceVO vm = vmGuru.findById(vmId); if (vm == null) { s_logger.debug("Unable to find a VM for " + vmId); return true; } VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm); Long hostId = vm.getHostId(); if (hostId == null) { s_logger.debug("Unable to migrate because the VM doesn't have a host id: " + vm); return true; } Host host = _hostDao.findById(hostId); DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), null, null); ExcludeList excludes = new ExcludeList(); excludes.addHost(hostId); DeployDestination dest = null; while (true) { for (DeploymentPlanner planner : _planners) { if (planner.canHandle(profile, plan, excludes)) { dest = planner.plan(profile, plan, excludes); } else { continue; } if (dest != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Planner " + planner + " found " + dest + " for migrating to."); } break; } if (s_logger.isDebugEnabled()) { s_logger.debug("Planner " + planner + " was unable to find anything."); } } if (dest == null) { throw new InsufficientServerCapacityException("Unable to find a server to migrate to.", host.getClusterId()); } excludes.addHost(dest.getHost().getId()); VMInstanceVO vmInstance = null; try { vmInstance = migrate(vm, srcHostId, dest); } catch (ResourceUnavailableException e) { s_logger.debug("Unable to migrate to unavailable " + dest); } catch (ConcurrentOperationException e) { s_logger.debug("Unable to migrate VM due to: " + e.getMessage()); } catch (ManagementServerException e) { s_logger.debug("Unable to migrate VM: " + e.getMessage()); } catch (VirtualMachineMigrationException e) { s_logger.debug("Got VirtualMachineMigrationException, Unable to migrate: " + e.getMessage()); if (vm.getState() == State.Starting) { s_logger.debug("VM seems to be still Starting, we should retry migration later"); throw e; } else { s_logger.debug("Unable to migrate VM, VM is not in Running or even Starting state, current state: " + vm.getState().toString()); } } if (vmInstance != null) { return true; } try { boolean result = advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount()); return result; } catch (ResourceUnavailableException e) { s_logger.debug("Unable to stop VM due to " + e.getMessage()); } catch (ConcurrentOperationException e) { s_logger.debug("Unable to stop VM due to " + e.getMessage()); } catch (OperationTimedoutException e) { s_logger.debug("Unable to stop VM due to " + e.getMessage()); } return false; } } protected class CleanupTask implements Runnable { @Override public void run() { s_logger.trace("VM Operation Thread Running"); try { _workDao.cleanup(_cleanupWait); } catch (Exception e) { s_logger.error("VM Operations failed due to ", e); } } } @Override public boolean isVirtualMachineUpgradable(UserVm vm, ServiceOffering offering) { Enumeration<HostAllocator> en = _hostAllocators.enumeration(); boolean isMachineUpgradable = true; while (isMachineUpgradable && en.hasMoreElements()) { final HostAllocator allocator = en.nextElement(); isMachineUpgradable = allocator.isVirtualMachineUpgradable(vm, offering); } return isMachineUpgradable; } @Override public <T extends VMInstanceVO> T reboot(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException, ResourceUnavailableException { try { return advanceReboot(vm, params, caller, account); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Unable to reboot a VM due to concurrent operation", e); } } @Override public <T extends VMInstanceVO> T advanceReboot(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { T rebootedVm = null; DataCenter dc = _configMgr.getZone(vm.getDataCenterIdToDeployIn()); Host host = _hostDao.findById(vm.getHostId()); Cluster cluster = null; if (host != null) { cluster = _configMgr.getCluster(host.getClusterId()); } HostPodVO pod = _configMgr.getPod(host.getPodId()); DeployDestination dest = new DeployDestination(dc, pod, cluster, host); try { Commands cmds = new Commands(OnError.Stop); cmds.addCommand(new RebootCommand(vm.getInstanceName())); _agentMgr.send(host.getId(), cmds); Answer rebootAnswer = cmds.getAnswer(RebootAnswer.class); if (rebootAnswer != null && rebootAnswer.getResult()) { rebootedVm = vm; return rebootedVm; } s_logger.info("Unable to reboot VM " + vm + " on " + dest.getHost() + " due to " + (rebootAnswer == null ? " no reboot answer" : rebootAnswer.getDetails())); } catch (OperationTimedoutException e) { s_logger.warn("Unable to send the reboot command to host " + dest.getHost() + " for the vm " + vm + " due to operation timeout", e); throw new CloudRuntimeException("Failed to reboot the vm on host " + dest.getHost()); } return rebootedVm; } @Override public VMInstanceVO findByIdAndType(VirtualMachine.Type type, long vmId) { VirtualMachineGuru<? extends VMInstanceVO> guru = _vmGurus.get(type); return guru.findById(vmId); } public Command cleanup(String vmName) { return new StopCommand(vmName); } public Commands fullHostSync(final long hostId, StartupRoutingCommand startup) { Commands commands = new Commands(OnError.Continue); Map<Long, AgentVmInfo> infos = convertToInfos(startup); final List<? extends VMInstanceVO> vms = _vmDao.listByHostId(hostId); s_logger.debug("Found " + vms.size() + " VMs for host " + hostId); for (VMInstanceVO vm : vms) { AgentVmInfo info = infos.remove(vm.getId()); VMInstanceVO castedVm = null; if (info == null) { info = new AgentVmInfo(vm.getInstanceName(), getVmGuru(vm), vm, State.Stopped); castedVm = info.guru.findById(vm.getId()); } else { castedVm = info.vm; } HypervisorGuru hvGuru = _hvGuruMgr.getGuru(castedVm.getHypervisorType()); Command command = compareState(hostId, castedVm, info, true, hvGuru.trackVmHostChange()); if (command != null) { commands.addCommand(command); } } for (final AgentVmInfo left : infos.values()) { boolean found = false; for (VirtualMachineGuru<? extends VMInstanceVO> vmGuru : _vmGurus.values()) { VMInstanceVO vm = vmGuru.findByName(left.name); if (vm != null) { found = true; HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType()); if(hvGuru.trackVmHostChange()) { Command command = compareState(hostId, vm, left, true, true); if (command != null) { commands.addCommand(command); } } else { s_logger.warn("Stopping a VM, VM " + left.name + " migrate from Host " + vm.getHostId() + " to Host " + hostId ); commands.addCommand(cleanup(left.name)); } break; } } if ( ! found ) { s_logger.warn("Stopping a VM that we have no record of: " + left.name); commands.addCommand(cleanup(left.name)); } } return commands; } public Commands deltaHostSync(long hostId, Map<String, State> newStates) { Map<Long, AgentVmInfo> states = convertDeltaToInfos(newStates); Commands commands = new Commands(OnError.Continue); for (Map.Entry<Long, AgentVmInfo> entry : states.entrySet()) { AgentVmInfo info = entry.getValue(); VMInstanceVO vm = info.vm; Command command = null; if (vm != null) { HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType()); command = compareState(hostId, vm, info, false, hvGuru.trackVmHostChange()); } else { if (s_logger.isDebugEnabled()) { s_logger.debug("Cleaning up a VM that is no longer found: " + info.name); } command = cleanup(info.name); } if (command != null) { commands.addCommand(command); } } return commands; } public Commands deltaSync(Map<String, Pair<String, State>> newStates) { Map<Long, AgentVmInfo> states = convertToInfos(newStates); Commands commands = new Commands(OnError.Continue); for (Map.Entry<Long, AgentVmInfo> entry : states.entrySet()) { AgentVmInfo info = entry.getValue(); VMInstanceVO vm = info.vm; Command command = null; if (vm != null) { String hostGuid = info.getHostUuid(); Host host = _resourceMgr.findHostByGuid(hostGuid); long hId = host.getId(); HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType()); command = compareState(hId, vm, info, false, hvGuru.trackVmHostChange()); } else { if (s_logger.isDebugEnabled()) { s_logger.debug("Cleaning up a VM that is no longer found: " + info.name); } command = cleanup(info.name); } if (command != null) { commands.addCommand(command); } } return commands; } public Commands fullSync(final long clusterId, Map<String, Pair<String, State>> newStates) { Commands commands = new Commands(OnError.Continue); Map<Long, AgentVmInfo> infos = convertToInfos(newStates); long hId = 0; final List<VMInstanceVO> vms = _vmDao.listByClusterId(clusterId); for (VMInstanceVO vm : vms) { AgentVmInfo info = infos.remove(vm.getId()); VMInstanceVO castedVm = null; if (info == null) { // the vm is not there on cluster, check the vm status in DB if (vm.getState() == State.Starting && (DateUtil.currentGMTTime().getTime() - vm.getUpdateTime().getTime()) < 10*60*1000){ continue; // ignoring this VM as it is still settling } info = new AgentVmInfo(vm.getInstanceName(), getVmGuru(vm), vm, State.Stopped); castedVm = info.guru.findById(vm.getId()); hId = vm.getHostId() == null ? vm.getLastHostId() : vm.getHostId(); } else { castedVm = info.vm; String hostGuid = info.getHostUuid(); Host host = _resourceMgr.findHostByGuid(hostGuid); if (host == null) { infos.put(vm.getId(), info); continue; } hId = host.getId(); } HypervisorGuru hvGuru = _hvGuruMgr.getGuru(castedVm.getHypervisorType()); Command command = compareState(hId, castedVm, info, true, hvGuru.trackVmHostChange()); if (command != null) { commands.addCommand(command); } } for (final AgentVmInfo left : infos.values()) { s_logger.warn("Stopping a VM that we have no record of: " + left.name); commands.addCommand(cleanup(left.name)); } return commands; } protected Map<Long, AgentVmInfo> convertToInfos(final Map<String, Pair<String, State>> newStates) { final HashMap<Long, AgentVmInfo> map = new HashMap<Long, AgentVmInfo>(); if (newStates == null) { return map; } Collection<VirtualMachineGuru<? extends VMInstanceVO>> vmGurus = _vmGurus.values(); for (Map.Entry<String, Pair<String, State>> entry : newStates.entrySet()) { for (VirtualMachineGuru<? extends VMInstanceVO> vmGuru : vmGurus) { String name = entry.getKey(); VMInstanceVO vm = vmGuru.findByName(name); if (vm != null) { map.put(vm.getId(), new AgentVmInfo(entry.getKey(), vmGuru, vm, entry.getValue().second(), entry.getValue().first())); break; } Long id = vmGuru.convertToId(name); if (id != null) { map.put(id, new AgentVmInfo(entry.getKey(), vmGuru, null, entry.getValue().second(), entry.getValue().first())); break; } } } return map; } protected Map<Long, AgentVmInfo> convertToInfos(StartupRoutingCommand cmd) { final Map<String, VmState> states = cmd.getVmStates(); final HashMap<Long, AgentVmInfo> map = new HashMap<Long, AgentVmInfo>(); if (states == null) { return map; } Collection<VirtualMachineGuru<? extends VMInstanceVO>> vmGurus = _vmGurus.values(); for (Map.Entry<String, VmState> entry : states.entrySet()) { for (VirtualMachineGuru<? extends VMInstanceVO> vmGuru : vmGurus) { String name = entry.getKey(); VMInstanceVO vm = vmGuru.findByName(name); if (vm != null) { map.put(vm.getId(), new AgentVmInfo(entry.getKey(), vmGuru, vm, entry.getValue().getState(), entry.getValue().getHost() )); break; } Long id = vmGuru.convertToId(name); if (id != null) { map.put(id, new AgentVmInfo(entry.getKey(), vmGuru, null,entry.getValue().getState(), entry.getValue().getHost() )); break; } } } return map; } protected Map<Long, AgentVmInfo> convertDeltaToInfos(final Map<String, State> states) { final HashMap<Long, AgentVmInfo> map = new HashMap<Long, AgentVmInfo>(); if (states == null) { return map; } Collection<VirtualMachineGuru<? extends VMInstanceVO>> vmGurus = _vmGurus.values(); for (Map.Entry<String, State> entry : states.entrySet()) { for (VirtualMachineGuru<? extends VMInstanceVO> vmGuru : vmGurus) { String name = entry.getKey(); VMInstanceVO vm = vmGuru.findByName(name); if (vm != null) { map.put(vm.getId(), new AgentVmInfo(entry.getKey(), vmGuru, vm, entry.getValue())); break; } Long id = vmGuru.convertToId(name); if (id != null) { map.put(id, new AgentVmInfo(entry.getKey(), vmGuru, null,entry.getValue())); break; } } } return map; } /** * compareState does as its name suggests and compares the states between * management server and agent. It returns whether something should be * cleaned up * */ protected Command compareState(long hostId, VMInstanceVO vm, final AgentVmInfo info, final boolean fullSync, boolean trackExternalChange) { State agentState = info.state; final String agentName = info.name; final State serverState = vm.getState(); final String serverName = vm.getInstanceName(); Command command = null; if (s_logger.isDebugEnabled()) { s_logger.debug("VM " + serverName + ": cs state = " + serverState + " and realState = " + agentState); } if (agentState == State.Error) { agentState = State.Stopped; short alertType = AlertManager.ALERT_TYPE_USERVM; if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) { alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER; } else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) { alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY; } HostPodVO podVO = _podDao.findById(vm.getPodIdToDeployIn()); DataCenterVO dcVO = _dcDao.findById(vm.getDataCenterIdToDeployIn()); HostVO hostVO = _hostDao.findById(vm.getHostId()); String hostDesc = "name: " + hostVO.getName() + " (id:" + hostVO.getId() + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName(); _alertMgr.sendAlert(alertType, vm.getDataCenterIdToDeployIn(), vm.getPodIdToDeployIn(), "VM (name: " + vm.getInstanceName() + ", id: " + vm.getId() + ") stopped on host " + hostDesc + " due to storage failure", "Virtual Machine " + vm.getInstanceName() + " (id: " + vm.getId() + ") running on host [" + vm.getHostId() + "] stopped due to storage failure."); } if (trackExternalChange) { if (serverState == State.Starting) { if (vm.getHostId() != null && vm.getHostId() != hostId) { s_logger.info("CloudStack is starting VM on host " + vm.getHostId() + ", but status report comes from a different host " + hostId + ", skip status sync for vm: " + vm.getInstanceName()); return null; } } if (vm.getHostId() == null || hostId != vm.getHostId()) { try { stateTransitTo(vm, VirtualMachine.Event.AgentReportMigrated, hostId); } catch (NoTransitionException e) { } } } // during VM migration time, don't sync state will agent status update if (serverState == State.Migrating) { s_logger.debug("Skipping vm in migrating state: " + vm); return null; } if (trackExternalChange) { if (serverState == State.Starting) { if (vm.getHostId() != null && vm.getHostId() != hostId) { s_logger.info("CloudStack is starting VM on host " + vm.getHostId() + ", but status report comes from a different host " + hostId + ", skip status sync for vm: " + vm.getInstanceName()); return null; } } if (serverState == State.Running) { try { // we had a bug that sometimes VM may be at Running State // but host_id is null, we will cover it here. // means that when CloudStack DB lost of host information, // we will heal it with the info reported from host if (vm.getHostId() == null || hostId != vm.getHostId()) { if (s_logger.isDebugEnabled()) { s_logger.debug("detected host change when VM " + vm + " is at running state, VM could be live-migrated externally from host " + vm.getHostId() + " to host " + hostId); } stateTransitTo(vm, VirtualMachine.Event.AgentReportMigrated, hostId); } } catch (NoTransitionException e) { s_logger.warn(e.getMessage()); } } } if (agentState == serverState) { if (s_logger.isDebugEnabled()) { s_logger.debug("Both states are " + agentState + " for " + vm); } assert (agentState == State.Stopped || agentState == State.Running) : "If the states we send up is changed, this must be changed."; if (agentState == State.Running) { try { stateTransitTo(vm, VirtualMachine.Event.AgentReportRunning, hostId); } catch (NoTransitionException e) { s_logger.warn(e.getMessage()); } // FIXME: What if someone comes in and sets it to stopping? Then // what? return null; } s_logger.debug("State matches but the agent said stopped so let's send a cleanup command anyways."); return cleanup(agentName); } if (agentState == State.Shutdowned) { if (serverState == State.Running || serverState == State.Starting || serverState == State.Stopping) { try { advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount()); } catch (AgentUnavailableException e) { assert (false) : "How do we hit this with forced on?"; return null; } catch (OperationTimedoutException e) { assert (false) : "How do we hit this with forced on?"; return null; } catch (ConcurrentOperationException e) { assert (false) : "How do we hit this with forced on?"; return null; } } else { s_logger.debug("Sending cleanup to a shutdowned vm: " + agentName); command = cleanup(agentName); } } else if (agentState == State.Stopped) { // This state means the VM on the agent was detected previously // and now is gone. This is slightly different than if the VM // was never completed but we still send down a Stop Command // to ensure there's cleanup. if (serverState == State.Running) { // Our records showed that it should be running so let's restart _haMgr.scheduleRestart(vm, false); } else if (serverState == State.Stopping) { _haMgr.scheduleStop(vm, hostId, WorkType.ForceStop); s_logger.debug("Scheduling a check stop for VM in stopping mode: " + vm); } else if (serverState == State.Starting) { s_logger.debug("Ignoring VM in starting mode: " + vm.getInstanceName()); _haMgr.scheduleRestart(vm, false); } command = cleanup(agentName); } else if (agentState == State.Running) { if (serverState == State.Starting) { if (fullSync) { try { ensureVmRunningContext(hostId, vm, Event.AgentReportRunning); } catch (OperationTimedoutException e) { s_logger.error("Exception during update for running vm: " + vm, e); return null; } catch (ResourceUnavailableException e) { s_logger.error("Exception during update for running vm: " + vm, e); return null; } catch (NoTransitionException e) { s_logger.warn(e.getMessage()); } } } else if (serverState == State.Stopping) { s_logger.debug("Scheduling a stop command for " + vm); _haMgr.scheduleStop(vm, hostId, WorkType.Stop); } else { s_logger.debug("server VM state " + serverState + " does not meet expectation of a running VM report from agent"); // just be careful not to stop VM for things we don't handle // command = cleanup(agentName); } } return command; } private void ensureVmRunningContext(long hostId, VMInstanceVO vm, Event cause) throws OperationTimedoutException, ResourceUnavailableException, NoTransitionException { VirtualMachineGuru<VMInstanceVO> vmGuru = getVmGuru(vm); s_logger.debug("VM state is starting on full sync so updating it to running"); vm = findByIdAndType(vm.getType(), vm.getId()); // grab outstanding work item if any ItWorkVO work = _workDao.findByOutstandingWork(vm.getId(), vm.getState()); if (work != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Found an outstanding work item for this vm " + vm + " in state:" + vm.getState() + ", work id:" + work.getId()); } } try { stateTransitTo(vm, cause, hostId); } catch (NoTransitionException e1) { s_logger.warn(e1.getMessage()); } s_logger.debug("VM's " + vm + " state is starting on full sync so updating it to Running"); vm = vmGuru.findById(vm.getId()); // this should ensure vm has the most // up to date info VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm); List<NicVO> nics = _nicsDao.listByVmId(profile.getId()); for (NicVO nic : nics) { Network network = _networkMgr.getNetwork(nic.getNetworkId()); NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null); profile.addNic(nicProfile); } Commands cmds = new Commands(OnError.Stop); s_logger.debug("Finalizing commands that need to be send to complete Start process for the vm " + vm); if (vmGuru.finalizeCommandsOnStart(cmds, profile)) { if (cmds.size() != 0) { _agentMgr.send(vm.getHostId(), cmds); } if (vmGuru.finalizeStart(profile, vm.getHostId(), cmds, null)) { stateTransitTo(vm, cause, vm.getHostId()); } else { s_logger.error("Unable to finish finialization for running vm: " + vm); } } else { s_logger.error("Unable to finalize commands on start for vm: " + vm); } if (work != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Updating outstanding work item to Done, id:" + work.getId()); } work.setStep(Step.Done); _workDao.update(work.getId(), work); } } @Override public boolean isRecurring() { return false; } @Override public boolean processAnswers(long agentId, long seq, Answer[] answers) { for (final Answer answer : answers) { if (answer instanceof ClusterSyncAnswer) { ClusterSyncAnswer hs = (ClusterSyncAnswer) answer; if (hs.execute()){ if (hs.isFull()) { fullSync(hs.getClusterId(), hs.getNewStates()); } else if (hs.isDelta()){ deltaSync(hs.getNewStates()); } } hs.setExecuted(); } else if (!answer.getResult()) { s_logger.warn("Cleanup failed due to " + answer.getDetails()); } else { if (s_logger.isDebugEnabled()) { s_logger.debug("Cleanup succeeded. Details " + answer.getDetails()); } } } return true; } @Override public boolean processTimeout(long agentId, long seq) { return true; } @Override public int getTimeout() { return -1; } @Override public boolean processCommands(long agentId, long seq, Command[] cmds) { boolean processed = false; for (Command cmd : cmds) { if (cmd instanceof PingRoutingCommand) { PingRoutingCommand ping = (PingRoutingCommand) cmd; if (ping.getNewStates() != null && ping.getNewStates().size() > 0) { Commands commands = deltaHostSync(agentId, ping.getNewStates()); if (commands.size() > 0) { try { _agentMgr.send(agentId, commands, this); } catch (final AgentUnavailableException e) { s_logger.warn("Agent is now unavailable", e); } } } processed = true; } } return processed; } @Override public AgentControlAnswer processControlCommand(long agentId, AgentControlCommand cmd) { return null; } @Override public boolean processDisconnect(long agentId, Status state) { return true; } @Override public void processConnect(HostVO agent, StartupCommand cmd, boolean forRebalance) throws ConnectionException { if (!(cmd instanceof StartupRoutingCommand)) { return; } if (forRebalance) { s_logger.debug("Not processing listener " + this + " as connect happens on rebalance process"); return; } if (forRebalance) { s_logger.debug("Not processing listener " + this + " as connect happens on rebalance process"); return; } Long clusterId = agent.getClusterId(); long agentId = agent.getId(); if (agent.getHypervisorType() == HypervisorType.XenServer || agent.getHypervisorType() == HypervisorType.Xen){ // only fro Xen ClusterSyncCommand syncCmd = new ClusterSyncCommand(Integer.parseInt(Config.ClusterDeltaSyncInterval.getDefaultValue()), Integer.parseInt(Config.ClusterFullSyncSkipSteps.getDefaultValue()), clusterId); try { long seq_no = _agentMgr.send(agentId, new Commands(syncCmd), this); s_logger.debug("Cluster VM sync started with jobid " + seq_no); } catch (AgentUnavailableException e) { s_logger.fatal("The Cluster VM sync process failed for cluster id " + clusterId + " with ", e); } } else { // for others KVM and VMWare StartupRoutingCommand startup = (StartupRoutingCommand) cmd; Commands commands = fullHostSync(agentId, startup); if (commands.size() > 0) { s_logger.debug("Sending clean commands to the agent"); try { boolean error = false; Answer[] answers = _agentMgr.send(agentId, commands); for (Answer answer : answers) { if (!answer.getResult()) { s_logger.warn("Unable to stop a VM due to " + answer.getDetails()); error = true; } } if (error) { throw new ConnectionException(true, "Unable to stop VMs"); } } catch (final AgentUnavailableException e) { s_logger.warn("Agent is unavailable now", e); throw new ConnectionException(true, "Unable to sync", e); } catch (final OperationTimedoutException e) { s_logger.warn("Agent is unavailable now", e); throw new ConnectionException(true, "Unable to sync", e); } } } } protected class TransitionTask implements Runnable { @Override public void run() { GlobalLock lock = GlobalLock.getInternLock("TransitionChecking"); if (lock == null) { s_logger.debug("Couldn't get the global lock"); return; } if (!lock.lock(30)) { s_logger.debug("Couldn't lock the db"); return; } try { lock.addRef(); List<VMInstanceVO> instances = _vmDao.findVMInTransition(new Date(new Date().getTime() - (_operationTimeout * 1000)), State.Starting, State.Stopping); for (VMInstanceVO instance : instances) { State state = instance.getState(); if (state == State.Stopping) { _haMgr.scheduleStop(instance, instance.getHostId(), WorkType.CheckStop); } else if (state == State.Starting) { _haMgr.scheduleRestart(instance, true); } } } catch (Exception e) { s_logger.warn("Caught the following exception on transition checking", e); } finally { StackMaid.current().exitCleanup(); lock.unlock(); } } } protected class AgentVmInfo { public String name; public State state; public String hostUuid; public VMInstanceVO vm; public VirtualMachineGuru<VMInstanceVO> guru; @SuppressWarnings("unchecked") public AgentVmInfo(String name, VirtualMachineGuru<? extends VMInstanceVO> guru, VMInstanceVO vm, State state, String host) { this.name = name; this.state = state; this.vm = vm; this.guru = (VirtualMachineGuru<VMInstanceVO>) guru; this.hostUuid = host; } public AgentVmInfo(String name, VirtualMachineGuru<? extends VMInstanceVO> guru, VMInstanceVO vm, State state) { this(name, guru, vm, state, null); } public String getHostUuid() { return hostUuid; } } @Override public VMInstanceVO findById(long vmId) { return _vmDao.findById(vmId); } }
package com.cloud.vm; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.ejb.Local; import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.AgentManager.OnError; import com.cloud.agent.Listener; import com.cloud.agent.api.AgentControlAnswer; import com.cloud.agent.api.AgentControlCommand; import com.cloud.agent.api.Answer; import com.cloud.agent.api.CheckVirtualMachineAnswer; import com.cloud.agent.api.CheckVirtualMachineCommand; import com.cloud.agent.api.Command; import com.cloud.agent.api.MigrateAnswer; import com.cloud.agent.api.MigrateCommand; import com.cloud.agent.api.PingRoutingCommand; import com.cloud.agent.api.PrepareForMigrationAnswer; import com.cloud.agent.api.PrepareForMigrationCommand; import com.cloud.agent.api.RebootAnswer; import com.cloud.agent.api.RebootCommand; import com.cloud.agent.api.StartAnswer; import com.cloud.agent.api.StartCommand; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupRoutingCommand; import com.cloud.agent.api.StopAnswer; import com.cloud.agent.api.StopCommand; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.manager.Commands; import com.cloud.agent.manager.allocator.HostAllocator; import com.cloud.alert.AlertManager; import com.cloud.capacity.CapacityManager; import com.cloud.cluster.ClusterManager; import com.cloud.cluster.StackMaid; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ResourceCount.ResourceType; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.consoleproxy.ConsoleProxyManager; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenterVO; import com.cloud.dc.HostPodVO; import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.HostPodDao; import com.cloud.deploy.DataCenterDeployment; import com.cloud.deploy.DeployDestination; import com.cloud.deploy.DeploymentPlan; import com.cloud.deploy.DeploymentPlanner; import com.cloud.deploy.DeploymentPlanner.ExcludeList; import com.cloud.domain.dao.DomainDao; import com.cloud.event.dao.UsageEventDao; import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ConnectionException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InsufficientServerCapacityException; import com.cloud.exception.ManagementServerException; import com.cloud.exception.OperationTimedoutException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.exception.VirtualMachineMigrationException; import com.cloud.ha.HighAvailabilityManager; import com.cloud.ha.HighAvailabilityManager.WorkType; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.Status; import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.HypervisorGuru; import com.cloud.hypervisor.HypervisorGuruManager; import com.cloud.network.Network; import com.cloud.network.NetworkManager; import com.cloud.network.NetworkVO; import com.cloud.offering.ServiceOffering; import com.cloud.org.Cluster; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.StorageManager; import com.cloud.storage.StoragePoolVO; import com.cloud.storage.VMTemplateVO; import com.cloud.storage.Volume; import com.cloud.storage.Volume.Type; import com.cloud.storage.VolumeVO; import com.cloud.storage.dao.GuestOSCategoryDao; import com.cloud.storage.dao.GuestOSDao; import com.cloud.storage.dao.StoragePoolDao; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.User; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserDao; import com.cloud.uservm.UserVm; import com.cloud.utils.Journal; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.Ternary; import com.cloud.utils.component.Adapters; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Inject; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.ExecutionException; import com.cloud.utils.fsm.NoTransitionException; import com.cloud.utils.fsm.StateMachine2; import com.cloud.vm.ItWorkVO.Step; import com.cloud.vm.VirtualMachine.Event; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.dao.ConsoleProxyDao; import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.NicDao; import com.cloud.vm.dao.SecondaryStorageVmDao; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; @Local(value = VirtualMachineManager.class) public class VirtualMachineManagerImpl implements VirtualMachineManager, Listener { private static final Logger s_logger = Logger.getLogger(VirtualMachineManagerImpl.class); String _name; @Inject protected StorageManager _storageMgr; @Inject protected NetworkManager _networkMgr; @Inject protected AgentManager _agentMgr; @Inject protected VMInstanceDao _vmDao; @Inject protected ServiceOfferingDao _offeringDao; @Inject protected VMTemplateDao _templateDao; @Inject protected UserDao _userDao; @Inject protected AccountDao _accountDao; @Inject protected DomainDao _domainDao; @Inject protected ClusterManager _clusterMgr; @Inject protected ItWorkDao _workDao; @Inject protected UserVmDao _userVmDao; @Inject protected DomainRouterDao _routerDao; @Inject protected ConsoleProxyDao _consoleDao; @Inject protected SecondaryStorageVmDao _secondaryDao; @Inject protected UsageEventDao _usageEventDao; @Inject protected NicDao _nicsDao; @Inject protected AccountManager _accountMgr; @Inject protected HostDao _hostDao; @Inject protected AlertManager _alertMgr; @Inject protected GuestOSCategoryDao _guestOsCategoryDao; @Inject protected GuestOSDao _guestOsDao; @Inject protected VolumeDao _volsDao; @Inject protected ConsoleProxyManager _consoleProxyMgr; @Inject protected ConfigurationManager _configMgr; @Inject protected CapacityManager _capacityMgr; @Inject protected HighAvailabilityManager _haMgr; @Inject protected HostPodDao _podDao; @Inject protected DataCenterDao _dcDao; @Inject protected StoragePoolDao _storagePoolDao; @Inject protected HypervisorGuruManager _hvGuruMgr; @Inject(adapter = DeploymentPlanner.class) protected Adapters<DeploymentPlanner> _planners; @Inject(adapter = HostAllocator.class) protected Adapters<HostAllocator> _hostAllocators; Map<VirtualMachine.Type, VirtualMachineGuru<? extends VMInstanceVO>> _vmGurus = new HashMap<VirtualMachine.Type, VirtualMachineGuru<? extends VMInstanceVO>>(); protected StateMachine2<State, VirtualMachine.Event, VirtualMachine> _stateMachine; ScheduledExecutorService _executor = null; protected int _operationTimeout; protected int _retry; protected long _nodeId; protected long _cleanupWait; protected long _cleanupInterval; protected long _cancelWait; protected long _opWaitInterval; protected int _lockStateRetry; @Override public <T extends VMInstanceVO> void registerGuru(VirtualMachine.Type type, VirtualMachineGuru<T> guru) { synchronized (_vmGurus) { _vmGurus.put(type, guru); } } @Override @DB public <T extends VMInstanceVO> T allocate(T vm, VMTemplateVO template, ServiceOfferingVO serviceOffering, Pair<? extends DiskOfferingVO, Long> rootDiskOffering, List<Pair<DiskOfferingVO, Long>> dataDiskOfferings, List<Pair<NetworkVO, NicProfile>> networks, Map<VirtualMachineProfile.Param, Object> params, DeploymentPlan plan, HypervisorType hyperType, Account owner) throws InsufficientCapacityException { if (s_logger.isDebugEnabled()) { s_logger.debug("Allocating entries for VM: " + vm); } VirtualMachineProfileImpl<T> vmProfile = new VirtualMachineProfileImpl<T>(vm, template, serviceOffering, owner, params); vm.setDataCenterId(plan.getDataCenterId()); if (plan.getPodId() != null) { vm.setPodId(plan.getPodId()); } assert (plan.getClusterId() == null && plan.getPoolId() == null) : "We currently don't support cluster and pool preset yet"; @SuppressWarnings("unchecked") VirtualMachineGuru<T> guru = (VirtualMachineGuru<T>) _vmGurus.get(vm.getType()); Transaction txn = Transaction.currentTxn(); txn.start(); vm = guru.persist(vm); if (s_logger.isDebugEnabled()) { s_logger.debug("Allocating nics for " + vm); } try { _networkMgr.allocate(vmProfile, networks); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Concurrent operation while trying to allocate resources for the VM", e); } if (dataDiskOfferings == null) { dataDiskOfferings = new ArrayList<Pair<DiskOfferingVO, Long>>(0); } if (s_logger.isDebugEnabled()) { s_logger.debug("Allocaing disks for " + vm); } if (template.getFormat() == ImageFormat.ISO) { _storageMgr.allocateRawVolume(Type.ROOT, "ROOT-" + vm.getId(), rootDiskOffering.first(), rootDiskOffering.second(), vm, owner); } else if (template.getFormat() == ImageFormat.BAREMETAL) { // Do nothing } else { _storageMgr.allocateTemplatedVolume(Type.ROOT, "ROOT-" + vm.getId(), rootDiskOffering.first(), template, vm, owner); } for (Pair<DiskOfferingVO, Long> offering : dataDiskOfferings) { _storageMgr.allocateRawVolume(Type.DATADISK, "DATA-" + vm.getId(), offering.first(), offering.second(), vm, owner); } txn.commit(); if (s_logger.isDebugEnabled()) { s_logger.debug("Allocation completed for VM: " + vm); } return vm; } @Override public <T extends VMInstanceVO> T allocate(T vm, VMTemplateVO template, ServiceOfferingVO serviceOffering, Long rootSize, Pair<DiskOfferingVO, Long> dataDiskOffering, List<Pair<NetworkVO, NicProfile>> networks, DeploymentPlan plan, HypervisorType hyperType, Account owner) throws InsufficientCapacityException { List<Pair<DiskOfferingVO, Long>> diskOfferings = new ArrayList<Pair<DiskOfferingVO, Long>>(1); if (dataDiskOffering != null) { diskOfferings.add(dataDiskOffering); } return allocate(vm, template, serviceOffering, new Pair<DiskOfferingVO, Long>(serviceOffering, rootSize), diskOfferings, networks, null, plan, hyperType, owner); } @Override public <T extends VMInstanceVO> T allocate(T vm, VMTemplateVO template, ServiceOfferingVO serviceOffering, List<Pair<NetworkVO, NicProfile>> networks, DeploymentPlan plan, HypervisorType hyperType, Account owner) throws InsufficientCapacityException { return allocate(vm, template, serviceOffering, new Pair<DiskOfferingVO, Long>(serviceOffering, null), null, networks, null, plan, hyperType, owner); } @SuppressWarnings("unchecked") private <T extends VMInstanceVO> VirtualMachineGuru<T> getVmGuru(T vm) { return (VirtualMachineGuru<T>) _vmGurus.get(vm.getType()); } @SuppressWarnings("unchecked") private <T extends VMInstanceVO> VirtualMachineGuru<T> getBareMetalVmGuru(T vm) { return (VirtualMachineGuru<T>) _vmGurus.get(VirtualMachine.Type.UserBareMetal); } @Override public <T extends VMInstanceVO> boolean expunge(T vm, User caller, Account account) throws ResourceUnavailableException { try { if (advanceExpunge(vm, caller, account)) { // Mark vms as removed remove(vm, caller, account); return true; } else { s_logger.info("Did not expunge " + vm); return false; } } catch (OperationTimedoutException e) { throw new CloudRuntimeException("Operation timed out", e); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Concurrent operation ", e); } } @Override public <T extends VMInstanceVO> boolean advanceExpunge(T vm, User caller, Account account) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException { if (vm == null || vm.getRemoved() != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find vm or vm is destroyed: " + vm); } return true; } if (!this.advanceStop(vm, false, caller, account)) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to stop the VM so we can't expunge it."); } } try { if (!stateTransitTo(vm, VirtualMachine.Event.ExpungeOperation, vm.getHostId())) { s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm); return false; } } catch (NoTransitionException e) { s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm); return false; } if (s_logger.isDebugEnabled()) { s_logger.debug("Destroying vm " + vm); } VirtualMachineProfile<T> profile = new VirtualMachineProfileImpl<T>(vm); _networkMgr.cleanupNics(profile); // Clean up volumes based on the vm's instance id _storageMgr.cleanupVolumes(vm.getId()); VirtualMachineGuru<T> guru = getVmGuru(vm); guru.finalizeExpunge(vm); if (s_logger.isDebugEnabled()) { s_logger.debug("Expunged " + vm); } return true; } @Override public boolean start() { _executor.scheduleAtFixedRate(new CleanupTask(), _cleanupInterval, _cleanupInterval, TimeUnit.SECONDS); cancelWorkItems(_nodeId); return true; } @Override public boolean stop() { return true; } @Override public boolean configure(String name, Map<String, Object> xmlParams) throws ConfigurationException { _name = name; ComponentLocator locator = ComponentLocator.getCurrentLocator(); ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); Map<String, String> params = configDao.getConfiguration(xmlParams); _retry = NumbersUtil.parseInt(params.get(Config.StartRetry.key()), 10); ReservationContextImpl.setComponents(_userDao, _domainDao, _accountDao); VirtualMachineProfileImpl.setComponents(_offeringDao, _templateDao, _accountDao); _cancelWait = NumbersUtil.parseLong(params.get(Config.VmOpCancelInterval.key()), 3600); _cleanupWait = NumbersUtil.parseLong(params.get(Config.VmOpCleanupWait.key()), 3600); _cleanupInterval = NumbersUtil.parseLong(params.get(Config.VmOpCleanupInterval.key()), 86400) * 1000; _opWaitInterval = NumbersUtil.parseLong(params.get(Config.VmOpWaitInterval.key()), 120) * 1000; _lockStateRetry = NumbersUtil.parseInt(params.get(Config.VmOpLockStateRetry.key()), 5); _operationTimeout = NumbersUtil.parseInt(params.get(Config.Wait.key()), 1800) * 2; _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Vm-Operations-Cleanup")); _nodeId = _clusterMgr.getManagementNodeId(); _agentMgr.registerForHostEvents(this, true, true, true); return true; } @Override public String getName() { return _name; } protected VirtualMachineManagerImpl() { setStateMachine(); } @Override public <T extends VMInstanceVO> T start(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException, ResourceUnavailableException { return start(vm, params, caller, account, null); } @Override public <T extends VMInstanceVO> T start(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account, DeploymentPlan planToDeploy) throws InsufficientCapacityException, ResourceUnavailableException { try { return advanceStart(vm, params, caller, account, planToDeploy); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Unable to start a VM due to concurrent operation", e); } } protected boolean checkWorkItems(VMInstanceVO vm, State state) throws ConcurrentOperationException { while (true) { ItWorkVO vo = _workDao.findByOutstandingWork(vm.getId(), state); if (vo == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find work for VM: " + vm + " and state: " + state); } return true; } if (vo.getStep() == Step.Done) { if (s_logger.isDebugEnabled()) { s_logger.debug("Work for " + vm + " is " + vo.getStep()); } return true; } if (vo.getSecondsTaskIsInactive() > _cancelWait) { s_logger.warn("The task item for vm " + vm + " has been inactive for " + vo.getSecondsTaskIsInactive()); return false; } try { Thread.sleep(_opWaitInterval); } catch (InterruptedException e) { s_logger.info("Waiting for " + vm + " but is interrupted"); throw new ConcurrentOperationException("Waiting for " + vm + " but is interrupted"); } s_logger.debug("Waiting some more to make sure there's no activity on " + vm); } } @DB protected <T extends VMInstanceVO> Ternary<T, ReservationContext, ItWorkVO> changeToStartState(VirtualMachineGuru<T> vmGuru, T vm, User caller, Account account) throws ConcurrentOperationException { long vmId = vm.getId(); ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Starting, vm.getType(), vm.getId()); int retry = _lockStateRetry; while (retry Transaction txn = Transaction.currentTxn(); txn.start(); try { try { if (stateTransitTo(vm, Event.StartRequested, null, work.getId())) { Journal journal = new Journal.LogJournal("Creating " + vm, s_logger); work = _workDao.persist(work); ReservationContextImpl context = new ReservationContextImpl(work.getId(), journal, caller, account); if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully transitioned to start state for " + vm + " reservation id = " + work.getId()); } return new Ternary<T, ReservationContext, ItWorkVO>(vmGuru.findById(vmId), context, work); } } catch (NoTransitionException e) { throw new CloudRuntimeException(e.getMessage()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Determining why we're unable to update the state to Starting for " + vm); } VMInstanceVO instance = _vmDao.findById(vmId); if (instance == null) { throw new ConcurrentOperationException("Unable to acquire lock on " + vm); } State state = instance.getState(); if (state == State.Running) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM is already started: " + vm); } return null; } if (state.isTransitional()) { if (!checkWorkItems(vm, state)) { throw new ConcurrentOperationException("There are concurrent operations on the VM " + vm); } else { continue; } } if (state != State.Stopped) { s_logger.debug("VM " + vm + " is not in a state to be started: " + state); return null; } } finally { txn.commit(); } } throw new ConcurrentOperationException("Unable to change the state of " + vm); } @DB protected <T extends VMInstanceVO> boolean changeState(T vm, Event event, Long hostId, ItWorkVO work, Step step) throws NoTransitionException { Transaction txn = Transaction.currentTxn(); txn.start(); if (!stateTransitTo(vm, event, hostId)) { return false; } _workDao.updateStep(work, step); txn.commit(); return true; } @Override public <T extends VMInstanceVO> T advanceStart(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { return advanceStart(vm, params, caller, account, null); } @Override public <T extends VMInstanceVO> T advanceStart(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account, DeploymentPlan planToDeploy) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { long vmId = vm.getId(); VirtualMachineGuru<T> vmGuru; if (vm.getHypervisorType() == HypervisorType.BareMetal) { vmGuru = getBareMetalVmGuru(vm); } else { vmGuru = getVmGuru(vm); } vm = vmGuru.findById(vm.getId()); Ternary<T, ReservationContext, ItWorkVO> start = changeToStartState(vmGuru, vm, caller, account); if (start == null) { return vmGuru.findById(vmId); } vm = start.first(); ReservationContext ctx = start.second(); ItWorkVO work = start.third(); T startedVm = null; ServiceOfferingVO offering = _offeringDao.findById(vm.getServiceOfferingId()); VMTemplateVO template = _templateDao.findById(vm.getTemplateId()); DataCenterDeployment plan = new DataCenterDeployment(vm.getDataCenterIdToDeployIn(), vm.getPodIdToDeployIn(), null, null, null); if(planToDeploy != null){ if (s_logger.isDebugEnabled()) { s_logger.debug("advanceStart: DeploymentPlan is provided, using that plan to deploy"); } plan = (DataCenterDeployment)planToDeploy; } HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType()); boolean canRetry = true; try { Journal journal = start.second().getJournal(); ExcludeList avoids = new ExcludeList(); if (vm.getType().equals(VirtualMachine.Type.DomainRouter)) { List<DomainRouterVO> routers = _routerDao.findBy(vm.getAccountId(), vm.getDataCenterIdToDeployIn()); for (DomainRouterVO router : routers) { if (router.hostId != null) { avoids.addHost(router.hostId); s_logger.info("Router: try to avoid host " + router.hostId); } } } int retry = _retry; while (retry-- != 0) { // It's != so that it can match -1. // edit plan if this vm's ROOT volume is in READY state already // edit plan if this vm's ROOT volume is in READY state already List<VolumeVO> vols = _volsDao.findReadyRootVolumesByInstance(vm.getId()); for (VolumeVO vol : vols) { // make sure if the templateId is unchanged. If it is changed, let planner // reassign pool for the volume even if it ready. Long volTemplateId = vol.getTemplateId(); if (volTemplateId != null && volTemplateId.longValue() != template.getId()) { if (s_logger.isDebugEnabled()) { s_logger.debug(vol + " of " + vm + " is READY, but template ids don't match, let the planner reassign a new pool"); } continue; } StoragePoolVO pool = _storagePoolDao.findById(vol.getPoolId()); if (!pool.isInMaintenance()) { if (s_logger.isDebugEnabled()) { s_logger.debug("Root volume is ready, need to place VM in volume's cluster"); } long rootVolDcId = pool.getDataCenterId(); Long rootVolPodId = pool.getPodId(); Long rootVolClusterId = pool.getClusterId(); if(planToDeploy != null){ Long clusterIdSpecified = planToDeploy.getClusterId(); if(clusterIdSpecified != null && rootVolClusterId != null){ if(rootVolClusterId.longValue() != clusterIdSpecified.longValue()){ //cannot satisfy the plan passed in to the planner if (s_logger.isDebugEnabled()) { s_logger.debug("Cannot satisfy the deployment plan passed in since the ready Root volume is in different cluster. volume's cluster: "+rootVolClusterId + ", cluster specified: "+clusterIdSpecified); } throw new ResourceUnavailableException("Root volume is ready in different cluster, Deployment plan provided cannot be satisfied, unable to create a deployment for " + vm, Cluster.class, clusterIdSpecified); } } plan = new DataCenterDeployment(planToDeploy.getDataCenterId(), planToDeploy.getPodId(), planToDeploy.getClusterId(), planToDeploy.getHostId(), vol.getPoolId()); }else{ plan = new DataCenterDeployment(rootVolDcId, rootVolPodId, rootVolClusterId, null, vol.getPoolId()); if (s_logger.isDebugEnabled()) { s_logger.debug(vol + " is READY, changing deployment plan to use this pool's dcId: " + rootVolDcId + " , podId: " + rootVolPodId + " , and clusterId: " + rootVolClusterId); } } } } VirtualMachineProfileImpl<T> vmProfile = new VirtualMachineProfileImpl<T>(vm, template, offering, account, params); DeployDestination dest = null; for (DeploymentPlanner planner : _planners) { if (planner.canHandle(vmProfile, plan, avoids)) { dest = planner.plan(vmProfile, plan, avoids); } else { continue; } if (dest != null) { avoids.addHost(dest.getHost().getId()); journal.record("Deployment found ", vmProfile, dest); break; } } if (dest == null) { //see if we can allocate the router without limitation if (vm.getType().equals(VirtualMachine.Type.DomainRouter)) { avoids = new ExcludeList(); s_logger.info("Router: cancel avoids "); for (DeploymentPlanner planner : _planners) { if (planner.canHandle(vmProfile, plan, avoids)) { dest = planner.plan(vmProfile, plan, avoids); } else { continue; } if (dest != null) { avoids.addHost(dest.getHost().getId()); journal.record("Deployment found ", vmProfile, dest); break; } } } if (dest == null) { throw new InsufficientServerCapacityException("Unable to create a deployment for " + vmProfile + " due to lack of VLAN available.", DataCenter.class, plan.getDataCenterId()); } } long destHostId = dest.getHost().getId(); try { if (!changeState(vm, Event.OperationRetry, destHostId, work, Step.Prepare)) { throw new ConcurrentOperationException("Unable to update the state of the Virtual Machine"); } } catch (NoTransitionException e1) { throw new ConcurrentOperationException(e1.getMessage()); } try { _networkMgr.prepare(vmProfile, dest, ctx); if (vm.getHypervisorType() != HypervisorType.BareMetal) { _storageMgr.prepare(vmProfile, dest); } vmGuru.finalizeVirtualMachineProfile(vmProfile, dest, ctx); VirtualMachineTO vmTO = hvGuru.implement(vmProfile); Commands cmds = new Commands(OnError.Stop); cmds.addCommand(new StartCommand(vmTO)); vmGuru.finalizeDeployment(cmds, vmProfile, dest, ctx); vm.setPodId(dest.getPod().getId()); work = _workDao.findById(work.getId()); if (work == null || work.getStep() != Step.Prepare) { throw new ConcurrentOperationException("Work steps have been changed: " + work); } _workDao.updateStep(work, Step.Starting); _agentMgr.send(destHostId, cmds); _workDao.updateStep(work, Step.Started); Answer startAnswer = cmds.getAnswer(StartAnswer.class); if (startAnswer != null && startAnswer.getResult()) { if (vmGuru.finalizeStart(vmProfile, destHostId, cmds, ctx)) { if (!changeState(vm, Event.OperationSucceeded, destHostId, work, Step.Done)) { throw new ConcurrentOperationException("Unable to transition to a new state."); } startedVm = vm; if (s_logger.isDebugEnabled()) { s_logger.debug("Start completed for VM " + vm); } return startedVm; } else { if (s_logger.isDebugEnabled()) { s_logger.info("The guru did not like the answers so stopping " + vm); } StopCommand cmd = new StopCommand(vm.getInstanceName()); StopAnswer answer = (StopAnswer)_agentMgr.easySend(destHostId, cmd); if (answer == null || !answer.getResult()) { s_logger.warn("Unable to stop " + vm + " due to " + (answer != null ? answer.getDetails() : "no answers")); canRetry = false; _haMgr.scheduleStop(vm, destHostId, WorkType.ForceStop); throw new ExecutionException("Unable to stop " + vm + " so we are unable to retry the start operation"); } } } s_logger.info("Unable to start VM on " + dest.getHost() + " due to " + (startAnswer == null ? " no start answer" : startAnswer.getDetails())); } catch (OperationTimedoutException e) { s_logger.debug("Unable to send the start command to host " + dest.getHost()); if (e.isActive()) { _haMgr.scheduleStop(vm, destHostId, WorkType.CheckStop); } canRetry = false; throw new AgentUnavailableException("Unable to start " + vm.getHostName(), destHostId, e); } catch (ResourceUnavailableException e) { s_logger.info("Unable to contact resource.", e); if (!avoids.add(e)) { if (e.getScope() == Volume.class || e.getScope() == Nic.class) { throw e; } else { s_logger.warn("unexpected ResourceUnavailableException : " + e.getScope().getName(), e); throw e; } } } catch (InsufficientCapacityException e) { s_logger.info("Insufficient capacity ", e); if (!avoids.add(e)) { if (e.getScope() == Volume.class || e.getScope() == Nic.class) { throw e; } else { s_logger.warn("unexpected InsufficientCapacityException : " + e.getScope().getName(), e); } } } catch (Exception e) { s_logger.error("Failed to start instance " + vm, e); throw new AgentUnavailableException("Unable to start instance", destHostId, e); } finally { if (startedVm == null && canRetry) { _workDao.updateStep(work, Step.Release); cleanup(vmGuru, vmProfile, work, Event.OperationFailed, false, caller, account); } } } } finally { if (startedVm == null) { // decrement only for user VM's and newly created VM if (vm.getType().equals(VirtualMachine.Type.User) && (vm.getLastHostId() == null)) { _accountMgr.decrementResourceCount(vm.getAccountId(), ResourceType.user_vm); } if (canRetry) { try { changeState(vm, Event.OperationFailed, null, work, Step.Done); } catch (NoTransitionException e) { throw new ConcurrentOperationException(e.getMessage()); } } } } return startedVm; } @Override public <T extends VMInstanceVO> boolean stop(T vm, User user, Account account) throws ResourceUnavailableException { try { return advanceStop(vm, false, user, account); } catch (OperationTimedoutException e) { throw new AgentUnavailableException("Unable to stop vm because the operation to stop timed out", vm.getHostId(), e); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Unable to stop vm because of a concurrent operation", e); } } protected <T extends VMInstanceVO> boolean sendStop(VirtualMachineGuru<T> guru, VirtualMachineProfile<T> profile, boolean force) { VMInstanceVO vm = profile.getVirtualMachine(); StopCommand stop = new StopCommand(vm, vm.getInstanceName(), null); try { Answer answer = _agentMgr.send(vm.getHostId(), stop); if (!answer.getResult()) { s_logger.debug("Unable to stop VM due to " + answer.getDetails()); return false; } guru.finalizeStop(profile, (StopAnswer)answer); } catch (AgentUnavailableException e) { if (!force) { return false; } } catch (OperationTimedoutException e) { if (!force) { return false; } } return true; } protected <T extends VMInstanceVO> boolean cleanup(VirtualMachineGuru<T> guru, VirtualMachineProfile<T> profile, ItWorkVO work, Event event, boolean force, User user, Account account) { T vm = profile.getVirtualMachine(); State state = vm.getState(); s_logger.debug("Cleaning up resources for the vm " + vm + " in " + state + " state"); if (state == State.Starting) { Step step = work.getStep(); if (step == Step.Starting && !force) { s_logger.warn("Unable to cleanup vm " + vm + "; work state is incorrect: " + step); return false; } if (step == Step.Started || step == Step.Starting) { if (vm.getHostId() != null) { if (!sendStop(guru, profile, force)) { s_logger.warn("Failed to stop vm " + vm + " in " + State.Starting + " state as a part of cleanup process"); return false; } } } if (step != Step.Release && step != Step.Prepare && step != Step.Started && step != Step.Starting) { s_logger.debug("Cleanup is not needed for vm " + vm + "; work state is incorrect: " + step); return true; } } else if (state == State.Stopping) { if (vm.getHostId() != null) { if (!sendStop(guru, profile, force)) { s_logger.warn("Failed to stop vm " + vm + " in " + State.Stopping + " state as a part of cleanup process"); return false; } } } else if (state == State.Migrating) { if (vm.getHostId() != null) { if (!sendStop(guru, profile, force)) { s_logger.warn("Failed to stop vm " + vm + " in " + State.Migrating + " state as a part of cleanup process"); return false; } } if (vm.getLastHostId() != null) { if (!sendStop(guru, profile, force)) { s_logger.warn("Failed to stop vm " + vm + " in " + State.Migrating + " state as a part of cleanup process"); return false; } } } else if (state == State.Running) { if (!sendStop(guru, profile, force)) { s_logger.warn("Failed to stop vm " + vm + " in " + State.Running + " state as a part of cleanup process"); return false; } } _networkMgr.release(profile, force); _storageMgr.release(profile); s_logger.debug("Successfully cleanued up resources for the vm " + vm + " in " + state + " state"); return true; } @Override public <T extends VMInstanceVO> boolean advanceStop(T vm, boolean forced, User user, Account account) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { State state = vm.getState(); if (state == State.Stopped) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM is already stopped: " + vm); } return true; } if (state == State.Destroyed || state == State.Expunging || state == State.Error) { if (s_logger.isDebugEnabled()) { s_logger.debug("Stopped called on " + vm + " but the state is " + state); } return true; } Long hostId = vm.getHostId(); if (hostId == null) { try { stateTransitTo(vm, Event.AgentReportStopped, null, null); } catch (NoTransitionException e) { s_logger.warn(e.getMessage()); } return true; } VirtualMachineGuru<T> vmGuru = getVmGuru(vm); try { if (!stateTransitTo(vm, forced ? Event.AgentReportStopped : Event.StopRequested, vm.getHostId(), null)) { throw new ConcurrentOperationException("VM is being operated on."); } } catch (NoTransitionException e1) { throw new CloudRuntimeException("We cannot stop " + vm + " when it is in state " + vm.getState()); } VirtualMachineProfile<T> profile = new VirtualMachineProfileImpl<T>(vm); if ((vm.getState() == State.Starting || vm.getState() == State.Stopping || vm.getState() == State.Migrating) && forced) { ItWorkVO work = _workDao.findByOutstandingWork(vm.getId(), vm.getState()); if (work != null) { if (cleanup(vmGuru, new VirtualMachineProfileImpl<T>(vm), work, Event.StopRequested, forced, user, account)) { try { return stateTransitTo(vm, Event.AgentReportStopped, null); } catch (NoTransitionException e) { s_logger.warn("Unable to cleanup " + vm); return false; } } } } if (vm.getHostId() != null) { String routerPrivateIp = null; if (vm.getType() == VirtualMachine.Type.DomainRouter) { routerPrivateIp = vm.getPrivateIpAddress(); } StopCommand stop = new StopCommand(vm, vm.getInstanceName(), null, routerPrivateIp); boolean stopped = false; StopAnswer answer = null; try { answer = (StopAnswer) _agentMgr.send(vm.getHostId(), stop); stopped = answer.getResult(); if (!stopped) { throw new CloudRuntimeException("Unable to stop the virtual machine due to " + answer.getDetails()); } vmGuru.finalizeStop(profile, answer); } catch (AgentUnavailableException e) { } catch (OperationTimedoutException e) { } finally { if (!stopped) { if (!forced) { s_logger.warn("Unable to stop vm " + vm); try { stateTransitTo(vm, Event.OperationFailed, vm.getHostId()); } catch (NoTransitionException e) { s_logger.warn("Unable to transition the state " + vm); } return false; } else { s_logger.warn("Unable to actually stop " + vm + " but continue with release because it's a force stop"); vmGuru.finalizeStop(profile, answer); } } } } if (s_logger.isDebugEnabled()) { s_logger.debug(vm + " is stopped on the host. Proceeding to release resource held."); } try { _networkMgr.release(profile, forced); s_logger.debug("Successfully released network resources for the vm " + vm); } catch (Exception e) { s_logger.warn("Unable to release some network resources.", e); } try { if (vm.getHypervisorType() != HypervisorType.BareMetal) { _storageMgr.release(profile); s_logger.debug("Successfully released storage resources for the vm " + vm); } } catch (Exception e) { s_logger.warn("Unable to release storage resources.", e); } vm.setReservationId(null); try { return stateTransitTo(vm, Event.OperationSucceeded, null); } catch (NoTransitionException e) { s_logger.warn(e.getMessage()); return false; } } private void setStateMachine() { _stateMachine = VirtualMachine.State.getStateMachine(); } protected boolean stateTransitTo(VMInstanceVO vm, VirtualMachine.Event e, Long hostId, String reservationId) throws NoTransitionException { vm.setReservationId(reservationId); return _stateMachine.transitTo(vm, e, hostId, _vmDao); } @Override public boolean stateTransitTo(VMInstanceVO vm, VirtualMachine.Event e, Long hostId) throws NoTransitionException { State oldState = vm.getState(); if (oldState == State.Starting) { if (e == Event.OperationSucceeded) { vm.setLastHostId(hostId); } } else if (oldState == State.Stopping) { if (e == Event.OperationSucceeded) { vm.setLastHostId(vm.getHostId()); } } return _stateMachine.transitTo(vm, e, hostId, _vmDao); } @Override public <T extends VMInstanceVO> boolean remove(T vm, User user, Account caller) { // expunge the corresponding nics VirtualMachineProfile<T> profile = new VirtualMachineProfileImpl<T>(vm); _networkMgr.expungeNics(profile); s_logger.trace("Nics of the vm " + vm + " are expunged successfully"); return _vmDao.remove(vm.getId()); } @Override public <T extends VMInstanceVO> boolean destroy(T vm, User user, Account caller) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { if (s_logger.isDebugEnabled()) { s_logger.debug("Destroying vm " + vm); } if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging || vm.getRemoved() != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find vm or vm is destroyed: " + vm); } return true; } if (!advanceStop(vm, false, user, caller)) { s_logger.debug("Unable to stop " + vm); return false; } try { if (!stateTransitTo(vm, VirtualMachine.Event.DestroyRequested, vm.getHostId())) { s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm); return false; } } catch (NoTransitionException e) { s_logger.debug(e.getMessage()); return false; } return true; } protected boolean checkVmOnHost(VirtualMachine vm, long hostId) throws AgentUnavailableException, OperationTimedoutException { CheckVirtualMachineAnswer answer = (CheckVirtualMachineAnswer) _agentMgr.send(hostId, new CheckVirtualMachineCommand(vm.getInstanceName())); if (!answer.getResult() || answer.getState() == State.Stopped) { return false; } return true; } @Override public <T extends VMInstanceVO> T migrate(T vm, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException { s_logger.info("Migrating " + vm + " to " + dest); long dstHostId = dest.getHost().getId(); Host fromHost = _hostDao.findById(srcHostId); if (fromHost == null) { s_logger.info("Unable to find the host to migrate from: " + srcHostId); throw new CloudRuntimeException("Unable to find the host to migrate from: " + srcHostId); } if (fromHost.getClusterId().longValue() != dest.getCluster().getId()) { s_logger.info("Source and destination host are not in same cluster, unable to migrate to host: " + dest.getHost().getId()); throw new CloudRuntimeException("Source and destination host are not in same cluster, unable to migrate to host: " + dest.getHost().getId()); } VirtualMachineGuru<T> vmGuru = getVmGuru(vm); long vmId = vm.getId(); vm = vmGuru.findById(vmId); if (vm == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find the vm " + vm); } throw new ManagementServerException("Unable to find a virtual machine with id " + vmId); } if (vm.getState() != State.Running) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM is not Running, unable to migrate the vm " + vm); } throw new VirtualMachineMigrationException("VM is not Running, unable to migrate the vm currently " + vm); } short alertType = AlertManager.ALERT_TYPE_USERVM_MIGRATE; if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) { alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE; } else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) { alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY_MIGRATE; } VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm); _networkMgr.prepareNicForMigration(profile, dest); _storageMgr.prepareForMigration(profile, dest); HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType()); VirtualMachineTO to = hvGuru.implement(profile); PrepareForMigrationCommand pfmc = new PrepareForMigrationCommand(to); ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Migrating, vm.getType(), vm.getId()); work.setStep(Step.Prepare); work.setResourceType(ItWorkVO.ResourceType.Host); work.setResourceId(dstHostId); work = _workDao.persist(work); PrepareForMigrationAnswer pfma = null; try { pfma = (PrepareForMigrationAnswer) _agentMgr.send(dstHostId, pfmc); if (!pfma.getResult()) { String msg = "Unable to prepare for migration due to " + pfma.getDetails(); pfma = null; throw new AgentUnavailableException(msg, dstHostId); } } catch (OperationTimedoutException e1) { throw new AgentUnavailableException("Operation timed out", dstHostId); } finally { if (pfma == null) { work.setStep(Step.Done); _workDao.update(work.getId(), work); } } vm.setLastHostId(srcHostId); try { if (vm == null || vm.getHostId() == null || vm.getHostId() != srcHostId || !changeState(vm, Event.MigrationRequested, dstHostId, work, Step.Migrating)) { s_logger.info("Migration cancelled because state has changed: " + vm); throw new ConcurrentOperationException("Migration cancelled because state has changed: " + vm); } } catch (NoTransitionException e1) { s_logger.info("Migration cancelled because " + e1.getMessage()); throw new ConcurrentOperationException("Migration cancelled because " + e1.getMessage()); } boolean migrated = false; try { boolean isWindows = _guestOsCategoryDao.findById(_guestOsDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows"); MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows); try { MigrateAnswer ma = (MigrateAnswer) _agentMgr.send(vm.getLastHostId(), mc); if (!ma.getResult()) { s_logger.error("Unable to migrate due to " + ma.getDetails()); return null; } } catch (OperationTimedoutException e) { if (e.isActive()) { s_logger.warn("Active migration command so scheduling a restart for " + vm); _haMgr.scheduleRestart(vm, true); } throw new AgentUnavailableException("Operation timed out on migrating " + vm, dstHostId); } try { if (!changeState(vm, VirtualMachine.Event.OperationSucceeded, dstHostId, work, Step.Started)) { throw new ConcurrentOperationException("Unable to change the state for " + vm); } } catch (NoTransitionException e1) { throw new ConcurrentOperationException("Unable to change state due to " + e1.getMessage()); } try { if (!checkVmOnHost(vm, dstHostId)) { s_logger.error("Unable to complete migration for " + vm); try { _agentMgr.send(srcHostId, new Commands(cleanup(vm.getInstanceName())), null); } catch (AgentUnavailableException e) { s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId); } cleanup(vmGuru, new VirtualMachineProfileImpl<T>(vm), work, Event.AgentReportStopped, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount()); return null; } } catch (OperationTimedoutException e) { } migrated = true; return vm; } finally { if (!migrated) { s_logger.info("Migration was unsuccessful. Cleaning up: " + vm); _alertMgr.sendAlert(alertType, fromHost.getDataCenterId(), fromHost.getPodId(), "Unable to migrate vm " + vm.getInstanceName() + " from host " + fromHost.getName() + " in zone " + dest.getDataCenter().getName() + " and pod " + dest.getPod().getName(), "Migrate Command failed. Please check logs."); try { _agentMgr.send(dstHostId, new Commands(cleanup(vm.getInstanceName())), null); } catch (AgentUnavailableException ae) { s_logger.info("Looks like the destination Host is unavailable for cleanup"); } try { stateTransitTo(vm, Event.OperationFailed, srcHostId); } catch (NoTransitionException e) { s_logger.warn(e.getMessage()); } } work.setStep(Step.Done); _workDao.update(work.getId(), work); } } protected void cancelWorkItems(long nodeId) { GlobalLock scanLock = GlobalLock.getInternLock("vmmgr.cancel.workitem"); try { if (scanLock.lock(3)) { try { List<ItWorkVO> works = _workDao.listWorkInProgressFor(nodeId); for (ItWorkVO work : works) { s_logger.info("Handling unfinished work item: " + work); try { VMInstanceVO vm = _vmDao.findById(work.getInstanceId()); if (vm != null) { if (work.getType() == State.Starting) { _haMgr.scheduleRestart(vm, true); } else if (work.getType() == State.Stopping) { _haMgr.scheduleStop(vm, vm.getHostId(), WorkType.CheckStop); } else if (work.getType() == State.Migrating) { _haMgr.scheduleMigration(vm); } } work.setStep(Step.Done); _workDao.update(work.getId(), work); } catch (Exception e) { s_logger.error("Error while handling " + work, e); } } } finally { scanLock.unlock(); } } } finally { scanLock.releaseRef(); } } @Override public boolean migrateAway(VirtualMachine.Type vmType, long vmId, long srcHostId) throws InsufficientServerCapacityException, VirtualMachineMigrationException { VirtualMachineGuru<? extends VMInstanceVO> vmGuru = _vmGurus.get(vmType); VMInstanceVO vm = vmGuru.findById(vmId); if (vm == null) { s_logger.debug("Unable to find a VM for " + vmId); return true; } VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm); Long hostId = vm.getHostId(); if (hostId == null) { s_logger.debug("Unable to migrate because the VM doesn't have a host id: " + vm); return true; } Host host = _hostDao.findById(hostId); DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), null, null); ExcludeList excludes = new ExcludeList(); excludes.addHost(hostId); DeployDestination dest = null; while (true) { for (DeploymentPlanner planner : _planners) { dest = planner.plan(profile, plan, excludes); if (dest != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Planner " + planner + " found " + dest + " for migrating to."); } break; } if (s_logger.isDebugEnabled()) { s_logger.debug("Planner " + planner + " was unable to find anything."); } } if (dest == null) { throw new InsufficientServerCapacityException("Unable to find a server to migrate to.", host.getClusterId()); } excludes.addHost(dest.getHost().getId()); VMInstanceVO vmInstance = null; try { vmInstance = migrate(vm, srcHostId, dest); } catch (ResourceUnavailableException e) { s_logger.debug("Unable to migrate to unavailable " + dest); } catch (ConcurrentOperationException e) { s_logger.debug("Unable to migrate VM due to: " + e.getMessage()); } catch (ManagementServerException e) { s_logger.debug("Unable to migrate VM: " + e.getMessage()); } catch (VirtualMachineMigrationException e) { s_logger.debug("Got VirtualMachineMigrationException, Unable to migrate: " + e.getMessage()); if (vm.getState() == State.Starting) { s_logger.debug("VM seems to be still Starting, we should retry migration later"); throw e; } else { s_logger.debug("Unable to migrate VM, VM is not in Running or even Starting state, current state: " + vm.getState().toString()); } } if (vmInstance != null) { return true; } try { boolean result = advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount()); return result; } catch (ResourceUnavailableException e) { s_logger.debug("Unable to stop VM due to " + e.getMessage()); } catch (ConcurrentOperationException e) { s_logger.debug("Unable to stop VM due to " + e.getMessage()); } catch (OperationTimedoutException e) { s_logger.debug("Unable to stop VM due to " + e.getMessage()); } return false; } } protected class CleanupTask implements Runnable { @Override public void run() { s_logger.trace("VM Operation Thread Running"); try { _workDao.cleanup(_cleanupWait); } catch (Exception e) { s_logger.error("VM Operations failed due to ", e); } } } @Override public boolean isVirtualMachineUpgradable(UserVm vm, ServiceOffering offering) { Enumeration<HostAllocator> en = _hostAllocators.enumeration(); boolean isMachineUpgradable = true; while (isMachineUpgradable && en.hasMoreElements()) { final HostAllocator allocator = en.nextElement(); isMachineUpgradable = allocator.isVirtualMachineUpgradable(vm, offering); } return isMachineUpgradable; } @Override public <T extends VMInstanceVO> T reboot(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException, ResourceUnavailableException { try { return advanceReboot(vm, params, caller, account); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Unable to reboot a VM due to concurrent operation", e); } } @Override public <T extends VMInstanceVO> T advanceReboot(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { T rebootedVm = null; DataCenter dc = _configMgr.getZone(vm.getDataCenterIdToDeployIn()); Host host = _hostDao.findById(vm.getHostId()); Cluster cluster = null; if (host != null) { cluster = _configMgr.getCluster(host.getClusterId()); } HostPodVO pod = _configMgr.getPod(host.getPodId()); DeployDestination dest = new DeployDestination(dc, pod, cluster, host); try { Commands cmds = new Commands(OnError.Stop); cmds.addCommand(new RebootCommand(vm.getInstanceName())); _agentMgr.send(host.getId(), cmds); Answer rebootAnswer = cmds.getAnswer(RebootAnswer.class); if (rebootAnswer != null && rebootAnswer.getResult()) { rebootedVm = vm; return rebootedVm; } s_logger.info("Unable to reboot VM " + vm + " on " + dest.getHost() + " due to " + (rebootAnswer == null ? " no reboot answer" : rebootAnswer.getDetails())); } catch (OperationTimedoutException e) { s_logger.warn("Unable to send the reboot command to host " + dest.getHost() + " for the vm " + vm + " due to operation timeout", e); throw new CloudRuntimeException("Failed to reboot the vm on host " + dest.getHost()); } return rebootedVm; } @Override public VMInstanceVO findById(VirtualMachine.Type type, long vmId) { VirtualMachineGuru<? extends VMInstanceVO> guru = _vmGurus.get(type); return guru.findById(vmId); } public Command cleanup(String vmName) { return new StopCommand(vmName); } public Commands deltaSync(long hostId, Map<String, State> newStates) { Map<Long, AgentVmInfo> states = convertToInfos(newStates); Commands commands = new Commands(OnError.Continue); boolean nativeHA = _agentMgr.isHostNativeHAEnabled(hostId); for (Map.Entry<Long, AgentVmInfo> entry : states.entrySet()) { AgentVmInfo info = entry.getValue(); VMInstanceVO vm = info.vm; Command command = null; if (vm != null) { command = compareState(vm, info, false, nativeHA); } else { if (s_logger.isDebugEnabled()) { s_logger.debug("Cleaning up a VM that is no longer found: " + info.name); } command = cleanup(info.name); } if (command != null) { commands.addCommand(command); } } return commands; } protected Map<Long, AgentVmInfo> convertToInfos(final Map<String, State> states) { final HashMap<Long, AgentVmInfo> map = new HashMap<Long, AgentVmInfo>(); if (states == null) { return map; } Collection<VirtualMachineGuru<? extends VMInstanceVO>> vmGurus = _vmGurus.values(); for (Map.Entry<String, State> entry : states.entrySet()) { for (VirtualMachineGuru<? extends VMInstanceVO> vmGuru : vmGurus) { String name = entry.getKey(); VMInstanceVO vm = vmGuru.findByName(name); if (vm != null) { map.put(vm.getId(), new AgentVmInfo(entry.getKey(), vmGuru, vm, entry.getValue())); break; } Long id = vmGuru.convertToId(name); if (id != null) { map.put(id, new AgentVmInfo(entry.getKey(), vmGuru, null, entry.getValue())); break; } } } return map; } /** * compareState does as its name suggests and compares the states between management server and agent. It returns whether * something should be cleaned up * */ protected Command compareState(VMInstanceVO vm, final AgentVmInfo info, final boolean fullSync, boolean nativeHA) { State agentState = info.state; final String agentName = info.name; final State serverState = vm.getState(); final String serverName = vm.getInstanceName(); VirtualMachineGuru<VMInstanceVO> vmGuru = getVmGuru(vm); Command command = null; if (s_logger.isDebugEnabled()) { s_logger.debug("VM " + serverName + ": server state = " + serverState + " and agent state = " + agentState); } if (agentState == State.Error) { agentState = State.Stopped; short alertType = AlertManager.ALERT_TYPE_USERVM; if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) { alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER; } else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) { alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY; } HostPodVO podVO = _podDao.findById(vm.getPodIdToDeployIn()); DataCenterVO dcVO = _dcDao.findById(vm.getDataCenterIdToDeployIn()); HostVO hostVO = _hostDao.findById(vm.getHostId()); String hostDesc = "name: " + hostVO.getName() + " (id:" + hostVO.getId() + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName(); _alertMgr.sendAlert(alertType, vm.getDataCenterIdToDeployIn(), vm.getPodIdToDeployIn(), "VM (name: " + vm.getInstanceName() + ", id: " + vm.getId() + ") stopped on host " + hostDesc + " due to storage failure", "Virtual Machine " + vm.getInstanceName() + " (id: " + vm.getId() + ") running on host [" + vm.getHostId() + "] stopped due to storage failure."); } // if (serverState == State.Migrating) { // s_logger.debug("Skipping vm in migrating state: " + vm); // return null; if (agentState == serverState) { if (s_logger.isDebugEnabled()) { s_logger.debug("Both states are " + agentState + " for " + vm); } assert (agentState == State.Stopped || agentState == State.Running) : "If the states we send up is changed, this must be changed."; if (agentState == State.Running) { try { stateTransitTo(vm, VirtualMachine.Event.AgentReportRunning, vm.getHostId()); } catch (NoTransitionException e) { s_logger.warn(e.getMessage()); } // FIXME: What if someone comes in and sets it to stopping? Then what? return null; } s_logger.debug("State matches but the agent said stopped so let's send a cleanup command anyways."); return cleanup(agentName); } if (agentState == State.Shutdowned) { if (serverState == State.Running || serverState == State.Starting || serverState == State.Stopping) { try { advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount()); } catch (AgentUnavailableException e) { assert (false) : "How do we hit this with forced on?"; return null; } catch (OperationTimedoutException e) { assert (false) : "How do we hit this with forced on?"; return null; } catch (ConcurrentOperationException e) { assert (false) : "How do we hit this with forced on?"; return null; } } else { s_logger.debug("Sending cleanup to a shutdowned vm: " + agentName); command = cleanup(agentName); } } else if (agentState == State.Stopped) { // This state means the VM on the agent was detected previously // and now is gone. This is slightly different than if the VM // was never completed but we still send down a Stop Command // to ensure there's cleanup. if (serverState == State.Running) { // Our records showed that it should be running so let's restart it. _haMgr.scheduleRestart(vm, false); } else if (serverState == State.Stopping) { _haMgr.scheduleStop(vm, vm.getHostId(), WorkType.ForceStop); s_logger.debug("Scheduling a check stop for VM in stopping mode: " + vm); } else if (serverState == State.Starting) { s_logger.debug("Ignoring VM in starting mode: " + vm.getInstanceName()); _haMgr.scheduleRestart(vm, false); } command = cleanup(agentName); } else if (agentState == State.Running) { if (serverState == State.Starting) { if (fullSync) { s_logger.debug("VM state is starting on full sync so updating it to running"); vm = findById(vm.getType(), vm.getId()); try { stateTransitTo(vm, Event.AgentReportRunning, vm.getHostId()); } catch (NoTransitionException e1) { s_logger.warn(e1.getMessage()); } s_logger.debug("VM's " + vm + " state is starting on full sync so updating it to Running"); vm = vmGuru.findById(vm.getId()); VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm); List<NicVO> nics = _nicsDao.listByVmId(profile.getId()); for (NicVO nic : nics) { Network network = _networkMgr.getNetwork(nic.getNetworkId()); NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null); profile.addNic(nicProfile); } Commands cmds = new Commands(OnError.Stop); s_logger.debug("Finalizing commands that need to be send to complete Start process for the vm " + vm); if (vmGuru.finalizeCommandsOnStart(cmds, profile)) { if (cmds.size() != 0) { try { _agentMgr.send(vm.getHostId(), cmds); } catch (OperationTimedoutException e) { s_logger.error("Exception during update for running vm: " + vm, e); return null; } catch (ResourceUnavailableException e) { s_logger.error("Exception during update for running vm: " + vm, e); return null; } } if (vmGuru.finalizeStart(profile, vm.getHostId(), cmds, null)) { try { stateTransitTo(vm, Event.AgentReportRunning, vm.getHostId()); } catch (NoTransitionException e) { s_logger.warn(e.getMessage()); } } else { s_logger.error("Exception during update for running vm: " + vm); return null; } } else { s_logger.error("Unable to finalize commands on start for vm: " + vm); return null; } } } else if (serverState == State.Stopping) { s_logger.debug("Scheduling a stop command for " + vm); _haMgr.scheduleStop(vm, vm.getHostId(), WorkType.Stop); } else { s_logger.debug("VM state is in stopped so stopping it on the agent"); command = cleanup(agentName); } } return command; } public Commands fullSync(final long hostId, final Map<String, State> newStates) { Commands commands = new Commands(OnError.Continue); final List<? extends VMInstanceVO> vms = _vmDao.listByHostId(hostId); s_logger.debug("Found " + vms.size() + " VMs for host " + hostId); Map<Long, AgentVmInfo> infos = convertToInfos(newStates); boolean nativeHA = _agentMgr.isHostNativeHAEnabled(hostId); for (VMInstanceVO vm : vms) { AgentVmInfo info = infos.remove(vm.getId()); VMInstanceVO castedVm = null; if (info == null) { info = new AgentVmInfo(vm.getInstanceName(), getVmGuru(vm), vm, State.Stopped); castedVm = info.guru.findById(vm.getId()); } else { castedVm = info.vm; } Command command = compareState(castedVm, info, true, nativeHA); if (command != null) { commands.addCommand(command); } } for (final AgentVmInfo left : infos.values()) { if (nativeHA) { for (VirtualMachineGuru<? extends VMInstanceVO> vmGuru : _vmGurus.values()) { VMInstanceVO vm = vmGuru.findByName(left.name); if (vm == null) { s_logger.warn("Stopping a VM that we have no record of: " + left.name); commands.addCommand(cleanup(left.name)); } else { Command command = compareState(vm, left, true, nativeHA); if (command != null) { commands.addCommand(command); } } } } else { s_logger.warn("Stopping a VM that we have no record of: " + left.name); commands.addCommand(cleanup(left.name)); } } return commands; } @Override public boolean isRecurring() { return false; } @Override public boolean processAnswers(long agentId, long seq, Answer[] answers) { for (final Answer answer : answers) { if (!answer.getResult()) { s_logger.warn("Cleanup failed due to " + answer.getDetails()); } else { if (s_logger.isDebugEnabled()) { s_logger.debug("Cleanup succeeded. Details " + answer.getDetails()); } } } return true; } @Override public boolean processTimeout(long agentId, long seq) { return true; } @Override public int getTimeout() { return -1; } @Override public boolean processCommands(long agentId, long seq, Command[] cmds) { boolean processed = false; for (Command cmd : cmds) { if (cmd instanceof PingRoutingCommand) { PingRoutingCommand ping = (PingRoutingCommand) cmd; if (ping.getNewStates().size() > 0) { Commands commands = deltaSync(agentId, ping.getNewStates()); if (commands.size() > 0) { try { _agentMgr.send(agentId, commands, this); } catch (final AgentUnavailableException e) { s_logger.warn("Agent is now unavailable", e); } } } processed = true; } } return processed; } @Override public AgentControlAnswer processControlCommand(long agentId, AgentControlCommand cmd) { return null; } @Override public boolean processDisconnect(long agentId, Status state) { return true; } @Override public void processConnect(HostVO agent, StartupCommand cmd) throws ConnectionException { if (!(cmd instanceof StartupRoutingCommand)) { return; } long agentId = agent.getId(); StartupRoutingCommand startup = (StartupRoutingCommand) cmd; Commands commands = fullSync(agentId, startup.getVmStates()); if (commands.size() > 0) { s_logger.debug("Sending clean commands to the agent"); try { boolean error = false; Answer[] answers = _agentMgr.send(agentId, commands); for (Answer answer : answers) { if (!answer.getResult()) { s_logger.warn("Unable to stop a VM due to " + answer.getDetails()); error = true; } } if (error) { throw new ConnectionException(true, "Unable to stop VMs"); } } catch (final AgentUnavailableException e) { s_logger.warn("Agent is unavailable now", e); throw new ConnectionException(true, "Unable to sync", e); } catch (final OperationTimedoutException e) { s_logger.warn("Agent is unavailable now", e); throw new ConnectionException(true, "Unable to sync", e); } } } protected class TransitionTask implements Runnable { @Override public void run() { GlobalLock lock = GlobalLock.getInternLock("TransitionChecking"); if (lock == null) { s_logger.debug("Couldn't get the global lock"); return; } if (!lock.lock(30)) { s_logger.debug("Couldn't lock the db"); return; } try { lock.addRef(); List<VMInstanceVO> instances = _vmDao.findVMInTransition(new Date(new Date().getTime() - (_operationTimeout * 1000)), State.Starting, State.Stopping); for (VMInstanceVO instance : instances) { State state = instance.getState(); if (state == State.Stopping) { _haMgr.scheduleStop(instance, instance.getHostId(), WorkType.CheckStop); } else if (state == State.Starting) { _haMgr.scheduleRestart(instance, true); } } } catch (Exception e) { s_logger.warn("Caught the following exception on transition checking", e); } finally { StackMaid.current().exitCleanup(); lock.unlock(); } } } protected class AgentVmInfo { public String name; public State state; public VMInstanceVO vm; public VirtualMachineGuru<VMInstanceVO> guru; @SuppressWarnings("unchecked") public AgentVmInfo(String name, VirtualMachineGuru<? extends VMInstanceVO> guru, VMInstanceVO vm, State state) { this.name = name; this.state = state; this.vm = vm; this.guru = (VirtualMachineGuru<VMInstanceVO>) guru; } } }
package mondrian.test; import mondrian.olap.Cube; import mondrian.olap.Result; import mondrian.olap.Cell; import mondrian.rolap.RolapCube; import mondrian.rolap.RolapStar; import mondrian.rolap.sql.SqlQuery; /** * Test generation of SQL to access the fact table data underlying an MDX * result set. * * @author jhyde * @since May 10, 2006 * @version $Id$ */ public class DrillThroughTest extends FoodMartTestCase { public DrillThroughTest() { super(); } public DrillThroughTest(String name) { super(name); } public void testDrillThrough() throws Exception { Result result = executeQuery( "WITH MEMBER [Measures].[Price] AS '[Measures].[Store Sales] / [Measures].[Unit Sales]'" + nl + "SELECT {[Measures].[Unit Sales], [Measures].[Price]} on columns," + nl + " {[Product].Children} on rows" + nl + "from Sales"); final Cell cell = result.getCell(new int[]{0, 0}); assertTrue(cell.canDrillThrough()); String sql = cell.getDrillThroughSQL(false); String expectedSql = "select `time_by_day`.`the_year` as `Year`," + " `product_class`.`product_family` as `Product Family`," + " `sales_fact_1997`.`unit_sales` as `Unit Sales` " + "from `time_by_day` =as= `time_by_day`," + " `sales_fact_1997` =as= `sales_fact_1997`," + " `product_class` =as= `product_class`," + " `product` =as= `product` " + "where `sales_fact_1997`.`time_id` = `time_by_day`.`time_id`" + " and `time_by_day`.`the_year` = 1997" + " and `sales_fact_1997`.`product_id` = `product`.`product_id`" + " and `product`.`product_class_id` = `product_class`.`product_class_id`" + " and `product_class`.`product_family` = 'Drink' " + "order by `time_by_day`.`the_year` ASC," + " `product_class`.`product_family` ASC"; getTestContext().assertSqlEquals(expectedSql, sql, 7978); // Cannot drill through a calc member. final Cell calcCell = result.getCell(new int[]{1, 1}); assertFalse(calcCell.canDrillThrough()); sql = calcCell.getDrillThroughSQL(false); assertNull(sql); } private String getNameExp(Result result, String hierName, String levelName) { final Cube cube = result.getQuery().getCube(); RolapStar star = ((RolapCube) cube).getStar(); String nameExpStr = null; mondrian.olap.Hierarchy h = cube.lookupHierarchy("Customers", false); if (h != null) { mondrian.rolap.RolapLevel rl = null; mondrian.olap.Level[] levels = h.getLevels(); for (mondrian.olap.Level l : levels) { if (l.getName().equals("Name")) { rl = (mondrian.rolap.RolapLevel) l; break; } } if (rl != null) { mondrian.olap.MondrianDef.Expression exp = rl.getNameExp(); nameExpStr = exp.getExpression(star.getSqlQuery()); nameExpStr = nameExpStr.replace('"', '`') ; } } return nameExpStr; } public void testDrillThrough2() throws Exception { Result result = executeQuery( "WITH MEMBER [Measures].[Price] AS '[Measures].[Store Sales] / [Measures].[Unit Sales]'" + nl + "SELECT {[Measures].[Unit Sales], [Measures].[Price]} on columns," + nl + " {[Product].Children} on rows" + nl + "from Sales"); String sql = result.getCell(new int[] {0, 0}).getDrillThroughSQL(true); String nameExpStr = getNameExp(result, "Customers", "Name"); String expectedSql = "select `store`.`store_country` as `Store Country`," + " `store`.`store_state` as `Store State`," + " `store`.`store_city` as `Store City`," + " `store`.`store_name` as `Store Name`," + " `store`.`store_sqft` as `Store Sqft`," + " `store`.`store_type` as `Store Type`," + " `time_by_day`.`the_year` as `Year`," + " `time_by_day`.`quarter` as `Quarter`," + " `time_by_day`.`month_of_year` as `Month`," + " `product_class`.`product_family` as `Product Family`," + " `product_class`.`product_department` as `Product Department`," + " `product_class`.`product_category` as `Product Category`," + " `product_class`.`product_subcategory` as `Product Subcategory`," + " `product`.`brand_name` as `Brand Name`," + " `product`.`product_name` as `Product Name`," + " `promotion`.`media_type` as `Media Type`," + " `promotion`.`promotion_name` as `Promotion Name`," + " `customer`.`country` as `Country`," + " `customer`.`state_province` as `State Province`," + " `customer`.`city` as `City`, " + nameExpStr + " as `Name`," + " `customer`.`customer_id` as `Name (Key)`," + " `customer`.`education` as `Education Level`," + " `customer`.`gender` as `Gender`," + " `customer`.`marital_status` as `Marital Status`," + " `customer`.`yearly_income` as `Yearly Income`," + " `sales_fact_1997`.`unit_sales` as `Unit Sales` " + "from `store` =as= `store`," + " `sales_fact_1997` =as= `sales_fact_1997`," + " `time_by_day` =as= `time_by_day`," + " `product_class` =as= `product_class`," + " `product` =as= `product`," + " `promotion` =as= `promotion`," + " `customer` =as= `customer` " + "where `sales_fact_1997`.`store_id` = `store`.`store_id`" + " and `sales_fact_1997`.`time_id` = `time_by_day`.`time_id`" + " and `time_by_day`.`the_year` = 1997" + " and `sales_fact_1997`.`product_id` = `product`.`product_id`" + " and `product`.`product_class_id` = `product_class`.`product_class_id`" + " and `product_class`.`product_family` = 'Drink'" + " and `sales_fact_1997`.`promotion_id` = `promotion`.`promotion_id`" + " and `sales_fact_1997`.`customer_id` = `customer`.`customer_id` " + "order by `store`.`store_country` ASC," + " `store`.`store_state` ASC," + " `store`.`store_city` ASC," + " `store`.`store_name` ASC," + " `store`.`store_sqft` ASC," + " `store`.`store_type` ASC," + " `time_by_day`.`the_year` ASC," + " `time_by_day`.`quarter` ASC," + " `time_by_day`.`month_of_year` ASC," + " `product_class`.`product_family` ASC," + " `product_class`.`product_department` ASC," + " `product_class`.`product_category` ASC," + " `product_class`.`product_subcategory` ASC," + " `product`.`brand_name` ASC," + " `product`.`product_name` ASC," + " `promotion`.`media_type` ASC," + " `promotion`.`promotion_name` ASC," + " `customer`.`country` ASC," + " `customer`.`state_province` ASC," + " `customer`.`city` ASC, " + nameExpStr + " ASC," + " `customer`.`customer_id` ASC," + " `customer`.`education` ASC," + " `customer`.`gender` ASC," + " `customer`.`marital_status` ASC," + " `customer`.`yearly_income` ASC"; getTestContext().assertSqlEquals(expectedSql, sql, 7978); // Drillthrough SQL is null for cell based on calc member sql = result.getCell(new int[] {1, 1}).getDrillThroughSQL(true); assertNull(sql); } public void testDrillThrough3() throws Exception { Result result = executeQuery( "select {[Measures].[Unit Sales], [Measures].[Store Cost], [Measures].[Store Sales]} ON COLUMNS, " + nl + "Hierarchize(Union(Union(Crossjoin({[Promotion Media].[All Media]}, {[Product].[All Products]}), " + nl + "Crossjoin({[Promotion Media].[All Media]}, [Product].[All Products].Children)), Crossjoin({[Promotion Media].[All Media]}, [Product].[All Products].[Drink].Children))) ON ROWS " + nl + "from [Sales] where [Time].[1997].[Q4].[12]"); // [Promotion Media].[All Media], [Product].[All Products].[Drink].[Dairy], [Measures].[Store Cost] Cell cell = result.getCell(new int[] {0, 4}); String sql = cell.getDrillThroughSQL(true); String nameExpStr = getNameExp(result, "Customers", "Name"); String expectedSql = "select " + "`store`.`store_country` as `Store Country`, `store`.`store_state` as `Store State`, `store`.`store_city` as `Store City`, `store`.`store_name` as `Store Name`, " + "`store`.`store_sqft` as `Store Sqft`, `store`.`store_type` as `Store Type`, " + "`time_by_day`.`the_year` as `Year`, `time_by_day`.`quarter` as `Quarter`, `time_by_day`.`month_of_year` as `Month`, " + "`product_class`.`product_family` as `Product Family`, `product_class`.`product_department` as `Product Department`, " + "`product_class`.`product_category` as `Product Category`, `product_class`.`product_subcategory` as `Product Subcategory`, " + "`product`.`brand_name` as `Brand Name`, `product`.`product_name` as `Product Name`, " + "`promotion`.`media_type` as `Media Type`, `promotion`.`promotion_name` as `Promotion Name`, " + "`customer`.`country` as `Country`, `customer`.`state_province` as `State Province`, `customer`.`city` as `City`, " + "fname + ' ' + lname as `Name`, `customer`.`customer_id` as `Name (Key)`, " + "`customer`.`education` as `Education Level`, `customer`.`gender` as `Gender`, `customer`.`marital_status` as `Marital Status`, " + "`customer`.`yearly_income` as `Yearly Income`, " + "`sales_fact_1997`.`unit_sales` as `Unit Sales` " + "from `store =as= `store`, " + "`sales_fact_1997` =as= `sales_fact_1997`, " + "`time_by_day` =as= `time_by_day`, " + "`product_class` =as= `product_class`, " + "`product` =as= `product`, " + "`promotion` =as= `promotion`, " + "`customer` =as= `customer` " + "where `sales_fact_1997`.`store_id` = `store`.`store_id` and " + "`sales_fact_1997`.`time_id` = `time_by_day`.`time_id` and " + "`time_by_day`.`the_year` = 1997 and " + "`time_by_day`.`quarter` = 'Q4' and " + "`time_by_day`.`month_of_year` = 12 and " + "`sales_fact_1997`.`product_id` = `product`.`product_id` and " + "`product`.`product_class_id` = `product_class`.`product_class_id` and " + "`product_class`.`product_family` = 'Drink' and " + "`product_class`.`product_department` = 'Dairy' and " + "`sales_fact_1997`.`promotion_id` = `promotion`.`promotion_id` and " + "`sales_fact_1997`.`customer_id` = `customer`.`customer_id` " + "order by `store`.`store_country` ASC, `store`.`store_state` ASC, `store`.`store_city` ASC, `store`.`store_name` ASC, `store`.`store_sqft` ASC, " + "`store`.`store_type` ASC, `time_by_day`.`the_year` ASC, `time_by_day`.`quarter` ASC, `time_by_day`.`month_of_year` ASC, " + "`product_class`.`product_family` ASC, `product_class`.`product_department` ASC, `product_class`.`product_category` ASC, " + "`product_class`.`product_subcategory` ASC, `product`.`brand_name` ASC, `product`.`product_name` ASC, " + "`promotion.media_type` ASC, `promotion`.`promotion_name` ASC, " + "`customer`.`country` ASC, `customer`.`state_province` ASC, `customer`.`city` ASC, " + nameExpStr + " ASC, " + "`customer`.`customer_id` ASC, `customer`.`education` ASC, `customer`.gender` ASC, `customer`.`marital_status` ASC, `customer`.`yearly_income` ASC"; getTestContext().assertSqlEquals(expectedSql, sql, 141); } /** * Testcase for bug 1472311, "Drillthrough fails, if Aggregate in * MDX-query". The problem actually occurs with any calculated member, * not just Aggregate. The bug was causing a syntactically invalid * constraint to be added to the WHERE clause; after the fix, we do * not constrain on the member at all. */ public void testDrillThroughBug1472311() throws Exception { /* * "with set [Date Range] as" + nl + "'{[Time].[1997].[Q1],[Time].[1997].[Q2]}'" + nl + "member [Time].[Date Range] as 'Aggregate([Date Range])'" + nl + "select {[Store]} on rows," + nl + "{[Measures].[Unit Sales]} on columns" + nl + "from [Sales]" + nl + "where [Time].[Date Range]"); */ Result result = executeQuery( "with set [Date Range] as '{[Time].[1997].[Q1], [Time].[1997].[Q2]}'" + nl + "member [Time].[Date Range] as 'Aggregate([Date Range])'" + nl + "select {[Measures].[Unit Sales]} ON COLUMNS," + nl + "Hierarchize(Union(Union(Union({[Store].[All Stores]}, [Store].[All Stores].Children), [Store].[All Stores].[USA].Children), [Store].[All Stores].[USA].[CA].Children)) ON ROWS" + nl + "from [Sales]" + nl + "where [Time].[Date Range]" ); //String sql = result.getCell(new int[] {0, 0}).getDrillThroughSQL(true); String sql = result.getCell(new int[] {0, 6}).getDrillThroughSQL(true); String nameExpStr = getNameExp(result, "Customers", "Name"); final String expectedSql = "select" + //`store`.`store_country` as `Store Country`," + " `store`.`store_state` as `Store State`," + " `store`.`store_city` as `Store City`," + " `store`.`store_name` as `Store Name`," + " `store`.`store_sqft` as `Store Sqft`," + " `store`.`store_type` as `Store Type`," + " `time_by_day`.`the_year` as `Year`," + " `time_by_day`.`quarter` as `Quarter`," + " `time_by_day`.`month_of_year` as `Month`," + " `product_class`.`product_family` as `Product Family`," + " `product_class`.`product_department` as `Product Department`," + " `product_class`.`product_category` as `Product Category`," + " `product_class`.`product_subcategory` as `Product Subcategory`," + " `product`.`brand_name` as `Brand Name`," + " `product`.`product_name` as `Product Name`," + " `promotion`.`media_type` as `Media Type`," + " `promotion`.`promotion_name` as `Promotion Name`," + " `customer`.`country` as `Country`," + " `customer`.`state_province` as `State Province`," + " `customer`.`city` as `City`, " + nameExpStr + " as `Name`," + " `customer`.`customer_id` as `Name (Key)`," + " `customer`.`education` as `Education Level`," + " `customer`.`gender` as `Gender`," + " `customer`.`marital_status` as `Marital Status`," + " `customer`.`yearly_income` as `Yearly Income`," + " `sales_fact_1997`.`unit_sales` as `Unit Sales` " + "from `store` =as= `store`," + " `sales_fact_1997` =as= `sales_fact_1997`," + " `time_by_day` =as= `time_by_day`," + " `product_class` =as= `product_class`," + " `product` =as= `product`," + " `promotion` =as= `promotion`," + " `customer` =as= `customer` " + "where `sales_fact_1997`.`store_id` = `store`.`store_id` and" + " `store`.`store_state` = 'CA' and" + " `store`.`store_city` = 'Beverly Hills' and" + " `sales_fact_1997`.time_id` = `time_by_day`.`time_id` and" + " `sales_fact_1997`.`product_id` = `product`.`product_id` and" + " `product`.`product_class_id` = `product_class`.`product_class_id` and" + " `sales_fact_1997`.`promotion_id` = `promotion`.`promotion_id` and" + " `sales_fact_1997`.`customer_id` = `customer`.`customer_id`" + " order by" + // `store`.`store_country` ASC," + " `store`.`store_state` ASC," + " `store`.`store_city` ASC," + " `store`.`store_name` ASC," + " `store`.`store_sqft` ASC," + " `store`.`store_type` ASC," + " `time_by_day`.`the_year` ASC," + " `time_by_day`.`quarter` ASC," + " `time_by_day`.`month_of_year` ASC," + " `product_class`.`product_family` ASC," + " `product_class`.`product_department` ASC," + " `product_class`.`product_category` ASC," + " `product_class`.`product_subcategory` ASC," + " `product`.`brand_name` ASC," + " `product`.`product_name` ASC," + " `promotion`.`media_type` ASC," + " `promotion`.`promotion_name` ASC," + " `customer`.`country` ASC," + " `customer`.`state_province` ASC," + " `customer`.`city` ASC, " + nameExpStr + " ASC," + " `customer`.`customer_id` ASC," + " `customer`.`education` ASC," + " `customer`.`gender` ASC," + " `customer`.`marital_status` ASC," + " `customer`.`yearly_income` ASC"; //getTestContext().assertSqlEquals(expectedSql, sql, 86837); getTestContext().assertSqlEquals(expectedSql, sql, 6815); } // Test that proper SQL is being generated for a Measure specified // as an expression public void testDrillThroughMeasureExp() throws Exception { Result result = executeQuery( "SELECT {[Measures].[Promotion Sales]} on columns," + nl + " {[Product].Children} on rows" + nl + "from Sales"); String sql = result.getCell(new int[] {0, 0}).getDrillThroughSQL(false); String expectedSql = "select `time_by_day`.`the_year` as `Year`," + " `product_class`.`product_family` as `Product Family`," + " (case when `sales_fact_1997`.`promotion_id` = 0 then 0" + " else `sales_fact_1997`.`store_sales` end)" + " as `Promotion Sales` " + "from `time_by_day` =as= `time_by_day`," + " `sales_fact_1997` =as= `sales_fact_1997`," + " `product_class` =as= `product_class`," + " `product` =as= `product` " + "where `sales_fact_1997`.`time_id` = `time_by_day`.`time_id`" + " and `time_by_day`.`the_year` = 1997" + " and `sales_fact_1997`.`product_id` = `product`.`product_id`" + " and `product`.`product_class_id` = `product_class`.`product_class_id`" + " and `product_class`.`product_family` = 'Drink' " + "order by `time_by_day`.`the_year` ASC, `product_class`.`product_family` ASC"; final Cube cube = result.getQuery().getCube(); RolapStar star = ((RolapCube) cube).getStar(); SqlQuery.Dialect dialect = star.getSqlQueryDialect(); if (dialect.isAccess()) { String caseStmt = " \\(case when `sales_fact_1997`.`promotion_id` = 0 then 0" + " else `sales_fact_1997`.`store_sales` end\\)"; expectedSql = expectedSql.replaceAll( caseStmt, " Iif(`sales_fact_1997`.`promotion_id` = 0, 0," + " `sales_fact_1997`.`store_sales`)"); } getTestContext().assertSqlEquals(expectedSql, sql, 7978); } /** * Tests that drill-through works if two dimension tables have primary key * columns with the same name. Related to bug 1592556, "XMLA Drill through * bug". */ public void testDrillThroughDupKeys() throws Exception { /* * Note here that the type on the Store Id level is Integer or Numeric. The default, of course, would be String. * * For DB2 and Derby, we need the Integer type, otherwise the generated SQL will be something like: * * `store_ragged`.`store_id` = '19' * * and DB2 and Derby don't like converting from CHAR to INTEGER */ final TestContext testContext = TestContext.createSubstitutingCube( "Sales", " <Dimension name=\"Store2\" foreignKey=\"store_id\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"store_id\">\n" + " <Table name=\"store_ragged\"/>\n" + " <Level name=\"Store Country\" column=\"store_country\" uniqueMembers=\"true\"/>\n" + " <Level name=\"Store Id\" column=\"store_id\" captionColumn=\"store_name\" uniqueMembers=\"true\" type=\"Integer\"/>\n" + " </Hierarchy>\n" + " </Dimension>\n" + " <Dimension name=\"Store3\" foreignKey=\"store_id\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"store_id\">\n" + " <Table name=\"store\"/>\n" + " <Level name=\"Store Country\" column=\"store_country\" uniqueMembers=\"true\"/>\n" + " <Level name=\"Store Id\" column=\"store_id\" captionColumn=\"store_name\" uniqueMembers=\"true\" type=\"Numeric\"/>\n" + " </Hierarchy>\n" + " </Dimension>\n"); Result result = testContext.executeQuery( "SELECT {[Store2].[Store Id].Members} on columns," + nl + " NON EMPTY([Store3].[Store Id].Members) on rows" + nl + "from Sales"); String sql = result.getCell(new int[] {0, 0}).getDrillThroughSQL(false); String expectedSql = "select `time_by_day`.`the_year` as `Year`," + " `store_ragged`.`store_id` as `Store Id`," + " `store`.`store_id` as `Store Id_0`," + " `sales_fact_1997`.`unit_sales` as" + " `Unit Sales` " + "from `time_by_day` =as= `time_by_day`," + " `sales_fact_1997` =as= `sales_fact_1997`," + " `store_ragged` =as= `store_ragged`," + " `store` =as= `store` " + "where `sales_fact_1997`.`time_id` = `time_by_day`.`time_id`" + " and `time_by_day`.`the_year` = 1997" + " and `sales_fact_1997`.`store_id` = `store_ragged`.`store_id`" + " and `store_ragged`.`store_id` = 19" + " and `sales_fact_1997`.`store_id` = `store`.`store_id`" + " and `store`.`store_id` = 2 " + "order by `time_by_day`.`the_year` ASC, `store_ragged`.`store_id` ASC, `store`.`store_id` ASC"; getTestContext().assertSqlEquals(expectedSql, sql, 0); } /** * Tests that cells in a virtual cube say they can be drilled through. */ public void testDrillThroughVirtualCube() throws Exception { Result result = executeQuery( "select Crossjoin([Customers].[All Customers].[USA].[OR].Children, {[Measures].[Unit Sales]}) ON COLUMNS, " + " [Gender].[All Gender].Children ON ROWS" + " from [Warehouse and Sales]" + " where [Time].[1997].[Q4].[12]"); String sql = result.getCell(new int[] {0, 0}).getDrillThroughSQL(false); String expectedSql = "select `time_by_day`.`the_year` as `Year`," + " `time_by_day`.`quarter` as `Quarter`," + " `time_by_day`.month_of_year` as `Month`," + " `customer`.`state_province` as `State Province`," + " `customer`.`city` as `City`," + " `customer`.`gender` as `Gender`," + " `sales_fact_1997`.`unit_sales` as `Unit Sales`" + " from `time_by_day` =as= `time_by_day`," + " `sales_fact_1997` =as= `sales_fact_1997`," + " `customer` =as= `customer`" + " where `sales_fact_1997`.`time_id` = `time_by_day`.`time_id` and" + " `time_by_day`.`the_year` = 1997 and" + " `time_by_day`.`quarter` = 'Q4' and" + " `time_by_day`.`month_of_year` = 12 and" + " `sales_fact_1997`.`customer_id` = `customer`.customer_id` and" + " `customer`.`state_province` = 'OR' and" + " `customer`.`city` = 'Albany' and" + " `customer`.`gender` = 'F'" + " order by `time_by_day`.`the_year` ASC," + " `time_by_day`.`quarter` ASC," + " `time_by_day`.`month_of_year` ASC," + " `customer`.`state_province` ASC," + " `customer`.`city` ASC," + " `customer`.`gender` ASC"; getTestContext().assertSqlEquals(expectedSql, sql, 73); } } // End DrillThroughTest.java
package io.luna.game.model; import io.luna.game.model.mobile.Player; public final class EntityConstants { /** * The default starting {@link Position} of all {@link Entity}s. */ public static final Position DEFAULT_POSITION = new Position(3222, 3222); /** * The maximum distance that a {@link Player} can view. */ public static final int VIEWING_DISTANCE = 15; /** * A private constructor to discourage external instantiation. */ private EntityConstants() {} }
package VASSAL.tools.swing; import java.awt.Toolkit; import java.awt.dnd.DragGestureEvent; import java.awt.event.InputEvent; import java.awt.event.MouseEvent; import java.awt.geom.AffineTransform; import java.util.Map; import javax.swing.SwingUtilities; import org.apache.commons.lang3.SystemUtils; public class SwingUtils { public static AffineTransform descaleTransform(AffineTransform t) { return new AffineTransform( 1.0, 0.0, 0.0, 1.0, t.getTranslateX(), t.getTranslateY() ); } public static final Map<?,?> FONT_HINTS = (Map<?,?>) Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints"); private interface InputClassifier { /* * @return whether the event is effectively for the left button */ boolean isLeftMouseButton(MouseEvent e); /* * @return whether the event is effectively for the right button */ boolean isRightMouseButton(MouseEvent e); } private static class DefaultInputClassifier implements InputClassifier { public boolean isLeftMouseButton(MouseEvent e) { return SwingUtilities.isLeftMouseButton(e); } public boolean isRightMouseButton(MouseEvent e) { return SwingUtilities.isRightMouseButton(e); } } private static class MacInputClassifier implements InputClassifier { private static final int B1_MASK = MouseEvent.BUTTON1_DOWN_MASK | MouseEvent.CTRL_DOWN_MASK; public boolean isLeftMouseButton(MouseEvent e) { // The left button on a Mac is the left button, except when it's the // right button because Ctrl is depressed. switch (e.getID()) { case MouseEvent.MOUSE_PRESSED: case MouseEvent.MOUSE_RELEASED: case MouseEvent.MOUSE_CLICKED: return e.getButton() == MouseEvent.BUTTON1 && (e.getModifiersEx() & MouseEvent.CTRL_DOWN_MASK) == 0; case MouseEvent.MOUSE_ENTERED: case MouseEvent.MOUSE_EXITED: case MouseEvent.MOUSE_DRAGGED: return (e.getModifiersEx() & B1_MASK) == MouseEvent.BUTTON1_DOWN_MASK; default: return (e.getModifiersEx() & B1_MASK) == MouseEvent.BUTTON1_DOWN_MASK || (e.getButton() == MouseEvent.BUTTON1 && (e.getModifiersEx() & MouseEvent.CTRL_DOWN_MASK) == 0); } } public boolean isRightMouseButton(MouseEvent e) { // The right button on a Mac can be either a real right button, or // Ctrl + the left button. switch (e.getID()) { case MouseEvent.MOUSE_PRESSED: case MouseEvent.MOUSE_RELEASED: case MouseEvent.MOUSE_CLICKED: return e.getButton() == MouseEvent.BUTTON3 || (e.getButton() == MouseEvent.BUTTON1 && (e.getModifiersEx() & MouseEvent.CTRL_DOWN_MASK) != 0); case MouseEvent.MOUSE_ENTERED: case MouseEvent.MOUSE_EXITED: case MouseEvent.MOUSE_DRAGGED: return (e.getModifiersEx() & MouseEvent.BUTTON3_DOWN_MASK) != 0 || (e.getModifiersEx() & B1_MASK) == B1_MASK; default: return (e.getModifiersEx() & MouseEvent.BUTTON3_DOWN_MASK) != 0 || (e.getModifiersEx() & B1_MASK) == B1_MASK || e.getButton() == MouseEvent.BUTTON3 || (e.getButton() == MouseEvent.BUTTON1 && (e.getModifiersEx() & MouseEvent.CTRL_DOWN_MASK) != 0); } } } private static final InputClassifier inputClassifier = SystemUtils.IS_OS_MAC_OSX ? new MacInputClassifier() : new DefaultInputClassifier(); /* * @return whether the event is effectively for the left button */ public static boolean isLeftMouseButton(MouseEvent e) { return inputClassifier.isLeftMouseButton(e); } /* * @return whether the event is effectively for the right button */ public static boolean isRightMouseButton(MouseEvent e) { return inputClassifier.isRightMouseButton(e); } /* * @return whether the drag is non-mouse or effectively from the left button */ public static boolean isDragTrigger(DragGestureEvent e) { final InputEvent te = e.getTriggerEvent(); return !(te instanceof MouseEvent) || isLeftMouseButton((MouseEvent) te); } }
package abra.cadabra; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import abra.CompareToReference2; import abra.Feature; import abra.Logger; import abra.SAMRecordUtils; import htsjdk.samtools.Cigar; import htsjdk.samtools.CigarElement; import htsjdk.samtools.CigarOperator; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.TextCigarCodec; public class CadabraProcessor { private static final int MIN_SUPPORTING_READS = 2; private Cadabra cadabra; private String normalBam; private String tumorBam; private ReadLocusReader normal; private ReadLocusReader tumor; private CompareToReference2 c2r; private Feature region; private int lastPos = 0; CadabraOptions options; List<SampleCall> sampleRecords = new ArrayList<SampleCall>(); List<SomaticCall> somaticCalls = new ArrayList<SomaticCall>(); CadabraProcessor(Cadabra cadabra, CadabraOptions options, CompareToReference2 c2r) { this.cadabra = cadabra; this.options = options; this.c2r = c2r; this.tumorBam = options.getTumor(); this.normalBam = options.getNormal(); } void process(Feature region) { this.region = region; this.tumor = new ReadLocusReader(tumorBam, region); if (normalBam != null) { this.normal = new ReadLocusReader(normalBam, region); processSomatic(); } else { processSimple(); } } private void processSimple() { Iterator<ReadsAtLocus> sampleIter = tumor.iterator(); ReadsAtLocus sampleReads = null; while (sampleIter.hasNext()) { sampleReads = sampleIter.next(); SampleCall call = processLocus(sampleReads, false); if (call != null && sampleCallExceedsThresholds(call)) { sampleRecords.add(call); } } this.cadabra.addCalls(region.getSeqname(), sampleRecords); } private boolean sampleCallExceedsThresholds(SampleCall call) { return call.alt != null && call.alt != Allele.UNK && call.alleleCounts.get(call.alt).getCount() >= MIN_SUPPORTING_READS && call.getVaf() >= options.getMinVaf() && call.qual >= options.getMinQual(); } private void processSomatic() { Iterator<ReadsAtLocus> normalIter = normal.iterator(); Iterator<ReadsAtLocus> tumorIter = tumor.iterator(); ReadsAtLocus normalReads = null; ReadsAtLocus tumorReads = null; int count = 0; while (normalIter.hasNext() && tumorIter.hasNext()) { if (normalReads != null && tumorReads != null) { int compare = normalReads.compareLoci(tumorReads, normal.getSamHeader().getSequenceDictionary()); if (compare < 0) { normalReads = normalIter.next(); } else if (compare > 0) { tumorReads = tumorIter.next(); } else { SampleCall normalCall = processLocus(normalReads, true); SampleCall tumorCall = processLocus(tumorReads, true); if (tumorCall.alt != null && tumorCall.alt != Allele.UNK && tumorCall.alleleCounts.get(tumorCall.alt).getCount() >= MIN_SUPPORTING_READS) { if (normalCall.getVaf()/tumorCall.getVaf() < .2) { int chromosomeLength = c2r.getChromosomeLength(tumorCall.chromosome); String refSeq = "N"; if (tumorCall.position > 10 && tumorCall.position < chromosomeLength-10) { refSeq = c2r.getSequence(tumorCall.chromosome, tumorCall.position-9, 20); } SomaticCall somaticCall = new SomaticCall(normalCall, tumorCall, refSeq, options); if (somaticCall.qual >= options.getMinQual() && somaticCall.tumor.getVaf() >= options.getMinVaf()) { somaticCalls.add(somaticCall); } } } normalReads = normalIter.next(); tumorReads = tumorIter.next(); } if ((count % 1000000) == 0) { System.err.println("Position: " + normalReads.getChromosome() + ":" + normalReads.getPosition()); } count += 1; } else { normalReads = normalIter.next(); tumorReads = tumorIter.next(); } } this.cadabra.addSomaticCalls(region.getSeqname(), somaticCalls); } private Character getBaseAtPosition(SAMRecord read, int refPos) { int readPos = 0; int refPosInRead = read.getAlignmentStart(); int cigarElementIdx = 0; while (refPosInRead <= refPos && cigarElementIdx < read.getCigar().numCigarElements() && readPos < read.getReadLength()) { CigarElement elem = read.getCigar().getCigarElement(cigarElementIdx++); switch(elem.getOperator()) { case H: //NOOP break; case S: case I: readPos += elem.getLength(); break; case D: case N: refPosInRead += elem.getLength(); break; case M: if (refPos < (refPosInRead + elem.getLength())) { readPos += refPos - refPosInRead; if (readPos < read.getReadLength()) { // Found the base. Return it return read.getReadString().charAt(readPos); } } else { readPos += elem.getLength(); refPosInRead += elem.getLength(); } break; default: throw new IllegalArgumentException("Invalid Cigar Operator: " + elem.getOperator() + " for read: " + read.getSAMString()); } } return null; } private char getRefBase(String chr, int pos) { return c2r.getSequence(chr, pos, 1).charAt(0); } private Allele getAltIndelAllele(Allele ref, Map<Allele, AlleleCounts> alleleCounts) { int maxAlt = 0; Allele alt = null; for (Allele allele : alleleCounts.keySet()) { if (allele != ref) { AlleleCounts ac = alleleCounts.get(allele); if (ac.getCount() > maxAlt && (allele.getType() == Allele.Type.DEL || allele.getType() == Allele.Type.INS)) { maxAlt = ac.getCount(); alt = allele; } } } return alt; } private SampleCall processLocus(ReadsAtLocus reads, boolean isSomatic) { SampleCall call = null; String chromosome = reads.getChromosome(); int position = reads.getPosition(); if (position > lastPos + 5000000) { Logger.info("Processing: %s:%d", chromosome, position); lastPos = position; } int tumorMapq0 = 0; int mismatchExceededReads = 0; int totalDepth = 0; Map<Allele, AlleleCounts> alleleCounts = new HashMap<Allele, AlleleCounts>(); // Always include ref allele char refBase = getRefBase(chromosome, position); Allele refAllele = Allele.getAllele(refBase); alleleCounts.put(refAllele, new AlleleCounts()); for (SAMRecord read : reads.getReads()) { if (!read.getDuplicateReadFlag() && !read.getReadUnmappedFlag() && (read.getFlags() & 0x900) == 0) { totalDepth += 1; if (read.getMappingQuality() < options.getMinMapq()) { tumorMapq0 += 1; continue; } if (read.getStringAttribute("YA") == null) { // Cap # mismatches in read that can be counted as reference // This is done because realigner caps # of mismatches for remapped indel reads. // This is needed to remove ref bias int editDist = SAMRecordUtils.getEditDistance(read, null); int indelBases = SAMRecordUtils.getNumIndelBases(read); int numMismatches = editDist - indelBases; float mismatchRate = (float) .05; if (numMismatches > SAMRecordUtils.getMappedLength(read) * mismatchRate) { // Skip this read mismatchExceededReads += 1; continue; } } IndelInfo readElement = checkForIndelAtLocus(read, position); Allele allele = Allele.UNK; if (readElement != null) { if (readElement.getCigarElement().getOperator() == CigarOperator.D) { allele = new Allele(Allele.Type.DEL, readElement.getCigarElement().getLength()); } else if (readElement.getCigarElement().getOperator() == CigarOperator.I) { allele = new Allele(Allele.Type.INS, readElement.getCigarElement().getLength()); } } else { Character base = getBaseAtPosition(read, position); Character nextBase = getBaseAtPosition(read, position+1); IndelInfo readIndel = checkForIndelAtLocus(read.getAlignmentStart(), read.getCigar(), position); if (readIndel == null && base != null && nextBase != null) { allele = Allele.getAllele(base); } } if (allele != Allele.UNK) { if (!alleleCounts.containsKey(allele)) { alleleCounts.put(allele, new AlleleCounts()); } AlleleCounts ac = alleleCounts.get(allele); ac.incrementCount(read); if (readElement != null) { ac.updateReadIdx(readElement.getReadIndex()); } if (allele.getType() == Allele.Type.INS) { ac.updateInsertBases(readElement.getInsertBases()); } } } } // Allow readId sets to be garbage collected. for (AlleleCounts counts : alleleCounts.values()) { counts.clearReadIds(); } Allele alt = getAltIndelAllele(Allele.getAllele(refBase), alleleCounts); int usableDepth = AlleleCounts.sum(alleleCounts.values()); String refSeq = null; if (!isSomatic) { int chromosomeLength = c2r.getChromosomeLength(chromosome); refSeq = "N"; if (position > 10 && position < chromosomeLength-10) { refSeq = c2r.getSequence(chromosome, position-9, 20); } } if (alt != null && (alt.getType() == Allele.Type.DEL || alt.getType() == Allele.Type.INS) && refAllele != Allele.UNK) { AlleleCounts altCounts = alleleCounts.get(alt); AlleleCounts refCounts = alleleCounts.get(refAllele); double qual = isSomatic ? 0 : calcPhredScaledQuality(refCounts.getCount(), altCounts.getCount(), usableDepth); int repeatPeriod = getRepeatPeriod(chromosome, position, alt, altCounts); String refField = ""; String altField = ""; if (alt.getType() == Allele.Type.DEL) { refField = getDelRefField(chromosome, position, alt.getLength()); altField = refField.substring(0, 1); } else if (alt.getType() == Allele.Type.INS) { refField = getInsRefField(chromosome, position); altField = refField + getPreferredInsertBases(alt, altCounts); } call = new SampleCall(chromosome, position, refAllele, alt, alleleCounts, totalDepth, usableDepth, qual, repeatPeriod, tumorMapq0, refField, altField, mismatchExceededReads, refSeq, options); } else { String refField = getInsRefField(chromosome, position); String altField = "."; double qual = 0; int rp = 0; call = new SampleCall(chromosome, position, refAllele, Allele.UNK, alleleCounts, totalDepth, usableDepth, qual, rp, tumorMapq0, refField, altField, mismatchExceededReads, refSeq, options); } return call; } private String getPreferredInsertBases(Allele allele, AlleleCounts counts) { String bases = null; if (counts.getPreferredInsertBases().isEmpty()) { StringBuffer buf = new StringBuffer(); for (int i=0; i<allele.getLength(); i++) { buf.append('N'); } bases = buf.toString(); } else { bases = counts.getPreferredInsertBases(); } return bases; } public static class SampleCall { public static final String FORMAT = "DP:DP2:AD:AD2:SOR:MQ0:ISPAN:VAF:MER:FS:GT"; String chromosome; int position; Allele ref; Allele alt; Map<Allele, AlleleCounts> alleleCounts; int totalReads; int usableDepth; double qual; int repeatPeriod; int mapq0; String refField; String altField; int mismatchExceededReads; HomopolymerRun hrun; String context; int ispan; double fs; CadabraOptions options; SampleCall(String chromosome, int position, Allele ref, Allele alt, Map<Allele, AlleleCounts> alleleCounts, int totalReads, int usableDepth, double qual, int repeatPeriod, int mapq0, String refField, String altField, int mismatchExceededReads, String context, CadabraOptions options) { this.chromosome = chromosome; this.position = position; this.ref = ref; this.alt = alt; this.alleleCounts = alleleCounts; this.totalReads = totalReads; this.usableDepth = usableDepth; this.qual = qual; this.repeatPeriod = repeatPeriod; this.mapq0 = mapq0; this.refField = refField; this.altField = altField; AlleleCounts altCounts = alleleCounts.get(alt); this.mismatchExceededReads = mismatchExceededReads; if (context != null) { this.hrun = HomopolymerRun.find(context); this.context = context; } ispan = altCounts == null ? 0 : altCounts.getMaxReadIdx()-altCounts.getMinReadIdx(); this.options = options; } public float getVaf() { float vaf = 0; AlleleCounts altCounts = alleleCounts.get(alt); if (altCounts != null) { vaf = (float) altCounts.getCount() / (float) usableDepth; } return vaf; } public String getSampleInfo(Allele ref, Allele alt) { AlleleCounts refCounts = alleleCounts.get(ref); AlleleCounts altCounts = alleleCounts.get(alt); if (refCounts == null) { refCounts = AlleleCounts.EMPTY_COUNTS; } if (altCounts == null) { altCounts = AlleleCounts.EMPTY_COUNTS; } float vaf = getVaf(); // Calculate phred scaled probability of read orientations occurring by chance int refFwd = refCounts.getFwd(); int refRev = refCounts.getRev(); int altFwd = altCounts.getFwd(); int altRev = altCounts.getRev(); FishersExactTest test = new FishersExactTest(); double fsP = test.twoTailedTest(refFwd, refRev, altFwd, altRev); // Use abs to get rid of -0 this.fs = Math.abs(-10 * Math.log10(fsP)); String sampleInfo = String.format("%d:%d:%d,%d:%d,%d:%d,%d,%d,%d:%d:%d:%.2f:%d:%.2f:0/1", usableDepth, totalReads, refCounts.getCount(), altCounts.getCount(), refCounts.getTotalCount(), altCounts.getTotalCount(), refCounts.getFwd(), refCounts.getRev(), altCounts.getFwd(), altCounts.getRev(), mapq0, ispan, vaf, mismatchExceededReads, fs); return sampleInfo; } public String toString() { String pos = String.valueOf(position); String qualStr = String.format("%.2f", qual); int hrunLen = hrun != null ? hrun.getLength() : 0; char hrunBase = hrun != null ? hrun.getBase() : 'N'; int hrunPos = hrun != null ? hrun.getPos() : 0; String info = String.format("STRP=%d;HRUN=%d,%c,%d;REF=%s", repeatPeriod, hrunLen, hrunBase, hrunPos, context); String sampleInfo = getSampleInfo(ref, alt); String filter = CadabraProcessor.applyFilters(this, null, options, hrunLen, qual); return String.join("\t", chromosome, pos, ".", refField, altField, qualStr, filter, info, SampleCall.FORMAT, sampleInfo); } } static String applyFilters(SampleCall tumor, SampleCall normal, CadabraOptions options, int hrunLen, double qual) { String filter = ""; // Filter variants that do not appear in sufficiently varying read positions if (tumor.ispan < options.getIspanFilter()) { filter += "ISPAN;"; } // Filter short tandem repeat expansion / contraction if (options.getStrpFilter() > 0 && tumor.repeatPeriod >= options.getStrpFilter()) { filter += "STR;"; } // Filter short indels near homopolymer runs if (options.getHrunFilter() > 0 && hrunLen >= options.getHrunFilter() && Math.abs(tumor.ref.getLength() - tumor.alt.getLength())<10) { filter += "HRUN;"; } // Too many low mapq reads if ((float)tumor.mapq0 / (float)tumor.totalReads > options.getLowMQFilter()) { filter += "LOW_MAPQ;"; } else if (normal != null && (float)normal.mapq0 / (float)normal.totalReads > options.getLowMQFilter()) { filter += "LOW_MAPQ;"; } if (tumor.fs > options.getFsFilter()) { filter += "FS;"; } if (qual < options.getQualFilter()) { filter += "LOW_QUAL;"; } if (filter.equals("")) { filter = "PASS"; } return filter; } static double calcFisherExactPhredScaledQuality(int normalRefObs, int normalAltObs, int tumorRefObs, int tumorAltObs) { FishersExactTest test = new FishersExactTest(); // Calc p-value double p = test.oneTailedTest(normalRefObs, normalAltObs, tumorRefObs, tumorAltObs); double qual; if (p <= 0) { // Don't allow division by 0 or rounding to negative value. qual = 5000.0; } else { // Convert to phred scale qual = -10 * Math.log10(p); // Round to tenths qual = (int) (qual * 10); qual = qual / 10.0; if (qual > 5000.0) { qual = 5000.0; } } return qual; } public static class SomaticCall { SampleCall normal; SampleCall tumor; double qual; double fs; HomopolymerRun hrun; String context; CadabraOptions options; public SomaticCall(SampleCall normal, SampleCall tumor, String context, CadabraOptions options) { this.normal = normal; this.tumor = tumor; int normalRef = normal.alleleCounts.get(tumor.ref) == null ? 0 : normal.alleleCounts.get(tumor.ref).getCount(); int normalAlt = normal.alleleCounts.get(tumor.alt) == null ? 0 : normal.alleleCounts.get(tumor.alt).getCount(); int tumorRef = tumor.alleleCounts.get(tumor.ref).getCount(); int tumorAlt = tumor.alleleCounts.get(tumor.alt).getCount(); this.qual = calcFisherExactPhredScaledQuality(normalRef, normalAlt, tumorRef, tumorAlt); this.hrun = HomopolymerRun.find(context); this.context = context; this.options = options; } public String toString() { String pos = String.valueOf(tumor.position); String qualStr = String.format("%.2f", qual); int hrunLen = hrun != null ? hrun.getLength() : 0; char hrunBase = hrun != null ? hrun.getBase() : 'N'; int hrunPos = hrun != null ? hrun.getPos() : 0; String info = String.format("STRP=%d;HRUN=%d,%c,%d;REF=%s", tumor.repeatPeriod, hrunLen, hrunBase, hrunPos, context); String normalInfo = normal.getSampleInfo(tumor.ref, tumor.alt); String tumorInfo = tumor.getSampleInfo(tumor.ref, tumor.alt); String filter = CadabraProcessor.applyFilters(tumor, normal, options, hrunLen, qual); return String.join("\t", tumor.chromosome, pos, ".", tumor.refField, tumor.altField, qualStr, filter, info, SampleCall.FORMAT, normalInfo, tumorInfo); } } static double strandBias(int rf, int rr, int af, int ar) { FishersExactTest test = new FishersExactTest(); double sb = test.twoTailedTest(rf, rf, af, ar); return sb; } static double calcPhredScaledQuality(int refObs, int altObs, int dp) { return -10 * Math.log10(BetaBinomial.betabinCDF(dp, altObs)); } private int getRepeatPeriod(String chromosome, int position, Allele indel, AlleleCounts indelCounts) { int chromosomeEnd = c2r.getReferenceLength(chromosome); int length = Math.min(indel.getLength() * 20, chromosomeEnd-position-2); String sequence = c2r.getSequence(chromosome, position+1, length); String bases; if (indel.getType() == Allele.Type.DEL) { bases = sequence.substring(0, indel.getLength()); } else { bases = indelCounts.getPreferredInsertBases(); } String repeatUnit = RepeatUtils.getRepeatUnit(bases); int period = RepeatUtils.getRepeatPeriod(repeatUnit, sequence); return period; } private String getDelRefField(String chromosome, int position, int length) { return c2r.getSequence(chromosome, position, length+1); } private String getInsRefField(String chromosome, int position) { return c2r.getSequence(chromosome, position, 1); } private IndelInfo checkForIndelAtLocus(SAMRecord read, int refPos) { IndelInfo elem = null; String contigInfo = read.getStringAttribute("YA"); if (contigInfo != null) { // Get assembled contig info. String[] fields = contigInfo.split(":"); int contigPos = Integer.parseInt(fields[1]); Cigar contigCigar = TextCigarCodec.decode(fields[2]); // Check to see if contig contains indel at current locus elem = checkForIndelAtLocus(contigPos, contigCigar, refPos); if (elem != null) { // Now check to see if this read supports the indel IndelInfo readElem = checkForIndelAtLocus(read.getAlignmentStart(), read.getCigar(), refPos); // Allow partially overlapping indels to support contig // (Should only matter for inserts) if (readElem == null || readElem.getCigarElement().getOperator() != elem.getCigarElement().getOperator()) { // Read element doesn't match contig indel elem = null; } else { elem.setReadIndex(readElem.getReadIndex()); // If this read overlaps the entire insert, capture the bases. if (elem.getCigarElement().getOperator() == CigarOperator.I && elem.getCigarElement().getLength() == readElem.getCigarElement().getLength()) { String insertBases = read.getReadString().substring(readElem.getReadIndex(), readElem.getReadIndex()+readElem.getCigarElement().getLength()); elem.setInsertBases(insertBases); } } } } return elem; } private IndelInfo checkForIndelAtLocus(int alignmentStart, Cigar cigar, int refPos) { IndelInfo ret = null; int readIdx = 0; int currRefPos = alignmentStart; for (CigarElement element : cigar.getCigarElements()) { if (element.getOperator() == CigarOperator.M) { readIdx += element.getLength(); currRefPos += element.getLength(); } else if (element.getOperator() == CigarOperator.I) { if (currRefPos == refPos+1) { ret = new IndelInfo(element, readIdx); break; } readIdx += element.getLength(); } else if (element.getOperator() == CigarOperator.D) { if (currRefPos == refPos+1) { ret = new IndelInfo(element, readIdx); break; } currRefPos += element.getLength(); } else if (element.getOperator() == CigarOperator.S) { readIdx += element.getLength(); } else if (element.getOperator() == CigarOperator.N) { currRefPos += element.getLength(); } if (currRefPos > refPos+1) { break; } } return ret; } }
package simpledb; import java.util.*; /** * Keeps information on the best plan that includes a given set of tables and has a given set of dirty attributes * Insertions into the cache are handled directly to only overwrite if of lower cost. */ public class ImputedPlanCachePareto extends AImputedPlanCache { public ImputedPlanCachePareto() { super(); } /** * Add a plan if it is of lower cost for the appropriate (tables, dirty set) key * @param ts tables in the underlying plan * @param newPlan plan */ public void addPlan(Set<String> ts, ImputedPlan newPlanIP) { addJoinPlan(ts, new HashSet<LogicalJoinNode>(), newPlanIP); } /** * Add a plan involving joins if it is of lower cost for the appropriate (tables, dirty set) key * @param ts tables in the underlying plan * @param joins join predicates involved in the plan * @param newPlan plan */ public void addJoinPlan(Set<String> ts, Set<LogicalJoinNode> joins, ImputedPlan newPlanIP) { Key key = new Key(ts, newPlanIP.getDirtySet()); Value newPlan = new Value(newPlanIP, joins); if (bestPlans.containsKey(key)) { SortedSet<Value> plans = bestPlans.get(key); boolean canBeApproximated = false; // Find dominating plans. for (Value plan : plans) { // Found a dominating plan. if (plan.dominates(newPlan)) { return; } canBeApproximated = canBeApproximated || plan.isApproximate(newPlan); } // Remove dominated plans. plans.removeIf(plan -> newPlan.dominates(plan)); if (!this.approximate || !canBeApproximated) { // add any non-dominated plans if this is not an approximate cache // or only add plans that can not be approximated, if we are an approximate cache plans.add(newPlan); } } else { // always insert if we don't have any info on this key combo TreeSet<Value> plans = new TreeSet<>(); plans.add(newPlan); bestPlans.put(key, plans); } } private double getMinPenalty(Set<String> tables) { double minPenalty = Double.MAX_VALUE; for (ImputedPlanCachePareto.Value val : bestPlans(tables)) { double penalty = val.plan.getPenalty(); if (penalty < minPenalty) { minPenalty = penalty; } } return minPenalty; } public ImputedPlan getFinalPlan(double alpha, Set<String> tables) { // need to know this upfront double minPenalty = getMinPenalty(tables); double minTime = Double.MAX_VALUE; ImputedPlan chosen = null; for (ImputedPlanCachePareto.Value val : bestPlans(tables)) { double time = val.plan.getTime(); double penalty = val.plan.getPenalty(); if ((penalty - minPenalty) <= alpha && time < minTime) { minTime = time; chosen = val.plan; } } return chosen; } }
package com.alexrnl.commons.time; import java.io.Serializable; import java.sql.Date; import java.util.Calendar; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import com.alexrnl.commons.utils.object.AutoCompare; import com.alexrnl.commons.utils.object.AutoHashCode; import com.alexrnl.commons.utils.object.Field; /** * Class representing a time (hours and minutes).<br /> * This time has <em>no limit</em>, which means that the number of hours may be anything (negative, * more than 23, etc.). However, the number of minutes is kept between 0 and 60.<br /> * This class is immutable. * @author Alex */ public class Time implements Serializable, Comparable<Time>, Cloneable { /** Logger */ private static Logger lg = Logger.getLogger(Time.class.getName()); /** Serial Version UID */ private static final long serialVersionUID = -8846707527438298774L; /** The separator between hours and minutes */ public static final String TIME_SEPARATOR = ":"; /** The regex pattern that matches any non decimal character */ public static final String NON_DECIMAL_CHARACTER = "[^0-9]"; /** Number of minutes per hour */ public static final int MINUTES_PER_HOURS = 60; /** The number of hours */ private final int hours; /** The number of minutes */ private final int minutes; /** * Constructor #1.<br /> * Default constructor, set time to midnight. */ public Time () { this(0); } /** * Constructor #2.<br /> * Number of minutes will be set to 0. * @param hours * the number of hours. */ public Time (final int hours) { this(hours, 0); } /** * Constructor #3.<br /> * @param hours * the number of hours. * @param minutes * the number of minutes. */ public Time (final int hours, final int minutes) { super(); int cHours = hours; int cMinutes = minutes; // Correcting if minutes are below zero while (cMinutes < 0) { --cHours; cMinutes += MINUTES_PER_HOURS; } this.hours = cHours + cMinutes / MINUTES_PER_HOURS; this.minutes = cMinutes % MINUTES_PER_HOURS; if (lg.isLoggable(Level.FINE)) { lg.fine("Created time: " + this.hours + " h, " + this.minutes + " min"); } } /** * Constructor #4.<br /> * @param timeStamp * the number of milliseconds since January 1st, 1970. */ public Time (final long timeStamp) { this(new Date(timeStamp)); } /** * Constructor #5.<br /> * Build the time from the date. * @param date * the date to use. */ public Time (final Date date) { final Calendar cal = Calendar.getInstance(Locale.getDefault()); cal.setTime(date); hours = cal.get(Calendar.HOUR_OF_DAY); minutes = cal.get(Calendar.MINUTE); } /** * Constructor #6.<br /> * Copy constructor, build a copy of the time. * @param time * the time to use. */ public Time (final Time time) { this(time.hours, time.minutes); } /** * Build a time based on a string.<br /> * The time format must be hours minutes seconds (in that order) separated using any * non-numerical character.<br /> * @param time * the time set. * @return the time matching the string. */ public static Time get (final String time) { return TimeSec.get(time).getTime(); } /** * Return the current time. * @return a {@link Time} object matching the current time. */ public static Time getCurrent () { return new Time(System.currentTimeMillis()); } /** * Return the attribute hours. * @return the attribute hours. */ @Field public int getHours () { return hours; } /** * Return the attribute minutes. * @return the attribute minutes. */ @Field public int getMinutes () { return minutes; } /** * Add the amount of time specified to the current time.<br /> * There is no maximum, so you may reach 25:48. * @param time * the time to add. * @return the new time. */ public Time add (final Time time) { return new Time(hours + time.hours, minutes + time.minutes); } /** * Subtract the amount of time specified to the current time.<br /> * There is no minimum, so you may reach -2:48. * @param time * the time to subtract. * @return the new time. */ public Time sub (final Time time) { return new Time(hours - time.hours, minutes - time.minutes); } /* * (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo (final Time o) { if (o == null) { return 1; } if (hours > o.hours) { return 1; } else if (hours < o.hours) { return -1; } if (minutes > o.minutes) { return 1; } else if (minutes < o.minutes) { return -1; } if (this.getClass().equals(Time.class) && o.getClass().equals(Time.class)) { // This is true only if both object are of type Time assert equals(o); } return 0; } /** * Check if the current time is after the specified time.<br /> * @param time * the time used for reference. * @return <code>true</code> if this time is after the reference time provided. * @see #compareTo(Time) */ public boolean after (final Time time) { return compareTo(time) > 0; } /** * Check if the current time is before the specified time.<br /> * @param time * the time used for reference. * @return <code>true</code> if this time is before the reference time provided. * @see #compareTo(Time) */ public boolean before (final Time time) { return compareTo(time) < 0; } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString () { String h = Integer.toString(hours); String m = Integer.toString(minutes); if (h.length() < 2) { h = Integer.valueOf(0) + h; } if (m.length() < 2) { m = Integer.valueOf(0) + m; } return h + TIME_SEPARATOR + m; } /* * (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode () { return AutoHashCode.getInstance().hashCode(this); } /* * (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals (final Object obj) { if (!(obj instanceof Time)) { return false; } return AutoCompare.getInstance().compare(this, (Time) obj); } /* * (non-Javadoc) * @see java.lang.Object#clone() */ @Override public Time clone () throws CloneNotSupportedException { return new Time(this); } }
import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Properties; import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.impl.Arguments; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.inf.Namespace; import reflect.CodeExceptions; import reflect.Plugins; import reflect.android.API; import reflect.api.Class; import reflect.api.Classes; import reflect.api.Method; import reflect.api.Param; import reflect.api.Property; import reflect.cpp.CppWriter; public class Reflect { private File m_inc; private File m_src; private boolean m_utf8; private List<String> m_classes; private List<File> m_files = new LinkedList<File>(); public Reflect(File inc, File src, boolean utf8) { m_inc = inc; m_src = src; m_utf8 = utf8; m_classes = null; } private void setKnownClasses(List<String> classes) { m_classes = classes; } private static final String spaces = " "; private void printClass(String clazz, int curr, int max) throws IOException { Class klazz = Classes.forName(clazz); if (klazz == null) return; String supah = klazz.getSuper(); String[] interfaces = klazz.getInterfaces(); System.out.print("class " + clazz); if (supah != null || interfaces.length > 0) { if (clazz.length() < spaces.length()) System.out.print(spaces.substring(clazz.length())); } if (supah != null) System.out.print(" extends " + supah); if (interfaces.length > 0) { System.out.print(" implements "); boolean first = true; for (String iface: interfaces) { if (first) first = false; else System.out.print(", "); System.out.print(iface); } } System.out.println(" (" + curr + "/" + max + ")"); CppWriter writer = new CppWriter(klazz, m_classes, m_utf8); writer.printHeader(m_inc, m_files); writer.printSource(m_src); } private static String relative(File dir, File path) { final String regexp = File.separator.replace("\\", "\\\\").replace(".", "\\."); String[] src = dir.toString().split(regexp); String[] dst = path.toString().split(regexp); int pos = 0; while (pos < src.length && pos < dst.length - 1 && src[pos].equals(dst[pos])) ++pos; StringBuilder sb = new StringBuilder(); for (int i = pos; i < src.length; ++i) sb.append("../"); for (int i = pos; i < dst.length - 1; ++i) sb.append(dst[i] + "/"); sb.append(dst[dst.length-1]); return sb.toString(); } public void fileList(File output) { PrintStream out = null; try { final File dir = output.getCanonicalFile().getParentFile(); out = new PrintStream(output, "UTF-8"); for (File f: m_files) out.println(relative(dir, f)); } catch (IOException e) { e.printStackTrace(); } finally { out.close(); } } private static File getAppDir() { String path = Reflect.class.getResource("/" + Reflect.class.getName() + ".class").toString(); while (path.startsWith("jar:")) { System.out.println(path); int pos = path.lastIndexOf("!"); if (pos == -1) pos = path.length(); path = path.substring(4, pos); } if (path.startsWith("file:/")) { path = path.substring(6); } System.out.println(path); try { return new File(path).getCanonicalFile().getParentFile(); } catch (IOException e) { e.printStackTrace(); }; return null; } public static void main(String[] args) { final File appDir = getAppDir(); if (appDir == null) return; Plugins.loadPlugins(new File(appDir, "plugins")); //CodeExceptions.readExceptions(appDir); ArgumentParser parser = ArgumentParsers.newArgumentParser("Reflect") .defaultHelp(true) .description("Create JINI bindings for given class(es). CLASS can be in form java.lang.Class to generate binding for one class only or java.lang.* to generate it for all java.lang classes (but not java.class.reflect classes). When a subclass is provided ($ is present), it will be changed to the outer-most class.") .epilog("Either --all or at least one class is needed."); parser.addArgument("-a", "--android") .metavar("API") .type(Integer.class) .dest("targetAPI") .required(true) .help("Android API Level (e.g. -a 17 for Android 4.2)"); parser.addArgument("-8", "--utf8") .action(Arguments.storeTrue()) .setDefault(false) .help("replace java.lang.String with const char*"); parser.addArgument("--dest") .metavar("DIR") .type(File.class) .setDefault(new File("./code")) .dest("dest") .help("the output directory"); parser.addArgument("--inc") .metavar("DIR") .type(File.class) .dest("inc") .help("the output dir for .hpp files (default: $dest" + File.separator + "inc)"); parser.addArgument("--src") .metavar("DIR") .type(File.class) .dest("src") .help("the output dir for .cpp files (default: $dest" + File.separator + "src)"); parser.addArgument("--preserve-refs") .action(Arguments.storeTrue()) .setDefault(false) .dest("refs") .help("preserve methods and properties, whose types are not builtin, in java.lang package nor on the list of classes"); parser.addArgument("--parents") .action(Arguments.storeTrue()) .setDefault(false) .help("generate classes for the superclass and interfaces classes"); parser.addArgument("--all-deps") .action(Arguments.storeTrue()) .setDefault(false) .help("Generate classes for the superclass, interfaces, field and parameter classes; implies --parent and --preserve-refs"); parser.addArgument("--all") .action(Arguments.storeTrue()) .setDefault(false) .help("Generate bindings for all the classes in the API; implies --all-deps, --parent and --preserve-refs"); parser.addArgument("--file-list") .metavar("FILE") .type(File.class) .help("output list of generated files for further processing"); parser.addArgument("classes") .metavar("CLASS") .type(String.class) .nargs("*") .help("class and/or package to generate bindings for"); Namespace ns = null; try { ns = parser.parseArgs(args); if (!ns.getBoolean("all") && ns.getList("classes").size() == 0) throw new ArgumentParserException("Either --all or at least one class is needed.", parser); } catch (ArgumentParserException e) { parser.handleError(e); System.exit(1); } File inc = (File)ns.get("inc"); File src = (File)ns.get("src"); File dest = (File)ns.get("dest"); File files = (File)ns.get("file_list"); boolean utf8 = ns.getBoolean("utf8"); boolean all = ns.getBoolean("all"); boolean deps = ns.getBoolean("all_deps"); boolean parents = ns.getBoolean("parents"); boolean refs = ns.getBoolean("refs"); final List<String> list = ns.getList("classes"); List<String> classes = new LinkedList<String>(); if (inc == null) inc = new File(dest, "inc"); if (src == null) src = new File(dest, "src"); if (all) deps = true; // deps is a subset of deps if (deps) parents = true; // parents is a subset of deps if (deps) refs = true; //if deps (or all) is present, we do not want to look for limits, as there should be none try { System.out.print("API Level : "); System.out.println(ns.getInt("targetAPI")); System.out.print("Headers : "); System.out.println(inc.getCanonicalPath()); System.out.print("Sources : "); System.out.println(src.getCanonicalPath()); System.out.print("Strings : "); System.out.println(utf8 ? "const char* utf8" : "java.lang.String"); System.out.print("Mode : "); System.out.println(all ? "Entire API" : deps ? "All dependencies" : parents ? "Parents" : "Classes"); System.out.print("Unk. refs : "); System.out.println(refs ? "preserved" : "methods removed"); System.out.print("Classes : "); if (all) System.out.println("all"); else System.out.println(list); } catch (IOException e1) { e1.printStackTrace(); } int sdk = ns.getInt("targetAPI"); try { final API android = new API(); Classes.addApi(android); if (!android.setTargetApi(sdk)) { System.err.println("Could not initiate android-" + sdk + " environment"); return; } if (!Classes.readApis()) return; final Reflect reflect = new Reflect(inc, src, utf8); for (String item: list) { if (item.endsWith(".*")) { String [] pkg = Classes.packageClasses(item.substring(0, item.length()-2)); for (String clazz: pkg) classes.add(clazz); continue; } classes.add(item); } if (all) { classes.clear(); String[] api_classes = Classes.classNames(); for (String clazz: api_classes) if (clazz.indexOf('$') == -1) classes.add(clazz); } else if (parents) // || deps, see above { int i = 0; while (i < classes.size()) addClass(classes, Classes.forName(classes.get(i++)), deps); } int curr = 0; if (!refs) reflect.setKnownClasses(classes); for (String s: classes) { reflect.printClass(s, ++curr, classes.size()); } if (files != null) reflect.fileList(files); } catch (Exception e) { e.printStackTrace(); } } static void addSignature(List<String> classes, String type) { int array = 0; while (array < type.length() && type.charAt(array) == '[') ++array; if (array < type.length() && type.charAt(array) == 'L') addClass(classes, type.substring(array + 1, type.length() - 1)); } static void addClass(List<String> classes, String className) { int pos = className.indexOf('$'); if (pos != -1) className = className.substring(0, pos); for (String s: classes) if (s.equals(className)) return; classes.add(className); } static void addClass(List<String> classes, Class c, boolean all) { if (c == null) return; final String sup = c.getSuper(); final String[] ifaces = c.getInterfaces(); if (sup != null) addClass(classes, sup); for (String iface: ifaces) addClass(classes, iface); if (all) { for (Property prop: c.getProperties()) addSignature(classes, prop.getSignature()); for (Method method: c.getMethods()) { addSignature(classes, method.getReturnType()); for (Param param: method.getParameterTypes()) addSignature(classes, param.getSignature()); } } for (Class sub: c.getClasses()) addClass(classes, sub, all); } }
package com.alibaba.excel; import java.io.OutputStream; import java.util.List; import com.alibaba.excel.metadata.BaseRowModel; import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Table; import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.write.ExcelBuilder; import com.alibaba.excel.write.ExcelBuilderImpl; /** * excelthread unsafe * * @author jipengfei */ public class ExcelWriter { private ExcelBuilder excelBuilder; /** * EXCEL * * @param outputStream * @param typeEnum 030707excel */ public ExcelWriter(OutputStream outputStream, ExcelTypeEnum typeEnum) { this(outputStream, typeEnum, true); } /** * EXCEL * * @param outputStream * @param typeEnum 030707excel * @param needHead */ public ExcelWriter(OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) { excelBuilder = new ExcelBuilderImpl(); excelBuilder.init(outputStream, typeEnum, needHead); } /** * sheet,sheet * * @param data BaseRowModel * @param sheet datasheet * @return this */ public ExcelWriter write(List<? extends BaseRowModel> data, Sheet sheet) { excelBuilder.addContent(data, sheet); return this; } /** * sheet,sheet * * @param data List * @param sheet datasheet * @return this */ public ExcelWriter write0(List<List<String>> data, Sheet sheet) { excelBuilder.addContent(data, sheet); return this; } /** * sheet,sheet * * @param data type java * @param sheet datasheet * @param table datatable * @return this */ public ExcelWriter write(List<? extends BaseRowModel> data, Sheet sheet, Table table) { excelBuilder.addContent(data, sheet, table); return this; } /** * sheet,sheet * * @param data List * @param sheet datasheet * @param table datatable * @return this */ public ExcelWriter write0(List<List<String>> data, Sheet sheet, Table table) { excelBuilder.addContent(data, sheet, table); return this; } public void finish() { excelBuilder.finish(); } }
// File: Guide.java (20-Oct-2011) // Tim Niblett (the Author) and may not be used, // sold, licenced, transferred, copied or reproduced in whole or in // part in any manner or form or in or on any media to any person // other than in accordance with the terms of The Author's agreement // or otherwise without the prior written consent of The Author. All // information contained in this source file is confidential information // belonging to The Author and as such may not be disclosed other // than in accordance with the terms of The Author's agreement, or // otherwise, without the prior written consent of The Author. As // confidential information this source file must be kept fully and // effectively secure at all times. package com.cilogi.ds.guide; import com.cilogi.ds.guide.diagrams.Diagrams; import com.cilogi.ds.guide.mapper.GuideMapper; import com.cilogi.ds.guide.galleries.Gallery; import com.cilogi.ds.guide.listings.Listing; import com.cilogi.ds.guide.mapper.Location; import com.cilogi.ds.guide.media.GuideAudio; import com.cilogi.ds.guide.media.GuideImage; import com.cilogi.ds.guide.pages.Page; import com.cilogi.ds.guide.pages.PageImage; import com.cilogi.ds.guide.shop.Shop; import com.cilogi.ds.guide.tours.IPageTitler; import com.cilogi.ds.guide.tours.PageRef; import com.cilogi.ds.guide.tours.Tour; import com.cilogi.ds.guide.tours.TourStop; import com.cilogi.util.path.PathUtil; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import lombok.*; import org.hjson.JsonValue; import java.io.IOException; import java.io.Serializable; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; @JsonInclude(JsonInclude.Include.NON_NULL) @EqualsAndHashCode @ToString @Data public class GuideJson implements Serializable, IGuide, IPageTitler { @SuppressWarnings("unused") static final Logger LOG = Logger.getLogger(GuideJson.class.getName()); private static final long serialVersionUID = -9153256781053121634L; private static final String CONFIG_NAME = "config.json"; private static final String DEFAULT_VERSION = "1"; private static final String DEFAULT_GUIDE_SPEC_VERSION = "3"; private static final Set<String> LOCAL_GUIDES = ImmutableSet.of( "stop" ); private java.lang.String name; private final String guideSpecVersion; private Config config; private String title; private String description; private List<Page> pages; private Map<String,String> pageDigests; private Diagrams diagrams; private Set<GuideImage> images; private Set<GuideAudio> audioClips; private List<Tour> tours; private List<Gallery> galleries; private List<Listing> listings; private Map<String,byte[]> etags; private Shop shop; public static Set<String> localGuides() { return LOCAL_GUIDES; } public static GuideJson fromJSON(String data) throws IOException { GuideMapper mapper = new GuideMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); return mapper.readValue(JsonValue.readHjson(data).toString(), GuideJson.class); } public String getConfigName() { return CONFIG_NAME; } public GuideJson() { title = ""; description = ""; guideSpecVersion = DEFAULT_GUIDE_SPEC_VERSION; config = new Config(); pages = new ArrayList<>(); pageDigests = new ConcurrentHashMap<>(); diagrams = new Diagrams(); images = Sets.newConcurrentHashSet(); audioClips = Sets.newConcurrentHashSet(); tours = new ArrayList<>(); galleries = new ArrayList<>(); listings = new ArrayList<>(); etags = new java.util.HashMap<>(); } public GuideJson(@NonNull String name) { this(); this.name = name; setTitle(name); } /** * Copy constructor * @param guide The guide to copy */ public GuideJson(IGuide guide) { this.guideSpecVersion = guide.getGuideSpecVersion(); this.name = guide.getName(); this.title = guide.getTitle(); this.description = guide.getDescription(); this.pages = new ArrayList<>(guide.getPages()); this.pageDigests = new ConcurrentHashMap<>(guide.getPageDigests()); this.diagrams = new Diagrams(guide.getDiagrams()); this.images = Sets.newConcurrentHashSet(guide.getImages()); this.audioClips = Sets.newConcurrentHashSet(guide.getAudioClips()); this.tours = new ArrayList<>(guide.getTours()); this.galleries = new ArrayList<>(guide.getGalleries()); this.listings = new ArrayList<>(guide.getListings()); this.etags = new java.util.HashMap<>(guide.getEtags()); this.config = (guide.getConfig() == null) ? null : new Config(guide.getConfig()); if (this.config != null && this.title != null) { this.config.setTitle(this.title); } this.shop = (guide.getShop() == null) ? null : new Shop(guide.getShop()); } /** * Can this guide be saved properly? * @return true iff its OK to save */ @JsonIgnore public boolean isValidState() { return name.length() > 0; } @JsonIgnore public boolean isShared() { return config != null && config.isShared(); } public String getTitle() { return (title == null) ? name : title; } public void setTitle(@NonNull String name) { title = name; getConfig().setTitle(name); } public Set<String> tourNames() { List<Tour> tours = getTours(); Set<String> names = new HashSet<>(); for (Tour tour : tours) { names.add(tour.getId()); } return names; } /** * Export named tour * @param name The name of the tour * @return null if there is no tour of that name, else the tour with stops prefixed with the guide * name, so that the tour can be imported without change into other guides. */ public Tour exportTour(@NonNull String name) { Tour tour = findTour(name); if (tour == null) { return null; } else { Tour out = new Tour(tour); for (TourStop stop : out.getStops()) { PageRef pageRef = stop.getPageRef(); if (!pageRef.isExternal()) { stop.setPageRef(new PageRef(getName(), pageRef.getPageIndex())); } } return out; } } /** * Import tour into guide * @param tourToImport The tour * @return The imported tour, where stops that are in this guide get converted to be local */ public Tour importTour(@NonNull Tour tourToImport) { Tour tour = new Tour(tourToImport); Tour current = findTour(tour.getId()); if (current != null) { getTours().remove(current); } String guideName = getName(); for (TourStop stop : tour.getStops()) { PageRef ref = stop.getPageRef(); if (ref.isExternal() && guideName.equals(ref.getGuideName())) { stop.setPageRef(new PageRef("", ref.getPageIndex())); } } getTours().add(tour); return tour; } public Tour findTour(@NonNull String name) { for (Tour tour : tours) { if (name.equals(tour.getId())) { return tour; } } return null; } public Page findPage(int pageId) { for (Page page: pages) { if (page.getId() == pageId) { return page; } } return null; } public GuideImage findImage(@NonNull String name) { Set<GuideImage> images = getImages(); for (GuideImage image : images) { if (name.equals(image.getId())) { return image; } } return null; } public void updatePage(@NonNull Page page) { int id = page.getId(); Page already = findPage(id); if (already != null) { pages.remove(already); } pages.add(page); } public void setPageDigest(int pageId, @NonNull String digest) { getPageDigests().put(Integer.toString(pageId), digest); } public synchronized GuideImage guideImageFor(String imageName) { String imageId = PathUtil.name(imageName); Set<GuideImage> images = getImages(); for (GuideImage image : images) { if (imageId.equals(image.getId())) { return image; } } return null; } public synchronized GuideAudio guideAudioFor(String audioName) { String audioId = PathUtil.name(audioName); Set<GuideAudio> audioClips = getAudioClips(); for (GuideAudio audioClip : audioClips) { if (audioId.equals(audioClip.getId())) { return audioClip; } } return null; } public synchronized void setGuideImageDigest(GuideImage guideImage, int width, int height, String digest) { guideImage.setDigest(digest) .setWidth(width) .setHeight(height); } public synchronized boolean setAudioDigest(String audioName, String digest) { String audioId = PathUtil.name(audioName); Set<GuideAudio> audios = getAudioClips(); for (GuideAudio audio : audios) { if (audioId.equals(audio.getId())) { audio.setDigest(digest) .setUrl(audioName); return true; } } return false; } public synchronized void appendPage(@NonNull Page page) { pages.add(page); } /** * If a page image has some alt text and the GuideImage does not have * a title set then set the title from the alt text. */ public synchronized void synchronizeGuideImagesWithPageImages() { for (Page page : getPages()) { List<PageImage> images = page.getImages(); for (PageImage image : images) { String src = PathUtil.name(image.getSrc()); String alt = image.getAlt(); GuideImage guideImage = findImage(src); if (guideImage == null) { LOG.warning("Can't find image " + src); continue; } String existingTitle = guideImage.getTitle(); if (alt != null) { if (existingTitle == null || existingTitle.trim().equals("")) { guideImage.setTitle(alt); } } else { image.setAlt(existingTitle); } } } } public synchronized void setTourLocations() { for (Tour tour : getTours()) { if (tour.getLocation() == null) { for (TourStop stop : tour.getStops()) { PageRef ref = stop.getPageRef(); if (ref.isCompatibleGuide(getName())) { Page page = findPage(ref.getPageIndex()); if (page != null && page.getLocation() != null && page.getLocation().isLatLng()) { tour.setLocation(page.getLocation()); break; } } } if (tour.getLocation() == null && getConfig().getLatlng() != null) { tour.setLocation(new Location(getConfig().getLatlng())); } } } } public void makeToursPublic() { makeToursPublic(this); } public void makeToursPublic(IPageTitler titler) { String guideName = getName(); for (Tour tour : getTours()) { tour.makePublic(guideName, titler); } } public String toJSONString() { try { GuideMapper mapper = new GuideMapper(); return mapper.writeValueAsString(this); } catch (JsonProcessingException e) { LOG.severe("Can't convert Guide " + this + " to JSON string"); return "{}"; } } @Override public String title(int pageIndex) { Page page = findPage(pageIndex); return (page == null) ? null : page.getTitle(); } }
package com.conveyal.gtfs.loader; import com.conveyal.gtfs.error.GTFSError; import com.conveyal.gtfs.error.NewGTFSError; import com.conveyal.gtfs.error.SQLErrorStorage; import com.conveyal.gtfs.model.*; import com.conveyal.gtfs.storage.StorageException; import com.conveyal.gtfs.validator.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static com.conveyal.gtfs.error.NewGTFSErrorType.VALIDATOR_FAILED; /** * This connects to an SQL RDBMS containing GTFS data and lets you fetch elements out of it. */ public class Feed { private static final Logger LOG = LoggerFactory.getLogger(Feed.class); private final DataSource dataSource; // The unique database schema name for this particular feed, including the separator charater (dot). // This may be the empty string if the feed is stored in the root ("public") schema. public final String tablePrefix; public final TableReader<Agency> agencies; public final TableReader<Calendar> calendars; public final TableReader<CalendarDate> calendarDates; // public final TableReader<Fare> fares; public final TableReader<Route> routes; public final TableReader<Stop> stops; public final TableReader<Trip> trips; public final TableReader<ShapePoint> shapePoints; public final TableReader<StopTime> stopTimes; /* A place to accumulate errors while the feed is loaded. Tolerate as many errors as possible and keep on loading. */ // TODO remove this and use only NewGTFSErrors in Validators, loaded into a JDBC table public final List<GTFSError> errors = new ArrayList<>(); /** * Create a feed that reads tables over a JDBC connection. The connection should already be set to the right * schema within the database. * @param tablePrefix the unique prefix for the table (may be null for no prefix) */ public Feed (DataSource dataSource, String tablePrefix) { this.dataSource = dataSource; // Ensure separator dot is present if (tablePrefix != null && !tablePrefix.endsWith(".")) tablePrefix += "."; this.tablePrefix = tablePrefix == null ? "" : tablePrefix; agencies = new JDBCTableReader(Table.AGENCY, dataSource, tablePrefix, EntityPopulator.AGENCY); // fares = new JDBCTableReader(Table.FARES, dataSource, tablePrefix, EntityPopulator.FARE); calendars = new JDBCTableReader(Table.CALENDAR, dataSource, tablePrefix, EntityPopulator.CALENDAR); calendarDates = new JDBCTableReader(Table.CALENDAR_DATES, dataSource, tablePrefix, EntityPopulator.CALENDAR_DATE); routes = new JDBCTableReader(Table.ROUTES, dataSource, tablePrefix, EntityPopulator.ROUTE); stops = new JDBCTableReader(Table.STOPS, dataSource, tablePrefix, EntityPopulator.STOP); trips = new JDBCTableReader(Table.TRIPS, dataSource, tablePrefix, EntityPopulator.TRIP); shapePoints = new JDBCTableReader(Table.SHAPES, dataSource, tablePrefix, EntityPopulator.SHAPE_POINT); stopTimes = new JDBCTableReader(Table.STOP_TIMES, dataSource, tablePrefix, EntityPopulator.STOP_TIME); } /** * TODO check whether validation has already occurred, overwrite results. * TODO allow validation within feed loading process, so the same connection can be used, and we're certain loaded data is 100% visible. * That would also avoid having to reconnect the error storage to the DB. */ public ValidationResult validate () { long validationStartTime = System.currentTimeMillis(); // Create an empty validation result that will have its fields populated by certain validators. ValidationResult validationResult = new ValidationResult(); // Error tables should already be present from the initial load. // Reconnect to the existing error tables. SQLErrorStorage errorStorage = null; try { errorStorage = new SQLErrorStorage(dataSource.getConnection(), tablePrefix, false); } catch (SQLException ex) { throw new StorageException(ex); } int errorCountBeforeValidation = errorStorage.getErrorCount(); List<FeedValidator> feedValidators = Arrays.asList( new MisplacedStopValidator(this, errorStorage, validationResult), new DuplicateStopsValidator(this, errorStorage), new TimeZoneValidator(this, errorStorage), new NewTripTimesValidator(this, errorStorage), new NamesValidator(this, errorStorage)); for (FeedValidator feedValidator : feedValidators) { String validatorName = feedValidator.getClass().getSimpleName(); try { LOG.info("Running {}.", validatorName); int errorCountBefore = errorStorage.getErrorCount(); // todo why not just pass the feed and errorstorage in here? feedValidator.validate(); LOG.info("{} found {} errors.", validatorName, errorStorage.getErrorCount() - errorCountBefore); } catch (Exception e) { // store an error if the validator fails // FIXME: should the exception be stored? String badValue = String.join(":", validatorName, e.toString()); errorStorage.storeError(NewGTFSError.forFeed(VALIDATOR_FAILED, badValue)); LOG.error("{} failed.", validatorName); LOG.error(e.toString()); e.printStackTrace(); } } // Signal to all validators that validation is complete and allow them to report on results / status. for (FeedValidator feedValidator : feedValidators) { try { feedValidator.complete(validationResult); } catch (Exception e) { String badValue = String.join(":", feedValidator.getClass().getSimpleName(), e.toString()); errorStorage.storeError(NewGTFSError.forFeed(VALIDATOR_FAILED, badValue)); LOG.error("Validator failed completion stage.", e); } } // Total validation errors accounts for errors found during both loading and validation. Otherwise, this value // may be confusing if it reads zero but there were a number of data type or referential integrity errors found // during feed loading stage. int totalValidationErrors = errorStorage.getErrorCount(); LOG.info("Errors found during load stage: {}", errorCountBeforeValidation); LOG.info("Errors found by validators: {}", totalValidationErrors - errorCountBeforeValidation); errorStorage.commitAndClose(); long validationEndTime = System.currentTimeMillis(); long totalValidationTime = validationEndTime - validationStartTime; LOG.info("{} validators completed in {} milliseconds.", feedValidators.size(), totalValidationTime); // update validation result fields validationResult.errorCount = totalValidationErrors; validationResult.validationTime = totalValidationTime; // FIXME: Validation result date and int[] fields need to be set somewhere. return validationResult; } /** * @return a JDBC connection to the database underlying this Feed. */ public Connection getConnection() throws SQLException { return dataSource.getConnection(); } }
package com.e16din.lightutils.utils; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.location.LocationManager; import android.net.ConnectivityManager; import android.os.Build; import android.os.Handler; import android.view.WindowManager; import android.webkit.CookieManager; import com.e16din.lightutils.LightUtils; import java.util.List; public final class U extends ResourcesUtils { public static final int WRONG_VALUE = -100500; private U() { } private static Handler handler = new Handler(); public static Handler getHandler() { return handler; } public static void log(Object object) { LogUtils.log(object); } public static boolean isEmulator() { return Build.FINGERPRINT.startsWith("generic") || Build.FINGERPRINT.startsWith("unknown") || Build.MODEL.contains("google_sdk") || Build.MODEL.contains("Emulator") || Build.MODEL.contains("Android SDK built for x86") || Build.MANUFACTURER.contains("Genymotion") || (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic")) || "google_sdk" .equals(Build.PRODUCT); } public static boolean isGpsEnabled() { final Context context = LightUtils.getInstance().getContext(); final LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); return manager.isProviderEnabled(LocationManager.GPS_PROVIDER); } public static boolean isOnline() { final Context context = LightUtils.getInstance().getContext(); ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting(); } public static boolean runIfOnline(boolean isOnline, Runnable callback) { boolean result = isOnline(); if (result == isOnline) callback.run(); return result; } public static boolean isCallable(Context context, Intent intent) { List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); return list.size() > 0; } public static boolean contains(int from, int to, int value) { return value >= from && value <= to; } public static boolean contains(float from, float to, float value) { return value >= from && value <= to; } public static boolean allAbsValuesSmallerThan(List<Float> values, float thanX) { boolean isClick = true; for (float value : values) { if (Math.abs(value) > thanX) { isClick = false; break; } } return isClick; } public static boolean tryThis(Runnable runnable) { try { if (runnable != null) { runnable.run(); return true; } } catch (NullPointerException | WindowManager.BadTokenException | IllegalStateException e) { e.printStackTrace(); } return false; } public static void startTimer(final Long interval, final int count, final Runnable onTick) { U.getHandler().postDelayed(new Runnable() { @Override public void run() { onTick.run(); if (count - 1 > 0) { startTimer(interval, count - 1, onTick); } } }, interval); } public static void clearCookie() { CookieManager cookieManager = CookieManager.getInstance(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { cookieManager.removeAllCookies(null); } else { cookieManager.removeAllCookie(); } } /** * Function from Objects(api level 19) for compatibility with old versions * <p/> * Null-safe equivalent of {@code a.equals(b)}. */ public static boolean equals(Object a, Object b) { return (a == null) ? (b == null) : a.equals(b); } /** * Get activity from context object * * @param context the context * @return object of Activity or null if it is not Activity */ public static Activity scanForActivity(Context context) { if (context == null) return null; else if (context instanceof Activity) return (Activity) context; else if (context instanceof ContextWrapper) return scanForActivity(((ContextWrapper) context).getBaseContext()); return null; } }
package com.fishercoder.solutions; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class _30 { public static class Solution1 { /**TODO: this one is not AC'ed. fix this one.*/ public List<Integer> findSubstring(String s, String[] words) { Map<String, Integer> map = new HashMap<>(); for (String word : words) { map.put(word, 1); } List<Integer> result = new ArrayList<>(); int startIndex = 0; int wordLen = words.length; for (int i = 0; i < s.length(); i++) { startIndex = i; Map<String, Integer> clone = new HashMap<>(map); int matchedWord = 0; for (int j = i + 1; j < s.length(); j++) { String word = s.substring(i, j); if (clone.containsKey(word) && clone.get(word) == 1) { clone.put(word, 0); i = j; matchedWord++; } if (matchedWord == wordLen) { boolean all = true; for (String key : clone.keySet()) { if (clone.get(key) != 0) { all = false; break; } } if (all) { result.add(startIndex); } matchedWord = 0; } } } return result; } } }
package com.fishercoder.solutions; import java.util.ArrayList; import java.util.List; /** * 46. Permutations * * Given a collection of distinct numbers, return all possible permutations. For example, [1,2,3] have the following permutations: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] */ public class _46 { public static class Solution1 { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> result = new ArrayList(); result.add(new ArrayList<>()); return backtracking(result, nums, 0); } private List<List<Integer>> backtracking(List<List<Integer>> result, int[] nums, int pos) { if (pos == nums.length) { return result; } List<List<Integer>> newResult = new ArrayList(); for (List<Integer> eachList : result) { for (int i = 0; i <= eachList.size(); i++) { //attn: i starts from 0 List<Integer> newList = new ArrayList(eachList); newList.add(i, nums[pos]); newResult.add(newList); } } result = newResult; return backtracking(result, nums, pos + 1); } } }
package com.flipstudio.pluma; import java.io.File; import java.util.List; import java.util.Map; import static com.flipstudio.pluma.Pluma.SQLITE_DONE; import static com.flipstudio.pluma.Pluma.SQLITE_MISUSE; import static com.flipstudio.pluma.Pluma.SQLITE_OK; import static com.flipstudio.pluma.Pluma.SQLITE_OPEN_CREATE; import static com.flipstudio.pluma.Pluma.SQLITE_OPEN_READWRITE; import static java.util.Arrays.asList; public final class Database { //region Fields private final String mPath; private String mTempDir; private long mDB; private DatabaseListener mDatabaseListener; //endregion //region Static static { System.loadLibrary("pluma"); } //endregion //region Constructors public Database(String path) { mPath = path; mTempDir = new File(path).getParent(); } //endregion //region Native private native long open(String filePath, int flags, int[] ppOpenCode, String[] ppOpenError); private native long prepare(long db, String sql, int[] ppPrepareCode); private native int exec(long db, String sql, String[] ppOutError); private native int close(long db); private native long lastInsertId(long db); private native String lastErrorMessage(long db); private native void setTempDir(String tempDir); //endregion //region Public public void open() throws SQLiteException { open(SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE); } public void open(int flags) throws SQLiteException { int[] codes = new int[1]; String[] errors = new String[1]; long db = open(mPath, flags, codes, errors); if (codes[0] != SQLITE_OK || db == 0 || errors[0] != null) { throw new SQLiteException(codes[0], errors[0]); } mDB = db; setTempDir(mTempDir); } public void setTempDirectory(String tempDir) { if (isOpen()) { setTempDir(tempDir); } mTempDir = tempDir; } public Statement prepareStatement(String sql) throws SQLiteException { int[] prepareCode = new int[1]; int rc; long stmt = prepare(mDB, sql, prepareCode); rc = prepareCode[0]; if (rc != SQLITE_OK || stmt == 0) { throw new SQLiteException(rc, lastErrorMessage(mDB), sql); } return new Statement(stmt); } public void execute(String sql) throws SQLiteException { String[] errors = new String[1]; int rc = exec(mDB, sql, errors); if (rc != SQLITE_OK) { throw new SQLiteException(rc, errors[0], sql); } notifyListenerOnExecuteQuery(sql); } public boolean executeUpdate(String sql) throws SQLiteException { return executeUpdate(sql, (Object[]) null); } public boolean executeUpdate(String sql, Map<String, Object> arguments) throws SQLiteException { return executeUpdate(sql, null, arguments); } public boolean executeUpdate(String sql, Object... arguments) throws SQLiteException { return executeUpdate(sql, arguments == null ? null : asList(arguments)); } public boolean executeUpdate(String sql, List<Object> arguments) throws SQLiteException { return executeUpdate(sql, arguments, null); } public ResultSet executeQuery(String sql) throws SQLiteException { return executeQuery(sql, (Object[]) null); } public ResultSet executeQuery(String sql, Map<String, Object> arguments) throws SQLiteException { return executeQuery(sql, null, arguments); } public ResultSet executeQuery(String sql, Object... arguments) throws SQLiteException { return executeQuery(sql, arguments == null ? null : asList(arguments)); } public ResultSet executeQuery(String sql, List<Object> arguments) throws SQLiteException { return executeQuery(sql, arguments, null); } public long getLastInsertId() { return lastInsertId(mDB); } public String getLastErrorMessage() { return lastErrorMessage(mDB); } /* Use with native code. sqlite3 *db = reinterpret_cast<sqlite3*>(jdb); */ public long getSQLiteHandler() { return mDB; } public boolean close() throws SQLiteException { int rc = close(mDB); if (rc != SQLITE_OK) { throw new SQLiteException(rc, lastErrorMessage(mDB)); } mDB = 0; return true; } public boolean isClosed() { return mDB == 0; } public boolean isOpen() { return mDB > 0; } public String getDatabasePath() { return mPath; } //endregion //region Private private boolean executeUpdate(String sql, List<Object> listArgs, Map<String, Object> mapArgs) throws SQLiteException { Statement statement = compileStatement(sql, listArgs, mapArgs); int rc = statement.step(); statement.close(); if (rc != SQLITE_DONE) { throw new SQLiteException(rc, getLastErrorMessage(), sql); } notifyListenerOnExecuteQuery(sql); return true; } private ResultSet executeQuery(String query, List<Object> listArgs, Map<String, Object> mapArgs) throws SQLiteException { ResultSet rs = new ResultSet(this, compileStatement(query, listArgs, mapArgs)); notifyListenerOnExecuteQuery(query); return rs; } private void notifyListenerOnExecuteQuery(String sql) { if (mDatabaseListener != null) { mDatabaseListener.onExecuteQuery(sql); } } private Statement compileStatement(String query, List<Object> listArgs, Map<String, Object> mapArgs) throws SQLiteException { Statement statement = prepareStatement(query); int rc, index = 1, bindsCount = statement.getBindParameterCount() + 1; if (mapArgs != null && mapArgs.size() > 0) { String parameterName; int parameterIndex; for (String key : mapArgs.keySet()) { parameterName = ":" + key; if ((parameterIndex = statement.getParameterIndex(parameterName)) > 0) { statement.bindObject(parameterIndex, mapArgs.get(key)); index++; } } } else if (listArgs != null && listArgs.size() > 0) { for (Object object : listArgs) { statement.bindObject(index++, object); } } if (index != bindsCount) { rc = statement.close(); if (rc != SQLITE_OK) { throw new SQLiteException(rc, lastErrorMessage(mDB)); } throw new SQLiteException(SQLITE_MISUSE, "The bind count is not correct for the number of variables", query); } return statement; } //endregion //region Getters and Setters public DatabaseListener getDatabaseListener() { return mDatabaseListener; } public void setDatabaseListener(DatabaseListener databaseListener) { mDatabaseListener = databaseListener; } //endregion public interface DatabaseListener { public void onExecuteQuery(String query); } }
package com.insys.trapps.model; import java.util.Date; import java.util.List; public class Client { private long id; private String name; private String description; private List<String> locations; private List<Date> dates; public Client(String name) { this.name = name; } public Client(long id, String name, String description, List<String> locations, List<Date> dates) { this.id = id; this.name = name; this.description = description; this.locations = locations; this.dates = dates; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<String> getLocations() { return locations; } public void setLocations(List<String> locations) { this.locations = locations; } public List<Date> getDates() { return dates; } public void setDates(List<Date> dates) { this.dates = dates; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Client [name=" + name + "]"; } }
package com.rultor.agents.req; import com.google.common.base.Joiner; import com.jcabi.aspects.Immutable; import com.jcabi.ssh.SSH; import com.jcabi.xml.XML; import com.rultor.spi.Profile; import java.io.IOException; import java.util.Collection; import java.util.LinkedList; import lombok.EqualsAndHashCode; import lombok.ToString; /** * Decrypt. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @since 1.37.4 */ @Immutable @ToString @EqualsAndHashCode(of = "profile") /** * Tests for {@link Decrypt}. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @since 1.37.4 */ final class Decrypt { /** * Profile. */ private final transient Profile profile; /** * Proxy usage command string. */ private final transient String proxy; /** * Ctor. * @param prof Profile * @param host Host * @param port Port */ Decrypt(final Profile prof, final String host, final int port) { this.profile = prof; if (host.isEmpty()) { this.proxy = ""; } else { this.proxy = String.format("http-proxy=%s:%d", host, port); } } /** * Ctor. * @param prof Profile */ Decrypt(final Profile prof) { this(prof, "", 0); } /** * Decrypt instructions. * @return Instructions * @throws IOException If fails */ public Iterable<String> commands() throws IOException { final Collection<XML> assets = this.profile.read().nodes("/p/entry[@key='decrypt']/entry"); final Collection<String> commands = new LinkedList<String>(); if (!assets.isEmpty()) { commands.add("gpgconf --reload gpg-agent"); commands.add( Joiner.on(' ').join( "gpg --keyserver hkp://pool.sks-keyservers.net", this.proxy, "--verbose --recv-keys 9AF0FA4C" ) ); commands.add("gpg --version"); } for (final XML asset : assets) { final String key = asset.xpath("@key").get(0); final String enc = String.format("%s.enc", key); commands.add( Joiner.on(' ').join( "gpg --verbose \"--keyring=$(pwd)/.gpg/pubring.gpg\"", "\"--secret-keyring=$(pwd)/.gpg/secring.gpg\"", String.format( "--decrypt %s > %s", SSH.escape(asset.xpath("./text()").get(0)), SSH.escape(enc) ) ) ); commands.add( String.format( Joiner.on(' ').join( "gpg --no-tty --batch --verbose --decrypt", "--passphrase %s %s > %s" ), SSH.escape( String.format("rultor-key:%s", this.profile.name()) ), SSH.escape(enc), SSH.escape(key) ) ); commands.add(String.format("rm -rf %s", SSH.escape(enc))); } commands.add("rm -rf .gpg"); return commands; } }
package com.sdklite.yahoo.yql; import java.io.Serializable; import java.util.List; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; /** * @author johnsonlee */ public interface Weather { public static class Forecast implements Serializable { private static final long serialVersionUID = 591051533092381223L; @SerializedName("channel") private Channel channel; public Channel getChannel() { return this.channel; } @Override public String toString() { return new Gson().toJson(this); } } public static class Channel implements Serializable { private static final long serialVersionUID = 2274631206833618460L; @SerializedName("units") private Units units; @SerializedName("title") private String title; @SerializedName("link") private String link; @SerializedName("language") private String language; @SerializedName("ttl") private long ttl; @SerializedName("location") private Location location; @SerializedName("wind") private Wind wind; @SerializedName("atmosphere") private Atmosphere atmosphere; @SerializedName("astronomy") private Astronomy astronomy; @SerializedName("item") private Conditions conditions; public Units getUnits() { return this.units; } public String getTitle() { return this.title; } public String getLink() { return this.link; } public String getLanguage() { return this.language; } public long getTtl() { return this.ttl; } public Location getLocation() { return this.location; } public Wind getWind() { return this.wind; } public Atmosphere getAtmosphere() { return this.atmosphere; } public Conditions getConditions() { return this.conditions; } public Astronomy getAstronomy() { return this.astronomy; } public void setAstronomy(Astronomy astronomy) { this.astronomy = astronomy; } @Override public String toString() { return new Gson().toJson(this); } } public static class Units implements Serializable { private static final long serialVersionUID = -7629289839813738138L; @SerializedName("distance") private String distance; @SerializedName("pressure") private String pressure; @SerializedName("speed") private String speed; @SerializedName("temperature") private String temperature; public String getDistance() { return this.distance; } public String getPressure() { return this.pressure; } public String getSpeed() { return this.speed; } public String getTemperature() { return this.temperature; } @Override public String toString() { return new Gson().toJson(this); } } public static class Location implements Serializable { private static final long serialVersionUID = 8964524120033451385L; @SerializedName("city") private String city; @SerializedName("country") private String country; @SerializedName("region") private String region; public String getCity() { return this.city; } public String getCountry() { return this.country; } public String getRegion() { return this.region; } @Override public String toString() { return new Gson().toJson(this); } } public static class Wind implements Serializable { private static final long serialVersionUID = 7533096636836257525L; @SerializedName("chill") private double chill; @SerializedName("direction") private double direction; @SerializedName("speed") private double speed; public double getChill() { return this.chill; } public double getDirection() { return this.direction; } public double getSpeed() { return this.speed; } @Override public String toString() { return new Gson().toJson(this); } } public static class Atmosphere implements Serializable { private static final long serialVersionUID = 5454279924569498048L; @SerializedName("humidity") private double humidity; @SerializedName("pressure") private double pressure; @SerializedName("rising") private double rising; @SerializedName("visibility") private double visibility; public double getHumidity() { return this.humidity; } public double getPressure() { return this.pressure; } public double getRising() { return this.rising; } public double getVisibility() { return this.visibility; } @Override public String toString() { return new Gson().toJson(this); } } public static class Astronomy implements Serializable { private static final long serialVersionUID = -4907053599305938039L; @SerializedName("sunrise") private String sunrise; @SerializedName("sunset") private String sunset; public String getSunrise() { return this.sunrise; } public String getSunset() { return this.sunset; } @Override public String toString() { return new Gson().toJson(this); } } public static class Conditions implements Serializable { private static final long serialVersionUID = 635105378389972971L; @SerializedName("title") private String title; @SerializedName("lat") private double latitude; @SerializedName("long") private double longitude; @SerializedName("condition") private Condition condition; @SerializedName("forecast") private List<Condition> forecasts; @SerializedName("description") private String description; public String getTitle() { return this.title; } public double getLatitude() { return this.latitude; } public double getLongitude() { return this.longitude; } public Condition getCondition() { return this.condition; } public List<Condition> getForecasts() { return this.forecasts; } @Override public String toString() { return new Gson().toJson(this); } } public static class Condition implements Serializable { private static final long serialVersionUID = 5883921573153814111L; @SerializedName("code") private int code; @SerializedName("date") private String date; /** * Day of week */ @SerializedName("day") private String day; @SerializedName("temp") private double temperature; @SerializedName("low") private double low; @SerializedName("high") private double high; @SerializedName("text") private String text; public int getCode() { return this.code; } public String getDate() { return this.date; } public double getTemperature() { return this.temperature; } public String getText() { return this.text; } public String getDay() { return this.day; } public double getLow() { return this.low; } public double getHigh() { return this.high; } @Override public String toString() { return new Gson().toJson(this); } } }
package com.timepath.io.struct; import com.timepath.io.OrderedInputStream; import com.timepath.io.OrderedOutputStream; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; public class Struct { private static final Logger LOG = Logger.getLogger(Struct.class.getName()); private Struct() { } @Deprecated public static int sizeof(@NotNull Class<?> clazz) throws IllegalArgumentException, IllegalAccessException, InstantiationException { return sizeof(clazz.newInstance()); } public static int sizeof(@NotNull Object instance) throws IllegalAccessException, InstantiationException { int size = 0; for (@NotNull Field field : instance.getClass().getDeclaredFields()) { boolean accessible = field.isAccessible(); field.setAccessible(true); StructField meta = field.getAnnotation(StructField.class); if (meta != null) { size += sizeof(field.getType(), meta, field.get(instance)); } field.setAccessible(accessible); } return size; } @Nullable public static byte[] pack(@NotNull Object instance) { @NotNull ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { pack(instance, new OrderedOutputStream(baos)); return baos.toByteArray(); } catch (@NotNull IOException | InstantiationException | IllegalAccessException | IllegalArgumentException ex) { LOG.log(Level.SEVERE, null, ex); } return null; } public static void pack(@NotNull Object instance, @NotNull OrderedOutputStream os) throws IllegalAccessException, IOException, InstantiationException { for (@NotNull Field field : getFields(instance.getClass())) { boolean accessible = field.isAccessible(); field.setAccessible(true); writeField(instance, field, os); field.setAccessible(accessible); } } private static void writeField(Object instance, @NotNull Field field, @NotNull OrderedOutputStream os) throws IOException, IllegalAccessException, InstantiationException { Object ref = field.get(instance); StructField meta = field.getAnnotation(StructField.class); os.write(new byte[meta.skip()]); Primitive primitive = Primitive.get(field.getType()); if (primitive != null) { // Field is a primitive type primitive.write(ref, os, meta.limit()); } else if (field.getType().isArray()) { // Field is an array if (ref == null) { // Check if instantiated if (meta.nullable()) return; throw new InstantiationException("Cannnot instantiate array of unknown length"); } writeArray(instance, field, os, 0); } else { // Field is a regular Object if (ref == null) { // Skip over LOG.log(Level.FINE, "Instantiating {0}", field); os.write(new byte[sizeof(instantiate(field.getType()))]); } else { pack(ref, os); } } } private static void writeArray(Object instance, @NotNull Field field, @NotNull OrderedOutputStream os, int depth) throws IOException, InstantiationException, IllegalAccessException { StructField meta = field.getAnnotation(StructField.class); int dimensions = getArrayDepth(field.getType()); Class<?> elemType = getArrayType(field.getType()); Primitive primitive = Primitive.get(elemType); Object ref = field.get(instance); for (int i = 0; i < Array.getLength(ref); i++) { Object elem = Array.get(ref, i); if (depth == dimensions) { // Not a nested array if (primitive != null) { // Element is a primitive type primitive.write(elem, os, meta.limit()); } else { if (elem == null) { // Instantiate if needed throw new UnsupportedOperationException("Null objects not yet supported"); } pack(elem, os); } Array.set(ref, i, elem); } else { writeArray(elem, field, os, depth + 1); } } } public static void unpack(@NotNull Object out, @NotNull byte... b) { try { unpack(out, new OrderedInputStream(new ByteArrayInputStream(b))); } catch (@NotNull IOException | InstantiationException | IllegalAccessException | IllegalArgumentException ex) { LOG.log(Level.SEVERE, null, ex); } } public static void unpack(@NotNull Object instance, @NotNull OrderedInputStream is) throws IOException, IllegalAccessException, InstantiationException { for (@NotNull Field field : getFields(instance.getClass())) { boolean accessible = field.isAccessible(); field.setAccessible(true); @Nullable Object var = readField(instance, field, is); field.set(instance, var); field.setAccessible(accessible); } } @NotNull private static Object instantiate(@NotNull Class<?> type) throws InstantiationException { @NotNull List<Throwable> exStack = new LinkedList<>(); try { return type.newInstance(); } catch (Throwable t) { exStack.add(0, t); } try { Constructor<?> ctor = type.getDeclaredConstructors()[0]; boolean accessible = ctor.isAccessible(); ctor.setAccessible(true); @NotNull Object instance = ctor.newInstance(); ctor.setAccessible(accessible); return instance; } catch (Throwable t) { exStack.add(0, t); } throw new InstantiationException(exStack.toString()); } private static int getArrayDepth(@NotNull Class<?> clazz) { return clazz.getName().lastIndexOf('['); } private static Class<?> getArrayType(@NotNull Class<?> clazz) { Class<?> elemType = clazz; for (int i = 0; i < (getArrayDepth(clazz) + 1); i++) { elemType = elemType.getComponentType(); } return elemType; } private static void readArray(@NotNull Object ref, @NotNull Field field, @NotNull OrderedInputStream is, int depth) throws IOException, InstantiationException, IllegalAccessException { StructField meta = field.getAnnotation(StructField.class); int dimensions = getArrayDepth(field.getType()); Class<?> elemType = getArrayType(field.getType()); Primitive primitive = Primitive.get(elemType); for (int i = 0; i < Array.getLength(ref); i++) { @Nullable Object elem = Array.get(ref, i); if (depth == dimensions) { // Not a nested array if (primitive != null) { // Element is a primitive type elem = primitive.read(is, meta.limit()); } else { if (elem == null) { // Instantiate if needed LOG.log(Level.FINE, "Instantiating {0}", field); elem = instantiate(elemType); } unpack(elem, is); } Array.set(ref, i, elem); } else { readArray(elem, field, is, depth + 1); } } } @Nullable private static Object readField(Object instance, @NotNull Field field, @NotNull OrderedInputStream is) throws IOException, IllegalArgumentException, IllegalAccessException, InstantiationException { StructField meta = field.getAnnotation(StructField.class); is.skipBytes(meta.skip()); Object ref; Primitive primitive = Primitive.get(field.getType()); if (primitive != null) { // Field is a primitive type return primitive.read(is, meta.limit()); } else if (field.getType().isArray()) { // Field is an array ref = field.get(instance); if (ref == null) { // Check if instantiated throw new InstantiationException("Cannnot instantiate array of unknown length"); } readArray(ref, field, is, 0); } else { // Field is a regular Object ref = field.get(instance); if (ref == null) { // Instantiate if needed LOG.log(Level.FINE, "Instantiating {0}", field); ref = instantiate(field.getType()); } unpack(ref, is); field.set(instance, ref); } return ref; } private static int sizeof(@NotNull Class<?> type, @NotNull StructField meta, @Nullable Object ref) throws IllegalArgumentException, IllegalAccessException, InstantiationException { int size = 0; Primitive primitive = Primitive.get(type); if (primitive != null) { // Field is primitive int sz = primitive.size; if (sz < 0) { if (meta.limit() <= 0) { // Dynamic length String return Integer.MIN_VALUE; } sz = meta.limit(); // Limit string } size += ((meta.limit() > 0) ? Math.min(sz, meta.limit()) : sz) + meta.skip(); } else if (type.isArray()) { // Field is an array if (ref == null) { // Check if instantiated throw new InstantiationException("Cannnot instantiate array of unknown length"); } for (int i = 0; i < Array.getLength(ref); i++) { size += sizeof(type.getComponentType(), meta, Array.get(ref, i)); } } else { // Field is a regular Object if (ref == null) { // Instantiate if needed LOG.log(Level.FINE, "Instantiating {0}", type); ref = type.newInstance(); } int sz = sizeof(ref); size += ((meta.limit() > 0) ? Math.min(sz, meta.limit()) : sz) + meta.skip(); } return size; } @NotNull private static List<Field> getFields(@NotNull Class<?> clazz) { @NotNull Field[] fields = clazz.getDeclaredFields(); // Filter @NotNull List<Field> al = new LinkedList<>(); for (@NotNull Field ref : fields) { StructField field = ref.getAnnotation(StructField.class); if (field != null) { al.add(ref); } } // Sort Collections.sort(al, new Comparator<Field>() { @Override public int compare(@NotNull Field o1, @NotNull Field o2) { return o1.getAnnotation(StructField.class).index() - o2.getAnnotation(StructField.class).index(); } }); return al; } private enum Primitive { BYTE("byte", 1), BOOLEAN("boolean", 1), SHORT("short", 2), CHAR("char", 2), INT("int", 4), FLOAT("float", 4), LONG("long", 8), DOUBLE("double", 8), STRING(String.class, -1); @NotNull private static final Map<String, Primitive> primitiveTypes; static { Primitive[] values = values(); primitiveTypes = new HashMap<>(values.length); for (@NotNull Primitive p : values) primitiveTypes.put(p.type, p); } String type; int size; Primitive(String type, int size) { this.type = type; this.size = size; } Primitive(@NotNull Class<?> type, int size) { this.type = type.getName(); this.size = size; } public static Primitive get(@NotNull final Class<?> type) { return primitiveTypes.get(type.getName()); } /** * Read a primitive * * @param is * @param limit Maximum amount of bytes to read * @return The primitive * @throws IOException */ @Nullable Object read(@NotNull OrderedInputStream is, int limit) throws IOException { switch (this) { case BOOLEAN: return is.readBoolean(); case BYTE: return is.readByte(); case CHAR: return is.readChar(); case SHORT: return is.readShort(); case INT: return is.readInt(); case LONG: return is.readLong(); case FLOAT: return is.readFloat(); case DOUBLE: return is.readDouble(); case STRING: if (limit > 0) { // Fixed size @NotNull byte[] b = new byte[limit]; is.readFully(b); return new String(b, StandardCharsets.UTF_8); } return is.readString(limit); // NUL terminated default: return null; } } public void write(Object o, @NotNull OrderedOutputStream os, int limit) throws IOException { switch (this) { case BOOLEAN: os.writeBoolean((boolean) o); break; case BYTE: os.writeByte((byte) o); break; case CHAR: os.writeChar((char) o); break; case SHORT: os.writeShort((short) o); break; case INT: os.writeInt((int) o); break; case LONG: os.writeLong((long) o); break; case FLOAT: os.writeFloat((float) o); break; case DOUBLE: os.writeDouble((double) o); break; case STRING: @NotNull String s = (String) o; @NotNull byte[] b = s.getBytes(StandardCharsets.UTF_8); if (limit > 0) { // Fixed size int min = Math.min(limit, b.length); os.write(b, 0, min); if (min == b.length) os.write(new byte[limit - b.length]); // Padding } else { os.write(b, 0, b.length); os.write(0); // NUL } break; } } } }
package com.untamedears.humbug; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger; import net.minecraft.server.v1_8_R3.EntityEnderPearl; import net.minecraft.server.v1_8_R3.EntityTypes; import net.minecraft.server.v1_8_R3.Item; import net.minecraft.server.v1_8_R3.ItemEnderPearl; import net.minecraft.server.v1_8_R3.MinecraftKey; import net.minecraft.server.v1_8_R3.RegistryID; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.block.Biome; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.block.ContainerBlock; import org.bukkit.block.Sign; import org.bukkit.block.Hopper; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Arrow; import org.bukkit.entity.Boat; import org.bukkit.entity.Damageable; import org.bukkit.entity.Enderman; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Horse; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Minecart; import org.bukkit.entity.Player; import org.bukkit.entity.Skeleton; import org.bukkit.entity.Skeleton.SkeletonType; import org.bukkit.entity.Vehicle; import org.bukkit.entity.minecart.HopperMinecart; import org.bukkit.entity.minecart.StorageMinecart; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockFromToEvent; import org.bukkit.event.block.BlockPhysicsEvent; import org.bukkit.event.block.BlockPistonExtendEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.BlockSpreadEvent; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.enchantment.EnchantItemEvent; import org.bukkit.event.enchantment.PrepareItemEnchantEvent; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityCreatePortalEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityInteractEvent; import org.bukkit.event.entity.EntityPortalEvent; import org.bukkit.event.entity.EntityShootBowEvent; import org.bukkit.event.entity.ExpBottleEvent; import org.bukkit.event.entity.FoodLevelChangeEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.entity.PotionSplashEvent; import org.bukkit.event.entity.SheepDyeWoolEvent; import org.bukkit.event.inventory.InventoryMoveItemEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.player.PlayerBedEnterEvent; import org.bukkit.event.player.PlayerBucketEmptyEvent; import org.bukkit.event.player.PlayerExpChangeEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerItemConsumeEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.event.vehicle.VehicleDestroyEvent; import org.bukkit.event.vehicle.VehicleEnterEvent; import org.bukkit.event.vehicle.VehicleExitEvent; import org.bukkit.event.vehicle.VehicleMoveEvent; import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.event.world.ChunkUnloadEvent; import org.bukkit.event.world.PortalCreateEvent; import org.bukkit.event.world.StructureGrowEvent; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.Recipe; import org.bukkit.inventory.FurnaceRecipe; import org.bukkit.inventory.ShapedRecipe; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitTask; import org.bukkit.util.Vector; import com.untamedears.humbug.annotations.BahHumbug; import com.untamedears.humbug.annotations.BahHumbugs; import com.untamedears.humbug.annotations.ConfigOption; import com.untamedears.humbug.annotations.OptType; public class Humbug extends JavaPlugin implements Listener { public static void severe(String message) { log_.severe("[Humbug] " + message); } public static void warning(String message) { log_.warning("[Humbug] " + message); } public static void info(String message) { log_.info("[Humbug] " + message); } public static void debug(String message) { if (config_.getDebug()) { log_.info("[Humbug] " + message); } } public static Humbug getPlugin() { return global_instance_; } private static final Logger log_ = Logger.getLogger("Humbug"); private static Humbug global_instance_ = null; private static Config config_ = null; private static int max_golden_apple_stack_ = 1; static { max_golden_apple_stack_ = Material.GOLDEN_APPLE.getMaxStackSize(); if (max_golden_apple_stack_ > 64) { max_golden_apple_stack_ = 64; } } private Random prng_ = new Random(); private CombatInterface combatTag_; public Humbug() {} // Reduce registered PlayerInteractEvent count. onPlayerInteractAll handles // cancelled events. @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onPlayerInteract(PlayerInteractEvent event) { onAnvilOrEnderChestUse(event); if (!event.isCancelled()) { onCauldronInteract(event); } if (!event.isCancelled()) { onRecordInJukebox(event); } if (!event.isCancelled()) { onEnchantingTableUse(event); } if (!event.isCancelled()) { onChangingSpawners(event); } } @EventHandler(priority = EventPriority.LOWEST) // ignoreCancelled=false public void onPlayerInteractAll(PlayerInteractEvent event) { onPlayerEatGoldenApple(event); throttlePearlTeleport(event); onEquippingBanners(event); } // Stops people from dying sheep @BahHumbug(opt="allow_dye_sheep", def="true") @EventHandler public void onDyeWool(SheepDyeWoolEvent event) { if (!config_.get("allow_dye_sheep").getBool()) { event.setCancelled(true); } } // Configurable bow buff @EventHandler public void onEntityShootBowEventAlreadyIntializedSoIMadeThisUniqueName(EntityShootBowEvent event) { Integer power = event.getBow().getEnchantmentLevel(Enchantment.ARROW_DAMAGE); MetadataValue metadata = new FixedMetadataValue(this, power); event.getProjectile().setMetadata("power", metadata); } @BahHumbug(opt="bow_buff", type=OptType.Double, def="1.000000") @EventHandler public void onArrowHitEntity(EntityDamageByEntityEvent event) { Double multiplier = config_.get("bow_buff").getDouble(); if(multiplier <= 1.000001 && multiplier >= 0.999999) { return; } if (event.getEntity() instanceof LivingEntity) { Entity damager = event.getDamager(); if (damager instanceof Arrow) { Arrow arrow = (Arrow) event.getDamager(); Double damage = event.getDamage() * config_.get("bow_buff").getDouble(); Integer power = 0; if(arrow.hasMetadata("power")) { power = arrow.getMetadata("power").get(0).asInt(); } damage *= Math.pow(1.25, power - 5); // f(x) = 1.25^(x - 5) event.setDamage(damage); } } } // Fixes Teleporting through walls and doors // ** and ** // Ender Pearl Teleportation disabling // ** and ** // Ender pearl cooldown timer private class PearlTeleportInfo { public long last_teleport; public long last_notification; } private Map<String, PearlTeleportInfo> pearl_teleport_info_ = new TreeMap<String, PearlTeleportInfo>(); private final static int PEARL_THROTTLE_WINDOW = 10000; // 10 sec private final static int PEARL_NOTIFICATION_WINDOW = 1000; // 1 sec // EventHandler registered in onPlayerInteractAll @BahHumbug(opt="ender_pearl_teleportation_throttled", def="true") public void throttlePearlTeleport(PlayerInteractEvent event) { if (!config_.get("ender_pearl_teleportation_throttled").getBool()) { return; } if (event.getItem() == null || !event.getItem().getType().equals(Material.ENDER_PEARL)) { return; } final Action action = event.getAction(); if (action != Action.RIGHT_CLICK_AIR && action != Action.RIGHT_CLICK_BLOCK) { return; } final Block clickedBlock = event.getClickedBlock(); BlockState clickedState = null; Material clickedMaterial = null; if (clickedBlock != null) { clickedState = clickedBlock.getState(); clickedMaterial = clickedState.getType(); } if (clickedState != null && ( clickedState instanceof InventoryHolder || clickedMaterial.equals(Material.ANVIL) || clickedMaterial.equals(Material.ENCHANTMENT_TABLE) || clickedMaterial.equals(Material.ENDER_CHEST) || clickedMaterial.equals(Material.WORKBENCH))) { // Prevent Combat Tag/Pearl cooldown on inventory access return; } final long current_time = System.currentTimeMillis(); final Player player = event.getPlayer(); final String player_name = player.getName(); PearlTeleportInfo teleport_info = pearl_teleport_info_.get(player_name); long time_diff = 0; if (teleport_info == null) { // New pearl thrown outside of throttle window teleport_info = new PearlTeleportInfo(); teleport_info.last_teleport = current_time; teleport_info.last_notification = current_time - (PEARL_NOTIFICATION_WINDOW + 100); // Force notify combatTag_.tagPlayer(player); } else { time_diff = current_time - teleport_info.last_teleport; if (PEARL_THROTTLE_WINDOW > time_diff) { // Pearl throw throttled event.setCancelled(true); } else { // New pearl thrown outside of throttle window combatTag_.tagPlayer(player); teleport_info.last_teleport = current_time; teleport_info.last_notification = current_time - (PEARL_NOTIFICATION_WINDOW + 100); // Force notify time_diff = 0; } } final long notify_diff = current_time - teleport_info.last_notification; if (notify_diff > PEARL_NOTIFICATION_WINDOW) { teleport_info.last_notification = current_time; Integer tagCooldown = combatTag_.remainingSeconds(player); if (tagCooldown != null) { player.sendMessage(String.format( "Pearl in %d seconds. Combat Tag in %d seconds.", (PEARL_THROTTLE_WINDOW - time_diff + 500) / 1000, tagCooldown)); } else { player.sendMessage(String.format( "Pearl Teleport Cooldown: %d seconds", (PEARL_THROTTLE_WINDOW - time_diff + 500) / 1000)); } } pearl_teleport_info_.put(player_name, teleport_info); return; } @BahHumbugs({ @BahHumbug(opt="ender_pearl_teleportation", def="true"), @BahHumbug(opt="fix_teleport_glitch", def="true") }) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onTeleport(PlayerTeleportEvent event) { TeleportCause cause = event.getCause(); if (cause != TeleportCause.ENDER_PEARL) { return; } else if (!config_.get("ender_pearl_teleportation").getBool()) { event.setCancelled(true); return; } if (!config_.get("fix_teleport_glitch").getBool()) { return; } Location to = event.getTo(); World world = to.getWorld(); // From and To are feet positions. Check and make sure we can teleport to a location with air // above the To location. Block toBlock = world.getBlockAt(to); Block aboveBlock = world.getBlockAt(to.getBlockX(), to.getBlockY()+1, to.getBlockZ()); Block belowBlock = world.getBlockAt(to.getBlockX(), to.getBlockY()-1, to.getBlockZ()); boolean lowerBlockBypass = false; double height = 0.0; switch( toBlock.getType() ) { case CHEST: // Probably never will get hit directly case ENDER_CHEST: // Probably never will get hit directly height = 0.875; break; case STEP: lowerBlockBypass = true; height = 0.5; break; case WATER_LILY: height = 0.016; break; case ENCHANTMENT_TABLE: lowerBlockBypass = true; height = 0.75; break; case BED: case BED_BLOCK: // This one is tricky, since even with a height offset of 2.5, it still glitches. //lowerBlockBypass = true; //height = 0.563; // Disabling teleporting on top of beds for now by leaving lowerBlockBypass false. break; case FLOWER_POT: case FLOWER_POT_ITEM: height = 0.375; break; case SKULL: // Probably never will get hit directly height = 0.5; break; default: break; } // Check if the below block is difficult // This is added because if you face downward directly on a gate, it will // teleport your feet INTO the gate, thus bypassing the gate until you leave that block. switch( belowBlock.getType() ) { case FENCE: case FENCE_GATE: case NETHER_FENCE: case COBBLE_WALL: height = 0.5; break; default: break; } boolean upperBlockBypass = false; if( height >= 0.5 ) { Block aboveHeadBlock = world.getBlockAt(aboveBlock.getX(), aboveBlock.getY()+1, aboveBlock.getZ()); if( false == aboveHeadBlock.getType().isSolid() ) { height = 0.5; } else { upperBlockBypass = true; // Cancel this event. What's happening is the user is going to get stuck due to the height. } } // Normalize teleport to the center of the block. Feet ON the ground, plz. // Leave Yaw and Pitch alone to.setX(Math.floor(to.getX()) + 0.5000); to.setY(Math.floor(to.getY()) + height); to.setZ(Math.floor(to.getZ()) + 0.5000); if(aboveBlock.getType().isSolid() || (toBlock.getType().isSolid() && !lowerBlockBypass) || upperBlockBypass ) { // One last check because I care about Top Nether. (someone build me a shrine up there) boolean bypass = false; if ((world.getEnvironment() == Environment.NETHER) && (to.getBlockY() > 124) && (to.getBlockY() < 129)) { bypass = true; } if (!bypass) { event.setCancelled(true); } } } // Villager Trading @BahHumbug(opt="villager_trades") @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onPlayerInteractEntity(PlayerInteractEntityEvent event) { if (config_.get("villager_trades").getBool()) { return; } Entity npc = event.getRightClicked(); if (npc == null) { return; } if (npc.getType() == EntityType.VILLAGER) { event.setCancelled(true); } } // Anvil and Ender Chest usage // EventHandler registered in onPlayerInteract @BahHumbugs({ @BahHumbug(opt="anvil"), @BahHumbug(opt="ender_chest") }) public void onAnvilOrEnderChestUse(PlayerInteractEvent event) { if (config_.get("anvil").getBool() && config_.get("ender_chest").getBool()) { return; } Action action = event.getAction(); Material material = event.getClickedBlock().getType(); boolean anvil = !config_.get("anvil").getBool() && action == Action.RIGHT_CLICK_BLOCK && material.equals(Material.ANVIL); boolean ender_chest = !config_.get("ender_chest").getBool() && action == Action.RIGHT_CLICK_BLOCK && material.equals(Material.ENDER_CHEST); if (anvil || ender_chest) { event.setCancelled(true); } } @BahHumbug(opt="enchanting_table", def = "false") public void onEnchantingTableUse(PlayerInteractEvent event) { if(!config_.get("enchanting_table").getBool()) { return; } Action action = event.getAction(); Material material = event.getClickedBlock().getType(); boolean enchanting_table = action == Action.RIGHT_CLICK_BLOCK && material.equals(Material.ENCHANTMENT_TABLE); if(enchanting_table) { event.setCancelled(true); } } @BahHumbug(opt="ender_chests_placeable", def="true") @EventHandler(ignoreCancelled=true) public void onEnderChestPlace(BlockPlaceEvent e) { Material material = e.getBlock().getType(); if (!config_.get("ender_chests_placeable").getBool() && material == Material.ENDER_CHEST) { e.setCancelled(true); } } public void EmptyEnderChest(HumanEntity human) { if (config_.get("ender_backpacks").getBool()) { dropInventory(human.getLocation(), human.getEnderChest()); } } public void dropInventory(Location loc, Inventory inv) { final World world = loc.getWorld(); final int end = inv.getSize(); for (int i = 0; i < end; ++i) { try { final ItemStack item = inv.getItem(i); if (item != null) { world.dropItemNaturally(loc, item); inv.clear(i); } } catch (Exception ex) {} } } // Unlimited Cauldron water // EventHandler registered in onPlayerInteract @BahHumbug(opt="unlimitedcauldron") public void onCauldronInteract(PlayerInteractEvent e) { if (!config_.get("unlimitedcauldron").getBool()) { return; } // block water going down on cauldrons if(e.getClickedBlock().getType() == Material.CAULDRON && e.getMaterial() == Material.GLASS_BOTTLE && e.getAction() == Action.RIGHT_CLICK_BLOCK) { Block block = e.getClickedBlock(); if(block.getData() > 0) { block.setData((byte)(block.getData()+1)); } } } // Quartz from Gravel @BahHumbug(opt="quartz_gravel_percentage", type=OptType.Int) @EventHandler(ignoreCancelled=true, priority = EventPriority.HIGHEST) public void onGravelBreak(BlockBreakEvent e) { if(e.getBlock().getType() != Material.GRAVEL || config_.get("quartz_gravel_percentage").getInt() <= 0) { return; } if(prng_.nextInt(100) < config_.get("quartz_gravel_percentage").getInt()) { e.setCancelled(true); e.getBlock().setType(Material.AIR); e.getBlock().getWorld().dropItemNaturally(e.getBlock().getLocation(), new ItemStack(Material.QUARTZ, 1)); } } // Portals @BahHumbug(opt="portalcreate", def="true") @EventHandler(ignoreCancelled=true) public void onPortalCreate(PortalCreateEvent e) { if (!config_.get("portalcreate").getBool()) { e.setCancelled(true); } } @EventHandler(ignoreCancelled=true) public void onEntityPortalCreate(EntityCreatePortalEvent e) { if (!config_.get("portalcreate").getBool()) { e.setCancelled(true); } } // EnderDragon @BahHumbug(opt="enderdragon", def="true") @EventHandler(ignoreCancelled=true) public void onDragonSpawn(CreatureSpawnEvent e) { if (e.getEntityType() == EntityType.ENDER_DRAGON && !config_.get("enderdragon").getBool()) { e.setCancelled(true); } } // Join/Quit/Kick messages @BahHumbug(opt="joinquitkick", def="true") @EventHandler(priority=EventPriority.HIGHEST) public void onJoin(PlayerJoinEvent e) { if (!config_.get("joinquitkick").getBool()) { e.setJoinMessage(null); } } @EventHandler(priority=EventPriority.HIGHEST) public void onQuit(PlayerQuitEvent e) { EmptyEnderChest(e.getPlayer()); if (!config_.get("joinquitkick").getBool()) { e.setQuitMessage(null); } } @EventHandler(priority=EventPriority.HIGHEST) public void onKick(PlayerKickEvent e) { EmptyEnderChest(e.getPlayer()); if (!config_.get("joinquitkick").getBool()) { e.setLeaveMessage(null); } } // Death Messages @BahHumbugs({ @BahHumbug(opt="deathannounce", def="true"), @BahHumbug(opt="deathlog"), @BahHumbug(opt="deathpersonal"), @BahHumbug(opt="deathred"), @BahHumbug(opt="ender_backpacks") }) @EventHandler(priority=EventPriority.HIGHEST) public void onDeath(PlayerDeathEvent e) { final boolean logMsg = config_.get("deathlog").getBool(); final boolean sendPersonal = config_.get("deathpersonal").getBool(); final Player player = e.getEntity(); EmptyEnderChest(player); if (logMsg || sendPersonal) { Location location = player.getLocation(); String msg = String.format( "%s ([%s] %d, %d, %d)", e.getDeathMessage(), location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()); if (logMsg) { info(msg); } if (sendPersonal) { e.getEntity().sendMessage(ChatColor.RED + msg); } } if (!config_.get("deathannounce").getBool()) { e.setDeathMessage(null); } else if (config_.get("deathred").getBool()) { e.setDeathMessage(ChatColor.RED + e.getDeathMessage()); } } // Endermen Griefing @BahHumbug(opt="endergrief", def="true") @EventHandler(ignoreCancelled=true) public void onEndermanGrief(EntityChangeBlockEvent e) { if (!config_.get("endergrief").getBool() && e.getEntity() instanceof Enderman) { e.setCancelled(true); } } // Wither Insta-breaking and Explosions @BahHumbug(opt="wither_insta_break") @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onEntityChangeBlock(EntityChangeBlockEvent event) { if (config_.get("wither_insta_break").getBool()) { return; } Entity npc = event.getEntity(); if (npc == null) { return; } EntityType npc_type = npc.getType(); if (npc_type.equals(EntityType.WITHER)) { event.setCancelled(true); } } @BahHumbug(opt="wither_explosions") @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onEntityExplode(EntityExplodeEvent event) { if (config_.get("wither_explosions").getBool()) { return; } Entity npc = event.getEntity(); if (npc == null) { return; } EntityType npc_type = npc.getType(); if ((npc_type.equals(EntityType.WITHER) || npc_type.equals(EntityType.WITHER_SKULL))) { event.blockList().clear(); } } @BahHumbug(opt="wither", def="true") @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onWitherSpawn(CreatureSpawnEvent event) { if (config_.get("wither").getBool()) { return; } if (!event.getEntityType().equals(EntityType.WITHER)) { return; } event.setCancelled(true); } // Prevent specified items from dropping off mobs public void removeItemDrops(EntityDeathEvent event) { if (!config_.doRemoveItemDrops()) { return; } if (event.getEntity() instanceof Player) { return; } Set<Integer> remove_ids = config_.getRemoveItemDrops(); List<ItemStack> drops = event.getDrops(); ItemStack item; int i = drops.size() - 1; while (i >= 0) { item = drops.get(i); if (remove_ids.contains(item.getTypeId())) { drops.remove(i); } --i; } } // Spawn more Wither Skeletons and Ghasts @BahHumbugs ({ @BahHumbug(opt="extra_ghast_spawn_rate", type=OptType.Int), @BahHumbug(opt="extra_wither_skele_spawn_rate", type=OptType.Int), @BahHumbug(opt="portal_extra_ghast_spawn_rate", type=OptType.Int), @BahHumbug(opt="portal_extra_wither_skele_spawn_rate", type=OptType.Int), @BahHumbug(opt="portal_pig_spawn_multiplier", type=OptType.Int) }) @EventHandler(priority = EventPriority.LOW, ignoreCancelled=true) public void spawnMoreHellMonsters(CreatureSpawnEvent e) { final Location loc = e.getLocation(); final World world = loc.getWorld(); boolean portalSpawn = false; final int blockType = world.getBlockTypeIdAt(loc); if (blockType == 90 || blockType == 49) { // >= because we are preventing instead of spawning if(prng_.nextInt(1000000) >= config_.get("portal_pig_spawn_multiplier").getInt()) { e.setCancelled(true); return; } portalSpawn = true; } if (config_.get("extra_wither_skele_spawn_rate").getInt() <= 0 && config_.get("extra_ghast_spawn_rate").getInt() <= 0) { return; } if (e.getEntityType() == EntityType.PIG_ZOMBIE) { int adjustedwither; int adjustedghast; if (portalSpawn) { adjustedwither = config_.get("portal_extra_wither_skele_spawn_rate").getInt(); adjustedghast = config_.get("portal_extra_ghast_spawn_rate").getInt(); } else { adjustedwither = config_.get("extra_wither_skele_spawn_rate").getInt(); adjustedghast = config_.get("extra_ghast_spawn_rate").getInt(); } if(prng_.nextInt(1000000) < adjustedwither) { e.setCancelled(true); world.spawnEntity(loc, EntityType.SKELETON); } else if(prng_.nextInt(1000000) < adjustedghast) { e.setCancelled(true); int x = loc.getBlockX(); int z = loc.getBlockZ(); List<Integer> heights = new ArrayList<Integer>(16); int lastBlockHeight = 2; int emptyCount = 0; int maxHeight = world.getMaxHeight(); for (int y = 2; y < maxHeight; ++y) { Block block = world.getBlockAt(x, y, z); if (block.isEmpty()) { ++emptyCount; if (emptyCount == 11) { heights.add(lastBlockHeight + 2); } } else { lastBlockHeight = y; emptyCount = 0; } } if (heights.size() <= 0) { return; } loc.setY(heights.get(prng_.nextInt(heights.size()))); world.spawnEntity(loc, EntityType.GHAST); } } else if (e.getEntityType() == EntityType.SKELETON && e.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM) { Entity entity = e.getEntity(); if (entity instanceof Skeleton) { Skeleton skele = (Skeleton)entity; skele.setSkeletonType(SkeletonType.WITHER); EntityEquipment entity_equip = skele.getEquipment(); entity_equip.setItemInHand(new ItemStack(Material.STONE_SWORD)); entity_equip.setItemInHandDropChance(0.0F); } } } // Wither Skull drop rate public static final int skull_id_ = Material.SKULL_ITEM.getId(); public static final byte wither_skull_data_ = 1; @BahHumbug(opt="wither_skull_drop_rate", type=OptType.Int) public void adjustWitherSkulls(EntityDeathEvent event) { Entity entity = event.getEntity(); if (!(entity instanceof Skeleton)) { return; } int rate = config_.get("wither_skull_drop_rate").getInt(); if (rate < 0 || rate > 1000000) { return; } Skeleton skele = (Skeleton)entity; if (skele.getSkeletonType() != SkeletonType.WITHER) { return; } List<ItemStack> drops = event.getDrops(); ItemStack item; int i = drops.size() - 1; while (i >= 0) { item = drops.get(i); if (item.getTypeId() == skull_id_ && item.getData().getData() == wither_skull_data_) { drops.remove(i); } --i; } if (rate - prng_.nextInt(1000000) <= 0) { return; } item = new ItemStack(Material.SKULL_ITEM); item.setAmount(1); item.setDurability((short)wither_skull_data_); drops.add(item); } // Fix a few issues with pearls, specifically pearls in unloaded chunks and slime blocks. @BahHumbug(opt="remove_pearls_chunks", type=OptType.Bool, def = "true") @EventHandler() public void onChunkUnloadEvent(ChunkUnloadEvent event){ Entity[] entities = event.getChunk().getEntities(); for (Entity ent: entities) if (ent.getType() == EntityType.ENDER_PEARL) ent.remove(); } private void registerTimerForPearlCheck(){ Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){ @Override public void run() { for (Entity ent: pearlTime.keySet()){ if (pearlTime.get(ent).booleanValue()){ ent.remove(); } else pearlTime.put(ent, true); } } }, 100, 200); } private Map<Entity, Boolean> pearlTime = new HashMap<Entity, Boolean>(); public void onPearlLastingTooLong(EntityInteractEvent event){ if (event.getEntityType() != EntityType.ENDER_PEARL) return; Entity ent = event.getEntity(); pearlTime.put(ent, false); } // Generic mob drop rate adjustment @BahHumbug(opt="disable_xp_orbs", type=OptType.Bool, def = "true") public void adjustMobItemDrops(EntityDeathEvent event){ Entity mob = event.getEntity(); if (mob instanceof Player){ return; } // Try specific multiplier, if that doesn't exist use generic EntityType mob_type = mob.getType(); int multiplier = config_.getLootMultiplier(mob_type.toString()); if (multiplier < 0) { multiplier = config_.getLootMultiplier("generic"); } //set entity death xp to zero so they don't drop orbs if(config_.get("disable_xp_orbs").getBool()){ event.setDroppedExp(0); } //if a dropped item was in the mob's inventory, drop only one, otherwise drop the amount * the multiplier LivingEntity liveMob = (LivingEntity) mob; EntityEquipment mobEquipment = liveMob.getEquipment(); ItemStack[] eeItem = mobEquipment.getArmorContents(); for (ItemStack item : event.getDrops()) { boolean armor = false; boolean hand = false; for(ItemStack i : eeItem){ if(i.isSimilar(item)){ armor = true; item.setAmount(1); } } if(item.isSimilar(mobEquipment.getItemInHand())){ hand = true; item.setAmount(1); } if(!hand && !armor){ int amount = item.getAmount() * multiplier; item.setAmount(amount); } } } @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onEntityDeathEvent(EntityDeathEvent event) { removeItemDrops(event); adjustWitherSkulls(event); adjustMobItemDrops(event); } // Enchanted Golden Apple public boolean isEnchantedGoldenApple(ItemStack item) { // Golden Apples are GOLDEN_APPLE with 0 durability // Enchanted Golden Apples are GOLDEN_APPLE with 1 durability if (item == null) { return false; } if (item.getDurability() != 1) { return false; } Material material = item.getType(); return material.equals(Material.GOLDEN_APPLE); } public boolean isCrackedStoneBrick(ItemStack item) { // Cracked stone bricks are stone bricks with 2 durability if (item == null) { return false; } if (item.getDurability() != 2) { return false; } Material material = item.getType(); return material.equals(Material.SMOOTH_BRICK); } public void replaceEnchantedGoldenApple( String player_name, ItemStack item, int inventory_max_stack_size) { if (!isEnchantedGoldenApple(item)) { return; } int stack_size = max_golden_apple_stack_; if (inventory_max_stack_size < max_golden_apple_stack_) { stack_size = inventory_max_stack_size; } info(String.format( "Replaced %d Enchanted with %d Normal Golden Apples for %s", item.getAmount(), stack_size, player_name)); item.setDurability((short)0); item.setAmount(stack_size); } @BahHumbug(opt="ench_gold_app_craftable", def = "false") public void removeRecipies() { if (config_.get("ench_gold_app_craftable").getBool()&&config_.get("moss_stone_craftable").getBool()&&config_.get("cracked_stone_craftable").getBool()) { return; } Iterator<Recipe> it = getServer().recipeIterator(); while (it.hasNext()) { Recipe recipe = it.next(); ItemStack resulting_item = recipe.getResult(); if (!config_.get("ench_gold_app_craftable").getBool() && isEnchantedGoldenApple(resulting_item)) { it.remove(); info("Enchanted Golden Apple Recipe disabled"); } if (recipe instanceof FurnaceRecipe) { FurnaceRecipe fre = (FurnaceRecipe) recipe; if (isCrackedStone(fre.getResult())) { it.remove(); info("Cracked Stone Furnace Recipe disabled"); } } } } public boolean isCrackedStone(ItemStack item) { if (item == null) return false; if (item.getDurability() != 2){ return false; } Material material = item.getType(); return material.equals(Material.SMOOTH_BRICK); } // EventHandler registered in onPlayerInteractAll @BahHumbug(opt="ench_gold_app_edible") public void onPlayerEatGoldenApple(PlayerInteractEvent event) { // The event when eating is cancelled before even LOWEST fires when the // player clicks on AIR. if (config_.get("ench_gold_app_edible").getBool()) { return; } Player player = event.getPlayer(); Inventory inventory = player.getInventory(); ItemStack item = event.getItem(); replaceEnchantedGoldenApple( player.getName(), item, inventory.getMaxStackSize()); } // Fix entities going through portals // This needs to be removed when updated to citadel 3.0 @BahHumbug(opt="disable_entities_portal", type = OptType.Bool, def = "true") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void entityPortalEvent(EntityPortalEvent event){ event.setCancelled(config_.get("disable_entities_portal").getBool()); } // Enchanted Book public boolean isNormalBook(ItemStack item) { if (item == null) { return false; } Material material = item.getType(); return material.equals(Material.BOOK); } @BahHumbug(opt="ench_book_craftable") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void onPrepareItemEnchantEvent(PrepareItemEnchantEvent event) { if (config_.get("ench_book_craftable").getBool()) { return; } ItemStack item = event.getItem(); if (isNormalBook(item)) { event.setCancelled(true); } } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void onEnchantItemEvent(EnchantItemEvent event) { if (config_.get("ench_book_craftable").getBool()) { return; } ItemStack item = event.getItem(); if (isNormalBook(item)) { event.setCancelled(true); Player player = event.getEnchanter(); warning( "Prevented book enchant. This should not trigger. Watch player " + player.getName()); } } // Stop Cobble generation from lava+water private static final BlockFace[] faces_ = new BlockFace[] { BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST, BlockFace.UP, BlockFace.DOWN }; private BlockFace WaterAdjacentLava(Block lava_block) { for (BlockFace face : faces_) { Block block = lava_block.getRelative(face); Material material = block.getType(); if (material.equals(Material.WATER) || material.equals(Material.STATIONARY_WATER)) { return face; } } return BlockFace.SELF; } public void ConvertLava(final Block block) { int data = (int)block.getData(); if (data == 0) { return; } Material material = block.getType(); if (!material.equals(Material.LAVA) && !material.equals(Material.STATIONARY_LAVA)) { return; } if (isLavaSourceNear(block, 3)) { return; } BlockFace face = WaterAdjacentLava(block); if (face == BlockFace.SELF) { return; } Bukkit.getScheduler().runTask(this, new Runnable() { @Override public void run() { block.setType(Material.AIR); } }); } public boolean isLavaSourceNear(Block block, int ttl) { int data = (int)block.getData(); if (data == 0) { Material material = block.getType(); if (material.equals(Material.LAVA) || material.equals(Material.STATIONARY_LAVA)) { return true; } } if (ttl <= 0) { return false; } for (BlockFace face : faces_) { Block child = block.getRelative(face); if (isLavaSourceNear(child, ttl - 1)) { return true; } } return false; } public void LavaAreaCheck(Block block, int ttl) { ConvertLava(block); if (ttl <= 0) { return; } for (BlockFace face : faces_) { Block child = block.getRelative(face); LavaAreaCheck(child, ttl - 1); } } @BahHumbugs ({ @BahHumbug(opt="cobble_from_lava"), @BahHumbug(opt="cobble_from_lava_scan_radius", type=OptType.Int, def="0") }) @EventHandler(priority = EventPriority.LOWEST) public void onBlockPhysicsEvent(BlockPhysicsEvent event) { if (config_.get("cobble_from_lava").getBool()) { return; } Block block = event.getBlock(); Material material = block.getType(); if (!material.equals(Material.LAVA) && !material.equals(Material.STATIONARY_LAVA)) { return; } LavaAreaCheck(block, config_.get("cobble_from_lava_scan_radius").getInt()); } // Counteract 1.4.6 protection enchant nerf @BahHumbug(opt="scale_protection_enchant", def="true") @EventHandler(priority = EventPriority.LOWEST) // ignoreCancelled=false public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) { if (!config_.get("scale_protection_enchant").getBool()) { return; } double damage = event.getDamage(); if (damage <= 0.0000001D) { return; } DamageCause cause = event.getCause(); if (!cause.equals(DamageCause.ENTITY_ATTACK) && !cause.equals(DamageCause.PROJECTILE)) { return; } Entity entity = event.getEntity(); if (!(entity instanceof Player)) { return; } Player defender = (Player)entity; PlayerInventory inventory = defender.getInventory(); int enchant_level = 0; for (ItemStack armor : inventory.getArmorContents()) { enchant_level += armor.getEnchantmentLevel(Enchantment.PROTECTION_ENVIRONMENTAL); } int damage_adjustment = 0; if (enchant_level >= 3 && enchant_level <= 6) { // 0 to 2 damage_adjustment = prng_.nextInt(3); } else if (enchant_level >= 7 && enchant_level <= 10) { // 0 to 3 damage_adjustment = prng_.nextInt(4); } else if (enchant_level >= 11 && enchant_level <= 14) { // 1 to 4 damage_adjustment = prng_.nextInt(4) + 1; } else if (enchant_level >= 15) { // 2 to 4 damage_adjustment = prng_.nextInt(3) + 2; } damage = Math.max(damage - (double)damage_adjustment, 0.0D); event.setDamage(damage); } @BahHumbug(opt="player_max_health", type=OptType.Int, def="20") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void onPlayerJoinEvent(PlayerJoinEvent event) { Player player = event.getPlayer(); player.setMaxHealth((double)config_.get("player_max_health").getInt()); } // Fix dupe bug with chests and other containers @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void blockExplodeEvent(EntityExplodeEvent event) { List<HumanEntity> humans = new ArrayList<HumanEntity>(); for (Block block: event.blockList()) { if (block.getState() instanceof InventoryHolder) { InventoryHolder holder = (InventoryHolder) block.getState(); for (HumanEntity ent: holder.getInventory().getViewers()) { humans.add(ent); } } } for (HumanEntity human: humans) { human.closeInventory(); } } // Prevent entity dup bug @BahHumbug(opt="fix_rail_dup_bug", def="true") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void onPistonPushRail(BlockPistonExtendEvent e) { if (!config_.get("fix_rail_dup_bug").getBool()) { return; } for (Block b : e.getBlocks()) { Material t = b.getType(); if (t == Material.RAILS || t == Material.POWERED_RAIL || t == Material.DETECTOR_RAIL) { e.setCancelled(true); return; } } } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void onRailPlace(BlockPlaceEvent e) { if (!config_.get("fix_rail_dup_bug").getBool()) { return; } Block b = e.getBlock(); Material t = b.getType(); if (t == Material.RAILS || t == Material.POWERED_RAIL || t == Material.DETECTOR_RAIL) { for (BlockFace face : faces_) { t = b.getRelative(face).getType(); if (t == Material.PISTON_STICKY_BASE || t == Material.PISTON_EXTENSION || t == Material.PISTON_MOVING_PIECE || t == Material.PISTON_BASE) { e.setCancelled(true); return; } } } } // Combat Tag players on server join @BahHumbug(opt="tag_on_join", def="true") @EventHandler public void tagOnJoin(PlayerJoinEvent event){ if(!config_.get("tag_on_join").getBool()) { return; } // Delay two ticks to tag after secure login has been denied. // This opens a 1 tick window for a cheater to login and grab // server info, which should be detectable and bannable. final Player loginPlayer = event.getPlayer(); Bukkit.getScheduler().runTaskLater(this, new Runnable() { @Override public void run() { if (loginPlayer == null) return; combatTag_.tagPlayer(loginPlayer.getName()); loginPlayer.sendMessage("You have been Combat Tagged on Login"); } }, 2L); } // Give one-time starting kit @BahHumbug(opt="drop_newbie_kit", def="true") @EventHandler public void onGiveKitOnJoin(PlayerJoinEvent event) { if (!config_.get("drop_newbie_kit").getBool()) { return; } final Player player = event.getPlayer(); if (player.hasPlayedBefore()) return; } final String playerName = player.getUniqueId().toString(); giveN00bKit(player); } public void giveN00bKit(Player player) { Inventory inv = player.getInventory(); inv.addItem(createN00bKit()); } public ItemStack createN00bKit() { ItemStack book = new ItemStack(Material.WRITTEN_BOOK); return book; } // Give introduction book to n00bs private Set<String> playersWithN00bBooks_ = new TreeSet<String>(); @BahHumbug(opt="drop_newbie_book", def="true") @EventHandler(priority=EventPriority.HIGHEST) public void onPlayerDeathBookDrop(PlayerDeathEvent e) { if (!config_.get("drop_newbie_book").getBool()) { return; } final String playerName = e.getEntity().getName(); List<ItemStack> dropList = e.getDrops(); for (int i = 0; i < dropList.size(); ++i) { final ItemStack item = dropList.get(i); if (item.getType().equals(Material.WRITTEN_BOOK)) { final BookMeta bookMeta = (BookMeta)item.getItemMeta(); if (bookMeta.getTitle().equals(config_.getTitle()) && bookMeta.getAuthor().equals(config_.getAuthor())) { playersWithN00bBooks_.add(playerName); dropList.remove(i); return; } } } playersWithN00bBooks_.remove(playerName); } @EventHandler public void onGiveBookOnRespawn(PlayerRespawnEvent event) { if (!config_.get("drop_newbie_book").getBool()) { return; } final Player player = event.getPlayer(); final String playerName = player.getName(); if (!playersWithN00bBooks_.contains(playerName)) { return; } playersWithN00bBooks_.remove(playerName); giveN00bBook(player); } @EventHandler public void onGiveBookOnJoin(PlayerJoinEvent event) { if (!config_.get("drop_newbie_book").getBool()) { return; } final Player player = event.getPlayer(); final String playerName = player.getName(); if (player.hasPlayedBefore() && !playersWithN00bBooks_.contains(playerName)) { return; } playersWithN00bBooks_.remove(playerName); giveN00bBook(player); } public void giveN00bBook(Player player) { Inventory inv = player.getInventory(); inv.addItem(createN00bBook()); } public ItemStack createN00bBook() { ItemStack book = new ItemStack(Material.WRITTEN_BOOK); BookMeta sbook = (BookMeta)book.getItemMeta(); sbook.setTitle(config_.getTitle()); sbook.setAuthor(config_.getAuthor()); sbook.setPages(config_.getPages()); book.setItemMeta(sbook); return book; } public boolean checkForInventorySpace(Inventory inv, int emptySlots) { int foundEmpty = 0; final int end = inv.getSize(); for (int slot = 0; slot < end; ++slot) { ItemStack item = inv.getItem(slot); if (item == null) { ++foundEmpty; } else if (item.getType().equals(Material.AIR)) { ++foundEmpty; } } return foundEmpty >= emptySlots; } public void giveHolidayPackage(Player player) { int count = 0; Inventory inv = player.getInventory(); while (checkForInventorySpace(inv, 4)) { inv.addItem(createHolidayBook()); inv.addItem(createFruitcake()); inv.addItem(createTurkey()); inv.addItem(createCoal()); ++count; } info(String.format("%s generated %d packs of holiday cheer.", player.getName(), count)); } public ItemStack createHolidayBook() { ItemStack book = new ItemStack(Material.WRITTEN_BOOK); BookMeta sbook = (BookMeta)book.getItemMeta(); sbook.setTitle(config_.getHolidayTitle()); sbook.setAuthor(config_.getHolidayAuthor()); sbook.setPages(config_.getHolidayPages()); List<String> lore = new ArrayList<String>(1); lore.add("December 25th, 2013"); sbook.setLore(lore); book.setItemMeta(sbook); return book; } public ItemStack createFruitcake() { ItemStack cake = new ItemStack(Material.CAKE); ItemMeta meta = cake.getItemMeta(); meta.setDisplayName("Fruitcake"); List<String> lore = new ArrayList<String>(1); lore.add("Deliciously stale"); meta.setLore(lore); cake.setItemMeta(meta); return cake; } private String[] turkey_names_ = new String[] { "Turkey", "Turkey", "Turkey", "Turducken", "Tofurkey", "Cearc Frangach", "Dinde", "Kalkoen", "Indeyka", "Pollo d'India", "Pelehu", "Chilmyeonjo" }; public ItemStack createTurkey() { String turkey_name = turkey_names_[prng_.nextInt(turkey_names_.length)]; ItemStack turkey = new ItemStack(Material.COOKED_CHICKEN); ItemMeta meta = turkey.getItemMeta(); meta.setDisplayName(turkey_name); List<String> lore = new ArrayList<String>(1); lore.add("Tastes like chicken"); meta.setLore(lore); turkey.setItemMeta(meta); return turkey; } public ItemStack createCoal() { ItemStack coal = new ItemStack(Material.COAL); ItemMeta meta = coal.getItemMeta(); List<String> lore = new ArrayList<String>(1); lore.add("You've been naughty"); meta.setLore(lore); coal.setItemMeta(meta); return coal; } // Playing records in jukeboxen? Gone // EventHandler registered in onPlayerInteract @BahHumbug(opt="disallow_record_playing", def="true") public void onRecordInJukebox(PlayerInteractEvent event) { if (!config_.get("disallow_record_playing").getBool()) { return; } Block cb = event.getClickedBlock(); if (cb == null || cb.getType() != Material.JUKEBOX) { return; } ItemStack his = event.getItem(); if(his != null && his.getType().isRecord()) { event.setCancelled(true); } } // Water in the nether? Nope. @BahHumbugs ({ @BahHumbug(opt="allow_water_in_nether"), @BahHumbug(opt="indestructible_end_portals", def="true") }) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerBucketEmptyEvent(PlayerBucketEmptyEvent e) { if(!config_.get("allow_water_in_nether").getBool()) { if( ( e.getBlockClicked().getBiome() == Biome.HELL ) && ( e.getBucket() == Material.WATER_BUCKET ) ) { e.setCancelled(true); e.getItemStack().setType(Material.BUCKET); e.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.WATER_BREATHING, 5, 1)); } } if (config_.get("indestructible_end_portals").getBool()) { Block baseBlock = e.getBlockClicked(); BlockFace face = e.getBlockFace(); Block block = baseBlock.getRelative(face); if (block.getType() == Material.ENDER_PORTAL) { e.setCancelled(true); } } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockFromToEvent(BlockFromToEvent e) { if(!config_.get("allow_water_in_nether").getBool()) { if( e.getToBlock().getBiome() == Biome.HELL ) { if( ( e.getBlock().getType() == Material.WATER ) || ( e.getBlock().getType() == Material.STATIONARY_WATER ) ) { e.setCancelled(true); } } } if (config_.get("indestructible_end_portals").getBool()) { if (e.getToBlock().getType() == Material.ENDER_PORTAL) { e.setCancelled(true); } } if(!e.isCancelled() && config_.get("obsidian_generator").getBool()) { generateObsidian(e); } } // Generates obsidian like it did in 1.7. // Note that this does not change anything in versions where obsidian generation exists. @BahHumbug(opt="obsidian_generator", def="false") public void generateObsidian(BlockFromToEvent event) { if(!event.getBlock().getType().equals(Material.STATIONARY_LAVA)) { return; } if(!event.getToBlock().getType().equals(Material.TRIPWIRE)) { return; } Block string = event.getToBlock(); if(!(string.getRelative(BlockFace.NORTH).getType().equals(Material.STATIONARY_WATER) || string.getRelative(BlockFace.EAST).getType().equals(Material.STATIONARY_WATER) || string.getRelative(BlockFace.WEST).getType().equals(Material.STATIONARY_WATER) || string.getRelative(BlockFace.SOUTH).getType().equals(Material.STATIONARY_WATER))) { return; } string.setType(Material.OBSIDIAN); } // Stops perculators private Map<Chunk, Integer> waterChunks = new HashMap<Chunk, Integer>(); BukkitTask waterSchedule = null; @BahHumbugs ({ @BahHumbug(opt="max_water_lava_height", def="100", type=OptType.Int), @BahHumbug(opt="max_water_lava_amount", def = "400", type=OptType.Int), @BahHumbug(opt="max_water_lava_timer", def = "1200", type=OptType.Int) }) @EventHandler(priority = EventPriority.LOWEST) public void stopLiquidMoving(BlockFromToEvent event){ try { Block to = event.getToBlock(); Block from = event.getBlock(); if (to.getLocation().getBlockY() < config_.get("max_water_lava_height").getInt()) { return; } Material mat = from.getType(); if (!(mat.equals(Material.WATER) || mat.equals(Material.STATIONARY_WATER) || mat.equals(Material.LAVA) || mat.equals(Material.STATIONARY_LAVA))) { return; } Chunk c = to.getChunk(); if (!waterChunks.containsKey(c)){ waterChunks.put(c, 0); } Integer i = waterChunks.get(c); i = i + 1; waterChunks.put(c, i); int amount = getWaterInNearbyChunks(c); if (amount > config_.get("max_water_lava_amount").getInt()) { event.setCancelled(true); } if (waterSchedule != null) { return; } waterSchedule = Bukkit.getScheduler().runTaskLater(this, new Runnable(){ @Override public void run() { waterChunks.clear(); waterSchedule = null; } }, config_.get("max_water_lava_timer").getInt()); } catch (Exception e){ getLogger().log(Level.INFO, "Tried getting info from a chunk before it generated, skipping."); return; } } public int getWaterInNearbyChunks(Chunk chunk){ World world = chunk.getWorld(); Chunk[] chunks = { world.getChunkAt(chunk.getX(), chunk.getZ()), world.getChunkAt(chunk.getX()-1, chunk.getZ()), world.getChunkAt(chunk.getX(), chunk.getZ()-1), world.getChunkAt(chunk.getX()-1, chunk.getZ()-1), world.getChunkAt(chunk.getX()+1, chunk.getZ()), world.getChunkAt(chunk.getX(), chunk.getZ()+1), world.getChunkAt(chunk.getX()+1, chunk.getZ()+1), world.getChunkAt(chunk.getX()-1, chunk.getZ()+1), world.getChunkAt(chunk.getX()+1, chunk.getZ()-1) }; int count = 0; for (Chunk c: chunks){ Integer amount = waterChunks.get(c); if (amount == null) continue; count += amount; } return count; } // Changes Strength Potions, strength_multiplier 3 is roughly Pre-1.6 Level @BahHumbugs ({ @BahHumbug(opt="nerf_strength", def="true"), @BahHumbug(opt="strength_multiplier", type=OptType.Int, def="3") }) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPlayerDamage(EntityDamageByEntityEvent event) { if (!config_.get("nerf_strength").getBool()) { return; } if (!(event.getDamager() instanceof Player)) { return; } Player player = (Player)event.getDamager(); final int strengthMultiplier = config_.get("strength_multiplier").getInt(); if (player.hasPotionEffect(PotionEffectType.INCREASE_DAMAGE)) { for (PotionEffect effect : player.getActivePotionEffects()) { if (effect.getType().equals(PotionEffectType.INCREASE_DAMAGE)) { final int potionLevel = effect.getAmplifier() + 1; final double unbuffedDamage = event.getDamage() / (1.3 * potionLevel + 1); final double newDamage = unbuffedDamage + (potionLevel * strengthMultiplier); event.setDamage(newDamage); break; } } } } // Buffs health splash to pre-1.6 levels @BahHumbug(opt="buff_health_pots", def="true") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPotionSplash(PotionSplashEvent event) { if (!config_.get("buff_health_pots").getBool()) { return; } for (PotionEffect effect : event.getEntity().getEffects()) { if (!(effect.getType().getName().equalsIgnoreCase("heal"))) { // Splash potion of poison return; } } for (LivingEntity entity : event.getAffectedEntities()) { if (entity instanceof Player) { if(((Damageable)entity).getHealth() > 0d) { final double newHealth = Math.min( ((Damageable)entity).getHealth() + 4.0D, ((Damageable)entity).getMaxHealth()); entity.setHealth(newHealth); } } } } @BahHumbugs({ @BahHumbug(opt="disable_bed_nether_end", def="true") }) @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerEnterBed(BlockPlaceEvent event) { Block b = event.getBlock(); if (!(b.getType() == Material.BED || b.getType() == Material.BED_BLOCK)) return; Environment env = b.getLocation().getWorld().getEnvironment(); if (config_.get("disable_bed_nether_end").getBool() && (env == Environment.NETHER || env == Environment.THE_END)) event.setCancelled(true); } // Bow shots cause slow debuff @BahHumbugs ({ @BahHumbug(opt="projectile_slow_chance", type=OptType.Int, def="30"), @BahHumbug(opt="projectile_slow_ticks", type=OptType.Int, def="100") }) @EventHandler public void onEDBE(EntityDamageByEntityEvent event) { int rate = config_.get("projectile_slow_chance").getInt(); if (rate <= 0 || rate > 100) { return; } if (!(event.getEntity() instanceof Player)) { return; } boolean damager_is_player_arrow = false; int chance_scaling = 0; Entity damager_entity = event.getDamager(); if (damager_entity != null) { // public LivingEntity CraftArrow.getShooter() // Playing this game to not have to take a hard dependency on // craftbukkit internals. try { Class<?> damager_class = damager_entity.getClass(); if (damager_class.getName().endsWith(".CraftArrow")) { Method getShooter = damager_class.getMethod("getShooter"); Object result = getShooter.invoke(damager_entity); if (result instanceof Player) { damager_is_player_arrow = true; String player_name = ((Player)result).getName(); if (bow_level_.containsKey(player_name)) { chance_scaling = bow_level_.get(player_name); } } } } catch(Exception ex) {} } if (!damager_is_player_arrow) { return; } rate += chance_scaling * 5; int percent = prng_.nextInt(100); if (percent < rate){ int ticks = config_.get("projectile_slow_ticks").getInt(); Player player = (Player)event.getEntity(); player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, ticks, 1, false)); } } // Used to track bow enchantment levels per player private Map<String, Integer> bow_level_ = new TreeMap<String, Integer>(); @EventHandler public void onEntityShootBow(EntityShootBowEvent event) { if (!(event.getEntity() instanceof Player)) { return; } int ench_level = 0; ItemStack bow = event.getBow(); Map<Enchantment, Integer> enchants = bow.getEnchantments(); for (Enchantment ench : enchants.keySet()) { int tmp_ench_level = 0; if (ench.equals(Enchantment.KNOCKBACK) || ench.equals(Enchantment.ARROW_KNOCKBACK)) { tmp_ench_level = enchants.get(ench) * 2; } else if (ench.equals(Enchantment.ARROW_DAMAGE)) { tmp_ench_level = enchants.get(ench); } if (tmp_ench_level > ench_level) { ench_level = tmp_ench_level; } } bow_level_.put( ((Player)event.getEntity()).getName(), ench_level); } // BottleO refugees // Changes the yield from an XP bottle @BahHumbugs ({ @BahHumbug(opt="ignore_experience", def="false"), @BahHumbug(opt="disable_experience", def="true"), @BahHumbug(opt="xp_per_bottle", type=OptType.Int, def="10") }) @EventHandler(priority=EventPriority.HIGHEST) public void onExpBottleEvent(ExpBottleEvent event) { if (config_.get("ignore_experience").getBool()) return; final int bottle_xp = config_.get("xp_per_bottle").getInt(); if (config_.get("disable_experience").getBool()) { ((Player) event.getEntity().getShooter()).giveExp(bottle_xp); event.setExperience(0); } else { event.setExperience(bottle_xp); } } // Diables all XP gain except when manually changed via code. @EventHandler public void onPlayerExpChangeEvent(PlayerExpChangeEvent event) { if (config_.get("ignore_experience").getBool()) return; if (config_.get("disable_experience").getBool()) { event.setAmount(0); } } // Find the end portals public static final int ender_portal_id_ = Material.ENDER_PORTAL.getId(); public static final int ender_portal_frame_id_ = Material.ENDER_PORTAL_FRAME.getId(); private Set<Long> end_portal_scanned_chunks_ = new TreeSet<Long>(); @BahHumbug(opt="find_end_portals", type=OptType.String) @EventHandler public void onFindEndPortals(ChunkLoadEvent event) { String scanWorld = config_.get("find_end_portals").getString(); if (scanWorld.isEmpty()) { return; } World world = event.getWorld(); if (!world.getName().equalsIgnoreCase(scanWorld)) { return; } Chunk chunk = event.getChunk(); long chunk_id = ((long)chunk.getX() << 32L) + (long)chunk.getZ(); if (end_portal_scanned_chunks_.contains(chunk_id)) { return; } end_portal_scanned_chunks_.add(chunk_id); int chunk_x = chunk.getX() * 16; int chunk_end_x = chunk_x + 16; int chunk_z = chunk.getZ() * 16; int chunk_end_z = chunk_z + 16; int max_height = 0; for (int x = chunk_x; x < chunk_end_x; x += 3) { for (int z = chunk_z; z < chunk_end_z; ++z) { int height = world.getMaxHeight(); if (height > max_height) { max_height = height; } } } for (int y = 1; y <= max_height; ++y) { int z_adj = 0; for (int x = chunk_x; x < chunk_end_x; ++x) { for (int z = chunk_z + z_adj; z < chunk_end_z; z += 3) { int block_type = world.getBlockTypeIdAt(x, y, z); if (block_type == ender_portal_id_ || block_type == ender_portal_frame_id_) { info(String.format("End portal found at %d,%d", x, z)); return; } } // This funkiness results in only searching 48 of the 256 blocks on // each y-level. 81.25% fewer blocks checked. ++z_adj; if (z_adj >= 3) { z_adj = 0; x += 2; } } } } // Prevent inventory access while in a vehicle, unless it's the Player's @BahHumbugs ({ @BahHumbug(opt="prevent_opening_container_carts", def="true"), @BahHumbug(opt="prevent_vehicle_inventory_open", def="true") }) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPreventVehicleInvOpen(InventoryOpenEvent event) { // Cheap break-able conditional statement while (config_.get("prevent_vehicle_inventory_open").getBool()) { HumanEntity human = event.getPlayer(); if (!(human instanceof Player)) { break; } if (!human.isInsideVehicle()) { break; } InventoryHolder holder = event.getInventory().getHolder(); if (holder == human) { break; } event.setCancelled(true); break; } if (config_.get("prevent_opening_container_carts").getBool() && !event.isCancelled()) { InventoryHolder holder = event.getInventory().getHolder(); if (holder instanceof StorageMinecart || holder instanceof HopperMinecart) { event.setCancelled(true); } } } // Disable outbound hopper transfers @BahHumbug(opt="disable_hopper_out_transfers", def="false") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onInventoryMoveItem(InventoryMoveItemEvent event) { if (!config_.get("disable_hopper_out_transfers").getBool()) { return; } final Inventory src = event.getSource(); final InventoryHolder srcHolder = src.getHolder(); if (srcHolder instanceof Hopper) { event.setCancelled(true); return; } } // Adjust horse speeds @BahHumbug(opt="horse_speed", type=OptType.Double, def="0.170000") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onVehicleEnter(VehicleEnterEvent event) { // 0.17 is just a tad slower than minecarts Vehicle vehicle = event.getVehicle(); if (!(vehicle instanceof Horse)) { return; } Versioned.setHorseSpeed((Entity)vehicle, config_.get("horse_speed").getDouble()); } // Admins can view player inventories @SuppressWarnings("deprecation") public void onInvseeCommand(Player admin, String playerName) { final Player player = Bukkit.getPlayerExact(playerName); if (player == null) { admin.sendMessage("Player not found"); return; } final Inventory pl_inv = player.getInventory(); final Inventory inv = Bukkit.createInventory( admin, 36, playerName + "'s Inventory"); for (int slot = 0; slot < 36; slot++) { final ItemStack it = pl_inv.getItem(slot); inv.setItem(slot, it); } admin.openInventory(inv); admin.updateInventory(); } // Fix boats @BahHumbug(opt="prevent_self_boat_break", def="true") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPreventLandBoats(VehicleDestroyEvent event) { if (!config_.get("prevent_land_boats").getBool()) { return; } final Vehicle vehicle = event.getVehicle(); if (vehicle == null || !(vehicle instanceof Boat)) { return; } final Entity passenger = vehicle.getPassenger(); if (passenger == null || !(passenger instanceof Player)) { return; } final Entity attacker = event.getAttacker(); if (attacker == null) { return; } if (!attacker.getUniqueId().equals(passenger.getUniqueId())) { return; } final Player player = (Player)passenger; Humbug.info(String.format( "Player '%s' kicked for self damaging boat at %s", player.getName(), vehicle.getLocation().toString())); vehicle.eject(); vehicle.getWorld().dropItem(vehicle.getLocation(), new ItemStack(Material.BOAT)); vehicle.remove(); ((Player)passenger).kickPlayer("Nope"); } @BahHumbug(opt="prevent_land_boats", def="true") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPreventLandBoats(VehicleMoveEvent event) { if (!config_.get("prevent_land_boats").getBool()) { return; } final Vehicle vehicle = event.getVehicle(); if (vehicle == null || !(vehicle instanceof Boat)) { return; } final Entity passenger = vehicle.getPassenger(); if (passenger == null || !(passenger instanceof Player)) { return; } final Location to = event.getTo(); final Material boatOn = to.getBlock().getType(); if (boatOn.equals(Material.STATIONARY_WATER) || boatOn.equals(Material.WATER)) { return; } Humbug.info(String.format( "Player '%s' removed from land-boat at %s", ((Player)passenger).getName(), to.toString())); vehicle.eject(); vehicle.getWorld().dropItem(vehicle.getLocation(), new ItemStack(Material.BOAT)); vehicle.remove(); } // Fix minecarts public boolean checkForTeleportSpace(Location loc) { final Block block = loc.getBlock(); final Material mat = block.getType(); if (mat.isSolid()) { return false; } final Block above = block.getRelative(BlockFace.UP); if (above.getType().isSolid()) { return false; } return true; } public boolean tryToTeleport(Player player, Location location, String reason) { Location loc = location.clone(); loc.setX(Math.floor(loc.getX()) + 0.500000D); loc.setY(Math.floor(loc.getY()) + 0.02D); loc.setZ(Math.floor(loc.getZ()) + 0.500000D); final Location baseLoc = loc.clone(); final World world = baseLoc.getWorld(); // Check if teleportation here is viable boolean performTeleport = checkForTeleportSpace(loc); if (!performTeleport) { loc.setY(loc.getY() + 1.000000D); performTeleport = checkForTeleportSpace(loc); } if (performTeleport) { player.setVelocity(new Vector()); player.teleport(loc); Humbug.info(String.format( "Player '%s' %s: Teleported to %s", player.getName(), reason, loc.toString())); return true; } loc = baseLoc.clone(); // Create a sliding window of block types and track how many of those // are solid. Keep fetching the block below the current block to move down. int air_count = 0; LinkedList<Material> air_window = new LinkedList<Material>(); loc.setY((float)world.getMaxHeight() - 2); Block block = world.getBlockAt(loc); for (int i = 0; i < 4; ++i) { Material block_mat = block.getType(); if (!block_mat.isSolid()) { ++air_count; } air_window.addLast(block_mat); block = block.getRelative(BlockFace.DOWN); } // Now that the window is prepared, scan down the Y-axis. while (block.getY() >= 1) { Material block_mat = block.getType(); if (block_mat.isSolid()) { if (air_count == 4) { player.setVelocity(new Vector()); loc = block.getLocation(); loc.setX(Math.floor(loc.getX()) + 0.500000D); loc.setY(loc.getY() + 1.02D); loc.setZ(Math.floor(loc.getZ()) + 0.500000D); player.teleport(loc); Humbug.info(String.format( "Player '%s' %s: Teleported to %s", player.getName(), reason, loc.toString())); return true; } } else { // !block_mat.isSolid() ++air_count; } air_window.addLast(block_mat); if (!air_window.removeFirst().isSolid()) { --air_count; } block = block.getRelative(BlockFace.DOWN); } return false; } @BahHumbug(opt="prevent_ender_pearl_save", def="true") @EventHandler public void enderPearlSave(EnderPearlUnloadEvent event) { if(!config_.get("prevent_ender_pearl_save").getBool()) return; event.setCancelled(true); } @BahHumbug(opt="fix_vehicle_logout_bug", def="true") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void onDisallowVehicleLogout(PlayerQuitEvent event) { if (!config_.get("fix_vehicle_logout_bug").getBool()) { return; } kickPlayerFromVehicle(event.getPlayer()); } public void kickPlayerFromVehicle(Player player) { Entity vehicle = player.getVehicle(); if (vehicle == null || !(vehicle instanceof Minecart || vehicle instanceof Horse || vehicle instanceof Arrow)) { return; } Location vehicleLoc = vehicle.getLocation(); // Vehicle data has been cached, now safe to kick the player out player.leaveVehicle(); if (!tryToTeleport(player, vehicleLoc, "logged out")) { player.setHealth(0.000000D); Humbug.info(String.format( "Player '%s' logged out in vehicle: Killed", player.getName())); } } @BahHumbug(opt="fix_minecart_reenter_bug", def="true") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onFixMinecartReenterBug(VehicleExitEvent event) { if (!config_.get("fix_minecart_reenter_bug").getBool()) { return; } final Vehicle vehicle = event.getVehicle(); if (vehicle == null || !(vehicle instanceof Minecart)) { return; } final Entity passengerEntity = event.getExited(); if (passengerEntity == null || !(passengerEntity instanceof Player)) { return; } // Must delay the teleport 2 ticks or else the player's mis-managed // movement still occurs. With 1 tick it could still occur. final Player player = (Player)passengerEntity; final Location vehicleLoc = vehicle.getLocation(); Bukkit.getScheduler().runTaskLater(this, new Runnable() { @Override public void run() { if (!tryToTeleport(player, vehicleLoc, "exiting vehicle")) { player.setHealth(0.000000D); Humbug.info(String.format( "Player '%s' exiting vehicle: Killed", player.getName())); } } }, 2L); } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onFixMinecartReenterBug(VehicleDestroyEvent event) { if (!config_.get("fix_minecart_reenter_bug").getBool()) { return; } final Vehicle vehicle = event.getVehicle(); if (vehicle == null || !(vehicle instanceof Minecart || vehicle instanceof Horse)) { return; } final Entity passengerEntity = vehicle.getPassenger(); if (passengerEntity == null || !(passengerEntity instanceof Player)) { return; } // Must delay the teleport 2 ticks or else the player's mis-managed // movement still occurs. With 1 tick it could still occur. final Player player = (Player)passengerEntity; final Location vehicleLoc = vehicle.getLocation(); Bukkit.getScheduler().runTaskLater(this, new Runnable() { @Override public void run() { if (!tryToTeleport(player, vehicleLoc, "in destroyed vehicle")) { player.setHealth(0.000000D); Humbug.info(String.format( "Player '%s' in destroyed vehicle: Killed", player.getName())); } } }, 2L); } // Adjust ender pearl gravity public final static int pearlId = 368; public final static MinecraftKey pearlKey = new MinecraftKey("ender_pearl"); @SuppressWarnings({ "rawtypes", "unchecked" }) @BahHumbug(opt="ender_pearl_gravity", type=OptType.Double, def="0.060000") private void hookEnderPearls() { try { // They thought they could stop us by preventing us from registering an // item. We'll show them Field idRegistryField = Item.REGISTRY.getClass().getDeclaredField("a"); idRegistryField.setAccessible(true); Object idRegistry = idRegistryField.get(Item.REGISTRY); Field idRegistryMapField = idRegistry.getClass().getDeclaredField("a"); idRegistryMapField.setAccessible(true); Object idRegistryMap = idRegistryMapField.get(idRegistry); Field idRegistryItemsField = idRegistry.getClass().getDeclaredField("b"); idRegistryItemsField.setAccessible(true); Object idRegistryItemList = idRegistryItemsField.get(idRegistry); // Remove ItemEnderPearl from the ID Registry Item idItem = null; Iterator<Item> itemListIter = ((List<Item>)idRegistryItemList).iterator(); while (itemListIter.hasNext()) { idItem = itemListIter.next(); if (idItem == null) { continue; } if (!(idItem instanceof ItemEnderPearl)) { continue; } itemListIter.remove(); break; } if (idItem != null) { ((Map<Item, Integer>)idRegistryMap).remove(idItem); } // Register our custom pearl Item. Item.REGISTRY.a(pearlId, pearlKey, new CustomNMSItemEnderPearl(config_)); // Setup the custom entity Field fieldStringToClass = EntityTypes.class.getDeclaredField("c"); Field fieldClassToString = EntityTypes.class.getDeclaredField("d"); fieldStringToClass.setAccessible(true); fieldClassToString.setAccessible(true); Field fieldClassToId = EntityTypes.class.getDeclaredField("f"); Field fieldStringToId = EntityTypes.class.getDeclaredField("g"); fieldClassToId.setAccessible(true); fieldStringToId.setAccessible(true); Map mapStringToClass = (Map)fieldStringToClass.get(null); Map mapClassToString = (Map)fieldClassToString.get(null); Map mapClassToId = (Map)fieldClassToId.get(null); Map mapStringToId = (Map)fieldStringToId.get(null); mapStringToClass.put("ThrownEnderpearl",CustomNMSEntityEnderPearl.class); mapStringToId.put("ThrownEnderpearl", Integer.valueOf(14)); mapClassToString.put(CustomNMSEntityEnderPearl.class, "ThrownEnderpearl"); mapClassToId.put(CustomNMSEntityEnderPearl.class, Integer.valueOf(14)); } catch (Exception e) { Humbug.severe("Exception while overriding MC's ender pearl class"); e.printStackTrace(); } } // Hunger Changes // Keep track if the player just ate. private Map<Player, Double> playerLastEat_ = new HashMap<Player, Double>(); @BahHumbug(opt="saturation_multiplier", type=OptType.Double, def="0.0") @EventHandler public void setSaturationOnFoodEat(PlayerItemConsumeEvent event) { // Each food sets a different saturation. final Player player = event.getPlayer(); ItemStack item = event.getItem(); Material mat = item.getType(); double multiplier = config_.get("saturation_multiplier").getDouble(); if (multiplier <= 0.000001 && multiplier >= -0.000001) { return; } switch(mat) { case APPLE: playerLastEat_.put(player, multiplier*2.4); case BAKED_POTATO: playerLastEat_.put(player, multiplier*7.2); case BREAD: playerLastEat_.put(player, multiplier*6); case CAKE: playerLastEat_.put(player, multiplier*0.4); case CARROT_ITEM: playerLastEat_.put(player, multiplier*4.8); case COOKED_FISH: playerLastEat_.put(player, multiplier*6); case GRILLED_PORK: playerLastEat_.put(player, multiplier*12.8); case COOKIE: playerLastEat_.put(player, multiplier*0.4); case GOLDEN_APPLE: playerLastEat_.put(player, multiplier*9.6); case GOLDEN_CARROT: playerLastEat_.put(player, multiplier*14.4); case MELON: playerLastEat_.put(player, multiplier*1.2); case MUSHROOM_SOUP: playerLastEat_.put(player, multiplier*7.2); case POISONOUS_POTATO: playerLastEat_.put(player, multiplier*1.2); case POTATO: playerLastEat_.put(player, multiplier*0.6); case RAW_FISH: playerLastEat_.put(player, multiplier*1); case PUMPKIN_PIE: playerLastEat_.put(player, multiplier*4.8); case RAW_BEEF: playerLastEat_.put(player, multiplier*1.8); case RAW_CHICKEN: playerLastEat_.put(player, multiplier*1.2); case PORK: playerLastEat_.put(player, multiplier*1.8); case ROTTEN_FLESH: playerLastEat_.put(player, multiplier*0.8); case SPIDER_EYE: playerLastEat_.put(player, multiplier*3.2); case COOKED_BEEF: playerLastEat_.put(player, multiplier*12.8); default: playerLastEat_.put(player, multiplier); Bukkit.getServer().getScheduler().runTaskLater(this, new Runnable() { // In case the player ingested a potion, this removes the // saturation from the list. Unsure if I have every item // listed. There is always the other cases of like food // that shares same id @Override public void run() { playerLastEat_.remove(player); } }, 80); } } @BahHumbug(opt="hunger_slowdown", type=OptType.Double, def="0.0") @EventHandler public void onFoodLevelChange(FoodLevelChangeEvent event) { final Player player = (Player) event.getEntity(); final double mod = config_.get("hunger_slowdown").getDouble(); Double saturation; if (playerLastEat_.containsKey(player)) { // if the player just ate saturation = playerLastEat_.get(player); if (saturation == null) { saturation = ((Float)player.getSaturation()).doubleValue(); } } else { saturation = Math.min( player.getSaturation() + mod, 20.0D + (mod * 2.0D)); } player.setSaturation(saturation.floatValue()); } //Remove Book Copying @BahHumbug(opt="copy_book_enable", def= "false") public void removeBooks() { if (config_.get("copy_book_enable").getBool()) { return; } Iterator<Recipe> it = getServer().recipeIterator(); while (it.hasNext()) { Recipe recipe = it.next(); ItemStack resulting_item = recipe.getResult(); if ( // !copy_book_enable_ && isWrittenBook(resulting_item)) { it.remove(); info("Copying Books disabled"); } } } public boolean isWrittenBook(ItemStack item) { if (item == null) { return false; } Material material = item.getType(); return material.equals(Material.WRITTEN_BOOK); } // Prevent tree growth wrap-around @BahHumbug(opt="prevent_tree_wraparound", def="true") @EventHandler(priority=EventPriority.LOWEST, ignoreCancelled = true) public void onStructureGrowEvent(StructureGrowEvent event) { if (!config_.get("prevent_tree_wraparound").getBool()) { return; } int maxY = 0, minY = 257; for (BlockState bs : event.getBlocks()) { final int y = bs.getLocation().getBlockY(); maxY = Math.max(maxY, y); minY = Math.min(minY, y); } if (maxY - minY > 240) { event.setCancelled(true); final Location loc = event.getLocation(); info(String.format("Prevented structure wrap-around at %d, %d, %d", loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); } } // Equipping banners @BahHumbug(opt="equipping_banners", def="true") public void onEquippingBanners(PlayerInteractEvent event){ if(!config_.get("equipping_banners").getBool()) { return; } if (event.getItem() == null || !event.getItem().getType().equals(Material.BANNER) || (event.getAction() != Action.LEFT_CLICK_AIR&&event.getAction() != Action.LEFT_CLICK_BLOCK)) { return; } Player player = event.getPlayer(); ItemStack banner = new ItemStack(event.getItem()); banner.setAmount(1); player.getInventory().removeItem(banner); if (player.getEquipment().getHelmet() != null) { if(player.getInventory().addItem(player.getEquipment().getHelmet()).size() != 0) { player.getWorld().dropItem(player.getLocation(), player.getEquipment().getHelmet()); } } player.getEquipment().setHelmet(banner); } // Disable changing spawners with eggs @BahHumbug(opt="changing_spawners_with_eggs", def="true") public void onChangingSpawners(PlayerInteractEvent event) { if (!config_.get("changing_spawners_with_eggs").getBool()) { return; } if ((event.getClickedBlock() != null) && (event.getItem() != null) && (event.getClickedBlock().getType()==Material.MOB_SPAWNER) && (event.getItem().getType() == Material.MONSTER_EGG)) { event.setCancelled(true); } } // Enforce good sign data length @BahHumbugs( { @BahHumbug(opt="prevent_long_signs", def="true"), @BahHumbug(opt="prevent_long_signs_limit", type=OptType.Int, def="100"), @BahHumbug(opt="prevent_long_signs_allornothing", def="true"), @BahHumbug(opt="prevent_long_signs_cancelevent", def="false") }) @EventHandler(ignoreCancelled=true) public void onSignFinalize(SignChangeEvent e) { if (!config_.get("prevent_long_signs").getBool()) { return; } String[] signdata = e.getLines(); for (int i = 0; i < signdata.length; i++) { if (signdata[i] != null && signdata[i].length() > config_.get("prevent_long_signs_limit").getInt()) { Player p = e.getPlayer(); Location location = e.getBlock().getLocation(); warning(String.format( "Player '%s' [%s] attempted to place sign at ([%s] %d, %d, %d) with line %d having length %d > %d. Preventing.", p.getPlayerListName(), p.getUniqueId(), location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), i, signdata[i].length(), config_.get("prevent_long_signs_limit").getInt())); if (config_.get("prevent_long_signs_cancelevent").getBool()) { e.setCancelled(true); return; } if (config_.get("prevent_long_signs_allornothing").getBool()) { e.setLine(i, ""); } else { e.setLine(i, signdata[i].substring(0, config_.get("prevent_long_signs_limit").getInt())); } } } } private HashMap<String, Set<Long>> signs_scanned_chunks_ = new HashMap<String, Set<Long>>(); @BahHumbug(opt="prevent_long_signs_in_chunks", def="true") @EventHandler(priority=EventPriority.HIGHEST, ignoreCancelled=false) public void onSignLoads(ChunkLoadEvent event) { if (!config_.get("prevent_long_signs_in_chunks").getBool()) { return; } Chunk chunk = event.getChunk(); String world = chunk.getWorld().getName(); long chunk_id = ((long)chunk.getX() << 32L) + (long)chunk.getZ(); if (signs_scanned_chunks_.containsKey(world)) { if (signs_scanned_chunks_.get(world).contains(chunk_id)) { return; } } else { signs_scanned_chunks_.put(world, new TreeSet<Long>()); } signs_scanned_chunks_.get(world).add(chunk_id); BlockState[] allTiles = chunk.getTileEntities(); for(BlockState tile: allTiles) { if (tile instanceof Sign) { Sign sign = (Sign) tile; String[] signdata = sign.getLines(); for (int i = 0; i < signdata.length; i++) { if (signdata[i] != null && signdata[i].length() > config_.get("prevent_long_signs_limit").getInt()) { Location location = sign.getLocation(); warning(String.format( "Line %d in sign at ([%s] %d, %d, %d) is length %d > %d. Curating.", i, world, location.getBlockX(), location.getBlockY(), location.getBlockZ(), signdata[i].length(), config_.get("prevent_long_signs_limit").getInt())); if (config_.get("prevent_long_signs_allornothing").getBool()) { sign.setLine(i, ""); } else { sign.setLine(i, signdata[i].substring(0, config_.get("prevent_long_signs_limit").getInt())); } sign.update(true); } } } } } @EventHandler(priority = EventPriority.HIGHEST) public void adminAccessBlockedChest(PlayerInteractEvent e) { if (!e.getPlayer().hasPermission("humbug.admin") && !e.getPlayer().isOp()) { return; } if (e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK) { Player p = e.getPlayer(); Set <Material> s = new TreeSet<Material>(); s.add(Material.AIR); s.add(Material.OBSIDIAN); //probably in a vault List <Block> blocks = p.getLineOfSight(s, 8); for(Block b:blocks) { Material m = b.getType(); if(m == Material.CHEST || m == Material.TRAPPED_CHEST) { if(b.getRelative(BlockFace.UP).getType().isOccluding()) { //dont show inventory twice if a normal chest is opened final Inventory che_inv = ((InventoryHolder)b.getState()).getInventory(); p.openInventory(che_inv); p.updateInventory(); } break; } } } } //there is a bug in minecraft 1.8, which allows fire and vines to spread into unloaded chunks //where they can replace any existing block @EventHandler(priority = EventPriority.LOWEST) public void fixSpreadInUnloadedChunks(BlockSpreadEvent e) { if (!e.getBlock().getChunk().isLoaded()) { e.setCancelled(true); } } // General public void onLoad() { loadConfiguration(); //hookEnderPearls(); info("Loaded"); } public void onEnable() { registerEvents(); registerCommands(); removeRecipies(); removeBooks(); registerTimerForPearlCheck(); global_instance_ = this; info("Enabled"); if (Bukkit.getPluginManager().getPlugin("CombatTag") != null) combatTag_ = new CombatTagManager(); else if (Bukkit.getPluginManager().getPlugin("CombatTagPlus") != null) combatTag_ = new CombatTagPlusManager(); } public void onDisable() { if (config_.get("fix_vehicle_logout_bug").getBool()) { for (World world: getServer().getWorlds()) { for (Player player: world.getPlayers()) { kickPlayerFromVehicle(player); } } } } public boolean isInitiaized() { return global_instance_ != null; } public boolean toBool(String value) { if (value.equals("1") || value.equalsIgnoreCase("true")) { return true; } return false; } public int toInt(String value, int default_value) { try { return Integer.parseInt(value); } catch(Exception e) { return default_value; } } public double toDouble(String value, double default_value) { try { return Double.parseDouble(value); } catch(Exception e) { return default_value; } } public int toMaterialId(String value, int default_value) { try { return Integer.parseInt(value); } catch(Exception e) { Material mat = Material.matchMaterial(value); if (mat != null) { return mat.getId(); } } return default_value; } public boolean onCommand( CommandSender sender, Command command, String label, String[] args) { if (sender instanceof Player && command.getName().equals("invsee")) { if (args.length < 1) { sender.sendMessage("Provide a name"); return false; } onInvseeCommand((Player)sender, args[0]); return true; } if (sender instanceof Player && command.getName().equals("introbook")) { if (!config_.get("drop_newbie_book").getBool()) { return true; } Player sendBookTo = (Player)sender; if (args.length >= 1) { Player possible = Bukkit.getPlayerExact(args[0]); if (possible != null) { sendBookTo = possible; } } giveN00bBook(sendBookTo); return true; } if (sender instanceof Player && command.getName().equals("bahhumbug")) { giveHolidayPackage((Player)sender); return true; } if (!(sender instanceof ConsoleCommandSender) || !command.getName().equals("humbug") || args.length < 1) { return false; } String option = args[0]; String value = null; String subvalue = null; boolean set = false; boolean subvalue_set = false; String msg = ""; if (args.length > 1) { value = args[1]; set = true; } if (args.length > 2) { subvalue = args[2]; subvalue_set = true; } ConfigOption opt = config_.get(option); if (opt != null) { if (set) { opt.set(value); } msg = String.format("%s = %s", option, opt.getString()); } else if (option.equals("debug")) { if (set) { config_.setDebug(toBool(value)); } msg = String.format("debug = %s", config_.getDebug()); } else if (option.equals("loot_multiplier")) { String entity_type = "generic"; if (set && subvalue_set) { entity_type = value; value = subvalue; } if (set) { config_.setLootMultiplier( entity_type, toInt(value, config_.getLootMultiplier(entity_type))); } msg = String.format( "loot_multiplier(%s) = %d", entity_type, config_.getLootMultiplier(entity_type)); } else if (option.equals("remove_mob_drops")) { if (set && subvalue_set) { if (value.equals("add")) { config_.addRemoveItemDrop(toMaterialId(subvalue, -1)); } else if (value.equals("del")) { config_.removeRemoveItemDrop(toMaterialId(subvalue, -1)); } } msg = String.format("remove_mob_drops = %s", config_.toDisplayRemoveItemDrops()); } else if (option.equals("save")) { config_.save(); msg = "Configuration saved"; } else if (option.equals("reload")) { config_.reload(); msg = "Configuration loaded"; } else { msg = String.format("Unknown option %s", option); } sender.sendMessage(msg); return true; } public void registerCommands() { ConsoleCommandSender console = getServer().getConsoleSender(); console.addAttachment(this, "humbug.console", true); } private void registerEvents() { getServer().getPluginManager().registerEvents(this, this); getServer().getScheduler().scheduleSyncRepeatingTask(this, new DiskMonitor(this), 0L, 20L*60L); //once a minute } private void loadConfiguration() { config_ = Config.initialize(this); } @BahHumbug(opt="disk_space_shutdown", type = OptType.Double, def = "0.02") public Config getHumbugConfig() { return config_; } }
package com.wizzardo.epoll; import com.wizzardo.epoll.readable.ReadableByteArray; import com.wizzardo.epoll.readable.ReadableData; import com.wizzardo.tools.io.IOTools; import java.io.Closeable; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.util.Deque; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.atomic.AtomicReference; public class Connection implements Cloneable, Closeable { protected static final int EPOLLIN = 0x001; protected static final int EPOLLOUT = 0x004; protected int fd; protected int ip, port; protected volatile Deque<ReadableData> sending; protected volatile IOThread epoll; protected volatile long ssl; protected volatile boolean sslAccepted; protected final AtomicReference<ByteBufferProvider> writer = new AtomicReference<>(); private volatile int mode = 1; private volatile boolean alive = true; volatile boolean readyToRead = true; private String ipString; private Long lastEvent; public Connection(int fd, int ip, int port) { this.fd = fd; this.ip = ip; this.port = port; } public String getIp() { if (ipString == null) ipString = getIp(ip); return ipString; } void setIpString(String ip) { ipString = ip; } private String getIp(int ip) { StringBuilder sb = new StringBuilder(); sb.append((ip >> 24) + (ip < 0 ? 256 : 0)).append("."); sb.append((ip & 16777215) >> 16).append("."); sb.append((ip & 65535) >> 8).append("."); sb.append(ip & 255); return sb.toString(); } public int getPort() { return port; } public boolean isReadyToRead() { return readyToRead; } Long setLastEvent(Long lastEvent) { Long last = this.lastEvent; this.lastEvent = lastEvent; return last; } Long getLastEvent() { return lastEvent; } public boolean isAlive() { return alive; } protected synchronized void setIsAlive(boolean isAlive) { alive = isAlive; } public boolean write(String s, ByteBufferProvider bufferProvider) { try { return write(s.getBytes("utf-8"), bufferProvider); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } public boolean write(byte[] bytes, ByteBufferProvider bufferProvider) { return write(bytes, 0, bytes.length, bufferProvider); } public boolean write(byte[] bytes, int offset, int length, ByteBufferProvider bufferProvider) { return write(new ReadableByteArray(bytes, offset, length), bufferProvider); } public boolean write(ReadableData readable, ByteBufferProvider bufferProvider) { if (sending == null) { if (writer.compareAndSet(null, bufferProvider)) { try { while (!readable.isComplete() && actualWrite(readable, bufferProvider)) { } if (!readable.isComplete()) { safeCreateQueueIfNotExists(); sending.addFirst(readable); return false; } readable.close(); readable.onComplete(); onWriteData(readable, false); } catch (Exception e) { e.printStackTrace(); try { close(); } catch (IOException e1) { e1.printStackTrace(); } } finally { writer.set(null); } } else { safeCreateQueueIfNotExists(); sending.add(readable); } return write(bufferProvider); } else { sending.add(readable); return write(bufferProvider); } } protected void safeCreateQueueIfNotExists() { if (sending == null) synchronized (this) { if (sending == null) sending = createSendingQueue(); } } protected Deque<ReadableData> createSendingQueue() { return new ConcurrentLinkedDeque<>(); } /* * @return true if connection is ready to write data */ public boolean write(ByteBufferProvider bufferProvider) { Queue<ReadableData> queue = this.sending; if (queue == null) return true; while (!queue.isEmpty() && writer.compareAndSet(null, bufferProvider)) { try { ReadableData readable; while ((readable = queue.peek()) != null) { while (!readable.isComplete() && actualWrite(readable, bufferProvider)) { } if (!readable.isComplete()) return false; queue.poll(); readable.close(); readable.onComplete(); onWriteData(readable, !queue.isEmpty()); } } catch (Exception e) { e.printStackTrace(); try { close(); } catch (IOException e1) { e1.printStackTrace(); } } finally { writer.set(null); } } return true; } /* * @return true if connection is ready to write data */ protected boolean actualWrite(ReadableData readable, ByteBufferProvider bufferProvider) throws IOException { ByteBufferWrapper bb = readable.getByteBuffer(bufferProvider); bb.clear(); int r = readable.read(bb); if (r > 0 && isAlive()) { int written = epoll.write(this, bb.address, bb.offset(), r); // System.out.println("write: " + written + " (" + readable.complete() + "/" + readable.length() + ")" + " to " + this); if (written != r) { readable.unread(r - written); return false; } return true; } return false; } public int read(byte[] b, int offset, int length, ByteBufferProvider bufferProvider) throws IOException { ByteBuffer bb = read(length, bufferProvider); int r = bb.limit(); bb.get(b, offset, r); return r; } public ByteBuffer read(int length, ByteBufferProvider bufferProvider) throws IOException { ByteBufferWrapper bb = bufferProvider.getBuffer(); bb.clear(); int l = Math.min(length, bb.limit()); int r = isAlive() ? epoll.read(this, bb.address, 0, l) : -1; if (r > 0) bb.position(r); bb.flip(); readyToRead = r == l; return bb.buffer(); } public void close() throws IOException { if (sending != null) for (ReadableData data : sending) IOTools.close(data); if (ssl != 0) epoll.closeSSL(ssl); epoll.close(this); } public boolean isSecured() { return ssl != 0; } protected void enableOnWriteEvent() { if ((mode & EPOLLIN) != 0) epoll.mod(this, EPOLLIN | EPOLLOUT); else epoll.mod(this, EPOLLOUT); } protected void disableOnWriteEvent() { if ((mode & EPOLLIN) != 0) epoll.mod(this, EPOLLIN); else epoll.mod(this, 0); } protected void enableOnReadEvent() { if ((mode & EPOLLOUT) != 0) epoll.mod(this, EPOLLIN | EPOLLOUT); else epoll.mod(this, EPOLLIN); } protected void disableOnReadEvent() { if ((mode & EPOLLOUT) != 0) epoll.mod(this, EPOLLOUT); else epoll.mod(this, 0); } public void onWriteData(ReadableData readable, boolean hasMore) { } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Connection that = (Connection) o; if (fd != that.fd) return false; if (ip != that.ip) return false; if (port != that.port) return false; return true; } @Override public int hashCode() { int result = fd; result = 31 * result + ip; result = 31 * result + port; return result; } @Override public String toString() { return fd + " " + getIp() + ":" + port; } public int read(byte[] bytes, ByteBufferProvider bufferProvider) throws IOException { return read(bytes, 0, bytes.length, bufferProvider); } boolean isInvalid(Long now) { return lastEvent.compareTo(now) <= 0; } void setMode(int mode) { this.mode = mode; } int getMode() { return mode; } public void setIOThread(IOThread IOThread) { epoll = IOThread; } boolean prepareSSL() { if (ssl == 0) ssl = epoll.createSSL(fd); if (!sslAccepted) { synchronized (this) { if (!sslAccepted) sslAccepted = epoll.acceptSSL(ssl); } } else return true; return sslAccepted; } }
package de.prob2.ui.states; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.ResourceBundle; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; import de.prob.animator.command.GetMachineStructureCommand; import de.prob.animator.domainobjects.AbstractEvalResult; import de.prob.animator.domainobjects.EvalResult; import de.prob.animator.domainobjects.EvaluationErrorResult; import de.prob.animator.domainobjects.EvaluationException; import de.prob.animator.domainobjects.FormulaExpand; import de.prob.animator.domainobjects.IEvalElement; import de.prob.animator.prologast.ASTCategory; import de.prob.animator.prologast.ASTFormula; import de.prob.animator.prologast.PrologASTNode; import de.prob.exception.ProBError; import de.prob.statespace.State; import de.prob.statespace.Trace; import de.prob2.ui.formula.FormulaStage; import de.prob2.ui.helpsystem.HelpButton; import de.prob2.ui.internal.StageManager; import de.prob2.ui.internal.StopActions; import de.prob2.ui.prob2fx.CurrentTrace; import de.prob2.ui.statusbar.StatusBar; import javafx.application.Platform; import javafx.beans.binding.Bindings; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; import javafx.scene.control.TextField; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeTableColumn; import javafx.scene.control.TreeTableRow; import javafx.scene.control.TreeTableView; import javafx.scene.input.MouseButton; import javafx.scene.layout.StackPane; import javafx.util.Callback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public final class StatesView extends StackPane { private static final Logger LOGGER = LoggerFactory.getLogger(StatesView.class); private static final TreeItem<StateItem<?>> LOADING_ITEM; static { LOADING_ITEM = new TreeItem<>(new StateItem<>("Loading...", false)); LOADING_ITEM.getChildren().add(new TreeItem<>(new StateItem<>("Loading", false))); } @FXML private Button searchButton; @FXML private TextField filterState; @FXML private HelpButton helpButton; @FXML private TreeTableView<StateItem<?>> tv; @FXML private TreeTableColumn<StateItem<?>, StateItem<?>> tvName; @FXML private TreeTableColumn<StateItem<?>, StateItem<?>> tvValue; @FXML private TreeTableColumn<StateItem<?>, StateItem<?>> tvPreviousValue; @FXML private TreeItem<StateItem<?>> tvRootItem; private final Injector injector; private final CurrentTrace currentTrace; private final StatusBar statusBar; private final StageManager stageManager; private final ResourceBundle bundle; private List<PrologASTNode> rootNodes; private List<PrologASTNode> filteredRootNodes; private final Set<IEvalElement> subscribedFormulas; private final Map<IEvalElement, AbstractEvalResult> currentValues; private final Map<IEvalElement, AbstractEvalResult> previousValues; private final ExecutorService updater; private String filter = ""; @Inject private StatesView(final Injector injector, final CurrentTrace currentTrace, final StatusBar statusBar, final StageManager stageManager, final ResourceBundle bundle, final StopActions stopActions) { this.injector = injector; this.currentTrace = currentTrace; this.statusBar = statusBar; this.stageManager = stageManager; this.bundle = bundle; this.rootNodes = null; this.filteredRootNodes = null; this.subscribedFormulas = new HashSet<>(); this.currentValues = new HashMap<>(); this.previousValues = new HashMap<>(); this.updater = Executors.newSingleThreadExecutor(r -> new Thread(r, "StatesView Updater")); stopActions.add(this.updater::shutdownNow); stageManager.loadFXML(this, "states_view.fxml"); } @FXML private void initialize() { helpButton.setHelpContent(this.getClass()); tv.setRowFactory(view -> initTableRow()); this.tvName.setCellFactory(col -> new NameCell()); this.tvValue.setCellFactory(col -> new ValueCell(bundle, this.currentValues, true)); this.tvPreviousValue.setCellFactory(col -> new ValueCell(bundle, this.previousValues, false)); final Callback<TreeTableColumn.CellDataFeatures<StateItem<?>, StateItem<?>>, ObservableValue<StateItem<?>>> cellValueFactory = data -> Bindings .createObjectBinding(data.getValue()::getValue, this.currentTrace); this.tvName.setCellValueFactory(cellValueFactory); this.tvValue.setCellValueFactory(cellValueFactory); this.tvPreviousValue.setCellValueFactory(cellValueFactory); this.tv.getRoot().setValue(new StateItem<>("Machine (this root item should be invisible)", false)); final ChangeListener<Trace> traceChangeListener = (observable, from, to) -> { if (to == null) { this.rootNodes = null; this.filteredRootNodes = null; this.currentValues.clear(); this.previousValues.clear(); this.tv.getRoot().getChildren().clear(); } else { this.updater.execute(() -> this.updateRoot(from, to, false)); } }; traceChangeListener.changed(this.currentTrace, null, currentTrace.get()); this.currentTrace.addListener(traceChangeListener); } private TreeTableRow<StateItem<?>> initTableRow() { final TreeTableRow<StateItem<?>> row = new TreeTableRow<>(); row.itemProperty().addListener((observable, from, to) -> { row.getStyleClass().remove("changed"); if (to != null && to.getContents() instanceof ASTFormula) { final IEvalElement formula = ((ASTFormula) to.getContents()).getFormula(); final AbstractEvalResult current = this.currentValues.get(formula); final AbstractEvalResult previous = this.previousValues.get(formula); if (current != null && previous != null && (!current.getClass().equals(previous.getClass()) || current instanceof EvalResult && !((EvalResult) current).getValue().equals(((EvalResult) previous).getValue()))) { row.getStyleClass().add("changed"); } } }); final MenuItem visualizeExpressionItem = new MenuItem(bundle.getString("states.menu.visualizeExpression")); // Expression can only be shown if the row item contains an ASTFormula // and the current state is initialized. visualizeExpressionItem.disableProperty().bind(Bindings.createBooleanBinding( () -> row.getItem() == null || !(row.getItem().getContents() instanceof ASTFormula), row.itemProperty()) .or(currentTrace.currentStateProperty().initializedProperty().not())); visualizeExpressionItem.setOnAction(event -> { try { FormulaStage formulaStage = injector.getInstance(FormulaStage.class); formulaStage.showFormula((IEvalElement)((ASTFormula) row.getItem().getContents()).getFormula()); formulaStage.show(); } catch (EvaluationException | ProBError e) { LOGGER.error("Could not visualize formula", e); stageManager.makeAlert(Alert.AlertType.ERROR, String.format(bundle.getString("states.error.couldNotVisualize"), e)).showAndWait(); } }); final MenuItem showFullValueItem = new MenuItem(bundle.getString("states.menu.showFullValue")); // Full value can only be shown if the row item contains an ASTFormula, // and the corresponding value is an EvalResult. showFullValueItem.disableProperty().bind(Bindings.createBooleanBinding( () -> row.getItem() == null || !(row.getItem().getContents() instanceof ASTFormula && this.currentValues .get(((ASTFormula) row.getItem().getContents()).getFormula()) instanceof EvalResult), row.itemProperty())); showFullValueItem.setOnAction(event -> this.showFullValue(row.getItem())); final MenuItem showErrorsItem = new MenuItem(bundle.getString("states.menu.showErrors")); // Errors can only be shown if the row contains an ASTFormula whose // value is an EvaluationErrorResult. showErrorsItem.disableProperty().bind(Bindings.createBooleanBinding( () -> row.getItem() == null || !(row.getItem().getContents() instanceof ASTFormula && this.currentValues .get(((ASTFormula) row.getItem().getContents()).getFormula()) instanceof EvaluationErrorResult), row.itemProperty())); showErrorsItem.setOnAction(event -> this.showError(row.getItem())); row.contextMenuProperty().bind(Bindings.when(row.emptyProperty()).then((ContextMenu) null) .otherwise(new ContextMenu(visualizeExpressionItem, showFullValueItem, showErrorsItem))); // Double-click on an item triggers "show full value" if allowed. row.setOnMouseClicked(event -> { if (!showFullValueItem.isDisable() && event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2) { showFullValueItem.getOnAction().handle(null); } }); return row; } private static void getInitialExpandedFormulas(final List<PrologASTNode> nodes, final List<IEvalElement> formulas) { for (final PrologASTNode node : nodes) { if (node instanceof ASTFormula) { formulas.add(((ASTFormula) node).getFormula()); } if (node instanceof ASTCategory && ((ASTCategory) node).isExpanded()) { getInitialExpandedFormulas(node.getSubnodes(), formulas); } } } private static List<IEvalElement> getInitialExpandedFormulas(final List<PrologASTNode> nodes) { final List<IEvalElement> formulas = new ArrayList<>(); getInitialExpandedFormulas(nodes, formulas); return formulas; } private static void getExpandedFormulas(final List<TreeItem<StateItem<?>>> treeItems, final List<IEvalElement> formulas) { for (final TreeItem<StateItem<?>> ti : treeItems) { if (ti.getValue().getContents() instanceof ASTFormula) { formulas.add(((ASTFormula) ti.getValue().getContents()).getFormula()); } if (ti.isExpanded()) { getExpandedFormulas(ti.getChildren(), formulas); } } } private static List<IEvalElement> getExpandedFormulas(final List<TreeItem<StateItem<?>>> treeItems) { final List<IEvalElement> formulas = new ArrayList<>(); getExpandedFormulas(treeItems, formulas); return formulas; } private void subscribeFormulas(final Collection<? extends IEvalElement> formulas) { this.currentTrace.getStateSpace().subscribe(this, formulas); this.subscribedFormulas.addAll(formulas); } private void unsubscribeFormulas(final Collection<? extends IEvalElement> formulas) { if(this.currentTrace != null && this.currentTrace.getStateSpace()!= null) { this.currentTrace.getStateSpace().unsubscribe(this, formulas); } this.subscribedFormulas.removeAll(formulas); } private void updateValueMaps(final Trace trace) { this.currentValues.clear(); this.currentValues.putAll(trace.getCurrentState().getValues()); this.previousValues.clear(); if (trace.canGoBack()) { this.previousValues.putAll(trace.getPreviousState().getValues()); } } @FXML private void handleSearchButton() { filter = filterState.getText(); this.updateRoot(currentTrace.get(), currentTrace.get(), true); } private List<PrologASTNode> filterNodes(final List<PrologASTNode> nodes, final String filter) { if (filter.isEmpty()) { return nodes; } final List<PrologASTNode> filteredNodes = new ArrayList<>(); for (final PrologASTNode node : nodes) { if (node instanceof ASTFormula) { if (((ASTFormula)node).getPrettyPrint().contains(filter)) { filteredNodes.add(node); } } else if (node instanceof ASTCategory) { final List<PrologASTNode> filteredSubnodes = filterNodes(node.getSubnodes(), filter); if (!filteredSubnodes.isEmpty()) { final ASTCategory category = (ASTCategory)node; filteredNodes.add(new ASTCategory(filteredSubnodes, category.getName(), category.isExpanded(), category.isPropagated())); } } else { throw new IllegalArgumentException("Unknown node type: " + node.getClass()); } } return filteredNodes; } private void buildNodes(final TreeItem<StateItem<?>> treeItem, final List<PrologASTNode> nodes) { Objects.requireNonNull(treeItem); Objects.requireNonNull(nodes); assert treeItem.getChildren().isEmpty(); for (final PrologASTNode node : nodes) { final TreeItem<StateItem<?>> subTreeItem = new TreeItem<>(); if (node instanceof ASTCategory && ((ASTCategory) node).isExpanded()) { subTreeItem.setExpanded(true); } treeItem.getChildren().add(subTreeItem); subTreeItem.setValue(new StateItem<>(node, false)); subTreeItem.expandedProperty().addListener((o, from, to) -> { final List<IEvalElement> formulas = getExpandedFormulas(subTreeItem.getChildren()); if (to) { this.subscribeFormulas(formulas); } else { this.unsubscribeFormulas(formulas); } this.updateValueMaps(this.currentTrace.get()); }); buildNodes(subTreeItem, node.getSubnodes()); } } private void updateNodes(final TreeItem<StateItem<?>> treeItem, final List<PrologASTNode> nodes) { Objects.requireNonNull(treeItem); Objects.requireNonNull(nodes); assert treeItem.getChildren().size() == nodes.size(); for (int i = 0; i < nodes.size(); i++) { final TreeItem<StateItem<?>> subTreeItem = treeItem.getChildren().get(i); final PrologASTNode node = nodes.get(i); subTreeItem.setValue(new StateItem<>(node, false)); updateNodes(subTreeItem, node.getSubnodes()); } } private void updateRoot(final Trace from, final Trace to, final boolean filterChanged) { final int selectedRow = tv.getSelectionModel().getSelectedIndex(); Platform.runLater(() -> { this.statusBar.setStatesViewUpdating(true); this.tv.setDisable(true); }); // If the model has changed or the machine structure hasn't been loaded // yet, update it and rebuild the tree view. final boolean reloadRootNodes = this.rootNodes == null || from == null || !from.getModel().equals(to.getModel()); if (reloadRootNodes) { final GetMachineStructureCommand cmd = new GetMachineStructureCommand(); to.getStateSpace().execute(cmd); this.rootNodes = cmd.getPrologASTList(); } // If the root nodes were reloaded or the filter has changed, update the filtered node list. if (reloadRootNodes || filterChanged) { this.filteredRootNodes = filterNodes(this.rootNodes, this.filter); this.unsubscribeFormulas(this.subscribedFormulas); this.subscribeFormulas(getInitialExpandedFormulas(this.filteredRootNodes)); } this.updateValueMaps(to); Platform.runLater(() -> { if (reloadRootNodes || filterChanged) { this.tvRootItem.getChildren().clear(); buildNodes(this.tvRootItem, this.filteredRootNodes); } else { updateNodes(this.tvRootItem, this.filteredRootNodes); } this.tv.refresh(); this.tv.getSelectionModel().select(selectedRow); this.tv.setDisable(false); this.statusBar.setStatesViewUpdating(false); }); } private void showError(StateItem<?> stateItem) { final FullValueStage stage = injector.getInstance(FullValueStage.class); if (stateItem.getContents() instanceof ASTFormula) { final AbstractEvalResult result = this.currentValues .get(((ASTFormula) stateItem.getContents()).getFormula()); if (result instanceof EvaluationErrorResult) { stage.setTitle(stateItem.toString()); stage.setCurrentValue(String.join("\n", ((EvaluationErrorResult) result).getErrors())); stage.setFormattingEnabled(false); stage.show(); } else { throw new IllegalArgumentException("Row item result is not an error: " + result.getClass()); } } else { throw new IllegalArgumentException("Invalid row item type: " + stateItem.getClass()); } } private static String getResultValue(final ASTFormula element, final State state) { final AbstractEvalResult result = state.eval(element.getFormula(FormulaExpand.EXPAND)); return result instanceof EvalResult ? ((EvalResult) result).getValue() : null; } private void showFullValue(StateItem<?> stateItem) { final FullValueStage stage = injector.getInstance(FullValueStage.class); if (stateItem.getContents() instanceof ASTFormula) { final ASTFormula element = (ASTFormula) stateItem.getContents(); stage.setTitle(element.getFormula().toString()); stage.setCurrentValue(getResultValue(element, this.currentTrace.getCurrentState())); stage.setPreviousValue( this.currentTrace.canGoBack() ? getResultValue(element, this.currentTrace.get().getPreviousState()) : null); stage.setFormattingEnabled(true); } else { throw new IllegalArgumentException("Invalid row item type: " + stateItem.getClass()); } stage.show(); } public TreeTableView<StateItem<?>> getTable() { return tv; } }
package edu.chl.proton.model; import javafx.scene.text.Text; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.*; public class Document { // Lika = document private Cursor cursor; private File file; private List<String> lines = new ArrayList<String>(); private List<Parts> parts = new ArrayList<Parts>(); DocTypeInterface docType; public Document(DocumentType type){ if(type == DocumentType.MARKDOWN){ docType = new Markdown(lines, parts); } else if(type == DocumentType.ASSIGNMENT){ // TODO } else if(type == DocumentType.PLAIN){ // TODO } else if(type == DocumentType.SLIDE){ // TODO } } public Document(String name){ String extension = name.substring(name.lastIndexOf(".") + 1, name.length()); } protected Cursor getCursor(){ return this.cursor; } protected void setCursor(Cursor cursor){ this.cursor = cursor; } protected File getFile(){ return this.file; } protected void setFile(File file){ this.file = file; } protected void addFile(String path){ // file.setPath(path); // setFile(rootFolder.getFileFromPath(path)); ??? } protected void addParts(Parts parts){ this.parts.add(parts); } protected void removeParts(int index){ parts.remove(index); } protected void removeAllParts(){ parts.clear(); } protected void addLines(String lines){ this.lines.add(lines); } protected void removeLines(int index){ lines.remove(index); } protected void removeAllLines(){ lines.clear(); } protected void insertChar(char ch){ int row = cursor.getPosition().getY(); int col = cursor.getPosition().getX(); // check if Enter was the key pressed if(ch == '\r'){ cursor.setPosition(row + 1, col); } else { String tmp = lines.get(row); StringBuilder str = new StringBuilder(tmp); str.insert(col, ch); lines.set(row, tmp); cursor.setPosition(row, col + 1); } } public List<Text> getText(){ return docType.getText(); } protected void setText(List<String> text){ for(String str : text){ lines.add(str); } } /* // Returns a formated List, where every lsit item is a row in the document protected List<Text> getText(){ List<Text> text = new ArrayList<Text>(); for(String str : lines){ Text newText = new Text(str); text.add(newText); } return text; }*/ protected void save(){ file.save(); } // Aqcuires the text from the file we opened. protected void aqcuireText(){ // This will reference one line at a time String line = null; try { // FileReader reads text files in the default encoding. FileReader fileReader = new FileReader(file.getName()); // Always wrap FileReader in BufferedReader. BufferedReader bufferedReader = new BufferedReader(fileReader); while((line = bufferedReader.readLine()) != null) { lines.add(line); } // Close file. bufferedReader.close(); } catch(FileNotFoundException ex) { System.out.println( "Unable to open file '" + file.getName() + "'"); } catch(IOException ex) { System.out.println( "Error reading file '" + file.getName() + "'"); } } }
package fr.electrogames.blocks; import fr.electrogames.Reference; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraftforge.fml.common.registry.GameRegistry; public class Blocks { public static Block Tablette; public static Block Window; public static void init() { Tablette = new BlockTablette(Material.wood).setUnlocalizedName( "table").setCreativeTab(CreativeTabs.tabDecorations); Window = new BlockWindow(Material.glass).setUnlocalizedName("window").setCreativeTab(CreativeTabs.tabBlock); } public static void register() { GameRegistry.registerBlock(Tablette, Tablette .getUnlocalizedName().substring(5)); GameRegistry.registerBlock(Window, Window.getUnlocalizedName().substring(5)); } public static void registerRenders() { registerRender(Tablette); registerRender(Window); } public static void registerRender(Block block) { Item item = Item.getItemFromBlock(block); Minecraft .getMinecraft() .getRenderItem() .getItemModelMesher() .register( item, 0, new ModelResourceLocation(Reference.ModID + ":" + item.getUnlocalizedName().substring(5), "inventory")); } }
package in.twizmwaz.cardinal; import com.google.common.collect.Lists; import ee.ellytr.chat.LocaleRegistry; import ee.ellytr.command.CommandExecutor; import ee.ellytr.command.CommandRegistry; import ee.ellytr.command.ProviderRegistry; import ee.ellytr.command.exception.CommandException; import in.twizmwaz.cardinal.command.CommandCardinal; import in.twizmwaz.cardinal.command.CommandCycle; import in.twizmwaz.cardinal.command.CommandJoin; import in.twizmwaz.cardinal.command.CommandNext; import in.twizmwaz.cardinal.command.CommandStart; import in.twizmwaz.cardinal.command.provider.LoadedMapProvider; import in.twizmwaz.cardinal.command.provider.TeamProvider; import in.twizmwaz.cardinal.event.matchthread.MatchThreadMakeEvent; import in.twizmwaz.cardinal.match.Match; import in.twizmwaz.cardinal.match.MatchThread; import in.twizmwaz.cardinal.module.Module; import in.twizmwaz.cardinal.module.ModuleHandler; import in.twizmwaz.cardinal.module.ModuleLoader; import in.twizmwaz.cardinal.module.ModuleRegistry; import in.twizmwaz.cardinal.module.event.ModuleLoadCompleteEvent; import in.twizmwaz.cardinal.module.repository.LoadedMap; import in.twizmwaz.cardinal.module.team.Team; import lombok.AccessLevel; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import org.apache.commons.lang.Validate; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Listener; import org.bukkit.plugin.java.JavaPlugin; import java.io.IOException; import java.util.List; import java.util.Locale; import java.util.logging.Logger; @Getter public final class Cardinal extends JavaPlugin { @Getter private static Cardinal instance; private ModuleLoader moduleLoader; @Setter(AccessLevel.PRIVATE) private ModuleHandler moduleHandler; private List<MatchThread> matchThreads; private CommandRegistry commandRegistry; private CommandExecutor commandExecutor; /** * Creates a new Cardinal object. */ public Cardinal() { if (instance != null) { throw new IllegalStateException("The Cardinal object has already been created."); } instance = this; matchThreads = Lists.newArrayList(); MatchThread matchThread = new MatchThread(); matchThreads.add(matchThread); Bukkit.getPluginManager().callEvent(new MatchThreadMakeEvent(matchThread)); registerCommands(); registerLocales(); } @Override public void onEnable() { Validate.notNull(Cardinal.getInstance()); commandRegistry.register(); if (!getDataFolder().exists()) { getDataFolder().mkdir(); } moduleLoader = new ModuleLoader(); try { moduleLoader.findEntries(getFile()); } catch (IOException ex) { getLogger().severe("A fatal exception occurred while trying to load internal modules."); ex.printStackTrace(); setEnabled(false); return; } Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> { ModuleRegistry registry = new ModuleRegistry(moduleLoader.makeModules(moduleLoader.getModuleEntries())); setModuleHandler(new ModuleHandler(registry)); Bukkit.getPluginManager().callEvent(new ModuleLoadCompleteEvent(moduleHandler)); } ); this.getLogger().info("Cardinal has loaded"); } @Override public void onDisable() { } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { try { commandExecutor.execute(command.getName(), sender, args); } catch (CommandException ex) { ex.printStackTrace(); } return true; } @NonNull public static Logger getPluginLogger() { return Cardinal.getInstance().getLogger(); } public static <T extends Module> T getModule(@NonNull Class<T> clazz) { return instance.moduleHandler.getRegistry().getModule(clazz); } public static void registerEvents(Listener listener) { Bukkit.getPluginManager().registerEvents(listener, getInstance()); } private void registerCommands() { commandRegistry = new CommandRegistry(this); commandRegistry.addClass(CommandCardinal.class); commandRegistry.addClass(CommandCycle.class); commandRegistry.addClass(CommandJoin.class); commandRegistry.addClass(CommandNext.class); commandRegistry.addClass(CommandStart.class); ProviderRegistry providerRegistry = commandRegistry.getProviderRegistry(); providerRegistry.registerProvider(Team.class, new TeamProvider()); providerRegistry.registerProvider(LoadedMap.class, new LoadedMapProvider()); commandRegistry.register(); commandExecutor = new CommandExecutor(commandRegistry.getFactory()); } /** * @param who A command sender. * @return The match thread that contains this player. */ @NonNull public static MatchThread getMatchThread(@NonNull CommandSender who) { if (!(who instanceof Player)) { return getInstance().getMatchThreads().get(0); } Player player = (Player) who; for (MatchThread matchThread : getInstance().getMatchThreads()) { if (matchThread.hasPlayer(player)) { return matchThread; } } return null; } /** * @param match The match. * @return The match thread that is running this match. */ public static MatchThread getMatchThread(@NonNull Match match) { for (MatchThread matchThread : getInstance().getMatchThreads()) { if (matchThread.getCurrentMatch().equals(match)) { return matchThread; } } return null; } /** * @param player The player. * @return The match that the player is in. */ @NonNull public static Match getMatch(@NonNull Player player) { MatchThread matchThread = getMatchThread(player); if (matchThread == null) { return null; } return matchThread.getCurrentMatch(); } /** * @param world The world. * @return The match that uses that world. */ @NonNull public static Match getMatch(@NonNull World world) { for (MatchThread matchThread : getInstance().getMatchThreads()) { if (matchThread.getCurrentMatch().getWorld().equals(world)) { return matchThread.getCurrentMatch(); } } return null; } private void registerLocales() { LocaleRegistry registry = new LocaleRegistry(); registry.addLocaleFile(new Locale("en", "US"), getResource("lang/cardinal/en_US.properties")); registry.register(); } }
package ingest.messaging; import ingest.database.PersistMetadata; import ingest.inspect.Inspector; import java.io.IOException; import java.util.Arrays; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.PostConstruct; import messaging.job.JobMessageFactory; import messaging.job.KafkaClientFactory; import model.job.Job; import model.job.JobProgress; import model.job.metadata.ResourceMetadata; import model.job.type.IngestJob; import model.status.StatusUpdate; import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.common.errors.WakeupException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; import com.mongodb.MongoException; /** * Main listener class for Ingest Jobs. Handles an incoming Ingest Job request * by indexing metadata, storing files, and updating appropriate database * tables. * * @author Patrick.Doody * */ @Component public class IngestWorker { @Autowired private PersistMetadata metadataPersist; @Value("${kafka.host}") private String KAFKA_HOST; @Value("${kafka.port}") private String KAFKA_PORT; @Value("${kafka.group}") private String KAFKA_GROUP; private Producer<String, String> producer; private Consumer<String, String> consumer; private final AtomicBoolean closed = new AtomicBoolean(false); private Inspector inspector = new Inspector(); public IngestWorker() { } @PostConstruct public void initialize() { // Initialize the Kafka consumer/producer producer = KafkaClientFactory.getProducer(KAFKA_HOST, KAFKA_PORT); consumer = KafkaClientFactory.getConsumer(KAFKA_HOST, KAFKA_PORT, KAFKA_GROUP); // Listen for events listen(); } /** * Begins listening for events. */ public void listen() { try { consumer.subscribe(Arrays.asList(JobMessageFactory.CREATE_JOB_TOPIC_NAME)); while (!closed.get()) { ConsumerRecords<String, String> consumerRecords = consumer.poll(1000); // Handle new Messages on this topic. for (ConsumerRecord<String, String> consumerRecord : consumerRecords) { System.out.println("Processing Ingest Message " + consumerRecord.topic() + " with key " + consumerRecord.key()); // Wrap the JobRequest in the Job object try { ObjectMapper mapper = new ObjectMapper(); Job job = mapper.readValue(consumerRecord.value(), Job.class); // Process Ingest Jobs if (job.jobType instanceof IngestJob) { // Update Status on Handling JobProgress jobProgress = new JobProgress(0); StatusUpdate statusUpdate = new StatusUpdate(StatusUpdate.STATUS_RUNNING, jobProgress); producer.send(JobMessageFactory.getUpdateStatusMessage(consumerRecord.key(), statusUpdate)); // Process the Job based on its information and // retrieve any available metadata ResourceMetadata metadata = inspector.inspect((IngestJob) job.jobType); // Store the Metadata in the MongoDB metadata // collection metadataPersist.insertMetadata(metadata); // If applicable, store the spatial information in // the Piazza databases. // TODO: Database stuff // Update Status when Complete jobProgress.percentComplete = 100; statusUpdate = new StatusUpdate(StatusUpdate.STATUS_SUCCESS, jobProgress); producer.send(JobMessageFactory.getUpdateStatusMessage(consumerRecord.key(), statusUpdate)); } } catch (IOException jsonException) { System.out.println("Error Parsing Ingest Job Message."); jsonException.printStackTrace(); } catch (MongoException mongoException) { System.out.println("Error committing Metadata object to Mongo Collections: " + mongoException.getMessage()); mongoException.printStackTrace(); } catch (Exception exception) { System.out.println("An unexpected error occurred while processing the Job Message: " + exception.getMessage()); exception.printStackTrace(); } } } } catch (WakeupException exception) { // Ignore exception if closing if (!closed.get()) { throw exception; } } finally { consumer.close(); } } }
package io.kamax.matrix.json; import com.google.gson.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java8.util.Optional; import java8.util.function.Consumer; import java8.util.stream.Collectors; import java8.util.stream.StreamSupport; public class GsonUtil { private static Gson instance = build(); private static Gson instancePretty = buildPretty(); private static GsonBuilder buildImpl() { return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .disableHtmlEscaping(); } public static Gson buildPretty() { return buildImpl().setPrettyPrinting().create(); } public static Gson build() { return buildImpl().create(); } public static JsonArray asArray(List<JsonElement> elements) { JsonArray a = new JsonArray(); elements.forEach(a::add); return a; } public static JsonArray asArrayObj(List<? extends Object> elements) { return asArray(StreamSupport.stream(elements).map(e -> get().toJsonTree(e)).collect(Collectors.toList())); } public static JsonArray asArray(String... elements) { return asArray( StreamSupport.stream(Arrays.asList(elements)).map(JsonPrimitive::new).collect(Collectors.toList())); } public static JsonArray asArray(Collection<String> elements) { JsonArray a = new JsonArray(); elements.forEach(a::add); return a; } public static <T> List<T> asList(JsonArray a, Class<T> c) { List<T> l = new ArrayList<>(); a.forEach(v -> l.add(GsonUtil.get().fromJson(v, c))); return l; } public static <T> List<T> asList(JsonObject obj, String member, Class<T> c) { return asList(getArray(obj, member), c); } public static JsonObject makeObj(Object o) { return instance.toJsonTree(o).getAsJsonObject(); } public static JsonObject makeObj(String key, Object value) { return makeObj(key, instance.toJsonTree(value)); } public static JsonObject makeObj(String key, JsonElement el) { JsonObject obj = new JsonObject(); obj.add(key, el); return obj; } public static JsonObject makeObj(Consumer<JsonObject> consumer) { JsonObject obj = new JsonObject(); consumer.accept(obj); return obj; } public static Gson get() { return instance; } public static Gson getPretty() { return instancePretty; } public static String getPrettyForLog(Object o) { return System.lineSeparator() + getPretty().toJson(o); } public static JsonElement parse(String s) { try { return new JsonParser().parse(s); } catch (JsonParseException e) { throw new InvalidJsonException(e); } } public static JsonObject parseObj(String s) { try { return parse(s).getAsJsonObject(); } catch (IllegalStateException e) { throw new InvalidJsonException("Not an object"); } } public static JsonArray getArray(JsonObject obj, String member) { return findArray(obj, member).orElseThrow(() -> new InvalidJsonException("Not an array")); } public static JsonObject getObj(JsonObject obj, String member) { return findObj(obj, member).orElseThrow(() -> new InvalidJsonException("No object for member " + member)); } public static Optional<String> findString(JsonObject o, String key) { return findPrimitive(o, key).map(JsonPrimitive::getAsString); } public static String getStringOrNull(JsonObject o, String key) { JsonElement el = o.get(key); if (el != null && el.isJsonPrimitive()) { return el.getAsString(); } else { return null; } } public static String getStringOrThrow(JsonObject obj, String member) { if (!obj.has(member)) { throw new InvalidJsonException(member + " key is missing"); } return obj.get(member).getAsString(); } public static Optional<JsonElement> findElement(JsonObject o, String key) { return Optional.ofNullable(o.get(key)); } public static Optional<JsonPrimitive> findPrimitive(JsonObject o, String key) { return findElement(o, key).map(el -> el.isJsonPrimitive() ? el.getAsJsonPrimitive() : null); } public static JsonPrimitive getPrimitive(JsonObject o, String key) { return findPrimitive(o, key).orElseThrow(() -> new InvalidJsonException("No primitive value for key " + key)); } public static Optional<Long> findLong(JsonObject o, String key) { return findPrimitive(o, key).map(JsonPrimitive::getAsLong); } public static long getLong(JsonObject o, String key) { return findLong(o, key).orElseThrow(() -> new InvalidJsonException("No numeric value for key " + key)); } public static Optional<JsonObject> findObj(JsonObject o, String key) { if (!o.has(key)) { return Optional.empty(); } return Optional.ofNullable(o.getAsJsonObject(key)); } public static Optional<JsonArray> findArray(JsonObject o, String key) { return findElement(o, key).filter(JsonElement::isJsonArray).map(JsonElement::getAsJsonArray); } }
package io.metacake.core; import io.metacake.core.common.window.CakeWindow; import io.metacake.core.input.InputDeviceName; import io.metacake.core.input.InputSystem; import io.metacake.core.input.system.InputDevice; import io.metacake.core.input.system.InputLayer; import io.metacake.core.output.OutputDeviceName; import io.metacake.core.output.OutputSystem; import io.metacake.core.output.system.OutputDevice; import io.metacake.core.output.system.OutputLayer; import io.metacake.core.process.GameRunner; import io.metacake.core.process.state.GameState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; /** * This class handles bootstrapping and launching the game. * <p> * The Bootstrapper sets up all of the necessary pieces of the game and does any binding that is necessary. * * @author florence * @author rpless */ public class Bootstrapper { public static final long DEFAULT_LOOP_MILLIS = 50; private static final Logger logger = LoggerFactory.getLogger(Bootstrapper.class); private CakeWindow window; private Map<InputDeviceName,InputDevice> inputs; private Map<OutputDeviceName, OutputDevice> outputs; private GameState initialState; private long loopTime; Bootstrapper(CakeWindow window, Map<InputDeviceName,InputDevice> inputs, Map<OutputDeviceName, OutputDevice> outputs, GameState g) { this(window, inputs, outputs, g, DEFAULT_LOOP_MILLIS); } Bootstrapper(CakeWindow window, Map<InputDeviceName,InputDevice> inputs, Map<OutputDeviceName, OutputDevice> outputs, GameState g, long loopTime) { this.window = window; this.inputs = inputs; this.outputs = outputs; this.initialState = g; this.loopTime = loopTime; } /** * Invokes the the binding phases of a game creation and then launches the game. */ public void setupAndLaunchGame() { GameRunner r = this.bootstrapSystem(); r.mainLoop(initialState, loopTime); } /** * Create a GameRunner that is ready to go * @return The game runner */ GameRunner bootstrapSystem() { this.bootstrapUserObjects(); InputSystem i = this.bootstrapInputSystem(); OutputSystem o = this.bootstrapOutputSystem(); GameRunner r = this.bootstrapProcessLayer(i, o); logger.info("starting i/o loops"); o.startOutputLoops(); i.startInputLoops(); return r; } /** * Invokes binding operations for all InputDevices and InputDevices */ void bootstrapUserObjects() { logger.info("Bootstrapping user objects"); inputs.values().forEach(i -> i.bind(window)); outputs.values().forEach(i -> i.bind(window)); } /** * @return Returns an InputSystem that has been set up and bound. */ InputSystem bootstrapInputSystem() { logger.info("Bootstrapping input system from user objects"); return new InputLayer(inputs); } /** * @return Returns an OutputSystem that has been set up and bound. */ OutputSystem bootstrapOutputSystem() { logger.info("Bootstrapping output system from user objects"); return new OutputLayer(outputs); } /** * @param i the InputSystem for the game * @param o the OutputSystem for the game * @return a GameRunner that has been bound to the Input and Output Systems and is ready to be launched */ GameRunner bootstrapProcessLayer(InputSystem i, OutputSystem o) { logger.info("bootstrapping process layer from i/o system"); return new GameRunner(i, o, window); } }
package io.redis.client; import static org.testng.Assert.assertEquals; import java.util.concurrent.TimeUnit; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; /** * JedisPoolTest.java{@link JedisPool} tutorial * * @author huagang.li 20141113 11:45:53 */ public class JedisPoolTest { private JedisPool pool; @BeforeClass public void init() { GenericObjectPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMinIdle(1); poolConfig.setTestOnBorrow(true); String host = "127.0.0.1"; int port = 6381; int timeout = (int) TimeUnit.MILLISECONDS.toMillis(100L); this.pool = new JedisPool(poolConfig, host, port, timeout); } /** * Strings */ @Test public void doString() { Jedis jedis = this.pool.getResource(); String key = "hello"; String value = "world"; // get assertEquals(jedis.get(key), null); // set String statusCode = jedis.set(key, value); assertEquals(statusCode, "OK"); assertEquals(jedis.get(key), "world"); // delete Long delNum = jedis.del(key); assertEquals(delNum.longValue(), 1L); } @AfterClass public void destroy() { if (this.pool != null) { this.pool.close(); } } }
package net.iponweb.disthene; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.carbon.CarbonServer; import net.iponweb.disthene.config.AggregationConfiguration; import net.iponweb.disthene.config.BlackListConfiguration; import net.iponweb.disthene.config.DistheneConfiguration; import net.iponweb.disthene.service.aggregate.RollupAggregator; import net.iponweb.disthene.service.aggregate.SumAggregator; import net.iponweb.disthene.service.blacklist.BlackList; import net.iponweb.disthene.service.events.DistheneEvent; import net.iponweb.disthene.service.general.GeneralStore; import net.iponweb.disthene.service.index.ESIndexStore; import net.iponweb.disthene.service.stats.Stats; import net.iponweb.disthene.service.store.CassandraMetricStore; import org.apache.commons.cli.*; import org.apache.log4j.Logger; import org.yaml.snakeyaml.Yaml; import sun.misc.Signal; import sun.misc.SignalHandler; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Map; /** * @author Andrei Ivanov */ public class Disthene { private static Logger logger; private static final String DEFAULT_CONFIG_LOCATION = "/etc/disthene/disthene.yaml"; private static final String DEFAULT_BLACKLIST_LOCATION = "/etc/disthene/blacklist.yaml"; private static final String DEFAULT_AGGREGATION_CONFIG_LOCATION = "/etc/disthene/aggregator.yaml"; private static final String DEFAULT_LOG_CONFIG_LOCATION = "/etc/disthene/disthene-log4j.xml"; private String configLocation; private String blacklistLocation; private String aggregationConfigLocation; private MBassador<DistheneEvent> bus; private BlackList blackList; private GeneralStore generalStore; private Stats stats; private ESIndexStore esIndexStore; private CassandraMetricStore cassandraMetricStore; private SumAggregator sumAggregator; private RollupAggregator rollupAggregator; private CarbonServer carbonServer; public Disthene(String configLocation, String blacklistLocation, String aggregationConfigLocation) { this.configLocation = configLocation; this.blacklistLocation = blacklistLocation; this.aggregationConfigLocation = aggregationConfigLocation; } private void run() { try { Yaml yaml = new Yaml(); InputStream in = Files.newInputStream(Paths.get(configLocation)); DistheneConfiguration distheneConfiguration = yaml.loadAs(in, DistheneConfiguration.class); in.close(); logger.info("Running with the following config: " + distheneConfiguration.toString()); logger.info("Creating dispatcher"); bus = new MBassador<>(); logger.info("Loading blacklists"); in = Files.newInputStream(Paths.get(blacklistLocation)); BlackListConfiguration blackListConfiguration = new BlackListConfiguration((Map<String, List<String>>) yaml.load(in)); in.close(); logger.debug("Running with the following blacklist: " + blackListConfiguration.toString()); blackList = new BlackList(blackListConfiguration); logger.info("Creating general store"); generalStore = new GeneralStore(bus, blackList); logger.info("Creating stats"); stats = new Stats(bus, distheneConfiguration.getStats(), distheneConfiguration.getCarbon().getBaseRollup()); logger.info("Creating ES index store"); esIndexStore = new ESIndexStore(distheneConfiguration, bus); logger.info("Creating C* metric store"); cassandraMetricStore = new CassandraMetricStore(distheneConfiguration.getStore(), bus); logger.info("Loading aggregation rules"); in = Files.newInputStream(Paths.get(aggregationConfigLocation)); AggregationConfiguration aggregationConfiguration = new AggregationConfiguration((Map<String, Map<String, String>>) yaml.load(in)); in.close(); logger.debug("Running with the following aggregation rule set: " + aggregationConfiguration.toString()); logger.info("Creating sum aggregator"); sumAggregator = new SumAggregator(bus, distheneConfiguration, aggregationConfiguration, blackList); logger.info("Creating rollup aggregator"); rollupAggregator = new RollupAggregator(bus, distheneConfiguration, distheneConfiguration.getCarbon().getRollups()); logger.info("Starting carbon"); carbonServer = new CarbonServer(distheneConfiguration, bus); carbonServer.run(); // adding signal handlers Signal.handle(new Signal("HUP"), new SighupSignalHandler()); Signal.handle(new Signal("TERM"), new SigtermSignalHandler()); } catch (IOException e) { logger.error(e); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) throws MalformedURLException { Options options = new Options(); options.addOption("c", "config", true, "config location"); options.addOption("l", "log-config", true, "log config location"); options.addOption("b", "blacklist", true, "blacklist location"); options.addOption("a", "agg-config", true, "aggregation config location"); CommandLineParser parser = new GnuParser(); try { CommandLine commandLine = parser.parse(options, args); System.getProperties().setProperty("log4j.configuration", "file:" + commandLine.getOptionValue("l", DEFAULT_LOG_CONFIG_LOCATION)); logger = Logger.getLogger(Disthene.class); new Disthene(commandLine.getOptionValue("c", DEFAULT_CONFIG_LOCATION), commandLine.getOptionValue("b", DEFAULT_BLACKLIST_LOCATION), commandLine.getOptionValue("a", DEFAULT_AGGREGATION_CONFIG_LOCATION) ).run(); } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Disthene", options); } catch (Exception e) { System.out.println("Start failed"); e.printStackTrace(); } } private class SighupSignalHandler implements SignalHandler { @Override public void handle(Signal signal) { logger.info("Received sighup"); logger.info("Reloading blacklists"); try { Yaml yaml = new Yaml(); InputStream in = Files.newInputStream(Paths.get(blacklistLocation)); BlackListConfiguration blackListConfiguration = new BlackListConfiguration((Map<String, List<String>>) yaml.load(in)); in.close(); blackList.setRules(blackListConfiguration); logger.debug("Reloaded blacklist: " + blackListConfiguration.toString()); } catch (Exception e) { logger.error("Reloading blacklists failed"); logger.error(e); } logger.info("Reloading aggregation rules"); try { Yaml yaml = new Yaml(); InputStream in = Files.newInputStream(Paths.get(aggregationConfigLocation)); AggregationConfiguration aggregationConfiguration = new AggregationConfiguration((Map<String, Map<String, String>>) yaml.load(in)); in.close(); sumAggregator.setAggregationConfiguration(aggregationConfiguration); logger.debug("Reloaded aggregation rules: " + aggregationConfiguration.toString()); } catch (Exception e) { logger.error("Reloading aggregation rules failed"); logger.error(e); } } } private class SigtermSignalHandler implements SignalHandler { @Override public void handle(Signal signal) { logger.info("Shutting down carbon server"); carbonServer.shutdown(); logger.info("Shutting down dispatcher"); bus.shutdown(); logger.info("Shutting down sum aggregator"); sumAggregator.shutdown(); logger.info("Shutting down rollup aggregator"); rollupAggregator.shutdown(); logger.info("Shutting down ES service"); esIndexStore.shutdown(); logger.info("Shutting down C* service"); cassandraMetricStore.shutdown(); logger.info("Shutdown complete"); System.exit(0); } } }
package net.sf.jabref.label; import net.sf.jabref.BibtexEntry; public interface LabelRule{ // the default rule is that it simply returns what it was given public String applyRule(BibtexEntry oldEntry) ; }
package net.zero918nobita.Xemime; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.TreeMap; /** * * @author Kodai Matsumoto */ public class Main { private static Parser parser; private static HashMap<X_Symbol, X_Address> globalSymbols = new HashMap<>(); private static TreeMap<X_Address, X_Code> entities = new TreeMap<X_Address, X_Code>() {{ put(new X_Address(0,0), X_Bool.T); }}; static Frame frame = new Frame(); static void loadLocalFrame(HashMap<X_Symbol, X_Address> table) { frame.loadLocalFrame(table); } static void unloadLocalFrame() { frame.unloadLocalFrame(); } static boolean hasSymbol(X_Symbol sym) { return frame.hasSymbol(sym) || globalSymbols.containsKey(sym); } /** * * @param sym * @return */ static X_Address getAddressOfSymbol(X_Symbol sym) { return (frame.hasSymbol(sym)) ? frame.getAddressOfSymbol(sym) : globalSymbols.get(sym); } /** * * @param sym * @return */ static X_Code getValueOfSymbol(X_Symbol sym) { if (frame.hasSymbol(sym)) { return frame.getValueOfSymbol(sym, entities); } else { return (globalSymbols.containsKey(sym)) ? globalSymbols.get(sym).fetch(entities) : null; } } /** * * @param address * @return */ static X_Code getValueOfReference(X_Address address) { return entities.get(address); } /** * * @param sym * @param ref */ static void setAddress(X_Symbol sym, X_Address ref) throws Exception { if (frame.hasSymbol(sym)) { frame.setAddress(sym, ref); return; } if (!globalSymbols.containsKey(sym)) throw new Exception(parser.getLocation() + ": `" + sym.getName() + "` "); globalSymbols.put(sym, ref); } /** * * @param sym * @param obj * @throws Exception */ static void setValue(X_Symbol sym, X_Code obj) throws Exception { if (frame.hasSymbol(sym)) { frame.setValue(sym, obj); return; } X_Address ref = register(obj); if (!globalSymbols.containsKey(sym)) throw new Exception(parser.getLocation() + ": `" + sym.getName() + "` "); globalSymbols.put(sym, ref); } /** * * @param sym * @param ref */ static void defAddress(X_Symbol sym, X_Address ref) throws Exception { if (frame.numberOfLayers() != 0) { frame.defAddress(sym, ref); return; } globalSymbols.put(sym, ref); } /** * * @param sym * @param obj */ static void defValue(X_Symbol sym, X_Code obj) throws Exception { if (frame.numberOfLayers() != 0) { frame.defValue(sym, obj); return; } X_Address ref = register(obj); globalSymbols.put(sym, ref); } static X_Address register(X_Code obj) { entities.put(new X_Address(0,entities.lastKey().getAddress() + 1), obj); return new X_Address(0, entities.lastKey().getAddress()); } public static void main(String[] args) { if (args.length >= 2) { usage(); System.out.println(System.lineSeparator() + "Usage: java -jar Xemime.jar [source file name]"); return; } globalSymbols.put(X_Symbol.intern(0, "Core"), register(new X_Core(0))); globalSymbols.put(X_Symbol.intern(0, "Object"), register(new X_Object(0))); try { parser = new Parser(); BufferedReader in; if (args.length == 0) { usage(); in = new BufferedReader(new InputStreamReader(System.in)); System.out.print(System.lineSeparator() + "[1]> "); String line; while (true) { line = in.readLine(); if (line != null && !line.equals("")) { X_Code obj = parser.parse(line); if (obj == null) break; System.out.println(obj.run().toString()); System.out.print("[" + (obj.getLocation() + 1) + "]> "); parser.goDown(1); } else if (line == null) { break; } } } else { in = new BufferedReader(new FileReader(args[0])); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = in.readLine()) != null) { stringBuilder.append(line); stringBuilder.append('\n'); } X_Code code = parser.parse("{" + stringBuilder.toString() + "};"); code.run(); } in.close(); } catch(Exception e) { e.printStackTrace(); } } private static void usage() { System.out.println(" _ __ _ \n" + " | |/ /__ ____ ___ (_)___ ___ ___ \n" + " | / _ \\/ __ `__ \\/ / __ `__ \\/ _ \\\n" + " / / __/ / / / / / / / / / / / __/\n" + "/_/|_\\___/_/ /_/ /_/_/_/ /_/ /_/\\___/ \n\n" + "Xemime Version 1.0.0 2017-08-07"); } private static class X_Object extends X_Handler { X_Object(int n) { super(n); setMember(X_Symbol.intern(0, "clone"), new X_Clone()); } private static class X_Clone extends X_Native { X_Clone() { super(0, 0); } @Override protected X_Address exec(ArrayList<X_Code> params) throws Exception { return Main.register(params.get(0).run()); } } } private static class X_Core extends X_Handler { X_Core(int n) { super(n); setMember(X_Symbol.intern(0, "if"), new X_If()); setMember(X_Symbol.intern(0, "print"), new X_Print()); setMember(X_Symbol.intern(0, "println"), new X_Println()); setMember(X_Symbol.intern(0, "exit"), new X_Exit()); } private static class X_Exit extends X_Native { X_Exit() { super(0, 0); } @Override protected X_Code exec(ArrayList<X_Code> params) throws Exception { System.exit(0); return new X_Int(0, 0); } } private static class X_Print extends X_Native { X_Print() { super(0, 1); } @Override protected X_Code exec(ArrayList<X_Code> params) throws Exception { X_Code o = params.get(1).run(); System.out.print(o); return o; } } private static class X_Println extends X_Native { X_Println() { super(0, 1); } @Override protected X_Code exec(ArrayList<X_Code> params) throws Exception { X_Code o = params.get(1).run(); System.out.println(o); return o; } } private static class X_If extends X_Native { X_If(){ super(0, 3); } @Override protected X_Code exec(ArrayList<X_Code> params) throws Exception { return (params.get(1).run().equals(X_Bool.Nil)) ? params.get(3).run() : params.get(2).run(); } } } }
package omtteam.omlib.util; import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.common.UsernameCache; import omtteam.omlib.handler.ConfigHandler; import omtteam.omlib.handler.OwnerShareHandler; import omtteam.omlib.tileentity.ITrustedPlayersManager; import omtteam.omlib.tileentity.TileEntityOwnedBlock; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import javax.annotation.ParametersAreNullableByDefault; import java.util.Map; import java.util.UUID; import static omtteam.omlib.handler.ConfigHandler.offlineModeSupport; @SuppressWarnings("unused") public class PlayerUtil { public static boolean isPlayerOP(EntityPlayer player) { return player.getServer() != null && player.getServer().getPlayerList().getOppedPlayers().getEntry(player.getGameProfile()) != null && player.getServer().getPlayerList().getOppedPlayers().getEntry(player.getGameProfile()).getPermissionLevel() == 4; } @Nullable public static UUID getPlayerUUID(String username) { for (Map.Entry<UUID, String> entry : UsernameCache.getMap().entrySet()) { if (entry.getValue().equalsIgnoreCase(username)) { return entry.getKey(); } } return null; } @Nullable @ParametersAreNullableByDefault public static UUID getPlayerUIDUnstable(String possibleUUID) { if (possibleUUID == null || possibleUUID.isEmpty()) { return null; } UUID uuid; try { uuid = UUID.fromString(possibleUUID); } catch (IllegalArgumentException e) { uuid = getPlayerUUID(possibleUUID); } return uuid; } @Nullable @ParametersAreNullableByDefault public static String getPlayerNameFromUUID(String possibleUUID) { if (possibleUUID == null || possibleUUID.isEmpty()) { return null; } return UsernameCache.getLastKnownUsername(UUID.fromString(possibleUUID)); } @Nullable @ParametersAreNonnullByDefault public static TrustedPlayer getTrustedPlayer(EntityPlayer player, ITrustedPlayersManager machine) { if (machine.getTrustedPlayer(player.getUniqueID()) != null || (offlineModeSupport && machine.getTrustedPlayer(player.getName()) != null)) { return (machine.getTrustedPlayer(player.getUniqueID()) == null ? machine.getTrustedPlayer(player.getName()) : machine.getTrustedPlayer(player.getUniqueID())); } else { return null; } } @ParametersAreNonnullByDefault public static boolean isPlayerTrusted(EntityPlayer entityPlayer, ITrustedPlayersManager trustedPlayersManager) { Player player = new Player(entityPlayer.getUniqueID(), entityPlayer.getName()); return isPlayerTrusted(player, trustedPlayersManager); } @ParametersAreNonnullByDefault public static boolean isPlayerTrusted(Player player, ITrustedPlayersManager trustedPlayersManager) { return (offlineModeSupport ? trustedPlayersManager.getTrustedPlayer(player.getName()) != null : trustedPlayersManager.getTrustedPlayer(player.getUuid()) != null); } @ParametersAreNonnullByDefault public static boolean isPlayerOwner(EntityPlayer checkPlayer, TileEntityOwnedBlock ownedBlock) { Player owner = new Player(getPlayerUIDUnstable(ownedBlock.getOwner()), ownedBlock.getOwnerName()); Player player = new Player(checkPlayer.getGameProfile().getId(), checkPlayer.getName()); boolean allowed; allowed = (player.equals(owner)); if (!allowed && (ConfigHandler.canOPAccessOwnedBlocks && isPlayerOP(checkPlayer))) { allowed = true; } else if (!allowed && OwnerShareHandler.getInstance().isPlayerSharedOwner(owner, player)) { allowed = true; } return allowed; } @ParametersAreNonnullByDefault public static boolean isPlayerOwner(Player player, TileEntityOwnedBlock ownedBlock) { Player owner = new Player(getPlayerUIDUnstable(ownedBlock.getOwner()), ownedBlock.getOwnerName()); boolean allowed; allowed = (player.equals(owner)); if (!allowed && OwnerShareHandler.getInstance().isPlayerSharedOwner(owner, player)) { allowed = true; } return allowed; } }
/** * Lists, tests. * * @since 0.14 * @todo #1230:30min The following list implmenetation classes * {@link org.cactoos.list.Joined}, {@link org.cactoos.list.Mapped}, * {@link org.cactoos.list.NoNulls}, {@link org.cactoos.list.Shuffled}, * {@link org.cactoos.list.Solid}, {@link org.cactoos.list.Solid}, * {@link org.cactoos.list.Sorted}, {@link org.cactoos.list.Sticky}, * {@link org.cactoos.list.Synced} should support mutability. */ package org.cactoos.list;
package org.dynmap.bukkit; /** * Bukkit specific implementation of DynmapWorld */ import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.util.Arrays; import java.util.List; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionDefault; import org.dynmap.DynmapChunk; import org.dynmap.DynmapLocation; import org.dynmap.DynmapWorld; import org.dynmap.utils.MapChunkCache; import org.dynmap.utils.TileFlags; public class BukkitWorld extends DynmapWorld { private World world; private World.Environment env; private boolean skylight; private DynmapLocation spawnloc = new DynmapLocation(); public BukkitWorld(World w) { this(w.getName(), w.getMaxHeight(), w.getSeaLevel(), w.getEnvironment()); setWorldLoaded(w); new Permission("dynmap.world." + getName(), "Dynmap access for world " + getName(), PermissionDefault.OP); } public BukkitWorld(String name, int height, int sealevel, World.Environment env) { super(name, height, sealevel); world = null; this.env = env; skylight = (env == World.Environment.NORMAL); new Permission("dynmap.world." + getName(), "Dynmap access for world " + getName(), PermissionDefault.OP); } /** * Set world online * @param w - loaded world */ public void setWorldLoaded(World w) { world = w; env = world.getEnvironment(); skylight = (env == World.Environment.NORMAL); } /** * Set world unloaded */ @Override public void setWorldUnloaded() { getSpawnLocation(); /* Remember spawn location before unload */ world = null; } /* Test if world is nether */ @Override public boolean isNether() { return env == World.Environment.NETHER; } /* Get world spawn location */ @Override public DynmapLocation getSpawnLocation() { if(world != null) { Location sloc = world.getSpawnLocation(); spawnloc.x = sloc.getBlockX(); spawnloc.y = sloc.getBlockY(); spawnloc.z = sloc.getBlockZ(); spawnloc.world = normalizeWorldName(sloc.getWorld().getName()); } return spawnloc; } /* Get world time */ @Override public long getTime() { if(world != null) { return world.getTime(); } else { return -1; } } /* World is storming */ @Override public boolean hasStorm() { if(world != null) { return world.hasStorm(); } else { return false; } } /* World is thundering */ @Override public boolean isThundering() { if(world != null) { return world.isThundering(); } else { return false; } } /* World is loaded */ @Override public boolean isLoaded() { return (world != null); } /* Get light level of block */ @Override public int getLightLevel(int x, int y, int z) { if(world != null) { return world.getBlockAt(x, y, z).getLightLevel(); } else { return -1; } } /* Get highest Y coord of given location */ @Override public int getHighestBlockYAt(int x, int z) { if(world != null) { return world.getHighestBlockYAt(x, z); } else { return -1; } } /* Test if sky light level is requestable */ @Override public boolean canGetSkyLightLevel() { return skylight && (world != null); } /* Return sky light level */ @Override public int getSkyLightLevel(int x, int y, int z) { if(world != null) { return world.getBlockAt(x, y, z).getLightFromSky(); } else { return -1; } } /** * Get world environment ID (lower case - normal, the_end, nether) */ @Override public String getEnvironment() { return env.name().toLowerCase(); } /** * Get map chunk cache for world */ @Override public MapChunkCache getChunkCache(List<DynmapChunk> chunks) { if(isLoaded()) { NewMapChunkCache c = new NewMapChunkCache(); c.setChunks(this, chunks); return c; } else { return null; } } public World getWorld() { return world; } // Return false if unimplemented @Override public int getChunkMap(TileFlags map) { map.clear(); if (world == null) return -1; int cnt = 0; // Mark loaded chunks for(Chunk c : world.getLoadedChunks()) { map.setFlag(c.getX(), c.getZ(), true); cnt++; } File f = world.getWorldFolder(); File regiondir = new File(f, "region"); File[] lst = regiondir.listFiles(); if(lst != null) { byte[] hdr = new byte[4096]; for(File rf : lst) { if(!rf.getName().endsWith(".mca")) { continue; } String[] parts = rf.getName().split("\\."); if((!parts[0].equals("r")) && (parts.length != 4)) continue; RandomAccessFile rfile = null; int x = 0, z = 0; try { x = Integer.parseInt(parts[1]); z = Integer.parseInt(parts[2]); rfile = new RandomAccessFile(rf, "r"); rfile.read(hdr, 0, hdr.length); } catch (IOException iox) { Arrays.fill(hdr, (byte)0); } catch (NumberFormatException nfx) { Arrays.fill(hdr, (byte)0); } finally { if(rfile != null) { try { rfile.close(); } catch (IOException iox) {} } } for (int i = 0; i < 1024; i++) { int v = hdr[4*i] | hdr[4*i + 1] | hdr[4*i + 2] | hdr[4*i + 3]; if (v == 0) continue; int xx = (x << 5) | (i & 0x1F); int zz = (z << 5) | ((i >> 5) & 0x1F); if (!map.setFlag(xx, zz, true)) { cnt++; } } } } return cnt; } }
package org.jtrfp.trcl; import java.awt.Color; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.TimerTask; import java.util.concurrent.Callable; import javax.media.opengl.GL3; import org.jtrfp.trcl.beh.FacingObject; import org.jtrfp.trcl.beh.MatchDirection; import org.jtrfp.trcl.beh.MatchPosition; import org.jtrfp.trcl.beh.RotateAroundObject; import org.jtrfp.trcl.beh.SkyCubeCloudModeUpdateBehavior; import org.jtrfp.trcl.core.Camera; import org.jtrfp.trcl.core.LazyTRFuture; import org.jtrfp.trcl.core.Renderer; import org.jtrfp.trcl.core.ResourceManager; import org.jtrfp.trcl.core.TR; import org.jtrfp.trcl.file.LVLFile; import org.jtrfp.trcl.file.TXTMissionBriefFile; import org.jtrfp.trcl.flow.Game; import org.jtrfp.trcl.flow.Mission.Result; import org.jtrfp.trcl.gpu.GPU; import org.jtrfp.trcl.gpu.Model; import org.jtrfp.trcl.img.vq.ColorPaletteVectorList; import org.jtrfp.trcl.obj.DEFObject; import org.jtrfp.trcl.obj.EnemyIntro; import org.jtrfp.trcl.obj.PositionedRenderable; import org.jtrfp.trcl.obj.Sprite2D; import org.jtrfp.trcl.obj.WorldObject; public class BriefingScreen extends RenderableSpacePartitioningGrid { private static final double Z_INCREMENT = .00001; private static final double Z_START = -.99999; private static final double BRIEFING_SPRITE_Z = Z_START; private static final double TEXT_Z = BRIEFING_SPRITE_Z + Z_INCREMENT; private static final double TEXT_BG_Z = TEXT_Z + Z_INCREMENT; public static final double MAX_Z_DEPTH = TEXT_BG_Z + Z_INCREMENT; //private static final double Z = .000000001; private final TR tr; private final Sprite2D briefingScreen; private final CharAreaDisplay briefingChars; private final Sprite2D blackRectangle; private volatile double scrollPos = 0; private double scrollIncrement=.01; private final int NUM_LINES=10; private final int WIDTH_CHARS=36; private ArrayList<Runnable> scrollFinishCallbacks = new ArrayList<Runnable>(); //private TXTMissionBriefFile missionTXT; private ColorPaletteVectorList palette; private LVLFile lvl; private TimerTask scrollTimer; private WorldObject planetObject; private final LazyTRFuture<TXTMissionBriefFile> missionTXT; public BriefingScreen(SpacePartitioningGrid<PositionedRenderable> parent, final TR tr, GLFont font) { super(parent); briefingScreen = new Sprite2D(tr,0, 2, 2, tr.getResourceManager().getSpecialRAWAsTextures("BRIEF.RAW", tr.getGlobalPalette(), tr.gpu.get().getGl(), 0,false),true); add(briefingScreen); this.tr = tr; briefingChars = new CharAreaDisplay(this,.047,WIDTH_CHARS,NUM_LINES,tr,font); briefingChars.activate(); briefingChars.setPosition(-.7, -.45, TEXT_Z); briefingScreen.setPosition(0,0,BRIEFING_SPRITE_Z); briefingScreen.notifyPositionChange(); briefingScreen.setImmuneToOpaqueDepthTest(true); briefingScreen.setActive(true); briefingScreen.setVisible(true); blackRectangle = new Sprite2D(tr,0, 2, .6, tr.gpu.get().textureManager.get().solidColor(Color.BLACK), true); add(blackRectangle); blackRectangle.setImmuneToOpaqueDepthTest(true); blackRectangle.setPosition(0, -.7, TEXT_BG_Z); blackRectangle.setVisible(true); blackRectangle.setActive(true); missionTXT = new LazyTRFuture<TXTMissionBriefFile>(tr,new Callable<TXTMissionBriefFile>(){ @Override public TXTMissionBriefFile call(){ return tr.getResourceManager().getMissionText(lvl.getBriefingTextFile()); }//end call() }); }//end constructor protected void notifyScrollFinishCallbacks() { for(Runnable r:scrollFinishCallbacks){ r.run(); } }//end notifyScrollFinishCallbacks() public void addScrollFinishCallback(Runnable r){ scrollFinishCallbacks.add(r); } public void removeScrollFinishCallback(Runnable r){ scrollFinishCallbacks.remove(r); } public void setContent(String content) { briefingChars.setContent(content); } public void startScroll() { scrollPos=0; tr.getThreadManager().getLightweightTimer().scheduleAtFixedRate(scrollTimer = new TimerTask(){ @Override public void run() { scrollPos+=scrollIncrement; briefingChars.setScrollPosition(scrollPos); if(scrollPos>briefingChars.getNumActiveLines()+NUM_LINES){ BriefingScreen.this.stopScroll(); notifyScrollFinishCallbacks(); scrollFinishCallbacks.clear(); } }}, 0, 20); }//end startScroll() public void stopScroll() { scrollTimer.cancel(); } private void planetDisplayMode(LVLFile lvl){ final Game game = tr.getGame(); final ResourceManager rm = tr.getResourceManager(); final Camera camera = tr.renderer.get().getCamera(); final GPU gpu = tr.gpu.get(); final GL3 gl = gpu.getGl(); this.lvl = lvl; //TODO: Depth range //Planet introduction if(planetObject!=null){ remove(planetObject); planetObject=null; } try{ final Model planetModel = rm.getBINModel( missionTXT.get().getPlanetModelFile(), rm.getRAWAsTexture(missionTXT.get().getPlanetTextureFile(), getPalette(), false, true), 8,false,getPalette()); planetObject = new WorldObject(tr,planetModel); planetObject.setPosition(0, TR.mapSquareSize*20, 0); add(planetObject); planetObject.setVisible(true); camera.probeForBehavior(FacingObject.class) .setTarget(planetObject); camera.probeForBehavior(RotateAroundObject.class).setTarget(planetObject); camera.probeForBehavior(RotateAroundObject.class).setAngularVelocityRPS(.05); camera.probeForBehavior(RotateAroundObject.class).setOffset( new double []{0,-planetModel.getTriangleList().getMaximumVertexDims().getY(),0}); camera.probeForBehavior(RotateAroundObject.class).setDistance( planetModel.getTriangleList().getMaximumVertexDims().getX()*4); }catch(Exception e){tr.showStopper(e);} // Turn the camera to the planet camera.probeForBehavior(MatchPosition.class).setEnable(false); camera.probeForBehavior(MatchDirection.class).setEnable(false); camera.probeForBehavior(RotateAroundObject.class).setEnable(true); camera.probeForBehavior(FacingObject.class).setEnable(true); tr.renderer.get().getCamera() .probeForBehavior(SkyCubeCloudModeUpdateBehavior.class) .setEnable(false); tr.renderer.get().getSkyCube().setSkyCubeGen(SkySystem.SPACE_STARS); tr.renderer.get().setAmbientLight(SkySystem.SPACE_AMBIENT_LIGHT); tr.renderer.get().setSunColor(SkySystem.SPACE_SUN_COLOR); game.setDisplayMode(game.briefingMode); }//end planetDisplayMode() public void missionCompleteSummary(LVLFile lvl, Result r){ final Game game = tr.getGame(); game.getPlayer().setActive(false); briefingChars.setScrollPosition(NUM_LINES-2); setContent("Air targets destroyed: "+r.getAirTargetsDestroyed()+ "\nGround targets destroyed: "+r.getGroundTargetsDestroyed()+ "\nVegetation destroyed: "+r.getFoliageDestroyed()+ "\nTunnels found: "+(int)(r.getTunnelsFoundPctNorm()*100.)+"%"); game.getCurrentMission().getOverworldSystem().activate(); planetDisplayMode(lvl); briefingChars.activate(); tr.getKeyStatus().waitForSequenceTyped(KeyEvent.VK_SPACE); final Camera camera = tr.renderer.get().getCamera(); camera.probeForBehavior(MatchPosition.class) .setEnable(true); camera.probeForBehavior(MatchDirection.class) .setEnable(true); camera.probeForBehavior(FacingObject.class) .setEnable(false); camera.probeForBehavior(RotateAroundObject.class).setEnable(false); game.getCurrentMission().getOverworldSystem().deactivate(); }//end missionCompleteSummary() public void briefingSequence(LVLFile lvl) { final Game game = tr.getGame(); final ResourceManager rm = tr.getResourceManager(); final Camera camera = tr.renderer.get().getCamera(); final OverworldSystem overworld = game.getCurrentMission().getOverworldSystem(); //missionTXT = rm.getMissionText(lvl.getBriefingTextFile()); missionTXT.reset(); game.getPlayer().setActive(false); planetDisplayMode(lvl); setContent( missionTXT.get().getMissionText().replace("\r","").replace("$C", ""+game.getPlayerName())); overworld.activate(); startScroll(); final boolean [] mWait = new boolean[]{false}; addScrollFinishCallback(new Runnable(){ @Override public void run() { synchronized(mWait){mWait[0] = true; mWait.notifyAll();} }}); final Thread spacebarWaitThread; (spacebarWaitThread = new Thread(){ @Override public void run(){ tr.getKeyStatus().waitForSequenceTyped(KeyEvent.VK_SPACE); synchronized(mWait){mWait[0] = true; mWait.notifyAll();} }//end run() }).start(); tr.getThreadManager().visibilityCalc(true); try{synchronized(mWait){while(!mWait[0])mWait.wait();}} catch(InterruptedException e){} stopScroll(); spacebarWaitThread.interrupt(); //Enemy introduction final Renderer renderer = tr.renderer.get(); final SkySystem skySystem = game.getCurrentMission().getOverworldSystem().getSkySystem(); tr.renderer.get().getCamera().probeForBehavior(SkyCubeCloudModeUpdateBehavior.class).setEnable(true); renderer.getSkyCube().setSkyCubeGen(skySystem.getBelowCloudsSkyCubeGen()); renderer.setAmbientLight(skySystem.getSuggestedAmbientLight()); renderer.setSunColor(skySystem.getSuggestedSunColor()); for(EnemyIntro intro:game.getCurrentMission().getOverworldSystem().getObjectSystem().getDefPlacer().getEnemyIntros()){ final WorldObject wo = intro.getWorldObject(); final boolean vis = wo.isVisible(); final boolean act = wo.isActive(); wo.setActive(true); wo.setVisible(true); camera.probeForBehavior(FacingObject.class).setTarget(wo); camera.probeForBehavior(RotateAroundObject.class).setTarget(wo); camera.probeForBehavior(RotateAroundObject.class).setAngularVelocityRPS(.3); //Roughly center the object (ground objects have their bottom at Y=0) if(wo.getModel().getTriangleList()!=null){ camera.probeForBehavior(RotateAroundObject.class).setOffset( new double []{ 0, wo.getModel(). getTriangleList(). getMaximumVertexDims(). getY()/2, 0}); camera.probeForBehavior(RotateAroundObject.class).setDistance( wo.getModel().getTriangleList().getMaximumVertexDims().getX()*6);} else if(wo.getModel().getTransparentTriangleList()!=null){ camera.probeForBehavior(RotateAroundObject.class).setOffset( new double []{ 0, wo.getModel(). getTransparentTriangleList(). getMaximumVertexDims(). getY()/2, 0}); camera.probeForBehavior(RotateAroundObject.class).setDistance( wo.getModel().getTransparentTriangleList().getMaximumVertexDims().getX()*6);} //If this intro takes place in the chamber, enter chamber mode. boolean chamberMode = false; if(wo instanceof DEFObject){ final DEFObject def = (DEFObject)wo; chamberMode = def.isShieldGen() || def.isBoss(); } if(chamberMode) tr.getGame().getCurrentMission().getOverworldSystem().setChamberMode(true); wo.tick(System.currentTimeMillis());//Make sure its position and state is sane. camera.tick(System.currentTimeMillis());//Make sure the camera knows what is going on. wo.setRespondToTick(false);//freeze briefingChars.setScrollPosition(NUM_LINES-2); setContent(intro.getDescriptionString()); tr.getKeyStatus().waitForSequenceTyped(KeyEvent.VK_SPACE); //Restore previous state. wo.setVisible(vis); wo.setActive(act); wo.setRespondToTick(true);//unfreeze if(chamberMode) tr.getGame().getCurrentMission().getOverworldSystem().setChamberMode(false); }//end for(enemyIntros) camera.probeForBehavior(FacingObject.class).setEnable(false); camera.probeForBehavior(RotateAroundObject.class).setEnable(false); camera.probeForBehavior(MatchPosition.class).setEnable(true); camera.probeForBehavior(MatchDirection.class).setEnable(true); }//end briefingSequence private ColorPaletteVectorList getPalette(){ if(palette==null){ try{palette = new ColorPaletteVectorList(tr.getResourceManager().getPalette(lvl.getGlobalPaletteFile()));} catch(Exception e){tr.showStopper(e);} }//end if(null) return palette; }//end ColorPaletteVectorList }//end BriefingScreen
package org.jtrfp.trcl.gui; import java.awt.event.ActionListener; public interface MenuSystem { public static double BEGINNING = 0, END = 1, MIDDLE = Utils.between(BEGINNING,END); public void setMenuPosition(double position, String ... path); public void addMenuItem (double position, String ... path) throws IllegalArgumentException; public void removeMenuItem(String ... path) throws IllegalArgumentException; public void addMenuItemListener (ActionListener l, String ... path) throws IllegalArgumentException; public void removeMenuItemListener(ActionListener l, String ... path) throws IllegalArgumentException; public void setMenuItemEnabled(boolean enabled, String ... path) throws IllegalArgumentException; public abstract class Utils { public static double between(double first, double second){ return (first+second) / 2.; }//end between(...) }//end Utils }//end MenuSystem
package org.minimalj.util; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.minimalj.model.Selection; import org.minimalj.repository.list.RelationList; @SuppressWarnings({ "rawtypes", "unchecked" }) public class CloneHelper { /* * With all the security checks getting a constructor is quite expensive. * So here is a cache for the constructors for the already cloned classes. */ private static Map<Class<?>, Constructor<?>> contructors = new HashMap<>(200); /** * note: clone works only with special classes validatable through * ModelTest . * * @param object the original object * @param <T> Type of clazz itself (caller of this method doesn't need to care about this) * @return a (deep) clone of th original object */ public static <T> T clone(T object) { if (object == null) return null; return clone(object, new ArrayList(), new ArrayList()); } public static <T> T clone(T object, List originals, List copies) { int pos = originals.indexOf(object); if (pos >= 0) { return (T) copies.get(pos); } Class<T> clazz = (Class<T>) object.getClass(); try { T copy = newInstance(clazz); originals.add(object); copies.add(copy); _deepCopy(object, copy, originals, copies); return copy; } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException(e); } } /** * note: deepCopy works only with special classes validatable through * ModelTest . * * @param from the original object * @param to an empty object to be filled */ public static void deepCopy(Object from, Object to) { if (from == null) throw new IllegalArgumentException("from must not be null"); if (to == null) throw new IllegalArgumentException("to must not be null"); if (from.getClass() != to.getClass()) throw new IllegalArgumentException("from and to must have exactly same class, from has " + from.getClass() + " to has " + to.getClass()); try { _deepCopy(from, to, new ArrayList(), new ArrayList()); } catch (IllegalAccessException | IllegalArgumentException x) { throw new RuntimeException(x); } } private static void _deepCopy(Object from, Object to, List originals, List copies) throws IllegalArgumentException, IllegalAccessException { for (Field field : from.getClass().getDeclaredFields()) { if (FieldUtils.isStatic(field) || !FieldUtils.isPublic(field)) continue; Object fromValue = field.get(from); Object toValue = field.get(to); if (fromValue instanceof List) { List fromList = (List)fromValue; List toList = (List)toValue; if (fromList instanceof RelationList) { // RelationList doesn't need to be cloned field.set(to, fromList); } else { if (FieldUtils.isFinal(field)) { toList.clear(); } else { toList = new ArrayList<>(); field.set(to, toList); } for (Object element : fromList) { toList.add(clone(element, originals, copies)); } } } else if (fromValue instanceof Set) { Set fromSet = (Set)field.get(from); Set toSet = (Set)toValue; // Set can only contain enums. No need for cloning the elements. toSet.clear(); toSet.addAll(fromSet); } else if (isPrimitive(field) || field.getType() == Selection.class) { if (!FieldUtils.isFinal(field)) { field.set(to, fromValue); } } else if (FieldUtils.isFinal(field)) { if (fromValue != null) { if (toValue != null) { _deepCopy(fromValue, toValue, originals, copies); } else { throw new IllegalStateException("final field is not null in from object but null in to object. Field: " + field); } } } else if (FieldUtils.isTransient(field) || fromValue == null) { // note: transient fields are copied but not cloned! field.set(to, fromValue); } else if (fromValue instanceof byte[]) { toValue = ((byte[]) fromValue).clone(); field.set(to, toValue); } else if (fromValue instanceof char[]) { toValue = ((char[]) fromValue).clone(); field.set(to, toValue); } else { toValue = clone(fromValue, originals, copies); field.set(to, toValue); } } } private static boolean isPrimitive(Field field) { String fieldTypeName = field.getType().getName(); if (field.getType().isPrimitive() || fieldTypeName.startsWith("java")) return true; if (Enum.class.isAssignableFrom(field.getType())) return true; return false; } public static <T> T newInstance(Class<T> clazz) { Constructor<T> constructor = (Constructor<T>) contructors.get(clazz); if (constructor == null) { try { constructor = clazz.getConstructor(); contructors.put(clazz, constructor); } catch (SecurityException | NoSuchMethodException e) { throw new RuntimeException("Failed to create new Instance of " + clazz.getName(), e); } } try { return constructor.newInstance(); } catch (IllegalArgumentException | InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } }
package org.mixer2.xhtml; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.TreeMap; import java.util.UUID; import java.util.regex.Pattern; import javax.xml.namespace.QName; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mixer2.util.CastUtil; import org.mixer2.util.M2StringUtils; import org.mixer2.xhtml.exception.TagTypeUnmatchException; import org.mixer2.xhtml.util.CopyUtil; import org.mixer2.xhtml.util.GetByIdUtil; import org.mixer2.xhtml.util.GetDescendantsUtil; import org.mixer2.xhtml.util.InsertByIdUtil; import org.mixer2.xhtml.util.RemoveByIdUtil; import org.mixer2.xhtml.util.RemoveDescendantsUtil; import org.mixer2.xhtml.util.RemoveEmptyCssClassUtil; import org.mixer2.xhtml.util.ReplaceByIdUtil; import org.mixer2.xhtml.util.ReplaceDescendantsUtil; import org.mixer2.xhtml.util.UnsetIdUtil; /** * <p> * base class of all tag type * </p> * <p> * * </p> * * @author watanabe * */ @javax.xml.bind.annotation.XmlTransient public abstract class AbstractJaxb implements Serializable { private static Log log = LogFactory.getLog(AbstractJaxb.class); private static final long serialVersionUID = 1L; /** * <p> * type cast. * </p> * <p> * * </p> * * <pre> * // usage: * // get a TD tag of first row, first column. * Td td = html.getById(&quot;foo&quot;, Table.class).getTr().get(0).getThOrTd().get(0) * .cast(Td.class); * </pre> * * @param clazz * tag type of org.mixer2.jaxb.xhtml.* * @return */ public <T> T cast(Class<T> clazz) { return CastUtil.<T> cast(this); } /** * <p> * get tag that has specified id property. You don't need to cast() because * you can specify the tag type. * </p> * <p> * id * </p> * * <pre> * // sample: get a Div tag having id=&quot;foo&quot; property. * html.getById(&quot;foo&quot;, Div.class); * </pre> * * @param id * @param tagType * @return * @throws TagTypeUnmatchException */ @SuppressWarnings("unchecked") public <T extends AbstractJaxb> T getById(String id, Class<T> tagType) throws TagTypeUnmatchException { Object obj = GetByIdUtil.getById(id, this); if (obj != null && !obj.getClass().isAssignableFrom(tagType)) { throw new TagTypeUnmatchException(tagType.getClass(), obj.getClass()); } return (T) obj; } /** * <p> * get tag that has specified id property. To use return value as ussual * tag, you must cast() it. * </p> * <p> * id * </p> * * @param id * @return */ @SuppressWarnings("unchecked") public <T extends AbstractJaxb> T getById(String id) { Object obj = GetByIdUtil.getById(id, this); return (T) obj; } /** * <p> * delete element that has specified property within descendant element * of oneself. you can't delete oneself. * </p> * <p> * * </p> * * @param target * @return if success to delete, return true. if no hit, return false. */ public <T extends AbstractJaxb> boolean remove(T target) { String id = target.getId(); if (id == null) { for (int i = 0; i < 256; i++) { id = UUID.randomUUID().toString(); if (this.getById(id) == null) { target.setId(id); break; } } } return RemoveByIdUtil.removeById(id, this); } /** * <p> * delete element that has specified id property within descendant element * of oneself. you can't delete oneself. * </p> * <p> * id * </p> * * @param id * @return */ public boolean removeById(String id) { return RemoveByIdUtil.removeById(id, this); } /** * <p> * replace element that has specified property within descendant element of * oneself. you can't replace oneself. It will be replaced by deep copy of * "replacement" * </p> * <p> * * replace * </p> * * @param target * @param replacement * @return if success to replace, return true. if no hit, return false. * @throws TagTypeUnmatchException */ public <T extends AbstractJaxb> boolean replace(T target, T replacement) throws TagTypeUnmatchException { String id = target.getId(); if (id == null) { for (int i = 0; i < 256; i++) { id = UUID.randomUUID().toString(); if (this.getById(id) == null && replacement.getById(id) == null) { target.setId(id); break; } } } return ReplaceByIdUtil.replaceById(id, this, replacement); } /** * <p> * replace element that has specified id property within descendant element * of oneself. you can't replace oneself. It will be replaced by deep copy * of "replacement" * </p> * <p> * id * replace * </p> * * @param id * @param replacement * @return if success to replace, return true. if no hit, return false. * @throws TagTypeUnmatchException */ public <T extends AbstractJaxb> boolean replaceById(String id, T replacement) throws TagTypeUnmatchException { return ReplaceByIdUtil.replaceById(id, this, replacement); } /** * <p> * replace element by string. you can't replace oneself. * </p> * <p> * id * </p> * * @param id * @param string * @return if success to replace, return true. if no hit, return false. * @throws TagTypeUnmatchException */ public <T extends AbstractJaxb> boolean replaceById(String id, String replacement) throws TagTypeUnmatchException { return ReplaceByIdUtil.replaceById(id, this, replacement); } /** * <p> * scan descendant element that is specified tag type having specified class * property and return it as List. * </p> * <p> * classList * </p> * * <pre> * // usage: * // get all div objects having &quot;foo&quot; class * List&lt;Div&gt; divList = html.getDescendants(&quot;foo&quot;, Div.class); * // get all Table objects having &quot;bar&quot; class within &lt;div id=&quot;foo&quot;&gt; * List&lt;Table&gt; tbList = html.getById(&quot;foo&quot;, Div.class).getDescendants(&quot;bar&quot;, * Table.class); * </pre> * * @param clazz * @param tagType * @return */ @SuppressWarnings("unchecked") public <T extends AbstractJaxb> List<T> getDescendants(String clazz, Class<T> tagType) { return GetDescendantsUtil.getDescendants((T) this, new ArrayList<T>(), clazz, tagType); } /** * <p> * scan descendant elements that has specified tag type and return it as * List. * </p> * <p> * List * </p> * * <pre> * // usage: * // get all div objects. * html.getDescendants(Div.class); * // get all table objects within &lt;div id=&quot;foo&quot;&gt; * html.getById(&quot;foo&quot;, Div.class).getDescendants(Table.class); * </pre> * * @param tagType * @return */ @SuppressWarnings("unchecked") public <T extends AbstractJaxb> List<T> getDescendants(Class<T> tagType) { return GetDescendantsUtil.getDescendants((T) this, new ArrayList<T>(), tagType); } /** * <p> * scan descendant elements that has specified class property and return it * as List * </p> * <p> * classList * </p> * * @param clazz * class property * @return */ @SuppressWarnings("unchecked") public <T extends AbstractJaxb> List<T> getDescendants(String clazz) { return GetDescendantsUtil.getDescendants((T) this, new ArrayList<T>(), clazz); } /** * <p> * delete all descendant elements that is specified tag type having * specified class property. * </p> * <p> * class * </p> * * @param clazz * class property * @param tagType */ @SuppressWarnings("unchecked") public <T extends AbstractJaxb> void removeDescendants(String clazz, Class<T> tagType) { RemoveDescendantsUtil.removeDescendants((T) this, clazz, tagType); } /** * <p> * delete all descendant elements that is specified tag type. * </p> * <p> * * </p> * * @param tagType */ @SuppressWarnings("unchecked") public <T extends AbstractJaxb> void removeDescendants(Class<T> tagType) { RemoveDescendantsUtil.removeDescendants((T) this, tagType); } /** * <p> * delete all descendant elements having specified classs property * </p> * <p> * class * </p> * * @param clazz * class property */ @SuppressWarnings("unchecked") public <T extends AbstractJaxb> void removeDescendants(String clazz) { RemoveDescendantsUtil.removeDescendants((T) this, clazz); } /** * <p> * relpace all the descendant elements that is specified tag type having * specified class property. this method use deep copy of "replacement" * </p> * <p> * class replace * </p> * * @param clazz * class property * @param tagType * @param replacement * @throws TagTypeUnmatchException */ @SuppressWarnings("unchecked") public <T extends AbstractJaxb> void replaceDescendants(String clazz, Class<T> tagType, T replacement) throws TagTypeUnmatchException { ReplaceDescendantsUtil.replaceDescendants((T) this, tagType, clazz, replacement); } /** * <p> * relpace all the descendant elements by String. The target is specified * tag type having specified class property. * </p> * <p> * class * </p> * * @param clazz * class property * @param tagType * @param replacement * @throws TagTypeUnmatchException */ @SuppressWarnings("unchecked") public <T extends AbstractJaxb> void replaceDescendants(String clazz, Class<T> tagType, String replacement) throws TagTypeUnmatchException { ReplaceDescendantsUtil.replaceDescendants((T) this, tagType, clazz, replacement); } /** * <p> * replace all descendant elements that is specified tag type. This method * use deep copy of "replacement" * </p> * <p> * "replacement" * </p> * * @param tagType * @param replacement * @throws TagTypeUnmatchException */ @SuppressWarnings("unchecked") public <T extends AbstractJaxb> void replaceDescendants(Class<T> tagType, T replacement) throws TagTypeUnmatchException { ReplaceDescendantsUtil.replaceDescendants((T) this, tagType, replacement); } /** * class replace * * * @param clazz * class property * @param replacement * @throws TagTypeUnmatchException */ @SuppressWarnings("unchecked") public <T extends AbstractJaxb> void replaceDescendants(String clazz, T replacement) throws TagTypeUnmatchException { ReplaceDescendantsUtil.replaceDescendants((T) this, clazz, replacement); } /** * <p> * replace all descendant element that is specified tag type by String * </p> * <p> * * </p> * * @param tagType * @param replacement * @throws TagTypeUnmatchException */ @SuppressWarnings("unchecked") public <T extends AbstractJaxb> void replaceDescendants(Class<T> tagType, String replacement) throws TagTypeUnmatchException { ReplaceDescendantsUtil.replaceDescendants((T) this, tagType, replacement); } /** * <p> * class * </p> * * @param clazz * class property * @param replacement * @throws TagTypeUnmatchException */ @SuppressWarnings("unchecked") public <T extends AbstractJaxb> void replaceDescendants(String clazz, String replacement) throws TagTypeUnmatchException { ReplaceDescendantsUtil.replaceDescendants((T) this, clazz, replacement); } /** * <p> * insert element after the element having specified id property. This * method use deep copy of "insObject" * </p> * * <p> * id replace * </p> * * @param id * id property * @param insObject * @return true if success to insert. if no hit, return false. * @throws TagTypeUnmatchException */ public <T extends AbstractJaxb> boolean insertAfterId(String id, T insObject) throws TagTypeUnmatchException { return InsertByIdUtil.insertAfterId(id, insObject, this); } /** * <p> * id * </p> * * @param id * @param insString * @return true if success to insert. if no hit, return false. * @throws TagTypeUnmatchException */ public boolean insertAfterId(String id, String insString) throws TagTypeUnmatchException { return InsertByIdUtil.insertAfterId(id, insString, this); } /** * <p> * id replace * </p> * * @param id * @param insObject * @return true if success to insert. if no hit, return false. * @throws TagTypeUnmatchException */ public <T extends AbstractJaxb> boolean insertBeforeId(String id, T insObject) throws TagTypeUnmatchException { return InsertByIdUtil.insertBeforeId(id, insObject, this); } /** * <p> * id * </p> * * @param id * @param insString * @return true if success to insert. if no hit, return false. * @throws TagTypeUnmatchException */ public boolean insertBeforeId(String id, String insString) throws TagTypeUnmatchException { return InsertByIdUtil.insertBeforeId(id, insString, this); } /** * <p> * write style property by TreeMap * </p> * <p> * TreeMapstyle * </p> * * <pre> * // usage: * TreeMap&lt;String, String&gt; styleMap = new TreeMap&lt;String, String&gt;(); * styleMap.put(&quot;border-color&quot;, &quot;red&quot;); * html.getById(Div.class, &quot;hellomsg&quot;).setStyleByTreeMap(styleMap); * // output: * // &lt;div id=&quot;hellomsg&quot; style=&quot;border-color:red;&quot;&gt;...&lt;/div&gt; * </pre> * * @param styleMap */ public <T extends AbstractJaxb> void setStyleByTreeMap( TreeMap<String, String> styleMap) { String str = ""; for (String key : styleMap.keySet()) { str += key + ":" + styleMap.get(key) + "; "; } this.setStyle(str); } /** * <p> * return style property as TreeMap * </p> * <p> * styleTreeMap * </p> * * @return */ public TreeMap<String, String> getStyleAsTreeMap() { TreeMap<String, String> resultMap = new TreeMap<String, String>(); if (M2StringUtils.isBlank(this.getStyle())) { return resultMap; } String st[] = this.getStyle().trim().split(";"); String st2[]; for (String s : st) { st2 = s.split(":"); resultMap.put(st2[0].trim(), st2[1].trim()); } return resultMap; } /** * <p> * return deep copy of myself * </p> * <p> * <strong>NOTICE: DO NOT USE clone() and copyTo() method !</strong> * They has bug. Use this copy() method instead of them. * </p> * <p> * * </p> * <p> * <strong>: clone()copyTo()</strong> * html5aria-*data-* * copy() * </p> * * <pre> * // usage * Div div = html.getById(Div.class, &quot;foo&quot;); * Div div2 = div.copy(Div.class); * </pre> * * @param tagType * @return * @throws TagTypeUnmatchException */ @SuppressWarnings("unchecked") public <T extends AbstractJaxb> T copy(Class<T> tagType) throws TagTypeUnmatchException { T copy = null; if (!tagType.equals(this.getClass())) { log.warn("to use copy() method, tagType must be same type of the original object."); throw new TagTypeUnmatchException(getClass(), tagType); } try { copy = (T) this.clone(); } catch (CloneNotSupportedException e) { log.error("can not create clone(copy) of this object.", e); } CopyUtil.copyOtherAttr(this, copy); return copy; } /** * <p> * same as {@link #copy(Class)} but never throw exception. * return null if failed to copy. * </p> * <p> * {@link #copy(Class)}null * </p> * * @param tagType * @return */ public <T extends AbstractJaxb> T copyNoException(Class<T> tagType) { T copy = null; try { copy = (T) this.copy(tagType); } catch (final TagTypeUnmatchException e) { return null; } return copy; } /** * <p> * set data-* property * </p> * <p> * data-* * </p> * * <pre> * Div div = new Div(); * div.setData(&quot;foo&quot;, &quot;bar&quot;); * // you get &lt;div data-foo=&quot;bar&quot;&gt;&lt;/div&gt; * </pre> * * @param key * data-"key" */ public void setData(String key, String value) { QName qn = new QName("data-" + key); this.getOtherAttributes().put(qn, value); } /** * <p> * return the value of data-* property. If not set, return null. * </p> * <p> * data-* null * </p> * * @param key * data-"key" * @return null if not found property */ public String getData(String key) { QName qn = new QName("data-" + key); return this.getOtherAttributes().get(qn); } /** * <p> * set area-* property * </p> * <p> * aria-* * </p> * * @param key * aria-"key" * @param value */ public void setAria(String key, String value) { QName qn = new QName("aria-" + key); this.getOtherAttributes().put(qn, value); } /** * <p> * return the value of area-* property. If not set, return null. * </p> * <p> * aria-* null * </p> * * @param key * aria-"key" * @return */ public String getAria(String key) { QName qn = new QName("aria-" + key); return this.getOtherAttributes().get(qn); } /** * <p> * data-* * </p> * <p> * remove attribute of data-* property. * </p> * @param key data-"key" * @return the previous value associated with key, or null if there was no mapping for key. */ public String removeData(String key) { QName qn = new QName("data-" + key); return this.getOtherAttributes().remove(qn); } /** * <p> * aria-* * </p> * <p> * remove attribute of aria-* property. * </p> * @param key data-"key" * @return the previous value associated with key, or null if there was no mapping for key. */ public String removeAria(String key) { QName qn = new QName("aria-" + key); return this.getOtherAttributes().remove(qn); } /** * <p> * get other attribute map. NOTICE: this method is dummy for make coding * easy. Acrually, this method is overridden by each tag class. * </p> * <p> * otherAttribute * * </p> * * @return */ public Map<QName, String> getOtherAttributes() { return null; } /** * <p> * get id property. return null if not set. NOTICE: this method is dummy for * make coding easy. Acrually, this method is overridden by each tag class. * </p> * <p> * idnull * xhtmlid * </p> * * @return */ public String getId() { return null; } /** * <p> * set id property. NOTICE: this method is dummy for make coding easy. * Acrually, this method is overridden by each tag class. * </p> * <p> * idnull * xhtmlid * </p> */ public void setId(String id) { } /** * <p> * NOTICE: this method is dummy for make coding easy. Acrually, this method * is overridden by each tag class. * </p> * <p> * idnull * xhtmlid * </p> */ public boolean isSetId() { return false; } /** * <p> * delete id property of all descendant elements. Also, remove id property * of myself. * </p> * <p> * id id * </p> */ public void unsetAllId() { UnsetIdUtil.unsetAllId(this); } /** * <p> * idid * idpattern * </p> */ public void unsetAllId(Pattern pattern) { UnsetIdUtil.unsetAllId(this, pattern); } /** * <p> * NOTICE: this method is dummy for make coding easy. Acrually, this method * is overridden by each tag class. * </p> * <p> * style * * html5classstyle * </p> * * @return */ public String getStyle() { return null; } /** * <p> * NOTICE: this method is dummy for make coding easy. Acrually, this method * is overridden by each tag class. * </p> * <p> * style * * html5classstyle * </p> * * @return */ public void setStyle(String value) { return; } /** * <p> * return class property as List. NOTICE: this method is dummy for make * coding easy. Acrually, this method is overridden by each tag class. * </p> * </p> class * * html5classstyle </p> * * @return */ public List<String> getCssClass() { return null; } /** * <p> * return true if having specified class property. * </p> * <p> * class * </p> * * @param clazz * class property * @return */ public <T extends AbstractJaxb> boolean hasCssClass(String clazz) { boolean result = false; List<String> classList = this.getCssClass(); if (classList != null && classList.contains(clazz)) { result = true; } return result; } /** * <p> * add class property. If already set, do nothing. * </p> * <p> * class * </p> */ public <T extends AbstractJaxb> void addCssClass(String clazz) { List<String> classList = this.getCssClass(); if (!this.hasCssClass(clazz)) { classList.add(clazz); } } /** * <p> * remove specified class property if having it. * </p> * <p> * class * </p> */ public <T extends AbstractJaxb> void removeCssClass(String clazz) { List<String> classList = this.getCssClass(); if (classList != null) { for (ListIterator<String> i = classList.listIterator(); i.hasNext();) { if (i.next().equals(clazz)) { i.remove(); } } } } /** * <p> * remove class property if it has no value. * </p> * <p> * classclass * class * </p> * * <pre> * &lt;div class=&quot;&quot;&gt;....&lt;/div&gt; * </pre> * */ public void removeEmptyCssClass() { RemoveEmptyCssClassUtil.removeEmptyCssClass(this); } /** * <p> * returns byte sequence of myself. * </p> * <p> * * </p> * * @return * @throws IOException */ public byte[] toByteArray() throws IOException { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(byteOut); out.writeObject(this); return byteOut.toByteArray(); } /** * <p> * FOR DEBUG. This method does not include the field of a null object in the * returned string. * </p> * <p> * null * </p> */ public String toString() { return M2StringUtils.stringifier(this); } }
package org.zendesk.client.v2; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.util.ISO8601DateFormat; import org.asynchttpclient.AsyncCompletionHandler; import org.asynchttpclient.AsyncHttpClient; import org.asynchttpclient.BoundRequestBuilder; import org.asynchttpclient.DefaultAsyncHttpClient; import org.asynchttpclient.ListenableFuture; import org.asynchttpclient.Realm; import org.asynchttpclient.Request; import org.asynchttpclient.RequestBuilder; import org.asynchttpclient.Response; import org.asynchttpclient.request.body.multipart.FilePart; import org.asynchttpclient.request.body.multipart.StringPart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zendesk.client.v2.model.AgentRole; import org.zendesk.client.v2.model.Attachment; import org.zendesk.client.v2.model.Audit; import org.zendesk.client.v2.model.Automation; import org.zendesk.client.v2.model.Brand; import org.zendesk.client.v2.model.Comment; import org.zendesk.client.v2.model.Field; import org.zendesk.client.v2.model.Forum; import org.zendesk.client.v2.model.Group; import org.zendesk.client.v2.model.GroupMembership; import org.zendesk.client.v2.model.Identity; import org.zendesk.client.v2.model.JobStatus; import org.zendesk.client.v2.model.Macro; import org.zendesk.client.v2.model.Metric; import org.zendesk.client.v2.model.Organization; import org.zendesk.client.v2.model.OrganizationField; import org.zendesk.client.v2.model.OrganizationMembership; import org.zendesk.client.v2.model.SatisfactionRating; import org.zendesk.client.v2.model.SearchResultEntity; import org.zendesk.client.v2.model.Status; import org.zendesk.client.v2.model.SuspendedTicket; import org.zendesk.client.v2.model.Ticket; import org.zendesk.client.v2.model.TicketForm; import org.zendesk.client.v2.model.TicketImport; import org.zendesk.client.v2.model.TicketResult; import org.zendesk.client.v2.model.Topic; import org.zendesk.client.v2.model.Trigger; import org.zendesk.client.v2.model.TwitterMonitor; import org.zendesk.client.v2.model.User; import org.zendesk.client.v2.model.UserField; import org.zendesk.client.v2.model.hc.Article; import org.zendesk.client.v2.model.hc.ArticleAttachments; import org.zendesk.client.v2.model.hc.Category; import org.zendesk.client.v2.model.hc.Section; import org.zendesk.client.v2.model.hc.Subscription; import org.zendesk.client.v2.model.hc.Translation; import org.zendesk.client.v2.model.schedules.Holiday; import org.zendesk.client.v2.model.schedules.Schedule; import org.zendesk.client.v2.model.targets.BasecampTarget; import org.zendesk.client.v2.model.targets.CampfireTarget; import org.zendesk.client.v2.model.targets.EmailTarget; import org.zendesk.client.v2.model.targets.PivotalTarget; import org.zendesk.client.v2.model.targets.Target; import org.zendesk.client.v2.model.targets.TwitterTarget; import org.zendesk.client.v2.model.targets.UrlTarget; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; /** * @author stephenc * @since 04/04/2013 13:08 */ public class Zendesk implements Closeable { private static final String JSON = "application/json; charset=UTF-8"; private final boolean closeClient; private final AsyncHttpClient client; private final Realm realm; private final String url; private final String oauthToken; private final ObjectMapper mapper; private final Logger logger; private boolean closed = false; private static final Map<String, Class<? extends SearchResultEntity>> searchResultTypes = searchResultTypes(); private static final Map<String, Class<? extends Target>> targetTypes = targetTypes(); private static Map<String, Class<? extends SearchResultEntity>> searchResultTypes() { Map<String, Class<? extends SearchResultEntity>> result = new HashMap<>(); result.put("ticket", Ticket.class); result.put("user", User.class); result.put("group", Group.class); result.put("organization", Organization.class); result.put("topic", Topic.class); result.put("article", Article.class); return Collections.unmodifiableMap(result); } private static Map<String, Class<? extends Target>> targetTypes() { Map<String, Class<? extends Target>> result = new HashMap<>(); result.put("url_target", UrlTarget.class); result.put("email_target",EmailTarget.class); result.put("basecamp_target", BasecampTarget.class); result.put("campfire_target", CampfireTarget.class); result.put("pivotal_target", PivotalTarget.class); result.put("twitter_target", TwitterTarget.class); // TODO: Implement other Target types //result.put("clickatell_target", ClickatellTarget.class); //result.put("flowdock_target", FlowdockTarget.class); //result.put("get_satisfaction_target", GetSatisfactionTarget.class); //result.put("yammer_target", YammerTarget.class); return Collections.unmodifiableMap(result); } private Zendesk(AsyncHttpClient client, String url, String username, String password) { this.logger = LoggerFactory.getLogger(Zendesk.class); this.closeClient = client == null; this.oauthToken = null; this.client = client == null ? new DefaultAsyncHttpClient() : client; this.url = url.endsWith("/") ? url + "api/v2" : url + "/api/v2"; if (username != null) { this.realm = new Realm.Builder(username, password) .setScheme(Realm.AuthScheme.BASIC) .setUsePreemptiveAuth(true) .build(); } else { if (password != null) { throw new IllegalStateException("Cannot specify token or password without specifying username"); } this.realm = null; } this.mapper = createMapper(); } private Zendesk(AsyncHttpClient client, String url, String oauthToken) { this.logger = LoggerFactory.getLogger(Zendesk.class); this.closeClient = client == null; this.realm = null; this.client = client == null ? new DefaultAsyncHttpClient() : client; this.url = url.endsWith("/") ? url + "api/v2" : url + "/api/v2"; if (oauthToken != null) { this.oauthToken = oauthToken; } else { throw new IllegalStateException("Cannot specify token or password without specifying username"); } this.mapper = createMapper(); } // Closeable interface methods public boolean isClosed() { return closed || client.isClosed(); } public void close() { if (closeClient && !client.isClosed()) { try { client.close(); } catch (IOException e) { logger.warn("Unexpected error on client close", e); } } closed = true; } // Action methods public <T> JobStatus<T> getJobStatus(JobStatus<T> status) { return complete(getJobStatusAsync(status)); } public <T> ListenableFuture<JobStatus<T>> getJobStatusAsync(JobStatus<T> status) { return submit(req("GET", tmpl("/job_statuses/{id}.json").set("id", status.getId())), handleJobStatus(status.getResultsClass())); } public List<JobStatus<HashMap<String, Object>>> getJobStatuses(List<JobStatus> statuses) { return complete(getJobStatusesAsync(statuses)); } public ListenableFuture<List<JobStatus<HashMap<String, Object>>>> getJobStatusesAsync(List<JobStatus> statuses) { List<String> ids = new ArrayList<>(statuses.size()); for (JobStatus status : statuses) { ids.add(status.getId()); } Class<JobStatus<HashMap<String, Object>>> clazz = (Class<JobStatus<HashMap<String, Object>>>)(Object)JobStatus.class; return submit(req("GET", tmpl("/job_statuses/show_many.json{?ids}").set("ids", ids)), handleList(clazz, "job_statuses")); } public List<Brand> getBrands(){ return complete(submit(req("GET", cnst("/brands.json")), handleList(Brand.class, "brands"))); } public TicketForm getTicketForm(long id) { return complete(submit(req("GET", tmpl("/ticket_forms/{id}.json").set("id", id)), handle(TicketForm.class, "ticket_form"))); } public List<TicketForm> getTicketForms() { return complete(submit(req("GET", cnst("/ticket_forms.json")), handleList(TicketForm.class, "ticket_forms"))); } public TicketForm createTicketForm(TicketForm ticketForm) { return complete(submit(req("POST", cnst("/ticket_forms.json"), JSON, json( Collections.singletonMap("ticket_form", ticketForm))), handle(TicketForm.class, "ticket_form"))); } public Ticket importTicket(TicketImport ticketImport) { return complete(submit(req("POST", cnst("/imports/tickets.json"), JSON, json(Collections.singletonMap("ticket", ticketImport))), handle(Ticket.class, "ticket"))); } public JobStatus<Ticket> importTickets(TicketImport... ticketImports) { return importTickets(Arrays.asList(ticketImports)); } public JobStatus<Ticket> importTickets(List<TicketImport> ticketImports) { return complete(importTicketsAsync(ticketImports)); } public ListenableFuture<JobStatus<Ticket>> importTicketsAsync(List<TicketImport> ticketImports) { return submit(req("POST", cnst("/imports/tickets/create_many.json"), JSON, json( Collections.singletonMap("tickets", ticketImports))), handleJobStatus(Ticket.class)); } public Ticket getTicket(long id) { return complete(submit(req("GET", tmpl("/tickets/{id}.json").set("id", id)), handle(Ticket.class, "ticket"))); } public List<Ticket> getTicketIncidents(long id) { return complete(submit(req("GET", tmpl("/tickets/{id}/incidents.json").set("id", id)), handleList(Ticket.class, "tickets"))); } public List<User> getTicketCollaborators(long id) { return complete(submit(req("GET", tmpl("/tickets/{id}/collaborators.json").set("id", id)), handleList(User.class, "users"))); } public void deleteTicket(Ticket ticket) { checkHasId(ticket); deleteTicket(ticket.getId()); } public void deleteTicket(long id) { complete(submit(req("DELETE", tmpl("/tickets/{id}.json").set("id", id)), handleStatus())); } public ListenableFuture<JobStatus<Ticket>> queueCreateTicketAsync(Ticket ticket) { return submit(req("POST", cnst("/tickets.json?async=true"), JSON, json(Collections.singletonMap("ticket", ticket))), handleJobStatus(Ticket.class)); } public ListenableFuture<Ticket> createTicketAsync(Ticket ticket) { return submit(req("POST", cnst("/tickets.json"), JSON, json(Collections.singletonMap("ticket", ticket))), handle(Ticket.class, "ticket")); } public Ticket createTicket(Ticket ticket) { return complete(createTicketAsync(ticket)); } public JobStatus<Ticket> createTickets(Ticket... tickets) { return createTickets(Arrays.asList(tickets)); } public JobStatus<Ticket> createTickets(List<Ticket> tickets) { return complete(createTicketsAsync(tickets)); } public ListenableFuture<JobStatus<Ticket>> createTicketsAsync(List<Ticket> tickets) { return submit(req("POST", cnst("/tickets/create_many.json"), JSON, json( Collections.singletonMap("tickets", tickets))), handleJobStatus(Ticket.class)); } public Ticket updateTicket(Ticket ticket) { checkHasId(ticket); return complete(submit(req("PUT", tmpl("/tickets/{id}.json").set("id", ticket.getId()), JSON, json(Collections.singletonMap("ticket", ticket))), handle(Ticket.class, "ticket"))); } public void markTicketAsSpam(Ticket ticket) { checkHasId(ticket); markTicketAsSpam(ticket.getId()); } public void markTicketAsSpam(long id) { complete(submit(req("PUT", tmpl("/tickets/{id}/mark_as_spam.json").set("id", id)), handleStatus())); } public void deleteTickets(long id, long... ids) { complete(submit(req("DELETE", tmpl("/tickets/destroy_many.json{?ids}").set("ids", idArray(id, ids))), handleStatus())); } public Iterable<Ticket> getTickets() { return new PagedIterable<>(cnst("/tickets.json"), handleList(Ticket.class, "tickets")); } /** * @deprecated This API is no longer available from the vendor. Use the {@link #getTicketsFromSearch(String)} method instead * @param ticketStatus * @return */ @Deprecated public Iterable<Ticket> getTicketsByStatus(Status... ticketStatus) { return new PagedIterable<>(tmpl("/tickets.json{?status}").set("status", statusArray(ticketStatus)), handleList(Ticket.class, "tickets")); } public Iterable<Ticket> getTicketsByExternalId(String externalId, boolean includeArchived) { Iterable<Ticket> results = new PagedIterable<>(tmpl("/tickets.json{?external_id}").set("external_id", externalId), handleList(Ticket.class, "tickets")); if (!includeArchived || results.iterator().hasNext()) { return results; } return new PagedIterable<>( tmpl("/search.json{?query}{&type}").set("query", "external_id:" + externalId).set("type", "ticket"), handleList(Ticket.class, "results")); } public Iterable<Ticket> getTicketsByExternalId(String externalId) { return getTicketsByExternalId(externalId, false); } public Iterable<Ticket> getTicketsFromSearch(String searchTerm) { return new PagedIterable<>(tmpl("/search.json{?query}").set("query", searchTerm + "+type:ticket"), handleList(Ticket.class, "results")); } public Iterable<Article> getArticleFromSearch(String searchTerm) { return new PagedIterable<>(tmpl("/help_center/articles/search.json{?query}").set("query", searchTerm), handleList(Article.class, "results")); } public Iterable<Article> getArticleFromSearch(String searchTerm, Long sectionId) { return new PagedIterable<>(tmpl("/help_center/articles/search.json{?section,query}") .set("query", searchTerm).set("section", sectionId), handleList(Article.class, "results")); } public List<ArticleAttachments> getAttachmentsFromArticle(Long articleID) { return complete(submit(req("GET", tmpl("/help_center/articles/{id}/attachments.json").set("id", articleID)), handleArticleAttachmentsList("article_attachments"))); } public List<Ticket> getTickets(long id, long... ids) { return complete(submit(req("GET", tmpl("/tickets/show_many.json{?ids}").set("ids", idArray(id, ids))), handleList(Ticket.class, "tickets"))); } public Iterable<Ticket> getRecentTickets() { return new PagedIterable<>(cnst("/tickets/recent.json"), handleList(Ticket.class, "tickets")); } public Iterable<Ticket> getTicketsIncrementally(Date startTime) { return new PagedIterable<>( tmpl("/incremental/tickets.json{?start_time}").set("start_time", msToSeconds(startTime.getTime())), handleIncrementalList(Ticket.class, "tickets")); } public Iterable<Ticket> getTicketsIncrementally(Date startTime, Date endTime) { return new PagedIterable<>( tmpl("/incremental/tickets.json{?start_time,end_time}") .set("start_time", msToSeconds(startTime.getTime())) .set("end_time", msToSeconds(endTime.getTime())), handleIncrementalList(Ticket.class, "tickets")); } public Iterable<Ticket> getOrganizationTickets(long organizationId) { return new PagedIterable<>( tmpl("/organizations/{organizationId}/tickets.json").set("organizationId", organizationId), handleList(Ticket.class, "tickets")); } public Iterable<Ticket> getUserRequestedTickets(long userId) { return new PagedIterable<>(tmpl("/users/{userId}/tickets/requested.json").set("userId", userId), handleList(Ticket.class, "tickets")); } public Iterable<Ticket> getUserCCDTickets(long userId) { return new PagedIterable<>(tmpl("/users/{userId}/tickets/ccd.json").set("userId", userId), handleList(Ticket.class, "tickets")); } public Iterable<Metric> getTicketMetrics() { return new PagedIterable<>(cnst("/ticket_metrics.json"), handleList(Metric.class, "ticket_metrics")); } public Metric getTicketMetricByTicket(long id) { return complete(submit(req("GET", tmpl("/tickets/{ticketId}/metrics.json").set("ticketId", id)), handle(Metric.class, "ticket_metric"))); } public Metric getTicketMetric(long id) { return complete(submit(req("GET", tmpl("/ticket_metrics/{ticketMetricId}.json").set("ticketMetricId", id)), handle(Metric.class, "ticket_metric"))); } public Iterable<Audit> getTicketAudits(Ticket ticket) { checkHasId(ticket); return getTicketAudits(ticket.getId()); } public Iterable<Audit> getTicketAudits(Long id) { return new PagedIterable<>(tmpl("/tickets/{ticketId}/audits.json").set("ticketId", id), handleList(Audit.class, "audits")); } public Audit getTicketAudit(Ticket ticket, Audit audit) { checkHasId(audit); return getTicketAudit(ticket, audit.getId()); } public Audit getTicketAudit(Ticket ticket, long id) { checkHasId(ticket); return getTicketAudit(ticket.getId(), id); } public Audit getTicketAudit(long ticketId, long auditId) { return complete(submit(req("GET", tmpl("/tickets/{ticketId}/audits/{auditId}.json").set("ticketId", ticketId) .set("auditId", auditId)), handle(Audit.class, "audit"))); } public void trustTicketAudit(Ticket ticket, Audit audit) { checkHasId(audit); trustTicketAudit(ticket, audit.getId()); } public void trustTicketAudit(Ticket ticket, long id) { checkHasId(ticket); trustTicketAudit(ticket.getId(), id); } public void trustTicketAudit(long ticketId, long auditId) { complete(submit(req("PUT", tmpl("/tickets/{ticketId}/audits/{auditId}/trust.json").set("ticketId", ticketId) .set("auditId", auditId)), handleStatus())); } public void makePrivateTicketAudit(Ticket ticket, Audit audit) { checkHasId(audit); makePrivateTicketAudit(ticket, audit.getId()); } public void makePrivateTicketAudit(Ticket ticket, long id) { checkHasId(ticket); makePrivateTicketAudit(ticket.getId(), id); } public void makePrivateTicketAudit(long ticketId, long auditId) { complete(submit(req("PUT", tmpl("/tickets/{ticketId}/audits/{auditId}/make_private.json").set("ticketId", ticketId) .set("auditId", auditId)), handleStatus())); } public List<Field> getTicketFields() { return complete(submit(req("GET", cnst("/ticket_fields.json")), handleList(Field.class, "ticket_fields"))); } public Field getTicketField(long id) { return complete(submit(req("GET", tmpl("/ticket_fields/{id}.json").set("id", id)), handle(Field.class, "ticket_field"))); } public Field createTicketField(Field field) { return complete(submit(req("POST", cnst("/ticket_fields.json"), JSON, json( Collections.singletonMap("ticket_field", field))), handle(Field.class, "ticket_field"))); } public Field updateTicketField(Field field) { checkHasId(field); return complete(submit(req("PUT", tmpl("/ticket_fields/{id}.json").set("id", field.getId()), JSON, json(Collections.singletonMap("ticket_field", field))), handle(Field.class, "ticket_field"))); } public void deleteTicketField(Field field) { checkHasId(field); deleteTicket(field.getId()); } public void deleteTicketField(long id) { complete(submit(req("DELETE", tmpl("/ticket_fields/{id}.json").set("id", id)), handleStatus())); } public Iterable<SuspendedTicket> getSuspendedTickets() { return new PagedIterable<>(cnst("/suspended_tickets.json"), handleList(SuspendedTicket.class, "suspended_tickets")); } public void deleteSuspendedTicket(SuspendedTicket ticket) { checkHasId(ticket); deleteSuspendedTicket(ticket.getId()); } public void deleteSuspendedTicket(long id) { complete(submit(req("DELETE", tmpl("/suspended_tickets/{id}.json").set("id", id)), handleStatus())); } public Attachment.Upload createUpload(String fileName, byte[] content) { return createUpload(null, fileName, "application/binary", content); } public Attachment.Upload createUpload(String fileName, String contentType, byte[] content) { return createUpload(null, fileName, contentType, content); } public Attachment.Upload createUpload(String token, String fileName, String contentType, byte[] content) { TemplateUri uri = tmpl("/uploads.json{?filename,token}").set("filename", fileName); if (token != null) { uri.set("token", token); } return complete( submit(req("POST", uri, contentType, content), handle(Attachment.Upload.class, "upload"))); } public void associateAttachmentsToArticle(String idArticle, List<Attachment> attachments) { TemplateUri uri = tmpl("/help_center/articles/{article_id}/bulk_attachments.json").set("article_id", idArticle); List<Long> attachmentsIds = new ArrayList<>(); for(Attachment item : attachments){ attachmentsIds.add(item.getId()); } complete(submit(req("POST", uri, JSON, json(Collections.singletonMap("attachment_ids", attachmentsIds))), handleStatus())); } /** * Create upload article with inline false */ public ArticleAttachments createUploadArticle(long articleId, File file) throws IOException { return createUploadArticle(articleId, file, false); } public ArticleAttachments createUploadArticle(long articleId, File file, boolean inline) throws IOException { BoundRequestBuilder builder = client.preparePost(tmpl("/help_center/articles/{id}/attachments.json").set("id", articleId).toString()); if (realm != null) { builder.setRealm(realm); } else { builder.addHeader("Authorization", "Bearer " + oauthToken); } builder.setHeader("Content-Type", "multipart/form-data"); if (inline) builder.addBodyPart(new StringPart("inline", "true")); builder.addBodyPart( new FilePart("file", file, "application/octet-stream", Charset.forName("UTF-8"), file.getName())); final Request req = builder.build(); return complete(submit(req, handle(ArticleAttachments.class, "article_attachment"))); } public void deleteUpload(Attachment.Upload upload) { checkHasToken(upload); deleteUpload(upload.getToken()); } public void deleteUpload(String token) { complete(submit(req("DELETE", tmpl("/uploads/{token}.json").set("token", token)), handleStatus())); } public Attachment getAttachment(Attachment attachment) { checkHasId(attachment); return getAttachment(attachment.getId()); } public Attachment getAttachment(long id) { return complete(submit(req("GET", tmpl("/attachments/{id}.json").set("id", id)), handle(Attachment.class, "attachment"))); } public void deleteAttachment(Attachment attachment) { checkHasId(attachment); deleteAttachment(attachment.getId()); } public void deleteAttachment(long id) { complete(submit(req("DELETE", tmpl("/attachments/{id}.json").set("id", id)), handleStatus())); } public Iterable<Target> getTargets() { return new PagedIterable<>(cnst("/targets.json"), handleTargetList("targets")); } public Target getTarget(long id) { return complete(submit(req("GET", tmpl("/targets/{id}.json").set("id", id)), handle(Target.class, "target"))); } public Target createTarget(Target target) { return complete(submit(req("POST", cnst("/targets.json"), JSON, json(Collections.singletonMap("target", target))), handle(Target.class, "target"))); } public void deleteTarget(long targetId) { complete(submit(req("DELETE", tmpl("/targets/{id}.json").set("id", targetId)), handleStatus())); } public Iterable<Trigger> getTriggers() { return new PagedIterable<>(cnst("/triggers.json"), handleList(Trigger.class, "triggers")); } public Trigger getTrigger(long id) { return complete(submit(req("GET", tmpl("/triggers/{id}.json").set("id", id)), handle(Trigger.class, "trigger"))); } public Trigger createTrigger(Trigger trigger) { return complete(submit(req("POST", cnst("/triggers.json"), JSON, json(Collections.singletonMap("trigger", trigger))), handle(Trigger.class, "trigger"))); } public Trigger updateTrigger(Long triggerId, Trigger trigger) { return complete(submit(req("PUT", tmpl("/triggers/{id}.json").set("id", triggerId), JSON, json(Collections.singletonMap("trigger", trigger))), handle(Trigger.class, "trigger"))); } public void deleteTrigger(long triggerId) { complete(submit(req("DELETE", tmpl("/triggers/{id}.json").set("id", triggerId)), handleStatus())); } // Automations public Iterable<Automation> getAutomations() { return new PagedIterable<>(cnst("/automations.json"), handleList(Automation.class, "automations")); } public Automation getAutomation(long id) { return complete(submit(req("GET", tmpl("/automations/{id}.json").set("id", id)), handle(Automation.class, "automation"))); } public Automation createAutomation(Automation automation) { return complete(submit( req("POST", cnst("/automations.json"), JSON, json(Collections.singletonMap("automation", automation))), handle(Automation.class, "automation"))); } public Automation updateAutomation(Long automationId, Automation automation) { return complete(submit( req("PUT", tmpl("/automations/{id}.json").set("id", automationId), JSON, json(Collections.singletonMap("automation", automation))), handle(Automation.class, "automation"))); } public void deleteAutomation(long automationId) { complete(submit(req("DELETE", tmpl("/automations/{id}.json").set("id", automationId)), handleStatus())); } public Iterable<TwitterMonitor> getTwitterMonitors() { return new PagedIterable<>(cnst("/channels/twitter/monitored_twitter_handles.json"), handleList(TwitterMonitor.class, "monitored_twitter_handles")); } public Iterable<User> getUsers() { return new PagedIterable<>(cnst("/users.json"), handleList(User.class, "users")); } public Iterable<User> getUsersByRole(String role, String... roles) { // Going to have to build this URI manually, because the RFC6570 template spec doesn't support // variables like ?role[]=...role[]=..., which is what Zendesk requires. // See https://developer.zendesk.com/rest_api/docs/core/users#filters final StringBuilder uriBuilder = new StringBuilder("/users.json"); if (roles.length == 0) { uriBuilder.append("?role=").append(encodeUrl(role)); } else { uriBuilder.append("?role[]=").append(encodeUrl(role)); } for (final String curRole : roles) { uriBuilder.append("&role[]=").append(encodeUrl(curRole)); } return new PagedIterable<>(cnst(uriBuilder.toString()), handleList(User.class, "users")); } public Iterable<User> getUsersIncrementally(Date startTime) { return new PagedIterable<>( tmpl("/incremental/users.json{?start_time}").set("start_time", msToSeconds(startTime.getTime())), handleIncrementalList(User.class, "users")); } public Iterable<User> getGroupUsers(long id) { return new PagedIterable<>(tmpl("/groups/{id}/users.json").set("id", id), handleList(User.class, "users")); } public Iterable<User> getOrganizationUsers(long id) { return new PagedIterable<>(tmpl("/organizations/{id}/users.json").set("id", id), handleList(User.class, "users")); } public User getUser(long id) { return complete(submit(req("GET", tmpl("/users/{id}.json").set("id", id)), handle(User.class, "user"))); } public User getAuthenticatedUser() { return complete(submit(req("GET", cnst("/users/me.json")), handle(User.class, "user"))); } public Iterable<UserField> getUserFields() { return complete(submit(req("GET", cnst("/user_fields.json")), handleList(UserField.class, "user_fields"))); } public User createUser(User user) { return complete(submit(req("POST", cnst("/users.json"), JSON, json( Collections.singletonMap("user", user))), handle(User.class, "user"))); } public JobStatus<User> createUsers(User... users) { return createUsers(Arrays.asList(users)); } public JobStatus<User> createUsers(List<User> users) { return complete(createUsersAsync(users)); } public User createOrUpdateUser(User user) { return complete(submit(req("POST", cnst("/users/create_or_update.json"), JSON, json( Collections.singletonMap("user", user))), handle(User.class, "user"))); } public ListenableFuture<JobStatus<User>> createUsersAsync(List<User> users) { return submit(req("POST", cnst("/users/create_many.json"), JSON, json( Collections.singletonMap("users", users))), handleJobStatus(User.class)); } public User updateUser(User user) { checkHasId(user); return complete(submit(req("PUT", tmpl("/users/{id}.json").set("id", user.getId()), JSON, json( Collections.singletonMap("user", user))), handle(User.class, "user"))); } public void deleteUser(User user) { checkHasId(user); deleteUser(user.getId()); } public void deleteUser(long id) { complete(submit(req("DELETE", tmpl("/users/{id}.json").set("id", id)), handleStatus())); } public User suspendUser(long id) { User user = new User(); user.setId(id); user.setSuspended(true); return updateUser(user); } public User unsuspendUser(long id) { User user = new User(); user.setId(id); user.setSuspended(false); return updateUser(user); } public Iterable<User> lookupUserByEmail(String email) { return new PagedIterable<>(tmpl("/users/search.json{?query}").set("query", email), handleList(User.class, "users")); } public Iterable<User> lookupUserByExternalId(String externalId) { return new PagedIterable<>(tmpl("/users/search.json{?external_id}").set("external_id", externalId), handleList(User.class, "users")); } public User getCurrentUser() { return complete(submit(req("GET", cnst("/users/me.json")), handle(User.class, "user"))); } public void resetUserPassword(User user, String password) { checkHasId(user); resetUserPassword(user.getId(), password); } public void resetUserPassword(long id, String password) { complete(submit(req("POST", tmpl("/users/{id}/password.json").set("id", id), JSON, json(Collections.singletonMap("password", password))), handleStatus())); } public void changeUserPassword(User user, String oldPassword, String newPassword) { checkHasId(user); Map<String, String> req = new HashMap<>(); req.put("previous_password", oldPassword); req.put("password", newPassword); complete(submit(req("PUT", tmpl("/users/{id}/password.json").set("id", user.getId()), JSON, json(req)), handleStatus())); } public List<Identity> getUserIdentities(User user) { checkHasId(user); return getUserIdentities(user.getId()); } public List<Identity> getUserIdentities(long userId) { return complete(submit(req("GET", tmpl("/users/{id}/identities.json").set("id", userId)), handleList(Identity.class, "identities"))); } public Identity getUserIdentity(User user, Identity identity) { checkHasId(identity); return getUserIdentity(user, identity.getId()); } public Identity getUserIdentity(User user, long identityId) { checkHasId(user); return getUserIdentity(user.getId(), identityId); } public Identity getUserIdentity(long userId, long identityId) { return complete(submit(req("GET", tmpl("/users/{userId}/identities/{identityId}.json").set("userId", userId) .set("identityId", identityId)), handle( Identity.class, "identity"))); } public List<Identity> setUserPrimaryIdentity(User user, Identity identity) { checkHasId(identity); return setUserPrimaryIdentity(user, identity.getId()); } public List<Identity> setUserPrimaryIdentity(User user, long identityId) { checkHasId(user); return setUserPrimaryIdentity(user.getId(), identityId); } public List<Identity> setUserPrimaryIdentity(long userId, long identityId) { return complete(submit(req("PUT", tmpl("/users/{userId}/identities/{identityId}/make_primary.json").set("userId", userId) .set("identityId", identityId), JSON, null), handleList(Identity.class, "identities"))); } public Identity verifyUserIdentity(User user, Identity identity) { checkHasId(identity); return verifyUserIdentity(user, identity.getId()); } public Identity verifyUserIdentity(User user, long identityId) { checkHasId(user); return verifyUserIdentity(user.getId(), identityId); } public Identity verifyUserIdentity(long userId, long identityId) { return complete(submit(req("PUT", tmpl("/users/{userId}/identities/{identityId}/verify.json") .set("userId", userId) .set("identityId", identityId), JSON, null), handle(Identity.class, "identity"))); } public Identity requestVerifyUserIdentity(User user, Identity identity) { checkHasId(identity); return requestVerifyUserIdentity(user, identity.getId()); } public Identity requestVerifyUserIdentity(User user, long identityId) { checkHasId(user); return requestVerifyUserIdentity(user.getId(), identityId); } public Identity requestVerifyUserIdentity(long userId, long identityId) { return complete(submit(req("PUT", tmpl("/users/{userId}/identities/{identityId}/request_verification.json") .set("userId", userId) .set("identityId", identityId), JSON, null), handle(Identity.class, "identity"))); } public Identity updateUserIdentity(long userId, Identity identity) { checkHasId(identity); return complete(submit(req("PUT", tmpl("/users/{userId}/identities/{identityId}.json") .set("userId", userId) .set("identityId", identity.getId()), JSON, null), handle(Identity.class, "identity"))); } public Identity updateUserIdentity(User user, Identity identity) { checkHasId(user); return updateUserIdentity(user.getId(), identity); } public void deleteUserIdentity(User user, Identity identity) { checkHasId(identity); deleteUserIdentity(user, identity.getId()); } public void deleteUserIdentity(User user, long identityId) { checkHasId(user); deleteUserIdentity(user.getId(), identityId); } public void deleteUserIdentity(long userId, long identityId) { complete(submit(req("DELETE", tmpl("/users/{userId}/identities/{identityId}.json") .set("userId", userId) .set("identityId", identityId) ), handleStatus())); } public Identity createUserIdentity(long userId, Identity identity) { return complete(submit(req("POST", tmpl("/users/{userId}/identities.json").set("userId", userId), JSON, json(Collections.singletonMap("identity", identity))), handle(Identity.class, "identity"))); } public Identity createUserIdentity(User user, Identity identity) { return complete(submit(req("POST", tmpl("/users/{userId}/identities.json").set("userId", user.getId()), JSON, json(Collections.singletonMap("identity", identity))), handle(Identity.class, "identity"))); } public Iterable<AgentRole> getCustomAgentRoles() { return new PagedIterable<>(cnst("/custom_roles.json"), handleList(AgentRole.class, "custom_roles")); } public Iterable<org.zendesk.client.v2.model.Request> getRequests() { return new PagedIterable<>(cnst("/requests.json"), handleList(org.zendesk.client.v2.model.Request.class, "requests")); } public Iterable<org.zendesk.client.v2.model.Request> getOpenRequests() { return new PagedIterable<>(cnst("/requests/open.json"), handleList(org.zendesk.client.v2.model.Request.class, "requests")); } public Iterable<org.zendesk.client.v2.model.Request> getSolvedRequests() { return new PagedIterable<>(cnst("/requests/solved.json"), handleList(org.zendesk.client.v2.model.Request.class, "requests")); } public Iterable<org.zendesk.client.v2.model.Request> getCCRequests() { return new PagedIterable<>(cnst("/requests/ccd.json"), handleList(org.zendesk.client.v2.model.Request.class, "requests")); } public Iterable<org.zendesk.client.v2.model.Request> getUserRequests(User user) { checkHasId(user); return getUserRequests(user.getId()); } public Iterable<org.zendesk.client.v2.model.Request> getUserRequests(long id) { return new PagedIterable<>(tmpl("/users/{id}/requests.json").set("id", id), handleList(org.zendesk.client.v2.model.Request.class, "requests")); } public org.zendesk.client.v2.model.Request getRequest(long id) { return complete(submit(req("GET", tmpl("/requests/{id}.json").set("id", id)), handle(org.zendesk.client.v2.model.Request.class, "request"))); } public org.zendesk.client.v2.model.Request createRequest(org.zendesk.client.v2.model.Request request) { return complete(submit(req("POST", cnst("/requests.json"), JSON, json(Collections.singletonMap("request", request))), handle(org.zendesk.client.v2.model.Request.class, "request"))); } public org.zendesk.client.v2.model.Request updateRequest(org.zendesk.client.v2.model.Request request) { checkHasId(request); return complete(submit(req("PUT", tmpl("/requests/{id}.json").set("id", request.getId()), JSON, json(Collections.singletonMap("request", request))), handle(org.zendesk.client.v2.model.Request.class, "request"))); } public Iterable<Comment> getRequestComments(org.zendesk.client.v2.model.Request request) { checkHasId(request); return getRequestComments(request.getId()); } public Iterable<Comment> getRequestComments(long id) { return new PagedIterable<>(tmpl("/requests/{id}/comments.json").set("id", id), handleList(Comment.class, "comments")); } public Iterable<Comment> getTicketComments(long id) { return new PagedIterable<>(tmpl("/tickets/{id}/comments.json").set("id", id), handleList(Comment.class, "comments")); } public Comment getRequestComment(org.zendesk.client.v2.model.Request request, Comment comment) { checkHasId(comment); return getRequestComment(request, comment.getId()); } public Comment getRequestComment(org.zendesk.client.v2.model.Request request, long commentId) { checkHasId(request); return getRequestComment(request.getId(), commentId); } public Comment getRequestComment(long requestId, long commentId) { return complete(submit(req("GET", tmpl("/requests/{requestId}/comments/{commentId}.json") .set("requestId", requestId) .set("commentId", commentId)), handle(Comment.class, "comment"))); } public Ticket createComment(long ticketId, Comment comment) { Ticket ticket = new Ticket(); ticket.setComment(comment); return complete(submit(req("PUT", tmpl("/tickets/{id}.json").set("id", ticketId), JSON, json(Collections.singletonMap("ticket", ticket))), handle(Ticket.class, "ticket"))); } public Ticket createTicketFromTweet(long tweetId, long monitorId) { Map<String,Object> map = new HashMap<>(); map.put("twitter_status_message_id", tweetId); map.put("monitored_twitter_handle_id", monitorId); return complete(submit(req("POST", cnst("/channels/twitter/tickets.json"), JSON, json(Collections.singletonMap("ticket", map))), handle(Ticket.class, "ticket"))); } public Iterable<Organization> getOrganizations() { return new PagedIterable<>(cnst("/organizations.json"), handleList(Organization.class, "organizations")); } public Iterable<Organization> getOrganizationsIncrementally(Date startTime) { return new PagedIterable<>( tmpl("/incremental/organizations.json{?start_time}") .set("start_time", msToSeconds(startTime.getTime())), handleIncrementalList(Organization.class, "organizations")); } public Iterable<OrganizationField> getOrganizationFields() { //The organization_fields api doesn't seem to support paging return complete(submit(req("GET", cnst("/organization_fields.json")), handleList(OrganizationField.class, "organization_fields"))); } public Iterable<Organization> getAutoCompleteOrganizations(String name) { if (name == null || name.length() < 2) { throw new IllegalArgumentException("Name must be at least 2 characters long"); } return new PagedIterable<>(tmpl("/organizations/autocomplete.json{?name}").set("name", name), handleList(Organization.class, "organizations")); } // TODO getOrganizationRelatedInformation public Organization getOrganization(long id) { return complete(submit(req("GET", tmpl("/organizations/{id}.json").set("id", id)), handle(Organization.class, "organization"))); } public Organization createOrganization(Organization organization) { return complete(submit(req("POST", cnst("/organizations.json"), JSON, json( Collections.singletonMap("organization", organization))), handle(Organization.class, "organization"))); } public JobStatus<Organization> createOrganizations(Organization... organizations) { return createOrganizations(Arrays.asList(organizations)); } public JobStatus createOrganizations(List<Organization> organizations) { return complete(createOrganizationsAsync(organizations)); } public ListenableFuture<JobStatus<Organization>> createOrganizationsAsync(List<Organization> organizations) { return submit(req("POST", cnst("/organizations/create_many.json"), JSON, json( Collections.singletonMap("organizations", organizations))), handleJobStatus(Organization.class)); } public Organization updateOrganization(Organization organization) { checkHasId(organization); return complete(submit(req("PUT", tmpl("/organizations/{id}.json").set("id", organization.getId()), JSON, json( Collections.singletonMap("organization", organization))), handle(Organization.class, "organization"))); } public void deleteOrganization(Organization organization) { checkHasId(organization); deleteOrganization(organization.getId()); } public void deleteOrganization(long id) { complete(submit(req("DELETE", tmpl("/organizations/{id}.json").set("id", id)), handleStatus())); } public Iterable<Organization> lookupOrganizationsByExternalId(String externalId) { if (externalId == null || externalId.length() < 2) { throw new IllegalArgumentException("Name must be at least 2 characters long"); } return new PagedIterable<>( tmpl("/organizations/search.json{?external_id}").set("external_id", externalId), handleList(Organization.class, "organizations")); } public Iterable<OrganizationMembership> getOrganizationMemberships() { return new PagedIterable<>(cnst("/organization_memberships.json"), handleList(OrganizationMembership.class, "organization_memberships")); } public Iterable<OrganizationMembership> getOrganizationMembershipsForOrg(long organization_id) { return new PagedIterable<>(tmpl("/organizations/{organization_id}/organization_memberships.json") .set("organization_id", organization_id), handleList(OrganizationMembership.class, "organization_memberships")); } public Iterable<OrganizationMembership> getOrganizationMembershipsForUser(long user_id) { return new PagedIterable<>(tmpl("/users/{user_id}/organization_memberships.json").set("user_id", user_id), handleList(OrganizationMembership.class, "organization_memberships")); } public OrganizationMembership getOrganizationMembershipForUser(long user_id, long id) { return complete(submit(req("GET", tmpl("/users/{user_id}/organization_memberships/{id}.json").set("user_id", user_id).set("id", id)), handle(OrganizationMembership.class, "organization_membership"))); } public OrganizationMembership getOrganizationMembership(long id) { return complete(submit(req("GET", tmpl("/organization_memberships/{id}.json").set("id", id)), handle(OrganizationMembership.class, "organization_membership"))); } public OrganizationMembership createOrganizationMembership(OrganizationMembership organizationMembership) { return complete(submit(req("POST", cnst("/organization_memberships.json"), JSON, json( Collections.singletonMap("organization_membership", organizationMembership))), handle(OrganizationMembership.class, "organization_membership"))); } public void deleteOrganizationMembership(long id) { complete(submit(req("DELETE", tmpl("/organization_memberships/{id}.json").set("id", id)), handleStatus())); } public Iterable<Group> getGroups() { return new PagedIterable<>(cnst("/groups.json"), handleList(Group.class, "groups")); } public Iterable<Group> getAssignableGroups() { return new PagedIterable<>(cnst("/groups/assignable.json"), handleList(Group.class, "groups")); } public Group getGroup(long id) { return complete(submit(req("GET", tmpl("/groups/{id}.json").set("id", id)), handle(Group.class, "group"))); } public Group createGroup(Group group) { return complete(submit(req("POST", cnst("/groups.json"), JSON, json( Collections.singletonMap("group", group))), handle(Group.class, "group"))); } @Deprecated public List<Group> createGroups(Group... groups) { return createGroups(Arrays.asList(groups)); } @Deprecated public List<Group> createGroups(List<Group> groups) { throw new ZendeskException("API Endpoint for createGroups does not exist."); } public Group updateGroup(Group group) { checkHasId(group); return complete(submit(req("PUT", tmpl("/groups/{id}.json").set("id", group.getId()), JSON, json( Collections.singletonMap("group", group))), handle(Group.class, "group"))); } public void deleteGroup(Group group) { checkHasId(group); deleteGroup(group.getId()); } public void deleteGroup(long id) { complete(submit(req("DELETE", tmpl("/groups/{id}.json").set("id", id)), handleStatus())); } public Iterable<Macro> getMacros(){ return new PagedIterable<>(cnst("/macros.json"), handleList(Macro.class, "macros")); } public Macro getMacro(long macroId){ return complete(submit(req("GET", tmpl("/macros/{id}.json").set("id", macroId)), handle(Macro.class, "macro"))); } public Macro createMacro(Macro macro) { return complete(submit( req("POST", cnst("/macros.json"), JSON, json(Collections.singletonMap("macro", macro))), handle(Macro.class, "macro"))); } public Macro updateMacro(Long macroId, Macro macro) { return complete(submit(req("PUT", tmpl("/macros/{id}.json").set("id", macroId), JSON, json(Collections.singletonMap("macro", macro))), handle(Macro.class, "macro"))); } public Ticket macrosShowChangesToTicket(long macroId) { return complete(submit(req("GET", tmpl("/macros/{id}/apply.json").set("id", macroId)), handle(TicketResult.class, "result"))).getTicket(); } public Ticket macrosShowTicketAfterChanges(long ticketId, long macroId) { return complete(submit(req("GET", tmpl("/tickets/{ticket_id}/macros/{id}/apply.json") .set("ticket_id", ticketId) .set("id", macroId)), handle(TicketResult.class, "result"))).getTicket(); } public List<String> addTagToTicket(long id, String... tags) { return complete(submit( req("PUT", tmpl("/tickets/{id}/tags.json").set("id", id), JSON, json(Collections.singletonMap("tags", tags))), handle(List.class, "tags"))); } public List<String> addTagToTopics(long id, String... tags) { return complete(submit( req("PUT", tmpl("/topics/{id}/tags.json").set("id", id), JSON, json(Collections.singletonMap("tags", tags))), handle(List.class, "tags"))); } public List<String> addTagToOrganisations(long id, String... tags) { return complete(submit( req("PUT", tmpl("/organizations/{id}/tags.json").set("id", id), JSON, json(Collections.singletonMap("tags", tags))), handle(List.class, "tags"))); } public List<String> setTagOnTicket(long id, String... tags) { return complete(submit( req("POST", tmpl("/tickets/{id}/tags.json").set("id", id), JSON, json(Collections.singletonMap("tags", tags))), handle(List.class, "tags"))); } public List<String> setTagOnTopics(long id, String... tags) { return complete(submit( req("POST", tmpl("/topics/{id}/tags.json").set("id", id), JSON, json(Collections.singletonMap("tags", tags))), handle(List.class, "tags"))); } public List<String> setTagOnOrganisations(long id, String... tags) { return complete(submit( req("POST", tmpl("/organizations/{id}/tags.json").set("id", id), JSON, json(Collections.singletonMap("tags", tags))), handle(List.class, "tags"))); } public List<String> removeTagFromTicket(long id, String... tags) { return complete(submit( req("DELETE", tmpl("/tickets/{id}/tags.json").set("id", id), JSON, json(Collections.singletonMap("tags", tags))), handle(List.class, "tags"))); } public List<String> removeTagFromTopics(long id, String... tags) { return complete(submit( req("DELETE", tmpl("/topics/{id}/tags.json").set("id", id), JSON, json(Collections.singletonMap("tags", tags))), handle(List.class, "tags"))); } public List<String> removeTagFromOrganisations(long id, String... tags) { return complete(submit( req("DELETE", tmpl("/organizations/{id}/tags.json").set("id", id), JSON, json(Collections.singletonMap("tags", tags))), handle(List.class, "tags"))); } public Map getIncrementalTicketsResult(long unixEpochTime) { return complete(submit( req("GET", tmpl("/exports/tickets.json?start_time={time}").set( "time", unixEpochTime)), handle(Map.class))); } public Iterable<GroupMembership> getGroupMemberships() { return new PagedIterable<>(cnst("/group_memberships.json"), handleList(GroupMembership.class, "group_memberships")); } public List<GroupMembership> getGroupMembershipByUser(long user_id) { return complete(submit(req("GET", tmpl("/users/{user_id}/group_memberships.json").set("user_id", user_id)), handleList(GroupMembership.class, "group_memberships"))); } public List<GroupMembership> getGroupMemberships(long group_id) { return complete(submit(req("GET", tmpl("/groups/{group_id}/memberships.json").set("group_id", group_id)), handleList(GroupMembership.class, "group_memberships"))); } public Iterable<GroupMembership> getAssignableGroupMemberships() { return new PagedIterable<>(cnst("/group_memberships/assignable.json"), handleList(GroupMembership.class, "group_memberships")); } public List<GroupMembership> getAssignableGroupMemberships(long group_id) { return complete(submit(req("GET", tmpl("/groups/{group_id}/memberships/assignable.json").set("group_id", group_id)), handleList(GroupMembership.class, "group_memberships"))); } public GroupMembership getGroupMembership(long id) { return complete(submit(req("GET", tmpl("/group_memberships/{id}.json").set("id", id)), handle(GroupMembership.class, "group_membership"))); } public GroupMembership getGroupMembership(long user_id, long group_membership_id) { return complete(submit(req("GET", tmpl("/users/{uid}/group_memberships/{gmid}.json").set("uid", user_id) .set("gmid", group_membership_id)), handle(GroupMembership.class, "group_membership"))); } public GroupMembership createGroupMembership(GroupMembership groupMembership) { return complete(submit(req("POST", cnst("/group_memberships.json"), JSON, json( Collections.singletonMap("group_membership", groupMembership))), handle(GroupMembership.class, "group_membership"))); } public GroupMembership createGroupMembership(long user_id, GroupMembership groupMembership) { return complete(submit(req("POST", tmpl("/users/{id}/group_memberships.json").set("id", user_id), JSON, json(Collections.singletonMap("group_membership", groupMembership))), handle(GroupMembership.class, "group_membership"))); } public void deleteGroupMembership(GroupMembership groupMembership) { checkHasId(groupMembership); deleteGroupMembership(groupMembership.getId()); } public void deleteGroupMembership(long id) { complete(submit(req("DELETE", tmpl("/group_memberships/{id}.json").set("id", id)), handleStatus())); } public void deleteGroupMembership(long user_id, GroupMembership groupMembership) { checkHasId(groupMembership); deleteGroupMembership(user_id, groupMembership.getId()); } public void deleteGroupMembership(long user_id, long group_membership_id) { complete(submit(req("DELETE", tmpl("/users/{uid}/group_memberships/{gmid}.json").set("uid", user_id) .set("gmid", group_membership_id)), handleStatus())); } public List<GroupMembership> setGroupMembershipAsDefault(long user_id, GroupMembership groupMembership) { checkHasId(groupMembership); return complete(submit(req("PUT", tmpl("/users/{uid}/group_memberships/{gmid}/make_default.json") .set("uid", user_id).set("gmid", groupMembership.getId()), JSON, json( Collections.singletonMap("group_memberships", groupMembership))), handleList(GroupMembership.class, "results"))); } public Iterable<Forum> getForums() { return new PagedIterable<>(cnst("/forums.json"), handleList(Forum.class, "forums")); } public List<Forum> getForums(long category_id) { return complete(submit(req("GET", tmpl("/categories/{id}/forums.json").set("id", category_id)), handleList(Forum.class, "forums"))); } public Forum getForum(long id) { return complete(submit(req("GET", tmpl("/forums/{id}.json").set("id", id)), handle(Forum.class, "forum"))); } public Forum createForum(Forum forum) { return complete(submit(req("POST", cnst("/forums.json"), JSON, json( Collections.singletonMap("forum", forum))), handle(Forum.class, "forum"))); } public Forum updateForum(Forum forum) { checkHasId(forum); return complete(submit(req("PUT", tmpl("/forums/{id}.json").set("id", forum.getId()), JSON, json( Collections.singletonMap("forum", forum))), handle(Forum.class, "forum"))); } public void deleteForum(Forum forum) { checkHasId(forum); complete(submit(req("DELETE", tmpl("/forums/{id}.json").set("id", forum.getId())), handleStatus())); } public Iterable<Topic> getTopics() { return new PagedIterable<>(cnst("/topics.json"), handleList(Topic.class, "topics")); } public List<Topic> getTopics(long forum_id) { return complete(submit(req("GET", tmpl("/forums/{id}/topics.json").set("id", forum_id)), handleList(Topic.class, "topics"))); } public List<Topic> getTopicsByUser(long user_id) { return complete(submit(req("GET", tmpl("/users/{id}/topics.json").set("id", user_id)), handleList(Topic.class, "topics"))); } public Topic getTopic(long id) { return complete(submit(req("GET", tmpl("/topics/{id}.json").set("id", id)), handle(Topic.class, "topic"))); } public Topic createTopic(Topic topic) { checkHasId(topic); return complete(submit(req("POST", cnst("/topics.json"), JSON, json( Collections.singletonMap("topic", topic))), handle(Topic.class, "topic"))); } public Topic importTopic(Topic topic) { checkHasId(topic); return complete(submit(req("POST", cnst("/import/topics.json"), JSON, json( Collections.singletonMap("topic", topic))), handle(Topic.class, "topic"))); } public List<Topic> getTopics(long id, long... ids) { return complete(submit(req("POST", tmpl("/topics/show_many.json{?ids}").set("ids", idArray(id, ids))), handleList(Topic.class, "topics"))); } public Topic updateTopic(Topic topic) { checkHasId(topic); return complete(submit(req("PUT", tmpl("/topics/{id}.json").set("id", topic.getId()), JSON, json( Collections.singletonMap("topic", topic))), handle(Topic.class, "topic"))); } public void deleteTopic(Topic topic) { checkHasId(topic); complete(submit(req("DELETE", tmpl("/topics/{id}.json").set("id", topic.getId())), handleStatus())); } public List<OrganizationMembership> getOrganizationMembershipByUser(long user_id) { return complete(submit(req("GET", tmpl("/users/{user_id}/organization_memberships.json").set("user_id", user_id)), handleList(OrganizationMembership.class, "organization_memberships"))); } public OrganizationMembership getGroupOrganization(long user_id, long organization_membership_id) { return complete(submit(req("GET", tmpl("/users/{uid}/organization_memberships/{oid}.json").set("uid", user_id) .set("oid", organization_membership_id)), handle(OrganizationMembership.class, "organization_membership"))); } public OrganizationMembership createOrganizationMembership(long user_id, OrganizationMembership organizationMembership) { return complete(submit(req("POST", tmpl("/users/{id}/organization_memberships.json").set("id", user_id), JSON, json(Collections.singletonMap("organization_membership", organizationMembership))), handle(OrganizationMembership.class, "organization_membership"))); } public void deleteOrganizationMembership(long user_id, OrganizationMembership organizationMembership) { checkHasId(organizationMembership); deleteOrganizationMembership(user_id, organizationMembership.getId()); } public void deleteOrganizationMembership(long user_id, long organization_membership_id) { complete(submit(req("DELETE", tmpl("/users/{uid}/organization_memberships/{oid}.json").set("uid", user_id) .set("oid", organization_membership_id)), handleStatus())); } public List<OrganizationMembership> setOrganizationMembershipAsDefault(long user_id, OrganizationMembership organizationMembership) { checkHasId(organizationMembership); return complete(submit(req("POST", tmpl("/users/{uid}/organization_memberships/{gmid}/make_default.json") .set("uid", user_id).set("gmid", organizationMembership.getId()), JSON, json( Collections.singletonMap("group_memberships", organizationMembership))), handleList(OrganizationMembership.class, "results"))); } //-- END BETA public Iterable<SearchResultEntity> getSearchResults(String query) { return new PagedIterable<>(tmpl("/search.json{?query}").set("query", query), handleSearchList("results")); } public <T extends SearchResultEntity> Iterable<T> getSearchResults(Class<T> type, String query) { return getSearchResults(type, query, null); } public <T extends SearchResultEntity> Iterable<T> getSearchResults(Class<T> type, String query, String params) { String typeName = null; for (Map.Entry<String, Class<? extends SearchResultEntity>> entry : searchResultTypes.entrySet()) { if (type.equals(entry.getValue())) { typeName = entry.getKey(); break; } } if (typeName == null) { return Collections.emptyList(); } return new PagedIterable<>(tmpl("/search.json{?query,params}") .set("query", query + "+type:" + typeName) .set("params", params), handleList(type, "results")); } public void notifyApp(String json) { complete(submit(req("POST", cnst("/apps/notify.json"), JSON, json.getBytes()), handleStatus())); } public void updateInstallation(int id, String json) { complete(submit(req("PUT", tmpl("/apps/installations/{id}.json").set("id", id), JSON, json.getBytes()), handleStatus())); } public Iterable<SatisfactionRating> getSatisfactionRatings() { return new PagedIterable<>(cnst("/satisfaction_ratings.json"), handleList(SatisfactionRating.class, "satisfaction_ratings")); } public SatisfactionRating getSatisfactionRating(long id) { return complete(submit(req("GET", tmpl("/satisfaction_ratings/{id}.json").set("id", id)), handle(SatisfactionRating.class, "satisfaction_rating"))); } public SatisfactionRating createSatisfactionRating(long ticketId, SatisfactionRating satisfactionRating) { return complete(submit(req("POST", tmpl("/tickets/{ticketId}/satisfaction_rating.json") .set("ticketId", ticketId), JSON, json(Collections.singletonMap("satisfaction_rating", satisfactionRating))), handle(SatisfactionRating.class, "satisfaction_rating"))); } public SatisfactionRating createSatisfactionRating(Ticket ticket, SatisfactionRating satisfactionRating) { return createSatisfactionRating(ticket.getId(), satisfactionRating); } // TODO search with sort order // TODO search with query building API // Action methods for Help Center /** * Get all articles from help center. * * @return List of Articles. */ public Iterable<Article> getArticles() { return new PagedIterable<>(cnst("/help_center/articles.json"), handleList(Article.class, "articles")); } public Iterable<Article> getArticles(Category category) { checkHasId(category); return new PagedIterable<>( tmpl("/help_center/categories/{id}/articles.json").set("id", category.getId()), handleList(Article.class, "articles")); } public Iterable<Article> getArticlesIncrementally(Date startTime) { return new PagedIterable<>( tmpl("/help_center/incremental/articles.json{?start_time}") .set("start_time", msToSeconds(startTime.getTime())), handleIncrementalList(Article.class, "articles")); } public List<Article> getArticlesFromPage(int page) { return complete(submit(req("GET", tmpl("/help_center/articles.json?page={page}").set("page", page)), handleList(Article.class, "articles"))); } public Article getArticle(long id) { return complete(submit(req("GET", tmpl("/help_center/articles/{id}.json").set("id", id)), handle(Article.class, "article"))); } public Iterable<Translation> getArticleTranslations(Long articleId) { return new PagedIterable<>( tmpl("/help_center/articles/{articleId}/translations.json").set("articleId", articleId), handleList(Translation.class, "translations")); } public Article createArticle(Article article) { checkHasSectionId(article); return complete(submit(req("POST", tmpl("/help_center/sections/{id}/articles.json").set("id", article.getSectionId()), JSON, json(Collections.singletonMap("article", article))), handle(Article.class, "article"))); } public Article updateArticle(Article article) { checkHasId(article); return complete(submit(req("PUT", tmpl("/help_center/articles/{id}.json").set("id", article.getId()), JSON, json(Collections.singletonMap("article", article))), handle(Article.class, "article"))); } public Translation createArticleTranslation(Long articleId, Translation translation) { checkHasArticleId(articleId); return complete(submit(req("POST", tmpl("/help_center/articles/{id}/translations.json").set("id", articleId), JSON, json(Collections.singletonMap("translation", translation))), handle(Translation.class, "translation"))); } public Translation updateArticleTranslation(Long articleId, String locale, Translation translation) { checkHasId(translation); return complete(submit(req("PUT", tmpl("/help_center/articles/{id}/translations/{locale}.json").set("id", articleId).set("locale",locale), JSON, json(Collections.singletonMap("translation", translation))), handle(Translation.class, "translation"))); } public void deleteArticle(Article article) { checkHasId(article); complete(submit(req("DELETE", tmpl("/help_center/articles/{id}.json").set("id", article.getId())), handleStatus())); } /** * Delete attachment from article. * @param attachment */ public void deleteArticleAttachment(ArticleAttachments attachment) { checkHasId(attachment); deleteArticleAttachment(attachment.getId()); } /** * Delete attachment from article. * @param id attachment identifier. */ public void deleteArticleAttachment(long id) { complete(submit(req("DELETE", tmpl("/help_center/articles/attachments/{id}.json").set("id", id)), handleStatus())); } public Iterable<Category> getCategories() { return new PagedIterable<>(cnst("/help_center/categories.json"), handleList(Category.class, "categories")); } public Category getCategory(long id) { return complete(submit(req("GET", tmpl("/help_center/categories/{id}.json").set("id", id)), handle(Category.class, "category"))); } public Iterable<Translation> getCategoryTranslations(Long categoryId) { return new PagedIterable<>( tmpl("/help_center/categories/{categoryId}/translations.json").set("categoryId", categoryId), handleList(Translation.class, "translations")); } public Category createCategory(Category category) { return complete(submit(req("POST", cnst("/help_center/categories.json"), JSON, json(Collections.singletonMap("category", category))), handle(Category.class, "category"))); } public Category updateCategory(Category category) { checkHasId(category); return complete(submit(req("PUT", tmpl("/help_center/categories/{id}.json").set("id", category.getId()), JSON, json(Collections.singletonMap("category", category))), handle(Category.class, "category"))); } public Translation createCategoryTranslation(Long categoryId, Translation translation) { checkHasCategoryId(categoryId); return complete(submit(req("POST", tmpl("/help_center/categories/{id}/translation.json").set("id", categoryId), JSON, json(Collections.singletonMap("translation", translation))), handle(Translation.class, "translation"))); } public Translation updateCategoryTranslation(Long categoryId, String locale, Translation translation) { checkHasId(translation); return complete(submit(req("PUT", tmpl("/help_center/categories/{id}/translations/{locale}.json").set("id", categoryId).set("locale",locale), JSON, json(Collections.singletonMap("translation", translation))), handle(Translation.class, "translation"))); } public void deleteCategory(Category category) { checkHasId(category); complete(submit(req("DELETE", tmpl("/help_center/categories/{id}.json").set("id", category.getId())), handleStatus())); } public Iterable<Section> getSections() { return new PagedIterable<>( cnst("/help_center/sections.json"), handleList(Section.class, "sections")); } public Iterable<Section> getSections(Category category) { checkHasId(category); return new PagedIterable<>( tmpl("/help_center/categories/{id}/sections.json").set("id", category.getId()), handleList(Section.class, "sections")); } public Section getSection(long id) { return complete(submit(req("GET", tmpl("/help_center/sections/{id}.json").set("id", id)), handle(Section.class, "section"))); } public Iterable<Translation> getSectionTranslations(Long sectionId) { return new PagedIterable<>( tmpl("/help_center/sections/{sectionId}/translations.json").set("sectionId", sectionId), handleList(Translation.class, "translations")); } public Section createSection(Section section) { return complete(submit(req("POST", cnst("/help_center/sections.json"), JSON, json(Collections.singletonMap("section", section))), handle(Section.class, "section"))); } public Section updateSection(Section section) { checkHasId(section); return complete(submit(req("PUT", tmpl("/help_center/sections/{id}.json").set("id", section.getId()), JSON, json(Collections.singletonMap("section", section))), handle(Section.class, "section"))); } public Translation createSectionTranslation(Long sectionId, Translation translation) { checkHasSectionId(sectionId); return complete(submit(req("POST", tmpl("/help_center/sections/{id}/translation.json").set("id", sectionId), JSON, json(Collections.singletonMap("translation", translation))), handle(Translation.class, "translation"))); } public Translation updateSectionTranslation(Long sectionId, String locale, Translation translation) { checkHasId(translation); return complete(submit(req("PUT", tmpl("/help_center/sections/{id}/translations/{locale}.json").set("id", sectionId).set("locale",locale), JSON, json(Collections.singletonMap("translation", translation))), handle(Translation.class, "translation"))); } public void deleteSection(Section section) { checkHasId(section); complete(submit(req("DELETE", tmpl("/help_center/sections/{id}.json").set("id", section.getId())), handleStatus())); } public Iterable<Subscription> getUserSubscriptions(User user) { checkHasId(user); return getUserSubscriptions(user.getId()); } public Iterable<Subscription> getUserSubscriptions(Long userId) { return new PagedIterable<>( tmpl("/help_center/users/{userId}/subscriptions.json").set("userId", userId), handleList(Subscription.class, "subscriptions")); } public Iterable<Subscription> getArticleSubscriptions(Long articleId) { return getArticleSubscriptions(articleId, null); } public Iterable<Subscription> getArticleSubscriptions(Long articleId, String locale) { return new PagedIterable<>( tmpl("/help_center{/locale}/articles/{articleId}/subscriptions.json").set("locale", locale) .set("articleId", articleId), handleList(Subscription.class, "subscriptions")); } public Iterable<Subscription> getSectionSubscriptions(Long sectionId) { return getSectionSubscriptions(sectionId, null); } public Iterable<Subscription> getSectionSubscriptions(Long sectionId, String locale) { return new PagedIterable<>( tmpl("/help_center{/locale}/sections/{sectionId}/subscriptions.json").set("locale", locale) .set("sectionId", sectionId), handleList(Subscription.class, "subscriptions")); } /** * Get a list of the current business hours schedules * @return A List of Schedules */ public Iterable<Schedule> getSchedules() { return complete(submit(req("GET", cnst("/business_hours/schedules.json")), handleList(Schedule.class, "schedules"))); } public Schedule getSchedule(Schedule schedule) { checkHasId(schedule); return getSchedule(schedule.getId()); } public Schedule getSchedule(Long scheduleId) { return complete(submit(req("GET", tmpl("/business_hours/schedules/{id}.json").set("id", scheduleId)), handle(Schedule.class, "schedule"))); } public Iterable<Holiday> getHolidaysForSchedule(Schedule schedule) { checkHasId(schedule); return getHolidaysForSchedule(schedule.getId()); } public Iterable<Holiday> getHolidaysForSchedule(Long scheduleId) { return complete(submit(req("GET", tmpl("/business_hours/schedules/{id}/holidays.json").set("id", scheduleId)), handleList(Holiday.class, "holidays"))); } // Helper methods private byte[] json(Object object) { try { return mapper.writeValueAsBytes(object); } catch (JsonProcessingException e) { throw new ZendeskException(e.getMessage(), e); } } private <T> ListenableFuture<T> submit(Request request, ZendeskAsyncCompletionHandler<T> handler) { if (logger.isDebugEnabled()) { if (request.getStringData() != null) { logger.debug("Request {} {}\n{}", request.getMethod(), request.getUrl(), request.getStringData()); } else if (request.getByteData() != null) { logger.debug("Request {} {} {} {} bytes", request.getMethod(), request.getUrl(), request.getHeaders().get("Content-type"), request.getByteData().length); } else { logger.debug("Request {} {}", request.getMethod(), request.getUrl()); } } return client.executeRequest(request, handler); } private static abstract class ZendeskAsyncCompletionHandler<T> extends AsyncCompletionHandler<T> { @Override public void onThrowable(Throwable t) { if (t instanceof IOException) { throw new ZendeskException(t); } else { super.onThrowable(t); } } } private Request req(String method, Uri template) { return req(method, template.toString()); } private static final Pattern RESTRICTED_PATTERN = Pattern.compile("%2B", Pattern.LITERAL); private Request req(String method, String url) { RequestBuilder builder = new RequestBuilder(method); if (realm != null) { builder.setRealm(realm); } else { builder.addHeader("Authorization", "Bearer " + oauthToken); } builder.setUrl(RESTRICTED_PATTERN.matcher(url).replaceAll("+")); // replace out %2B with + due to API restriction return builder.build(); } private Request req(String method, Uri template, String contentType, byte[] body) { RequestBuilder builder = new RequestBuilder(method); if (realm != null) { builder.setRealm(realm); } else { builder.addHeader("Authorization", "Bearer " + oauthToken); } builder.setUrl(RESTRICTED_PATTERN.matcher(template.toString()).replaceAll("+")); //replace out %2B with + due to API restriction builder.addHeader("Content-type", contentType); builder.setBody(body); return builder.build(); } protected ZendeskAsyncCompletionHandler<Void> handleStatus() { return new ZendeskAsyncCompletionHandler<Void>() { @Override public Void onCompleted(Response response) throws Exception { logResponse(response); if (isStatus2xx(response)) { return null; } else if (isRateLimitResponse(response)) { throw new ZendeskResponseRateLimitException(response); } throw new ZendeskResponseException(response); } }; } @SuppressWarnings("unchecked") protected <T> ZendeskAsyncCompletionHandler<T> handle(final Class<T> clazz) { return new ZendeskAsyncCompletionHandler<T>() { @Override public T onCompleted(Response response) throws Exception { logResponse(response); if (isStatus2xx(response)) { return (T) mapper.reader(clazz).readValue(response.getResponseBodyAsStream()); } else if (isRateLimitResponse(response)) { throw new ZendeskResponseRateLimitException(response); } if (response.getStatusCode() == 404) { return null; } throw new ZendeskResponseException(response); } }; } private class BasicAsyncCompletionHandler<T> extends ZendeskAsyncCompletionHandler<T> { private final Class<T> clazz; private final String name; private final Class[] typeParams; public BasicAsyncCompletionHandler(Class clazz, String name, Class... typeParams) { this.clazz = clazz; this.name = name; this.typeParams = typeParams; } @Override public T onCompleted(Response response) throws Exception { logResponse(response); if (isStatus2xx(response)) { if (typeParams.length > 0) { JavaType type = mapper.getTypeFactory().constructParametricType(clazz, typeParams); return mapper.convertValue(mapper.readTree(response.getResponseBodyAsStream()).get(name), type); } return mapper.convertValue(mapper.readTree(response.getResponseBodyAsStream()).get(name), clazz); } else if (isRateLimitResponse(response)) { throw new ZendeskResponseRateLimitException(response); } if (response.getStatusCode() == 404) { return null; } throw new ZendeskResponseException(response); } } protected <T> ZendeskAsyncCompletionHandler<T> handle(final Class<T> clazz, final String name, final Class... typeParams) { return new BasicAsyncCompletionHandler<>(clazz, name, typeParams); } protected <T> ZendeskAsyncCompletionHandler<JobStatus<T>> handleJobStatus(final Class<T> resultClass) { return new BasicAsyncCompletionHandler<JobStatus<T>>(JobStatus.class, "job_status", resultClass) { @Override public JobStatus<T> onCompleted(Response response) throws Exception { JobStatus<T> result = super.onCompleted(response); result.setResultsClass(resultClass); return result; } }; } private static final String NEXT_PAGE = "next_page"; private static final String END_TIME = "end_time"; private static final String COUNT = "count"; private static final int INCREMENTAL_EXPORT_MAX_COUNT_BY_REQUEST = 1000; private abstract class PagedAsyncCompletionHandler<T> extends ZendeskAsyncCompletionHandler<T> { private String nextPage; public void setPagedProperties(JsonNode responseNode, Class<?> clazz) { JsonNode node = responseNode.get(NEXT_PAGE); if (node == null) { this.nextPage = null; if (logger.isDebugEnabled()) { logger.debug(NEXT_PAGE + " property not found, pagination not supported" + (clazz != null ? " for " + clazz.getName() : "")); } } else { this.nextPage = node.asText(); } } public String getNextPage() { return nextPage; } public void setNextPage(String nextPage) { this.nextPage = nextPage; } } private class PagedAsyncListCompletionHandler<T> extends PagedAsyncCompletionHandler<List<T>> { private final Class<T> clazz; private final String name; public PagedAsyncListCompletionHandler(Class<T> clazz, String name) { this.clazz = clazz; this.name = name; } @Override public List<T> onCompleted(Response response) throws Exception { logResponse(response); if (isStatus2xx(response)) { JsonNode responseNode = mapper.readTree(response.getResponseBodyAsBytes()); setPagedProperties(responseNode, clazz); List<T> values = new ArrayList<>(); for (JsonNode node : responseNode.get(name)) { values.add(mapper.convertValue(node, clazz)); } return values; } else if (isRateLimitResponse(response)) { throw new ZendeskResponseRateLimitException(response); } throw new ZendeskResponseException(response); } } protected <T> PagedAsyncCompletionHandler<List<T>> handleList(final Class<T> clazz, final String name) { return new PagedAsyncListCompletionHandler<>(clazz, name); } private static final long FIVE_MINUTES = TimeUnit.MINUTES.toMillis(5); protected <T> PagedAsyncCompletionHandler<List<T>> handleIncrementalList(final Class<T> clazz, final String name) { return new PagedAsyncListCompletionHandler<T>(clazz, name) { @Override public void setPagedProperties(JsonNode responseNode, Class<?> clazz) { JsonNode node = responseNode.get(NEXT_PAGE); if (node == null) { if (logger.isDebugEnabled()) { logger.debug(NEXT_PAGE + " property not found, pagination not supported" + (clazz != null ? " for " + clazz.getName() : "")); } setNextPage(null); return; } JsonNode endTimeNode = responseNode.get(END_TIME); if (endTimeNode == null || endTimeNode.asLong() == 0) { if (logger.isDebugEnabled()) { logger.debug(END_TIME + " property not found, incremental export pagination not supported" + (clazz != null ? " for " + clazz.getName() : "")); } setNextPage(null); return; } /* A request after five minutes ago will result in a 422 responds from Zendesk. Therefore, we stop pagination. */ if (TimeUnit.SECONDS.toMillis(endTimeNode.asLong()) > System.currentTimeMillis() - FIVE_MINUTES) { setNextPage(null); } else { // Taking into account documentation found at https://developer.zendesk.com/rest_api/docs/core/incremental_export#polling-strategy JsonNode countNode = responseNode.get(COUNT); if (countNode == null) { if (logger.isDebugEnabled()) { logger.debug(COUNT + " property not found, incremental export pagination not supported" + (clazz != null ? " for " + clazz.getName() : "")); } setNextPage(null); return; } if (countNode.asInt() < INCREMENTAL_EXPORT_MAX_COUNT_BY_REQUEST) { setNextPage(null); } else { setNextPage(node.asText()); } } } }; } protected PagedAsyncCompletionHandler<List<SearchResultEntity>> handleSearchList(final String name) { return new PagedAsyncCompletionHandler<List<SearchResultEntity>>() { @Override public List<SearchResultEntity> onCompleted(Response response) throws Exception { logResponse(response); if (isStatus2xx(response)) { JsonNode responseNode = mapper.readTree(response.getResponseBodyAsStream()).get(name); setPagedProperties(responseNode, null); List<SearchResultEntity> values = new ArrayList<>(); for (JsonNode node : responseNode) { Class<? extends SearchResultEntity> clazz = searchResultTypes.get(node.get("result_type").asText()); if (clazz != null) { values.add(mapper.convertValue(node, clazz)); } } return values; } else if (isRateLimitResponse(response)) { throw new ZendeskResponseRateLimitException(response); } throw new ZendeskResponseException(response); } }; } protected PagedAsyncCompletionHandler<List<Target>> handleTargetList(final String name) { return new PagedAsyncCompletionHandler<List<Target>>() { @Override public List<Target> onCompleted(Response response) throws Exception { logResponse(response); if (isStatus2xx(response)) { JsonNode responseNode = mapper.readTree(response.getResponseBodyAsBytes()); setPagedProperties(responseNode, null); List<Target> values = new ArrayList<>(); for (JsonNode node : responseNode.get(name)) { Class<? extends Target> clazz = targetTypes.get(node.get("type").asText()); if (clazz != null) { values.add(mapper.convertValue(node, clazz)); } } return values; } else if (isRateLimitResponse(response)) { throw new ZendeskResponseRateLimitException(response); } throw new ZendeskResponseException(response); } }; } protected PagedAsyncCompletionHandler<List<ArticleAttachments>> handleArticleAttachmentsList(final String name) { return new PagedAsyncCompletionHandler<List<ArticleAttachments>>() { @Override public List<ArticleAttachments> onCompleted(Response response) throws Exception { logResponse(response); if (isStatus2xx(response)) { JsonNode responseNode = mapper.readTree(response.getResponseBodyAsBytes()); List<ArticleAttachments> values = new ArrayList<>(); for (JsonNode node : responseNode.get(name)) { values.add(mapper.convertValue(node, ArticleAttachments.class)); } return values; } else if (isRateLimitResponse(response)) { throw new ZendeskResponseRateLimitException(response); } throw new ZendeskResponseException(response); } }; } private TemplateUri tmpl(String template) { return new TemplateUri(url + template); } private Uri cnst(String template) { return new FixedUri(url + template); } private void logResponse(Response response) throws IOException { if (logger.isDebugEnabled()) { logger.debug("Response HTTP/{} {}\n{}", response.getStatusCode(), response.getStatusText(), response.getResponseBody()); } if (logger.isTraceEnabled()) { logger.trace("Response headers {}", response.getHeaders()); } } private static final String UTF_8 = "UTF-8"; private static String encodeUrl(String input) { try { return URLEncoder.encode(input, UTF_8); } catch (UnsupportedEncodingException impossible) { return input; } } private static long msToSeconds(long millis) { return TimeUnit.MILLISECONDS.toSeconds(millis); } private boolean isStatus2xx(Response response) { return response.getStatusCode() / 100 == 2; } private boolean isRateLimitResponse(Response response) { return response.getStatusCode() == 429; } // Static helper methods private static <T> T complete(ListenableFuture<T> future) { try { return future.get(); } catch (InterruptedException e) { throw new ZendeskException(e.getMessage(), e); } catch (ExecutionException e) { if (e.getCause() instanceof ZendeskException) { if (e.getCause() instanceof ZendeskResponseRateLimitException) { throw new ZendeskResponseRateLimitException((ZendeskResponseRateLimitException) e.getCause()); } if (e.getCause() instanceof ZendeskResponseException) { throw new ZendeskResponseException((ZendeskResponseException)e.getCause()); } throw new ZendeskException(e.getCause()); } throw new ZendeskException(e.getMessage(), e); } } private static void checkHasId(Ticket ticket) { if (ticket.getId() == null) { throw new IllegalArgumentException("Ticket requires id"); } } private static void checkHasId(org.zendesk.client.v2.model.Request request) { if (request.getId() == null) { throw new IllegalArgumentException("Request requires id"); } } private static void checkHasId(Audit audit) { if (audit.getId() == null) { throw new IllegalArgumentException("Audit requires id"); } } private static void checkHasId(Comment comment) { if (comment.getId() == null) { throw new IllegalArgumentException("Comment requires id"); } } private static void checkHasId(Field field) { if (field.getId() == null) { throw new IllegalArgumentException("Field requires id"); } } private static void checkHasId(Attachment attachment) { if (attachment.getId() == null) { throw new IllegalArgumentException("Attachment requires id"); } } private static void checkHasId(ArticleAttachments attachments) { if (attachments.getId() == null) { throw new IllegalArgumentException("Attachment requires id"); } } private static void checkHasId(User user) { if (user.getId() == null) { throw new IllegalArgumentException("User requires id"); } } private static void checkHasId(Identity identity) { if (identity.getId() == null) { throw new IllegalArgumentException("Identity requires id"); } } private static void checkHasId(Organization organization) { if (organization.getId() == null) { throw new IllegalArgumentException("Organization requires id"); } } private static void checkHasId(Group group) { if (group.getId() == null) { throw new IllegalArgumentException("Group requires id"); } } private static void checkHasId(GroupMembership groupMembership) { if (groupMembership.getId() == null) { throw new IllegalArgumentException("GroupMembership requires id"); } } private void checkHasId(Forum forum) { if (forum.getId() == null) { throw new IllegalArgumentException("Forum requires id"); } } private void checkHasId(Topic topic) { if (topic.getId() == null) { throw new IllegalArgumentException("Topic requires id"); } } private static void checkHasId(OrganizationMembership organizationMembership) { if (organizationMembership.getId() == null) { throw new IllegalArgumentException("OrganizationMembership requires id"); } } private static void checkHasId(Article article) { if (article.getId() == null) { throw new IllegalArgumentException("Article requires id"); } } private static void checkHasSectionId(Article article) { if (article.getSectionId() == null) { throw new IllegalArgumentException("Article requires section id"); } } private static void checkHasArticleId(Long articleId) { if (articleId == null) { throw new IllegalArgumentException("Translation requires article id"); } } private static void checkHasSectionId(Long articleId) { if (articleId == null) { throw new IllegalArgumentException("Translation requires section id"); } } private static void checkHasCategoryId(Long articleId) { if (articleId == null) { throw new IllegalArgumentException("Translation requires category id"); } } private static void checkHasId(Category category) { if (category.getId() == null) { throw new IllegalArgumentException("Category requires id"); } } private static void checkHasId(Section section) { if (section.getId() == null) { throw new IllegalArgumentException("Section requires id"); } } private static void checkHasId(SuspendedTicket ticket) { if (ticket == null || ticket.getId() == null) { throw new IllegalArgumentException("SuspendedTicket requires id"); } } private static void checkHasId(Translation translation) { if (translation.getId() == null) { throw new IllegalArgumentException("Translation requires id"); } } private static void checkHasId(Schedule schedule) { if (schedule == null || schedule.getId() == null) { throw new IllegalArgumentException("Schedule requires id"); } } private static void checkHasId(Holiday holiday) { if (holiday == null || holiday.getId() == null) { throw new IllegalArgumentException("Holiday requires id"); } } private static void checkHasToken(Attachment.Upload upload) { if (upload.getToken() == null) { throw new IllegalArgumentException("Upload requires token"); } } private static List<Long> idArray(long id, long... ids) { List<Long> result = new ArrayList<>(ids.length + 1); result.add(id); for (long i : ids) { result.add(i); } return result; } private static List<String> statusArray(Status... statuses) { List<String> result = new ArrayList<>(statuses.length); for (Status s : statuses) { result.add(s.toString()); } return result; } public static ObjectMapper createMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.setDateFormat(new ISO8601DateFormat()); return mapper; } // Helper classes private class PagedIterable<T> implements Iterable<T> { private final Uri url; private final PagedAsyncCompletionHandler<List<T>> handler; private PagedIterable(Uri url, PagedAsyncCompletionHandler<List<T>> handler) { this.handler = handler; this.url = url; } public Iterator<T> iterator() { return new PagedIterator(url); } private class PagedIterator implements Iterator<T> { private Iterator<T> current; private String nextPage; public PagedIterator(Uri url) { this.nextPage = url.toString(); } public boolean hasNext() { if (current == null || !current.hasNext()) { if (nextPage == null || nextPage.equalsIgnoreCase("null")) { return false; } List<T> values = complete(submit(req("GET", nextPage), handler)); nextPage = handler.getNextPage(); current = values.iterator(); } return current.hasNext(); } public T next() { if (!hasNext()) { throw new NoSuchElementException(); } return current.next(); } public void remove() { throw new UnsupportedOperationException(); } } } public static class Builder { private AsyncHttpClient client = null; private final String url; private String username = null; private String password = null; private String token = null; private String oauthToken = null; public Builder(String url) { this.url = url; } public Builder setClient(AsyncHttpClient client) { this.client = client; return this; } public Builder setUsername(String username) { this.username = username; return this; } public Builder setPassword(String password) { this.password = password; if (password != null) { this.token = null; this.oauthToken = null; } return this; } public Builder setToken(String token) { this.token = token; if (token != null) { this.password = null; this.oauthToken = null; } return this; } public Builder setOauthToken(String oauthToken) { this.oauthToken = oauthToken; if (oauthToken != null) { this.password = null; this.token = null; } return this; } public Builder setRetry(boolean retry) { return this; } public Zendesk build() { if (token != null) { return new Zendesk(client, url, username + "/token", token); } else if (oauthToken != null) { return new Zendesk(client, url, oauthToken); } return new Zendesk(client, url, username, password); } } }
package refinedstorage; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; import refinedstorage.gui.grid.ClientStack; import refinedstorage.proxy.CommonProxy; import java.util.ArrayList; import java.util.List; @Mod(modid = RefinedStorage.ID, version = RefinedStorage.VERSION) public final class RefinedStorage { public static final String ID = "refinedstorage"; public static final String VERSION = "0.8.13"; @SidedProxy(clientSide = "refinedstorage.proxy.ClientProxy", serverSide = "refinedstorage.proxy.ServerProxy") public static CommonProxy PROXY; @Instance public static RefinedStorage INSTANCE; public final SimpleNetworkWrapper network = NetworkRegistry.INSTANCE.newSimpleChannel(ID); public final CreativeTabs tab = new CreativeTabs(ID) { @Override public ItemStack getIconItemStack() { return new ItemStack(RefinedStorageItems.STORAGE_HOUSING); } @Override public Item getTabIconItem() { return null; } }; public List<ClientStack> items = new ArrayList<ClientStack>(); public int controllerUsage; public int cableUsage; public int constructorUsage; public int crafterUsage; public int crafterPerPatternUsage; public int craftingMonitorUsage; public int destructorUsage; public int detectorUsage; public int diskDriveUsage; public int diskDrivePerDiskUsage; public int externalStorageUsage; public int externalStoragePerStorageUsage; public int exporterUsage; public int importerUsage; public int interfaceUsage; public int relayUsage; public int soldererUsage; public int storageUsage; public int wirelessTransmitterUsage; public int gridUsage; public int craftingGridUsage; public int patternGridUsage; public int controllerCapacity; public boolean controllerUsesEnergy; public int wirelessTransmitterBaseRange; public int rangeUpgradeUsage; public int speedUpgradeUsage; public int craftingUpgradeUsage; public int stackUpgradeUsage; public int wirelessTransmitterRangePerUpgrade; @EventHandler public void preInit(FMLPreInitializationEvent e) { PROXY.preInit(e); Configuration config = new Configuration(e.getSuggestedConfigurationFile()); controllerUsage = config.getInt("controller", "energy", 0, 0, Integer.MAX_VALUE, "The base energy used by the Controller"); cableUsage = config.getInt("cable", "energy", 0, 0, Integer.MAX_VALUE, "The energy used by Cables"); constructorUsage = config.getInt("constructor", "energy", 1, 0, Integer.MAX_VALUE, "The energy used by Constructors"); crafterUsage = config.getInt("crafter", "energy", 2, 0, Integer.MAX_VALUE, "The base energy used by Crafters"); crafterPerPatternUsage = config.getInt("crafterPerPattern", "energy", 1, 0, Integer.MAX_VALUE, "The additional energy used per Pattern in a Crafter"); craftingMonitorUsage = config.getInt("craftingMonitor", "energy", 2, 0, Integer.MAX_VALUE, "The energy used by Crafting Monitors"); destructorUsage = config.getInt("destructor", "energy", 1, 0, Integer.MAX_VALUE, "The energy used by Destructors"); detectorUsage = config.getInt("detector", "energy", 2, 0, Integer.MAX_VALUE, "The energy used by Detectors"); diskDriveUsage = config.getInt("diskDrive", "energy", 0, 0, Integer.MAX_VALUE, "The base energy used by Disk Drives"); diskDrivePerDiskUsage = config.getInt("diskDrivePerDisk", "energy", 1, 0, Integer.MAX_VALUE, "The additional energy used by Storage Disks in Disk Drives"); externalStorageUsage = config.getInt("externalStorage", "energy", 0, 0, Integer.MAX_VALUE, "The base energy used by External Storages"); externalStoragePerStorageUsage = config.getInt("externalStoragePerStorage", "energy", 1, 0, Integer.MAX_VALUE, "The additional energy used per connected storage to an External Storage"); exporterUsage = config.getInt("exporter", "energy", 1, 0, Integer.MAX_VALUE, "The energy used by Exporters"); importerUsage = config.getInt("importer", "energy", 1, 0, Integer.MAX_VALUE, "The energy used by Importers"); interfaceUsage = config.getInt("interface", "energy", 3, 0, Integer.MAX_VALUE, "The energy used by Interfaces"); relayUsage = config.getInt("relay", "energy", 1, 0, Integer.MAX_VALUE, "The energy used by Relays"); soldererUsage = config.getInt("solderer", "energy", 3, 0, Integer.MAX_VALUE, "The energy used by Solderers"); storageUsage = config.getInt("storage", "energy", 1, 0, Integer.MAX_VALUE, "The energy used by Storage Blocks"); wirelessTransmitterUsage = config.getInt("wirelessTransmitter", "energy", 8, 0, Integer.MAX_VALUE, "The energy used by Wireless Transmitters"); gridUsage = config.getInt("grid", "energy", 2, 0, Integer.MAX_VALUE, "The energy used by Grids"); craftingGridUsage = config.getInt("craftingGrid", "energy", 4, 0, Integer.MAX_VALUE, "The energy used by Crafting Grids"); patternGridUsage = config.getInt("patternGrid", "energy", 3, 0, Integer.MAX_VALUE, "The energy used by Pattern Grids"); controllerCapacity = config.getInt("capacity", "controller", 32000, 0, Integer.MAX_VALUE, "The energy capacity of the Controller"); controllerUsesEnergy = config.getBoolean("usesEnergy", "controller", true, "Whether the Controller uses energy"); wirelessTransmitterBaseRange = config.getInt("range", "wirelessTransmitter", 16, 0, Integer.MAX_VALUE, "The base range of the Wireless Transmitter"); wirelessTransmitterRangePerUpgrade = config.getInt("rangePerUpgrade", "wirelessTransmitter", 8, 0, Integer.MAX_VALUE, "The additional range per Range Upgrade in the Wireless Transmitter"); rangeUpgradeUsage = config.getInt("range", "upgrades", 8, 0, Integer.MAX_VALUE, "The additional energy used per Range Upgrade"); speedUpgradeUsage = config.getInt("speed", "upgrades", 2, 0, Integer.MAX_VALUE, "The additional energy used per Speed Upgrade"); craftingUpgradeUsage = config.getInt("crafting", "upgrades", 5, 0, Integer.MAX_VALUE, "The additional energy used per Crafting Upgrade"); stackUpgradeUsage = config.getInt("stack", "upgrades", 12, 0, Integer.MAX_VALUE, "The additional energy used per Stack Upgrade"); config.save(); } @EventHandler public void init(FMLInitializationEvent e) { PROXY.init(e); } @EventHandler public void postInit(FMLPostInitializationEvent e) { PROXY.postInit(e); } public static boolean hasJei() { return Loader.isModLoaded("JEI"); } public static boolean hasIC2() { return Loader.isModLoaded("IC2"); } public static boolean hasTesla() { return Loader.isModLoaded("Tesla"); } }
package se.fnord.katydid.internal; import se.fnord.katydid.ComparisonStatus; import java.nio.ByteBuffer; public class Int extends AbstractDataTester { public enum IntFormat {HEX, SIGNED, UNSIGNED}; private final int elementWidth; private final Number[] values; private final IntFormatter formatter; public Int(String name, IntFormat format, int elementWidth, Number... values) { super(name); this.elementWidth = elementWidth; this.values = values; this.formatter = formatterFor(elementWidth, format); } private long read(ByteBuffer bb) { return Util.read(bb, elementWidth); } private void write(ByteBuffer bb, long value) { Util.write(bb, elementWidth, value); } @Override protected int sizeOf(int itemIndex) { return elementWidth; } @Override protected int itemCount() { return values.length; } @Override public ComparisonStatus compareToLevel0(TestingContext context) { ByteBuffer bb = context.buffer(); ComparisonStatus status = ComparisonStatus.EQUAL; for (int i = 0; i < values.length; i++) { if (!checkHasRemaining(context, i)) return ComparisonStatus.ERROR; if (!checkEquals(context, i, values[i].longValue(), read(bb))) status = ComparisonStatus.NOT_EQUAL; } return status; } @Override public String formatName(TestingContext context, int index) { if (values.length == 1) { return context.name(); } return String.format("%s[%d]", context.name(), index); } @Override public String formatValue(Object v) { return formatter.format(((Number) v).longValue()); } @Override public void toBuffer(ByteBuffer bb) { for (int i = 0; i < values.length; i++) { write(bb, values[i].longValue()); } } static interface IntFormatter { String format(long value); } static long mask(int width) { if (width == 8) { return -1L; } return (1L << (width * 8)) - 1; } static long signBit(int width) { return 1L << (width * 8 - 1); } static Int.IntFormatter formatterFor(int width, IntFormat format) { if (width == 0) { throw new IllegalArgumentException(); } switch (format) { case HEX: return hexFormatterFor(width); case SIGNED: return signedFormatterFor(width); case UNSIGNED: return unsignedFormatterFor(width); } throw new IllegalArgumentException(); } private static Int.IntFormatter hexFormatterFor(int width) { final long mask = mask(width); final String format = String.format("%%0%dx", width * 2); return new Int.IntFormatter() { @Override public String format(long value) { return String.format(format, value & mask); } }; } private static Int.IntFormatter signedFormatterFor(final int width) { final long mask = mask(width); final long signBit = signBit(width); return new Int.IntFormatter() { @Override public String format(long value) { if (width < 8) { value &= mask; // Most hackish sign-extension for negative values if ((value & signBit) != 0L) { value = -(~(value - 1L) & mask); } } return Long.toString(value); } }; } private static Int.IntFormatter unsignedFormatterFor(int width) { final long mask = mask(width); return new Int.IntFormatter() { @Override public String format(long value) { value &= mask; // The value is already unsigned, no magic needed. if (value >= 0) return Long.toString(value); // Unsigned divide by 10 final long quotient = (value >>> 1) / 5; final long remainder = value - quotient * 10; return Long.toString(quotient) + remainder; } }; } }
package seedu.address.model.item; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.commons.util.CollectionUtil; import seedu.address.model.tag.UniqueTagList; import java.util.Objects; import java.util.Set; /** * Represents a Item in the address book. * Guarantees: details are present and not null, field values are validated. */ public class Item implements ReadOnlyItem { private ItemType itemType; private Name name; private Date startDate; private Time startTime; private Date endDate; private Time endTime; private UniqueTagList tags; /** * Convenience constructor for tasks. Calls primary constructor with empty fields for startDate, startTime, endDate, endTime * */ public Item(ItemType itemType, Name name, UniqueTagList tags) { this(itemType, name, new Date(), new Time(), new Date(), new Time(), tags); } /** * Convenience constructor for deadlines. Calls primary constructor with empty fields for startDate and startTime * */ public Item(ItemType itemType, Name name, Date endDate, Time endTime, UniqueTagList tags) { this(itemType, name, new Date(), new Time(), endDate, endTime, tags); } /** * Every field must be present and not null. */ public Item(ItemType itemType, Name name, Date startDate, Time startTime, Date endDate, Time endTime, UniqueTagList tags) { assert !CollectionUtil.isAnyNull(itemType, name, endDate, endTime, tags); this.itemType = itemType; this.name = name; this.startDate = startDate; this.startTime = startTime; this.endDate = endDate; this.endTime = endTime; this.tags = new UniqueTagList(tags); // protect internal tags from changes in the arg list } /** * Copy constructor. */ public Item(ReadOnlyItem source) { this(source.getItemType(), source.getName(), source.getStartDate(), source.getStartTime(), source.getEndDate(), source.getEndTime(), source.getTags()); } @Override public ItemType getItemType() { return itemType; } @Override public Name getName() { return name; } public void setName(String name) throws IllegalValueException { this.name = new Name(name); } @Override public Date getStartDate() { return startDate; } @Override public Time getStartTime() { return startTime; } @Override public Date getEndDate() { return endDate; } public void setEndDate(String endDate) throws IllegalValueException { this.endDate = new Date(endDate); } @Override public Time getEndTime() { return endTime; } @Override public UniqueTagList getTags() { return new UniqueTagList(tags); } /** * Replaces this person's tags with the tags in the argument tag list. */ public void setTags(UniqueTagList replacement) { tags.setTags(replacement); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof ReadOnlyItem // instanceof handles nulls && this.isSameStateAs((ReadOnlyItem) other)); } @Override public int hashCode() { // use this method for custom fields hashing instead of implementing your own return Objects.hash(itemType, name, endDate, endTime, tags); } @Override public String toString() { return getAsText(); } }
package sssj.index; import static sssj.base.Commons.*; import it.unimi.dsi.fastutil.BidirectionalIterator; import it.unimi.dsi.fastutil.ints.Int2DoubleMap.Entry; import it.unimi.dsi.fastutil.ints.Int2ReferenceMap; import it.unimi.dsi.fastutil.ints.Int2ReferenceOpenHashMap; import it.unimi.dsi.fastutil.longs.Long2DoubleMap; import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap; import java.util.Iterator; import java.util.Map; import org.apache.commons.math3.util.FastMath; import sssj.base.CircularBuffer; import sssj.base.ResidualList; import sssj.base.Vector; import sssj.index.L2APIndex.L2APPostingEntry; import com.google.common.primitives.Doubles; public class StreamingL2APIndex implements Index { private final Int2ReferenceMap<StreamingL2APPostingList> idx = new Int2ReferenceOpenHashMap<>(); private final ResidualList resList = new ResidualList(); private final Long2DoubleOpenHashMap ps = new Long2DoubleOpenHashMap(); private final Long2DoubleOpenHashMap accumulator = new Long2DoubleOpenHashMap(); private final Long2DoubleOpenHashMap matches = new Long2DoubleOpenHashMap(); private final double theta; private final double lambda; private final double tau; private final Vector maxVector; // \hat{c_w} private int size = 0; public StreamingL2APIndex(double theta, double lambda) { this.theta = theta; this.lambda = lambda; this.maxVector = new Vector(); this.tau = tau(theta, lambda); System.out.println("Tau = " + tau); precomputeFFTable(lambda, (int) Math.ceil(tau)); } @Override public Map<Long, Double> queryWith(final Vector v, final boolean addToIndex) { accumulator.clear(); matches.clear(); Vector updates = maxVector.updateMaxByDimension(v); /* reindexing */ reindex(updates); /* candidate generation */ generateCandidates(v); /* candidate verification */ verifyCandidates(v); /* index building */ if (addToIndex) addToIndex(v); return matches; } private final void reindex(Vector updates) { // TODO use updates for reindexing } private final void generateCandidates(final Vector v) { // upper bound on the forgetting factor w.r.t. the maximum vector // TODO can be tightened with a deltaT per dimension final long maxDeltaT = v.timestamp() - maxVector.timestamp(); if (maxDeltaT > tau) // time filtering return; final double maxff = forgettingFactor(lambda, maxDeltaT); // rs3, enhanced remscore bound with addded forgetting factor, for Streaming maxVector is the max vector in the index double remscore = Vector.similarity(v, maxVector); // rs3, enhanced remscore bound double l2remscore = 1, // rs4 rst = 1, squaredQueryPrefixMagnitude = 1; for (BidirectionalIterator<Entry> vecIter = v.int2DoubleEntrySet().fastIterator(v.int2DoubleEntrySet().last()); vecIter .hasPrevious();) { // iterate over v in reverse order final Entry e = vecIter.previous(); final int dimension = e.getIntKey(); final double queryWeight = e.getDoubleValue(); // forgetting factor applied directly to the prefix and l2prefix bounds final double rscore = Math.min(remscore, l2remscore) * maxff; // FIXME ff squaredQueryPrefixMagnitude -= queryWeight * queryWeight; StreamingL2APPostingList list; if ((list = idx.get(dimension)) != null) { // TODO possibly size filtering: remove entries from the posting list with |y| < minsize (need to save size in the posting list) for (Iterator<L2APPostingEntry> listIter = list.iterator(); listIter.hasNext();) { final L2APPostingEntry pe = listIter.next(); final long targetID = pe.getID(); // time filtering final long deltaT = v.timestamp() - targetID; if (Doubles.compare(deltaT, tau) > 0) { listIter.remove(); size continue; } final double ff = forgettingFactor(lambda, deltaT); if (accumulator.containsKey(targetID) || Double.compare(rscore, theta) >= 0) { final double targetWeight = pe.getWeight(); final double additionalSimilarity = queryWeight * targetWeight; // x_j * y_j accumulator.addTo(targetID, additionalSimilarity); // A[y] += x_j * y_j final double l2bound = accumulator.get(targetID) + FastMath.sqrt(squaredQueryPrefixMagnitude) * pe.magnitude; // A[y] + ||x'_j|| * ||y'_j|| // forgetting factor applied directly to the l2bound if (Double.compare(l2bound * ff, theta) < 0) // FIXME ff accumulator.remove(targetID); // prune this candidate (early verification) } } remscore -= queryWeight * maxVector.get(dimension); // rs_3 -= x_j * \hat{c_w} rst -= queryWeight * queryWeight; // rs_t -= x_j^2 l2remscore = FastMath.sqrt(rst); // rs_4 = sqrt(rs_t) } } } private final void verifyCandidates(final Vector v) { for (Long2DoubleMap.Entry e : accumulator.long2DoubleEntrySet()) { // TODO possibly use size filtering (sz_3) final long candidateID = e.getLongKey(); final long deltaT = v.timestamp() - candidateID; final double ff = forgettingFactor(lambda, deltaT); if (Double.compare((e.getDoubleValue() + ps.get(candidateID)) * ff, theta) < 0) // A[y] = dot(x, y'') // FIXME ff continue; // l2 pruning final long lowWatermark = (long) Math.floor(v.timestamp() - tau); final Vector residual = resList.getAndPrune(candidateID, lowWatermark); assert (residual != null); double dpscore = e.getDoubleValue() + Math.min(v.maxValue() * residual.size(), residual.maxValue() * v.size()); if (Double.compare(dpscore * ff, theta) < 0) // FIXME ff continue; // dpscore, eq. (5) double score = e.getDoubleValue() + Vector.similarity(v, residual); // dot(x, y) = A[y] + dot(x, y') score *= ff; // apply forgetting factor // FIXME ff if (Double.compare(score, theta) >= 0) // final check matches.put(candidateID, score); } } private final void addToIndex(final Vector v) { double b1 = 0, bt = 0, b3 = 0, pscore = 0; boolean psSaved = false; final Vector residual = new Vector(v.timestamp()); // upper bound on the forgetting factor w.r.t. the maximum vector // TODO can be tightened with a deltaT per dimension // final long maxDeltaT = v.timestamp() - maxVector.timestamp(); // final double maxff = forgettingFactor(lambda, maxDeltaT); // FIXME maxDeltaT can be larger than tau. How do we use it? for (Entry e : v.int2DoubleEntrySet()) { final int dimension = e.getIntKey(); final double weight = e.getDoubleValue(); pscore = Math.min(b1, b3); b1 += weight * maxVector.get(dimension); bt += weight * weight; b3 = FastMath.sqrt(bt); // forgetting factor applied directly bounds // if (Double.compare(Math.min(b1, b3) * maxff, theta) >= 0) { // FIXME ff if (Double.compare(Math.min(b1, b3), theta) >= 0) { // FIXME ff if (!psSaved) { assert (!ps.containsKey(v.timestamp())); ps.put(v.timestamp(), pscore); psSaved = true; } StreamingL2APPostingList list; if ((list = idx.get(dimension)) == null) { list = new StreamingL2APPostingList(); idx.put(dimension, list); } list.add(v.timestamp(), weight, b3); size++; } else { residual.put(dimension, weight); } } resList.add(residual); } @Override public int size() { return size; } @Override public String toString() { return "StreamingL2APIndex [idx=" + idx + ", resList=" + resList + ", ps=" + ps + "]"; } public static class StreamingL2APPostingList implements Iterable<L2APPostingEntry> { private final CircularBuffer ids = new CircularBuffer(); // longs private final CircularBuffer weights = new CircularBuffer(); // doubles private final CircularBuffer magnitudes = new CircularBuffer(); // doubles public void add(long vectorID, double weight, double magnitude) { ids.pushLong(vectorID); weights.pushDouble(weight); magnitudes.pushDouble(magnitude); } @Override public String toString() { return "[ids=" + ids + ", weights=" + weights + ", magnitudes=" + magnitudes + "]"; } @Override public Iterator<L2APPostingEntry> iterator() { return new Iterator<L2APPostingEntry>() { private final L2APPostingEntry entry = new L2APPostingEntry(); private int i = 0; @Override public boolean hasNext() { return i < ids.size(); } @Override public L2APPostingEntry next() { entry.setID(ids.peekLong(i)); entry.setWeight(weights.peekDouble(i)); entry.setMagnitude(magnitudes.peekDouble(i)); i++; return entry; } @Override public void remove() { i assert (i == 0); // removal always happens at the head ids.popLong(); weights.popDouble(); magnitudes.popDouble(); } }; } } }
package wyjs.tasks; import static wybs.util.AbstractCompilationUnit.ITEM_bool; import static wybs.util.AbstractCompilationUnit.ITEM_byte; import static wybs.util.AbstractCompilationUnit.ITEM_int; import static wybs.util.AbstractCompilationUnit.ITEM_null; import static wybs.util.AbstractCompilationUnit.ITEM_utf8; import static wyil.lang.WyilFile.EXPR_arrayaccess; import static wyil.lang.WyilFile.EXPR_arrayborrow; import static wyil.lang.WyilFile.EXPR_dereference; import static wyil.lang.WyilFile.EXPR_fielddereference; import static wyil.lang.WyilFile.EXPR_recordaccess; import static wyil.lang.WyilFile.EXPR_recordborrow; import static wyil.lang.WyilFile.EXPR_variablecopy; import static wyil.lang.WyilFile.EXPR_variablemove; import static wyil.lang.WyilFile.EXPR_tupleinitialiser; import static wyil.lang.WyilFile.TYPE_array; import static wyil.lang.WyilFile.TYPE_bool; import static wyil.lang.WyilFile.TYPE_byte; import static wyil.lang.WyilFile.TYPE_int; import static wyil.lang.WyilFile.TYPE_nominal; import static wyil.lang.WyilFile.TYPE_null; import static wyil.lang.WyilFile.TYPE_record; import static wyil.lang.WyilFile.TYPE_reference; import static wyil.lang.WyilFile.TYPE_union; import static wyil.lang.WyilFile.TYPE_method; import static wyil.lang.WyilFile.TYPE_function; import static wyil.lang.WyilFile.TYPE_property; import static wyjs.core.JavaScriptFile.and; import static wyjs.core.JavaScriptFile.not; import static wyjs.core.JavaScriptFile.or; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import wybs.lang.Build; import wybs.lang.SyntacticException; import wybs.lang.SyntacticHeap; import wybs.lang.SyntacticItem; import wybs.util.AbstractCompilationUnit.Identifier; import wybs.util.AbstractCompilationUnit.Tuple; import wybs.util.AbstractCompilationUnit.Value; import wyfs.util.ArrayUtils; import wyfs.util.Pair; import wyil.lang.WyilFile; import wyil.lang.WyilFile.Decl; import wyil.lang.WyilFile.Expr; import wyil.lang.WyilFile.LVal; import wyil.lang.WyilFile.Modifier; import wyil.lang.WyilFile.Stmt; import wyil.lang.WyilFile.Type; import wyil.util.AbstractVisitor; import wyil.util.IncrementalSubtypingEnvironment; import wyil.util.Subtyping; import wyjs.core.JavaScriptFile; import wyjs.core.JavaScriptFile.Operator.Kind; import wyjs.core.JavaScriptFile.*; import wyil.util.TypeMangler; import wyil.util.AbstractTranslator; public class JavaScriptCompiler extends AbstractTranslator<Term, Term, Term> { /** * Provides a standard mechanism for writing out type mangles. */ private final static TypeMangler mangler = new TypeMangler.Default(); /** * Provides a standard mechanism for checking whether two Whiley types are * subtypes or not. */ private final static Subtyping.Environment subtyping = new IncrementalSubtypingEnvironment(); /** * Represents the JavaScriptFile which is being written to. */ private final JavaScriptFile jsFile; /** * Used to determine what runtime type tests are required. */ private final HashSet<Pair<Type,Type>> runtimeTypeTests = new HashSet<>(); /** * Provides numbering for temporary variables to ensure uniqueness. */ private int temporaryIndex = 0; public JavaScriptCompiler(Build.Meter meter, JavaScriptFile jsFile) { super(meter,subtyping); this.jsFile = jsFile; } public void visitModule(WyilFile wf) { // Translate local units for (Decl.Unit unit : wf.getModule().getUnits()) { for(Decl decl : unit.getDeclarations()) { Declaration d = (Declaration) visitDeclaration(decl); if(d != null) { jsFile.getDeclarations().add(d); } } } // Translate all type tests translateTypeTests(runtimeTypeTests); // Release memory runtimeTypeTests.clear(); } // Declarations @Override public Term constructImport(Decl.Import d) { // NOTE: it's unclear what we can or should do here. return null; } @Override public Term constructType(Decl.Type d, List<Term> clauses) { // NOTE: an interesting question is whether we need to always generate this // method, especially in cases where there is no invariant. String name = toMangledName(d); String param = d.getVariableDeclaration().getName().toString(); // Construct body from translated clauses Term body; if(clauses.isEmpty()) { return null; } else { body = new Return(and(clauses)); } // Done return new JavaScriptFile.Method(name,Arrays.asList(param),new Block(body)); } @Override public Term constructStaticVariable(Decl.StaticVariable decl, Term initialiser) { // Determine qualified name String name = toMangledName(decl); // Determine appropriate modifier JavaScriptFile.VariableDeclaration.Kind kind=toVariableKind(decl); return new JavaScriptFile.VariableDeclaration(kind,name,initialiser); } @Override public Term constructProperty(Decl.Property decl, List<Term> clauses) { // Determine qualified name String name = toMangledName(decl); // Translate parameters List<String> parameters = toParameterNames(decl.getParameters()); // Construct body from translated clauses Term body = new Return(and(clauses)); // Done return new JavaScriptFile.Method(name, parameters, new Block(body)); } @Override public Term constructFunction(Decl.Function decl, List<Term> precondition, List<Term> postcondition, Term _body) { if (decl.getModifiers().match(Modifier.Native.class) == null) { Block body = (Block) _body; // Determine qualified name String name = toMangledName(decl); // Translate parameters List<String> parameters = toParameterNames(decl.getParameters()); declareNamedReturns(decl, body); // Done return new JavaScriptFile.Method(name, parameters, body); } else { // Native methods don't generate any JavaScript return null; } } @Override public Term constructMethod(Decl.Method decl, List<Term> precondition, List<Term> postcondition, Term body) { if (decl.getModifiers().match(Modifier.Native.class) == null) { // Determine qualified name String name = toMangledName(decl); // Translate parameters List<String> parameters = toParameterNames(decl.getParameters()); // Done return new JavaScriptFile.Method(name, parameters, (Block) body); } else { // Native methods don't generate any JavaScript return null; } } @Override public Term constructLambda(Decl.Lambda decl, Term term) { List<String> parameters = toParameterNames(decl.getParameters()); // Construct inner lambda Term inner = new Lambda(parameters,new Block(new Return(term))); // NOTE: need to use Immediately Invoked Function Expression here, otherwise // capture variables don't behave properly. Tuple<Decl.Variable> captured = new Tuple<>(decl.getCapturedVariables(meter)); List<String> captures = toParameterNames(captured); Term[] capturedArgs = toLambdaArguments(captured); // Construct outer lambda (this is for the IIFE) Term outer = new Lambda(captures,new Block(new Return(inner))); return new JavaScriptFile.IndirectInvoke(outer, capturedArgs); } // Statements @Override public Term constructAssert(Stmt.Assert stmt, Term condition) { return WY_ASSERT(condition); } @Override public Term constructAssign(Stmt.Assign stmt, List<Term> lhs, List<Term> rhs) { boolean simple = isSimpleAssignment(stmt); if(lhs.size() == 1 && simple) { // Easy case with no destructuring assignment (unless ES6) return new JavaScriptFile.Assignment(lhs.get(0), rhs.get(0)); } else if(simple) { // NOTE: what we know here is that there is no interference between the left and // right-hand sides. Also, that we have no destructuring assignment (unless ES6) ArrayList<Term> stmts = new ArrayList<>(); for(int i=0;i!=lhs.size();++i) { stmts.add(new JavaScriptFile.Assignment(lhs.get(i), rhs.get(i))); } return new Block(stmts); } else { // Harder case as have to workaround interference. Tuple<LVal> lvals = stmt.getLeftHandSide(); // Contains set of rhs terms to evaluate first. These all have to be executed // before the lhs terms because of the potential for interference. ArrayList<Term> first = new ArrayList<>(); // Contains set of assignments to evaluate afterwards. ArrayList<Term> second = new ArrayList<>(); // Finally, handle assignents to lvals for(int i=0;i!=lvals.size();++i) { Type lv_t = lvals.get(i).getType(); // Translate right-hand side VariableAccess tmp = new VariableAccess("$" + (temporaryIndex++)); first.add(new VariableDeclaration(toConstKind(),tmp.getName(),rhs.get(i))); // Translate left-hand side if(lv_t.shape() == 1) { // Unit assignment second.add(new JavaScriptFile.Assignment(lhs.get(i), tmp)); } else { // Multi-assignment JavaScriptFile.ArrayInitialiser ai = (JavaScriptFile.ArrayInitialiser) lhs.get(i); for(int k=0;k!=lv_t.shape();++k) { Term a = new ArrayAccess(tmp,new Constant(k)); second.add(new JavaScriptFile.Assignment(ai.getElement(k), a)); } } } // Build first.addAll(second); return new Block(first); } } @Override public Term constructAssume(Stmt.Assume stmt, Term condition) { return WY_ASSERT(condition); } @Override public Term constructBlock(Stmt.Block s, List<Term> stmts) { return new Block(stmts); } @Override public Term constructBreak(Stmt.Break stmt) { return new Break(); } @Override public Term constructContinue(Stmt.Continue stmt) { return new Continue(); } @Override public Term constructDebug(Stmt.Debug stmt, Term operand) { return null; } @Override public Term constructDoWhile(Stmt.DoWhile stmt, Term body, Term condition, List<Term> invariant) { // FIXME: support loop invariant return new DoWhile((Block) body,condition); } @Override public Term constructFail(Stmt.Fail stmt) { return WY_ASSERT(Constant.FALSE); } @Override public Term constructFor(Stmt.For stmt, Pair<Term, Term> range, List<Term> invariant, Term body) { // NOTE: eventually we'll want to employ foreach loops in some situations. WyilFile.Decl.StaticVariable v = stmt.getVariable(); VariableDeclaration decl = new VariableDeclaration(toLetKind(), v.getName().toString(), range.first()); VariableAccess var = new VariableAccess(v.getName().toString()); Term condition = new JavaScriptFile.Operator(Kind.LT, var, range.second()); Term increment = new Assignment(var, new Operator(Kind.ADD, var, new Constant(1))); // FIXME: support for loop invariant return new For(decl, condition, increment, (Block) body); } @Override public Term constructIfElse(Stmt.IfElse stmt, Term condition, Term trueBranch, Term falseBranch) { ArrayList<IfElse.Case> cases = new ArrayList<>(); // Translate true branch cases.add(new IfElse.Case(condition, (Block) trueBranch)); // Translate false branch (if applicable) if (stmt.hasFalseBranch()) { cases.add(new IfElse.Case(null, (Block) falseBranch)); } return new JavaScriptFile.IfElse(cases); } @Override public Term constructInitialiser(Stmt.Initialiser stmt, Term initialiser) { JavaScriptFile.VariableDeclaration.Kind kind=toVariableKind(stmt); Tuple<Decl.Variable> variables = stmt.getVariables(); if (initialiser == null) { // unit declaration String[][] names = new String[variables.size()][1]; // Determine appropriate modifier Term[] initialisers = new Term[names.length]; for (int i = 0; i != names.length; ++i) { names[i][0] = variables.get(i).getName().toString(); } return new JavaScriptFile.VariableDeclaration(kind, names, initialisers); } else if (jsFile.ES6() || variables.size() == 1) { // destructuring declaration String[][] names = new String[1][variables.size()]; // Determine appropriate modifier Term[] initialisers = new Term[] { initialiser }; for (int i = 0; i != variables.size(); ++i) { names[0][i] = variables.get(i).getName().toString(); } return new JavaScriptFile.VariableDeclaration(kind, names, initialisers); } else { // non-destructuring assignment ArrayList<Term> first = new ArrayList<>(); // Translate right-hand side expression VariableAccess tmp = new VariableAccess("$" + (temporaryIndex++)); first.add(new VariableDeclaration(toConstKind(), tmp.getName(), initialiser)); // Translate destructuring assignments for (int i = 0; i != variables.size(); ++i) { String l = variables.get(i).getName().toString(); Term r = new ArrayAccess(tmp, new Constant(i)); first.add(new JavaScriptFile.VariableDeclaration(kind, l, r)); } return new Block(first); } } @Override public Term constructInvokeStmt(Expr.Invoke expr, List<Term> arguments) { return constructInvoke(expr,arguments); } @Override public Term constructIndirectInvokeStmt(Expr.IndirectInvoke expr, Term source, List<Term> arguments) { return constructIndirectInvoke(expr,source, arguments); } @Override public Term constructNamedBlock(Stmt.NamedBlock stmt, List<Term> stmts) { return new Block(stmts); } @Override public Term constructReturn(Stmt.Return stmt, Term rval) { return new Return(rval); } @Override public Term constructSkip(Stmt.Skip stmt) { // There is no skip statement in JavaScript! return new Block(); } @Override public Term constructSwitch(Stmt.Switch stmt, Term condition, List<Pair<List<Term>,Term>> cases) { // NOTE: switches are challenging because we cannot necessarily translate a // Whiley switch directly as a JavaScript switch. This is because switches in // Whiley are valid for any datatype, whilst in JavaScript they are only valid // for integer types. Therefore, we must first identify which case we are in, // then handle them separately. boolean simple = subtyping.isSatisfiableSubtype(Type.Int, stmt.getCondition().getType()); if(!simple) { // hard case return translateSwitchAsIfElse(stmt, condition, cases); } else { return translateSwitchAsSwitch(stmt, condition, cases); } } @Override public Term constructWhile(Stmt.While stmt, Term condition, List<Term> invariant, Term body) { // FIXME: support loop invariant return new While(condition,(Block) body); } // LVal Constructors @Override public Term constructArrayAccessLVal(Expr.ArrayAccess expr, Term source, Term index) { Type t = expr.getFirstOperand().getType(); // Check whether it's a js string if (isJsString(t)) { // Return character code instead of string. WyilFile parent = (WyilFile) expr.getHeap(); throw new SyntacticException("Cannot assign JavaScript strings as they are immutable!", parent.getEntry(), expr); } else { return new ArrayAccess(source,index); } } @Override public Term constructDereferenceLVal(Expr.Dereference expr, Term operand) { Type.Reference type = expr.getOperand().getType().as(Type.Reference.class); if (isBoxedType(type)) { return new PropertyAccess(operand, "$ref"); } else { return operand; } } @Override public Term constructFieldDereferenceLVal(Expr.FieldDereference expr, Term operand) { Type.Reference type = expr.getOperand().getType().as(Type.Reference.class); if (isBoxedType(type)) { // Immutable types must be explicitly boxed since they cannot be updated in // place. operand = new PropertyAccess(operand, "$ref"); } return new PropertyAccess(operand, expr.getField().get()); } @Override public Term constructRecordAccessLVal(Expr.RecordAccess expr, Term source) { return new JavaScriptFile.PropertyAccess(source, expr.getField().toString()); } @Override public Term constructTupleInitialiserLVal(Expr.TupleInitialiser expr, List<Term> terms) { return new JavaScriptFile.ArrayInitialiser(terms); } @Override public Term constructVariableAccessLVal(Expr.VariableAccess expr) { String name = expr.getVariableDeclaration().getName().toString(); return new JavaScriptFile.VariableAccess(name); } // Expression Constructors @Override public Term constructArrayAccess(Expr.ArrayAccess expr, Term source, Term index) { // Extract type of source operand Type t = expr.getFirstOperand().getType(); // Check whether it's a js string if (isJsString(t)) { // Return character code instead of string. return new JavaScriptFile.Invoke(source, "charCodeAt", index); } else { Term term = new ArrayAccess(source, index); if (expr.isMove() || isCopyable(expr.getType())) { return term; } else { return WY_COPY(term); } } } @Override public Term constructArrayLength(Expr.ArrayLength expr, Term source) { return new ArrayLength(source); } @Override public Term constructArrayGenerator(Expr.ArrayGenerator expr, Term value, Term length) { return WY_ARRAY(value,length); } @Override public Term constructArrayInitialiser(Expr.ArrayInitialiser expr, List<Term> values) { return new ArrayInitialiser(values); } @Override public Term constructBitwiseComplement(Expr.BitwiseComplement expr, Term operand) { return MASK_FF(new Operator(Kind.BITWISEINVERT, operand)); } @Override public Term constructBitwiseAnd(Expr.BitwiseAnd expr, List<Term> operands) { return new JavaScriptFile.Operator(Kind.BITWISEAND, operands); } @Override public Term constructBitwiseOr(Expr.BitwiseOr expr, List<Term> operands) { return new JavaScriptFile.Operator(Kind.BITWISEOR, operands); } @Override public Term constructBitwiseXor(Expr.BitwiseXor expr, List<Term> operands) { return new JavaScriptFile.Operator(Kind.BITWISEXOR, operands); } @Override public Term constructBitwiseShiftLeft(Expr.BitwiseShiftLeft expr, Term lhs, Term rhs) { return new JavaScriptFile.Operator(Kind.LEFTSHIFT, lhs, rhs); } @Override public Term constructBitwiseShiftRight(Expr.BitwiseShiftRight expr, Term lhs, Term rhs) { return new JavaScriptFile.Operator(Kind.RIGHTSHIFT, lhs, rhs); } @Override public Term constructCast(Expr.Cast expr, Term operand) { return applyImplicitCoercion(expr.getType(), expr.getOperand().getType(), operand); } @Override public Term constructConstant(Expr.Constant expr) { Value val = expr.getValue(); switch (val.getOpcode()) { case ITEM_null: return Constant.NULL; case ITEM_bool: { boolean b = ((Value.Bool) val).get(); return b ? Constant.TRUE : Constant.FALSE; } case ITEM_byte: { byte b = ((Value.Byte) val).get(); if(jsFile.ES6()) { return new Constant(b); } else { // NOTE: this is the old way return PARSE_INT(Integer.toBinaryString(b & 0xFF),2); } } case ITEM_int: { BigInteger i = ((Value.Int) val).get(); if(jsFile.bigInt()) { return new Constant(i); } else { // NOTE: this will fail for bigintegers try { return new Constant(i.longValueExact()); } catch(Exception e) { throw new SyntacticException( "Integer " + i.toString() + " cannot be represented in 64bits (see Issue #15)", null, expr); } } } default: case ITEM_utf8: // NOTE: special case as Whiley strings are int arrays. Value.UTF8 utf8 = (Value.UTF8) val; String str = new String(utf8.get()); Term term = new JavaScriptFile.Constant(str); return isJsString(expr.getType()) ? term : WY_TOSTRING(term); } } @Override public Term constructDereference(Expr.Dereference expr, Term operand) { Type.Reference type = expr.getOperand().getType().as(Type.Reference.class); if(isBoxedType(type)) { // Immutable types must be explicitly boxed since they cannot be updated in // place. return new PropertyAccess(operand, "$ref"); } else { return operand; } } @Override public Term constructFieldDereference(Expr.FieldDereference expr, Term operand) { Type.Reference type = expr.getOperand().getType().as(Type.Reference.class); if (isBoxedType(type)) { // Immutable types must be explicitly boxed since they cannot be updated in // place. operand = new PropertyAccess(operand, "$ref"); } return new PropertyAccess(operand, expr.getField().get()); } @Override public Term constructEqual(Expr.Equal expr, Term lhs, Term rhs) { Type lhsT = expr.getFirstOperand().getType(); Type rhsT = expr.getSecondOperand().getType(); return translateEquality(true, lhs, lhsT, rhs, rhsT); } @Override public Term constructIntegerLessThan(Expr.IntegerLessThan expr, Term lhs, Term rhs) { return new JavaScriptFile.Operator(Kind.LT, lhs, rhs); } @Override public Term constructIntegerLessThanOrEqual(Expr.IntegerLessThanOrEqual expr, Term lhs, Term rhs) { return new JavaScriptFile.Operator(Kind.LTEQ, lhs, rhs); } @Override public Term constructIntegerGreaterThan(Expr.IntegerGreaterThan expr, Term lhs, Term rhs) { return new JavaScriptFile.Operator(Kind.GT, lhs, rhs); } @Override public Term constructIntegerGreaterThanOrEqual(Expr.IntegerGreaterThanOrEqual expr, Term lhs, Term rhs) { return new JavaScriptFile.Operator(Kind.GTEQ, lhs, rhs); } @Override public Term constructIntegerNegation(Expr.IntegerNegation expr, Term operand) { return new JavaScriptFile.Operator(Kind.NEG, operand); } @Override public Term constructIntegerAddition(Expr.IntegerAddition expr, Term lhs, Term rhs) { return new JavaScriptFile.Operator(Kind.ADD, lhs, rhs); } @Override public Term constructIntegerSubtraction(Expr.IntegerSubtraction expr, Term lhs, Term rhs) { return new JavaScriptFile.Operator(Kind.SUB, lhs, rhs); } @Override public Term constructIntegerMultiplication(Expr.IntegerMultiplication expr, Term lhs, Term rhs) { return new JavaScriptFile.Operator(Kind.MUL, lhs, rhs); } @Override public Term constructIntegerDivision(Expr.IntegerDivision expr, Term lhs, Term rhs) { Type type = expr.getType(); if(isJsNumber(type)) { return new JavaScriptFile.Operator(Kind.DIV, lhs, rhs); } else { // NOTE: must floor result as JavaScript numbers are floating point. return MATH_FLOOR(new JavaScriptFile.Operator(Kind.DIV, lhs, rhs)); } } @Override public Term constructIntegerRemainder(Expr.IntegerRemainder expr, Term lhs, Term rhs) { return new JavaScriptFile.Operator(Kind.REM, lhs, rhs); } @Override public Term constructIs(Expr.Is expr, Term operand) { Type test = expr.getTestType(); Type type = expr.getOperand().getType(); return translateIs(type, test, operand, runtimeTypeTests); } @Override public Term constructLogicalAnd(Expr.LogicalAnd expr, List<Term> operands) { return and(operands); } @Override public Term constructLogicalImplication(Expr.LogicalImplication expr, Term lhs, Term rhs) { // A ==> B equivalent to (!A) || B return or(not(lhs), rhs); } @Override public Term constructLogicalIff(Expr.LogicalIff expr, Term lhs, Term rhs) { Type lhsT = expr.getFirstOperand().getType(); Type rhsT = expr.getSecondOperand().getType(); return translateEquality(true, lhs, lhsT, rhs, rhsT); } @Override public Term constructLogicalNot(Expr.LogicalNot expr, Term operand) { return not(operand); } @Override public Term constructLogicalOr(Expr.LogicalOr expr, List<Term> operands) { return or(operands); } @Override public Term constructExistentialQuantifier(Expr.ExistentialQuantifier expr, List<Pair<Term,Term>> ranges, Term body) { return translateQuantifier(expr,ranges,body); } @Override public Term constructUniversalQuantifier(Expr.UniversalQuantifier expr, List<Pair<Term,Term>> ranges, Term body) { return translateQuantifier(expr,ranges,body); } @Override public Term constructInvoke(Expr.Invoke expr, List<Term> arguments) { // Determine the qualified name String name = toMangledName(expr.getLink().getTarget()); // Done return new JavaScriptFile.Invoke(null, name, arguments); } @Override public Term constructIndirectInvoke(Expr.IndirectInvoke expr, Term source, List<Term> arguments) { return new JavaScriptFile.IndirectInvoke(source, arguments); } @Override public Term constructLambdaAccess(Expr.LambdaAccess expr) { // NOTE: see // Get mangled name String name = toMangledName(expr.getLink().getTarget()); return new JavaScriptFile.VariableAccess(name); } @Override public Term constructNew(Expr.New expr, Term operand) { Type.Reference type = expr.getType().as(Type.Reference.class); if (isBoxedType(type)) { // Immutable types must be boxed as they cannot be updated in place. All other // types don't need to be boxed. return new Operator(Kind.NEW,WY_REF(operand)); } else { return operand; } } @Override public Term constructNotEqual(Expr.NotEqual expr, Term lhs, Term rhs) { Type lhsT = expr.getFirstOperand().getType(); Type rhsT = expr.getSecondOperand().getType(); return translateEquality(false, lhs, lhsT, rhs, rhsT); } @Override public Term constructRecordAccess(Expr.RecordAccess expr, Term source) { Term term = new JavaScriptFile.PropertyAccess(source, expr.getField().toString()); if(expr.isMove() || isCopyable(expr.getType())) { return term; } else { return WY_COPY(term); } } @Override public Term constructRecordInitialiser(Expr.RecordInitialiser expr, List<Term> operands) { // Extract field names Tuple<Identifier> names = expr.getFields(); ArrayList<Pair<String, Term>> fields = new ArrayList<>(); for (int i = 0; i != operands.size(); ++i) { fields.add(new Pair<>(names.get(i).toString(), operands.get(i))); } // NOTE: Invoking Wy.Record is necessary to set the prototype on the generated // object. return new Operator(Kind.NEW,WY_RECORD(new JavaScriptFile.ObjectLiteral(fields))); } @Override public Term constructTupleInitialiser(Expr.TupleInitialiser expr, List<Term> operands) { return new ArrayInitialiser(operands); } @Override public Term constructStaticVariableAccess(Expr.StaticVariableAccess expr) { String name = toMangledName(expr.getLink().getTarget()); VariableAccess var = new JavaScriptFile.VariableAccess(name); // Check whether variable move is sufficient // FIXME: should support isMove? if(isCopyable(expr.getType())) { return var; } else { return WY_COPY(var); } } @Override public Term constructVariableAccess(Expr.VariableAccess expr) { Decl.Variable decl = expr.getVariableDeclaration(); String name = decl.getName().toString(); VariableAccess var = new JavaScriptFile.VariableAccess(name); if (expr.isMove() || isCopyable(expr.getType())) { return var; } else { return WY_COPY(var); } } // Coercions @Override public Term applyImplicitCoercion(Type target, Type source, Term term) { if (target.equals(source)) { // No coercion required return term; } else if (isJsString(target) && !containsJsString(source)) { // Coercion to a JavaScript string required return WY_FROMSTRING(term); } else if (!containsJsString(target) && isJsString(source)) { // Coercion from a JavaScript string required return WY_TOSTRING(term); } else if(target instanceof Type.Int && isJsNumber(source)) { // Coercion from a JavaScript number required return MATH_FLOOR(term); } // No operation return term; } /** * Check whether a given target type corresponds to a native JavaScript string. * * @param target * @return */ private boolean isJsString(Type target) { if (target instanceof Type.Nominal) { Type.Nominal t = (Type.Nominal) target; Decl.Type decl = t.getLink().getTarget(); return decl.getQualifiedName().toString().equals("js::core::string"); } else { return false; } } /** * Check whether a given target type corresponds to a native JavaScript string. * * @param target * @return */ private boolean isJsNumber(Type target) { if (target instanceof Type.Nominal) { Type.Nominal t = (Type.Nominal) target; Decl.Type decl = t.getLink().getTarget(); return decl.getQualifiedName().toString().equals("js::core::number"); } else { return false; } } private boolean containsJsString(Type target) { // FIXME: this function is a HACK. if(isJsString(target)) { return true; } else if(target instanceof Type.Union) { Type.Union t = (Type.Union) target; for(int i=0;i!=t.size();++i) { if(containsJsString(t.get(i))) { return true; } } } return false; } // Helpers /** * Translate a runtime type test, given the type of the operand and the type * being tested against. For example, consider this: * * <pre> * function get(int|null x): * if x is int: * return x * else: * return 0 * </pre> * * In this case, the type of the source operand is <code>int|null</code> whilst * the type being tested against is <code>int</code>. * * @param type The type of the operand or <code>null</code> if any type possible. * @param test The type being tested against * @param operand The translated operand expression * @param tests Records additional type tests which are required. * @return */ private Term translateIs(Type type, Type test, Term operand, Set<Pair<Type, Type>> tests) { Term result = null; // Quick sanity check first if(type != null && type.equals(test)) { return Constant.TRUE; } // Handle all easy cases first. These can all be inlined directly and do not // require the creation of a separate helper method. We want to do this as much // as possible. switch(test.getOpcode()) { case TYPE_null: result = translateIsNull(type, (Type.Null) test, operand); break; case TYPE_bool: result = translateIsBool(type, (Type.Bool) test, operand); break; case TYPE_byte: result = translateIsByte(type, (Type.Byte) test, operand); break; case TYPE_int: result = translateIsInt(type, (Type.Int) test, operand); break; case TYPE_nominal: { Type.Nominal t = (Type.Nominal) test; Decl.Type decl = t.getLink().getTarget(); // NOTE: we only consider case where empty invariant. This is necessary because, // otherwise, would have to evaluate operand more than once. if(decl.getInvariant().size() == 0) { result = translateIs(type,t.getConcreteType(),operand,tests); } else if(isJsString(t)) { result = translateIsString(type, (Type.Nominal) test, operand); } break; } } if(result != null) { return result; } else { // In this event, we're going to fall back to creating a specialised helper // method. tests.add(new Pair<>(type, test)); String name = getTypeTestMangle(type,test); // Done return new JavaScriptFile.Invoke(null, name, operand); } } /** * Translate a type tests against <code>null</code>. This is very easy in * JavaScript since we can just directly compare against the <code>null</code> * value. For example, the following Whiley: * * <pre> * if x is null: * ... * </pre> * * Becomes the following in JavaScript: * * <pre> * if(x == null) { * ... * } * </pre> * * * @param type The type of the operand. * @param test The type being tested against * @param operand The translated operand expression * @return */ private Term translateIsNull(Type type, Type.Null test, Term operand) { return new Operator(Kind.EEQ,operand,Constant.NULL); } /** * Translate a type test against <code>bool</code>. This is very easy in * JavaScript since we can employ the <code>typeof</code> operator to resolve * this. For example, the following Whiley: * * <pre> * if x is bool: * ... * </pre> * * Becomes the following in JavaScript: * * <pre> * if((typeof x) == "boolean") { * ... * } * </pre> * * * @param type The type of the operand. * @param test The type being tested against * @param operand The translated operand expression * @return */ private Term translateIsBool(Type type, Type.Bool test, Term operand) { return TypeOf(operand,"boolean"); } private Term translateIsByte(Type type, Type.Byte test, Term operand) { // FIXME: need constructor for byte types?? return TypeOf(operand,"number"); } /** * Translate a type test against <code>int</code>. This is very easy in * JavaScript since we can employ the <code>typeof</code> operator to resolve * this. For example, the following Whiley: * * <pre> * if x is int: * ... * </pre> * * Becomes the following in JavaScript: * * <pre> * if((typeof x) == "number") { * ... * } * </pre> * * * @param type The type of the operand. * @param test The type being tested against * @param operand The translated operand expression * @return */ private Term translateIsInt(Type type, Type.Int test, Term operand) { return TypeOf(operand,"number"); } /** * Translate a type test against a native JavaScript <code>string</code>. This * is very easy in JavaScript since we can employ the <code>typeof</code> * operator to resolve this. For example, the following Whiley: * * <pre> * if x is string: * ... * </pre> * * Becomes the following in JavaScript: * * <pre> * if((typeof x) == "string") { * ... * } * </pre> * * * @param type The type of the operand. * @param test The type being tested against * @param operand The translated operand expression * @return */ private Term translateIsString(Type type, Type.Nominal test, Term operand) { return TypeOf(operand,"string"); } /** * Translate all type tests into corresponding functions. This must be done in * an iterative fashion, since translating a given type test might require * generating another, etc. * * @param tests */ private void translateTypeTests(HashSet<Pair<Type,Type>> tests) { HashSet<Pair<Type,Type>> delta = new HashSet<>(tests); while(delta.size() > 0) { Pair<Type,Type>[] iteration = delta.toArray(new Pair[delta.size()]); delta.clear(); for(Pair<Type,Type> p : iteration) { // Construct type test method Declaration d = translateTypeTest(p.first(),p.second(),delta); // Add test to the JavaScript file jsFile.getDeclarations().add(d); } // Remove all from delta to see what is left! delta.removeAll(tests); // Ensure tests contains all known type tests tests.addAll(delta); } } /** * Translate a runtime type test, given the type of the source operand and the * type being tested against. For example, consider this: * * <pre> * function get(int|null x): * if x is int: * return x * else: * return 0 * </pre> * * In this case, the type of the source operand is <code>int|null</code> whilst * the type being tested against is <code>int</code>. * * @param type The type of the source operand. * @param test The type being tested against * @param tests Records additional type tests which are required. * @return */ private Declaration translateTypeTest(Type type, Type test, Set<Pair<Type, Type>> tests) { // Calculate mangled name String name = getTypeTestMangle(type,test); String parameter = "v"; Term operand = new VariableAccess(parameter); Block body; switch (test.getOpcode()) { case TYPE_null: case TYPE_bool: case TYPE_byte: case TYPE_int: // NOTE: these are all handled separately throw new IllegalArgumentException("unexpected type: " + test); case TYPE_nominal: body = translateIsNominal(type, (Type.Nominal) test, operand, tests); break; case TYPE_union: body = translateIsUnion(type, (Type.Union) test, operand, tests); break; case TYPE_record: body = translateIsRecord(type, (Type.Record) test, operand, tests); break; case TYPE_array: body = translateIsArray(type, (Type.Array) test, operand, tests); break; case TYPE_reference: body = translateIsReference(type, (Type.Reference) test, operand, tests); break; case TYPE_method: case TYPE_function: case TYPE_property: body = translateIsLambda(type, (Type.Callable) test, operand, tests); break; default: throw new IllegalArgumentException("unexpected type: " + test); } return new JavaScriptFile.Method(name, Arrays.asList(parameter), body); } private Block translateIsNominal(Type type, Type.Nominal test, Term operand, Set<Pair<Type,Type>> tests) { Decl.Type decl = test.getLink().getTarget(); // Test against the underlying type Term t1 = translateIs(type, test.getConcreteType(), operand, tests); // Test against invariant (if applicable) if(decl.getInvariant().size() == 0) { return new Block(new Return(t1)); } else { // Second, test against type invariant String name = toMangledName(decl); Term t2 = new Invoke(null,name,operand); // Done return new Block(new Return(and(t1, t2))); } } private Block translateIsUnion(Type type, Type.Union test, Term operand, Set<Pair<Type,Type>> tests) { ArrayList<Term> terms = new ArrayList<>(); for (int i = 0; i != test.size(); ++i) { terms.add(translateIs(type, test.get(i), operand, tests)); } return new Block(new Return(or(terms))); } private Block translateIsRecord(Type type, Type.Record test, Term operand, Set<Pair<Type,Type>> tests) { Tuple<Type.Field> fields = test.getFields(); // Attempt simple selection ArrayList<Term> operands = new ArrayList<>(); if (isSubtype(type, Type.Null)) { // NOTE: since null could be a value of the operand being tested, we must // eliminate this to be sure we have a record. That's because <code>typeof // null</code> annoyingly returns <code>"object"</code> in JavaScript. operands.add(NonNull(operand)); } // Check whether any non-record types. if(hasOtherSubtypesBesidesNull(type,Type.Record.class)) { // Yes, therefore check this is an object. operands.add(RecordConstructor(operand)); } List<Type.Record> candidates = null; if(type != null) { // Eliminate all non-records candidates = type.filter(Type.Record.class); // Is that enough? if(areSubtypes(test,candidates)) { // YES! return new Block(new Return(and(operands))); } // Eliminate records based on their field count if(filteredByFieldCount(candidates,fields.size(),test.isOpen())) { operands.add(checkFieldCount(operand,fields.size())); // Is that enough? if(areSubtypes(test,candidates)) { // YES! return new Block(new Return(and(operands))); } } } // NOTE: at this point, we could do more by attempting to find one or more // fields which uniquely identify this record. Block returnFalse = new Block(new Return(Constant.FALSE)); ArrayList<IfElse.Case> cases = new ArrayList<>(); if (operands.size() > 0) { cases.add(new IfElse.Case(not(and(operands)), returnFalse)); } for (int i = 0; i != fields.size(); ++i) { Type.Field field = fields.get(i); Type type_field = toFieldType(field.getName(), candidates); // Create field check Term f = new PropertyAccess(operand, field.getName().toString()); Term condition = or(TypeOf(f, "undefined"), not(translateIs(type_field, field.getType(), f, tests))); cases.add(new IfElse.Case(condition, returnFalse)); } return new Block(new IfElse(cases), new Return(Constant.TRUE)); } private Block translateIsArray(Type type, Type.Array test, Term operand, Set<Pair<Type,Type>> tests) { // Attempt simple selection ArrayList<Term> operands = new ArrayList<>(); // Check whether non-null possible if (isSubtype(type, Type.Null)) { // NOTE: since null could be a value of the operand being tested, we must // eliminate this to be sure we have a record. That's because <code>typeof // null</code> annoyingly returns <code>"object"</code> in JavaScript. operands.add(NonNull(operand)); } // Check whether any non-record types. if(hasOtherSubtypesBesidesNull(type,Type.Array.class)) { // Yes, therefore check this is an object. operands.add(ArrayConstructor(operand)); } // Have now eliminated all non-array types. This maybe enough. List<Type.Array> candidates = null; // Attempt to do things with knowledge of declared type if(type != null) { candidates = type.filter(Type.Array.class); // Check whether can select purely on basis of being array if(areSubtypes(test,candidates)) { // YES return new Block(new Return(and(operands))); } } // TODO: can improve this in some cases by examining the first element. This // works when the element types are disjoint. Type.Array arrtype = toArrayType(candidates); // Create inner for loop Block body = translateIsArrayHelper(arrtype, test, operand, tests); // Create outer if (where necessary) if (operands.size() == 0) { // Not necessary return body; } else { IfElse.Case caSe = new IfElse.Case(and(operands), body); Term outerIf = new IfElse(Arrays.asList(caSe)); return new Block(outerIf, new Return(Constant.FALSE)); } } /** * Construct a for loop of the following form: * * <pre> * for (int i = 0; i < v.length; i = i + 1) { * if (!isXXX(v[i])) { * return false; * } * } * return true; * </pre> * * This basically iterates through all the elements of an array and checks the * have a given type. * * @param from * @param test * @param operand * @return */ private Block translateIsArrayHelper(Type.Array from, Type.Array test, Term operand, Set<Pair<Type, Type>> tests) { // Loop Header VariableDeclaration decl = new VariableDeclaration(toLetKind(), "i",new Constant(0)); VariableAccess var = new VariableAccess("i"); Term loopTest = new Operator(Kind.LT, var, new ArrayLength(operand)); Term increment = new Assignment(var, new Operator(Kind.ADD, var, new Constant(1))); // Loop Body Term if_condition = new Operator(Kind.NOT, translateIs(from == null ? null : from.getElement(), test.getElement(), new ArrayAccess(operand, var), tests)); Block if_body = new Block(new Return(Constant.FALSE)); Term inner_if = new IfElse(new IfElse.Case(if_condition, if_body)); Term forLoop = new For(decl, loopTest, increment, new Block(inner_if)); // Done return new Block(forLoop, new Return(Constant.TRUE)); } private Block translateIsReference(Type type, Type.Reference test, Term operand, Set<Pair<Type, Type>> tests) { ArrayList<Term> operands = new ArrayList<>(); // Check whether non-null possible if (isSubtype(type, Type.Null)) { // NOTE: since null could be a value of the operand being tested, we must // eliminate this to be sure we have a record. That's because <code>typeof // null</code> annoyingly returns <code>"object"</code> in JavaScript. operands.add(NonNull(operand)); } // Check whether any non-record types. if(hasOtherSubtypesBesidesNull(type,Type.Reference.class)) { // Yes, therefore check this is an object. operands.add(ReferenceConstructor(operand)); } // FIXME: in principle there is more to do here, but we'll save that for another // day because the whole type test mechanism is going to change. Block body = new Block(new Return(Constant.TRUE)); if (operands.size() == 0) { // Not necessary return body; } else { IfElse.Case caSe = new IfElse.Case(and(operands), body); Term outerIf = new IfElse(Arrays.asList(caSe)); return new Block(outerIf, new Return(Constant.FALSE)); } } private Block translateIsLambda(Type type, Type.Callable test, Term operand, Set<Pair<Type, Type>> tests) { ArrayList<Term> operands = new ArrayList<>(); // Check whether non-null possible if (isSubtype(type, Type.Null)) { // NOTE: since null could be a value of the operand being tested, we must // eliminate this to be sure we have a record. That's because <code>typeof // null</code> annoyingly returns <code>"object"</code> in JavaScript. operands.add(NonNull(operand)); } // Check whether any non-record types. if(hasOtherSubtypesBesidesNull(type,Type.Callable.class)) { // Yes, therefore check this is an object. operands.add(TypeOf(operand,"function")); } // FIXME: in principle there is more to do here, but we'll save that for another // day because the whole type test mechanism is going to change. Block body = new Block(new Return(Constant.TRUE)); if (operands.size() == 0) { // Not necessary return body; } else { IfElse.Case caSe = new IfElse.Case(and(operands), body); Term outerIf = new IfElse(Arrays.asList(caSe)); return new Block(outerIf, new Return(Constant.FALSE)); } } /** * Implementing equality is tricky because of the disparity between JavaScript * types and Whiley types. For example, equality of arrays is not reference * equality in Whiley (as it is in JavaScript). * * @return */ private Term translateEquality(boolean positive, Term lhs, Type lhsT, Term rhs, Type rhsT) { if (isCopyable(lhsT) && isCopyable(rhsT)) { return new JavaScriptFile.Operator(positive ? Kind.EEQ : Kind.NEEQ, lhs, rhs); } else { Term t3 = WY_EQUALS(lhs, rhs); if (!positive) { t3 = new JavaScriptFile.Operator(Kind.NOT, t3); } return t3; } } /** * This is the easy case for translating switches. We translate a While switch * directly as a JavaScript switch. For example, the following Whiley code: * * <pre> * switch x: * case 1, 2: * return -1 * case 3: * return 1 * </pre> * * into the following JavaScript code: * * <pre> * switch (x) { * case 1: * case 2: { * return -1; * break; * } * case 3: { * return 1; * break; * } * } * </pre> * * A further optimisation could be made in this case to drop the break * statements. * * @param stmt * @return */ private Term translateSwitchAsSwitch(Stmt.Switch stmt, Term condition, List<Pair<List<Term>,Term>> cases) { // Translate each case one-by-one. Tuple<Stmt.Case> wycases = stmt.getCases(); ArrayList<Switch.Case> jscases = new ArrayList<>(); for (int i = 0; i != wycases.size(); ++i) { // NOTE: one case in Whiley can correspond to multiple cases in JavaScript. // That's because Whiley allows multiple values per case. List<Term> values = cases.get(i).first(); Block body = (Block) cases.get(i).second(); // Add terminal break since Whiley doesn't use them body.getTerms().add(new Break()); // Check for default case if (values.size() == 0) { jscases.add(new Switch.Case(null, body)); } else { // Handle all fall-thru cases first. for (int j = 1; j != values.size(); ++j) { jscases.add(new Switch.Case(values.get(j - 1), null)); } // Handle content case finally jscases.add(new Switch.Case(values.get(values.size() - 1), body)); } } return new Switch(condition, jscases); } /** * This is the hard case for translating a switch statement. For example, we * translate the following Whiley code: * * <pre> * switch x: * case true: * return 0 * case false: * return -1 * </pre> * * into the following JavaScript code: * * <pre> * { * var $0 = x; * if ($0 == true) { * return 0; * } else if ($0 == false) { * return -1; * } * } * </pre> * * The temporary variable is used to ensure the switch condition is only ever * evaluated once. In this case, the temporary variable is not actuall required. * * @param stmt * @return */ private Term translateSwitchAsIfElse(Stmt.Switch stmt, Term condition, List<Pair<List<Term>,Term>> cases) { Type conditionT = stmt.getCondition().getType(); VariableAccess tmp = new VariableAccess("$" + temporaryIndex++); // Create temporary variable declaration VariableDeclaration decl = new VariableDeclaration(toLetKind(),tmp.getName(),condition); // Translate each case one-by-one. Tuple<Stmt.Case> wycases = stmt.getCases(); ArrayList<IfElse.Case> jscases = new ArrayList<>(); for (int i = 0; i != wycases.size(); ++i) { // NOTE: one case in Whiley can correspond to multiple cases in JavaScript. // That's because Whiley allows multiple values per case. Stmt.Case wycase = wycases.get(i); Pair<List<Term>,Term> jscase = cases.get(i); // Translate the operands Tuple<Expr> values = wycase.getConditions(); // Check for default case if (values.size() == 0) { jscases.add(new IfElse.Case(null, (Block) jscase.second())); } else { Term[] eqs = new Term[values.size()]; List<Term> terms = jscase.first(); // Construct disjunction of cases for (int j = 0; j != eqs.length; ++j) { Expr value = values.get(j); eqs[j] = translateEquality(true, tmp, conditionT, terms.get(j), value.getType()); } Term c = eqs.length == 1 ? eqs[0] : or(eqs); // Handle content case finally jscases.add(new IfElse.Case(c, (Block) jscase.second())); } } return new Block(decl, new IfElse(jscases)); } /** * Translate a quantifier expression into JavaScript. This is done use a loop * nest embedded within a lambda. For example, the following While code: * * <pre> * bool b = all { i in 0..|items| | items[i] >= 0 } * </pre> * * Is translated into the following JavaScript: * * <pre> * var b = function() { * for(int i=0;i<items.length;i=i+1) { * if(!(items[i] < 0)) { return false; } * } * return true; * }(); * </pre> * * This is a bit more verbose, but it works quite well. * * @param expr * @return */ private Term translateQuantifier(Expr.Quantifier expr, List<Pair<Term,Term>> ranges, Term condition) { boolean isUniversal = expr instanceof Expr.UniversalQuantifier; // Translate quantifier into loop nest Term body = translateQuantifier(0,expr,ranges,condition); // Construct final return statement Term ret = new Return(isUniversal ? Constant.TRUE : Constant.FALSE); // Construct lambda itself Term lambda = new Lambda(Collections.EMPTY_LIST, new Block(body,ret)); // Return invocation of lambda return new JavaScriptFile.IndirectInvoke(lambda); } private Term translateQuantifier(int index, Expr.Quantifier expr, List<Pair<Term, Term>> ranges, Term condition) { boolean isUniversal = expr instanceof Expr.UniversalQuantifier; Tuple<Decl.StaticVariable> parameters = expr.getParameters(); // Generate nest if (parameters.size() == index) { // Base case Term body = new Return(isUniversal ? Constant.FALSE : Constant.TRUE); if (isUniversal) { condition = new Operator(Kind.NOT, condition); } return new IfElse(new IfElse.Case(condition, new Block(body))); } else { // Recursive case Decl.Variable v = parameters.get(index); Pair<Term, Term> range = ranges.get(index); VariableAccess var = new VariableAccess(v.getName().toString()); VariableDeclaration decl = new VariableDeclaration(toLetKind(),var.getName(),range.first()); Term test = new Operator(Kind.LT, var, range.second()); Term increment = new Assignment(var, new Operator(Kind.ADD, var, new Constant(1))); Term body = translateQuantifier(index + 1, expr, ranges, condition); return new JavaScriptFile.For(decl, test, increment, new Block(body)); } } /** * Determine the appropriate mangle for a type test function. * * @param type * @param test * @return */ private String getTypeTestMangle(Type type, Type test) { String mangle; // Calculate mangled name if(type == null) { mangle = getMangle(test); } else { mangle = getMangle(type, test); } return "is" + mangle; } /** * Declare any named returns as, otherwise, they will have no local variable * declaration and, hence, in strict mode, this will fail. * * @param fm * @param body */ private void declareNamedReturns(Decl.FunctionOrMethod fm, Block body) { Tuple<Decl.Variable> returns = fm.getReturns(); for(int i=0;i!=returns.size();++i) { Decl.Variable v = returns.get(i); String name = v.getName().get(); if(!name.equals("$")) { body.getTerms().add(0,new JavaScriptFile.VariableDeclaration(toLetKind(), name)); } } } /** * Check whether a given assignment is "simple" or not. That is, where the * right-hand side contains no multi-expressions and there is no interference * between the lhs and rhs. The following illustrates a multi-assignment case: * * <pre> * x,y = f() * </pre> * * This case is problematic because the return of <code>f()</code> will be an * array which must be destructured. The following illustrates interference * between the lhs and rhs: * * <pre> * x,y = y,x * </pre> * * Interference means that locations assigned on the left-hand side are * (potentially) present on the right-hand side. To understand why this is a * problem, consider this naive translation into JavaScript: * * <pre> * x = y; * y = x; * </pre> * * This obviously doesn't work because <code>x</code> is assigned a new value * before its original value is assigned to <code>y</code>. To work around this, * we need to introduce temporary variables. * * @param stmt * @return */ private boolean isSimpleAssignment(Stmt.Assign stmt) { Tuple<LVal> lhs = stmt.getLeftHandSide(); Tuple<Expr> rhs = stmt.getRightHandSide(); HashSet<Decl.Variable> uses = new HashSet<>(); HashSet<Decl.Variable> defs = new HashSet<>(); // Identify all defs and uses for(int i=0;i!=lhs.size();++i) { LVal lv = lhs.get(i); if(lv instanceof Expr.TupleInitialiser && !jsFile.ES6()) { // Prior to ES6 was no destructuring assignment return false; } else if(!extractDefinedVariable(lhs.get(i),defs)) { // Couldn't tell what was being defined. return false; } extractUsedVariables(lhs.get(i),uses); extractUsedVariables(rhs.get(i),uses); } // Check for interference for(Decl.Variable def : defs) { if(uses.contains(def)) { // Interference detected return false; } } return true; } private boolean extractDefinedVariable(LVal lval, Set<Decl.Variable> defs) { switch (lval.getOpcode()) { case EXPR_arrayaccess: case EXPR_arrayborrow: { Expr.ArrayAccess e = (Expr.ArrayAccess) lval; return extractDefinedVariable((WyilFile.LVal) e.getFirstOperand(), defs); } case EXPR_fielddereference: case EXPR_dereference: { // NOTE: it's impossible to tell what variable is being defined through a // dereference. return false; } case EXPR_tupleinitialiser: { Expr.TupleInitialiser e = (Expr.TupleInitialiser) lval; Tuple<Expr> operands = e.getOperands(); for(int i=0;i!=operands.size();++i) { if(!extractDefinedVariable((WyilFile.LVal)operands.get(i),defs)) { return false; } } return true; } case EXPR_recordaccess: case EXPR_recordborrow: { Expr.RecordAccess e = (Expr.RecordAccess) lval; return extractDefinedVariable((WyilFile.LVal) e.getOperand(),defs); } case EXPR_variablecopy: case EXPR_variablemove: { Expr.VariableAccess e = (Expr.VariableAccess) lval; defs.add(e.getVariableDeclaration()); return true; } default: throw new IllegalArgumentException("invalid lval: " + lval); } } private void extractUsedVariables(LVal lval, Set<Decl.Variable> uses) { switch (lval.getOpcode()) { case EXPR_arrayaccess: case EXPR_arrayborrow: { Expr.ArrayAccess e = (Expr.ArrayAccess) lval; extractUsedVariables((WyilFile.LVal) e.getFirstOperand(), uses); extractUsedVariables(e.getSecondOperand(), uses); break; } case EXPR_dereference: { Expr.Dereference e = (Expr.Dereference) lval; extractUsedVariables(e.getOperand(), uses); break; } case EXPR_recordaccess: case EXPR_recordborrow: { Expr.RecordAccess e = (Expr.RecordAccess) lval; extractUsedVariables((WyilFile.LVal) e.getOperand(), uses); break; } case EXPR_tupleinitialiser: { Expr.TupleInitialiser e = (Expr.TupleInitialiser) lval; Tuple<Expr> operands = e.getOperands(); for(int i=0;i!=operands.size();++i) { extractUsedVariables((WyilFile.LVal) operands.get(i),uses); } break; } case EXPR_variablecopy: case EXPR_variablemove: { // NOTE: nothing to do here, since this variable is being defined. break; } default: throw new IllegalArgumentException("invalid lval: " + lval); } } /** * Extract all used variables from a given expression. This is tricky as we must * account properly for captured variables, etc. * * @param e * @param uses */ private void extractUsedVariables(Expr e, Set<Decl.Variable> uses) { // Construct appropriate visitor AbstractVisitor visitor = new AbstractVisitor(meter) { @Override public void visitVariableAccess(Expr.VariableAccess e) { uses.add(e.getVariableDeclaration()); } @Override public void visitDeclaration(Decl d) { // NOTE: this is needed to prevent traversal into type invariants, etc. if(d instanceof Decl.Lambda) { // NOTE: must account for variable capture here Decl.Lambda l = (Decl.Lambda) d; HashSet<Decl.Variable> tmp = new HashSet<>(); // Traverse quantify body super.visitLambda(l); // Remove all captured variables for(Decl.Variable v : l.getParameters()) { tmp.remove(v); } // Done uses.addAll(tmp); } } @Override public void visitUniversalQuantifier(Expr.UniversalQuantifier q) { // NOTE: must account for variable capture here HashSet<Decl.Variable> tmp = new HashSet<>(); // Traverse quantify body super.visitUniversalQuantifier(q); // Remove all captured variables for(Decl.Variable v : q.getParameters()) { tmp.remove(v); } // Done uses.addAll(tmp); } @Override public void visitExistentialQuantifier(Expr.ExistentialQuantifier q) { // NOTE: must account for variable capture here HashSet<Decl.Variable> tmp = new HashSet<>(); // Traverse quantify body super.visitExistentialQuantifier(q); // Remove all captured variables for(Decl.Variable v : q.getParameters()) { tmp.remove(v); } // Done uses.addAll(tmp); } @Override public void visitType(Type t) { // NOTE: stop traversal here since we cannot reach any variable declarations // from here. This is just an optimisation. } }; visitor.visitExpression(e); } /** * Check that a given type (<code>t2</code>) is a subtype of another * (<code>t1</code>). * * @param t1 The supertype being checked. * @param t2 The subtype(s) being checked. * @return */ private boolean isSubtype(Type t1, Type t2) { return t1 == null || subtyping.isSatisfiableSubtype(t1, t2); } /** * Check that a given set of types are all subtypes of a given type. * * @param type The supertype being checked. * @param types The subtype(s) being checked. * @return */ private boolean areSubtypes(Type type, List<? extends Type> types) { for(Type t : types) { if (t != null && !subtyping.isSatisfiableSubtype(type, t)) { return false; } } return true; } /** * Check whether a given type is immutable or not. An immutable type is one * which needs to be boxed for a reference to it to be generated. * * @return */ public boolean isBoxedType(Type.Reference type) { Type element = type.getElement(); // Strip away nominal info while(element instanceof Type.Nominal) { Type.Nominal n = (Type.Nominal) element; element = n.getConcreteType(); } if(element instanceof Type.Record) { Type.Record r = (Type.Record) element; return !r.isOpen(); } else { return true; } } /** * Return true if the type in question can be copied directly. More * specifically, if a bitwise copy of the value is sufficient to fully copy * it. In general, this is true for primitive data types in JavaScript. But, * for array types or general class types, it is not true (since these are * references into the heap). As an exception, class types which are known * to be immutable can be safely considered as copyable. * * @param type * @return */ private boolean isCopyable(Type type) { if (type instanceof Type.Primitive) { return true; } else if (type instanceof Type.Callable) { return true; } else if (type instanceof Type.Reference) { return true; } else if (type instanceof Type.Nominal) { Type.Nominal tn = (Type.Nominal) type; Decl.Type td = tn.getLink().getTarget(); return isCopyable(td.getType()); } else if (type instanceof Type.Union) { Type.Union union = (Type.Union) type; for (int i = 0; i != union.size(); ++i) { if (!isCopyable(union.get(i))) { return false; } } return true; } else { return false; } } /** * Check whether the given type has any subtypes other than that of the given * kind. For example, <code>int|{int f}</code> has a subtype other than a record * (i.e. an <code>int</code>). * * @param type * @param kind * @return */ public static boolean hasOtherSubtypesBesidesNull(Type type, Class<? extends Type> kind) { if (type instanceof Type.Nominal) { Type.Nominal t = (Type.Nominal) type; return hasOtherSubtypesBesidesNull(t.getConcreteType(), kind); } else if (type instanceof Type.Union) { Type.Union t = (Type.Union) type; for (int i = 0; i != t.size(); ++i) { if (hasOtherSubtypesBesidesNull(t.get(i), kind)) { return true; } } } else if (!(type instanceof Type.Null || kind.isInstance(type))) { return true; } return false; } /** * Determine the appropriate mangled string for a given named declaration. This * is critical to ensuring that overloaded declarations do not clash. * * @param decl * @return */ private String toMangledName(Decl.Named<?> decl) { // Determine whether this is an exported symbol or not boolean exported = decl.getModifiers().match(Modifier.Export.class) != null; // Construct base name String name = decl.getQualifiedName().toString().replace("::", "$"); // Add type mangles for non-exported symbols if(!exported && decl instanceof Decl.Method) { // FIXME: this could be simplified if TypeMangler was updated to support void. Decl.Method method = (Decl.Method) decl; Type parameters = method.getType().getParameter(); Type returns = method.getType().getReturn(); name += getMangle(parameters); name += getMangle(returns); } else if(!exported && decl instanceof Decl.Callable) { // FIXME: this could be simplified if TypeMangler was updated to support void. Decl.Callable callable = (Decl.Callable) decl; Type parameters = callable.getType().getParameter(); Type returns = callable.getType().getReturn(); name += getMangle(parameters); name += getMangle(returns); } else if(decl instanceof Decl.Type) { name += "$type"; } else if(decl instanceof Decl.StaticVariable) { name += "$static"; } return name; } /** * Determine the appropriate kind for a variable declaration. This depends on * what JavaScript standard is available. * * @param decl * @return */ private JavaScriptFile.VariableDeclaration.Kind toVariableKind(Decl.Named decl) { // Determine appropriate modifier if(jsFile.ES6()) { if(decl.getModifiers().match(Modifier.Final.class) != null) { return JavaScriptFile.VariableDeclaration.Kind.CONST; } else { return JavaScriptFile.VariableDeclaration.Kind.LET; } } else { return JavaScriptFile.VariableDeclaration.Kind.VAR; } } /** * Determine the appropriate kind for a statement initialiser. This depends on * what JavaScript standard is available. * * @param stmt * @return */ private JavaScriptFile.VariableDeclaration.Kind toVariableKind(Stmt.Initialiser stmt) { JavaScriptFile.VariableDeclaration.Kind kind = null; // Determine appropriate modifier for(Decl.Variable v : stmt.getVariables()) { JavaScriptFile.VariableDeclaration.Kind old = kind; kind = toVariableKind(v); if(old != null && kind != old) { // NOTE: this is a conservative translation as it's not clear how this could be done better. return JavaScriptFile.VariableDeclaration.Kind.VAR; } } return kind; } /** * Determine the best kind for an immutable local variable declaration. This * depends on what JavaScript standard is available. * * @return */ private JavaScriptFile.VariableDeclaration.Kind toLetKind() { if(jsFile.ES6()) { return JavaScriptFile.VariableDeclaration.Kind.LET; } else { return JavaScriptFile.VariableDeclaration.Kind.VAR; } } /** * Determine the best kind for a mutable local variable declaration. This * depends on what JavaScript standard is available. * * @return */ private JavaScriptFile.VariableDeclaration.Kind toConstKind() { if(jsFile.ES6()) { return JavaScriptFile.VariableDeclaration.Kind.CONST; } else { return JavaScriptFile.VariableDeclaration.Kind.VAR; } } /** * Convert a tuple of parameters into a list of their name strings. * * @param parameters * @return */ private List<String> toParameterNames(Tuple<Decl.Variable> parameters) { ArrayList<String> results = new ArrayList<>(); for(int i=0;i!=parameters.size();++i) { results.add(parameters.get(i).getName().toString()); } return results; } private Term[] toLambdaArguments(Tuple<Decl.Variable> arguments) { Term[] results = new Term[arguments.size()]; for (int i = 0; i != arguments.size(); ++i) { results[i] = new JavaScriptFile.VariableAccess(arguments.get(i).getName().toString()); } return results; } private String getMangle(Type type) { if (type.shape() == 0) { return "$V"; } else { return "$" + mangler.getMangle(type); } } private String getMangle(Type... types) { if (types.length == 0) { return "$V"; } else { return "$" + mangler.getMangle(types); } } /** * Attempt to filter the record array based on the number of fields. * Specifically, any records which don't have the specified number of fields are * eliminated. * * @param records * @param size * @return */ private static boolean filteredByFieldCount(List<Type.Record> records, int size, boolean isOpen) { boolean r = false; for (int i = 0; i != records.size(); ++i) { Type.Record record = records.get(i); int record_size = record.getFields().size(); if(isOpen || record.isOpen()) { // Could match r = true; } else if(isOpen && size <= record_size) { // Could match r = true; } else if (record.isOpen() && record_size <= size) { // Could match r = true; } else if(record_size != size) { // Could not match records.set(i, null); r = true; } } return r; } /** * Combine one or more array types into a single array type. * * @param types * @return */ private static Type.Array toArrayType(List<Type.Array> types) { if(types == null) { return null; } else if(types.size() == 0) { throw new IllegalArgumentException(); } else if(types.size() == 1) { return types.get(0); } else { Type[] elements = new Type[types.size()]; for(int i=0;i!=elements.length;++i) { elements[i] = types.get(i).getElement(); } return new Type.Array(new Type.Union(elements)); } } private static Type toFieldType(Identifier field, List<Type.Record> types) { if(types == null) { return null; } else if(types.size() == 0) { throw new IllegalArgumentException(); } else { Type[] elements = new Type[types.size()]; for(int i=0;i!=types.size();++i) { Type.Record rec = types.get(i); if (rec != null) { Type t = rec.getField(field); if (rec.isOpen() && t == null) { // NOTE: this is important as, otherwise, we'll make false assumptions in the // resulting type test. return null; } elements[i] = t; } } // Strip any null elements elements = ArrayUtils.removeAll(elements, null); // Done return new Type.Union(elements); } } /** * Strip off any nominal information. * * @param type * @return */ private static Type stripNominal(Type type) { if(type instanceof Type.Nominal) { Type.Nominal t = (Type.Nominal) type; return stripNominal(t.getConcreteType()); } else { return type; } } // Whiley Runtime Accessors /** * The unique name via which we can access the While runtime. This provides a * range of useful features for simplifying the translation to JavaScript. */ private static Term WY_RUNTIME = new JavaScriptFile.VariableAccess("Wy"); private static Term WY_ARRAY(Term t1, Term t2) { return new JavaScriptFile.Invoke(WY_RUNTIME, "array", t1, t2); } private static Term WY_ASSERT(Term t1) { return new JavaScriptFile.Invoke(WY_RUNTIME, "assert", t1); } private static Term WY_COPY(Term t1) { return new JavaScriptFile.Invoke(WY_RUNTIME, "copy", t1); } private static Term WY_EQUALS(Term t1, Term t2) { return new JavaScriptFile.Invoke(WY_RUNTIME, "equals", t1, t2); } private static Term WY_RECORD(Term t1) { return new JavaScriptFile.Invoke(WY_RUNTIME, "Record", t1); } private static Term WY_REF(Term t1) { return new JavaScriptFile.Invoke(WY_RUNTIME, "Ref", t1); } private static Term WY_TOSTRING(Term t1) { return new JavaScriptFile.Invoke(WY_RUNTIME, "toString", t1); } private static Term WY_FROMSTRING(Term t1) { return new JavaScriptFile.Invoke(WY_RUNTIME, "fromString", t1); } // JavaScript Runtime Accessors /** * Represents the Math module available from JavaScript. */ private static Term MATH_RUNTIME = new JavaScriptFile.VariableAccess("Math"); private static Term OBJECT_RUNTIME = new JavaScriptFile.VariableAccess("Object"); private static Term TypeOf(Term t1, String kind) { return new Operator(Kind.EEQ, new Operator(Kind.TYPEOF, t1), new Constant(kind)); } private static Term NonNull(Term t1) { return new Operator(Kind.NEEQ, t1, Constant.NULL); } private static Term ArrayConstructor(Term t1) { return new Operator(Kind.EEQ, new PropertyAccess(t1, "constructor"), new VariableAccess("Array")); } private static Term RecordConstructor(Term t1) { // NOTE: the or is necessary because of Wy.Copy I believe. return or( new Operator(Kind.EEQ, new PropertyAccess(t1, "constructor"), new PropertyAccess(new VariableAccess("Wy"), "Record")), new Operator(Kind.EEQ, new PropertyAccess(t1, "constructor"), new VariableAccess("Object"))); } private static Term ReferenceConstructor(Term t1) { return new Operator(Kind.NEQ, new Operator(Kind.TYPEOF, new PropertyAccess(t1, "$ref")), new Constant("undefined")); } private static Term MATH_FLOOR(Term t1) { return new JavaScriptFile.Invoke(MATH_RUNTIME, "floor", t1); } private static Term checkFieldCount(Term operand, int size) { Term term = new Invoke(new VariableAccess("Object"),"keys",operand); return new Operator(Kind.EEQ, new ArrayLength(term), new Constant(size)); } private static Term MASK_FF(Term t1) { Term FF = new Constant(0xFF); return new Operator(Operator.Kind.BITWISEAND,t1,FF); } private static Term PARSE_INT(String str, int base) { return new JavaScriptFile.Invoke(null, "parseInt", new Constant(str), new Constant(base)); } }
package P; import java.util.ArrayList; import java.util.List; public class A3 extends AMaster { public List<B3> listOfB3; public A3() { listOfB3 = new ArrayList<B3>(); } public int getSumNumberOfBElements() { int totalNumberOfElements = 0; for(B3 b : listOfB3) { totalNumberOfElements += b.getbVar1(); } return totalNumberOfElements; } }
package com.dianping.cat.report.page.home; import org.unidal.lookup.util.StringUtils; import org.unidal.web.mvc.ActionContext; import org.unidal.web.mvc.payload.annotation.FieldMeta; import com.dianping.cat.report.ReportPage; import com.dianping.cat.report.page.AbstractReportPayload; public class Payload extends AbstractReportPayload<Action> { @FieldMeta("op") private Action m_action; @FieldMeta("docName") private String m_docName = "userMonitor"; @FieldMeta("subDocName") private String m_subDocName; public Payload() { super(ReportPage.HOME); } @Override public Action getAction() { return m_action; } public String getSubDocName() { return m_subDocName; } public void setSubDocName(String subDocName) { m_subDocName = subDocName; } public void setAction(Action action) { m_action = action; } public String getDocName() { return m_docName; } public void setAction(String action) { m_action = Action.getByName(action, Action.VIEW); } public void setDocName(String docName) { m_docName = docName; } @Override public void validate(ActionContext<?> ctx) { if (m_action == null) { m_action = Action.VIEW; } } }
package cn.jingzhuan.lib.chart.renderer; import android.graphics.Canvas; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import cn.jingzhuan.lib.chart.AxisAutoValues; import cn.jingzhuan.lib.chart.base.Chart; import cn.jingzhuan.lib.chart.Viewport; import cn.jingzhuan.lib.chart.component.Axis; import cn.jingzhuan.lib.chart.component.AxisX; import cn.jingzhuan.lib.chart.component.AxisY; import cn.jingzhuan.lib.chart.data.LabelColorSetter; import cn.jingzhuan.lib.chart.data.ValueFormatter; import cn.jingzhuan.lib.chart.utils.FloatUtils; import java.util.List; public class AxisRenderer implements Renderer { private Viewport mCurrentViewport; private Rect mContentRect; private Axis mAxis; private final char[] mLabelBuffer = new char[100]; private Paint mGridPaint; private Paint mLabelTextPaint; private Paint mAxisPaint; private static final int POW10[] = {1, 10, 100, 1000, 10000, 100000, 1000000}; public AxisRenderer(Chart chart, Axis axis) { this.mCurrentViewport = chart.getCurrentViewport(); this.mContentRect = chart.getContentRect(); this.mAxis = axis; initPaints(); } public AxisRenderer(cn.jingzhuan.lib.chart2.base.Chart chart, Axis axis) { this.mCurrentViewport = chart.getCurrentViewport(); this.mContentRect = chart.getContentRect(); this.mAxis = axis; initPaints(); } protected void initPaints() { mGridPaint = new Paint(); mGridPaint.setStrokeWidth(mAxis.getGridThickness()); mGridPaint.setColor(mAxis.getGridColor()); mGridPaint.setStyle(Paint.Style.STROKE); mLabelTextPaint = new Paint(); mLabelTextPaint.setAntiAlias(true); mLabelTextPaint.setTextSize(mAxis.getLabelTextSize()); mLabelTextPaint.setColor(mAxis.getLabelTextColor()); mAxis.setLabelWidth((int) mLabelTextPaint.measureText("0000")); if (mAxis.getLabelTextSize() > 0) { mAxis.setLabelHeight((int) Math.abs(mLabelTextPaint.getFontMetrics().top)); } mAxisPaint = new Paint(); mAxisPaint.setStrokeWidth(mAxis.getAxisThickness()); mAxisPaint.setColor(mAxis.getAxisColor()); mAxisPaint.setStyle(Paint.Style.STROKE); } @Override public void renderer(Canvas canvas) { if (mAxis.getLabels() == null) { if (mAxis instanceof AxisX) { computeAxisStopsX(mCurrentViewport.left, mCurrentViewport.right, (AxisX) mAxis, null); } else if (mAxis instanceof AxisY) { computeAxisStopsY((AxisY) mAxis); } } // Draws lib container drawAxisLine(canvas); } private static void computeAxisStopsY(AxisY axis) { double min = axis.getYMin(); double max = axis.getYMax(); int count = axis.getGridCount() + 1; double interval = (max - min) / count; axis.mLabelEntries = new float[count + 1]; if (min < Float.MAX_VALUE && max > -Float.MAX_VALUE && min <= max) { double f = min; for (int j = 0; j < count + 1; f += interval, j++) { axis.mLabelEntries[j] = (float) f; } } } private void drawAxisLine(Canvas canvas) { float startX = 0f, startY = 0f, stopX = 0f, stopY = 0f; float halfThickness = mAxis.getAxisThickness() * .5f; switch (mAxis.getAxisPosition()) { case AxisX.TOP: case AxisX.TOP_INSIDE: startX = mContentRect.left; startY = mContentRect.top + halfThickness; stopX = mContentRect.right; stopY = startY; break; case AxisX.BOTTOM: case AxisX.BOTTOM_INSIDE: startX = mContentRect.left; startY = mContentRect.bottom - halfThickness; stopX = mContentRect.right; stopY = startY; break; case AxisY.LEFT_INSIDE: case AxisY.LEFT_OUTSIDE: startX = mContentRect.left + halfThickness; startY = mContentRect.top; stopX = startX; stopY = mContentRect.bottom; break; case AxisY.RIGHT_INSIDE: case AxisY.RIGHT_OUTSIDE: startX = mContentRect.right - halfThickness; startY = mContentRect.top; stopX = startX; stopY = mContentRect.bottom; break; } // Draw axis line if (mAxis.isEnable()) { canvas.drawLine(startX, startY, stopX, stopY, mAxisPaint); } } private static void computeAxisStopsX(float start, float stop, AxisX axis, AxisAutoValues autoValues) { double range = stop - start; if (axis.getGridCount() == 0 || range <= 0) { return; } final int count = axis.getGridCount() + 1; double rawInterval = range / count; double interval = roundToOneSignificantFigure(rawInterval); double first = Math.ceil(start / interval) * interval; double f; int i; axis.mLabelEntries = new float[count + 1]; for (f = first, i = 0; i < count + 1; f += interval, ++i) { axis.mLabelEntries[i] = (float) f; } } private static float roundToOneSignificantFigure(double num) { final float d = (float) Math.ceil((float) Math.log10(num < 0 ? -num : num)); final int power = 1 - (int) d; final float magnitude = (float) Math.pow(10, power); final long shifted = Math.round(num * magnitude); return shifted / magnitude; } /** * Computes the pixel offset for the given X lib value. This may be outside the view bounds. */ private float getDrawX(float x) { return mContentRect.left + mContentRect.width() * (x - mCurrentViewport.left) / mCurrentViewport.width(); } /** * Computes the pixel offset for the given Y lib value. This may be outside the view bounds. */ private float getDrawY(float y) { return mContentRect.bottom - mContentRect.height() * (y - mCurrentViewport.top) / mCurrentViewport.height(); } /** * Formats a float value to the given number of decimals. Returns the length of the string. * The string begins at out.length - [return value]. */ private static int formatFloat(final char[] out, float val, int digits) { boolean negative = false; if (val == 0) { out[out.length - 1] = '0'; return 1; } if (val < 0) { negative = true; val = -val; } if (digits > POW10.length) { digits = POW10.length - 1; } val *= POW10[digits]; long lval = Math.round(val); int index = out.length - 1; int charCount = 0; while (lval != 0 || charCount < (digits + 1)) { int digit = (int) (lval % 10); lval = lval / 10; out[index--] = (char) (digit + '0'); charCount++; if (charCount == digits) { out[index charCount++; } } if (negative) { out[index charCount++; } return charCount; } public void drawGridLines(Canvas canvas) { if (mAxis.isEnable() && mAxis.isGridLineEnable() && mAxis.getGridCount() > 0) { int count = mAxis.getGridCount() + 1; if (mAxis.getDashedGridIntervals() != null && mAxis.getDashedGridPhase() > 0) { mGridPaint.setPathEffect(new DashPathEffect(mAxis.getDashedGridIntervals(), mAxis.getDashedGridPhase())); } if (mAxis instanceof AxisX) { final float width = mContentRect.width() / ((float) count); for (int i = 1; i < count; i++) { if (mAxis.getGirdLineColorSetter() != null) { mGridPaint.setColor(mAxis.getGirdLineColorSetter().getColorByIndex(mAxis.getGridColor(), i)); } canvas.drawLine( mContentRect.left + i * width, mContentRect.top, mContentRect.left + i * width, mContentRect.bottom, mGridPaint); } } if (mAxis instanceof AxisY) { final float height = mContentRect.height() / ((float) count); for (int i = 1; i < count; i++) { if (mAxis.getGirdLineColorSetter() != null) { mGridPaint.setColor(mAxis.getGirdLineColorSetter().getColorByIndex(mAxis.getGridColor(), i)); } canvas.drawLine( mContentRect.left, mContentRect.top + i * height, mContentRect.right, mContentRect.top + i * height, mGridPaint); } } } } public void drawAxisLabels(Canvas canvas) { if (!mAxis.isLabelEnable()) return; if (mAxis.getLabels() == null || mAxis.getLabels().size() <= 0) return; List<String> labels = mAxis.getLabels(); mLabelTextPaint.setColor(mAxis.getLabelTextColor()); mLabelTextPaint.setTextSize(mAxis.getLabelTextSize()); float x = 0f, y = 0f; switch (mAxis.getAxisPosition()) { case AxisX.TOP: case AxisX.TOP_INSIDE: x = mContentRect.left; y = mContentRect.top; break; case AxisX.BOTTOM: case AxisX.BOTTOM_INSIDE: x = mContentRect.left; y = mContentRect.top + mContentRect.height(); break; case AxisY.LEFT_INSIDE: case AxisY.LEFT_OUTSIDE: x = mContentRect.left; y = mContentRect.bottom; break; case AxisY.RIGHT_INSIDE: case AxisY.RIGHT_OUTSIDE: x = mContentRect.right; y = mContentRect.bottom; break; } int labelOffset; int labelLength; if (mAxis instanceof AxisX) { final float width = mContentRect.width() / ((float) labels.size()); for (int i = 0; i < labels.size(); i++) { char[] labelCharArray = labels.get(i).toCharArray(); labelLength = labelCharArray.length; System.arraycopy(labelCharArray, 0, mLabelBuffer, mLabelBuffer.length - labelLength, labelLength); labelOffset = mLabelBuffer.length - labelLength; mLabelTextPaint.setTextAlign(Paint.Align.CENTER); LabelColorSetter colorSetter = mAxis.getLabelColorSetter(); if (colorSetter != null) { mLabelTextPaint.setColor(colorSetter.getColorByIndex(i)); } canvas.drawText(mLabelBuffer, labelOffset, labelLength, width * 0.5f + getDrawX(i / ((float) labels.size())), y + mLabelTextPaint.getTextSize(), mLabelTextPaint); } } else { final float height = mContentRect.height() / (mAxis.getLabels().size() - 1F); float separation = 0; for (int i = 0; i < mAxis.getLabels().size(); i++) { char[] labelCharArray = mAxis.getLabels().get(i).toCharArray(); labelLength = labelCharArray.length; System.arraycopy(labelCharArray, 0, mLabelBuffer, mLabelBuffer.length - labelLength, labelLength); labelOffset = mLabelBuffer.length - labelLength; switch (mAxis.getAxisPosition()) { case AxisY.LEFT_OUTSIDE: case AxisY.RIGHT_INSIDE: mLabelTextPaint.setTextAlign(Paint.Align.RIGHT); separation = -mAxis.getLabelSeparation(); break; case AxisY.LEFT_INSIDE: case AxisY.RIGHT_OUTSIDE: mLabelTextPaint.setTextAlign(Paint.Align.LEFT); separation = mAxis.getLabelSeparation(); break; } float textHeightOffset = (mLabelTextPaint.descent() + mLabelTextPaint.ascent()) / 2; LabelColorSetter colorSetter = mAxis.getLabelColorSetter(); if (colorSetter != null) { mLabelTextPaint.setColor(colorSetter.getColorByIndex(i)); } canvas.drawText(mLabelBuffer, labelOffset, labelLength, x + separation, y - i * height - textHeightOffset, mLabelTextPaint); } } } private void drawGridLabels(Canvas canvas) { if (!mAxis.isLabelEnable()) return; float[] labels = mAxis.mLabelEntries; if (labels == null || labels.length < 1) { return; } mLabelTextPaint.setColor(mAxis.getLabelTextColor()); mLabelTextPaint.setTextSize(mAxis.getLabelTextSize()); float x = 0f, y = 0f; switch (mAxis.getAxisPosition()) { case AxisX.TOP: case AxisX.TOP_INSIDE: x = mContentRect.left; y = mContentRect.top; break; case AxisX.BOTTOM: case AxisX.BOTTOM_INSIDE: x = mContentRect.left; y = mContentRect.top + mContentRect.height(); break; case AxisY.LEFT_INSIDE: case AxisY.LEFT_OUTSIDE: x = mContentRect.left; y = mContentRect.bottom; break; case AxisY.RIGHT_INSIDE: case AxisY.RIGHT_OUTSIDE: x = mContentRect.right; y = mContentRect.bottom; break; } int labelOffset; int labelLength; if (mAxis instanceof AxisX) { final float width = mContentRect.width() / (labels.length - 1F); for (int i = 0; i < labels.length; i++) { ValueFormatter valueFormatter = mAxis.getLabelValueFormatter(); if (valueFormatter == null) { labelLength = FloatUtils.formatFloatValue(mLabelBuffer, labels[i], 2); } else { char[] labelCharArray = valueFormatter.format(labels[i], i).toCharArray(); labelLength = labelCharArray.length; System.arraycopy(labelCharArray, 0, mLabelBuffer, mLabelBuffer.length - labelLength, labelLength); } labelOffset = mLabelBuffer.length - labelLength; if (i == 0) { mLabelTextPaint.setTextAlign(Paint.Align.LEFT); } else if (i == labels.length - 1) { mLabelTextPaint.setTextAlign(Paint.Align.RIGHT); } else { mLabelTextPaint.setTextAlign(Paint.Align.CENTER); } LabelColorSetter colorSetter = ((AxisX) mAxis).getLabelColorSetter(); if (colorSetter != null) { mLabelTextPaint.setColor(colorSetter.getColorByIndex(i)); } canvas.drawText(mLabelBuffer, labelOffset, labelLength, x + i * width, // - textWidth * 0.5f, y + mLabelTextPaint.getTextSize(), mLabelTextPaint); } } else { final float height = mContentRect.height() / (labels.length - 1F); float separation = 0; for (int i = 0; i < labels.length; i++) { ValueFormatter valueFormatter = mAxis.getLabelValueFormatter(); if (valueFormatter == null) { labelLength = FloatUtils.formatFloatValue(mLabelBuffer, labels[i], 2); } else { char[] labelCharArray = valueFormatter.format(labels[i], i).toCharArray(); labelLength = labelCharArray.length; System.arraycopy(labelCharArray, 0, mLabelBuffer, mLabelBuffer.length - labelLength, labelLength); } labelOffset = mLabelBuffer.length - labelLength; switch (mAxis.getAxisPosition()) { case AxisY.LEFT_OUTSIDE: case AxisY.RIGHT_INSIDE: mLabelTextPaint.setTextAlign(Paint.Align.RIGHT); separation = -mAxis.getLabelSeparation(); break; case AxisY.LEFT_INSIDE: case AxisY.RIGHT_OUTSIDE: mLabelTextPaint.setTextAlign(Paint.Align.LEFT); separation = mAxis.getLabelSeparation(); break; } float textHeightOffset = (mLabelTextPaint.descent() + mLabelTextPaint.ascent()) / 2; if (i == 0) { // Bottom textHeightOffset = mAxis.getLabelSeparation(); } else if (i == labels.length - 1) { // Top textHeightOffset += textHeightOffset - mAxis.getLabelSeparation(); } LabelColorSetter colorSetter = ((AxisY) mAxis).getLabelColorSetter(); if (colorSetter != null) { mLabelTextPaint.setColor(colorSetter.getColorByIndex(i)); } canvas.drawText(mLabelBuffer, labelOffset, labelLength, x + separation, y - i * height - textHeightOffset, mLabelTextPaint); } } } public void drawLabels(Canvas canvas) { if (mAxis.getLabels() == null) { drawGridLabels(canvas); } else { drawAxisLabels(canvas); } } public void setTypeface(Typeface tf) { mLabelTextPaint.setTypeface(tf); } }
package co.chatsdk.core.utils; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import io.reactivex.disposables.Disposable; public class DisposableList { private final List<Disposable> disposables = Collections.synchronizedList(new ArrayList<>()); public void add (Disposable d) { disposables.add(d); } public void remove (Disposable d) { disposables.remove(d); } public void dispose () { synchronized (disposables) { Iterator<Disposable> iterator = disposables.iterator(); while (iterator.hasNext()) { iterator.next().dispose(); } disposables.clear(); } } }
package prj.chameleon.qqmsdk; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.RemoteException; import android.util.Log; import android.widget.Toast; import com.tencent.msdk.WeGame; import com.tencent.msdk.api.LoginRet; import com.tencent.msdk.api.MsdkBaseInfo; import com.tencent.msdk.api.ShareRet; import com.tencent.msdk.api.TokenRet; import com.tencent.msdk.api.WGPlatform; import com.tencent.msdk.api.WGPlatformObserver; import com.tencent.msdk.api.WGQZonePermissions; import com.tencent.msdk.api.WakeupRet; import com.tencent.msdk.consts.CallbackFlag; import com.tencent.msdk.consts.EPlatform; import com.tencent.msdk.consts.TokenType; import com.tencent.msdk.myapp.autoupdate.WGSaveUpdateObserver; import com.tencent.msdk.remote.api.RelationRet; import com.tencent.unipay.plugsdk.IUnipayServiceCallBack; import com.tencent.unipay.plugsdk.UnipayPlugAPI; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import prj.chameleon.channelapi.ApiCommonCfg; import prj.chameleon.channelapi.Constants; import prj.chameleon.channelapi.IAccountActionListener; import prj.chameleon.channelapi.IDispatcherCb; import prj.chameleon.channelapi.JsonMaker; import prj.chameleon.channelapi.SingleSDKChannelAPI; public final class QqmsdkChannelAPI extends SingleSDKChannelAPI.SingleSDK { private static class Config { public String mQQAppId; public String mQQAppKey; public String mWXAppId; public String mWXAppKey; public String mOfferId; public String mMoneyIconFile; public boolean mIsTest; } private static class PaymentEnv { public PaymentEnv (Activity activity, IDispatcherCb cb) { mActivity = new WeakReference<Activity>(activity); mCb = cb; } public WeakReference<Activity> mActivity; public IDispatcherCb mCb; } private static class UserInfo { public boolean mIsLogined; public String mAccessToken; public String mPayToken; public String mRefreshToken; public String mOpenId; public String mDesc; public String mPf; public String mPfKey; public EPlatform mPlatform; public long mAccessTokenExpire; public long mRefrehTokenExpire; public UserInfo() { mIsLogined = false; } public void setLogout() { mIsLogined = false; mAccessToken = ""; mPayToken = ""; mRefreshToken = ""; mOpenId = ""; mDesc = ""; mPf = ""; mPfKey = ""; mAccessTokenExpire = 0; mRefrehTokenExpire = 0; mPlatform = EPlatform.ePlatform_None; } } private static final String WX_PLATFORM = "w"; private static final String QQ_PLATFORM = "q"; private static final int INVALID_PLAT = -99999; private static final int LOGIN_TIMEOUT = 10; private static final int LOGIN_TIMEOUT_EVT_ID = 0; private IAccountActionListener mAccountActionListener; private final Config mCfg = new Config(); private int mPlatform = INVALID_PLAT; private final UserInfo mUserInfo = new UserInfo(); private UnipayPlugAPI mUniPay = null; private IDispatcherCb mLoginCb = null; private PaymentEnv mPayEnv = null; private byte[] mMoneyIcon = null; private int mCmdSeq = 0; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case LOGIN_TIMEOUT_EVT_ID: if (mLoginCb != null && msg.arg1 == mCmdSeq) { mLoginCb.onFinished(Constants.ErrorCode.ERR_FAIL, null); } break; default: break; } } }; private class PlatformObserver implements WGPlatformObserver { @Override public void OnLoginNotify(LoginRet loginRet) { if (mLoginCb == null) { return; } switch (loginRet.flag) { case CallbackFlag.eFlag_Succ: FillUserInfo(loginRet); String platform = null; if (loginRet.flag == WeGame.QQPLATID) { platform = QQ_PLATFORM; } else if (loginRet.flag == WeGame.WXPLATID) { platform = WX_PLATFORM; } try { mLoginCb.onFinished(Constants.ErrorCode.ERR_OK, makeLoginInfo(mUserInfo.mOpenId, mUserInfo.mAccessToken, platform)); } catch (JSONException e) { mLoginCb.onFinished(Constants.ErrorCode.ERR_INTERNAL, null); } break; case CallbackFlag.eFlag_WX_UserCancel: case CallbackFlag.eFlag_QQ_UserCancel: mLoginCb.onFinished(Constants.ErrorCode.ERR_CANCEL, null); break; case CallbackFlag.eFlag_QQ_NotInstall: mLoginCb.onFinished(Constants.ErrorCode.ERR_LOGIN_IN_QQ_NON_INSTALLED, null); break; case CallbackFlag.eFlag_WX_NotInstall: mLoginCb.onFinished(Constants.ErrorCode.ERR_LOGIN_IN_WX_NON_INSTALLED, null); break; case CallbackFlag.eFlag_WX_NotSupportApi: case CallbackFlag.eFlag_WX_LoginFail: case CallbackFlag.eFlag_QQ_NotSupportApi: case CallbackFlag.eFlag_QQ_LoginFail: case CallbackFlag.eFlag_Local_Invalid: mLoginCb.onFinished(Constants.ErrorCode.ERR_FAIL, null); break; default: mLoginCb.onFinished(Constants.ErrorCode.ERR_UNKNOWN, null); break; } if (loginRet.flag != CallbackFlag.eFlag_Succ) { Log.e(Constants.TAG, "Fail to login " + loginRet.flag + loginRet.desc); } mLoginCb = null; } @Override public void OnShareNotify(ShareRet shareRet) { } @Override public void OnWakeupNotify(WakeupRet wakeupRet) { } @Override public void OnRelationNotify(RelationRet relationRet) { } @Override public void OnLocationNotify(RelationRet relationRet) { } @Override public void OnFeedbackNotify(int i, String s) { } @Override public String OnCrashExtMessageNotify() { return null; } } IUnipayServiceCallBack.Stub mUnipayStubCallBack = new IUnipayServiceCallBack.Stub() { @Override public void UnipayNeedLogin() throws RemoteException { if (mPayEnv == null) { Log.e(Constants.TAG, "pay callback is null"); return; } Activity activity = mPayEnv.mActivity.get(); if (activity == null) { Log.e(Constants.TAG, "callback activity is gone"); mPayEnv = null; return; } activity.runOnUiThread(new Runnable() { @Override public void run() { mPayEnv.mCb.onFinished(Constants.ErrorCode.ERR_PAY_SESSION_INVALID, null); mPayEnv = null; } }); } @Override public void UnipayCallBack(final int code, int payChannel, final int payState, int providerState, int saveNum, String resultMsg, String extendInfo) throws RemoteException { if (mPayEnv == null) { Log.e(Constants.TAG, "pay callback is null"); return; } Log.d(Constants.TAG, "receive code: " + code + " msg: " + resultMsg); final Activity activity = mPayEnv.mActivity.get(); if (activity == null) { Log.e(Constants.TAG, "callback activity is gone"); mPayEnv = null; return; } activity.runOnUiThread(new Runnable() { @Override public void run() { switch (code) { case 0: if (payState == 0) { CharSequence text = ""; Toast toast = Toast.makeText(activity.getApplicationContext(), text, Toast.LENGTH_SHORT); toast.show(); mPayEnv.mCb.onFinished(Constants.ErrorCode.ERR_PAY_RETRY, null); } else if (payState == 1) { mPayEnv.mCb.onFinished(Constants.ErrorCode.ERR_PAY_CANCEL, null); } else if (payState == 2) { mPayEnv.mCb.onFinished(Constants.ErrorCode.ERR_PAY_FAIL, null); } else { mPayEnv.mCb.onFinished(Constants.ErrorCode.ERR_PAY_UNKNOWN, null); } break; case -2: Log.e(Constants.TAG, "binding error"); mPayEnv.mCb.onFinished(Constants.ErrorCode.ERR_INTERNAL, null); break; case 2: mPayEnv.mCb.onFinished(Constants.ErrorCode.ERR_PAY_CANCEL, null); break; default: mPayEnv.mCb.onFinished(Constants.ErrorCode.ERR_FAIL, null); } mPayEnv = null; } }); } }; public void initCfg(ApiCommonCfg commCfg, Bundle cfg) { mChannel = commCfg.mChannel; mCfg.mQQAppId = cfg.getString("qqAppId"); mCfg.mQQAppKey = cfg.getString("qqAppKey"); mCfg.mWXAppId = cfg.getString("wxAppId"); mCfg.mWXAppKey = cfg.getString("wxAppKey"); mCfg.mOfferId = cfg.getString("qqAppId"); mCfg.mMoneyIconFile = cfg.getString("moneyIcon"); mCfg.mIsTest = cfg.getBoolean("test"); } /** * init the SDK * @param activity the activity to give the real SDK * @param cb callback function when the request is finished, the JSON object is null */ @Override public void init(android.app.Activity activity, final IDispatcherCb cb) { MsdkBaseInfo baseInfo = new MsdkBaseInfo(); if (mCfg.mQQAppId != null) { baseInfo.qqAppId = mCfg.mQQAppId; baseInfo.qqAppKey = mCfg.mQQAppKey; } if (mCfg.mWXAppId != null) { baseInfo.wxAppId = mCfg.mWXAppId; baseInfo.wxAppKey = mCfg.mWXAppKey; } baseInfo.offerId = mCfg.mOfferId; WGPlatform.Initialized(activity, baseInfo); WGPlatform.WGSetPermission(WGQZonePermissions.eOPEN_ALL); WGPlatform.WGSetObserver(new PlatformObserver()); WGPlatform.WGSetSaveUpdateObserver(new WGSaveUpdateObserver() { @Override public void OnCheckNeedUpdateInfo(long l, String s, long l2, int i, String s2, int i2) { } @Override public void OnDownloadAppProgressChanged(long l, long l2) { } @Override public void OnDownloadAppStateChanged(int i, int i2, String s) { } @Override public void OnDownloadYYBProgressChanged(String s, long l, long l2) { } @Override public void OnDownloadYYBStateChanged(String s, int i, int i2, String s2) { } }); WGPlatform.handleCallback(activity.getIntent()); try { InputStream is = activity.getAssets().open(mCfg.mMoneyIconFile); mMoneyIcon = new byte[is.available()]; is.read(mMoneyIcon); cb.onFinished(Constants.ErrorCode.ERR_OK, null); } catch (IOException e) { Log.e(Constants.TAG, "Fail to open money cfg"); cb.onFinished(Constants.ErrorCode.ERR_FAIL, null); } } /** * user login to platform * @param activity the activity to give the real SDK * @param cb JSON object will have two fields * token : the access token from the platform * others: a segment of json string for SDK server * @param accountActionListener listener of the user account actions, refer to the interface definition */ @Override public void login(android.app.Activity activity, final IDispatcherCb cb, IAccountActionListener accountActionListener) { if (mLoginCb != null) { cb.onFinished(Constants.ErrorCode.ERR_LOGIN_IN_PROGRESS, null); return; } setAccountActionListener(accountActionListener); mUserInfo.setLogout(); LoginRet lr = new LoginRet(); int platform = WGPlatform.WGGetLoginRecord(lr); if (platform != 0 && lr.flag == CallbackFlag.eFlag_Succ) { mPlatform = platform; try { if (platform == WeGame.QQPLATID) { JSONObject loginInfo = onLocalQQLoginRecord(lr); cb.onFinished(Constants.ErrorCode.ERR_OK, loginInfo); return; } else if (platform == WeGame.WXPLATID) { JSONObject loginInfo = onLocalWXLoginRecord(lr); cb.onFinished(Constants.ErrorCode.ERR_OK, loginInfo); return; } } catch (Exception e) { cb.onFinished(Constants.ErrorCode.ERR_INTERNAL, null); return; } } if (mPlatform == WeGame.QQPLATID) { WGPlatform.WGLogin(EPlatform.ePlatform_QQ); mLoginCb = cb; } else if (mPlatform == WeGame.WXPLATID) { WGPlatform.WGLogin(EPlatform.ePlatform_Weixin); mLoginCb = cb; startLoginTimer(); } else { cb.onFinished(Constants.ErrorCode.ERR_LOGIN_MSDK_PLAT_NO_SPEC, null); } } /** * user charge the currency in the game * @param activity the activity to give the real SDK * @param orderId the order id from server * @param uidInGame player id in the game * @param userNameInGame player name in the game * @param serverId current server id * @param currencyName the currency name * @param rate the rate of the game currency to RMB, e.g. 1.0 can buy 10 game currency, then * rate = 10 * @param realPayMoney the real money to pay * @param allowUserChange can user change the amnout he paid * @param cb JSON object will be null */ public void charge(Activity activity, String orderId, String uidInGame, String userNameInGame, String serverId, String currencyName, String payInfo, int rate, int realPayMoney, boolean allowUserChange, final IDispatcherCb cb) { if (mPayEnv != null) { cb.onFinished(Constants.ErrorCode.ERR_PAY_IN_PROGRESS, null); return; } if (!mUserInfo.mIsLogined) { cb.onFinished(Constants.ErrorCode.ERR_PAY_SESSION_INVALID, null); return; } try { JSONObject payInfoObj = new JSONObject(payInfo); int rest = payInfoObj.getInt("rest"); if (rest < 0) { cb.onFinished(Constants.ErrorCode.ERR_OK, null); } else { CharSequence text = ""; Toast toast = Toast.makeText(activity.getApplicationContext(), text, Toast.LENGTH_SHORT); toast.show(); String sessionid = "openid"; String sessiontype = "kp_actoken"; if (mUserInfo.mPlatform == EPlatform.ePlatform_Weixin) { sessionid = "hy_gameid"; sessiontype = "wc_actoken"; } mUniPay.SaveGameCoinsWithNum(mUserInfo.mOpenId, mUserInfo.mPayToken, sessionid, sessiontype, serverId, mUserInfo.mPf, mUserInfo.mPfKey, UnipayPlugAPI.ACCOUNT_TYPE_COMMON, String.valueOf(rest), allowUserChange, mMoneyIcon); mPayEnv = new PaymentEnv(activity, cb); } } catch (JSONException e) { Log.e(Constants.TAG, "Fail to parse pay info from server", e); cb.onFinished(Constants.ErrorCode.ERR_INTERNAL, null); } catch (RemoteException e) { Log.e(Constants.TAG, "remote error", e); cb.onFinished(Constants.ErrorCode.ERR_FAIL, null); } } /** * user buy a product * @param activity the activity to give the real SDK * @param orderId the order id from server * @param uidInGame player id in the game * @param userNameInGame player name in the game * @param serverId current server id * @param productName the name of the product * @param productID the id of the product * @param productCount the count of product * @param realPayMoney the real money to pay * @param cb JSON object will be null */ @Override public void buy(Activity activity, String orderId, String uidInGame, String userNameInGame, String serverId, String productName, String productID, String payInfo, int productCount, int realPayMoney, final IDispatcherCb cb) { if (mPayEnv != null) { cb.onFinished(Constants.ErrorCode.ERR_PAY_IN_PROGRESS, null); return; } if (!mUserInfo.mIsLogined) { cb.onFinished(Constants.ErrorCode.ERR_PAY_SESSION_INVALID, null); return; } try { JSONObject payInfoObj = new JSONObject(payInfo); int rest = payInfoObj.getInt("rest"); if (rest < 0) { cb.onFinished(Constants.ErrorCode.ERR_OK, null); } else { CharSequence text = ""; Toast toast = Toast.makeText(activity.getApplicationContext(), text, Toast.LENGTH_SHORT); toast.show(); String sessionid = "openid"; String sessiontype = "kp_actoken"; if (mUserInfo.mPlatform == EPlatform.ePlatform_Weixin) { sessionid = "hy_gameid"; sessiontype = "wc_actoken"; } mUniPay.SaveGameCoinsWithNum(mUserInfo.mOpenId, mUserInfo.mPayToken, sessionid, sessiontype, serverId, mUserInfo.mPf, mUserInfo.mPfKey, UnipayPlugAPI.ACCOUNT_TYPE_COMMON, String.valueOf(rest), true, mMoneyIcon); mPayEnv = new PaymentEnv(activity, cb); } } catch (JSONException e) { Log.e(Constants.TAG, "Fail to parse pay info from server", e); cb.onFinished(Constants.ErrorCode.ERR_INTERNAL, null); } catch (RemoteException e) { Log.e(Constants.TAG, "remote error", e); cb.onFinished(Constants.ErrorCode.ERR_FAIL, null); } } @Override public JSONObject getPayInfo() { if (!mUserInfo.mIsLogined) { return null; } try { JSONObject ret = new JSONObject(); ret.put("p", mUserInfo.mPf); ret.put("pk", mUserInfo.mPfKey); ret.put("t", mUserInfo.mAccessToken); ret.put("pt", mUserInfo.mPayToken); if (mUserInfo.mPlatform == EPlatform.ePlatform_QQ) { ret.put("pl", QQ_PLATFORM); } else { ret.put("pl", WX_PLATFORM); } return ret; } catch (JSONException e) { Log.e(Constants.TAG, "Fail to get pay info from msdk", e); return null; } } @Override public String getId() { return "qqmsdk"; } /** * user logout * @param activity the activity to give the real SDK */ @Override public void logout(Activity activity) { WGPlatform.WGLogout(); mUserInfo.setLogout(); if (mAccountActionListener != null) { activity.runOnUiThread(new Runnable() { @Override public void run() { mAccountActionListener.onAccountLogout(); } }); } } @Override public String getUid() { return mUserInfo.mOpenId; } @Override public String getToken() { return mUserInfo.mAccessToken; } @Override public boolean isLogined() { return mUserInfo.mIsLogined; } @Override public void onNewIntent(Activity activity, Intent intent) { WGPlatform.handleCallback(intent); } @Override public void onDestroy(Activity activity) { WGPlatform.onDestory(activity); mMoneyIcon = null; mLoginCb = null; mPayEnv = null; } /** * destroy the sdk instance * @param activity the activity to give the real SDK */ @Override public void exit(Activity activity, final IDispatcherCb cb) { cb.onFinished(Constants.ErrorCode.ERR_LOGIN_GAME_EXIT_NOCARE, null); } /** * set account action listener, add global nd91 listener * @param accountActionListener account action */ private void setAccountActionListener(final IAccountActionListener accountActionListener) { this.mAccountActionListener = accountActionListener; } private JSONObject onLocalQQLoginRecord(LoginRet ret) throws JSONException { FillUserInfo(ret); mUserInfo.mAccessToken = WeGame.getInstance().getLocalTokenByType(TokenType.eToken_QQ_Access); mUserInfo.mPayToken = WeGame.getInstance().getLocalTokenByType(TokenType.eToken_QQ_Pay); return makeLoginInfo(mUserInfo.mOpenId, mUserInfo.mAccessToken, QQ_PLATFORM); } private JSONObject onLocalWXLoginRecord(LoginRet ret) throws JSONException { FillUserInfo(ret); mUserInfo.mAccessToken = WeGame.getInstance().getLocalTokenByType(TokenType.eToken_WX_Access); mUserInfo.mRefreshToken = WeGame.getInstance().getLocalTokenByType(TokenType.eToken_WX_Refresh); mUserInfo.mPayToken = mUserInfo.mAccessToken; return makeLoginInfo(mUserInfo.mOpenId, mUserInfo.mAccessToken, WX_PLATFORM); } private JSONObject makeLoginInfo(String openId, String openKey, String platform) throws JSONException { JSONObject obj = new JSONObject(); obj.put("uid", openId); obj.put("pl", platform); return JsonMaker.makeLoginResponse(openKey, obj.toString(), mChannel); } private void FillUserInfo(LoginRet ret) { mUserInfo.mOpenId = ret.open_id; mUserInfo.mDesc = ret.desc; mUserInfo.mPf = ret.pf; mUserInfo.mPfKey = ret.pf_key; if (ret.platform == WeGame.QQPLATID) { mUserInfo.mPlatform = EPlatform.ePlatform_QQ; for (TokenRet tr: ret.token) { switch (tr.type) { case TokenType.eToken_QQ_Access: mUserInfo.mAccessToken = tr.value; mUserInfo.mAccessTokenExpire = tr.expiration; break; case TokenType.eToken_QQ_Pay: mUserInfo.mPayToken = tr.value; mUserInfo.mRefrehTokenExpire = tr.expiration; break; } } } else if (ret.platform == WeGame.WXPLATID) { mUserInfo.mPlatform = EPlatform.ePlatform_Weixin; for (TokenRet tr: ret.token) { switch (tr.type) { case TokenType.eToken_WX_Access: mUserInfo.mAccessToken = tr.value; mUserInfo.mAccessTokenExpire = tr.expiration; break; case TokenType.eToken_WX_Refresh: mUserInfo.mRefreshToken = tr.value; mUserInfo.mRefrehTokenExpire = tr.expiration; break; } } } else { throw new RuntimeException("unknown platform " + ret.platform); } } @Override public boolean onLoginRsp(String loginRsp) { JSONObject obj; try { obj = new JSONObject(loginRsp); int code = obj.getInt("code"); if (code != Constants.ErrorCode.ERR_OK) { return false; } else { mUserInfo.mIsLogined = true; return true; } } catch (JSONException e) { Log.e(Constants.TAG, "Fail to parse login rsp", e); return false; } } @Override public void onResume(Activity activity, final IDispatcherCb cb) { WGPlatform.onResume(); cb.onFinished(Constants.ErrorCode.ERR_OK, null); if (mPayEnv != null) { mPayEnv.mCb.onFinished(Constants.ErrorCode.ERR_CANCEL, null); mPayEnv = null; } } @Override public void onPause(Activity activity) { WGPlatform.onPause(); } @Override public void onStart(Activity activity) { if (mUniPay == null) { mUniPay = new UnipayPlugAPI(activity); mUniPay.setCallBack(mUnipayStubCallBack); mUniPay.bindUnipayService(); mUniPay.setOfferId(mCfg.mQQAppId); if (mCfg.mIsTest) { mUniPay.setEnv("test"); } else { mUniPay.setEnv("release"); } } } @Override public void onStop(Activity activity) { if (mUniPay != null) { mUniPay.unbindUnipayService(); } mUniPay = null; } @Override public boolean runProtocol(Activity activity, String protocol, String message, IDispatcherCb cb) { if (protocol.equals("qqmsdk_setplat")) { int ret = Constants.ErrorCode.ERR_OK; if (message.equals("wx")) { mPlatform = WeGame.WXPLATID; } else if (message.equals("qq")) { mPlatform = WeGame.QQPLATID; } else { ret = Constants.ErrorCode.ERR_FAIL; } cb.onFinished(ret, null); return true; } return false; } @Override public boolean isSupportProtocol(String protocol) { if (protocol.equals("qqmsdk_setplat")) { return true; } return false; } private void startLoginTimer () { mCmdSeq += 1; Message msg = new Message(); msg.arg1 = mCmdSeq; mHandler.sendMessageAtTime(msg, LOGIN_TIMEOUT*1000); } }
package com.newsblur.service; import android.util.Log; import com.newsblur.domain.Story; import com.newsblur.network.domain.StoriesResponse; import com.newsblur.network.domain.UnreadStoryHashesResponse; import com.newsblur.util.AppConstants; import com.newsblur.util.DefaultFeedView; import com.newsblur.util.FeedUtils; import com.newsblur.util.PrefsUtils; import com.newsblur.util.StoryOrder; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.Set; import java.util.TreeMap; public class UnreadsService extends SubService { private static volatile boolean Running = false; private static volatile boolean doMetadata = false; /** Unread story hashes the API listed that we do not appear to have locally yet. */ private static List<String> StoryHashQueue; static { StoryHashQueue = new ArrayList<String>(); } public UnreadsService(NBSyncService parent) { super(parent); } @Override protected void exec() { // only use the unread status API if the user is premium if (parent.isPremium != Boolean.TRUE) return; if (doMetadata) { gotWork(); syncUnreadList(); doMetadata = false; } if (StoryHashQueue.size() < 1) return; getNewUnreadStories(); } private void syncUnreadList() { // a self-sorting map with keys based upon the timestamp of the story returned by // the unreads API, concatenated with the hash to disambiguate duplicate timestamps. // values are the actual story hash, which will be extracted once we have processed // all hashes. NavigableMap<String,String> sortingMap = new TreeMap<String,String>(); UnreadStoryHashesResponse unreadHashes = parent.apiManager.getUnreadStoryHashes(); // note all the stories we thought were unread before. if any fail to appear in // the API request for unreads, we will mark them as read List<String> oldUnreadHashes = parent.dbHelper.getUnreadStoryHashes(); // process the api response, both bookkeeping no-longer-unread stories and populating // the sortation map we will use to create the fetch list for step two for (Entry<String, List<String[]>> entry : unreadHashes.unreadHashes.entrySet()) { String feedId = entry.getKey(); // ignore unreads from orphaned feeds if( ! parent.orphanFeedIds.contains(feedId)) { // only fetch the reported unreads if we don't already have them List<String> existingHashes = parent.dbHelper.getStoryHashesForFeed(feedId); for (String[] newHash : entry.getValue()) { if (!existingHashes.contains(newHash[0])) { sortingMap.put(newHash[1]+newHash[0], newHash[0]); } oldUnreadHashes.remove(newHash[0]); } } } // now that we have the sorted set of hashes, turn them into a list over which we // can iterate to fetch them if (PrefsUtils.getDefaultStoryOrder(parent) == StoryOrder.NEWEST) { // if the user reads newest-first by default, reverse the download order sortingMap = sortingMap.descendingMap(); } StoryHashQueue.clear(); for (Map.Entry<String,String> entry : sortingMap.entrySet()) { StoryHashQueue.add(entry.getValue()); } // any stories that we previously thought to be unread but were not found in the // list, mark them read now parent.dbHelper.markStoryHashesRead(oldUnreadHashes); } private void getNewUnreadStories() { unreadsyncloop: while (StoryHashQueue.size() > 0) { if (parent.stopSync()) return; if(!PrefsUtils.isOfflineEnabled(parent)) return; gotWork(); List<String> hashBatch = new ArrayList(AppConstants.UNREAD_FETCH_BATCH_SIZE); batchloop: for (String hash : StoryHashQueue) { hashBatch.add(hash); if (hashBatch.size() >= AppConstants.UNREAD_FETCH_BATCH_SIZE) break batchloop; } StoriesResponse response = parent.apiManager.getStoriesByHash(hashBatch); if (! isStoryResponseGood(response)) { Log.e(this.getClass().getName(), "error fetching unreads batch, abandoning sync."); break unreadsyncloop; } parent.insertStories(response); for (String hash : hashBatch) { StoryHashQueue.remove(hash); } for (Story story : response.stories) { if (story.imageUrls != null) { for (String url : story.imageUrls) { parent.imagePrefetchService.addUrl(url); } } DefaultFeedView mode = PrefsUtils.getDefaultFeedViewForFeed(parent, story.feedId); if (mode == DefaultFeedView.TEXT) { parent.originalTextService.addHash(story.storyHash); } } parent.originalTextService.start(startId); parent.imagePrefetchService.start(startId); } } private boolean isStoryResponseGood(StoriesResponse response) { if (response == null) { Log.e(this.getClass().getName(), "Null response received while loading stories."); return false; } if (response.stories == null) { Log.e(this.getClass().getName(), "Null stories member received while loading stories."); return false; } return true; } public static void clearHashes() { StoryHashQueue.clear(); } /** * Describe the number of unreads left to be synced or return an empty message (space padded). */ public static String getPendingCount() { int c = StoryHashQueue.size(); if (c < 1) { return " "; } else { return " " + c + " "; } } public static void doMetadata() { doMetadata = true; } public static boolean running() { return Running; } @Override protected void setRunning(boolean running) { Running = running; } @Override protected boolean isRunning() { return Running; } }
package com.newsblur.util; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.os.Build; import com.newsblur.R; import com.newsblur.activity.FeedReading; import com.newsblur.activity.Reading; import com.newsblur.database.DatabaseConstants; import com.newsblur.domain.Story; import com.newsblur.util.FileCache; public class NotificationUtils { private static final int NOTIFY_COLOUR = 0xFFDA8A35; private static final int MAX_CONCUR_NOTIFY = 5; private NotificationUtils() {} // util class - no instances /** * @param storiesFocus a cursor of unread, focus stories to notify, ordered newest to oldest * @param storiesUnread a cursor of unread, neutral stories to notify, ordered newest to oldest */ public static synchronized void notifyStories(Cursor storiesFocus, Cursor storiesUnread, Context context, FileCache iconCache) { FeedUtils.offerInitContext(context); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); int count = 0; while (storiesFocus.moveToNext()) { Story story = Story.fromCursor(storiesFocus); if (story.read) { nm.cancel(story.hashCode()); continue; } if (FeedUtils.dbHelper.isStoryDismissed(story.storyHash)) { nm.cancel(story.hashCode()); continue; } if (count < MAX_CONCUR_NOTIFY) { Notification n = buildStoryNotification(story, storiesFocus, context, iconCache); nm.notify(story.hashCode(), n); } else { nm.cancel(story.hashCode()); FeedUtils.dbHelper.putStoryDismissed(story.storyHash); } count++; } while (storiesUnread.moveToNext()) { Story story = Story.fromCursor(storiesUnread); if (story.read) { nm.cancel(story.hashCode()); continue; } if (FeedUtils.dbHelper.isStoryDismissed(story.storyHash)) { nm.cancel(story.hashCode()); continue; } if (count < MAX_CONCUR_NOTIFY) { Notification n = buildStoryNotification(story, storiesUnread, context, iconCache); nm.notify(story.hashCode(), n); } else { nm.cancel(story.hashCode()); FeedUtils.dbHelper.putStoryDismissed(story.storyHash); } count++; } } // addAction deprecated in 23 but replacement not avail until 21 @SuppressWarnings("deprecation") private static Notification buildStoryNotification(Story story, Cursor cursor, Context context, FileCache iconCache) { Intent i = new Intent(context, FeedReading.class); // the action is unused, but bugs in some platform versions ignore extras if it is unset i.setAction(story.storyHash); // these extras actually dictate activity behaviour i.putExtra(Reading.EXTRA_FEEDSET, FeedSet.singleFeed(story.feedId)); i.putExtra(Reading.EXTRA_STORY_HASH, story.storyHash); // force a new Reading activity, since if multiple notifications are tapped, any re-use or // stacking of the activity would almost certainly out-race the sync loop and cause stale // UI on some devices. i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); // set the requestCode to the story hashcode to prevent the PI re-using the wrong Intent PendingIntent pendingIntent = PendingIntent.getActivity(context, story.hashCode(), i, 0); Intent dismissIntent = new Intent(context, NotifyDismissReceiver.class); dismissIntent.putExtra(Reading.EXTRA_STORY_HASH, story.storyHash); PendingIntent dismissPendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), story.hashCode(), dismissIntent, 0); Intent saveIntent = new Intent(context, NotifySaveReceiver.class); saveIntent.putExtra(Reading.EXTRA_STORY_HASH, story.storyHash); PendingIntent savePendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), story.hashCode(), saveIntent, 0); Intent markreadIntent = new Intent(context, NotifyMarkreadReceiver.class); markreadIntent.putExtra(Reading.EXTRA_STORY_HASH, story.storyHash); PendingIntent markreadPendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), story.hashCode(), markreadIntent, 0); String feedTitle = cursor.getString(cursor.getColumnIndex(DatabaseConstants.FEED_TITLE)); StringBuilder title = new StringBuilder(); title.append(feedTitle).append(": ").append(story.title); String faviconUrl = cursor.getString(cursor.getColumnIndex(DatabaseConstants.FEED_FAVICON_URL)); Bitmap feedIcon = ImageLoader.getCachedImageSynchro(iconCache, faviconUrl); Notification.Builder nb = new Notification.Builder(context) .setContentTitle(title.toString()) .setContentText(story.shortContent) .setSmallIcon(R.drawable.logo_monochrome) .setContentIntent(pendingIntent) .setDeleteIntent(dismissPendingIntent) .setAutoCancel(true) .setWhen(story.timestamp) .addAction(0, "Save", savePendingIntent) .addAction(0, "Mark Read", markreadPendingIntent); if (feedIcon != null) { nb.setLargeIcon(feedIcon); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { nb.setColor(NOTIFY_COLOUR); } return nb.build(); } public static void clear(Context context) { NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); nm.cancelAll(); } public static void cancel(Context context, int nid) { NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); nm.cancel(nid); } }
package com.prairie.eevernote.ui; import java.util.Arrays; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.fieldassist.SimpleContentProposalProvider; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import com.prairie.eevernote.Constants; import com.prairie.eevernote.EEProperties; import com.prairie.eevernote.client.EEClipper; import com.prairie.eevernote.client.EEClipperFactory; import com.prairie.eevernote.client.ENNote; import com.prairie.eevernote.client.impl.ENNoteImpl; import com.prairie.eevernote.exception.ThrowableHandler; import com.prairie.eevernote.util.ConstantsUtil; import com.prairie.eevernote.util.EclipseUtil; import com.prairie.eevernote.util.IDialogSettingsUtil; import com.prairie.eevernote.util.ListUtil; import com.prairie.eevernote.util.MapUtil; import com.prairie.eevernote.util.StringUtil; public class HotTextDialog extends Dialog implements ConstantsUtil, Constants { public static final int SHOULD_NOT_SHOW = EECLIPPERPLUGIN_HOTINPUTDIALOG_SHOULD_NOT_SHOW_ID; private final Shell shell; private static HotTextDialog thisDialog; private EEClipper clipper; private Map<String, String> notebooks; // <Name, Guid> private Map<String, String> notes; // <Name, Guid> private List<String> tags; private SimpleContentProposalProvider noteProposalProvider; private Map<String, Text> fields; private ENNote quickSettings; // <Field Property, <Field Property, Field Value>> private Map<String, Map<String, String>> matrix; private boolean fatal = false;// TODO may remove public HotTextDialog(final Shell parentShell) { super(parentShell); shell = parentShell; notebooks = MapUtil.map(); notes = MapUtil.map(); tags = ListUtil.list(); clipper = EEClipperFactory.getInstance().getEEClipper(); } @Override protected void configureShell(final Shell newShell) { super.configureShell(newShell); newShell.setText(EEProperties.getProperties().getProperty(EECLIPPERPLUGIN_HOTINPUTDIALOG_SHELL_TITLE)); } @Override protected void setShellStyle(final int newShellStyle) { super.setShellStyle(newShellStyle | SWT.RESIZE); } @Override protected Control createDialogArea(final Composite parent) { Composite area = (Composite) super.createDialogArea(parent); Composite container = new Composite(area, SWT.NONE); // container.setLayoutData(new GridData(GridData.FILL_BOTH)); container.setLayout(new GridLayout(2, false)); container.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false)); if (shouldShow(SETTINGS_SECTION_NOTEBOOK, SETTINGS_KEY_GUID)) { Text notebookField = createLabelTextField(container, EECLIPPERPLUGIN_CONFIGURATIONS_NOTEBOOK); addField(EECLIPPERPLUGIN_CONFIGURATIONS_NOTEBOOK, notebookField); try { new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor monitor) { monitor.beginTask("Fetching notebooks...", IProgressMonitor.UNKNOWN); try { notebooks = clipper.listNotebooks(); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e); } monitor.done(); } }); EclipseUtil.enableFilteringContentAssist(notebookField, notebooks.keySet().toArray(new String[notebooks.size()])); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e); } } if (shouldShow(SETTINGS_SECTION_NOTE, SETTINGS_KEY_GUID)) { Text noteField = createLabelTextField(container, EECLIPPERPLUGIN_CONFIGURATIONS_NOTE); addField(EECLIPPERPLUGIN_CONFIGURATIONS_NOTE, noteField); final String notebook = getFieldValue(EECLIPPERPLUGIN_CONFIGURATIONS_NOTEBOOK); try { new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor monitor) { monitor.beginTask("Fetching notes...", IProgressMonitor.UNKNOWN); try { notes = clipper.listNotesWithinNotebook(ENNoteImpl.forNotebookGuid(IDialogSettingsUtil.getBoolean(SETTINGS_SECTION_NOTEBOOK, SETTINGS_KEY_CHECKED) ? IDialogSettingsUtil.get(SETTINGS_SECTION_NOTEBOOK, SETTINGS_KEY_GUID) : notebooks.get(notebook))); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e); } monitor.done(); } }); noteProposalProvider = EclipseUtil.enableFilteringContentAssist(noteField, notes.keySet().toArray(new String[notes.size()])); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e); } if (IDialogSettingsUtil.getBoolean(SETTINGS_SECTION_NOTEBOOK, SETTINGS_KEY_CHECKED)) { noteField.addFocusListener(new FocusAdapter() { @Override public void focusGained(final FocusEvent e) { if (shouldRefresh(EECLIPPERPLUGIN_CONFIGURATIONS_NOTE, EECLIPPERPLUGIN_CONFIGURATIONS_NOTEBOOK)) { final String hotebook = getFieldValue(EECLIPPERPLUGIN_CONFIGURATIONS_NOTEBOOK); BusyIndicator.showWhile(Display.getDefault(), new Runnable() { @Override public void run() { try { notes = clipper.listNotesWithinNotebook(ENNoteImpl.forNotebookGuid(notebooks.get(hotebook))); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e); } } }); String[] ns = notes.keySet().toArray(new String[notes.size()]); Arrays.sort(ns); noteProposalProvider.setProposals(ns); } } }); } } if (shouldShow(SETTINGS_SECTION_TAGS, SETTINGS_KEY_NAME)) { Text tagsField = createLabelTextField(container, EECLIPPERPLUGIN_CONFIGURATIONS_TAGS); addField(EECLIPPERPLUGIN_CONFIGURATIONS_TAGS, tagsField); try { new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor monitor) { monitor.beginTask("Fetching tags...", IProgressMonitor.UNKNOWN); try { tags = clipper.listTags(); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e); } monitor.done(); } }); EclipseUtil.enableFilteringContentAssist(tagsField, tags.toArray(new String[tags.size()]), TAGS_SEPARATOR); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e); } } if (shouldShow(SETTINGS_SECTION_COMMENTS, SETTINGS_KEY_NAME)) { addField(EECLIPPERPLUGIN_CONFIGURATIONS_COMMENTS, createLabelTextField(container, EECLIPPERPLUGIN_CONFIGURATIONS_COMMENTS)); } return container; } private void authInProgress() { try { new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor monitor) { monitor.beginTask("Authenticating...", IProgressMonitor.UNKNOWN); try { clipper = EEClipperFactory.getInstance().getEEClipper(IDialogSettingsUtil.get(SETTINGS_KEY_TOKEN), false); } catch (Throwable e) { fatal = true; ThrowableHandler.handleDesignTimeErr(shell, e, true); } monitor.done(); } }); } catch (Throwable e) { fatal = true; ThrowableHandler.handleDesignTimeErr(shell, e, true); } } @Override protected void createButtonsForButtonBar(final Composite parent) { createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } @Override protected Point getInitialSize() { return new Point(450, 200); } @Override protected void okPressed() { saveQuickSettings(); if (!confirmDefault()) { return; } super.okPressed(); } private boolean confirmDefault() { boolean confirm = false; String msg = StringUtils.EMPTY; if (shouldShow(SETTINGS_SECTION_NOTE, SETTINGS_KEY_GUID) && StringUtils.isBlank(quickSettings.getGuid())) { msg = "No existing note found, will create a new one" + (StringUtils.isBlank(quickSettings.getName()) ? StringUtils.EMPTY : " with given name " + quickSettings.getName()) + "."; confirm = true; } else if (shouldShow(SETTINGS_SECTION_NOTEBOOK, SETTINGS_KEY_GUID) && StringUtils.isBlank(quickSettings.getNotebook().getGuid())) { msg = "No existing notebook found, will clip to default."; confirm = true; } return confirm ? MessageDialog.openQuestion(shell, EEProperties.getProperties().getProperty(EECLIPPERPLUGIN_HOTINPUTDIALOG_SHELL_TITLE), msg) : true; } private void saveQuickSettings() { quickSettings = new ENNoteImpl(); quickSettings.getNotebook().setName(getFieldValue(EECLIPPERPLUGIN_CONFIGURATIONS_NOTEBOOK)); quickSettings.getNotebook().setGuid(notebooks.get(getFieldValue(EECLIPPERPLUGIN_CONFIGURATIONS_NOTEBOOK))); quickSettings.setName(getFieldValue(EECLIPPERPLUGIN_CONFIGURATIONS_NOTE)); quickSettings.setGuid(notes.get(getFieldValue(EECLIPPERPLUGIN_CONFIGURATIONS_NOTE))); String tags = getFieldValue(EECLIPPERPLUGIN_CONFIGURATIONS_TAGS); if (!StringUtils.isBlank(tags)) { quickSettings.setTags(ListUtil.toList(tags.split(ConstantsUtil.TAGS_SEPARATOR))); } quickSettings.setComments(getFieldValue(EECLIPPERPLUGIN_CONFIGURATIONS_COMMENTS)); } public ENNote getQuickSettings() { return quickSettings; } private boolean shouldRefresh(final String uniqueKey, final String property) { return fieldValueChanged(uniqueKey, property); } private boolean fieldValueChanged(final String uniqueKey, final String property) { if (matrix == null) { matrix = MapUtil.map(); } Map<String, String> map = matrix.get(uniqueKey); if (map == null) { map = MapUtil.map(); matrix.put(uniqueKey, map); } if (!StringUtil.equalsInLogic(getFieldValue(property), map.get(property))) { map.put(property, getFieldValue(property)); return true; } return false; } public static int show(final Shell shell) { if (shouldShow()) { thisDialog = new HotTextDialog(shell); thisDialog.authInProgress(); return thisDialog.fatal ? CANCEL : thisDialog.open(); } return HotTextDialog.SHOULD_NOT_SHOW; } protected static boolean shouldShow() { return shouldShow(SETTINGS_SECTION_NOTEBOOK, SETTINGS_KEY_GUID) || shouldShow(SETTINGS_SECTION_NOTE, SETTINGS_KEY_GUID) || shouldShow(SETTINGS_SECTION_TAGS, SETTINGS_KEY_NAME) || shouldShow(SETTINGS_SECTION_COMMENTS, SETTINGS_KEY_NAME); } private static boolean shouldShow(final String property, final String key) { if (property.equals(SETTINGS_SECTION_NOTEBOOK)) { if (IDialogSettingsUtil.getBoolean(SETTINGS_SECTION_NOTE, SETTINGS_KEY_CHECKED) && !shouldShow(SETTINGS_SECTION_NOTE, key)) { return false; } } boolean checked = IDialogSettingsUtil.getBoolean(property, SETTINGS_KEY_CHECKED); String value = IDialogSettingsUtil.get(property, key); return checked && StringUtils.isBlank(value); } protected Text createLabelTextField(final Composite container, final String labelText) { Label label = new Label(container, SWT.NONE); label.setText(EEProperties.getProperties().getProperty(labelText) + COLON); Text text = new Text(container, SWT.BORDER); text.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false)); return text; } protected String getFieldValue(final String property) { Text text = (Text) getField(property); if (text == null) { return null; } return text.getText().trim(); } protected Control getField(final String property) { if (fields == null) { return null; } return fields.get(property); } protected void addField(final String key, final Text value) { if (fields == null) { fields = MapUtil.map(); } fields.put(key, value); } public static HotTextDialog getThis() { return thisDialog; } }
package elki.gui; import java.awt.AWTError; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; import elki.logging.Logging; /** * GUI utilities. * * @author Erich Schubert * @since 0.5.5 */ public final class GUIUtil { /** * Whether to prefer the GTK look and feel on Unix. */ public static final boolean PREFER_GTK = true; /** * Fake constructor. Do not instantiate. */ private GUIUtil() { // Static methods only - do not instantiate } /** * Setup look at feel. */ public static void setLookAndFeel() { try { if(PREFER_GTK) { LookAndFeelInfo[] lfs = UIManager.getInstalledLookAndFeels(); for(LookAndFeelInfo lf : lfs) { if(lf.getClassName().contains("GTK")) { UIManager.setLookAndFeel(lf.getClassName()); return; } } } // Fallback: UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception | AWTError e) { // ignore } } /** * Setup logging of uncaught exceptions. * * @param logger logger */ public static void logUncaughtExceptions(Logging logger) { try { Thread.setDefaultUncaughtExceptionHandler((t, e) -> logger.exception(e)); } catch(SecurityException e) { logger.warning("Could not set the Default Uncaught Exception Handler", e); } } }
package com.intellij.compiler.classParsing; import com.intellij.openapi.compiler.CompilerBundle; import java.text.CharacterIterator; public class SignatureParser { public static final SignatureParser INSTANCE = new SignatureParser(); public void parseIdentifier(CharacterIterator it, final StringBuffer buf) { while (Character.isJavaIdentifierPart(it.current())) { buf.append(it.current()); it.next(); } } public void parseFormalTypeParameters(CharacterIterator it, final StringBuffer buf) throws SignatureParsingException { if (it.current() != '<') { throw new SignatureParsingException(CompilerBundle.message("error.signature.parsing.expected.other.symbol", "<", buf.toString())); } buf.append(it.current()); // skip '<' it.next(); while (it.current() != '>') { parseFormalTypeParameter(it, buf); } buf.append(it.current()); it.next(); } public void parseFormalTypeParameter(CharacterIterator it, final StringBuffer buf) throws SignatureParsingException { parseIdentifier(it, buf); parseClassBound(it, buf); while (it.current() == ':') { parseInterfaceBound(it, buf); } } public void parseClassBound(CharacterIterator it, final StringBuffer buf) throws SignatureParsingException { if (it.current() != ':') { throw new SignatureParsingException(CompilerBundle.message("error.signature.parsing.expected.other.symbol", ":", buf.toString())); } buf.append(it.current()); it.next(); final char current = it.current(); if (current != CharacterIterator.DONE && current != ':') { parseFieldTypeSignature(it, buf); } } public void parseInterfaceBound(CharacterIterator it, final StringBuffer buf) throws SignatureParsingException { if (it.current() != ':') { throw new SignatureParsingException(CompilerBundle.message("error.signature.parsing.expected.other.symbol", ":", buf.toString())); } buf.append(it.current()); it.next(); parseFieldTypeSignature(it, buf); } public void parseSuperclassSignature(CharacterIterator it, final StringBuffer buf) throws SignatureParsingException { parseClassTypeSignature(it, buf); } public void parseSuperinterfaceSignature(CharacterIterator it, final StringBuffer buf) throws SignatureParsingException { parseClassTypeSignature(it, buf); } public void parseFieldTypeSignature(CharacterIterator it, final StringBuffer buf) throws SignatureParsingException { if (it.current() == 'L') { parseClassTypeSignature(it, buf); } else if (it.current() == '[') { parseArrayTypeSignature(it, buf); } else if (it.current() == 'T') { parseTypeVariableSignature(it, buf); } else { //noinspection HardCodedStringLiteral throw new SignatureParsingException(CompilerBundle.message("error.signature.parsing.expected.other.symbol", "'L' / '[' / 'T'", buf.toString())); } } public void parseClassTypeSignature(CharacterIterator it, final StringBuffer buf) throws SignatureParsingException { buf.append(it.current()); it.next(); // consume 'L' parseSimpleClassTypeSignature(it, buf); while (it.current() == '/') { parseClassTypeSignatureSuffix(it, buf); } if (it.current() != ';') { throw new SignatureParsingException(CompilerBundle.message("error.signature.parsing.expected.other.symbol", ";", buf.toString())); } buf.append(it.current()); it.next(); // consume ';' } public void parseSimpleClassTypeSignature(CharacterIterator it, final StringBuffer buf) throws SignatureParsingException { parseIdentifier(it, buf); if (it.current() == '<') { parseTypeArguments(it, buf); } } public void parseClassTypeSignatureSuffix(CharacterIterator it, final StringBuffer buf) throws SignatureParsingException { buf.append(it.current()); it.next(); parseSimpleClassTypeSignature(it, buf); } public void parseTypeVariableSignature(CharacterIterator it, final StringBuffer buf) throws SignatureParsingException { buf.append(it.current()); it.next(); // consume 'T' parseIdentifier(it, buf); if (it.current() != ';') { throw new SignatureParsingException(CompilerBundle.message("error.signature.parsing.expected.other.symbol", ";", buf.toString())); } buf.append(it.current()); it.next(); // consume ';' } public void parseTypeArguments(CharacterIterator it, final StringBuffer buf) throws SignatureParsingException { buf.append(it.current()); it.next(); // consume '<' while (it.current() != '>') { parseTypeArgument(it, buf); } buf.append(it.current()); it.next(); // consume '>' } public void parseTypeArgument(CharacterIterator it, final StringBuffer buf) throws SignatureParsingException { if (it.current() == '*') { parseWildcardIndicator(it, buf); } else { if (it.current() == '+' || it.current() == '-') { parseWildcardIndicator(it, buf); } parseFieldTypeSignature(it, buf); } } public void parseWildcardIndicator(CharacterIterator it, final StringBuffer buf) { buf.append(it.current()); it.next(); } public void parseArrayTypeSignature(CharacterIterator it, final StringBuffer buf) throws SignatureParsingException { buf.append(it.current()); it.next(); // consume '[' parseTypeSignature(it, buf); } public void parseTypeSignature(CharacterIterator it, final StringBuffer buf) throws SignatureParsingException { char current = it.current(); if (current == 'B' || current == 'C' || current == 'D' || current == 'F' || current == 'I' || current == 'J' || current == 'S' || current == 'Z') { buf.append(it.current()); it.next(); // base type } else if (current == 'L' || current == '[' || current == 'T') { parseFieldTypeSignature(it, buf); } else { throw new SignatureParsingException(CompilerBundle.message("error.signature.parsing.unknown.type.signature")); } } public void parseReturnType(CharacterIterator it, final StringBuffer buf) throws SignatureParsingException { if (it.current() == 'V') { buf.append(it.current()); it.next(); } else { parseTypeSignature(it, buf); } } public void parseThrowsSignature(CharacterIterator it, final StringBuffer buf) throws SignatureParsingException { if (it.current() != '^') { throw new SignatureParsingException(CompilerBundle.message("error.signature.parsing.expected.other.symbol", "^", buf.toString())); } buf.append(it.current()); it.next(); if (it.current() == 'T') { parseTypeVariableSignature(it, buf); } else { parseClassTypeSignature(it, buf); } } public void parseMethodSignature(CharacterIterator it, final StringBuffer buf) throws SignatureParsingException { if (it.current() == '<') { parseFormalTypeParameters(it, buf); } if (it.current() != '(') { throw new SignatureParsingException(CompilerBundle.message("error.signature.parsing.expected.other.symbol", "(", buf.toString())); } buf.append(it.current()); it.next(); // skip '(' while (it.current() != ')') { parseTypeSignature(it, buf); } buf.append(it.current()); it.next(); // skip ')' parseReturnType(it, buf); if (it.current() != CharacterIterator.DONE) { parseThrowsSignature(it, buf); } } public void parseClassSignature(CharacterIterator it, final StringBuffer buf) throws SignatureParsingException { if (it.current() == '<') { buf.append(it.current()); it.next(); while (it.current() != '>') { parseFormalTypeParameter(it, buf); } buf.append(it.current()); it.next(); } parseClassTypeSignature(it, buf); while (it.current() != CharacterIterator.DONE) { parseClassTypeSignature(it, buf); } } }
package org.intermine.web; import java.util.Collections; import java.util.HashSet; import java.util.Set; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.StringWriter; import java.io.PrintWriter; import org.apache.struts.Globals; import org.apache.struts.action.ActionMessages; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionErrors; import org.apache.log4j.Logger; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.ObjectStoreQueryDurationException; import org.intermine.objectstore.query.Query; import org.intermine.web.results.PagedResults; import org.intermine.web.results.TableHelper; /** * Business logic that interacts with session data. These methods are generally * called by actions to perform business logic. Obviously, a lot of the business * logic happens in other parts of intermine, called from here, then the users * session is updated accordingly. * * @author Thomas Riley */ public class SessionMethods { protected static final Logger LOG = Logger.getLogger(SessionMethods.class); /** * Executes current query and sets session attributes QUERY_RESULTS and RESULTS_TABLE. If the * query fails for some reason, this method returns false and ActionErrors are set on the * request. If the parameter <code>saveQuery</code> is true then the query is * automatically saved in the user's query history and a message is added to the * request. * * @param action the current action * @param session the http session * @param request the current http request * @param saveQuery if true, query will be saved automatically * @return true if query ran successfully, false if an error occured * @throws Exception if getting results info from paged results fails */ public static boolean runQuery(InterMineAction action, HttpSession session, HttpServletRequest request, boolean saveQuery) throws Exception { ServletContext servletContext = session.getServletContext(); Profile profile = (Profile) session.getAttribute(Constants.PROFILE); PathQuery query = (PathQuery) session.getAttribute(Constants.QUERY); ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE); PagedResults pr; try { Query q = MainHelper.makeQuery(query, profile.getSavedBags()); pr = TableHelper.makeTable(os, q, query.getView()); } catch (ObjectStoreException e) { ActionErrors errors = (ActionErrors) request.getAttribute(Globals.ERROR_KEY); if (errors == null) { errors = new ActionErrors(); request.setAttribute(Globals.ERROR_KEY, errors); } String key = (e instanceof ObjectStoreQueryDurationException) ? "errors.query.estimatetimetoolong" : "errors.query.objectstoreerror"; errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(key)); // put stack trace in the log StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); LOG.error(sw.toString()); return false; } session.setAttribute(Constants.QUERY_RESULTS, pr); session.setAttribute(Constants.RESULTS_TABLE, pr); if (saveQuery) { String queryName = SaveQueryHelper.findNewQueryName(profile.getSavedQueries()); query.setInfo(pr.getResultsInfo()); saveQuery(request, queryName, query); action.recordMessage(new ActionMessage("saveQuery.message", queryName), request); } return true; } /** * Load a query into the session, cloning to avoid modifying the original * @param query the query * @param session the session */ public static void loadQuery(PathQuery query, HttpSession session) { session.setAttribute(Constants.QUERY, query.clone()); //at the moment we can only load queries that have saved using the webapp //this is because the webapp satisfies our (dumb) assumption that the view list is not empty String path = (String) query.getView().iterator().next(); if (path.indexOf(".") != -1) { path = path.substring(0, path.indexOf(".")); } session.setAttribute("path", path); session.removeAttribute("prefix"); } /** * Save a query in the Map on the session, and clone it to allow further editing * @param request The HTTP request we are processing * @param queryName the name to save the query under * @param query the PathQuery */ public static void saveQuery(HttpServletRequest request, String queryName, PathQuery query) { HttpSession session = request.getSession(); Profile profile = (Profile) session.getAttribute(Constants.PROFILE); profile.saveQuery(queryName, query); session.setAttribute(Constants.QUERY, query.clone()); } /** * Record a message that will be stored in the session until it is displayed to * the user. This allows actions that result in a redirect to display * messages to the user after the redirect. Messages are stored in a Collection * session attribute so you may call this method multiple times to display * multiple messages.<p> * * <code>recordMessage</code> and <code>recordError</code> are used by * <code>InterMineRequestProcessor.processForwardConfig</code> to store errors * and messages in the session when a redirecting forward is about to occur. * * @param session The Session object in which to store the message * @param message The message to store * @see InterMineRequestProcessor#processForwardConfig */ public static void recordMessage(String message, HttpSession session) { recordMessage(message, Constants.MESSAGES, session); } /** * @see SessionMethods#recordMessage */ public static void recordError(String error, HttpSession session) { recordMessage(error, Constants.ERRORS, session); } /** * Record a message that will be stored in the session until it is displayed to * the user. This allows actions that result in a redirect to display * message to the user after the redirect. Messages are stored in a Set * session attribute so you may call this method multiple times to display * multiple errors. Identical errors will be ignored.<p> * * The <code>attrib</code> parameter specifies the name of the session attribute * used to store the set of messages. * * @param session The Session object in which to store the message * @param attrib The name of the session attribute in which to store message * @param message The message to store */ private static void recordMessage(String message, String attrib, HttpSession session) { Set set = (Set) session.getAttribute(attrib); if (set == null) { set = Collections.synchronizedSet(new HashSet()); session.setAttribute(attrib, set); } set.add(message); } }
package org.flymine.web.results; /** * Configuration information for a column in a table * * @author Andrew Varley */ public class Column { protected boolean visible = true; protected String alias = ""; protected int index; /** * Is the column visible * * @return true if the column is visible */ public boolean isVisible() { return visible; } /** * Set the visibility of the column * * @param visible true if visible, false if not */ public void setVisible(boolean visible) { this.visible = visible; } /** * Get the alias of the column * * @return the alias of the column */ public String getAlias() { return alias; } /** * Set the alias of the column * * @param alias the alias for the column */ public void setAlias(String alias) { this.alias = alias; } /** * Get the index of the column. This is the index that we use in a * call to the get() method of a ResultsRow. * * @return the index of the column */ public int getIndex() { return index; } /** * Set the index of the column * * @param index the index for the column */ public void setIndex(int index) { this.index = index; } /** * @see Object#equals * * @param other the object to compare with * @return true if the objects are equal */ public boolean equals(Object other) { if (other instanceof Column) { return alias.equals(((Column) other).getAlias()); } return false; } /** * @see Object#hashCode * * @return a hashCode for this column */ public int hashCode() { return alias.hashCode(); } }
package edu.colorado.csdms.wmt.client.ui; import com.google.gwt.core.shared.GWT; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.TextBox; import edu.colorado.csdms.wmt.client.data.ParameterJSO; /** * Used to display the value of a parameter in a {@link ParameterTable}, a * ValueCell renders as a ListBox (droplist) if the parameter type = "choice" * or "file"; otherwise, it renders as an editable TextBox. Changes to the * value in a ValueCell are stored in the WMT DataManager. * * @author Mark Piper (mark.piper@colorado.edu) */ public class ValueCell extends HorizontalPanel { private ParameterJSO parameter; /** * Makes a ValueCell from the information contained in the input * {@link ParameterJSO} object. * * @param parameter a ParameterJSO object */ public ValueCell(ParameterJSO parameter) { this.parameter = parameter; // If the parameter is a separator, short-circuit the method and return. if (this.parameter.getKey().matches("separator")) { return; } // Helpful locals. String type = this.parameter.getValue().getType(); String value = this.parameter.getValue().getDefault(); String range = ""; // Match the type -- choice, file or other. if (type.matches("choice")) { ListBox choiceDroplist = new ListBox(false); // no multi select choiceDroplist.addChangeHandler(new ListSelectionHandler()); Integer nChoices = this.parameter.getValue().getChoices().length(); for (int i = 0; i < nChoices; i++) { choiceDroplist.addItem(this.parameter.getValue().getChoices().get(i)); if (choiceDroplist.getItemText(i).matches(value)) { choiceDroplist.setSelectedIndex(i); } } choiceDroplist.setVisibleItemCount(1); // show one item -- a droplist this.add(choiceDroplist); } else if (type.matches("file")) { ListBox fileDroplist = new ListBox(false); // no multi select fileDroplist.addChangeHandler(new ListSelectionHandler()); Integer nFiles = this.parameter.getValue().getFiles().length(); for (int i = 0; i < nFiles; i++) { fileDroplist.addItem(this.parameter.getValue().getFiles().get(i)); if (fileDroplist.getItemText(i).matches(value)) { fileDroplist.setSelectedIndex(i); } } fileDroplist.setVisibleItemCount(1); // show one item -- a droplist this.add(fileDroplist); Button uploadButton = new Button("<i class='fa fa-cloud-upload'></i>"); uploadButton.addClickHandler(new UploadHandler()); uploadButton.setTitle("Upload file to server"); this.add(uploadButton); this.setCellVerticalAlignment(fileDroplist, ALIGN_MIDDLE); uploadButton.getElement().getStyle().setMarginLeft(3, Unit.PX); } else { TextBox valueTextBox = new TextBox(); valueTextBox.addKeyUpHandler(new TextEditHandler()); valueTextBox.setText(value); valueTextBox.getElement().getStyle().setBackgroundColor("#ffc"); this.add(valueTextBox); } // If appropriate, add a tooltip showing the valid range of the value. if (!type.matches("string") && !type.matches("choice")) { range += "Valid range = ( " + parameter.getValue().getMin() + ", " + parameter.getValue().getMax() + " )"; this.setTitle(range); } } /** * Passes the modified value up to * {@link ParameterTable#setValue(ParameterJSO, String)}. This isn't an * elegant solution, but ParameterTable knows the component this parameter * belongs to and it has access to the DataManager object for storage. * * @param value */ public void setValue(String value) { ParameterTable pt = (ParameterTable) ValueCell.this.getParent(); pt.setValue(parameter, value); } /** * A class to handle selection in the "choices" ListBox. */ public class ListSelectionHandler implements ChangeHandler { @Override public void onChange(ChangeEvent event) { GWT.log("(onChange)"); ListBox listBox = (ListBox) event.getSource(); String value = listBox.getValue(listBox.getSelectedIndex()); setValue(value); } } /** * A class to handle keyboard events in the TextBox -- every key press, so * there could be many. Might consider acting on only Tab or Enter. */ public class TextEditHandler implements KeyUpHandler { @Override public void onKeyUp(KeyUpEvent event) { GWT.log("(onKeyUp)"); TextBox textBox = (TextBox) event.getSource(); String value = textBox.getText(); setValue(value); } } /** * A class to handle selection in the "files" ListBox. */ public class UploadHandler implements ClickHandler { @Override public void onClick(ClickEvent event) { Window.alert("Upload"); } } }
package hex.word2vec; import hex.*; import hex.word2vec.Word2VecModel.*; import hex.schemas.Word2VecModelV2; import hex.word2vec.Word2VecModel.Word2VecParameters; import water.*; import water.api.ModelSchema; import water.fvec.Chunk; import water.fvec.Frame; import water.fvec.NewChunk; import water.fvec.AppendableVec; import water.fvec.Vec; import water.nbhm.NonBlockingHashMap; import water.parser.ValueString; import water.util.ArrayUtils; import water.util.Log; import java.util.Arrays; import java.util.Random; public class Word2VecModel extends Model<Word2VecModel, Word2VecParameters, Word2VecOutput> { private volatile Word2VecModelInfo _modelInfo; void setModelInfo(Word2VecModelInfo mi) { _modelInfo = mi; } final public Word2VecModelInfo getModelInfo() { return _modelInfo; } private Key _w2vKey; private long run_time; private long start_time; public long actual_train_samples_per_iteration; public double time_for_communication_us; //helper for auto-tuning: time in microseconds for collective bcast/reduce of the model public double epoch_counter; public long training_rows; public long validation_rows; public Word2VecModel(final Key selfKey, Frame fr, final Word2VecParameters params) { super(selfKey, fr, params, new Word2VecOutput()); run_time = 0; start_time = System.currentTimeMillis(); _modelInfo = new Word2VecModelInfo(params); assert(Arrays.equals(_key._kb, selfKey._kb)); } @Override public boolean isSupervised() {return false;} // Default publicly visible Schema is V2 @Override public ModelSchema schema() { return new Word2VecModelV2(); } @Override protected float[] score0(Chunk[] cs, int foo, double data[/*ncols*/], float preds[/*nclasses+1*/]) { throw H2O.unimpl(); } @Override protected float[] score0(double data[/*ncols*/], float preds[/*nclasses+1*/]) { throw H2O.unimpl(); } /** * Takes an input string can return the word vector for that word. * * @param target - String of desired word * @return float array containing the word vector values or null if * the word isn't present in the vocabulary. */ public float[] transform(String target) { NonBlockingHashMap<ValueString, Integer> vocabHM = buildVocabHashMap(); Vec[] vs = ((Frame) _w2vKey.get()).vecs(); ValueString tmp = new ValueString(target); return transform(tmp, vocabHM, vs); } private float[] transform(ValueString tmp, NonBlockingHashMap<ValueString, Integer> vocabHM, Vec[] vs) { final int vecSize = vs.length-1; float[] vec = new float[vecSize]; if (!vocabHM.containsKey(tmp)) { Log.warn("Target word " + tmp + " isn't in vocabulary."); return null; } int row = vocabHM.get(tmp); for(int i=0; i < vecSize; i++) vec[i] = (float) vs[i+1].at(row); return vec; } /** * Find synonyms (i.e. wordvectors with the * highest cosine similarity) of the supplied * String and print them to stdout. * * @param target String of desired word * @param cnt Number of synonyms to find */ public void findSynonyms(String target, int cnt) { if (cnt > 0) { NonBlockingHashMap<ValueString, Integer> vocabHM = buildVocabHashMap(); Vec[] vs = ((Frame) _w2vKey.get()).vecs(); ValueString tmp = new ValueString(target); float[] tarVec = transform(tmp, vocabHM, vs); findSynonyms(tarVec, cnt, vs); } else Log.err("Synonym count must be greater than 0."); } /** * Find synonyms (i.e. wordvectors with the * highest cosine similarity) of the word vector * for a word. * * @param tarVec word vector of a word * @param cnt number of synonyms to find * */ public void findSynonyms(float[] tarVec, int cnt) { if (cnt > 0) { Vec[] vs = ((Frame) _w2vKey.get()).vecs(); findSynonyms(tarVec, cnt, vs); } else Log.err("Synonym count must be greater than 0."); } private void findSynonyms(float[] tarVec, int cnt, Vec[] vs) { final int vecSize= vs.length - 1, vocabSize = (int) vs[0].length(); int[] matches = new int[cnt]; float [] scores = new float[cnt]; float[] curVec = new float[vecSize]; if (tarVec.length != vs.length-1) { Log.warn("Target vector length differs from the vocab's vector length."); return; } for (int i=0; i < vocabSize; i++) { for(int j=0; j < vecSize; j++) curVec[j] = (float) vs[j+1].at(i); float score = cosineSimilarity(tarVec, curVec); for (int j = 0; j < cnt; j++) { if (score > scores[j] && score < 0.999999) { for (int k = cnt - 1; k > j; k scores[k] = scores[k - 1]; matches[k] = matches[k-1]; } scores[j] = score; matches[j] = i; break; } } } for (int i=0; i < cnt; i++) System.out.println(vs[0].atStr(new ValueString(), matches[i]) + " " + scores[i]); } /** * Basic calculation of cosine similarity * @param target - a word vector * @param current - a word vector * @return cosine similarity between the two word vectors */ public float cosineSimilarity(float[] target, float[] current) { float dotProd = 0, tsqr = 0, csqr = 0; for(int i=0; i< target.length; i++) { dotProd += target[i] * current[i]; tsqr += Math.pow(target[i],2); csqr += Math.pow(current[i],2); } return (float) (dotProd / (Math.sqrt(tsqr)*Math.sqrt(csqr))); } /** * Hashmap for quick lookup of a word's row number. */ private NonBlockingHashMap<ValueString, Integer> buildVocabHashMap() { NonBlockingHashMap<ValueString, Integer> vocabHM; Vec word = ((Frame) _w2vKey.get()).vec(0); final int vocabSize = (int) ((Frame) _w2vKey.get()).numRows(); vocabHM = new NonBlockingHashMap<>(vocabSize); for(int i=0; i < vocabSize; i++) vocabHM.put(word.atStr(new ValueString(),i),i); return vocabHM; } public void buildModelOutput() { final int vecSize = _parms._vecSize; Futures fs = new Futures(); String[] colNames = new String[vecSize]; Vec[] vecs = new Vec[vecSize]; Key keys[] = Vec.VectorGroup.VG_LEN1.addVecs(vecs.length); //allocate NewChunk cs[] = new NewChunk[vecs.length]; AppendableVec avs[] = new AppendableVec[vecs.length]; for (int i = 0; i < vecs.length; i++) { avs[i] = new AppendableVec(keys[i]); cs[i] = new NewChunk(avs[i], 0); } //fill in vector values for( int i = 0; i < _modelInfo._vocabSize; i++ ) { for (int j=0; j < vecSize; j++) { cs[j].addNum(_modelInfo._syn0[i * vecSize + j]); } } //finalize vectors for (int i = 0; i < vecs.length; i++) { colNames[i] = new String("V"+i); cs[i].close(0, fs); vecs[i] = avs[i].close(fs); } fs.blockForPending(); Frame fr = new Frame(_w2vKey = Key.make("w2v")); //FIXME this ties the word count frame to this one which makes cleanup messy fr.add("Word", ((Frame) _parms._vocabKey.get()).vec(0)); fr.add(colNames, vecs); DKV.put(_w2vKey, fr); } @Override public void delete() { _parms._vocabKey.remove(); _w2vKey.remove(); remove(); super.delete(); } public static class Word2VecParameters extends Model.Parameters { static final int MAX_VEC_SIZE = 10000; Word2Vec.WordModel _wordModel; Word2Vec.NormModel _normModel; Key _vocabKey; int _minWordFreq, _vecSize, _windowSize, _epochs, _negSampleCnt; float _initLearningRate, _sentSampleRate; @Override public int sanityCheckParameters() { if (_vecSize > MAX_VEC_SIZE) validation_error("vecSize", "Requested vector size of "+_vecSize+" in Word2Vec, exceeds limit of "+MAX_VEC_SIZE+"."); if (_vecSize < 1) validation_error("vecSize", "Requested vector size of "+_vecSize+" in Word2Vec, is not allowed."); if (_windowSize < 1) validation_error("windowSize", "Negative window size not allowed for Word2Vec. Expected value > 0, received "+_windowSize); if (_sentSampleRate < 0.0) validation_error("sentSampleRate", "Negative sentence sample rate not allowed for Word2Vec. Expected a value > 0.0, received "+_sentSampleRate); if (_initLearningRate < 0.0) validation_error("initLearningRate", "Negative learning rate not allowed for Word2Vec. Expected a value > 0.0, received "+ _initLearningRate); if (_epochs < 1) validation_error("epochs", "Negative epoch count not allowed for Word2Vec. Expected value > 0, received "+_epochs); return _validation_error_count; } } public static class Word2VecOutput extends Model.Output{ } public static class Word2VecModelInfo extends Iced { static final int UNIGRAM_TABLE_SIZE = 10000000; static final float UNIGRAM_POWER = 0.75F; static final int MAX_CODE_LENGTH = 40; long _trainFrameSize; int _vocabSize; float _curLearningRate; float[] _syn0, _syn1; int[] _uniTable = null; int[][] _HBWTCode = null; int[][] _HBWTPoint = null; private Word2VecParameters _parameters; public final Word2VecParameters getParams() { return _parameters; } public Word2VecModelInfo() {} public Word2VecModelInfo(final Word2VecParameters params) { _parameters = params; if(_parameters._vocabKey == null) { _parameters._vocabKey = (new WordCountTask(_parameters._minWordFreq)).doAll(_parameters.train())._wordCountKey; } _vocabSize = (int) ((Frame) _parameters._vocabKey.get()).numRows(); _trainFrameSize = getTrainFrameSize(_parameters.train()); //initialize weights to random values Random rand = new Random(); _syn1 = new float[_parameters._vecSize * _vocabSize]; _syn0 = new float[_parameters._vecSize * _vocabSize]; for (int i = 0; i < _parameters._vecSize * _vocabSize; i++) _syn0[i] = (rand.nextFloat() - 0.5f) / _parameters._vecSize; if(_parameters._normModel == Word2Vec.NormModel.HSM) buildHuffmanBinaryWordTree(); else // NegSampling buildUnigramTable(); } /* Word2VecModelInfo deep_clone() { AutoBuffer ab = new AutoBuffer(); this.write(ab); ab.flipForReading(); return (Word2VecModelInfo) new Word2VecModelInfo().read(ab); } */ /** * Set of functions to accumulate counts of how many * words were processed so far. */ private static int _localWordCnt=0, _globalWordCnt=0; public synchronized void addLocallyProcessed(long p) { _localWordCnt += p; } public synchronized long getLocallyProcessed() { return _localWordCnt; } public synchronized void setLocallyProcessed(int p) { _localWordCnt = p; } public synchronized void addGloballyProcessed(long p) { _globalWordCnt += p; } public synchronized long getGloballyProcessed() { return _globalWordCnt; } public synchronized long getTotalProcessed() { return _globalWordCnt + _localWordCnt; } /** * Used to add together the weight vectors between * two map instances. * * @param other - parameters object from other map method */ protected void add(Word2VecModelInfo other) { ArrayUtils.add(_syn0, other._syn0); ArrayUtils.add(_syn1, other._syn1); addLocallyProcessed(other.getLocallyProcessed()); } /** * Used to reduce the summations from map methods * to an average across map/reduce threads. * * @param N - number of map/reduce threads to divide by */ protected void div(float N) { if (N > 1) { ArrayUtils.div(_syn0, N); ArrayUtils.div(_syn1, N); } } /** * Calculates a new global learning rate for the next round * of map/reduce calls. * The learning rate is a coefficient that controls the amount that * newly learned information affects current learned information. */ public void updateLearningRate() { _curLearningRate = _parameters._initLearningRate * (1 - getTotalProcessed() / (float) (_parameters._epochs * _trainFrameSize + 1)); if (_curLearningRate < _parameters._initLearningRate * 0.0001F) _curLearningRate = _parameters._initLearningRate * 0.0001F; } /** * Generates a unigram table from the [word, count] * vocab frame. The unigram table is needed for * normalizing through negative sampling. * * @return - returns a key to a vec holding the unigram table results. */ private void buildUnigramTable() { float d = 0; long vocabWordsPow = 0; _uniTable = new int[UNIGRAM_TABLE_SIZE]; Vec wCount = ((Frame)_parameters._vocabKey.get()).vec(1); for (int i=0; i < wCount.length(); i++) vocabWordsPow += Math.pow(wCount.at8(i), UNIGRAM_POWER); for (int i = 0, j =0; i < UNIGRAM_TABLE_SIZE; i++) { _uniTable[i] = j; if (i / (float) UNIGRAM_TABLE_SIZE > d) { d += Math.pow(wCount.at8(++j), UNIGRAM_POWER) / (float) vocabWordsPow; } if (j >= _vocabSize) j = _vocabSize - 1; } } /* Explored packing the unigram table into chunks for the benefit of compression. The random access nature ended up increasing the run time of a negative sampling run by ~50%. Tests without using this as a giant lookup table don't seem to fair much better. private Key buildUnigramTable() { Futures fs = new Futures(); Vec wCount, uniTblVec; AppendableVec utAV = new AppendableVec(Vec.newKey()); NewChunk utNC = null; long vocabWordsPow = 0; float d = 0; int chkIdx = 0; wCount = ((Frame)_vocabKey.get()).vec(1); for (int i=0; i < wCount.length(); i++) vocabWordsPow += Math.pow(wCount.at8(i), UNIGRAM_POWER); for (int i = 0, j =0; i < UNIGRAM_TABLE_SIZE; i++) { //allocate as needed if ((i % Vec.CHUNK_SZ) == 0){ if (utNC != null) utNC.close(chkIdx++, fs); utNC = new NewChunk(utAV, chkIdx); } utNC.addNum(j, 0); if (i / (float) UNIGRAM_TABLE_SIZE > d) { d += Math.pow(wCount.at8(++j), UNIGRAM_POWER) / (float) vocabWordsPow; } if (j >= _vocabSize) j = _vocabSize - 1; } //finalize vectors utNC.close(chkIdx, fs); uniTblVec = utAV.close(fs); fs.blockForPending(); return uniTblVec._key; } */ /** * Generates the values for a Huffman binary tree * from the [word, count] vocab frame. */ private void buildHuffmanBinaryWordTree() { int min1i, min2i, pos1, pos2; int[] point = new int[MAX_CODE_LENGTH]; int[] code = new int[MAX_CODE_LENGTH]; long[] count = new long[_vocabSize * 2 - 1]; int[] binary = new int[_vocabSize * 2 - 1]; int[] parent_node = new int[_vocabSize * 2 - 1]; Vec wCount = ((Frame) _parameters._vocabKey.get()).vec(1); _HBWTCode = new int[_vocabSize][]; _HBWTPoint = new int[_vocabSize][]; assert (_vocabSize == wCount.length()); for (int i = 0; i < _vocabSize; i++) count[i] = wCount.at8(i); for (int i = _vocabSize; i < _vocabSize * 2 - 1; i++) count[i] = (long) 1e15; pos1 = _vocabSize - 1; pos2 = _vocabSize; // Following algorithm constructs the Huffman tree by adding one node at a time for (int i = 0; i < _vocabSize - 1; i++) { // First, find two smallest nodes 'min1, min2' if (pos1 >= 0) { if (count[pos1] < count[pos2]) { min1i = pos1; pos1 } else { min1i = pos2; pos2++; } } else { min1i = pos2; pos2++; } if (pos1 >= 0) { if (count[pos1] < count[pos2]) { min2i = pos1; pos1 } else { min2i = pos2; pos2++; } } else { min2i = pos2; pos2++; } count[_vocabSize + i] = count[min1i] + count[min2i]; parent_node[min1i] = _vocabSize + i; parent_node[min2i] = _vocabSize + i; binary[min2i] = 1; } // Now assign binary code to each vocabulary word for (int j = 0; j < _vocabSize; j++) { int k = j; int m = 0; while (true) { int val = binary[k]; code[m] = val; point[m] = k; m++; k = parent_node[k]; if (k == 0) break; } _HBWTCode[j] = new int[m]; _HBWTPoint[j] = new int[m + 1]; _HBWTPoint[j][0] = _vocabSize - 2; for (int l = 0; l < m; l++) { _HBWTCode[j][m - l - 1] = code[l]; _HBWTPoint[j][m - l] = point[l] - _vocabSize; } } } /** * Calculates the number of words that Word2Vec will train on. * This is a needed parameter for correct trimming of the learning * rate in the algo. Rather that require the user to calculate it, * this finds it and adds it to the parameters object. * * @param tf - frame containing words to train on * @return count - total words in training frame */ private long getTrainFrameSize(Frame tf) { long count=0; for (Vec v: tf.vecs()) if(v.isString()) count += v.length(); return count; } } }
package io.hawt.web; import org.jolokia.converter.Converters; import org.jolokia.converter.json.JsonConvertOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.InstanceNotFoundException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.ReflectionException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.lang.management.ManagementFactory; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * @author Stan Lewis */ public class PluginServlet extends HttpServlet { private static final transient Logger LOG = LoggerFactory.getLogger(PluginServlet.class); MBeanServer mBeanServer; ObjectName pluginQuery; Converters converters = new Converters(); JsonConvertOptions options = JsonConvertOptions.DEFAULT; String attributes[] = {"Context", "Domain", "Name", "Scripts"}; @Override public void init() throws ServletException { mBeanServer = ManagementFactory.getPlatformMBeanServer(); try { pluginQuery = new ObjectName("hawtio:type=plugin,name=*"); } catch (MalformedObjectNameException e) { LOG.warn("Failed to create object name: ", e); } super.init(); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); final PrintWriter out = response.getWriter(); Set<ObjectInstance> objectInstances = mBeanServer.queryMBeans(pluginQuery, null); if (objectInstances.size() == 0) { ServletHelpers.writeEmpty(out); return; } Map<String, Map<Object, Object>> answer = new HashMap<String, Map<Object, Object>>(); for (ObjectInstance objectInstance : objectInstances) { AttributeList attributeList = null; try { attributeList = mBeanServer.getAttributes(objectInstance.getObjectName(), attributes); } catch (InstanceNotFoundException e) { LOG.warn("Object instance not found: ", e); } catch (ReflectionException e) { LOG.warn("Failed to get attribute list for " + objectInstance.getObjectName(), e); } if (attributeList != null && attributes.length == attributeList.size()) { Map<Object, Object> pluginDefinition = new HashMap<Object, Object>(); for (Attribute attribute : attributeList.asList()) { pluginDefinition.put(attribute.getName(), attribute.getValue()); } answer.put((String) pluginDefinition.get("Name"), pluginDefinition); } } ServletHelpers.writeObject(converters, options, out, answer); } }
package com.intellij.ide; import com.intellij.diagnostic.PerformanceWatcher; import com.intellij.ide.actions.MaximizeActiveDialogAction; import com.intellij.ide.dnd.DnDManager; import com.intellij.ide.dnd.DnDManagerImpl; import com.intellij.ide.plugins.MainRunner; import com.intellij.ide.ui.UISettings; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.KeyboardShortcut; import com.intellij.openapi.actionSystem.Shortcut; import com.intellij.openapi.actionSystem.impl.ActionManagerImpl; import com.intellij.openapi.application.*; import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.application.impl.LaterInvocator; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.FrequentEventDetector; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.keymap.Keymap; import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.keymap.impl.IdeKeyEventDispatcher; import com.intellij.openapi.keymap.impl.IdeMouseEventDispatcher; import com.intellij.openapi.keymap.impl.KeyState; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.ui.JBPopupMenu; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.WindowManager; import com.intellij.openapi.wm.ex.WindowManagerEx; import com.intellij.openapi.wm.impl.FocusManagerImpl; import com.intellij.ui.ComponentUtil; import com.intellij.ui.mac.touchbar.TouchBarsManager; import com.intellij.util.Alarm; import com.intellij.util.ReflectionUtil; import com.intellij.util.SystemProperties; import com.intellij.util.concurrency.NonUrgentExecutor; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.lang.JavaVersion; import com.intellij.util.ui.UIUtil; import gnu.trove.THashMap; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import sun.awt.AppContext; import sun.awt.SunToolkit; import javax.swing.*; import javax.swing.plaf.basic.ComboPopup; import java.awt.*; import java.awt.event.*; import java.lang.ref.WeakReference; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.List; import java.util.Queue; import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; public final class IdeEventQueue extends EventQueue { private static final Logger LOG = Logger.getInstance("#com.intellij.ide.IdeEventQueue"); private static final Logger TYPEAHEAD_LOG = Logger.getInstance("#com.intellij.ide.IdeEventQueue.typeahead"); private static final Logger FOCUS_AWARE_RUNNABLES_LOG = Logger.getInstance("#com.intellij.ide.IdeEventQueue.runnables"); private static final boolean JAVA11_ON_MAC = SystemInfo.isMac && SystemInfo.isJavaVersionAtLeast(11, 0, 0); private static TransactionGuardImpl ourTransactionGuard; private static ProgressManager ourProgressManager; private static PerformanceWatcher ourPerformanceWatcher; private final static LinkedHashSet<Window> activatedWindows = new LinkedHashSet<>(); private static void updateActivatedWindowSet() { for (Iterator<Window> iter = activatedWindows.iterator(); iter.hasNext(); ) { Window window = iter.next(); if (!window.isVisible()) { iter.remove(); } } assert !activatedWindows.isEmpty(); } public Window nextWindowAfter (@NotNull Window w) { updateActivatedWindowSet(); assert activatedWindows.contains(w); Window[] windows = activatedWindows.toArray(new Window[0]); if (w.equals(windows[windows.length - 1])) { return windows[0]; } for (int i = (windows.length - 2); i >= 0; i if (w.equals(windows[i])) { return windows[i + 1]; } } throw new IllegalArgumentException("The window after " + w.getName() + " has not been found"); } public Window nextWindowBefore (@NotNull Window w) { updateActivatedWindowSet(); assert activatedWindows.contains(w); Window[] windows = activatedWindows.toArray(new Window[0]); if (w.equals(windows[0])) { return windows[windows.length - 1]; } for (int i = 1; i < windows.length; i++) { if (w.equals(windows[i])) { return windows[i - 1]; } } throw new IllegalArgumentException("The window after " + w.getName() + " has not been found"); } /** * Adding/Removing of "idle" listeners should be thread safe. */ private final Object myLock = new Object(); private final List<Runnable> myIdleListeners = ContainerUtil.createLockFreeCopyOnWriteList(); private final List<Runnable> myActivityListeners = ContainerUtil.createLockFreeCopyOnWriteList(); private final Alarm myIdleRequestsAlarm = new Alarm(); private final Map<Runnable, MyFireIdleRequest> myListenerToRequest = new THashMap<>(); // IdleListener -> MyFireIdleRequest private final IdeKeyEventDispatcher myKeyEventDispatcher = new IdeKeyEventDispatcher(this); private final IdeMouseEventDispatcher myMouseEventDispatcher = new IdeMouseEventDispatcher(); private final IdePopupManager myPopupManager = new IdePopupManager(); private final ToolkitBugsProcessor myToolkitBugsProcessor = new ToolkitBugsProcessor(); /** * Counter of processed events. It is used to assert that data context lives only inside single * <p/> * Swing event. */ private int myEventCount; final AtomicInteger myKeyboardEventsPosted = new AtomicInteger(); final AtomicInteger myKeyboardEventsDispatched = new AtomicInteger(); private boolean myIsInInputEvent; @NotNull private AWTEvent myCurrentEvent = new InvocationEvent(this, EmptyRunnable.getInstance()); private volatile long myLastActiveTime = System.nanoTime(); private long myLastEventTime = System.currentTimeMillis(); private WindowManagerEx myWindowManager; private final List<EventDispatcher> myDispatchers = ContainerUtil.createLockFreeCopyOnWriteList(); private final List<EventDispatcher> myPostProcessors = ContainerUtil.createLockFreeCopyOnWriteList(); private final Set<Runnable> myReady = new THashSet<>(); private boolean myKeyboardBusy; private boolean myWinMetaPressed; private int myInputMethodLock; private final com.intellij.util.EventDispatcher<PostEventHook> myPostEventListeners = com.intellij.util.EventDispatcher.create(PostEventHook.class); private final Map<AWTEvent, List<Runnable>> myRunnablesWaitingFocusChange = new THashMap<>(); private MyLastShortcut myLastShortcut; public void executeWhenAllFocusEventsLeftTheQueue(@NotNull Runnable runnable) { ifFocusEventsInTheQueue(e -> { List<Runnable> runnables = myRunnablesWaitingFocusChange.get(e); if (runnables != null) { if (FOCUS_AWARE_RUNNABLES_LOG.isDebugEnabled()) { FOCUS_AWARE_RUNNABLES_LOG.debug("We have already had a runnable for the event: " + e); } runnables.add(runnable); } else { runnables = new ArrayList<>(); runnables.add(runnable); myRunnablesWaitingFocusChange.put(e, runnables); } }, runnable); } @NotNull public String runnablesWaitingForFocusChangeState() { return StringUtil.join(focusEventsList, event -> "[" + event.getID() + "; "+ event.getSource().getClass().getName()+"]", ", "); } private void ifFocusEventsInTheQueue(@NotNull Consumer<? super AWTEvent> yes, @NotNull Runnable no) { if (!focusEventsList.isEmpty()) { if (FOCUS_AWARE_RUNNABLES_LOG.isDebugEnabled()) { FOCUS_AWARE_RUNNABLES_LOG.debug("Focus event list (trying to execute runnable): "+runnablesWaitingForFocusChangeState()); } // find the latest focus gained AWTEvent first = ContainerUtil.find(focusEventsList, e -> e.getID() == FocusEvent.FOCUS_GAINED); if (first != null) { if (FOCUS_AWARE_RUNNABLES_LOG.isDebugEnabled()) { FOCUS_AWARE_RUNNABLES_LOG .debug(" runnable saved for : [" + first.getID() + "; " + first.getSource() + "] -> " + no.getClass().getName()); } yes.accept(first); } else { if (FOCUS_AWARE_RUNNABLES_LOG.isDebugEnabled()) { FOCUS_AWARE_RUNNABLES_LOG.debug(" runnable is run on EDT if needed : " + no.getClass().getName()); } UIUtil.invokeLaterIfNeeded(no); } } else { if (FOCUS_AWARE_RUNNABLES_LOG.isDebugEnabled()) { FOCUS_AWARE_RUNNABLES_LOG.debug("Focus event list is empty: runnable is run right away : " + no.getClass().getName()); } UIUtil.invokeLaterIfNeeded(no); } } private static class IdeEventQueueHolder { private static final IdeEventQueue INSTANCE = new IdeEventQueue(); } public static IdeEventQueue getInstance() { return IdeEventQueueHolder.INSTANCE; } private IdeEventQueue() { EventQueue systemEventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue(); assert !(systemEventQueue instanceof IdeEventQueue) : systemEventQueue; systemEventQueue.push(this); KeyboardFocusManager keyboardFocusManager = IdeKeyboardFocusManager.replaceDefault(); keyboardFocusManager.addPropertyChangeListener("permanentFocusOwner", e -> { final Application application = ApplicationManager.getApplication(); if (application == null) { // We can get focus event before application is initialized return; } application.assertIsDispatchThread(); }); addDispatcher(new WindowsAltSuppressor(), null); if (SystemInfo.isWin7OrNewer && SystemProperties.getBooleanProperty("keymap.windows.up.to.maximize.dialogs", true)) { // 'Windows+Up' shortcut would maximize active dialog under Win 7+ addDispatcher(new WindowsUpMaximizer(), null); } addDispatcher(new EditingCanceller(), null); abracadabraDaberBoreh(); IdeKeyEventDispatcher.addDumbModeWarningListener(() -> flushDelayedKeyEvents()); if (SystemProperties.getBooleanProperty("skip.move.resize.events", true)) { myPostEventListeners.addListener(IdeEventQueue::skipMoveResizeEvents); } ((IdeKeyboardFocusManager)KeyboardFocusManager.getCurrentKeyboardFocusManager()).setTypeaheadHandler(ke -> { if (myKeyEventDispatcher.dispatchKeyEvent(ke)) { ke.consume(); } }); } private static boolean skipMoveResizeEvents(AWTEvent event) { // JList, JTable and JTree paint every cell/row/column using the following method: // CellRendererPane.paintComponent(Graphics, Component, Container, int, int, int, int, boolean) // This method sets bounds to a renderer component and invokes the following internal method: // Component.notifyNewBounds // All default and simple renderers do not post specified events, // but panel-based renderers have to post events by contract. switch (event.getID()) { case ComponentEvent.COMPONENT_MOVED: case ComponentEvent.COMPONENT_RESIZED: case HierarchyEvent.ANCESTOR_MOVED: case HierarchyEvent.ANCESTOR_RESIZED: Object source = event.getSource(); if (source instanceof Component && ComponentUtil.getParentOfType((Class<? extends CellRendererPane>)CellRendererPane.class, (Component)source) != null) { return true; } } return false; } private void abracadabraDaberBoreh() { // We need to track if there are KeyBoardEvents in IdeEventQueue // So we want to intercept all events posted to IdeEventQueue and increment counters // However, the regular control flow goes like this: // PostEventQueue.flush() -> EventQueue.postEvent() -> IdeEventQueue.postEventPrivate() -> AAAA we missed event, because postEventPrivate() can't be overridden. // Instead, we do following: // - create new PostEventQueue holding our IdeEventQueue instead of old EventQueue // - replace "PostEventQueue" value in AppContext with this new PostEventQueue // After that the control flow goes like this: // PostEventQueue.flush() -> IdeEventQueue.postEvent() -> We intercepted event, incremented counters. try { Class<?> aClass = Class.forName("sun.awt.PostEventQueue"); Constructor<?> constructor = aClass.getDeclaredConstructor(EventQueue.class); constructor.setAccessible(true); Object postEventQueue = constructor.newInstance(this); AppContext.getAppContext().put("PostEventQueue", postEventQueue); } catch (Exception e) { throw new RuntimeException(e); } } public void setWindowManager(@NotNull WindowManagerEx windowManager) { myWindowManager = windowManager; } public void addIdleListener(@NotNull final Runnable runnable, final int timeoutMillis) { if (timeoutMillis <= 0 || TimeUnit.MILLISECONDS.toHours(timeoutMillis) >= 24) { throw new IllegalArgumentException("This timeout value is unsupported: " + timeoutMillis); } synchronized (myLock) { myIdleListeners.add(runnable); final MyFireIdleRequest request = new MyFireIdleRequest(runnable, timeoutMillis); myListenerToRequest.put(runnable, request); UIUtil.invokeLaterIfNeeded(() -> myIdleRequestsAlarm.addRequest(request, timeoutMillis)); } } public void removeIdleListener(@NotNull final Runnable runnable) { synchronized (myLock) { final boolean wasRemoved = myIdleListeners.remove(runnable); if (!wasRemoved) { LOG.error("unknown runnable: " + runnable); } final MyFireIdleRequest request = myListenerToRequest.remove(runnable); LOG.assertTrue(request != null); myIdleRequestsAlarm.cancelRequest(request); } } public void addActivityListener(@NotNull Runnable runnable, @NotNull Disposable parentDisposable) { ContainerUtil.add(runnable, myActivityListeners, parentDisposable); } public void addDispatcher(@NotNull EventDispatcher dispatcher, Disposable parent) { _addProcessor(dispatcher, parent, myDispatchers); } public void removeDispatcher(@NotNull EventDispatcher dispatcher) { myDispatchers.remove(dispatcher); } public boolean containsDispatcher(@NotNull EventDispatcher dispatcher) { return myDispatchers.contains(dispatcher); } public void addPostprocessor(@NotNull EventDispatcher dispatcher, @Nullable Disposable parent) { _addProcessor(dispatcher, parent, myPostProcessors); } public void removePostprocessor(@NotNull EventDispatcher dispatcher) { myPostProcessors.remove(dispatcher); } private static void _addProcessor(@NotNull EventDispatcher dispatcher, Disposable parent, @NotNull Collection<? super EventDispatcher> set) { set.add(dispatcher); if (parent != null) { Disposer.register(parent, () -> set.remove(dispatcher)); } } public int getEventCount() { return myEventCount; } public void setEventCount(int evCount) { myEventCount = evCount; } @NotNull public AWTEvent getTrueCurrentEvent() { return myCurrentEvent; } private static boolean ourAppIsLoaded; private static boolean appIsLoaded() { if (ourAppIsLoaded) { return true; } boolean loaded = ApplicationManagerEx.isAppLoaded(); if (loaded) { ourAppIsLoaded = true; } return loaded; } //Use for GuiTests to stop IdeEventQueue when application is disposed already public static void applicationClose() { ourAppIsLoaded = false; } private boolean skipTypedEvents; @Override public void dispatchEvent(@NotNull AWTEvent e) { // DO NOT ADD ANYTHING BEFORE performanceWatcher.edtEventStarted is called long startedAt = System.currentTimeMillis(); PerformanceWatcher performanceWatcher = obtainPerformanceWatcher(); try { if (performanceWatcher != null) { performanceWatcher.edtEventStarted(startedAt); } // Add code below if you need if (e.getID() == WindowEvent.WINDOW_ACTIVATED) { activatedWindows.add((Window)e.getSource()); updateActivatedWindowSet(); } if (SystemProperties.getBooleanProperty("skip.typed.event", true) && skipTypedKeyEventsIfFocusReturnsToOwner(e)) { return; } if (isMetaKeyPressedOnLinux(e)) return; if (isSpecialSymbolMatchingShortcut(e)) return; if (e.getSource() instanceof TrayIcon) { dispatchTrayIconEvent(e); return; } checkForTimeJump(startedAt); if (!appIsLoaded()) { try { super.dispatchEvent(e); } catch (Throwable t) { processException(t); } return; } e = mapEvent(e); AWTEvent metaEvent = mapMetaState(e); if (metaEvent != null && Registry.is("keymap.windows.as.meta")) { e = metaEvent; } if (JAVA11_ON_MAC && e instanceof InputEvent) { disableAltGrUnsupportedOnMac(e); } boolean wasInputEvent = myIsInInputEvent; myIsInInputEvent = isInputEvent(e); AWTEvent oldEvent = myCurrentEvent; myCurrentEvent = e; try (AccessToken ignored = startActivity(e)) { ProgressManager progressManager = obtainProgressManager(); if (progressManager != null) { progressManager.computePrioritized(() -> { _dispatchEvent(myCurrentEvent); return null; }); } else { _dispatchEvent(myCurrentEvent); } } catch (Throwable t) { processException(t); } finally { myIsInInputEvent = wasInputEvent; myCurrentEvent = oldEvent; for (EventDispatcher each : myPostProcessors) { each.dispatch(e); } if (e instanceof KeyEvent) { maybeReady(); } TransactionGuardImpl.logTimeMillis(startedAt, e); } if (isFocusEvent(e)) { onFocusEvent(e); } } finally { if (performanceWatcher != null) { performanceWatcher.edtEventFinished(); } } } private static void dispatchTrayIconEvent(@NotNull AWTEvent e) { if (e instanceof ActionEvent) { for (ActionListener listener : ((TrayIcon)e.getSource()).getActionListeners()) { listener.actionPerformed((ActionEvent)e); } } } private static void disableAltGrUnsupportedOnMac(@NotNull AWTEvent e) { if (e instanceof KeyEvent && ((KeyEvent)e).getKeyCode() == KeyEvent.VK_ALT_GRAPH) ((KeyEvent)e).setKeyCode(KeyEvent.VK_ALT); IdeKeyEventDispatcher.removeAltGraph((InputEvent)e); } private void onFocusEvent(@NotNull AWTEvent e) { TouchBarsManager.onFocusEvent(e); if (FOCUS_AWARE_RUNNABLES_LOG.isDebugEnabled()) { FOCUS_AWARE_RUNNABLES_LOG.debug("Focus event list (execute on focus event): " + runnablesWaitingForFocusChangeState()); } List<AWTEvent> events = new ArrayList<>(); while (!focusEventsList.isEmpty()) { AWTEvent f = focusEventsList.poll(); events.add(f); if (f.equals(e)) break; } events.stream() .map(entry -> myRunnablesWaitingFocusChange.remove(entry)) .filter(lor -> lor != null) .flatMap(listOfRunnables -> listOfRunnables.stream()) .filter(r -> r != null) .filter(r -> !(r instanceof ExpirableRunnable && ((ExpirableRunnable)r).isExpired())) .forEach(runnable -> { try { runnable.run(); } catch (Exception ex) { LOG.error(ex); } }); } private boolean isSpecialSymbolMatchingShortcut(AWTEvent e) { final MyLastShortcut shortcut = myLastShortcut; if (shortcut != null && e instanceof KeyEvent && e.getID() == KeyEvent.KEY_TYPED) { KeyEvent symbol = (KeyEvent)e; long time = symbol.getWhen() - shortcut.when; //todo[kb] this is a double check based on time of events. We assume that the shortcut and special symbol will be received one by one. // Try to avoid using timing checks and create a more solid solution return time < 17 && shortcut.keyChar == symbol.getKeyChar(); } return false; } public void onActionInvoked(@NotNull KeyEvent e) { myLastShortcut = new MyLastShortcut(e.getWhen(), e.getKeyChar()); } @Nullable private static ProgressManager obtainProgressManager() { ProgressManager manager = ourProgressManager; if (manager == null) { Application app = ApplicationManager.getApplication(); if (app != null && !app.isDisposed()) { ourProgressManager = manager = ServiceManager.getService(ProgressManager.class); } } return manager; } @Nullable private static PerformanceWatcher obtainPerformanceWatcher() { PerformanceWatcher watcher = ourPerformanceWatcher; if (watcher == null) { Application app = ApplicationManager.getApplication(); if (app != null && !app.isDisposed()) { ourPerformanceWatcher = watcher = PerformanceWatcher.getInstance(); } } return watcher; } private static boolean isMetaKeyPressedOnLinux(@NotNull AWTEvent e) { if (!SystemProperties.getBooleanProperty("keymap.skip.meta.press.on.linux", false)) { return false; } boolean metaIsPressed = e instanceof InputEvent && (((InputEvent)e).getModifiersEx() & InputEvent.META_DOWN_MASK) != 0; boolean typedKeyEvent = e.getID() == KeyEvent.KEY_TYPED; return SystemInfo.isLinux && typedKeyEvent && metaIsPressed; } private boolean skipTypedKeyEventsIfFocusReturnsToOwner(@NotNull AWTEvent e) { if (e.getID() == WindowEvent.WINDOW_LOST_FOCUS) { WindowEvent wfe = (WindowEvent)e; if (wfe.getWindow().getParent() != null && wfe.getWindow().getParent() == wfe.getOppositeWindow()) { skipTypedEvents = true; } } if (skipTypedEvents && e instanceof KeyEvent) { if (e.getID() == KeyEvent.KEY_TYPED) { ((KeyEvent)e).consume(); return true; } else { skipTypedEvents = false; } } return false; } //As we rely on system time monotonicity in many places let's log anomalies at least. private void checkForTimeJump(long now) { if (myLastEventTime > now + 1000) { LOG.warn("System clock's jumped back by ~" + (myLastEventTime - now) / 1000 + " sec"); } myLastEventTime = now; } private static boolean isInputEvent(@NotNull AWTEvent e) { return e instanceof InputEvent || e instanceof InputMethodEvent || e instanceof WindowEvent || e instanceof ActionEvent; } @Override @NotNull public AWTEvent getNextEvent() throws InterruptedException { AWTEvent event = super.getNextEvent(); if (isKeyboardEvent(event) && myKeyboardEventsDispatched.incrementAndGet() > myKeyboardEventsPosted.get()) { throw new RuntimeException(event + "; posted: " + myKeyboardEventsPosted + "; dispatched: " + myKeyboardEventsDispatched); } return event; } @Nullable static AccessToken startActivity(@NotNull AWTEvent e) { if (ourTransactionGuard == null && appIsLoaded()) { if (ApplicationManager.getApplication() != null && !ApplicationManager.getApplication().isDisposed()) { ourTransactionGuard = (TransactionGuardImpl)TransactionGuard.getInstance(); } } return ourTransactionGuard == null ? null : ourTransactionGuard.startActivity(isInputEvent(e) || e instanceof ItemEvent || e instanceof FocusEvent); } private void processException(@NotNull Throwable t) { if (!myToolkitBugsProcessor.process(t)) { MainRunner.processException(t); } } @NotNull private static AWTEvent mapEvent(@NotNull AWTEvent e) { if (SystemInfo.isXWindow && e instanceof MouseEvent && ((MouseEvent)e).getButton() > 3) { MouseEvent src = (MouseEvent)e; if (src.getButton() < 6) { // Convert these events(buttons 4&5 in are produced by touchpad, they must be converted to horizontal scrolling events e = new MouseWheelEvent(src.getComponent(), MouseEvent.MOUSE_WHEEL, src.getWhen(), src.getModifiers() | InputEvent.SHIFT_DOWN_MASK, src.getX(), src.getY(), 0, false, MouseWheelEvent.WHEEL_UNIT_SCROLL, src.getClickCount(), src.getButton() == 4 ? -1 : 1); } else { // Here we "shift" events with buttons 6 and 7 to similar events with buttons 4 and 5 // See java.awt.InputEvent#BUTTON_DOWN_MASK, 1<<14 is 4th physical button, 1<<15 is 5th. //noinspection MagicConstant e = new MouseEvent(src.getComponent(), src.getID(), src.getWhen(), src.getModifiers() | (1 << 8 + src.getButton()), src.getX(), src.getY(), 1, src.isPopupTrigger(), src.getButton() - 2); } } return e; } /** * Here we try to use 'Windows' key like modifier, so we patch events with modifier 'Meta' * when 'Windows' key was pressed and still is not released. * * @param e event to be patched * @return new 'patched' event if need, otherwise null * <p> * Note: As side-effect this method tracks special flag for 'Windows' key state that is valuable on itself */ @Nullable private AWTEvent mapMetaState(@NotNull AWTEvent e) { if (myWinMetaPressed) { Application app = ApplicationManager.getApplication(); boolean weAreNotActive = app == null || !app.isActive(); weAreNotActive |= e instanceof FocusEvent && ((FocusEvent)e).getOppositeComponent() == null; if (weAreNotActive) { myWinMetaPressed = false; return null; } } if (e instanceof KeyEvent) { KeyEvent ke = (KeyEvent)e; if (ke.getKeyCode() == KeyEvent.VK_WINDOWS) { if (ke.getID() == KeyEvent.KEY_PRESSED) myWinMetaPressed = true; if (ke.getID() == KeyEvent.KEY_RELEASED) myWinMetaPressed = false; return null; } if (myWinMetaPressed) { return new KeyEvent(ke.getComponent(), ke.getID(), ke.getWhen(), ke.getModifiers() | ke.getModifiersEx() | InputEvent.META_MASK, ke.getKeyCode(), ke.getKeyChar(), ke.getKeyLocation()); } } if (myWinMetaPressed && e instanceof MouseEvent && ((MouseEvent)e).getButton() != 0) { MouseEvent me = (MouseEvent)e; return new MouseEvent(me.getComponent(), me.getID(), me.getWhen(), me.getModifiers() | me.getModifiersEx() | InputEvent.META_MASK, me.getX(), me.getY(), me.getClickCount(), me.isPopupTrigger(), me.getButton()); } return null; } private void _dispatchEvent(@NotNull AWTEvent e) { if (e.getID() == MouseEvent.MOUSE_DRAGGED) { DnDManagerImpl dndManager = (DnDManagerImpl)DnDManager.getInstance(); if (dndManager != null) { dndManager.setLastDropHandler(null); } } myEventCount++; if (processAppActivationEvents(e)) return; myKeyboardBusy = e instanceof KeyEvent || myKeyboardEventsPosted.get() > myKeyboardEventsDispatched.get(); if (e instanceof KeyEvent) { if (e.getID() == KeyEvent.KEY_RELEASED && ((KeyEvent)e).getKeyCode() == KeyEvent.VK_SHIFT) { myMouseEventDispatcher.resetHorScrollingTracker(); } } if (e instanceof WindowEvent || e instanceof FocusEvent) { ActivityTracker.getInstance().inc(); } if (e instanceof MouseWheelEvent && processMouseWheelEvent((MouseWheelEvent)e)) { return; } if (e instanceof KeyEvent || e instanceof MouseEvent) { ActivityTracker.getInstance().inc(); processIdleActivityListeners(e); } // We must ignore typed events that are dispatched between KEY_PRESSED and KEY_RELEASED. // Key event dispatcher resets its state on KEY_RELEASED event if (e.getID() == KeyEvent.KEY_TYPED && myKeyEventDispatcher.isPressedWasProcessed()) { assert e instanceof KeyEvent; ((KeyEvent)e).consume(); } if (myPopupManager.isPopupActive() && myPopupManager.dispatch(e)) { if (myKeyEventDispatcher.isWaitingForSecondKeyStroke()) { myKeyEventDispatcher.setState(KeyState.STATE_INIT); } return; } if (e instanceof InputEvent && SystemInfo.isMac) { TouchBarsManager.onInputEvent((InputEvent)e); } if (dispatchByCustomDispatchers(e)) { return; } if (e instanceof InputMethodEvent) { if (SystemInfo.isMac && myKeyEventDispatcher.isWaitingForSecondKeyStroke()) { return; } } if (e instanceof ComponentEvent && myWindowManager != null) { myWindowManager.dispatchComponentEvent((ComponentEvent)e); } if (e instanceof KeyEvent) { dispatchKeyEvent(e); } else if (e instanceof MouseEvent) { dispatchMouseEvent(e); } else { defaultDispatchEvent(e); } } private static boolean processMouseWheelEvent(@NotNull MouseWheelEvent e) { final MenuElement[] selectedPath = MenuSelectionManager.defaultManager().getSelectedPath(); if (selectedPath.length > 0 && !(selectedPath[0] instanceof ComboPopup)) { e.consume(); Component component = selectedPath[0].getComponent(); if (component instanceof JBPopupMenu) { ((JBPopupMenu)component).processMouseWheelEvent(e); } return true; } return false; } private void processIdleActivityListeners(@NotNull AWTEvent e) { synchronized (myLock) { myIdleRequestsAlarm.cancelAllRequests(); for (Runnable idleListener : myIdleListeners) { final MyFireIdleRequest request = myListenerToRequest.get(idleListener); if (request == null) { LOG.error("There is no request for " + idleListener); } else { myIdleRequestsAlarm.addRequest(request, request.getTimeout(), ModalityState.NON_MODAL); } } if (KeyEvent.KEY_PRESSED == e.getID() || KeyEvent.KEY_TYPED == e.getID() || MouseEvent.MOUSE_PRESSED == e.getID() || MouseEvent.MOUSE_RELEASED == e.getID() || MouseEvent.MOUSE_CLICKED == e.getID()) { myLastActiveTime = System.nanoTime(); for (Runnable activityListener : myActivityListeners) { activityListener.run(); } } } } private void dispatchKeyEvent(@NotNull AWTEvent e) { if ( !SystemInfo.isJetBrainsJvm || (JavaVersion.current().compareTo(JavaVersion.compose(8, 0, 202, 1504, false)) < 0 && JavaVersion.current().compareTo(JavaVersion.compose(9, 0, 0, 0, false)) < 0) || JavaVersion.current().compareTo(JavaVersion.compose(11, 0, 0, 0, false)) > 0 ) { if (myKeyEventDispatcher.dispatchKeyEvent((KeyEvent)e)) { ((KeyEvent)e).consume(); } } defaultDispatchEvent(e); } private void dispatchMouseEvent(@NotNull AWTEvent e) { MouseEvent me = (MouseEvent)e; if (me.getID() == MouseEvent.MOUSE_PRESSED && me.getModifiers() > 0 && me.getModifiersEx() == 0) { // In case of these modifiers java.awt.Container#LightweightDispatcher.processMouseEvent() uses a recent 'active' component // from inner WeakReference (see mouseEventTarget field) even if the component has been already removed from component hierarchy. // So we have to reset this WeakReference with synthetic event just before processing of actual event super.dispatchEvent(new MouseEvent(me.getComponent(), MouseEvent.MOUSE_MOVED, me.getWhen(), 0, me.getX(), me.getY(), 0, false, 0)); } if (IdeMouseEventDispatcher.patchClickCount(me) && me.getID() == MouseEvent.MOUSE_CLICKED) { final MouseEvent toDispatch = new MouseEvent(me.getComponent(), me.getID(), System.currentTimeMillis(), me.getModifiers(), me.getX(), me.getY(), 1, me.isPopupTrigger(), me.getButton()); //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> dispatchEvent(toDispatch)); } if (!myMouseEventDispatcher.dispatchMouseEvent(me)) { defaultDispatchEvent(e); } } private boolean dispatchByCustomDispatchers(@NotNull AWTEvent e) { for (EventDispatcher eachDispatcher : myDispatchers) { if (eachDispatcher.dispatch(e)) { return true; } } return false; } private static boolean processAppActivationEvents(@NotNull AWTEvent e) { if (e instanceof WindowEvent) { final WindowEvent we = (WindowEvent)e; ApplicationActivationStateManager.updateState(we); storeLastFocusedComponent(we); } return false; } private static void storeLastFocusedComponent(@NotNull WindowEvent we) { final Window eventWindow = we.getWindow(); if (we.getID() == WindowEvent.WINDOW_DEACTIVATED || we.getID() == WindowEvent.WINDOW_LOST_FOCUS) { Component frame = ComponentUtil.findUltimateParent(eventWindow); Component focusOwnerInDeactivatedWindow = eventWindow.getMostRecentFocusOwner(); IdeFrame[] allProjectFrames = WindowManager.getInstance().getAllProjectFrames(); if (focusOwnerInDeactivatedWindow != null) { for (IdeFrame ideFrame : allProjectFrames) { JFrame aFrame = WindowManager.getInstance().getFrame(ideFrame.getProject()); if (aFrame.equals(frame)) { IdeFocusManager focusManager = IdeFocusManager.getGlobalInstance(); if (focusManager instanceof FocusManagerImpl) { ((FocusManagerImpl)focusManager).setLastFocusedAtDeactivation(ideFrame, focusOwnerInDeactivatedWindow); } } } } } } private void defaultDispatchEvent(@NotNull AWTEvent e) { try { maybeReady(); fixStickyAlt(e); super.dispatchEvent(e); } catch (Throwable t) { processException(t); } } private static void fixStickyAlt(@NotNull AWTEvent e) { if (!Registry.is("actionSystem.win.suppressAlt.new") && SystemInfo.isWinXpOrNewer && !SystemInfo.isWinVistaOrNewer && e instanceof KeyEvent && ((KeyEvent)e).getKeyCode() == KeyEvent.VK_ALT) { ((KeyEvent)e).consume(); // IDEA-17359 } } public void flushQueue() { while (true) { AWTEvent event = peekEvent(); if (event == null) return; try { AWTEvent event1 = getNextEvent(); dispatchEvent(event1); } catch (Exception e) { LOG.error(e); } } } public void pumpEventsForHierarchy(@NotNull Component modalComponent, @NotNull Condition<? super AWTEvent> exitCondition) { if (LOG.isDebugEnabled()) { LOG.debug("pumpEventsForHierarchy(" + modalComponent + ", " + exitCondition + ")"); } AWTEvent event; do { try { event = getNextEvent(); boolean eventOk = true; if (event instanceof InputEvent) { final Object s = event.getSource(); if (s instanceof Component) { Component c = (Component)s; Window modalWindow = SwingUtilities.windowForComponent(modalComponent); while (c != null && c != modalWindow) c = c.getParent(); if (c == null) { eventOk = false; if (LOG.isDebugEnabled()) { LOG.debug("pumpEventsForHierarchy.consumed: " + event); } ((InputEvent)event).consume(); } } } if (eventOk) { dispatchEvent(event); } } catch (Throwable e) { LOG.error(e); event = null; } } while (!exitCondition.value(event)); if (LOG.isDebugEnabled()) { LOG.debug("pumpEventsForHierarchy.exit(" + modalComponent + ", " + exitCondition + ")"); } } @FunctionalInterface public interface EventDispatcher { boolean dispatch(@NotNull AWTEvent e); } private final class MyFireIdleRequest implements Runnable { private final Runnable myRunnable; private final int myTimeout; MyFireIdleRequest(@NotNull Runnable runnable, final int timeout) { myTimeout = timeout; myRunnable = runnable; } @Override public void run() { myRunnable.run(); synchronized (myLock) { if (myIdleListeners.contains(myRunnable)) // do not reschedule if not interested anymore { myIdleRequestsAlarm.addRequest(this, myTimeout, ModalityState.NON_MODAL); } } } public int getTimeout() { return myTimeout; } @Override public String toString() { return "Fire idle request. delay: " + getTimeout() + "; runnable: " + myRunnable; } } public long getIdleTime() { return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - myLastActiveTime); } @NotNull public IdePopupManager getPopupManager() { return myPopupManager; } @NotNull public IdeKeyEventDispatcher getKeyEventDispatcher() { return myKeyEventDispatcher; } /** * Same as {@link #blockNextEvents(MouseEvent, IdeEventQueue.BlockMode)} with {@code blockMode} equal to {@code COMPLETE}. */ public void blockNextEvents(@NotNull MouseEvent e) { blockNextEvents(e, BlockMode.COMPLETE); } /** * When {@code blockMode} is {@code COMPLETE}, blocks following related mouse events completely, when {@code blockMode} is * {@code ACTIONS} only blocks performing actions bound to corresponding mouse shortcuts. */ public void blockNextEvents(@NotNull MouseEvent e, @NotNull BlockMode blockMode) { myMouseEventDispatcher.blockNextEvents(e, blockMode); } private boolean isReady() { return !myKeyboardBusy && myKeyEventDispatcher.isReady(); } public void maybeReady() { if (myReady.isEmpty() || !isReady()) return; Runnable[] ready = myReady.toArray(new Runnable[0]); myReady.clear(); for (Runnable each : ready) { each.run(); } } public void doWhenReady(@NotNull Runnable runnable) { if (EventQueue.isDispatchThread()) { myReady.add(runnable); maybeReady(); } else { //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> { myReady.add(runnable); maybeReady(); }); } } public boolean isPopupActive() { return myPopupManager.isPopupActive(); } private static class WindowsAltSuppressor implements EventDispatcher { private boolean myWaitingForAltRelease; private Robot myRobot; @Override public boolean dispatch(@NotNull AWTEvent e) { boolean dispatch = true; if (e instanceof KeyEvent) { KeyEvent ke = (KeyEvent)e; final Component component = ke.getComponent(); boolean pureAlt = ke.getKeyCode() == KeyEvent.VK_ALT && (ke.getModifiers() | InputEvent.ALT_MASK) == InputEvent.ALT_MASK; if (!pureAlt) { myWaitingForAltRelease = false; } else { UISettings uiSettings = UISettings.getInstanceOrNull(); if (uiSettings == null || !SystemInfo.isWindows || !Registry.is("actionSystem.win.suppressAlt") || !(uiSettings.getHideToolStripes() || uiSettings.getPresentationMode())) { return false; } if (ke.getID() == KeyEvent.KEY_PRESSED) { dispatch = !myWaitingForAltRelease; } else if (ke.getID() == KeyEvent.KEY_RELEASED) { if (myWaitingForAltRelease) { myWaitingForAltRelease = false; dispatch = false; } else if (component != null) { //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> { try { final Window window = ComponentUtil.getWindow(component); if (window == null || !window.isActive()) { return; } myWaitingForAltRelease = true; if (myRobot == null) { myRobot = new Robot(); } myRobot.keyPress(KeyEvent.VK_ALT); myRobot.keyRelease(KeyEvent.VK_ALT); } catch (AWTException e1) { LOG.debug(e1); } }); } } } } return !dispatch; } } //Windows OS doesn't support a Windows+Up/Down shortcut for dialogs, so we provide a workaround private class WindowsUpMaximizer implements EventDispatcher { @SuppressWarnings("SSBasedInspection") @Override public boolean dispatch(@NotNull AWTEvent e) { if (myWinMetaPressed && e instanceof KeyEvent && e.getID() == KeyEvent.KEY_RELEASED && (((KeyEvent)e).getKeyCode() == KeyEvent.VK_UP || ((KeyEvent)e).getKeyCode() == KeyEvent.VK_DOWN)) { Component parent = ComponentUtil.getWindow(((KeyEvent)e).getComponent()); if (parent instanceof JDialog) { final JDialog dialog = (JDialog)parent; SwingUtilities.invokeLater(() -> { if (((KeyEvent)e).getKeyCode() == KeyEvent.VK_UP) { MaximizeActiveDialogAction.maximize(dialog); } else { MaximizeActiveDialogAction.normalize(dialog); } }); return true; } } return false; } } //We have to stop editing with <ESC> (if any) and consume the event to prevent any further processing (dialog closing etc.) private static class EditingCanceller implements EventDispatcher { @Override public boolean dispatch(@NotNull AWTEvent e) { if (e instanceof KeyEvent && e.getID() == KeyEvent.KEY_PRESSED && ((KeyEvent)e).getKeyCode() == KeyEvent.VK_ESCAPE && !getInstance().getPopupManager().isPopupActive()) { final Component owner = ComponentUtil.findParentByCondition(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(), component -> component instanceof JTable || component instanceof JTree); if (owner instanceof JTable && ((JTable)owner).isEditing()) { ((JTable)owner).editingCanceled(null); return true; } if (owner instanceof JTree && ((JTree)owner).isEditing()) { ((JTree)owner).cancelEditing(); return true; } } return false; } } public boolean isInputMethodEnabled() { return !SystemInfo.isMac || myInputMethodLock == 0; } public void disableInputMethods(@NotNull Disposable parentDisposable) { myInputMethodLock++; Disposer.register(parentDisposable, () -> myInputMethodLock } private final FrequentEventDetector myFrequentEventDetector = new FrequentEventDetector(1009, 100); @Override public void postEvent(@NotNull AWTEvent event) { doPostEvent(event); } /** * Checks if focus is being transferred from IDE frame to a heavyweight popup. * For this, we use {@link WindowEvent}s that notify us about opened or focused windows. * We assume that by this moment AWT has enabled its typeahead machinery, so * after this check, it is safe to dequeue all postponed key events */ private static boolean doesFocusGoIntoPopup(@NotNull AWTEvent e) { AWTEvent unwrappedEvent = unwrapWindowEvent(e); if (TYPEAHEAD_LOG.isDebugEnabled() && (e instanceof WindowEvent || e.getClass().getName().contains("SequencedEvent"))) { TYPEAHEAD_LOG.debug("Window event: " + e.paramString()); } return doesFocusGoIntoPopupFromWindowEvent(unwrappedEvent); } private static class SequencedEventNestedFieldHolder { private static final Field NESTED_FIELD; private static final Class<?> SEQUENCED_EVENT_CLASS; static { try { SEQUENCED_EVENT_CLASS = Class.forName("java.awt.SequencedEvent"); NESTED_FIELD = ReflectionUtil.getDeclaredField(SEQUENCED_EVENT_CLASS, "nested"); if (NESTED_FIELD == null) throw new RuntimeException(); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } @NotNull private static AWTEvent unwrapWindowEvent(@NotNull AWTEvent e) { AWTEvent unwrappedEvent = e; if (e.getClass() == SequencedEventNestedFieldHolder.SEQUENCED_EVENT_CLASS) { try { unwrappedEvent = (AWTEvent)SequencedEventNestedFieldHolder.NESTED_FIELD.get(e); } catch (IllegalAccessException illegalAccessException) { TYPEAHEAD_LOG.error(illegalAccessException); } } TYPEAHEAD_LOG.assertTrue(unwrappedEvent != null); return unwrappedEvent; } private boolean isTypeaheadTimeoutExceeded() { if (!delayKeyEvents.get()) return false; long currentTypeaheadDelay = System.currentTimeMillis() - lastTypeaheadTimestamp; if (currentTypeaheadDelay > Registry.get("action.aware.typeaheadTimout").asDouble()) { // Log4j uses appenders. The appenders potentially may use invokeLater method // In this particular place it is possible to get a deadlock because of // sun.awt.PostEventQueue#flush implementation. // This is why we need to log the message on the event dispatch thread super.postEvent(new InvocationEvent(this, () -> TYPEAHEAD_LOG.error(new RuntimeException("Typeahead timeout is exceeded: " + currentTypeaheadDelay)) )); return true; } return false; } private static boolean doesFocusGoIntoPopupFromWindowEvent(@NotNull AWTEvent e) { if (e.getID() == WindowEvent.WINDOW_GAINED_FOCUS || SystemInfo.isLinux && e.getID() == WindowEvent.WINDOW_OPENED) { if (UIUtil.isTypeAheadAware(((WindowEvent)e).getWindow())) { TYPEAHEAD_LOG.debug("Focus goes into TypeAhead aware window"); return true; } } return false; } private static boolean isFocusEvent(@NotNull AWTEvent e) { return e.getID() == FocusEvent.FOCUS_GAINED || e.getID() == FocusEvent.FOCUS_LOST || e.getID() == WindowEvent.WINDOW_ACTIVATED || e.getID() == WindowEvent.WINDOW_DEACTIVATED || e.getID() == WindowEvent.WINDOW_LOST_FOCUS || e.getID() == WindowEvent.WINDOW_GAINED_FOCUS; } private final Queue<AWTEvent> focusEventsList = new ConcurrentLinkedQueue<>(); private final AtomicLong ourLastTimePressed = new AtomicLong(0); // return true if posted, false if consumed immediately boolean doPostEvent(@NotNull AWTEvent event) { for (PostEventHook listener : myPostEventListeners.getListeners()) { if (listener.consumePostedEvent(event)) return false; } String message = myFrequentEventDetector.getMessageOnEvent(event); if (message != null) { // we can't log right here, because logging has locks inside, and postEvents can deadlock if it's blocked by anything (IDEA-161322) NonUrgentExecutor.getInstance().execute(() -> myFrequentEventDetector.logMessage(message)); } boolean typeAheadEnabled = SystemProperties.getBooleanProperty("action.aware.typeAhead", true); if (isKeyboardEvent(event)) { myKeyboardEventsPosted.incrementAndGet(); if (typeAheadEnabled && delayKeyEvents.get()) { myDelayedKeyEvents.offer((KeyEvent)event); if (TYPEAHEAD_LOG.isDebugEnabled()) { TYPEAHEAD_LOG.debug("Waiting for typeahead : " + event); } return true; } } if (isFocusEvent(event)) { focusEventsList.add(event); } boolean typeAheadSearchEverywhereEnabled = SystemProperties.getBooleanProperty("action.aware.typeAhead.searchEverywhere", false); if (typeAheadEnabled) { if (event.getID() == KeyEvent.KEY_PRESSED) { KeyEvent keyEvent = (KeyEvent)event; KeyStroke keyStrokeToFind = KeyStroke.getKeyStroke(keyEvent.getKeyCode(), keyEvent.getModifiers()); boolean thisShortcutMayShowPopup = ContainerUtil.exists(getShortcutsShowingPopups(), s -> s instanceof KeyboardShortcut && ((KeyboardShortcut)s).getSecondKeyStroke() == null && ((KeyboardShortcut)s).getFirstKeyStroke().equals(keyStrokeToFind)); if (!isActionPopupShown() && thisShortcutMayShowPopup && KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow() instanceof IdeFrame) { if (TYPEAHEAD_LOG.isDebugEnabled()) { TYPEAHEAD_LOG.debug("Delay following events; Focused window is " + KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow().getClass().getName()); } delayKeyEvents.set(true); lastTypeaheadTimestamp = System.currentTimeMillis(); } } else if (event.getID() == KeyEvent.KEY_RELEASED && typeAheadSearchEverywhereEnabled && KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow() instanceof IdeFrame) { KeyEvent keyEvent = (KeyEvent)event; // 1. check key code // 2. if key code != SHIFT -> restart // 3. if has other modifiers - > restart // 4. keyEvent.getWhen() - ourLastTimePressed.get() < 100 -> restart // 5. if the second time and (keyEvent.getWhen() - ourLastTimePressed.get() > 500) -> restart state if (keyEvent.getKeyCode() == KeyEvent.VK_SHIFT) { switch (mySearchEverywhereTypeaheadState) { case DEACTIVATED: mySearchEverywhereTypeaheadState = SearchEverywhereTypeaheadState.TRIGGERED; ourLastTimePressed.set(keyEvent.getWhen()); break; case TRIGGERED: long timeDelta = keyEvent.getWhen() - ourLastTimePressed.get(); if (!isActionPopupShown() && timeDelta >= 100 && timeDelta <= 500) { delayKeyEvents.set(true); lastTypeaheadTimestamp = System.currentTimeMillis(); mySearchEverywhereTypeaheadState = SearchEverywhereTypeaheadState.DETECTED; } else { mySearchEverywhereTypeaheadState = SearchEverywhereTypeaheadState.DEACTIVATED; flushDelayedKeyEvents(); // no need to reset ourLastTimePressed } break; case DETECTED: break; } } } if (isTypeaheadTimeoutExceeded()) { TYPEAHEAD_LOG.debug("Clear delayed events because of IdeFrame deactivation"); delayKeyEvents.set(false); flushDelayedKeyEvents(); lastTypeaheadTimestamp = 0; if (typeAheadSearchEverywhereEnabled) { mySearchEverywhereTypeaheadState = SearchEverywhereTypeaheadState.DEACTIVATED; } } } super.postEvent(event); if (typeAheadSearchEverywhereEnabled && event instanceof KeyEvent && (mySearchEverywhereTypeaheadState == SearchEverywhereTypeaheadState.TRIGGERED || mySearchEverywhereTypeaheadState == SearchEverywhereTypeaheadState.DETECTED)) { long timeDelta = ((KeyEvent)event).getWhen() - ourLastTimePressed.get(); if (timeDelta < 100 || timeDelta > 500) { mySearchEverywhereTypeaheadState = SearchEverywhereTypeaheadState.DEACTIVATED; flushDelayedKeyEvents(); } } if (typeAheadEnabled && doesFocusGoIntoPopup(event)) { delayKeyEvents.set(false); postDelayedKeyEvents(); if (typeAheadSearchEverywhereEnabled) { mySearchEverywhereTypeaheadState = SearchEverywhereTypeaheadState.DEACTIVATED; } } return true; } private int numberOfDelayedKeyEvents() { // for debug purposes only since it's slow and unreliable return myDelayedKeyEvents.size(); } private void postDelayedKeyEvents() { if (TYPEAHEAD_LOG.isDebugEnabled()) { TYPEAHEAD_LOG.debug("Stop delaying events. Events to post: " + numberOfDelayedKeyEvents()); } KeyEvent event; while ((event = myDelayedKeyEvents.poll()) != null) { if (TYPEAHEAD_LOG.isDebugEnabled()) { TYPEAHEAD_LOG.debug("Posted after delay: " + event.paramString()); } super.postEvent(event); } if (TYPEAHEAD_LOG.isDebugEnabled()) { TYPEAHEAD_LOG.debug("Events after posting: " + numberOfDelayedKeyEvents()); } } public void flushDelayedKeyEvents() { long startedAt = System.currentTimeMillis(); if (!isActionPopupShown() && delayKeyEvents.compareAndSet(true, false)) { postDelayedKeyEvents(); } TransactionGuardImpl.logTimeMillis(startedAt, "IdeEventQueue#flushDelayedKeyEvents"); } private static boolean isActionPopupShown() { if (ApplicationManager.getApplication() == null) { return false; } ActionManager actionManager = ActionManager.getInstance(); return actionManager instanceof ActionManagerImpl && !((ActionManagerImpl)actionManager).isActionPopupStackEmpty() && !((ActionManagerImpl)actionManager).isToolWindowContextMenuVisible(); } private SearchEverywhereTypeaheadState mySearchEverywhereTypeaheadState = SearchEverywhereTypeaheadState.DEACTIVATED; private enum SearchEverywhereTypeaheadState { DEACTIVATED, TRIGGERED, DETECTED } private final Set<Shortcut> shortcutsShowingPopups = new HashSet<>(); private WeakReference<Keymap> lastActiveKeymap = new WeakReference<>(null); private final List<String> actionsShowingPopupsList = new ArrayList<>(); private long lastTypeaheadTimestamp = -1; @Nullable public static KeymapManager getKeymapManager() { ApplicationEx app = ApplicationManagerEx.getApplicationEx(); return app != null && app.isLoaded() ? KeymapManager.getInstance() : null; } @NotNull private Set<Shortcut> getShortcutsShowingPopups () { KeymapManager keymapManager = getKeymapManager(); if (keymapManager != null) { Keymap keymap = keymapManager.getActiveKeymap(); if (!keymap.equals(lastActiveKeymap.get())) { String actionsAwareTypeaheadActionsList = Registry.get("action.aware.typeahead.actions.list").asString(); shortcutsShowingPopups.clear(); actionsShowingPopupsList.addAll(StringUtil.split(actionsAwareTypeaheadActionsList, ",")); actionsShowingPopupsList.forEach(actionId -> { List<Shortcut> shortcuts = Arrays.asList(keymap.getShortcuts(actionId)); if (TYPEAHEAD_LOG.isDebugEnabled()) { shortcuts.forEach(s -> TYPEAHEAD_LOG.debug("Typeahead for " + actionId + " : Shortcuts: " + s)); } shortcutsShowingPopups.addAll(shortcuts); }); lastActiveKeymap = new WeakReference<>(keymap); } } return shortcutsShowingPopups; } private final Queue<KeyEvent> myDelayedKeyEvents = new ConcurrentLinkedQueue<>(); private final AtomicBoolean delayKeyEvents = new AtomicBoolean(); private static boolean isKeyboardEvent(@NotNull AWTEvent event) { return event instanceof KeyEvent; } @Override public AWTEvent peekEvent() { AWTEvent event = super.peekEvent(); if (event != null) { return event; } if (isTestMode() && LaterInvocator.ensureFlushRequested()) { return super.peekEvent(); } return null; } private Boolean myTestMode; private boolean isTestMode() { Boolean testMode = myTestMode; if (testMode != null) return testMode; Application application = ApplicationManager.getApplication(); if (application == null) return false; testMode = application.isUnitTestMode(); myTestMode = testMode; return testMode; } /** * @see IdeEventQueue#blockNextEvents(MouseEvent, IdeEventQueue.BlockMode) */ public enum BlockMode { COMPLETE, ACTIONS } /** * An absolutely guru API, please avoid using it at all cost. */ @FunctionalInterface public interface PostEventHook extends EventListener { /** * @return true if event is handled by the listener and should't be added to event queue at all */ boolean consumePostedEvent(@NotNull AWTEvent event); } public void addPostEventListener(@NotNull PostEventHook listener, @NotNull Disposable parentDisposable) { myPostEventListeners.addListener(listener, parentDisposable); } private static class Holder { // JBSDK only private static final Method unsafeNonBlockingExecuteRef = ReflectionUtil.getDeclaredMethod(SunToolkit.class, "unsafeNonblockingExecute", Runnable.class); } /** * Must be called on the Event Dispatching thread. * Executes the runnable so that it can perform a non-blocking invocation on the toolkit thread. * Not for general-purpose usage. * * @param r the runnable to execute */ public static void unsafeNonblockingExecute(@NotNull Runnable r) { assert EventQueue.isDispatchThread(); // The method is available in JBSDK. if (Holder.unsafeNonBlockingExecuteRef != null) { try { Holder.unsafeNonBlockingExecuteRef.invoke(Toolkit.getDefaultToolkit(), r); return; } catch (Exception ignore) { } } r.run(); } private static class MyLastShortcut { public final long when; public final char keyChar; private MyLastShortcut(long when, char keyChar) { this.when = when; this.keyChar = keyChar; } } }
package pt.up.fe.aiad.scheduler.agentbehaviours; import jade.core.AID; import jade.core.behaviours.SimpleBehaviour; import jade.lang.acl.ACLMessage; import jade.lang.acl.MessageTemplate; import pt.up.fe.aiad.scheduler.SchedulerAgent; import pt.up.fe.aiad.scheduler.Serializer; import pt.up.fe.aiad.utils.TimeInterval; import java.util.*; public class ABTBehaviour extends SimpleBehaviour { //TODO private TreeSet<AID> _links; //TODO: create agent view and link structure private boolean isFinished = false; private SchedulerAgent _agent; private ABTSelf self = new ABTSelf(); public ABTBehaviour () { } public static class ABTSelf { Variable x; ArrayList<TimeInterval> domain; HashMap<String, TimeInterval> agentview; TreeSet<String> lower_agents; ArrayList<NoGood> nogoods; int cost; TreeSet<String> tag; boolean exact; } public static class Variable { public TimeInterval v; public String agent; } public static class NoGood { public TimeInterval v; public HashMap<String, TimeInterval> cond; public TreeSet<String> tag; public int cost; public boolean exact; } @Override public void onStart() { _agent = (SchedulerAgent) myAgent; if (_agent._events.isEmpty()) { terminate(0); return; } self.x = new Variable(); self.x.agent = myAgent.getAID().getName(); self.x.v = null; self.nogoods = new ArrayList<>(); self.lower_agents = new TreeSet<>(); self.agentview = new HashMap<>(); self.tag = new TreeSet<>(); self.cost = 0; self.exact = true; self.domain = _agent._events.get(0)._possibleSolutions; for (AID agent : _agent._events.get(0)._participants) { if (_agent.getAID().compareTo(agent) < 0) self.lower_agents.add(agent.getName()); // if (_agent.getAID().compareTo(agent) > 0) // ) self.agentview.put(agent.getName(), null); } adjust_value(); } public void adjust_value() { TimeInterval old_value = self.x.v; self.cost = Integer.MAX_VALUE; for (TimeInterval v : self.domain) { int delta = _agent._events.get(0).getCost(v); /* TODO: ask mike */ int LB = 0; TreeSet<String> tag = new TreeSet<>(); tag.add(_agent.getName()); boolean exact = true; for (String xj : self.agentview.keySet()) { delta += 0; /* TODO: ask mike */ } for (NoGood ng : self.nogoods) { if (!ng.v.equals(v)) { continue; } LB += ng.cost; tag.addAll(ng.tag); exact = exact && ng.exact; } exact = exact && tag.containsAll(self.lower_agents); if (delta + LB <= self.cost) { self.x.v = v; self.cost = delta + LB; self.tag = tag; self.exact = exact; } } if (self.cost != 0 || self.exact) { if (_agent.getName().equals(_agent.allAgents.first().getName())) { terminate(self.cost); return; } if (!self.agentview.isEmpty()) { TreeSet<String> s = new TreeSet<>(self.agentview.keySet()); Variable xj = new Variable(); xj.agent = s.last(); xj.v = self.agentview.get(xj.agent); NoGood ng = new NoGood(); ng.v = xj.v; ng.cond = new HashMap<>(self.agentview); ng.cond.remove(xj.agent); ng.tag = self.tag; ng.exact = self.exact; sendNoGood(xj.agent, ng); } } if (!self.x.v.equals(old_value)) { for (String a : self.lower_agents) { sendOk(a, self.x); } } } private void terminate(int cost) { _agent._events.get(0)._currentInterval = self.x.v; _agent._events.get(0)._currentCost = cost; if (!self.lower_agents.isEmpty()) sendTerminate(cost); isFinished = true; _agent.finishedAlgorithm(); } private void sendNoGood(String agent, NoGood ng) { String json = Serializer.NoGoodToJSON(ng); ACLMessage msg = new ACLMessage(ACLMessage.REJECT_PROPOSAL); msg.addReceiver(new AID(agent, true)); msg.setContent("NOGOOD-" + json); msg.setConversationId("ABT"); getAgent().send(msg); } private void sendOk(String agent, Variable x) { String json = Serializer.VariableToJSON(x); ACLMessage msg = new ACLMessage(ACLMessage.PROPOSE); msg.addReceiver(new AID(agent, true)); msg.setContent("OK?-" + json); msg.setConversationId("ABT"); getAgent().send(msg); } private void sendAddLink(String agent, Variable x) { String json = Serializer.VariableToJSON(x); ACLMessage msg = new ACLMessage(ACLMessage.PROPAGATE); msg.addReceiver(new AID(agent, true)); msg.setContent("LINK-" + json); msg.setConversationId("ABT"); getAgent().send(msg); } private void sendTerminate(int cost) { ACLMessage msg = new ACLMessage(ACLMessage.CANCEL); for (String agent : self.lower_agents) { msg.addReceiver(new AID(agent, true)); } msg.setContent("TERM-" + cost); msg.setConversationId("ABT"); getAgent().send(msg); } private void receiveAddLink(Variable xj) { self.lower_agents.add(xj.agent); sendOk(xj.agent, self.x); } private void receiveOk(Variable var) { ArrayList<NoGood> toRemove = new ArrayList<>(); for (NoGood ng : self.nogoods) { for (Map.Entry<String, TimeInterval> vc : ng.cond.entrySet()) { if (vc.getKey().equals(var.agent) && !vc.getValue().equals(var.v)) { toRemove.add(ng); break; } } } toRemove.forEach(self.nogoods::remove); self.agentview.put(var.agent, var.v); adjust_value(); } private void receiveNoGood(NoGood new_ng) { for (Map.Entry<String, TimeInterval> var : new_ng.cond.entrySet()) { TimeInterval cvv = self.agentview.get(var.getKey()); if (cvv == null) { self.agentview.put(var.getKey(), var.getValue()); sendAddLink(var.getKey(), self.x); } else { if (!cvv.equals(var.getValue())) return; } } ArrayList<NoGood> toRemove = new ArrayList<>(); for (NoGood ng : self.nogoods) { if (ng.v.equals(new_ng.v) && new_ng.tag.containsAll(ng.tag)) { toRemove.add(ng); } } toRemove.forEach(self.nogoods::remove); self.nogoods.add(new_ng); /* can this be duplicated? */ adjust_value(); } private void receiveTerminate(int cost) { terminate(cost); } @Override public void action() { if (isFinished) return; MessageTemplate mt = MessageTemplate.MatchConversationId("ABT"); ACLMessage msg = myAgent.receive(mt); if (msg != null) { int separatorIndex = msg.getContent().indexOf('-'); if (separatorIndex != -1) { String str = msg.getContent(); String[] strs = str.split("-", 2); switch (strs[0]) { case "OK?": receiveOk(Serializer.VariableFromJSON(strs[1])); break; case "NOGOOD": receiveNoGood(Serializer.NoGoodFromJSON(strs[1])); break; case "LINK": receiveAddLink(Serializer.VariableFromJSON(strs[1])); break; case "TERM": receiveTerminate(Integer.parseInt(strs[1])); break; default: System.err.println("Received an invalid message type."); break; } } else { System.err.println("Received an invalid message"); } } else { block(); } } @Override public boolean done() { return isFinished; } }
package com.cloud.baremetal; import java.net.InetAddress; import java.net.URI; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.ejb.Local; import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupRoutingCommand; import com.cloud.api.ApiConstants; import com.cloud.dc.ClusterVO; import com.cloud.dc.DataCenterVO; import com.cloud.dc.dao.ClusterDao; import com.cloud.dc.dao.DataCenterDao; import com.cloud.exception.DiscoveryException; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.network.Network; import com.cloud.resource.Discoverer; import com.cloud.resource.DiscovererBase; import com.cloud.resource.ResourceManager; import com.cloud.resource.ResourceStateAdapter; import com.cloud.resource.ServerResource; import com.cloud.resource.UnableDeleteHostException; import com.cloud.utils.component.Inject; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.script.Script; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.dao.VMInstanceDao; @Local(value=Discoverer.class) public class BareMetalDiscoverer extends DiscovererBase implements Discoverer, ResourceStateAdapter { private static final Logger s_logger = Logger.getLogger(BareMetalDiscoverer.class); @Inject ClusterDao _clusterDao; @Inject protected HostDao _hostDao; @Inject DataCenterDao _dcDao; @Inject VMInstanceDao _vmDao = null; @Inject ResourceManager _resourceMgr; @Override public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); return super.configure(name, params); } @Override public boolean stop() { _resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName()); return super.stop(); } @Override public Map<? extends ServerResource, Map<String, String>> find(long dcId, Long podId, Long clusterId, URI url, String username, String password, List<String> hostTags) throws DiscoveryException { Map<BareMetalResourceBase, Map<String, String>> resources = new HashMap<BareMetalResourceBase, Map<String, String>>(); Map<String, String> details = new HashMap<String, String>(); if (!url.getScheme().equals("http")) { String msg = "urlString is not http so we're not taking care of the discovery for this: " + url; s_logger.debug(msg); return null; } if (clusterId == null) { String msg = "must specify cluster Id when add host"; s_logger.debug(msg); throw new RuntimeException(msg); } if (podId == null) { String msg = "must specify pod Id when add host"; s_logger.debug(msg); throw new RuntimeException(msg); } ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null || (cluster.getHypervisorType() != HypervisorType.BareMetal)) { if (s_logger.isInfoEnabled()) s_logger.info("invalid cluster id or cluster is not for Bare Metal hosts"); return null; } DataCenterVO zone = _dcDao.findById(dcId); if (zone == null) { throw new RuntimeException("Cannot find zone " + dcId); } try { String hostname = url.getHost(); InetAddress ia = InetAddress.getByName(hostname); String ipmiIp = ia.getHostAddress(); String guid = UUID.nameUUIDFromBytes(ipmiIp.getBytes()).toString(); String injectScript = "scripts/util/ipmi.py"; String scriptPath = Script.findScript("", injectScript); if (scriptPath == null) { throw new CloudRuntimeException("Unable to find key ipmi script " + injectScript); } final Script command = new Script(scriptPath, s_logger); command.add("ping"); command.add("hostname="+ipmiIp); command.add("usrname="+username); command.add("password="+password); final String result = command.execute(); if (result != null) { s_logger.warn(String.format("Can not set up ipmi connection(ip=%1$s, username=%2$s, password=%3$s, args) because %4$s", ipmiIp, username, password, result)); return null; } ClusterVO clu = _clusterDao.findById(clusterId); if (clu.getGuid() == null) { clu.setGuid(UUID.randomUUID().toString()); _clusterDao.update(clusterId, clu); } Map<String, Object> params = new HashMap<String, Object>(); params.putAll(_params); params.put("zone", Long.toString(dcId)); params.put("pod", Long.toString(podId)); params.put("cluster", Long.toString(clusterId)); params.put("guid", guid); params.put(ApiConstants.PRIVATE_IP, ipmiIp); params.put(ApiConstants.USERNAME, username); params.put(ApiConstants.PASSWORD, password); BareMetalResourceBase resource = new BareMetalResourceBase(); resource.configure("Bare Metal Agent", params); String memCapacity = (String)params.get(ApiConstants.MEMORY); String cpuCapacity = (String)params.get(ApiConstants.CPU_SPEED); String cpuNum = (String)params.get(ApiConstants.CPU_NUMBER); String mac = (String)params.get(ApiConstants.HOST_MAC); if (hostTags != null && hostTags.size() != 0) { details.put("hostTag", hostTags.get(0)); } details.put(ApiConstants.MEMORY, memCapacity); details.put(ApiConstants.CPU_SPEED, cpuCapacity); details.put(ApiConstants.CPU_NUMBER, cpuNum); details.put(ApiConstants.HOST_MAC, mac); details.put(ApiConstants.USERNAME, username); details.put(ApiConstants.PASSWORD, password); details.put(ApiConstants.PRIVATE_IP, ipmiIp); resources.put(resource, details); resource.start(); zone.setGatewayProvider(Network.Provider.ExternalGateWay.getName()); zone.setDnsProvider(Network.Provider.ExternalDhcpServer.getName()); zone.setDhcpProvider(Network.Provider.ExternalDhcpServer.getName()); _dcDao.update(zone.getId(), zone); s_logger.debug(String.format("Discover Bare Metal host successfully(ip=%1$s, username=%2$s, password=%3%s," + "cpuNum=%4$s, cpuCapacity-%5$s, memCapacity=%6$s)", ipmiIp, username, password, cpuNum, cpuCapacity, memCapacity)); return resources; } catch (Exception e) { s_logger.warn("Can not set up bare metal agent", e); } return null; } @Override public void postDiscovery(List<HostVO> hosts, long msId) throws DiscoveryException { } @Override public boolean matchHypervisor(String hypervisor) { return hypervisor.equalsIgnoreCase(Hypervisor.HypervisorType.BareMetal.toString()); } @Override public HypervisorType getHypervisorType() { return Hypervisor.HypervisorType.BareMetal; } @Override public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { // TODO Auto-generated method stub return null; } @Override public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map<String, String> details, List<String> hostTags) { StartupCommand firstCmd = startup[0]; if (!(firstCmd instanceof StartupRoutingCommand)) { return null; } StartupRoutingCommand ssCmd = ((StartupRoutingCommand) firstCmd); if (ssCmd.getHypervisorType() != HypervisorType.BareMetal) { return null; } return _resourceMgr.fillRoutingHostVO(host, ssCmd, HypervisorType.BareMetal, details, hostTags); } @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { if (host.getType() != Host.Type.Routing || host.getHypervisorType() != HypervisorType.BareMetal) { return null; } List<VMInstanceVO> deadVms = _vmDao.listByLastHostId(host.getId()); for (VMInstanceVO vm : deadVms) { if (vm.getState() == State.Running || vm.getHostId() != null) { throw new CloudRuntimeException("VM " + vm.getId() + "is still running on host " + host.getId()); } _vmDao.remove(vm.getId()); } return new DeleteHostAnswer(true); } }
package com.cloud.cluster; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.ejb.Local; import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import com.cloud.cluster.dao.StackMaidDao; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.serializer.SerializerHelper; import com.cloud.utils.DateUtil; import com.cloud.utils.NumbersUtil; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; import com.cloud.utils.db.GlobalLock; @Local(value=CheckPointManager.class) public class CheckPointManagerImpl implements CheckPointManager, Manager, ClusterManagerListener { private static final Logger s_logger = Logger.getLogger(CheckPointManagerImpl.class); private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 3; // 3 seconds private static final int GC_INTERVAL = 10000; // 10 seconds private int _cleanupRetryInterval; private String _name; @Inject private StackMaidDao _maidDao; @Inject private ClusterManager _clusterMgr; long _msId; private final ScheduledExecutorService _heartbeatScheduler = Executors.newScheduledThreadPool(1, new NamedThreadFactory("TaskMgr-Heartbeat")); private final ScheduledExecutorService _cleanupScheduler = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Task-Cleanup")); protected CheckPointManagerImpl() { } @Override public boolean configure(String name, Map<String, Object> xmlParams) throws ConfigurationException { _name = name; if (s_logger.isInfoEnabled()) { s_logger.info("Start configuring StackMaidManager : " + name); } StackMaid.init(ManagementServerNode.getManagementServerId()); _msId = ManagementServerNode.getManagementServerId(); _clusterMgr.registerListener(this); ComponentLocator locator = ComponentLocator.getCurrentLocator(); ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); Map<String, String> params = configDao.getConfiguration(xmlParams); _cleanupRetryInterval = NumbersUtil.parseInt(params.get(Config.TaskCleanupRetryInterval.key()), 600); _maidDao.takeover(_msId, _msId); return true; } private void cleanupLeftovers(List<CheckPointVO> l) { for (CheckPointVO maid : l) { if (StackMaid.doCleanup(maid)) { _maidDao.expunge(maid.getId()); } } } @DB private Runnable getGCTask() { return new Runnable() { @Override public void run() { GlobalLock scanLock = GlobalLock.getInternLock("StackMaidManagerGC"); try { if (scanLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION)) { try { reallyRun(); } finally { scanLock.unlock(); } } } finally { scanLock.releaseRef(); } } public void reallyRun() { try { Date cutTime = new Date(DateUtil.currentGMTTime().getTime() - 7200000); List<CheckPointVO> l = _maidDao.listLeftoversByCutTime(cutTime); cleanupLeftovers(l); } catch (Throwable e) { s_logger.error("Unexpected exception when trying to execute queue item, ", e); } } }; } @Override public boolean start() { // try { // List<TaskVO> l = _maidDao.listLeftoversByMsid(_clusterMgr.getManagementNodeId()); // cleanupLeftovers(l); // } catch (Throwable e) { // s_logger.error("Unexpected exception " + e.getMessage(), e); // _heartbeatScheduler.scheduleAtFixedRate(getGCTask(), GC_INTERVAL, GC_INTERVAL, TimeUnit.MILLISECONDS); _cleanupScheduler.schedule(new CleanupTask(), _cleanupRetryInterval > 0 ? _cleanupRetryInterval : 600, TimeUnit.SECONDS); return true; } @Override public boolean stop() { return true; } @Override public String getName() { return _name; } @Override public void onManagementNodeJoined(List<ManagementServerHostVO> nodeList, long selfNodeId) { // Nothing to do } @Override public void onManagementNodeLeft(List<ManagementServerHostVO> nodeList, long selfNodeId) { for (ManagementServerHostVO node : nodeList) { if (_maidDao.takeover(node.getMsid(), selfNodeId)) { s_logger.info("Taking over from " + node.getMsid()); _cleanupScheduler.execute(new CleanupTask()); } } } @Override public long pushCheckPoint(CleanupMaid context) { long seq = _maidDao.pushCleanupDelegate(_msId, 0, context.getClass().getName(), context); return seq; } @Override public void updateCheckPointState(long taskId, CleanupMaid updatedContext) { CheckPointVO task = _maidDao.createForUpdate(); task.setDelegate(updatedContext.getClass().getName()); task.setContext(SerializerHelper.toSerializedStringOld(updatedContext)); _maidDao.update(taskId, task); } @Override public void popCheckPoint(long taskId) { _maidDao.remove(taskId); } protected boolean cleanup(CheckPointVO task) { s_logger.info("Cleaning up " + task); CleanupMaid delegate = (CleanupMaid)SerializerHelper.fromSerializedString(task.getContext()); assert delegate.getClass().getName().equals(task.getDelegate()) : "Deserializer says " + delegate.getClass().getName() + " but it's suppose to be " + task.getDelegate(); int result = delegate.cleanup(); if (result <= 0) { if (result == 0) { s_logger.info("Successfully cleaned up " + task.getId()); } else { s_logger.warn("Unsuccessful in cleaning up " + task + ". Procedure to cleanup manaully: " + delegate.getCleanupProcedure()); } popCheckPoint(task.getId()); return true; } else { s_logger.error("Unable to cleanup " + task.getId()); return false; } } class CleanupTask implements Runnable { public CleanupTask() { } @Override public void run() { try { List<CheckPointVO> tasks = _maidDao.listCleanupTasks(_msId); List<CheckPointVO> retries = new ArrayList<CheckPointVO>(); for (CheckPointVO task : tasks) { try { if (!cleanup(task)) { retries.add(task); } } catch (Exception e) { s_logger.warn("Unable to clean up " + task, e); } } if (retries.size() > 0) { if (_cleanupRetryInterval > 0) { _cleanupScheduler.schedule(this, _cleanupRetryInterval, TimeUnit.SECONDS); } else { for (CheckPointVO task : retries) { s_logger.warn("Cleanup procedure for " + task + ": " + ((CleanupMaid)SerializerHelper.fromSerializedString(task.getContext())).getCleanupProcedure()); } } } } catch (Exception e) { s_logger.error("Unable to cleanup all of the tasks for " + _msId, e); } } } }
package io.flutter.view; import android.content.Context; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.os.Bundle; import android.os.Looper; import android.os.SystemClock; import android.util.Log; import io.flutter.util.PathUtils; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; /** * A class to intialize the Flutter engine. */ public class FlutterMain { private static final String TAG = "FlutterMain"; // Must match values in sky::shell::switches private static final String AOT_SHARED_LIBRARY_PATH = "aot-shared-library-path"; private static final String AOT_SNAPSHOT_PATH_KEY = "aot-snapshot-path"; private static final String AOT_VM_SNAPSHOT_DATA_KEY = "vm-snapshot-data"; private static final String AOT_VM_SNAPSHOT_INSTR_KEY = "vm-snapshot-instr"; private static final String AOT_ISOLATE_SNAPSHOT_DATA_KEY = "isolate-snapshot-data"; private static final String AOT_ISOLATE_SNAPSHOT_INSTR_KEY = "isolate-snapshot-instr"; private static final String FLX_KEY = "flx"; private static final String SNAPSHOT_BLOB_KEY = "snapshot-blob"; private static final String FLUTTER_ASSETS_DIR_KEY = "flutter-assets-dir"; // XML Attribute keys supported in AndroidManifest.xml public static final String PUBLIC_AOT_AOT_SHARED_LIBRARY_PATH = FlutterMain.class.getName() + '.' + AOT_SHARED_LIBRARY_PATH; public static final String PUBLIC_AOT_VM_SNAPSHOT_DATA_KEY = FlutterMain.class.getName() + '.' + AOT_VM_SNAPSHOT_DATA_KEY; public static final String PUBLIC_AOT_VM_SNAPSHOT_INSTR_KEY = FlutterMain.class.getName() + '.' + AOT_VM_SNAPSHOT_INSTR_KEY; public static final String PUBLIC_AOT_ISOLATE_SNAPSHOT_DATA_KEY = FlutterMain.class.getName() + '.' + AOT_ISOLATE_SNAPSHOT_DATA_KEY; public static final String PUBLIC_AOT_ISOLATE_SNAPSHOT_INSTR_KEY = FlutterMain.class.getName() + '.' + AOT_ISOLATE_SNAPSHOT_INSTR_KEY; public static final String PUBLIC_FLX_KEY = FlutterMain.class.getName() + '.' + FLX_KEY; public static final String PUBLIC_SNAPSHOT_BLOB_KEY = FlutterMain.class.getName() + '.' + SNAPSHOT_BLOB_KEY; public static final String PUBLIC_FLUTTER_ASSETS_DIR_KEY = FlutterMain.class.getName() + '.' + FLUTTER_ASSETS_DIR_KEY; // Resource names used for components of the precompiled snapshot. private static final String DEFAULT_AOT_SHARED_LIBRARY_PATH= "app.so"; private static final String DEFAULT_AOT_VM_SNAPSHOT_DATA = "vm_snapshot_data"; private static final String DEFAULT_AOT_VM_SNAPSHOT_INSTR = "vm_snapshot_instr"; private static final String DEFAULT_AOT_ISOLATE_SNAPSHOT_DATA = "isolate_snapshot_data"; private static final String DEFAULT_AOT_ISOLATE_SNAPSHOT_INSTR = "isolate_snapshot_instr"; private static final String DEFAULT_FLX = "app.flx"; private static final String DEFAULT_SNAPSHOT_BLOB = "snapshot_blob.bin"; private static final String DEFAULT_KERNEL_BLOB = "kernel_blob.bin"; private static final String DEFAULT_PLATFORM_DILL = "platform.dill"; private static final String DEFAULT_FLUTTER_ASSETS_DIR = "flutter_assets"; // Assets that are shared among all Flutter apps within an APK. private static final String SHARED_ASSET_DIR = "flutter_shared"; private static final String SHARED_ASSET_ICU_DATA = "icudtl.dat"; private static String fromFlutterAssets(String filePath) { return sFlutterAssetsDir + File.separator + filePath; } // Mutable because default values can be overridden via config properties private static String sAotSharedLibraryPath = DEFAULT_AOT_SHARED_LIBRARY_PATH; private static String sAotVmSnapshotData = DEFAULT_AOT_VM_SNAPSHOT_DATA; private static String sAotVmSnapshotInstr = DEFAULT_AOT_VM_SNAPSHOT_INSTR; private static String sAotIsolateSnapshotData = DEFAULT_AOT_ISOLATE_SNAPSHOT_DATA; private static String sAotIsolateSnapshotInstr = DEFAULT_AOT_ISOLATE_SNAPSHOT_INSTR; private static String sFlx = DEFAULT_FLX; private static String sSnapshotBlob = DEFAULT_SNAPSHOT_BLOB; private static String sFlutterAssetsDir = DEFAULT_FLUTTER_ASSETS_DIR; private static boolean sInitialized = false; private static ResourceExtractor sResourceExtractor; private static boolean sIsPrecompiledAsBlobs; private static boolean sIsPrecompiledAsSharedLibrary; private static Settings sSettings; private static String sIcuDataPath; private static final class ImmutableSetBuilder<T> { static <T> ImmutableSetBuilder<T> newInstance() { return new ImmutableSetBuilder<>(); } HashSet<T> set = new HashSet<>(); private ImmutableSetBuilder() {} ImmutableSetBuilder<T> add(T element) { set.add(element); return this; } @SafeVarargs final ImmutableSetBuilder<T> add(T... elements) { for (T element : elements) { set.add(element); } return this; } Set<T> build() { return Collections.unmodifiableSet(set); } } public static class Settings { private String logTag; public String getLogTag() { return logTag; } /** * Set the tag associated with Flutter app log messages. * @param tag Log tag. */ public void setLogTag(String tag) { logTag = tag; } } /** * Starts initialization of the native system. * @param applicationContext The Android application context. */ public static void startInitialization(Context applicationContext) { startInitialization(applicationContext, new Settings()); } /** * Starts initialization of the native system. * @param applicationContext The Android application context. * @param settings Configuration settings. */ public static void startInitialization(Context applicationContext, Settings settings) { if (Looper.myLooper() != Looper.getMainLooper()) { throw new IllegalStateException("startInitialization must be called on the main thread"); } // Do not run startInitialization more than once. if (sSettings != null) { return; } sSettings = settings; long initStartTimestampMillis = SystemClock.uptimeMillis(); initConfig(applicationContext); initAot(applicationContext); initResources(applicationContext); System.loadLibrary("flutter"); // We record the initialization time using SystemClock because at the start of the // initialization we have not yet loaded the native library to call into dart_tools_api.h. // To get Timeline timestamp of the start of initialization we simply subtract the delta // from the Timeline timestamp at the current moment (the assumption is that the overhead // of the JNI call is negligible). long initTimeMillis = SystemClock.uptimeMillis() - initStartTimestampMillis; nativeRecordStartTimestamp(initTimeMillis); } /** * Blocks until initialization of the native system has completed. * @param applicationContext The Android application context. * @param args Flags sent to the Flutter runtime. */ public static void ensureInitializationComplete(Context applicationContext, String[] args) { if (Looper.myLooper() != Looper.getMainLooper()) { throw new IllegalStateException("ensureInitializationComplete must be called on the main thread"); } if (sSettings == null) { throw new IllegalStateException("ensureInitializationComplete must be called after startInitialization"); } if (sInitialized) { return; } try { sResourceExtractor.waitForCompletion(); List<String> shellArgs = new ArrayList<>(); shellArgs.add("--icu-data-file-path=" + sIcuDataPath); if (args != null) { Collections.addAll(shellArgs, args); } if (sIsPrecompiledAsSharedLibrary) { shellArgs.add("--" + AOT_SHARED_LIBRARY_PATH + "=" + new File(PathUtils.getDataDirectory(applicationContext), sAotSharedLibraryPath)); } else { if (sIsPrecompiledAsBlobs) { shellArgs.add("--" + AOT_SNAPSHOT_PATH_KEY + "=" + PathUtils.getDataDirectory(applicationContext)); } else { shellArgs.add("--cache-dir-path=" + PathUtils.getCacheDirectory(applicationContext)); shellArgs.add("--" + AOT_SNAPSHOT_PATH_KEY + "=" + PathUtils.getDataDirectory(applicationContext) + "/" + sFlutterAssetsDir); } shellArgs.add("--" + AOT_VM_SNAPSHOT_DATA_KEY + "=" + sAotVmSnapshotData); shellArgs.add("--" + AOT_VM_SNAPSHOT_INSTR_KEY + "=" + sAotVmSnapshotInstr); shellArgs.add("--" + AOT_ISOLATE_SNAPSHOT_DATA_KEY + "=" + sAotIsolateSnapshotData); shellArgs.add("--" + AOT_ISOLATE_SNAPSHOT_INSTR_KEY + "=" + sAotIsolateSnapshotInstr); } if (sSettings.getLogTag() != null) { shellArgs.add("--log-tag=" + sSettings.getLogTag()); } String appBundlePath = findAppBundlePath(applicationContext); nativeInit(applicationContext, shellArgs.toArray(new String[0]), appBundlePath); sInitialized = true; } catch (Exception e) { Log.e(TAG, "Flutter initialization failed.", e); throw new RuntimeException(e); } } private static native void nativeInit(Context context, String[] args, String bundlePath); private static native void nativeRecordStartTimestamp(long initTimeMillis); /** * Initialize our Flutter config values by obtaining them from the * manifest XML file, falling back to default values. */ private static void initConfig(Context applicationContext) { try { Bundle metadata = applicationContext.getPackageManager().getApplicationInfo( applicationContext.getPackageName(), PackageManager.GET_META_DATA).metaData; if (metadata != null) { sAotSharedLibraryPath = metadata.getString(PUBLIC_AOT_AOT_SHARED_LIBRARY_PATH, DEFAULT_AOT_SHARED_LIBRARY_PATH); sAotVmSnapshotData = metadata.getString(PUBLIC_AOT_VM_SNAPSHOT_DATA_KEY, DEFAULT_AOT_VM_SNAPSHOT_DATA); sAotVmSnapshotInstr = metadata.getString(PUBLIC_AOT_VM_SNAPSHOT_INSTR_KEY, DEFAULT_AOT_VM_SNAPSHOT_INSTR); sAotIsolateSnapshotData = metadata.getString(PUBLIC_AOT_ISOLATE_SNAPSHOT_DATA_KEY, DEFAULT_AOT_ISOLATE_SNAPSHOT_DATA); sAotIsolateSnapshotInstr = metadata.getString(PUBLIC_AOT_ISOLATE_SNAPSHOT_INSTR_KEY, DEFAULT_AOT_ISOLATE_SNAPSHOT_INSTR); sFlx = metadata.getString(PUBLIC_FLX_KEY, DEFAULT_FLX); sSnapshotBlob = metadata.getString(PUBLIC_SNAPSHOT_BLOB_KEY, DEFAULT_SNAPSHOT_BLOB); sFlutterAssetsDir = metadata.getString(PUBLIC_FLUTTER_ASSETS_DIR_KEY, DEFAULT_FLUTTER_ASSETS_DIR); } } catch (PackageManager.NameNotFoundException e) { throw new RuntimeException(e); } } private static void initResources(Context applicationContext) { Context context = applicationContext; new ResourceCleaner(context).start(); sResourceExtractor = new ResourceExtractor(context); // Search for the icudtl.dat file at the old and new locations. // TODO(jsimmons): remove the old location when all tools have been updated. Set<String> sharedAssets = listAssets(applicationContext, SHARED_ASSET_DIR); String icuAssetPath; if (sharedAssets.contains(SHARED_ASSET_ICU_DATA)) { icuAssetPath = SHARED_ASSET_DIR + File.separator + SHARED_ASSET_ICU_DATA; } else { icuAssetPath = SHARED_ASSET_ICU_DATA; } sResourceExtractor.addResource(icuAssetPath); sIcuDataPath = PathUtils.getDataDirectory(applicationContext) + File.separator + icuAssetPath; sResourceExtractor .addResource(fromFlutterAssets(sFlx)) .addResource(fromFlutterAssets(sSnapshotBlob)) .addResource(fromFlutterAssets(sAotVmSnapshotData)) .addResource(fromFlutterAssets(sAotVmSnapshotInstr)) .addResource(fromFlutterAssets(sAotIsolateSnapshotData)) .addResource(fromFlutterAssets(sAotIsolateSnapshotInstr)) .addResource(fromFlutterAssets(DEFAULT_KERNEL_BLOB)) .addResource(fromFlutterAssets(DEFAULT_PLATFORM_DILL)); if (sIsPrecompiledAsSharedLibrary) { sResourceExtractor .addResource(sAotSharedLibraryPath); } else { sResourceExtractor .addResource(sAotVmSnapshotData) .addResource(sAotVmSnapshotInstr) .addResource(sAotIsolateSnapshotData) .addResource(sAotIsolateSnapshotInstr) .addResource(sSnapshotBlob); } sResourceExtractor.start(); } /** * Returns a list of the file names at the root of the application's asset * path. */ private static Set<String> listAssets(Context applicationContext, String path) { AssetManager manager = applicationContext.getResources().getAssets(); try { return ImmutableSetBuilder.<String>newInstance() .add(manager.list(path)) .build(); } catch (IOException e) { Log.e(TAG, "Unable to list assets", e); throw new RuntimeException(e); } } private static void initAot(Context applicationContext) { Set<String> assets = listAssets(applicationContext, ""); sIsPrecompiledAsBlobs = assets.containsAll(Arrays.asList( sAotVmSnapshotData, sAotVmSnapshotInstr, sAotIsolateSnapshotData, sAotIsolateSnapshotInstr )); sIsPrecompiledAsSharedLibrary = assets.contains(sAotSharedLibraryPath); if (sIsPrecompiledAsBlobs && sIsPrecompiledAsSharedLibrary) { throw new RuntimeException( "Found precompiled app as shared library and as Dart VM snapshots."); } } public static boolean isRunningPrecompiledCode() { return sIsPrecompiledAsBlobs || sIsPrecompiledAsSharedLibrary; } public static String findAppBundlePath(Context applicationContext) { String dataDirectory = PathUtils.getDataDirectory(applicationContext); File appBundle = new File(dataDirectory, sFlutterAssetsDir); return appBundle.exists() ? appBundle.getPath() : null; } /** * Returns the file name for the given asset. * The returned file name can be used to access the asset in the APK * through the {@link AssetManager} API. * * @param asset the name of the asset. The name can be hierarchical * @return the filename to be used with {@link AssetManager} */ public static String getLookupKeyForAsset(String asset) { return fromFlutterAssets(asset); } /** * Returns the file name for the given asset which originates from the * specified packageName. The returned file name can be used to access * the asset in the APK through the {@link AssetManager} API. * * @param asset the name of the asset. The name can be hierarchical * @param packageName the name of the package from which the asset originates * @return the file name to be used with {@link AssetManager} */ public static String getLookupKeyForAsset(String asset, String packageName) { return getLookupKeyForAsset( "packages" + File.separator + packageName + File.separator + asset); } }
package me.Qball.Wild.Listeners; import me.Qball.Wild.Utils.Region; import me.Qball.Wild.Wild; import org.bukkit.ChatColor; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; import java.util.Collections; import java.util.UUID; public class BlockClickEvent implements Listener { private Wild wild; public BlockClickEvent(Wild wild) { this.wild = wild; } @EventHandler(priority = EventPriority.HIGHEST) public void onBlockClick(PlayerInteractEvent e) { if(e.getItem()==null) return; if (e.getAction().equals(Action.LEFT_CLICK_BLOCK) && e.getItem().getItemMeta().hasLore()) { if (e.getItem().getItemMeta().getLore().equals(Collections.singletonList("Right/left click on blocks to make a region"))&& !checkFirstMap(e.getPlayer().getUniqueId(),e.getClickedBlock().getLocation().toVector())) { e.setCancelled(true); wild.firstCorner.put(e.getPlayer().getUniqueId(), e.getClickedBlock().getLocation().toVector()); e.getPlayer().sendMessage(ChatColor.GREEN + "First corner set"); } } else if (e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { ItemStack stack = e.getPlayer().getItemInHand(); if (!stack.getItemMeta().hasLore()) return; if (!stack.getItemMeta().getLore().equals(Collections.singletonList("Right/left click on blocks to make a region"))) return; if (checkSecondMap(e.getPlayer().getUniqueId(),e.getClickedBlock().getLocation().toVector())) return; e.setCancelled(true); wild.secondCorner.put(e.getPlayer().getUniqueId(),e.getClickedBlock().getLocation().toVector()); e.getPlayer().sendMessage(ChatColor.GREEN+"Second corner set"); } } public boolean checkFirstMap(UUID id, Vector vec){ if(wild.firstCorner.containsKey(id)) { if (wild.firstCorner.get(id).equals(vec)) return true; }else return false; return false; } public boolean checkSecondMap(UUID id, Vector vec){ if(wild.secondCorner.containsKey(id)) { if (wild.secondCorner.get(id).equals(vec)) return true; }else return false; return false; } }
package mods.themike.modjam; import mods.themike.modjam.blocks.BlockCarvingStone; import mods.themike.modjam.blocks.BlockDecoration; import mods.themike.modjam.blocks.BlockGhostBlock; import mods.themike.modjam.blocks.BlockMagebrickLamp; import mods.themike.modjam.blocks.BlockSlabs; import mods.themike.modjam.items.ItemMulti; import mods.themike.modjam.items.ItemPapyrus; import mods.themike.modjam.items.ItemRune; import mods.themike.modjam.items.ItemStaff; import mods.themike.modjam.items.ToolReaper; import net.minecraftforge.common.Configuration; public class ModJamConfiguration { public static void init(Configuration config) { ModJam.carvingStone = new BlockCarvingStone(config.getBlock("Carving Stone", 1100).getInt(1100)); ModJam.decoration = new BlockDecoration(config.getBlock("Decorative Blocks", 1101).getInt(1101)); ModJam.slabs = new BlockSlabs(config.getBlock("Decorative Slabs", 1102).getInt(1102)); ModJam.ghost = new BlockGhostBlock(config.getBlock("Ghost Block", 1103).getInt(1103)); ModJam.lamp = new BlockMagebrickLamp(config.getBlock("Magebrick Lamp", 1104).getInt(1104)); ModJam.item = new ItemMulti(config.getItem("Main Items", 5500).getInt(5500)); ModJam.runes = new ItemRune(config.getItem("Runes", 5501).getInt(5501)); ModJam.scroll = new ItemPapyrus(config.getItem("Papyrus Scroll", 5502).getInt(5502)); ModJam.staff = new ItemStaff(config.getItem("Staffs", 5503).getInt(5503)); ModJam.reaper = new ToolReaper(config.getItem("Reaper", 5504).getInt(5504)); config.save(); } }
package net.commotionwireless.olsrinfo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; public class OlsrInfo { String host = "127.0.0.1"; int port = 2006; public OlsrInfo() { } public OlsrInfo(String sethost) { host = sethost; } public OlsrInfo(String sethost, int setport) { host = sethost; port = setport; } public String[] request(String req) throws IOException { Socket sock = null; BufferedReader in = null; PrintWriter out = null; List<String> retlist = new ArrayList<String>(); try { sock = new Socket(host, port); in = new BufferedReader(new InputStreamReader(sock.getInputStream())); out = new PrintWriter(sock.getOutputStream(), true); } catch (UnknownHostException e) { throw new IOException(); } catch (IOException e) { System.err.println("Couldn't get I/O for socket to " + host + ":" + Integer.toString(port)); } out.println(req); String line; while((line = in.readLine()) != null) { retlist.add(line); } // the txtinfo plugin drops the connection once it outputs out.close(); in.close(); sock.close(); return retlist.toArray(new String[retlist.size()]); } public String[] routes() { String [] data = null; int startpos = 0; try { data = request("/route"); } catch (IOException e) { System.err.println("Couldn't get I/O for socket to " + host + ":" + Integer.toString(port)); } for(int i = 0; i < data.length; i++) { if(data[i].startsWith("Table: Routes")) { startpos = i + 2; break; } } String[] ret = new String[data.length - startpos]; for (int i = 0; i < ret.length; i++) ret[i] = data[i + startpos]; return ret; } public static void main (String[] args) throws IOException { OlsrInfo txtinfo = new OlsrInfo(); try { for (String s : txtinfo.request("/all") ) System.out.println(s); } catch (IOException e) { System.err.println("Couldn't get I/O for socket to " + txtinfo.host + ":" + Integer.toString(txtinfo.port)); } System.out.println("ROUTES for(String s : txtinfo.routes()) System.out.println(s); } }
package net.coobird.paint.brush; import java.awt.AlphaComposite; import java.awt.Composite; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import net.coobird.paint.image.ImageLayer; /** * The {@code BrushController} handles the drawing of brushes onto an image. * @author coobird * */ public class BrushController { /** * The {@code BrushAction} class represents an event to process. * Events such as drawing and releasing a brush is represented as an * instance of {@code BrushAction}, and is processed by the * {@code BrushController}. * @author coobird * */ static class BrushAction { private final Brush b; private final ImageLayer il; private final int x; private final int y; private final State state; private enum State { DRAW, RELEASE; } private BrushAction(ImageLayer il, Brush b, int x, int y) { this.b = b; this.il = il; this.x = x; this.y = y; this.state = State.DRAW; } private BrushAction() { this.b = null; this.il = null; this.x = UNDEFINED; this.y = UNDEFINED; this.state = State.RELEASE; } private int getX() { return this.x; } private int getY() { return this.y; } private Brush getBrush() { return this.b; } private ImageLayer getLayer() { return this.il; } private State getState() { return this.state; } } private static final int UNDEFINED = Integer.MIN_VALUE; private static final double UNDEFINED_THETA = Double.NaN; private Queue<BrushAction> actionQueue; private double theta; private double lastTheta = UNDEFINED_THETA; private int lastX = UNDEFINED; private int lastY = UNDEFINED; private Brush lastBrush = null; private boolean rotatable = true; private long lastTime = System.currentTimeMillis(); private DrawingThread drawingThread = new DrawingThread(); private ExecutorService executor = Executors.newSingleThreadExecutor(); /** * Constructs an instance of the {@code BrushController}. */ public BrushController() { actionQueue = new LinkedList<BrushAction>(); theta = 0; } /** * Draws the brush between last draw point and current draw point. * @param action The {@code BrushAction} containing the draw action. */ private void interpolatedDraw(BrushAction action) { // Constant used to determine the distance moved between one brush draw. // By detault, the distance is 1/8 the size of the brush. final int STEP_DIVISION = 8; Graphics2D g = action.getLayer().getGraphics(); setCompositeForBrush(g, action.getBrush()); BufferedImage brushImage = action.getBrush().getBrush(); double distX = lastX - action.getX(); double distY = lastY - action.getY(); // System.out.println(distX); // System.out.println(distY); double dist = Math.sqrt(Math.pow(distX, 2) + Math.pow(distY, 2)); double steps = dist / (double)(brushImage.getWidth() / (double)STEP_DIVISION); double incX = -distX / steps; double incY = -distY / steps; double x = lastX - (brushImage.getWidth() / 2); double y = lastY - (brushImage.getHeight() / 2); int intSteps = (int)Math.round(steps); // true -> unsmooth transition of brush angle // false -> smooth transition of brush angle --> buggy if (false) { BufferedImage rotatedBrushImage = new BufferedImage( brushImage.getWidth(), brushImage.getHeight(), BufferedImage.TYPE_INT_ARGB ); Graphics2D brushg = rotatedBrushImage.createGraphics(); if (rotatable) { brushg.rotate( theta, rotatedBrushImage.getWidth() / 2.0d, rotatedBrushImage.getHeight() / 2.0d ); } brushg.drawImage(brushImage, 0, 0, null); for (int i = 0; i < intSteps; i++) { x += incX; y += incY; g.drawImage(rotatedBrushImage, (int)x, (int)y, null); } brushg.dispose(); } else { double t = lastTheta; double incTheta = lastTheta - theta; for (int i = 0; i < intSteps; i++) { x += incX; y += incY; t += incTheta; BufferedImage rotatedBrushImage = new BufferedImage( brushImage.getWidth(), brushImage.getHeight(), BufferedImage.TYPE_INT_ARGB ); Graphics2D brushg = rotatedBrushImage.createGraphics(); if (rotatable) { brushg.rotate( t, rotatedBrushImage.getWidth() / 2, rotatedBrushImage.getHeight() / 2 ); } brushg.drawImage(brushImage, 0, 0, null); g.drawImage(rotatedBrushImage, (int)x, (int)y, null); brushg.dispose(); } } } /** * Processes a {@code BrushAction} in the queue. */ private void processBrush() { BrushAction action = actionQueue.remove(); if ( lastBrush != action.getBrush() || action.getState() == BrushAction.State.RELEASE ) { System.out.println("last brush released."); clearTheta(); } if (action.getState() == BrushAction.State.RELEASE) { lastX = UNDEFINED; lastY = UNDEFINED; return; } Graphics2D g = action.getLayer().getGraphics(); // TODO Setting Composite for g should be fine. // if so, remove one setComposite... from interpolateDraw and here. // uncomment below: // setCompositeForBrush(g, action.getBrush()); BufferedImage brushImage = action.getBrush().getBrush(); // Determine the brush painting mean to use. // If brush is already being dragged across, then use interpolatedDraw. // If not, handle the "single-click" painting of brush. if (lastX != UNDEFINED) { if (rotatable) { calcTheta(action.getX(), action.getY()); } interpolatedDraw(action); } else { int x = action.getX() - (brushImage.getWidth() / 2); int y = action.getY() - (brushImage.getHeight() / 2); setCompositeForBrush(g, action.getBrush()); g.drawImage(brushImage, x, y, null); } lastX = action.x; lastY = action.y; lastBrush = action.getBrush(); } /** * Sets the {@link Composite} of the given {@link Graphics2D} object. Used * for setting the composite mode of the {@code Graphics2D} object to allow * switching modes between a regular brush and an eraser. * @param g The {@code Graphics2D} object to change the * composite mode of. * @param b The {@code Brush} object from which the composite * mode to set to should be retrieved. */ private void setCompositeForBrush(Graphics2D g, Brush b) { Composite layerComposite = AlphaComposite.getInstance( b.getMode().getComposite().getRule(), b.getAlpha() ); g.setComposite(layerComposite); } /** * Draws the on the specified {@link ImageLayer} object, using the specified * {@link Brush} object at the location {@code x, y}. * @param il The {@code ImageLayer} object to draw on. * @param b The {@code Brush} object to draw with. * @param x The {@code x} coordinate of the {@code ImageLayer} * to draw the brush at. * @param y The {@code y} coordinate of the {@code ImageLayer} * to draw the brush at. */ public void drawBrush(ImageLayer il, Brush b, int x, int y) { actionQueue.add(new BrushAction(il, b, x, y)); System.out.println("add brushevent"); long timePast = System.currentTimeMillis() - lastTime; if (!drawingThread.running && timePast > 100) { System.out.println("start thread"); //new DrawingThread().start(); //drawingThread.start(); executor.execute(drawingThread); lastTime = System.currentTimeMillis(); } } public void releaseBrush() { actionQueue.add(new BrushAction()); } /** * Calculate the angle to rotate the brush. * @param x The x coordinate of the brush. * @param y The y coordinate of the brush. */ private void calcTheta(int x, int y) { if (lastX == UNDEFINED && lastY == UNDEFINED) { lastX = x; lastY = y; } lastTheta = theta; int diffX = lastX - x; int diffY = lastY - y; theta = Math.atan2(diffX, diffY); } /** * Clears the stored location and angle of the last brush action. */ private void clearTheta() { lastX = UNDEFINED; lastY = UNDEFINED; lastTheta = UNDEFINED_THETA; } /** * Sets the state for allowing the brush to rotate depending on the movement * of the brush. * @param b Whether or not to allow rotation of the brush. */ public void setMovable(boolean b) { this.rotatable = b; } /** * Returns whether or not brush rotation is currently enabled. * @return Returns {@code true} if brush rotation is allowed, * {@code false} otherwise. */ public boolean getMovable() { return this.rotatable; } /** * Thread for processing the {@link BrushAction} queue. * @author coobird * */ class DrawingThread extends Thread { boolean running = false; /** * Processes the {@link BrushAction} queue. */ public void run() { running = true; while(!actionQueue.isEmpty()) { System.out.println("processing"); processBrush(); } running = false; } } }
package net.decusatis.genderamenderrender; import java.util.Collection; public class Utils { /** * The options we're working with (for now) */ public enum Gender { MALE, FEMALE, NONBINARY, // non-male or female genders go in this bucket for now DECLINE, // they've selected they don't want to provide this UNSURE, // they've selected something we can't parse to m, f, or neither UNSPECIFIED // they haven't selected something } /** * Business logic to transform a collection of strings to a gender enum item */ public static Gender renderGenderEnglish(Collection<String> selections) { // unspecified if (selections == null || selections.isEmpty()){ return Gender.UNSPECIFIED; } // these booleans are set up throughout this method, and their combination determines the value we return boolean male = false; boolean female = false; boolean nonbinary = false; boolean decline = false; for (String elt : selections) { switch (elt) { // decline to provide setup case "decline to provide": case "prefer not to say": decline = true; break; // male setup case "f to m": case "female to male": case "male": case "man": case "transmasculine": male = true; break; // female setup case "female": case "femme": case "m to f": case "male to female": case "transfeminine": case "woman": female = true; break; // nonbinary setup case "?": case "agender": case "bigender": case "gender nonconforming": case "gender questioning": case "gender variant": case "genderfluid": case "genderqueer": case "neither": case "neutrois": case "nonbinary": case "none": case "other": case "pangender": case "polygender": case "questioning": case "two spirit": nonbinary = true; break; default: // words like "trans" which don't denote anything about m/f/nb status break; } } // determination if(decline) { return Gender.DECLINE; // if they decline to provide it doesn't matter what else they said, we don't use it } // if they're clearly selecting only male, only female, or only neither male nor female options, assign as such else if (male && !female && !nonbinary) { return Gender.MALE; } else if (female && !male && !nonbinary) { return Gender.FEMALE; } else if (nonbinary && !male && !female) { return Gender.NONBINARY; } // otherwise, let's not do anything clever for now else { return Gender.UNSURE; } } /** * Helper methods */ public static boolean getIsMale(Gender g) { return Gender.MALE == g; } public static boolean getIsFemale(Gender g) { return Gender.FEMALE == g; } }
package sopc2dts.lib.components; import java.util.Vector; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import sopc2dts.generators.AbstractSopcGenerator; import sopc2dts.lib.SopcInfoAssignment; import sopc2dts.lib.SopcInfoConnection; import sopc2dts.lib.SopcInfoElement; import sopc2dts.lib.SopcInfoParameter; public class SopcInfoComponent extends SopcInfoElement { public enum parameter_action { NONE, CMACRCO, ALL }; private String instanceName; private String version; private int addr = 0; private Vector<SopcInfoAssignment> vParams = new Vector<SopcInfoAssignment>(); private Vector<SopcInfoInterface> vInterfaces = new Vector<SopcInfoInterface>(); private SopcComponentDescription scd; public SopcInfoComponent(ContentHandler p, XMLReader xr, SopcComponentDescription scd, String iName, String ver) { super(p,xr); this.setScd(scd); this.setInstanceName(iName); version = ver; } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if(localName.equalsIgnoreCase("assignment")) { getParams().add(new SopcInfoAssignment(this, xmlReader)); } else if(localName.equalsIgnoreCase("parameter")) { getParams().add(new SopcInfoParameter(this, xmlReader, atts.getValue("name"))); } else if(localName.equalsIgnoreCase("interface")) { getInterfaces().add(new SopcInfoInterface(this, xmlReader, atts.getValue("name"), atts.getValue("kind"), this)); } else { super.startElement(uri, localName, qName, atts); } } protected String getRegForDTS(int indentLevel, SopcInfoConnection conn, SopcInfoInterface intf) { if((conn!=null) && (intf!=null)) { return AbstractSopcGenerator.indent(indentLevel) + "reg = <0x" + Integer.toHexString(conn.getBaseAddress()) + " 0x" + Integer.toHexString(intf.getAddressableSize()) + ">;\n"; } else { return ""; } } protected String getInterruptsForDTS(int indentLevel) { String interrupts =AbstractSopcGenerator.indent(indentLevel) + "interrupts = <"; SopcInfoComponent irqParent = null; for(SopcInfoInterface intf : getInterfaces()) { if(intf.getKind().equalsIgnoreCase("interrupt_sender")) { if(irqParent==null) { irqParent = intf.getConnections().get(0).getMasterInterface().getOwner(); } if(intf.getConnections().get(0).getMasterInterface().getOwner().equals(irqParent)) { interrupts += " " + intf.getConnections().get(0).getParamValue("irqNumber").getValue(); } } } if(irqParent!=null) { return AbstractSopcGenerator.indent(indentLevel) + "interrupt-parent = < &" + irqParent.getInstanceName() + " >;\n" + interrupts + " >;\n"; } else { return ""; } } public String toDts(int indentLevel, SopcInfoComponent.parameter_action paramAction) { return toDts(indentLevel, paramAction, null, true); } public String toDts(int indentLevel, SopcInfoComponent.parameter_action paramAction, SopcInfoConnection conn, Boolean endComponent) { int tmpAddr = getAddrFromConnection(conn); String res = AbstractSopcGenerator.indent(indentLevel++) + getInstanceName() + ": " + getScd().getGroup() + "@0x" + Integer.toHexString(tmpAddr) + " {\n"; res += toDtsExtrasFirst(indentLevel, conn, endComponent); if((getScd().getGroup().equalsIgnoreCase("cpu"))||(getScd().getGroup().equalsIgnoreCase("memory"))) { res += AbstractSopcGenerator.indent(indentLevel) + "device-type = \"" + getScd().getGroup() +"\";\n"; } res += AbstractSopcGenerator.indent(indentLevel) + "compatible = " + getScd().getCompatible(version); res += ";\n"; if (getScd().getGroup().equalsIgnoreCase("cpu")) { res += AbstractSopcGenerator.indent(indentLevel) + "reg = <" + getAddr() + ">;\n"; } else if(conn!=null) { res += getRegForDTS(indentLevel, conn, conn.getSlaveInterface()); } res += getInterruptMasterDesc(indentLevel); res += getInterruptsForDTS(indentLevel); for(SopcComponentDescription.SICAutoParam ap : getScd().vAutoParams) { String ass = getParamValue(ap.sopcInfoName); if(ass!=null) { res += AbstractSopcGenerator.indent(indentLevel) + ap.dtsName + " = <" + ass + ">;\n"; } else if(ap.dtsName.equalsIgnoreCase("clock-frequency")) { res += AbstractSopcGenerator.indent(indentLevel) + ap.dtsName + " = <" + getClockRate() + ">;\n"; } else if(ap.dtsName.equalsIgnoreCase("regstep")) { res += AbstractSopcGenerator.indent(indentLevel) + ap.dtsName + " = <4>;\n"; } } if((paramAction != parameter_action.NONE)&&(getParams().size()>0)) { res += AbstractSopcGenerator.indent(indentLevel) + "//Dumping SOPC parameters...\n"; for(SopcInfoAssignment ass : getParams()) { String assName = ass.getName(); if(assName.startsWith("embeddedsw.CMacro.")) { assName = assName.substring(18); } else if(paramAction == parameter_action.CMACRCO) { assName = null; } if(assName!=null) { assName = assName.replace('_', '-'); res += AbstractSopcGenerator.indent(indentLevel) + scd.getVendor() + "," + assName + " = \"" + ass.getValue() + "\";\n"; } } } res += toDtsExtras(indentLevel, conn, endComponent); if(endComponent) res += AbstractSopcGenerator.indent(--indentLevel) + "};\n"; return res; } private String getInterruptMasterDesc(int indentLevel) { for(SopcInfoInterface intf : getInterfaces()) { if(intf.getKind().equalsIgnoreCase("interrupt_receiver")) { return AbstractSopcGenerator.indent(indentLevel) + "interrupt-controller;\n" + AbstractSopcGenerator.indent(indentLevel) + "#interrupt-cells = <1>;\n"; } } return ""; } public String toDtsExtrasFirst(int indentLevel, SopcInfoConnection conn, Boolean endComponent) { return ""; } public String toDtsExtras(int indentLevel, SopcInfoConnection conn, Boolean endComponent) { return ""; } @Override public String getElementName() { return "module"; } public String getParamValue(String paramName) { for(SopcInfoAssignment ass : getParams()) { if(ass.getName().equalsIgnoreCase(paramName)) { return ass.getValue(); } } return null; } public SopcInfoInterface getInterfaceByName(String ifName) { for(SopcInfoInterface intf : getInterfaces()) { if(intf.getName().equalsIgnoreCase(ifName)) { return intf; } } return null; } public Boolean isUsefullForDTS() { return true; } public void setScd(SopcComponentDescription scd) { this.scd = scd; } public SopcComponentDescription getScd() { return scd; } public void setInstanceName(String instanceName) { this.instanceName = instanceName; } public String getInstanceName() { return instanceName; } public void setParams(Vector<SopcInfoAssignment> vParams) { this.vParams = vParams; } public Vector<SopcInfoAssignment> getParams() { return vParams; } public void setInterfaces(Vector<SopcInfoInterface> vInterfaces) { this.vInterfaces = vInterfaces; } public Vector<SopcInfoInterface> getInterfaces() { return vInterfaces; } public void setAddr(int addr) { this.addr = addr; } public int getAddr() { return addr; } public int getAddrFromMaster() { return getAddrFromMaster(0); } public int getAddrFromMaster(int index) { for(SopcInfoInterface intf : vInterfaces) { if(intf.isMemorySlave()) { if(intf.getConnections().size()>index) { return intf.getConnections().get(index).getBaseAddress(); } } } return -1; } protected int getAddrFromConnection(SopcInfoConnection conn) { return (conn==null ? getAddr() : conn.getBaseAddress()); } public int getClockRate() { int rate = 0; for(SopcInfoInterface intf : vInterfaces) { if(intf.isClockInput()) { rate = Integer.decode(intf.getConnections().get(0).getMasterInterface().getParamValue("clockRate").getValue()); } } return rate; } public boolean hasMemoryMaster() { for(SopcInfoInterface intf : vInterfaces) { if(intf.isMemoryMaster()) return true; } return false; } }
package nl.sense_os.service.motion; import java.math.BigDecimal; import java.util.ArrayList; import nl.sense_os.service.R; import nl.sense_os.service.constants.SenseDataTypes; import nl.sense_os.service.constants.SensePrefs; import nl.sense_os.service.constants.SensePrefs.Main.Motion; import nl.sense_os.service.constants.SensorData.DataPoint; import nl.sense_os.service.constants.SensorData.SensorNames; import nl.sense_os.service.provider.SNTP; import nl.sense_os.service.states.EpiStateMonitor; import org.json.JSONArray; import org.json.JSONObject; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Build; import android.os.Handler; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.util.FloatMath; import android.util.Log; /** * Represents the main motion sensor. Listens for events from the Android SensorManager and parses * the results.<br/> * <br/> * The resulting data is divided over several separate sensors in CommonSense: * * <ul> * <li>accelerometer</li> * <li>gyroscope</li> * <li>motion energy</li> * <li>linear acceleration</li> * </ul> * Besides these basic sensors, the sensor can also gather data for high-speed epilepsy detection * and fall detection. * * @author Ted Schmidt <ted@sense-os.nl> * @author Steven Mulder <steven@sense-os.nl> */ public class MotionSensor implements SensorEventListener { private static MotionSensor instance = null; protected MotionSensor(Context context) { this.context = context; } public static MotionSensor getInstance(Context context) { if(instance == null) { instance = new MotionSensor(context); } return instance; } /** * BroadcastReceiver that listens for screen state changes. Re-registers the motion sensor when * the screen turns off. */ private class ScreenOffListener extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // Check action just to be on the safe side. if (false == intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { return; } SharedPreferences prefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); boolean useFix = prefs.getBoolean(Motion.SCREENOFF_FIX, false); if (useFix) { // wait half a second and re-register Runnable restartSensing = new Runnable() { @Override public void run() { // Unregisters the motion listener and registers it again. // Log.v(TAG, "Screen went off, re-registering the Motion sensor"); stopMotionSensing(); startMotionSensing(sampleDelay); }; }; new Handler().postDelayed(restartSensing, 500); } } } private static final String TAG = "Sense Motion"; private final BroadcastReceiver screenOffListener = new ScreenOffListener(); private final FallDetector fallDetector = new FallDetector(); private final Context context; private boolean isFallDetectMode; private boolean isEnergyMode; private boolean isEpiMode; private boolean isUnregisterWhenIdle; private boolean firstStart = true; private ArrayList<Sensor> sensors; private final long[] lastSampleTimes = new long[50]; private Handler motionHandler = new Handler(); private boolean motionSensingActive = false; private Runnable motionThread = null; private long sampleDelay = 0; // in milliseconds private long[] lastLocalSampleTimes = new long[50]; private long localBufferTime = 15 * 1000; private long firstTimeSend = 0; private JSONArray[] dataBuffer = new JSONArray[10]; // members for calculating the avg speed change during a time period, for motion energy sensor private static final long ENERGY_SAMPLE_LENGTH = 500; private long energySampleStart = 0; private long prevEnergySampleTime; private double avgSpeedChange; private int avgSpeedCount; private boolean hasLinAccSensor; private float[] gravity = { 0, 0, SensorManager.GRAVITY_EARTH }; // members for waking up the device for sampling private static final String ACTION_WAKEUP_ALARM = "nl.sense_os.service.MotionWakeUp"; private static final int ALARM_ID = 256; private BroadcastReceiver wakeReceiver; private WakeLock wakeLock; private boolean isRegistered; private long lastRegistered = -1; private static final long DELAY_AFTER_REGISTRATION = 500; /** * Calculates the linear acceleration of a raw accelerometer sample. Tries to determine the * gravity component by putting the signal through a first-order low-pass filter. * * @param values * Array with accelerometer values for the three axes. * @return The approximate linear acceleration of the sample. */ private float[] calcLinAcc(float[] values) { // low-pass filter raw accelerometer data to approximate the gravity final float alpha = 0.8f; // filter constants should depend on sample rate gravity[0] = alpha * gravity[0] + (1 - alpha) * values[0]; gravity[1] = alpha * gravity[1] + (1 - alpha) * values[1]; gravity[2] = alpha * gravity[2] + (1 - alpha) * values[2]; return new float[] { values[0] - gravity[0], values[1] - gravity[1], values[2] - gravity[2] }; } @SuppressWarnings("deprecation") private JSONObject createJsonValue(SensorEvent event) { final Sensor sensor = event.sensor; final JSONObject json = new JSONObject(); int axis = 0; try { for (double value : event.values) { // scale to three decimal precision value = BigDecimal.valueOf(value).setScale(3, 0).doubleValue(); switch (axis) { case 0: if (sensor.getType() == Sensor.TYPE_ACCELEROMETER || sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD || sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) { json.put("x-axis", value); } else if (sensor.getType() == Sensor.TYPE_ORIENTATION || sensor.getType() == Sensor.TYPE_GYROSCOPE) { json.put("azimuth", value); } else { Log.e(TAG, "Unexpected sensor type creating JSON value"); return null; } break; case 1: if (sensor.getType() == Sensor.TYPE_ACCELEROMETER || sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD || sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) { json.put("y-axis", value); } else if (sensor.getType() == Sensor.TYPE_ORIENTATION || sensor.getType() == Sensor.TYPE_GYROSCOPE) { json.put("pitch", value); } else { Log.e(TAG, "Unexpected sensor type creating JSON value"); return null; } break; case 2: if (sensor.getType() == Sensor.TYPE_ACCELEROMETER || sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD || sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) { json.put("z-axis", value); } else if (sensor.getType() == Sensor.TYPE_ORIENTATION || sensor.getType() == Sensor.TYPE_GYROSCOPE) { json.put("roll", value); } else { Log.e(TAG, "Unexpected sensor type creating JSON value"); return null; } break; default: Log.w(TAG, "Unexpected sensor value! More than three axes?!"); } axis++; } } catch (Exception e) { Log.e(TAG, "Exception creating motion JSON value", e); return null; } return json; } /** * Measures the speed change and determines the average, for the motion energy sensor. * * @param event * The sensor change event with accelerometer or linear acceleration data. */ private void doEnergySample(SensorEvent event) { float[] linAcc = null; // approximate linear acceleration if we have no special sensor for it if (!hasLinAccSensor && Sensor.TYPE_ACCELEROMETER == event.sensor.getType()) { linAcc = calcLinAcc(event.values); } else if (hasLinAccSensor && Sensor.TYPE_LINEAR_ACCELERATION == event.sensor.getType()) { linAcc = event.values; } else { // sensor is not the right type return; } // calculate speed change and adjust average if (null != linAcc) { // record the start of the motion sample if (avgSpeedCount == 0) { energySampleStart = System.currentTimeMillis(); } float timeStep = (System.currentTimeMillis() - prevEnergySampleTime) / 1000f; prevEnergySampleTime = System.currentTimeMillis(); if (timeStep > 0 && timeStep < 1) { float accLength = FloatMath.sqrt((float) (Math.pow(linAcc[0], 2) + Math.pow(linAcc[1], 2) + Math.pow(linAcc[2], 2))); // float speedChange = accLength * timeStep; // Log.v(TAG, "Speed change: " + speedChange); avgSpeedChange = (avgSpeedCount * avgSpeedChange + accLength) / (avgSpeedCount + 1); avgSpeedCount++; } } } private void doEpiSample(Sensor sensor, JSONObject json) { if (dataBuffer[sensor.getType()] == null) { dataBuffer[sensor.getType()] = new JSONArray(); } dataBuffer[sensor.getType()].put(json); if (lastLocalSampleTimes[sensor.getType()] == 0) { lastLocalSampleTimes[sensor.getType()] = System.currentTimeMillis(); } if (System.currentTimeMillis() > lastLocalSampleTimes[sensor.getType()] + localBufferTime) { // send the stuff // pass message to the MsgHandler Intent i = new Intent(context.getString(R.string.action_sense_new_data)); i.putExtra(DataPoint.SENSOR_NAME, SensorNames.ACCELEROMETER_EPI); i.putExtra(DataPoint.SENSOR_DESCRIPTION, sensor.getName()); i.putExtra( DataPoint.VALUE, "{\"interval\":" + Math.round(localBufferTime / dataBuffer[sensor.getType()].length()) + ",\"data\":" + dataBuffer[sensor.getType()].toString() + "}"); i.putExtra(DataPoint.DATA_TYPE, SenseDataTypes.JSON_TIME_SERIES); i.putExtra(DataPoint.TIMESTAMP, lastLocalSampleTimes[sensor.getType()]); context.startService(i); dataBuffer[sensor.getType()] = new JSONArray(); lastLocalSampleTimes[sensor.getType()] = System.currentTimeMillis(); if (firstTimeSend == 0) { firstTimeSend = System.currentTimeMillis(); } } } private void doFallSample(SensorEvent event) { float aX = event.values[1]; float aY = event.values[0]; float aZ = event.values[2]; float accVecSum = FloatMath.sqrt(aX * aX + aY * aY + aZ * aZ); if (fallDetector.fallDetected(accVecSum)) { sendFallMessage(true); // send msg } } public long getSampleDelay() { return sampleDelay; } /** * @return Time stamp of the oldest sample, or -1 if not all sensors have sampled yet. */ private long getOldestSampleTime() { int count = 0; long oldestSample = Long.MAX_VALUE; for (long time : lastSampleTimes) { if (time != 0) { count++; if (time < oldestSample) { oldestSample = time; } } } if (count < sensors.size()) { return -1; } else { return oldestSample; } } /** * @return true if it is too long since the sensor was registered. */ private boolean isTimeToRegister() { return motionSensingActive && !isRegistered && System.currentTimeMillis() - getOldestSampleTime() + DELAY_AFTER_REGISTRATION > sampleDelay; } /** * @return true if all active sensors have recently passed a data point. */ private boolean isTimeToUnregister() { boolean unregister = isUnregisterWhenIdle; // only unregister if all sensors have submitted a new sample long oldestSample = getOldestSampleTime(); if (oldestSample == -1) { unregister = false; } else { unregister = unregister && (lastRegistered < oldestSample); } // only unregister when sample delay is large enough unregister = unregister && sampleDelay > DELAY_AFTER_REGISTRATION; // only unregister when fall detection is not active unregister = unregister && !isFallDetectMode; // only unregister when energy sample has finished unregister = unregister && (!isEnergyMode || (energySampleStart != 0 && System.currentTimeMillis() - energySampleStart > ENERGY_SAMPLE_LENGTH)); return unregister; } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // do nothing } @SuppressWarnings("deprecation") @Override public void onSensorChanged(SensorEvent event) { if (!motionSensingActive) { Log.w(TAG, "Motion sensor value received when sensor is inactive! (Re)try stopping..."); stopMotionSensing(); return; } final Sensor sensor = event.sensor; // pass sensor value to fall detector first if (isFallDetectMode && sensor.getType() == Sensor.TYPE_ACCELEROMETER) { doFallSample(event); } // if motion energy sensor is active, determine energy of every sample boolean isEnergySample = !hasLinAccSensor && Sensor.TYPE_ACCELEROMETER == sensor.getType() || hasLinAccSensor && Sensor.TYPE_LINEAR_ACCELERATION == sensor.getType(); if (isEnergyMode && isEnergySample) { doEnergySample(event); } // check sensor delay if (System.currentTimeMillis() > lastSampleTimes[sensor.getType()] + sampleDelay) { lastSampleTimes[sensor.getType()] = System.currentTimeMillis(); } else { // new sample is too soon // unregister when sensor listener when we can if (isTimeToUnregister()) { // unregister the listener and start again in sampleDelay seconds unregisterSensors(); motionHandler.postDelayed(motionThread = new Runnable() { @Override public void run() { registerSensors(); } }, sampleDelay - DELAY_AFTER_REGISTRATION); } return; } // Epi-mode is only interested in the accelerometer if (isEpiMode && sensor.getType() != Sensor.TYPE_ACCELEROMETER) { return; } // determine sensor name String sensorName = ""; switch (sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: sensorName = SensorNames.ACCELEROMETER; break; case Sensor.TYPE_ORIENTATION: sensorName = SensorNames.ORIENT; break; case Sensor.TYPE_MAGNETIC_FIELD: sensorName = SensorNames.MAGNETIC_FIELD; break; case Sensor.TYPE_GYROSCOPE: sensorName = SensorNames.GYRO; break; case Sensor.TYPE_LINEAR_ACCELERATION: sensorName = SensorNames.LIN_ACCELERATION; break; default: Log.w(TAG, "Unexpected sensor type: " + sensor.getType()); return; } // prepare JSON object to send to MsgHandler final JSONObject json = createJsonValue(event); if (null == json) { // error occurred creating the JSON object return; } // add the data to the buffer if we are in Epi-mode: if (isEpiMode) { doEpiSample(sensor, json); } else { sendNormalMessage(sensor, sensorName, json); } // send motion energy message if (isEnergyMode && isEnergySample) { sendEnergyMessage(); } } /** * Registers for updates from the device's motion sensors. */ private synchronized void registerSensors() { if (!isRegistered) { // Log.v(TAG, "Register the motion sensor for updates"); SensorManager mgr = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); int delay = isFallDetectMode || isEpiMode || isEnergyMode ? SensorManager.SENSOR_DELAY_GAME : SensorManager.SENSOR_DELAY_NORMAL; for (Sensor sensor : sensors) { mgr.registerListener(this, sensor, delay); } isRegistered = true; } else { // Log.v(TAG, "Did not register for motion sensor updates: already registered"); } } /** * Sends message with average motion energy to the MsgHandler. */ private void sendEnergyMessage() { if (avgSpeedCount > 1) { // Log.v(TAG, NAME_MOTION_ENERGY + " value. Count: " + avgSpeedCount); // round to three decimals float value = BigDecimal.valueOf(avgSpeedChange).setScale(3, 0).floatValue(); // prepare intent to send to MsgHandler Intent i = new Intent(context.getString(R.string.action_sense_new_data)); i.putExtra(DataPoint.SENSOR_NAME, SensorNames.MOTION_ENERGY); i.putExtra(DataPoint.SENSOR_DESCRIPTION, SensorNames.MOTION_ENERGY); i.putExtra(DataPoint.VALUE, value); i.putExtra(DataPoint.DATA_TYPE, SenseDataTypes.FLOAT); i.putExtra(DataPoint.TIMESTAMP, SNTP.getInstance().getTime()); context.startService(i); } avgSpeedChange = 0; avgSpeedCount = 0; } private void sendFallMessage(boolean fall) { Intent i = new Intent(context.getString(R.string.action_sense_new_data)); i.putExtra(DataPoint.SENSOR_NAME, SensorNames.FALL_DETECTOR); i.putExtra(DataPoint.SENSOR_DESCRIPTION, fallDetector.demo ? "demo fall" : "human fall"); i.putExtra(DataPoint.VALUE, fall); i.putExtra(DataPoint.DATA_TYPE, SenseDataTypes.BOOL); i.putExtra(DataPoint.TIMESTAMP, SNTP.getInstance().getTime()); context.startService(i); } private void sendNormalMessage(Sensor sensor, String sensorName, JSONObject json) { Intent i = new Intent(context.getString(R.string.action_sense_new_data)); i.putExtra(DataPoint.SENSOR_NAME, sensorName); i.putExtra(DataPoint.SENSOR_DESCRIPTION, sensor.getName()); i.putExtra(DataPoint.VALUE, json.toString()); i.putExtra(DataPoint.DATA_TYPE, SenseDataTypes.JSON); i.putExtra(DataPoint.TIMESTAMP, SNTP.getInstance().getTime()); context.startService(i); } public void setSampleDelay(long sampleDelay) { this.sampleDelay = sampleDelay; } @SuppressWarnings("deprecation") public void startMotionSensing(long sampleDelay) { motionHandler = new Handler(); final SharedPreferences mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); isEpiMode = mainPrefs.getBoolean(Motion.EPIMODE, false); isEnergyMode = mainPrefs.getBoolean(Motion.MOTION_ENERGY, false); isUnregisterWhenIdle = mainPrefs.getBoolean(Motion.UNREG, true); if (isEpiMode) { sampleDelay = 0; Log.v(TAG, "Start epi state sensor"); context.startService(new Intent(context, EpiStateMonitor.class)); } // check if the fall detector is enabled isFallDetectMode = mainPrefs.getBoolean(Motion.FALL_DETECT, false); if (fallDetector.demo == mainPrefs.getBoolean(Motion.FALL_DETECT_DEMO, false)) { isFallDetectMode = true; Log.v(TAG, "Start epi state sensor"); context.startService(new Intent(context, EpiStateMonitor.class)); } if (firstStart && isFallDetectMode) { sendFallMessage(false); firstStart = false; } SensorManager mgr = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); sensors = new ArrayList<Sensor>(); // add accelerometer if (null != mgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)) { sensors.add(mgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)); } if (!isEpiMode) { // add orientation sensor if (null != mgr.getDefaultSensor(Sensor.TYPE_ORIENTATION)) { sensors.add(mgr.getDefaultSensor(Sensor.TYPE_ORIENTATION)); } // add gyroscope if (null != mgr.getDefaultSensor(Sensor.TYPE_GYROSCOPE)) { sensors.add(mgr.getDefaultSensor(Sensor.TYPE_GYROSCOPE)); } // add linear acceleration if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { // only devices with gingerbread+ have linear acceleration sensors if (null != mgr.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION)) { sensors.add(mgr.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION)); hasLinAccSensor = true; } } } motionSensingActive = true; setSampleDelay(sampleDelay); registerSensors(); startWakeUpAlarms(); enableScreenOffListener(true); } private void enableScreenOffListener(boolean enable) { if (enable) { // Register the receiver for SCREEN OFF events IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF); context.registerReceiver(screenOffListener, filter); } else { // Unregister the receiver for SCREEN OFF events try { context.unregisterReceiver(screenOffListener); } catch (IllegalArgumentException e) { // Log.v(TAG, "Ignoring exception when unregistering screen off listener"); } } } /** * Sets a periodic alarm that makes sure the the device is awake for a short while for every * sample. */ private void startWakeUpAlarms() { // register receiver for wake up alarm wakeReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Log.v(TAG, "Wake up! " + new SimpleDateFormat("k:mm:ss.SSS").format(new Date())); if (null == wakeLock) { PowerManager powerMgr = (PowerManager) context .getSystemService(Context.POWER_SERVICE); wakeLock = powerMgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); } if (!wakeLock.isHeld()) { Log.i(TAG, "Acquire wake lock for 500ms"); wakeLock.acquire(500); } else { // Log.v(TAG, "Wake lock already held"); } if (isTimeToRegister()) { // Log.v(TAG, "Time to register!"); registerSensors(); } } }; context.registerReceiver(wakeReceiver, new IntentFilter(ACTION_WAKEUP_ALARM)); // schedule alarm to go off and wake up the receiver Intent wakeUp = new Intent(ACTION_WAKEUP_ALARM); PendingIntent operation = PendingIntent.getBroadcast(context, ALARM_ID, wakeUp, 0); final AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); mgr.cancel(operation); mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, sampleDelay, operation); } /** * Unregisters the listener for updates from the motion sensors, and stops waking up the device * for sampling. */ public void stopMotionSensing() { // Log.v(TAG, "Stop motion sensor"); try { motionSensingActive = false; unregisterSensors(); if (motionThread != null) { motionHandler.removeCallbacks(motionThread); motionThread = null; } } catch (Exception e) { Log.e(TAG, e.getMessage()); } if (isEpiMode || isFallDetectMode) { Log.v(TAG, "Stop epi state sensor"); context.stopService(new Intent(context, EpiStateMonitor.class)); } enableScreenOffListener(false); stopWakeUpAlarms(); } /** * Stops the periodic alarm to wake up the device and take a sample. */ private void stopWakeUpAlarms() { // unregister wake up receiver try { context.unregisterReceiver(wakeReceiver); } catch (IllegalArgumentException e) { // do nothing } // cancel the wake up alarm Intent wakeUp = new Intent(ACTION_WAKEUP_ALARM); PendingIntent operation = PendingIntent.getBroadcast(context, ALARM_ID, wakeUp, 0); final AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); mgr.cancel(operation); } private synchronized void unregisterSensors() { if (isRegistered) { // Log.v(TAG, "Unregister the motion sensor for updates"); ((SensorManager) context.getSystemService(Context.SENSOR_SERVICE)) .unregisterListener(this); lastRegistered = System.currentTimeMillis(); } else { // Log.v(TAG, "Did not unregister for motion sensor updates: already unregistered"); } isRegistered = false; } }
package sopc2dts.lib.components; import java.util.Vector; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import sopc2dts.generators.AbstractSopcGenerator; import sopc2dts.lib.SopcInfoAssignment; import sopc2dts.lib.SopcInfoConnection; import sopc2dts.lib.SopcInfoElementWithParams; public class SopcInfoComponent extends SopcInfoElementWithParams { public enum parameter_action { NONE, CMACRCO, ALL }; private String instanceName; private String version; private int addr = 0; private Vector<SopcInfoInterface> vInterfaces = new Vector<SopcInfoInterface>(); private SopcComponentDescription scd; public SopcInfoComponent(ContentHandler p, XMLReader xr, SopcComponentDescription scd, String iName, String ver) { super(p,xr); this.setScd(scd); this.setInstanceName(iName); version = ver; } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if(localName.equalsIgnoreCase("interface")) { getInterfaces().add(new SopcInfoInterface(this, xmlReader, atts.getValue("name"), atts.getValue("kind"), this)); } else { super.startElement(uri, localName, qName, atts); } } protected String getRegForDTS(int indentLevel, SopcInfoComponent master) { String res = ""; for(SopcInfoInterface intf : vInterfaces) { if(intf.isMemorySlave()) { //Check all interfaces for a connection to master SopcInfoConnection conn = null; for(int i=0; (i<intf.getConnections().size()) && (conn==null); i++) { if(intf.getConnections().get(i).getMasterModule().equals(master)) { conn = intf.getConnections().get(i); } } if((conn!=null) && (intf!=null)) { if(res.length()==0) { res = AbstractSopcGenerator.indent(indentLevel) + "reg = <"; } res += " 0x" + Integer.toHexString(conn.getBaseAddress()) + " 0x" + Integer.toHexString(intf.getAddressableSize()); } } } if(res.length()>0) { res += ">;\n"; } return res; } protected String getInterruptsForDTS(int indentLevel) { String interrupts =AbstractSopcGenerator.indent(indentLevel) + "interrupts = <"; SopcInfoComponent irqParent = null; for(SopcInfoInterface intf : getInterfaces()) { if(intf.getKind().equalsIgnoreCase("interrupt_sender")) { if(irqParent==null) { irqParent = intf.getConnections().get(0).getMasterModule(); } if(intf.getConnections().get(0).getMasterModule().equals(irqParent)) { interrupts += " " + intf.getConnections().get(0).getParamValue("irqNumber"); } } } if(irqParent!=null) { return AbstractSopcGenerator.indent(indentLevel) + "interrupt-parent = < &" + irqParent.getInstanceName() + " >;\n" + interrupts + " >;\n"; } else { return ""; } } public String toDts(int indentLevel, SopcInfoComponent.parameter_action paramAction) { return toDts(indentLevel, paramAction, null, true); } public String toDts(int indentLevel, SopcInfoComponent.parameter_action paramAction, SopcInfoConnection conn, Boolean endComponent) { int tmpAddr = getAddrFromConnection(conn); String res = AbstractSopcGenerator.indent(indentLevel++) + getInstanceName() + ": " + getScd().getGroup() + "@0x" + Integer.toHexString(tmpAddr) + " {\n"; res += toDtsExtrasFirst(indentLevel, conn, endComponent); if((getScd().getGroup().equalsIgnoreCase("cpu"))||(getScd().getGroup().equalsIgnoreCase("memory"))) { res += AbstractSopcGenerator.indent(indentLevel) + "device-type = \"" + getScd().getGroup() +"\";\n"; } res += AbstractSopcGenerator.indent(indentLevel) + "compatible = " + getScd().getCompatible(version); res += ";\n"; if (getScd().getGroup().equalsIgnoreCase("cpu")) { res += AbstractSopcGenerator.indent(indentLevel) + "reg = <" + getAddr() + ">;\n"; } else if(conn!=null) { res += getRegForDTS(indentLevel, conn.getMasterModule()); } res += getInterruptMasterDesc(indentLevel); res += getInterruptsForDTS(indentLevel); for(SopcComponentDescription.SICAutoParam ap : getScd().vAutoParams) { String ass = getParamValue(ap.sopcInfoName); if(ass!=null) { res += AbstractSopcGenerator.indent(indentLevel) + ap.dtsName + " = <" + ass + ">;\n"; } else if(ap.dtsName.equalsIgnoreCase("clock-frequency")) { res += AbstractSopcGenerator.indent(indentLevel) + ap.dtsName + " = <" + getClockRate() + ">;\n"; } else if(ap.dtsName.equalsIgnoreCase("regstep")) { res += AbstractSopcGenerator.indent(indentLevel) + ap.dtsName + " = <4>;\n"; } } if((paramAction != parameter_action.NONE)&&(getParams().size()>0)) { res += AbstractSopcGenerator.indent(indentLevel) + "//Dumping SOPC parameters...\n"; for(SopcInfoAssignment ass : getParams()) { String assName = ass.getName(); if(assName.startsWith("embeddedsw.CMacro.")) { assName = assName.substring(18); } else if(paramAction == parameter_action.CMACRCO) { assName = null; } if(assName!=null) { assName = assName.replace('_', '-'); res += AbstractSopcGenerator.indent(indentLevel) + scd.getVendor() + "," + assName + " = \"" + ass.getValue() + "\";\n"; } } } res += toDtsExtras(indentLevel, conn, endComponent); if(endComponent) res += AbstractSopcGenerator.indent(--indentLevel) + "};\n"; return res; } private String getInterruptMasterDesc(int indentLevel) { for(SopcInfoInterface intf : getInterfaces()) { if(intf.getKind().equalsIgnoreCase("interrupt_receiver")) { return AbstractSopcGenerator.indent(indentLevel) + "interrupt-controller;\n" + AbstractSopcGenerator.indent(indentLevel) + "#interrupt-cells = <1>;\n"; } } return ""; } public String toDtsExtrasFirst(int indentLevel, SopcInfoConnection conn, Boolean endComponent) { return ""; } public String toDtsExtras(int indentLevel, SopcInfoConnection conn, Boolean endComponent) { return ""; } @Override public String getElementName() { return "module"; } public SopcInfoInterface getInterfaceByName(String ifName) { for(SopcInfoInterface intf : getInterfaces()) { if(intf.getName().equalsIgnoreCase(ifName)) { return intf; } } return null; } public Boolean isUsefullForDTS() { return true; } public void setScd(SopcComponentDescription scd) { this.scd = scd; } public SopcComponentDescription getScd() { return scd; } public void setInstanceName(String instanceName) { this.instanceName = instanceName; } public String getInstanceName() { return instanceName; } public void setInterfaces(Vector<SopcInfoInterface> vInterfaces) { this.vInterfaces = vInterfaces; } public Vector<SopcInfoInterface> getInterfaces() { return vInterfaces; } public void setAddr(int addr) { this.addr = addr; } public int getAddr() { return addr; } public int getAddrFromMaster() { return getAddrFromMaster(0); } public int getAddrFromMaster(int index) { for(SopcInfoInterface intf : vInterfaces) { if(intf.isMemorySlave()) { if(intf.getConnections().size()>index) { return intf.getConnections().get(index).getBaseAddress(); } } } return -1; } protected int getAddrFromConnection(SopcInfoConnection conn) { return (conn==null ? getAddr() : conn.getBaseAddress()); } public int getClockRate() { int rate = 0; for(SopcInfoInterface intf : vInterfaces) { if(intf.isClockInput()) { rate = Integer.decode(intf.getConnections().get(0).getMasterInterface().getParamValue("clockRate")); } } return rate; } public boolean hasMemoryMaster() { for(SopcInfoInterface intf : vInterfaces) { if(intf.isMemoryMaster()) return true; } return false; } }
package hex.genmodel; import hex.ModelCategory; import java.io.*; import hex.genmodel.prediction.*; public class PredictCsv { private static String modelClassName; private static String inputCSVFileName; private static String outputCSVFileName; private static int haveHeaders = -1; private static void usage() { System.out.println(""); System.out.println("usage: java [...java args...] PredictCsv --header --model modelClassName --input inputCSVFileName --output outputCSVFileName"); System.out.println(""); System.out.println(" model class name is something like GBMModel_blahblahblahblah."); System.out.println(""); System.out.println(" inputCSVFileName is the test data set."); System.out.println(" Specifying --header is required for h2o-3."); System.out.println(""); System.out.println(" outputCSVFieName is the prediction data set (one row per test data set row)."); System.out.println(""); System.exit(1); } private static void parseArgs(String[] args) { for (int i = 0; i < args.length; i++) { String s = args[i]; switch (s) { case "--model": i++; if (i >= args.length) usage(); modelClassName = args[i]; break; case "--input": i++; if (i >= args.length) usage(); inputCSVFileName = args[i]; break; case "--output": i++; if (i >= args.length) usage(); outputCSVFileName = args[i]; break; case "--header": haveHeaders = 1; break; default: System.out.println("ERROR: Bad parameter: " + s); usage(); } } if (haveHeaders != 1) { System.out.println("ERROR: header not specified"); usage(); } if (modelClassName == null) { System.out.println("ERROR: model not specified"); usage(); } if (inputCSVFileName == null) { System.out.println("ERROR: input not specified"); usage(); } if (outputCSVFileName == null) { System.out.println("ERROR: output not specified"); usage(); } } /** * This CSV header row parser is as bare bones as it gets. * Doesn't handle funny quoting, spacing, or other issues. */ private static String[] parseHeaderRow(String line) { return line.trim().split(","); } /** * This CSV parser is as bare bones as it gets. * Our test data doesn't have funny quoting, spacing, or other issues. * Can't handle cases where the number of data columns is less than the number of header columns. */ private static RowData parseDataRow(String line, String[] inputColumnNames) { String[] inputData = line.trim().split(","); // Assemble the input values for the row. RowData row = new RowData(); for (int i = 0; i < inputColumnNames.length; i++) { String columnName = inputColumnNames[i]; String cellData = inputData[i]; switch (cellData) { case "": case "NA": case "N/A": case "-": continue; default: row.put(columnName, cellData); } } return row; } private static String myDoubleToString(double d) { if (Double.isNaN(d)) { return "NA"; } return Double.toHexString(d); } /** * CSV reader and predictor test program. * * @param args Command-line args. * @throws Exception */ public static void main(String[] args) throws Exception { parseArgs(args); hex.genmodel.GenModel rawModel; rawModel = (hex.genmodel.GenModel) Class.forName(modelClassName).newInstance(); EasyPredictModelWrapper model = new EasyPredictModelWrapper(rawModel); ModelCategory category = model.getModelCategory(); BufferedReader input = new BufferedReader(new FileReader(inputCSVFileName)); BufferedWriter output = new BufferedWriter(new FileWriter(outputCSVFileName)); // Emit outputCSV column names. switch (category) { case AutoEncoder: output.write(model.getHeader()); break; case Binomial: case Multinomial: output.write("predict"); String[] responseDomainValues = model.getResponseDomainValues(); for (String s : responseDomainValues) { output.write(","); output.write(s); } break; case Clustering: output.write("cluster"); break; case Regression: output.write("predict"); break; default: throw new Exception("Unknown model category " + category); } output.write("\n"); // Loop over inputCSV one row at a time. int lineNum = 0; String line; String[] inputColumnNames = null; try { while ((line = input.readLine()) != null) { lineNum++; // Handle the header. if (lineNum == 1) { inputColumnNames = parseHeaderRow(line); continue; } // Parse the CSV line. Don't handle quoted commas. This isn't a parser test. RowData row = parseDataRow(line, inputColumnNames); // Do the prediction. // Emit the result to the output file. switch (category) { case AutoEncoder: { AutoEncoderModelPrediction p = model.predictAutoEncoder(row); throw new Exception("TODO"); // break; } case Binomial: { BinomialModelPrediction p = model.predictBinomial(row); output.write(p.label); output.write(","); for (int i = 0; i < p.classProbabilities.length; i++) { if (i > 0) { output.write(","); } output.write(myDoubleToString(p.classProbabilities[i])); } break; } case Multinomial: { MultinomialModelPrediction p = model.predictMultinomial(row); output.write(p.label); output.write(","); for (int i = 0; i < p.classProbabilities.length; i++) { if (i > 0) { output.write(","); } output.write(myDoubleToString(p.classProbabilities[i])); } break; } case Clustering: { ClusteringModelPrediction p = model.predictClustering(row); output.write(myDoubleToString(p.cluster)); break; } case Regression: { RegressionModelPrediction p = model.predictRegression(row); output.write(myDoubleToString(p.value)); break; } default: throw new Exception("Unknown model category " + category); } output.write("\n"); } } catch (Exception e) { System.out.println("Caught exception on line " + lineNum); System.out.println(""); e.printStackTrace(); System.exit(1); } // Clean up. output.close(); input.close(); // Predictions were successfully generated. Calling program can now compare them with something. System.exit(0); } }