answer
stringlengths
17
10.2M
package com.ctrip.ops.sysdev.decoder; import java.util.HashMap; import java.util.Map; import org.joda.time.DateTime; import org.json.simple.JSONValue; import org.json.simple.parser.ParseException; import org.apache.log4j.Logger; public class JsonDecoder implements IDecode { private static final Logger logger = Logger .getLogger(JsonDecoder.class.getName()); @SuppressWarnings("unchecked") @Override public Map<String, Object> decode(final String message) { Map<String, Object> event = null; try { event = (HashMap<String, Object>) JSONValue .parseWithException(message); } catch (Exception e) { logger.warn("failed to json parse message to a Map"); event = new HashMap<String, Object>() { { put("message", message); put("@timestamp", DateTime.now()); } }; } if (event == null) { event = new HashMap<String, Object>() { { put("message", message); put("@timestamp", DateTime.now()); } }; } else { if (!event.containsKey("@timestamp")) { event.put("@timestamp", DateTime.now()); } } return event; } }
package com.diozero.api; import org.pmw.tinylog.Logger; import com.diozero.internal.spi.PwmOutputDeviceFactoryInterface; import com.diozero.internal.spi.PwmOutputDeviceInterface; import com.diozero.util.RuntimeIOException; import com.diozero.util.SleepUtil; /** * Represent a generic PWM output GPIO. * Note the following BCM GPIO pins provide hardware PWM support: * 12 (phys 32, wPi 26), 13 (phys 33, wPi 23), 18 (phys 12, wPi 1), 19 (phys 35, wPi 24) * Any other pin will revert to software controlled PWM (not very good) */ public class PwmOutputDevice extends GpioDevice { public static final int INFINITE_ITERATIONS = -1; private PwmOutputDeviceInterface device; private boolean running; private Thread backgroundThread; public PwmOutputDevice(int pinNumber) throws RuntimeIOException { this(pinNumber, 0); } public PwmOutputDevice(int pinNumber, float initialValue) throws RuntimeIOException { this(DeviceFactoryHelper.getNativeDeviceFactory(), pinNumber, initialValue); } public PwmOutputDevice(PwmOutputDeviceFactoryInterface pwmDeviceFactory, int pinNumber, float initialValue) throws RuntimeIOException { this(pwmDeviceFactory.provisionPwmOutputPin(pinNumber, initialValue)); } public PwmOutputDevice(PwmOutputDeviceInterface device) { super(device.getPin()); this.device = device; } @Override public void close() { Logger.debug("close()"); stopLoops(); if (backgroundThread != null) { Logger.info("Interrupting background thread " + backgroundThread.getName()); backgroundThread.interrupt(); } Logger.info("Setting value to 0"); try { device.setValue(0); } catch (RuntimeIOException e) { } if (device != null) { device.close(); } Logger.debug("device closed"); } protected void onOffLoop(float onTime, float offTime, int n, boolean background) throws RuntimeIOException { stopLoops(); if (background) { DioZeroScheduler.getDaemonInstance().execute(() -> { backgroundThread = Thread.currentThread(); onOffLoop(onTime, offTime, n); Logger.info("Background on-off loop finished"); backgroundThread = null; }); } else { onOffLoop(onTime, offTime, n); } } private void onOffLoop(float onTime, float offTime, int n) throws RuntimeIOException { if (n > 0) { running = true; for (int i=0; i<n && running; i++) { onOff(onTime, offTime); } running = false; } else if (n == INFINITE_ITERATIONS) { running = true; while (running) { onOff(onTime, offTime); } } } protected void fadeInOutLoop(float fadeTime, int steps, int iterations, boolean background) throws RuntimeIOException { stopLoops(); if (background) { DioZeroScheduler.getDaemonInstance().execute(() -> { backgroundThread = Thread.currentThread(); fadeInOutLoop(fadeTime, steps, iterations); Logger.info("Background fade in-out loop finished"); backgroundThread = null; }); } else { fadeInOutLoop(fadeTime, steps, iterations); } } private void fadeInOutLoop(float fadeTime, int steps, int iterations) throws RuntimeIOException { float sleep_time = fadeTime / steps; float delta = 1f / steps; if (iterations > 0) { running = true; for (int i=0; i<iterations && running; i++) { fadeInOut(sleep_time, delta); } running = false; } else if (iterations == INFINITE_ITERATIONS) { running = true; while (running) { fadeInOut(sleep_time, delta); } } } private void fadeInOut(float sleepTime, float delta) throws RuntimeIOException { float value = 0; while (value <= 1 && running) { setValueInternal(value); SleepUtil.sleepSeconds(sleepTime); value += delta; } value = 1; while (value >= 0 && running) { setValueInternal(value); SleepUtil.sleepSeconds(sleepTime); value -= delta; } } private void stopLoops() { running = false; } private void onOff(float onTime, float offTime) throws RuntimeIOException { setValueInternal(1); SleepUtil.sleepSeconds(onTime); setValueInternal(0); SleepUtil.sleepSeconds(offTime); } private void setValueInternal(float value) throws RuntimeIOException { device.setValue(value); } // Exposed operations public void on() throws RuntimeIOException { stopLoops(); setValueInternal(1); } public void off() throws RuntimeIOException { stopLoops(); setValueInternal(0); } public void toggle() throws RuntimeIOException { stopLoops(); setValueInternal(1 - device.getValue()); } public boolean isOn() throws RuntimeIOException { return device.getValue() > 0; } public float getValue() throws RuntimeIOException { return device.getValue(); } public void setValue(float value) throws RuntimeIOException { stopLoops(); setValueInternal(value); } }
package com.devesion.obd.command; import lombok.ToString; /** * Skeletal implementation of {@link com.devesion.obd.command.ObdCommand} interface. */ @ToString public abstract class AbstractCommand implements ObdCommand { private CommandResult result; public CommandResult getResult() { return result; } @Override public void setResult(CommandResult result) { this.result = result; } @Override public boolean checkResponseEnabled() { return true; } }
package verification; import java.awt.AWTError; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Properties; import java.util.prefs.Preferences; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import lpn.parser.Abstraction; import lpn.parser.LhpnFile; import lpn.parser.Place; import lpn.parser.Transition; import lpn.parser.Variable; import lpn.parser.LpnDecomposition.Component; import lpn.parser.LpnDecomposition.LpnComponentList; import lpn.parser.LpnDecomposition.LpnProcess; import main.Gui; import main.Log; import verification.platu.main.Options; import verification.platu.project.Project; import verification.platu.stategraph.StateGraph; import verification.timed_state_exploration.zoneProject.Zone; import biomodel.gui.PropertyList; import biomodel.util.Utility; /** * This class creates a GUI front end for the Verification tool. It provides the * necessary options to run an atacs simulation of the circuit and manage the * results from the BioSim GUI. * * @author Kevin Jones */ public class Verification extends JPanel implements ActionListener, Runnable { private static final long serialVersionUID = -5806315070287184299L; private JButton save, run, viewCircuit, viewTrace, viewLog, addComponent, removeComponent, addSFile, addLPN, removeLPN; private JLabel algorithm, timingMethod, timingOptions, otherOptions, otherOptions2, compilation, bddSizeLabel, advTiming, abstractLabel, listLabel; public JRadioButton untimed, geometric, posets, bag, bap, baptdc, verify, vergate, orbits, search, trace, bdd, dbm, smt, untimedStateSearch, lhpn, view, none, simplify, abstractLhpn, dbm2, splitZone; private JCheckBox abst, partialOrder, dot, verbose, graph, untimedPOR, decomposeLPN, multipleLPNs, genrg, timsubset, superset, infopt, orbmatch, interleav, prune, disabling, nofail, noproj, keepgoing, explpn, nochecks, reduction, newTab, postProc, redCheck, xForm2, expandRate, useGraphs; private JTextField bddSize, backgroundField, componentField; private JList sList; private DefaultListModel sListModel; private ButtonGroup timingMethodGroup, algorithmGroup, abstractionGroup; private String directory, separator, root, verFile, oldBdd, sourceFileNoPath; public String verifyFile; private boolean change, atacs, lema; private PropertyList componentList, lpnList; private AbstPane abstPane; private Log log; private Gui biosim; /** * This is the constructor for the Verification class. It initializes all * the input fields, puts them on panels, adds the panels to the frame, and * then displays the frame. */ public Verification(String directory, String verName, String filename, Log log, Gui biosim, boolean lema, boolean atacs) { if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } this.atacs = atacs; this.lema = lema; this.biosim = biosim; this.log = log; this.directory = directory; verFile = verName + ".ver"; String[] tempArray = filename.split("\\."); String traceFilename = tempArray[0] + ".trace"; File traceFile = new File(traceFilename); String[] tempDir = directory.split(separator); root = tempDir[0]; for (int i = 1; i < tempDir.length - 1; i++) { root = root + separator + tempDir[i]; } this.setMaximumSize(new Dimension(300,300)); this.setMinimumSize(new Dimension(300,300)); JPanel abstractionPanel = new JPanel(); abstractionPanel.setMaximumSize(new Dimension(1000, 35)); JPanel timingRadioPanel = new JPanel(); timingRadioPanel.setMaximumSize(new Dimension(1000, 35)); JPanel timingCheckBoxPanel = new JPanel(); timingCheckBoxPanel.setMaximumSize(new Dimension(1000, 30)); JPanel otherPanel = new JPanel(); otherPanel.setMaximumSize(new Dimension(1000, 35)); JPanel preprocPanel = new JPanel(); preprocPanel.setMaximumSize(new Dimension(1000, 700)); JPanel algorithmPanel = new JPanel(); algorithmPanel.setMaximumSize(new Dimension(1000, 35)); JPanel buttonPanel = new JPanel(); JPanel compilationPanel = new JPanel(); compilationPanel.setMaximumSize(new Dimension(1000, 35)); JPanel advancedPanel = new JPanel(); advancedPanel.setMaximumSize(new Dimension(1000, 35)); JPanel bddPanel = new JPanel(); bddPanel.setMaximumSize(new Dimension(1000, 35)); JPanel pruningPanel = new JPanel(); pruningPanel.setMaximumSize(new Dimension(1000, 35)); JPanel advTimingPanel = new JPanel(); advTimingPanel.setMaximumSize(new Dimension(1000, 62)); advTimingPanel.setPreferredSize(new Dimension(1000, 62)); bddSize = new JTextField(""); bddSize.setPreferredSize(new Dimension(40, 18)); oldBdd = bddSize.getText(); componentField = new JTextField(""); componentList = new PropertyList(""); lpnList = new PropertyList(""); abstractLabel = new JLabel("Abstraction:"); algorithm = new JLabel("Verification Algorithm:"); timingMethod = new JLabel("Timing Method:"); timingOptions = new JLabel("Timing Options:"); otherOptions = new JLabel("Other Options:"); otherOptions2 = new JLabel("Other Options:"); compilation = new JLabel("Compilation Options:"); bddSizeLabel = new JLabel("BDD Linkspace Size:"); advTiming = new JLabel("Timing Options:"); //preprocLabel = new JLabel("Preprocess Command:"); listLabel = new JLabel("Assembly Files:"); JPanel labelPane = new JPanel(); labelPane.add(listLabel); sListModel = new DefaultListModel(); sList = new JList(sListModel); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(260, 200)); scroll.setPreferredSize(new Dimension(276, 132)); scroll.setViewportView(sList); JPanel scrollPane = new JPanel(); scrollPane.add(scroll); addSFile = new JButton("Add File"); addSFile.addActionListener(this); JPanel buttonPane = new JPanel(); buttonPane.add(addSFile); //preprocStr = new JTextField(); //preprocStr.setPreferredSize(new Dimension(500, 18)); // Initializes the radio buttons and check boxes // Abstraction Options none = new JRadioButton("None"); simplify = new JRadioButton("Simplification"); abstractLhpn = new JRadioButton("Abstraction"); // Timing Methods if (atacs) { untimed = new JRadioButton("Untimed"); geometric = new JRadioButton("Geometric"); posets = new JRadioButton("POSETs"); bag = new JRadioButton("BAG"); bap = new JRadioButton("BAP"); baptdc = new JRadioButton("BAPTDC"); untimed.addActionListener(this); geometric.addActionListener(this); posets.addActionListener(this); bag.addActionListener(this); bap.addActionListener(this); baptdc.addActionListener(this); } else { untimedStateSearch = new JRadioButton("Untimed"); bdd = new JRadioButton("BDD"); dbm = new JRadioButton("DBM"); smt = new JRadioButton("SMT"); dbm2 = new JRadioButton("DBM2"); splitZone = new JRadioButton("Split Zone"); bdd.addActionListener(this); dbm.addActionListener(this); smt.addActionListener(this); dbm2.addActionListener(this); splitZone.addActionListener(this); } lhpn = new JRadioButton("LPN"); view = new JRadioButton("View"); lhpn.addActionListener(this); view.addActionListener(this); // Basic Timing Options abst = new JCheckBox("Abstract"); partialOrder = new JCheckBox("Partial Order"); abst.addActionListener(this); partialOrder.addActionListener(this); // Other Basic Options dot = new JCheckBox("Dot"); verbose = new JCheckBox("Verbose"); graph = new JCheckBox("Show State Graph"); untimedPOR = new JCheckBox("Use Partial Orders"); decomposeLPN = new JCheckBox("Decompose LPN into components"); multipleLPNs = new JCheckBox("Multiple LPNs"); dot.addActionListener(this); verbose.addActionListener(this); graph.addActionListener(this); untimedPOR.addActionListener(this); decomposeLPN.addActionListener(this); multipleLPNs.addActionListener(this); // Verification Algorithms verify = new JRadioButton("Verify"); vergate = new JRadioButton("Verify Gates"); orbits = new JRadioButton("Orbits"); search = new JRadioButton("Search"); trace = new JRadioButton("Trace"); verify.addActionListener(this); vergate.addActionListener(this); orbits.addActionListener(this); search.addActionListener(this); trace.addActionListener(this); // Compilations Options newTab = new JCheckBox("New Tab"); postProc = new JCheckBox("Post Processing"); redCheck = new JCheckBox("Redundancy Check"); xForm2 = new JCheckBox("Don't Use Transform 2"); expandRate = new JCheckBox("Expand Rate"); newTab.addActionListener(this); postProc.addActionListener(this); redCheck.addActionListener(this); xForm2.addActionListener(this); expandRate.addActionListener(this); // Advanced Timing Options genrg = new JCheckBox("Generate RG"); timsubset = new JCheckBox("Subsets"); superset = new JCheckBox("Supersets"); infopt = new JCheckBox("Infinity Optimization"); orbmatch = new JCheckBox("Orbits Match"); interleav = new JCheckBox("Interleave"); prune = new JCheckBox("Prune"); disabling = new JCheckBox("Disabling"); nofail = new JCheckBox("No fail"); noproj = new JCheckBox("No project"); keepgoing = new JCheckBox("Keep going"); explpn = new JCheckBox("Expand LPN"); useGraphs = new JCheckBox("Use Graph Storage"); genrg.addActionListener(this); timsubset.addActionListener(this); superset.addActionListener(this); infopt.addActionListener(this); orbmatch.addActionListener(this); interleav.addActionListener(this); prune.addActionListener(this); disabling.addActionListener(this); nofail.addActionListener(this); noproj.addActionListener(this); keepgoing.addActionListener(this); explpn.addActionListener(this); useGraphs.addActionListener(this); // Other Advanced Options nochecks = new JCheckBox("No checks"); reduction = new JCheckBox("Reduction"); nochecks.addActionListener(this); reduction.addActionListener(this); // Component List addComponent = new JButton("Add Component"); removeComponent = new JButton("Remove Component"); GridBagConstraints constraints = new GridBagConstraints(); JPanel componentPanel = Utility.createPanel(this, "Components", componentList, addComponent, removeComponent, null); constraints.gridx = 0; constraints.gridy = 1; // LPN List addLPN = new JButton("Add LPN"); removeLPN = new JButton("Remove LPN"); //divideLPN1 = new JButton("Divide LPN into Modules"); GridBagConstraints gridBagConstraints = new GridBagConstraints(); JPanel LPNPanel = Utility.createPanel(this, "LPNs", lpnList, addLPN, removeLPN, null); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; abstractionGroup = new ButtonGroup(); timingMethodGroup = new ButtonGroup(); algorithmGroup = new ButtonGroup(); none.setSelected(true); if (lema) { dbm.setSelected(true); } else if (atacs) { untimed.setSelected(true); } verify.setSelected(true); // Groups the radio buttons abstractionGroup.add(none); abstractionGroup.add(simplify); abstractionGroup.add(abstractLhpn); if (lema) { timingMethodGroup.add(untimedStateSearch); timingMethodGroup.add(splitZone); timingMethodGroup.add(bdd); timingMethodGroup.add(dbm); timingMethodGroup.add(smt); timingMethodGroup.add(dbm2); } else { timingMethodGroup.add(untimed); timingMethodGroup.add(geometric); timingMethodGroup.add(posets); timingMethodGroup.add(bag); timingMethodGroup.add(bap); timingMethodGroup.add(baptdc); } timingMethodGroup.add(lhpn); timingMethodGroup.add(view); algorithmGroup.add(verify); algorithmGroup.add(vergate); algorithmGroup.add(orbits); algorithmGroup.add(search); algorithmGroup.add(trace); JPanel basicOptions = new JPanel(); JPanel advOptions = new JPanel(); // Adds the buttons to their panels abstractionPanel.add(abstractLabel); abstractionPanel.add(none); abstractionPanel.add(simplify); abstractionPanel.add(abstractLhpn); timingRadioPanel.add(timingMethod); if (atacs) { timingRadioPanel.add(untimed); timingRadioPanel.add(geometric); timingRadioPanel.add(posets); timingRadioPanel.add(bag); timingRadioPanel.add(bap); timingRadioPanel.add(baptdc); } else { timingRadioPanel.add(untimedStateSearch); timingRadioPanel.add(splitZone); timingRadioPanel.add(bdd); timingRadioPanel.add(dbm); timingRadioPanel.add(smt); timingRadioPanel.add(dbm2); } timingRadioPanel.add(lhpn); timingRadioPanel.add(view); timingCheckBoxPanel.add(timingOptions); timingCheckBoxPanel.add(abst); timingCheckBoxPanel.add(partialOrder); otherPanel.add(otherOptions); otherPanel.add(dot); otherPanel.add(verbose); otherPanel.add(graph); otherPanel.add(untimedPOR); otherPanel.add(decomposeLPN); otherPanel.add(multipleLPNs); preprocPanel.add(labelPane); preprocPanel.add(scrollPane); preprocPanel.add(buttonPane); algorithmPanel.add(algorithm); algorithmPanel.add(verify); algorithmPanel.add(vergate); algorithmPanel.add(orbits); algorithmPanel.add(search); algorithmPanel.add(trace); compilationPanel.add(compilation); compilationPanel.add(newTab); compilationPanel.add(postProc); compilationPanel.add(redCheck); compilationPanel.add(xForm2); compilationPanel.add(expandRate); advTimingPanel.add(advTiming); advTimingPanel.add(genrg); advTimingPanel.add(timsubset); advTimingPanel.add(superset); advTimingPanel.add(infopt); advTimingPanel.add(orbmatch); advTimingPanel.add(interleav); advTimingPanel.add(prune); advTimingPanel.add(disabling); advTimingPanel.add(nofail); advTimingPanel.add(noproj); advTimingPanel.add(keepgoing); advTimingPanel.add(explpn); advTimingPanel.add(useGraphs); advancedPanel.add(otherOptions2); advancedPanel.add(nochecks); advancedPanel.add(reduction); bddPanel.add(bddSizeLabel); bddPanel.add(bddSize); // load parameters Properties load = new Properties(); verifyFile = ""; try { FileInputStream in = new FileInputStream(new File(directory + separator + verFile)); load.load(in); in.close(); if (load.containsKey("verification.file")) { verifyFile = load.getProperty("verification.file"); } if (load.containsKey("verification.bddSize")) { bddSize.setText(load.getProperty("verification .bddSize")); } if (load.containsKey("verification.component")) { componentField.setText(load .getProperty("verification.component")); } Integer i = 0; while (load.containsKey("verification.compList" + i.toString())) { componentList.addItem(load.getProperty("verification.compList" + i.toString())); i++; } Integer k = 0; while (load.containsKey("verification.lpnList" + k.toString())) { lpnList.addItem(load.getProperty("verification.lpnList" + k.toString())); k++; } if (load.containsKey("verification.abstraction")) { if (load.getProperty("verification.abstraction").equals("none")) { none.setSelected(true); } else if (load.getProperty("verification.abstraction").equals( "simplify")) { simplify.setSelected(true); } else { abstractLhpn.setSelected(true); } } abstPane = new AbstPane(root + separator + verName, this, log, lema, atacs); if (load.containsKey("verification.timing.methods")) { if (atacs) { if (load.getProperty("verification.timing.methods").equals( "untimed")) { untimed.setSelected(true); } else if (load.getProperty("verification.timing.methods") .equals("geometric")) { geometric.setSelected(true); } else if (load.getProperty("verification.timing.methods") .equals("posets")) { posets.setSelected(true); } else if (load.getProperty("verification.timing.methods") .equals("bag")) { bag.setSelected(true); } else if (load.getProperty("verification.timing.methods") .equals("bap")) { bap.setSelected(true); } else if (load.getProperty("verification.timing.methods") .equals("baptdc")) { baptdc.setSelected(true); } else if (load.getProperty("verification.timing.methods") .equals("lhpn")) { lhpn.setSelected(true); } else { view.setSelected(true); } } else { if (load.getProperty("verification.timing.methods").equals( "bdd")) { bdd.setSelected(true); } else if (load.getProperty("verification.timing.methods") .equals("dbm")) { dbm.setSelected(true); } else if (load.getProperty("verification.timing.methods") .equals("smt")) { smt.setSelected(true); } else if (load.getProperty("verification.timing.methods") .equals("untimedStateSearch")) { untimedStateSearch.setSelected(true); } else if (load.getProperty("verification.timing.methods") .equals("lhpn")) { lhpn.setSelected(true); } else { view.setSelected(true); } } } if (load.containsKey("verification.Abst")) { if (load.getProperty("verification.Abst").equals("true")) { abst.setSelected(true); } } if (load.containsKey("verification.partial.order")) { if (load.getProperty("verification.partial.order").equals( "true")) { partialOrder.setSelected(true); } } if (load.containsKey("verification.Dot")) { if (load.getProperty("verification.Dot").equals("true")) { dot.setSelected(true); } } if (load.containsKey("verification.Verb")) { if (load.getProperty("verification.Verb").equals("true")) { verbose.setSelected(true); } } if (load.containsKey("verification.Graph")) { if (load.getProperty("verification.Graph").equals("true")) { graph.setSelected(true); } } if (load.containsKey("verification.UntimedPOR")) { if (load.getProperty("verification.UntimedPOR").equals("true")) { untimedPOR.setSelected(true); } } if (load.containsKey("verification.DecomposeLPN")) { if (load.getProperty("verification.DecomposeLPN").equals("true")) { decomposeLPN.setSelected(true); } } if (load.containsKey("verification.MultipleLPNs")) { if (load.getProperty("verification.MultipleLPNs").equals("true")) { multipleLPNs.setSelected(true); } } if (load.containsKey("verification.partial.order")) { if (load.getProperty("verification.partial.order").equals( "true")) { partialOrder.setSelected(true); } } if (load.containsKey("verification.partial.order")) { if (load.getProperty("verification.partial.order").equals( "true")) { partialOrder.setSelected(true); } } if (load.containsKey("verification.algorithm")) { if (load.getProperty("verification.algorithm").equals("verify")) { verify.setSelected(true); } else if (load.getProperty("verification.algorithm").equals( "vergate")) { vergate.setSelected(true); } else if (load.getProperty("verification.algorithm").equals( "orbits")) { orbits.setSelected(true); } else if (load.getProperty("verification.algorithm").equals( "search")) { search.setSelected(true); } else if (load.getProperty("verification.algorithm").equals( "trace")) { trace.setSelected(true); } } if (load.containsKey("verification.compilation.newTab")) { if (load.getProperty("verification.compilation.newTab").equals( "true")) { newTab.setSelected(true); } } if (load.containsKey("verification.compilation.postProc")) { if (load.getProperty("verification.compilation.postProc") .equals("true")) { postProc.setSelected(true); } } if (load.containsKey("verification.compilation.redCheck")) { if (load.getProperty("verification.compilation.redCheck") .equals("true")) { redCheck.setSelected(true); } } if (load.containsKey("verification.compilation.xForm2")) { if (load.getProperty("verification.compilation.xForm2").equals( "true")) { xForm2.setSelected(true); } } if (load.containsKey("verification.compilation.expandRate")) { if (load.getProperty("verification.compilation.expandRate") .equals("true")) { expandRate.setSelected(true); } } if (load.containsKey("verification.timing.genrg")) { if (load.getProperty("verification.timing.genrg") .equals("true")) { genrg.setSelected(true); } } if (load.containsKey("verification.timing.subset")) { if (load.getProperty("verification.timing.subset").equals( "true")) { timsubset.setSelected(true); } } if (load.containsKey("verification.timing.superset")) { if (load.getProperty("verification.timing.superset").equals( "true")) { superset.setSelected(true); } } if (load.containsKey("verification.timing.infopt")) { if (load.getProperty("verification.timing.infopt").equals( "true")) { infopt.setSelected(true); } } if (load.containsKey("verification.timing.orbmatch")) { if (load.getProperty("verification.timing.orbmatch").equals( "true")) { orbmatch.setSelected(true); } } if (load.containsKey("verification.timing.interleav")) { if (load.getProperty("verification.timing.interleav").equals( "true")) { interleav.setSelected(true); } } if (load.containsKey("verification.timing.prune")) { if (load.getProperty("verification.timing.prune") .equals("true")) { prune.setSelected(true); } } if (load.containsKey("verification.timing.disabling")) { if (load.getProperty("verification.timing.disabling").equals( "true")) { disabling.setSelected(true); } } if (load.containsKey("verification.timing.nofail")) { if (load.getProperty("verification.timing.nofail").equals( "true")) { nofail.setSelected(true); } } if (load.containsKey("verification.timing.noproj")) { if (load.getProperty("verification.timing.noproj").equals( "true")) { nofail.setSelected(true); } } if (load.containsKey("verification.timing.explpn")) { if (load.getProperty("verification.timing.explpn").equals( "true")) { explpn.setSelected(true); } } if (load.containsKey("verification.nochecks")) { if (load.getProperty("verification.nochecks").equals("true")) { nochecks.setSelected(true); } } if (load.containsKey("verification.reduction")) { if (load.getProperty("verification.reduction").equals("true")) { reduction.setSelected(true); } } if (verifyFile.endsWith(".s")) { sListModel.addElement(verifyFile); } if (load.containsKey("verification.sList")) { String concatList = load.getProperty("verification.sList"); String[] list = concatList.split("\\s"); for (String s : list) { sListModel.addElement(s); } } if (load.containsKey("abstraction.interesting")) { String intVars = load.getProperty("abstraction.interesting"); String[] array = intVars.split(" "); for (String s : array) { if (!s.equals("")) { abstPane.addIntVar(s); } } } HashMap<Integer, String> preOrder = new HashMap<Integer, String>(); HashMap<Integer, String> loopOrder = new HashMap<Integer, String>(); HashMap<Integer, String> postOrder = new HashMap<Integer, String>(); boolean containsAbstractions = false; for (String s : abstPane.transforms) { if (load.containsKey(s)) { containsAbstractions = true; } } for (String s : abstPane.transforms) { if (load.containsKey("abstraction.transform." + s)) { if (load.getProperty("abstraction.transform." + s).contains("preloop")) { Pattern prePattern = Pattern.compile("preloop(\\d+)"); Matcher intMatch = prePattern.matcher(load .getProperty("abstraction.transform." + s)); if (intMatch.find()) { Integer index = Integer.parseInt(intMatch.group(1)); preOrder.put(index, s); } else { abstPane.addPreXform(s); } } else { abstPane.preAbsModel.removeElement(s); } if (load.getProperty("abstraction.transform." + s).contains("mainloop")) { Pattern loopPattern = Pattern .compile("mainloop(\\d+)"); Matcher intMatch = loopPattern.matcher(load .getProperty("abstraction.transform." + s)); if (intMatch.find()) { Integer index = Integer.parseInt(intMatch.group(1)); loopOrder.put(index, s); } else { abstPane.addLoopXform(s); } } else { abstPane.loopAbsModel.removeElement(s); } if (load.getProperty("abstraction.transform." + s).contains("postloop")) { Pattern postPattern = Pattern .compile("postloop(\\d+)"); Matcher intMatch = postPattern.matcher(load .getProperty("abstraction.transform." + s)); if (intMatch.find()) { Integer index = Integer.parseInt(intMatch.group(1)); postOrder.put(index, s); } else { abstPane.addPostXform(s); } } else { abstPane.postAbsModel.removeElement(s); } } else if (containsAbstractions) { abstPane.preAbsModel.removeElement(s); abstPane.loopAbsModel.removeElement(s); abstPane.postAbsModel.removeElement(s); } } if (preOrder.size() > 0) { abstPane.preAbsModel.removeAllElements(); } for (Integer j = 0; j < preOrder.size(); j++) { abstPane.preAbsModel.addElement(preOrder.get(j)); } if (loopOrder.size() > 0) { abstPane.loopAbsModel.removeAllElements(); } for (Integer j = 0; j < loopOrder.size(); j++) { abstPane.loopAbsModel.addElement(loopOrder.get(j)); } if (postOrder.size() > 0) { abstPane.postAbsModel.removeAllElements(); } for (Integer j = 0; j < postOrder.size(); j++) { abstPane.postAbsModel.addElement(postOrder.get(j)); } abstPane.preAbs.setListData(abstPane.preAbsModel.toArray()); abstPane.loopAbs.setListData(abstPane.loopAbsModel.toArray()); abstPane.postAbs.setListData(abstPane.postAbsModel.toArray()); if (load.containsKey("abstraction.transforms")) { String xforms = load.getProperty("abstraction.transforms"); String[] array = xforms.split(", "); for (String s : array) { if (!s.equals("")) { abstPane.addLoopXform(s.replace(",", "")); } } } if (load.containsKey("abstraction.factor")) { abstPane.factorField.setText(load .getProperty("abstraction.factor")); } if (load.containsKey("abstraction.iterations")) { abstPane.iterField.setText(load .getProperty("abstraction.iterations")); } tempArray = verifyFile.split(separator); sourceFileNoPath = tempArray[tempArray.length - 1]; backgroundField = new JTextField(sourceFileNoPath); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(Gui.frame, "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } // Creates the run button run = new JButton("Save and Verify"); run.addActionListener(this); buttonPanel.add(run); run.setMnemonic(KeyEvent.VK_S); // Creates the save button save = new JButton("Save Parameters"); save.addActionListener(this); buttonPanel.add(save); save.setMnemonic(KeyEvent.VK_P); // Creates the view circuit button viewCircuit = new JButton("View Circuit"); viewCircuit.addActionListener(this); viewCircuit.setMnemonic(KeyEvent.VK_C); // Creates the view trace button viewTrace = new JButton("View Trace"); viewTrace.addActionListener(this); buttonPanel.add(viewTrace); if (!traceFile.exists()) { viewTrace.setEnabled(false); } viewTrace.setMnemonic(KeyEvent.VK_T); // Creates the view log button viewLog = new JButton("View Log"); viewLog.addActionListener(this); buttonPanel.add(viewLog); viewLog.setMnemonic(KeyEvent.VK_V); viewLog.setEnabled(false); JPanel backgroundPanel = new JPanel(); JLabel backgroundLabel = new JLabel("Model File:"); tempArray = verifyFile.split(separator); JLabel componentLabel = new JLabel("Component:"); componentField.setPreferredSize(new Dimension(200, 20)); String sourceFile = tempArray[tempArray.length - 1]; backgroundField = new JTextField(sourceFile); backgroundField.setMaximumSize(new Dimension(200, 20)); backgroundField.setEditable(false); backgroundPanel.add(backgroundLabel); backgroundPanel.add(backgroundField); if (verifyFile.endsWith(".vhd")) { backgroundPanel.add(componentLabel); backgroundPanel.add(componentField); } backgroundPanel.setMaximumSize(new Dimension(500, 30)); basicOptions.add(backgroundPanel); basicOptions.add(abstractionPanel); basicOptions.add(timingRadioPanel); if (!lema) { basicOptions.add(timingCheckBoxPanel); } basicOptions.add(otherPanel); //if (lema) { // basicOptions.add(preprocPanel); if (!lema) { basicOptions.add(algorithmPanel); } if (verifyFile.endsWith(".vhd")) { basicOptions.add(componentPanel); } if (verifyFile.endsWith(".lpn")) { basicOptions.add(LPNPanel); } basicOptions.setLayout(new BoxLayout(basicOptions, BoxLayout.Y_AXIS)); basicOptions.add(Box.createVerticalGlue()); advOptions.add(compilationPanel); advOptions.add(advTimingPanel); advOptions.add(advancedPanel); advOptions.add(bddPanel); advOptions.setLayout(new BoxLayout(advOptions, BoxLayout.Y_AXIS)); advOptions.add(Box.createVerticalGlue()); JTabbedPane tab = new JTabbedPane(); tab.addTab("Basic Options", basicOptions); tab.addTab("Advanced Options", advOptions); tab.addTab("Abstraction Options", abstPane); tab.setPreferredSize(new Dimension(1000, 480)); this.setLayout(new BorderLayout()); this.add(tab, BorderLayout.PAGE_START); change = false; } /** * This method performs different functions depending on what menu items or * buttons are selected. * * @throws * @throws */ public void actionPerformed(ActionEvent e) { change = true; if (e.getSource() == run) { save(verFile); new Thread(this).start(); } else if (e.getSource() == save) { log.addText("Saving:\n" + directory + separator + verFile + "\n"); save(verFile); } else if (e.getSource() == viewCircuit) { viewCircuit(); } else if (e.getSource() == viewTrace) { viewTrace(); } else if (e.getSource() == viewLog) { viewLog(); } else if (e.getSource() == addComponent) { String[] vhdlFiles = new File(root).list(); ArrayList<String> tempFiles = new ArrayList<String>(); for (int i = 0; i < vhdlFiles.length; i++) { if (vhdlFiles[i].endsWith(".vhd") && !vhdlFiles[i].equals(sourceFileNoPath)) { tempFiles.add(vhdlFiles[i]); } } vhdlFiles = new String[tempFiles.size()]; for (int i = 0; i < vhdlFiles.length; i++) { vhdlFiles[i] = tempFiles.get(i); } String filename = (String) JOptionPane.showInputDialog(this, "", "Select Component", JOptionPane.PLAIN_MESSAGE, null, vhdlFiles, vhdlFiles[0]); if (filename != null) { String[] comps = componentList.getItems(); boolean contains = false; for (int i = 0; i < comps.length; i++) { if (comps[i].equals(filename)) { contains = true; } } if (!filename.endsWith(".vhd")) { JOptionPane.showMessageDialog(Gui.frame, "You must select a valid VHDL file.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (new File(directory + separator + filename).exists() || filename.equals(sourceFileNoPath) || contains) { JOptionPane .showMessageDialog( Gui.frame, "This component is already contained in this tool.", "Error", JOptionPane.ERROR_MESSAGE); return; } componentList.addItem(filename); return; } } else if (e.getSource() == removeComponent) { if (componentList.getSelectedValue() != null) { String selected = componentList.getSelectedValue().toString(); componentList.removeItem(selected); new File(directory + separator + selected).delete(); } } else if (e.getSource() == addSFile) { String sFile = JOptionPane.showInputDialog(this, "Enter Assembly File Name:", "Assembly File Name", JOptionPane.PLAIN_MESSAGE); if ((!sFile.endsWith(".s") && !sFile.endsWith(".inst")) || !(new File(sFile).exists())) { JOptionPane.showMessageDialog(this, "Invalid filename entered.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == addLPN) { String[] lpnFiles = new File(root).list(); ArrayList<String> tempFiles = new ArrayList<String>(); for (int i = 0; i < lpnFiles.length; i++) { if (lpnFiles[i].endsWith(".lpn") && !lpnFiles[i].equals(sourceFileNoPath)) { tempFiles.add(lpnFiles[i]); } } Object[] tempFilesArray = tempFiles.toArray(); Arrays.sort(tempFilesArray); lpnFiles = new String[tempFilesArray.length]; for (int i = 0; i < lpnFiles.length; i++) { lpnFiles[i] = (String) tempFilesArray[i]; } JList lpnListInCurDir = new JList(lpnFiles); JScrollPane scroll = new JScrollPane(lpnListInCurDir); String[] options = new String[]{"OK", "Cancel"}; int selection = JOptionPane.showOptionDialog(this, scroll, "Select LPN", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (selection == JOptionPane.YES_OPTION) { for (Object obj : lpnListInCurDir.getSelectedValues()) { String filename = (String) obj; if (filename != null) { String[] lpns = lpnList.getItems(); boolean contains = false; for (int i = 0; i < lpns.length; i++) { if (lpns[i].equals(filename)) { contains = true; } } if (!filename.endsWith(".lpn")) { JOptionPane.showMessageDialog(Gui.frame, "You must select a valid LPN file.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (new File(directory + separator + filename).exists() || filename.equals(sourceFileNoPath) || contains) { JOptionPane .showMessageDialog( Gui.frame, "This lpn is already contained in this tool.", "Error", JOptionPane.ERROR_MESSAGE); return; } lpnList.addItem(filename); } } } return; } else if (e.getSource() == removeLPN) { if (lpnList.getSelectedValue() != null) { String selected = lpnList.getSelectedValue().toString(); lpnList.removeItem(selected); new File(directory + separator + selected).delete(); } } } // private void printAllProcesses(HashMap<Transition, Integer> allProcessTrans) { // System.out.println("~~~~~~~~~~Begin~~~~~~~~~"); // Set<Transition> allTransitions = allProcessTrans.keySet(); // for (Iterator<Transition> allTransIter = allTransitions.iterator(); allTransIter.hasNext();) { // Transition curTran = allTransIter.next(); // System.out.println(curTran.getName() + "\t" + allProcessTrans.get(curTran)); // System.out.println("~~~~~~~~~~End~~~~~~~~~"); @SuppressWarnings("unchecked") public void run() { copyFile(); String[] array = directory.split(separator); String tempDir = ""; String lpnFileName = ""; if (!verifyFile.endsWith("lpn")) { String[] temp = verifyFile.split("\\."); lpnFileName = temp[0] + ".lpn"; } else { lpnFileName = verifyFile; } if (untimedStateSearch.isSelected()) { LhpnFile lpn = new LhpnFile(); lpn.load(directory + separator + lpnFileName); Options.setLogName(lpn.getLabel()); if (!decomposeLPN.isSelected()) { ArrayList<LhpnFile> selectedLPNs = new ArrayList<LhpnFile>(); selectedLPNs.add(lpn); for (int i=0; i < lpnList.getSelectedValues().length; i++) { String curLPNname = (String) lpnList.getSelectedValues()[i]; LhpnFile curLPN = new LhpnFile(); curLPN.load(directory + separator + curLPNname); selectedLPNs.add(curLPN); } // Options for printing out intermediate results during POR Options.setDebugMode(true); //Options.setDebugMode(false); Options.setNecessaryUsingDependencyGraphs(true); //Options.setNecessaryUsingDependencyGraphs(false); Project untimed_dfs = new Project(selectedLPNs); // if (untimedPOR.isSelected()) { // // Options for using trace-back in ample calculation // String[] ampleMethds = {"Use trace-back for ample computation", "No trace-back for ample computation"}; // JList ampleMethdsList = new JList(ampleMethds); // ampleMethdsList.setVisibleRowCount(2); // //cycleClosingList.addListSelectionListener(new ValueReporter()); // JScrollPane ampleMethdsPane = new JScrollPane(ampleMethdsList); // JPanel mainPanel0 = new JPanel(new BorderLayout()); // mainPanel0.add("North", new JLabel("Select an ample set computation method:")); // mainPanel0.add("Center", ampleMethdsPane); // Object[] options0 = {"Run", "Cancel"}; // int optionRtVal0 = JOptionPane.showOptionDialog(Gui.frame, mainPanel0, "Ample set computation methods selection", // JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options0, options0[0]); // if (optionRtVal0 == 1) { // // Cancel // return; // int ampleMethdsIndex = ampleMethdsList.getSelectedIndex(); // if (ampleMethdsIndex == 0) // Options.setPOR("tb"); // if (ampleMethdsIndex == 1) // Options.setPOR("tboff"); // // GUI for different cycle closing methods. // String[] entries = {"Use behavioral analysis", // "Use behavioral analysis and state trace-back", // "No cycle closing", // "Strong cycle condition"}; // JList cycleClosingList = new JList(entries); // cycleClosingList.setVisibleRowCount(4); // //cycleClosingList.addListSelectionListener(new ValueReporter()); // JScrollPane cycleClosingPane = new JScrollPane(cycleClosingList); // JPanel mainPanel = new JPanel(new BorderLayout()); // mainPanel.add("North", new JLabel("Select a cycle closing method:")); // mainPanel.add("Center", cycleClosingPane); // Object[] options = {"Run", "Cancel"}; // int optionRtVal = JOptionPane.showOptionDialog(Gui.frame, mainPanel, "Cycle closing methods selection", // JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); // if (optionRtVal == 1) { // // Cancel // return; // int cycleClosingMthdIndex = cycleClosingList.getSelectedIndex(); // if (cycleClosingMthdIndex == 0) { // Options.setCycleClosingMthd("behavioral"); // if (Options.getPOR().equals("tb")) { // String[] cycleClosingAmpleMethds = {"Use trace-back", "No trace-back"}; // JList cycleClosingAmpleList = new JList(cycleClosingAmpleMethds); // cycleClosingAmpleList.setVisibleRowCount(2); // JScrollPane cycleClosingAmpleMethdsPane = new JScrollPane(cycleClosingAmpleList); // JPanel mainPanel1 = new JPanel(new BorderLayout()); // mainPanel1.add("North", new JLabel("Select a cycle closing ample computation method:")); // mainPanel1.add("Center", cycleClosingAmpleMethdsPane); // Object[] options1 = {"Run", "Cancel"}; // int optionRtVal1 = JOptionPane.showOptionDialog(Gui.frame, mainPanel1, "Cycle closing ample computation method selection", // JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options1, options1[0]); // if (optionRtVal1 == 1) { // // Cancel // return; // int cycleClosingAmpleMethdIndex = cycleClosingAmpleList.getSelectedIndex(); // if (cycleClosingAmpleMethdIndex == 0) // Options.setCycleClosingAmpleMethd("cctb"); // if (cycleClosingAmpleMethdIndex == 1) // Options.setCycleClosingAmpleMethd("cctboff"); // else if (Options.getPOR().equals("tboff")) { // Options.setCycleClosingAmpleMethd("cctboff"); // else if (cycleClosingMthdIndex == 1) // Options.setCycleClosingMthd("state_search"); // else if (cycleClosingMthdIndex == 2) // Options.setCycleClosingMthd("no_cycleclosing"); // else if (cycleClosingMthdIndex == 3) // Options.setCycleClosingMthd("strong"); // if (dot.isSelected()) { // Options.setOutputSgFlag(true); // Options.setPrjSgPath(directory + separator); // // Options for printing the final numbers from search_dfs or search_dfsPOR. // Options.setOutputLogFlag(true); //// Options.setPrintLogToFile(false); // StateGraph[] stateGraphArray = untimed_dfs.searchPOR(); // if (dot.isSelected()) { // for (int i=0; i<stateGraphArray.length; i++) { // String graphFileName = stateGraphArray[i].getLpn().getLabel() + "POR_"+ Options.getCycleClosingMthd() + "_local_sg.dot"; // stateGraphArray[i].outputLocalStateGraph(directory + separator + graphFileName); // // Code for producing global state graph is in search_dfsPOR in the Analysis class. if (untimedPOR.isSelected()) { // Options for using trace-back in ample calculation String[] ampleMethds = {"Trace-back", "Trace-back with dependency graphs","No trace-back for ample computation"}; JList ampleMethdsList = new JList(ampleMethds); ampleMethdsList.setVisibleRowCount(3); //cycleClosingList.addListSelectionListener(new ValueReporter()); JScrollPane ampleMethdsPane = new JScrollPane(ampleMethdsList); JPanel mainPanel0 = new JPanel(new BorderLayout()); mainPanel0.add("North", new JLabel("Select an ample set computation method:")); mainPanel0.add("Center", ampleMethdsPane); Object[] options0 = {"Run", "Cancel"}; int optionRtVal0 = JOptionPane.showOptionDialog(Gui.frame, mainPanel0, "Ample set computation methods selection", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options0, options0[0]); if (optionRtVal0 == 1) { // Cancel return; } int ampleMethdsIndex = ampleMethdsList.getSelectedIndex(); if (ampleMethdsIndex == 0) { Options.setPOR("tb"); Options.setCycleClosingMthd("behavioral"); Options.setCycleClosingAmpleMethd("cctb"); } if (ampleMethdsIndex == 1) { Options.setPOR("tbdg"); Options.setCycleClosingMthd("behavioral"); Options.setCycleClosingAmpleMethd("cctbdg"); } if (ampleMethdsIndex == 2) { Options.setPOR("tboff"); Options.setCycleClosingMthd("behavioral"); Options.setCycleClosingAmpleMethd("cctboff"); } // Choose different cycle closing methods // int cycleClosingMthdIndex = cycleClosingList.getSelectedIndex(); // if (cycleClosingMthdIndex == 0) { // Options.setCycleClosingMthd("behavioral"); // if (Options.getPOR().equals("tb")) { // String[] cycleClosingAmpleMethds = {"Use trace-back", "No trace-back"}; // JList cycleClosingAmpleList = new JList(cycleClosingAmpleMethds); // cycleClosingAmpleList.setVisibleRowCount(2); // JScrollPane cycleClosingAmpleMethdsPane = new JScrollPane(cycleClosingAmpleList); // JPanel mainPanel1 = new JPanel(new BorderLayout()); // mainPanel1.add("North", new JLabel("Select a cycle closing ample computation method:")); // mainPanel1.add("Center", cycleClosingAmpleMethdsPane); // Object[] options1 = {"Run", "Cancel"}; // int optionRtVal1 = JOptionPane.showOptionDialog(Gui.frame, mainPanel1, "Cycle closing ample computation method selection", // JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options1, options1[0]); // if (optionRtVal1 == 1) { // // Cancel // return; // int cycleClosingAmpleMethdIndex = cycleClosingAmpleList.getSelectedIndex(); // if (cycleClosingAmpleMethdIndex == 0) // Options.setCycleClosingAmpleMethd("cctb"); // if (cycleClosingAmpleMethdIndex == 1) // Options.setCycleClosingAmpleMethd("cctboff"); // else if (Options.getPOR().equals("tboff")) { // Options.setCycleClosingAmpleMethd("cctboff"); // else if (cycleClosingMthdIndex == 1) // Options.setCycleClosingMthd("state_search"); // else if (cycleClosingMthdIndex == 2) // Options.setCycleClosingMthd("no_cycleclosing"); // else if (cycleClosingMthdIndex == 3) // Options.setCycleClosingMthd("strong"); if (dot.isSelected()) { Options.setOutputSgFlag(true); } Options.setPrjSgPath(directory + separator); // Options for printing the final numbers from search_dfs or search_dfsPOR. Options.setOutputLogFlag(true); // Options.setPrintLogToFile(false); StateGraph[] stateGraphArray = untimed_dfs.searchPOR(); if (dot.isSelected()) { for (int i=0; i<stateGraphArray.length; i++) { String graphFileName = stateGraphArray[i].getLpn().getLabel() + "POR_"+ Options.getCycleClosingMthd() + "_local_sg.dot"; stateGraphArray[i].outputLocalStateGraph(directory + separator + graphFileName); } // Code for producing global state graph is in search_dfsPOR in the Analysis class. } } else { // No POR Options.setPrjSgPath(directory + separator); // Options for printing the final numbers from search_dfs or search_dfsPOR. Options.setOutputLogFlag(true); // Options.setPrintLogToFile(false); if (dot.isSelected()) Options.setOutputSgFlag(true); StateGraph[] stateGraphArray = untimed_dfs.search(); if (stateGraphArray != null) if (dot.isSelected()) { for (int i=0; i<stateGraphArray.length; i++) { String graphFileName = stateGraphArray[i].getLpn().getLabel() + "_local_sg.dot"; stateGraphArray[i].outputLocalStateGraph(directory + separator + graphFileName); } // Code for producing global state graph is in search_dfsPOR in the Analysis class. } } return; } else if (!untimedPOR.isSelected() && !multipleLPNs.isSelected() && decomposeLPN.isSelected() && verbose.isSelected() && lpnList.getSelectedValue() == null) { HashMap<Transition, Integer> allProcessTrans = new HashMap<Transition, Integer>(); // create an Abstraction object to get all processes in one LPN Abstraction abs = lpn.abstractLhpn(this); abs.decomposeLpnIntoProcesses(); allProcessTrans.putAll((HashMap<Transition, Integer>)abs.getTransWithProcIDs().clone()); HashMap<Integer, LpnProcess> processMap = new HashMap<Integer, LpnProcess>(); for (Iterator<Transition> tranIter = allProcessTrans.keySet().iterator(); tranIter.hasNext();) { Transition curTran = tranIter.next(); Integer procId = allProcessTrans.get(curTran); if (!processMap.containsKey(procId)) { LpnProcess newProcess = new LpnProcess(procId); newProcess.addTranToProcess(curTran); if (curTran.getPreset() != null) { Place[] preset = curTran.getPreset(); for (Place p : preset) { newProcess.addPlaceToProcess(p); } } processMap.put(procId, newProcess); } else { LpnProcess curProcess = processMap.get(procId); curProcess.addTranToProcess(curTran); if (curTran.getPreset() != null) { Place[] preset = curTran.getPreset(); for (Place p : preset) { curProcess.addPlaceToProcess(p); } } } } HashMap<String, ArrayList<Integer>> allProcessRead = abs.getProcessRead(); HashMap<String, ArrayList<Integer>> allProcessWrite = abs.getProcessWrite(); for (String curRead : allProcessRead.keySet()) { if (allProcessRead.get(curRead).size() == 1 && allProcessWrite.get(curRead).size() == 1) { if (allProcessRead.get(curRead).equals(allProcessWrite.get(curRead))) { // variable is read and written only by one process Integer curProcessID = allProcessRead.get(curRead).get(0); ArrayList<Variable> processInternal = processMap.get(curProcessID).getProcessInternal(); if (!processInternal.contains(abs.getVariable(curRead))) processInternal.add(abs.getVariable(curRead)); } else { // variable is read in one process and written by another Integer curProcessID = allProcessRead.get(curRead).get(0); ArrayList<Variable> processInput = processMap.get(curProcessID).getProcessInput(); if (!processInput.contains(abs.getVariable(curRead))) processInput.add(abs.getVariable(curRead)); curProcessID = allProcessWrite.get(curRead).get(0); ArrayList<Variable> processOutput = processMap.get(curProcessID).getProcessOutput(); if (!processOutput.contains(abs.getVariable(curRead))) processOutput.add(abs.getVariable(curRead)); } } else if (allProcessRead.get(curRead).size() > 1 || allProcessWrite.get(curRead).size() > 1) { ArrayList<Integer> readList = allProcessRead.get(curRead); ArrayList<Integer> writeList = allProcessWrite.get(curRead); ArrayList<Integer> alreadyAssignedAsOutput = new ArrayList<Integer>(); for (int i=0; i<writeList.size(); i++) { Integer curProcessID = writeList.get(i); ArrayList<Variable> processOutput = processMap.get(curProcessID).getProcessOutput(); if (!processOutput.contains(abs.getVariable(curRead))) processOutput.add(abs.getVariable(curRead)); if (!alreadyAssignedAsOutput.contains(curProcessID)) alreadyAssignedAsOutput.add(curProcessID); } readList.removeAll(alreadyAssignedAsOutput); for (int i=0; i<readList.size(); i++) { Integer curProcessID = readList.get(i); ArrayList<Variable> processInput = processMap.get(curProcessID).getProcessInput(); if (!processInput.contains(abs.getVariable(curRead))) processInput.add(abs.getVariable(curRead)); } } else if (allProcessWrite.get(curRead).size() == 0) { // variable is only read, but never written if (allProcessRead.get(curRead).size() == 1) { // variable is read locally Integer curProcessID = allProcessRead.get(curRead).get(0); ArrayList<Variable> processInternal = processMap.get(curProcessID).getProcessInternal(); if (!processInternal.contains(abs.getVariable(curRead))) processInternal.add(abs.getVariable(curRead)); } else if (allProcessRead.get(curRead).size() > 1) { // variable is read globally by multiple processes for (int i=0; i < allProcessRead.get(curRead).size(); i++) { Integer curProcessID = allProcessRead.get(curRead).get(i); ArrayList<Variable> processInput = processMap.get(curProcessID).getProcessInput(); if (!processInput.contains(abs.getVariable(curRead))) processInput.add(abs.getVariable(curRead)); } } } else if (allProcessRead.get(curRead).size() == 0) { // variable is only written, but never read if (allProcessWrite.get(curRead).size() == 1) { // variable is written locally Integer curProcessID = allProcessWrite.get(curRead).get(0); ArrayList<Variable> processInternal = processMap.get(curProcessID).getProcessInternal(); if (!processInternal.contains(abs.getVariable(curRead))) processInternal.add(abs.getVariable(curRead)); } if (allProcessWrite.get(curRead).size() > 1) { // variable is written globally by multiple processes for (int i=0; i < allProcessWrite.get(curRead).size(); i++) { Integer curProcessID = allProcessWrite.get(curRead).get(i); ArrayList<Variable> processInput = processMap.get(curProcessID).getProcessInput(); if (!processInput.contains(abs.getVariable(curRead))) processInput.add(abs.getVariable(curRead)); } } } } // Options to get all possible decompositions or just one decomposition String[] decomposition = {"Get ALL decompositions", "Get ONE decomposition"}; JList decompositionList = new JList(decomposition); decompositionList.setVisibleRowCount(2); JScrollPane decompMethdsPane = new JScrollPane(decompositionList); JPanel mainPanel0 = new JPanel(new BorderLayout()); mainPanel0.add("North", new JLabel("Select a LPN decomposition method:")); mainPanel0.add("Center", decompMethdsPane); Object[] options0 = {"Run", "Cancel"}; int optionRtVal0 = JOptionPane.showOptionDialog(Gui.frame, mainPanel0, "LPN decomposition methods selection", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options0, options0[0]); if (optionRtVal0 == 1) { // Cancel return; } int decompMethdIndex = decompositionList.getSelectedIndex(); if (decompMethdIndex == 0) { // Automatically find all possible LPN partitions. // Find the process with least number of variables int leastNumVarsInOneProcess = lpn.getVariables().length; for (Integer curProcId : processMap.keySet()) { LpnProcess curProcess = processMap.get(curProcId); if (curProcess.getProcessVarSize() < leastNumVarsInOneProcess) { leastNumVarsInOneProcess = curProcess.getProcessVarSize(); } } Integer maxNumVarsInOneComp = leastNumVarsInOneProcess; Integer tryNumDecomps = processMap.size(); // The maximal number of decomposed LPNs is the number of all processes in the LPN. HashSet<Integer> possibleDecomps = new HashSet<Integer>(); //System.out.println("lpn.getVariables().length = " + lpn.getVariables().length); while(tryNumDecomps > 1) { LpnComponentList componentList = new LpnComponentList(maxNumVarsInOneComp); componentList.buildComponents(processMap, directory, lpn.getLabel()); HashMap<Integer, Component> compMap = componentList.getComponentMap(); tryNumDecomps = compMap.size(); if (tryNumDecomps == 1) break; if (!possibleDecomps.contains(compMap.size())) { possibleDecomps.add(compMap.size()); for (Component comp : compMap.values()) { LhpnFile lpnComp = new LhpnFile(); lpnComp = comp.buildLPN(lpnComp); lpnComp.save(root + separator + lpn.getLabel() + "_decomp" + maxNumVarsInOneComp + "vars" + comp.getComponentId() + ".lpn"); } } maxNumVarsInOneComp++; } System.out.println("possible decompositions for " + lpn.getLabel() + ".lpn: "); for (Integer i : possibleDecomps) { System.out.print(i + ", "); } System.out.println(); return; } if (decompMethdIndex ==1) { // User decides one LPN partition. // Find the process with the least number of variables int leastNumVarsInOneProcess = lpn.getVariables().length; for (Iterator<Integer> processMapIter = processMap.keySet().iterator(); processMapIter.hasNext();) { Integer curProcId = processMapIter.next(); LpnProcess curProcess = processMap.get(curProcId); if (curProcess.getProcessVarSize() < leastNumVarsInOneProcess) { leastNumVarsInOneProcess = curProcess.getProcessVarSize(); } } // Coalesce an array of processes into one LPN component. JPanel mainPanel = new JPanel(new BorderLayout()); JPanel maxVarsPanel = new JPanel(); JTextField maxVarsText = new JTextField(3); maxVarsText.setText("" + lpn.getVariables().length); maxVarsPanel.add(new JLabel("Enter the maximal number of variables allowed in one component:")); maxVarsPanel.add(maxVarsText); mainPanel.add("North", new JLabel("number of variables in this LPN: " + lpn.getVariables().length)); mainPanel.add("Center", new JLabel("number of variables in the smallest process: " + leastNumVarsInOneProcess)); mainPanel.add("South", maxVarsPanel); Object[] options = {"Run", "Cancel"}; int optionRtVal = JOptionPane.showOptionDialog(Gui.frame, mainPanel, "Assign the maximal number of variables in one component", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (optionRtVal == 1) { // Cancel return; } Integer maxNumVarsInOneComp = Integer.parseInt(maxVarsText.getText().trim());; if (leastNumVarsInOneProcess >= maxNumVarsInOneComp) { // The original LPN is decomposed into processes. // Store each process as individual LPN. for (Iterator<Integer> processMapIter = processMap.keySet().iterator(); processMapIter.hasNext();) { Integer curProcId = processMapIter.next(); LpnProcess curProcess = processMap.get(curProcId); LhpnFile lpnProc = new LhpnFile(); lpnProc = curProcess.buildLPN(lpnProc); lpnProc.save(root + separator + lpn.getLabel() + "_decomp" + maxNumVarsInOneComp + "vars" + curProcId + ".lpn"); //lpnProc.save(directory + separator + lpn.getLabel() + curProcId + ".lpn"); } JOptionPane.showMessageDialog( Gui.frame, "The entered maximal number of variables in one component is too small. The LPN was decomposed into processes.", "Warning", JOptionPane.WARNING_MESSAGE); return; } LpnComponentList componentList = new LpnComponentList(maxNumVarsInOneComp); componentList.buildComponents(processMap, directory, lpn.getLabel()); HashMap<Integer, Component> compMap = componentList.getComponentMap(); for (Component comp : compMap.values()) { LhpnFile lpnComp = new LhpnFile(); lpnComp = comp.buildLPN(lpnComp); lpnComp.save(root + separator + lpn.getLabel() + "_decomp" + maxNumVarsInOneComp + "vars" + comp.getComponentId() + ".lpn"); } return; } } else if (!untimedPOR.isSelected() && !decomposeLPN.isSelected() && multipleLPNs.isSelected() && lpnList.getSelectedValues().length < 1) { JOptionPane.showMessageDialog( Gui.frame, "Please select at least 1 more LPN.", "Error", JOptionPane.ERROR_MESSAGE); return; } } long time1 = System.nanoTime(); File work = new File(directory); /* if (!preprocStr.getText().equals("")) { try { String preprocCmd = preprocStr.getText(); Runtime exec = Runtime.getRuntime(); Process preproc = exec.exec(preprocCmd, null, work); log.addText("Executing:\n" + preprocCmd + "\n"); preproc.waitFor(); } catch (Exception e) { JOptionPane.showMessageDialog(Gui.frame, "Error with preprocessing.", "Error", JOptionPane.ERROR_MESSAGE); //e.printStackTrace(); } } */ try { if (verifyFile.endsWith(".lpn")) { Runtime.getRuntime().exec("atacs -llsl " + verifyFile, null, work); } else if (verifyFile.endsWith(".vhd")) { Runtime.getRuntime().exec("atacs -lvsl " + verifyFile, null, work); } else if (verifyFile.endsWith(".g")) { Runtime.getRuntime().exec("atacs -lgsl " + verifyFile, null, work); } else if (verifyFile.endsWith(".hse")) { Runtime.getRuntime().exec("atacs -lhsl " + verifyFile, null, work); } } catch (Exception e) { } for (int i = 0; i < array.length - 1; i++) { tempDir = tempDir + array[i] + separator; } LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(directory + separator + lpnFileName); Abstraction abstraction = lhpnFile.abstractLhpn(this); String abstFilename; if(dbm2.isSelected()) { try { verification.timed_state_exploration.dbm2.StateExploration.findStateGraph(lhpnFile, directory+separator, lpnFileName); } catch (FileNotFoundException e) { e.printStackTrace(); } return; } /** * If the splitZone option (labeled "Split Zone") is selected, * run the timed analysis. */ if(splitZone.isSelected()) { // Version prior to adding zones to the project states. // Uses the timed_state_exploration.zone infrastructure. // if(multipleLPNs.isSelected()) // else // LhpnFile lpn = new LhpnFile(); // lpn.load(directory + separator + lpnFileName); // // The full state graph is created for only one LPN. // /** // * This is what selects the timing analysis. // * The method setTimingAnalysisType sets a static variable // * in the Options class that is queried by the search method. // */ // Options.setTimingAnalsysisType("zone"); // ZoneType.setSubsetFlag(!timsubset.isSelected()); // ZoneType.setSupersetFlag(!superset.isSelected()); // Project_Timed timedStateSearch = new Project_Timed(lpn, // Options.getTimingAnalysisFlag(), false); // if(useGraphs.isSelected()){ // timedStateSearch = new Project_Timed(lpn, // Options.getTimingAnalysisFlag(), true); // StateGraph_timed[] stateGraphArray = timedStateSearch.search(); // String graphFileName = verifyFile.replace(".lpn", "") + "_sg.dot"; // if (stateGraphArray.length > 1) { // JOptionPane.showMessageDialog( // Gui.frame, // "Mutiple state graphs should not be produced.", // "Error", JOptionPane.ERROR_MESSAGE); // else { // if (dot.isSelected()) { // stateGraphArray[0].outputLocalStateGraph(directory + separator + graphFileName); // if(graph.isSelected()){ // showGraph(directory + separator + graphFileName); // Options.setTimingAnalsysisType("off"); // Zone.clearLexicon(); // return; // This is the code before the revision for allowing multiple LPNs // // Uses the timed_state_exploration.zoneProject infrastructure. // LhpnFile lpn = new LhpnFile(); // lpn.load(directory + separator + lpnFileName); // // The full state graph is created for only one LPN. // /** // * This is what selects the timing analysis. // * The method setTimingAnalysisType sets a static variable // * in the Options class that is queried by the search method. // */ // Options.setTimingAnalsysisType("zone"); // ZoneType.setSubsetFlag(!timsubset.isSelected()); // ZoneType.setSupersetFlag(!superset.isSelected()); // Project timedStateSearch = new Project(lpn); // StateGraph[] stateGraphArray = timedStateSearch.search(); // String graphFileName = verifyFile.replace(".lpn", "") + "_sg.dot"; // if (dot.isSelected()) { // stateGraphArray[0].outputLocalStateGraph(directory + separator + graphFileName); // if(graph.isSelected()){ // showGraph(directory + separator + graphFileName); // Options.setTimingAnalsysisType("off"); // Zone.clearLexicon(); // return; // Uses the timed_state_exploration.zoneProject infrastructure. LhpnFile lpn = new LhpnFile(); lpn.load(directory + separator + lpnFileName); // Load any other listed LPNs. ArrayList<LhpnFile> selectedLPNs = new ArrayList<LhpnFile>(); // Add the current LPN to the list. selectedLPNs.add(lpn); // for (int i=0; i < lpnList.getSelectedValues().length; i++) { // String curLPNname = (String) lpnList.getSelectedValues()[i]; // LhpnFile curLPN = new LhpnFile(); // curLPN.load(directory + separator + curLPNname); // selectedLPNs.add(curLPN); String[] guiLPNList = lpnList.getItems(); for (int i=0; i < guiLPNList.length; i++) { String curLPNname = guiLPNList[i]; LhpnFile curLPN = new LhpnFile(); curLPN.load(directory + separator + curLPNname); selectedLPNs.add(curLPN); } // Extract boolean variables from continuous variable inequalities. for(int i=0; i<selectedLPNs.size(); i++){ selectedLPNs.get(i).parseBooleanInequalities(); } /** * This is what selects the timing analysis. * The method setTimingAnalysisType sets a static variable * in the Options class that is queried by the search method. */ Options.setTimingAnalsysisType("zone"); Zone.setSubsetFlag(!timsubset.isSelected()); Zone.setSupersetFlag(!superset.isSelected()); Project timedStateSearch = new Project(selectedLPNs); StateGraph[] stateGraphArray = timedStateSearch.search(); String graphFileName = verifyFile.replace(".lpn", "") + "_sg.dot"; if (dot.isSelected()) { stateGraphArray[0].outputLocalStateGraph(directory + separator + graphFileName); } if(graph.isSelected()){ showGraph(directory + separator + graphFileName); } Options.setTimingAnalsysisType("off"); return; } if (lhpn.isSelected()) { abstFilename = (String) JOptionPane.showInputDialog(this, "Please enter the file name for the abstracted LPN.", "Enter Filename", JOptionPane.PLAIN_MESSAGE); if (abstFilename != null) { if (!abstFilename.endsWith(".lpn")) { while (abstFilename.contains("\\.")) { abstFilename = (String) JOptionPane.showInputDialog(this, "Please enter a valid file name for the abstracted LPN.", "Invalid Filename", JOptionPane.PLAIN_MESSAGE); } abstFilename = abstFilename + ".lpn"; } } } else { abstFilename = lpnFileName.replace(".lpn", "_abs.lpn"); } String sourceFile; if (simplify.isSelected() || abstractLhpn.isSelected()) { String[] boolVars = lhpnFile.getBooleanVars(); String[] contVars = lhpnFile.getContVars(); String[] intVars = lhpnFile.getIntVars(); String[] variables = new String[boolVars.length + contVars.length + intVars.length]; int k = 0; for (int j = 0; j < contVars.length; j++) { variables[k] = contVars[j]; k++; } for (int j = 0; j < intVars.length; j++) { variables[k] = intVars[j]; k++; } for (int j = 0; j < boolVars.length; j++) { variables[k] = boolVars[j]; k++; } if (abstFilename != null) { if (!abstFilename.endsWith(".lpn")) abstFilename = abstFilename + ".lpn"; if (abstPane.loopAbsModel.contains("Remove Variables")) { abstraction.abstractVars(abstPane.getIntVars()); } abstraction.abstractSTG(true); } if (!lhpn.isSelected() && !view.isSelected()) { abstraction.save(directory + separator + abstFilename); } sourceFile = abstFilename; } else { String[] tempArray = verifyFile.split(separator); sourceFile = tempArray[tempArray.length - 1]; } if (!lhpn.isSelected() && !view.isSelected()) { abstraction.save(directory + separator + abstFilename); } if (!lhpn.isSelected() && !view.isSelected()) { String[] tempArray = verifyFile.split("\\."); String traceFilename = tempArray[0] + ".trace"; File traceFile = new File(traceFilename); String pargName = ""; String dotName = ""; if (componentField.getText().trim().equals("")) { if (verifyFile.endsWith(".g")) { pargName = directory + separator + sourceFile.replace(".g", ".prg"); dotName = directory + separator + sourceFile.replace(".g", ".dot"); } else if (verifyFile.endsWith(".lpn")) { pargName = directory + separator + sourceFile.replace(".lpn", ".prg"); dotName = directory + separator + sourceFile.replace(".lpn", ".dot"); } else if (verifyFile.endsWith(".vhd")) { pargName = directory + separator + sourceFile.replace(".vhd", ".prg"); dotName = directory + separator + sourceFile.replace(".vhd", ".dot"); } } else { pargName = directory + separator + componentField.getText().trim() + ".prg"; dotName = directory + separator + componentField.getText().trim() + ".dot"; } File pargFile = new File(pargName); File dotFile = new File(dotName); if (traceFile.exists()) { traceFile.delete(); } if (pargFile.exists()) { pargFile.delete(); } if (dotFile.exists()) { dotFile.delete(); } for (String s : componentList.getItems()) { try { FileInputStream in = new FileInputStream(new File(root + separator + s)); FileOutputStream out = new FileOutputStream(new File( directory + separator + s)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } catch (IOException e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(Gui.frame, "Cannot update the file " + s + ".", "Error", JOptionPane.ERROR_MESSAGE); } } for (String s : lpnList.getItems()) { try { FileInputStream in = new FileInputStream(new File(root + separator + s)); FileOutputStream out = new FileOutputStream(new File( directory + separator + s)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } catch (IOException e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(Gui.frame, "Cannot update the file " + s + ".", "Error", JOptionPane.ERROR_MESSAGE); } } String options = ""; // BDD Linkspace Size if (!bddSize.getText().equals("") && !bddSize.getText().equals("0")) { options = options + "-L" + bddSize.getText() + " "; } options = options + "-oq"; // Timing method if (atacs) { if (untimed.isSelected()) { options = options + "tu"; } else if (geometric.isSelected()) { options = options + "tg"; } else if (posets.isSelected()) { options = options + "ts"; } else if (bag.isSelected()) { options = options + "tg"; } else if (bap.isSelected()) { options = options + "tp"; } else { options = options + "tt"; } } else { if (bdd.isSelected()) { options = options + "tB"; } else if (dbm.isSelected()) { options = options + "tL"; } else if (smt.isSelected()) { options = options + "tM"; } } // Timing Options if (abst.isSelected()) { options = options + "oa"; } if (partialOrder.isSelected()) { options = options + "op"; } // Other Options if (dot.isSelected()) { options = options + "od"; } if (verbose.isSelected()) { options = options + "ov"; } // Advanced Timing Options if (genrg.isSelected()) { options = options + "oG"; } if (timsubset.isSelected()) { options = options + "oS"; } if (superset.isSelected()) { options = options + "oU"; } if (infopt.isSelected()) { options = options + "oF"; } if (orbmatch.isSelected()) { options = options + "oO"; } if (interleav.isSelected()) { options = options + "oI"; } if (prune.isSelected()) { options = options + "oP"; } if (disabling.isSelected()) { options = options + "oD"; } if (nofail.isSelected()) { options = options + "of"; } if (noproj.isSelected()) { options = options + "oj"; } if (keepgoing.isSelected()) { options = options + "oK"; } if (explpn.isSelected()) { options = options + "oL"; } // Other Advanced Options if (nochecks.isSelected()) { options = options + "on"; } if (reduction.isSelected()) { options = options + "oR"; } // Compilation Options if (newTab.isSelected()) { options = options + "cN"; } if (postProc.isSelected()) { options = options + "cP"; } if (redCheck.isSelected()) { options = options + "cR"; } if (xForm2.isSelected()) { options = options + "cT"; } if (expandRate.isSelected()) { options = options + "cE"; } // Load file type if (verifyFile.endsWith(".g")) { options = options + "lg"; } else if (verifyFile.endsWith(".lpn")) { options = options + "ll"; } else if (verifyFile.endsWith(".vhd") || verifyFile.endsWith(".vhdl")) { options = options + "lvslll"; } // Verification Algorithms if (verify.isSelected()) { options = options + "va"; } else if (vergate.isSelected()) { options = options + "vg"; } else if (orbits.isSelected()) { options = options + "vo"; } else if (search.isSelected()) { options = options + "vs"; } else if (trace.isSelected()) { options = options + "vt"; } if (graph.isSelected()) { options = options + "ps"; } String cmd = "atacs " + options; String[] components = componentList.getItems(); for (String s : components) { cmd = cmd + " " + s; } cmd = cmd + " " + sourceFile; if (!componentField.getText().trim().equals("")) { cmd = cmd + " " + componentField.getText().trim(); } final JButton cancel = new JButton("Cancel"); final JFrame running = new JFrame("Progress"); WindowListener w = new WindowListener() { public void windowClosing(WindowEvent arg0) { cancel.doClick(); running.dispose(); } public void windowOpened(WindowEvent arg0) { } public void windowClosed(WindowEvent arg0) { } public void windowIconified(WindowEvent arg0) { } public void windowDeiconified(WindowEvent arg0) { } public void windowActivated(WindowEvent arg0) { } public void windowDeactivated(WindowEvent arg0) { } }; running.addWindowListener(w); JPanel text = new JPanel(); JPanel progBar = new JPanel(); JPanel button = new JPanel(); JPanel all = new JPanel(new BorderLayout()); JLabel label = new JLabel("Running..."); JProgressBar progress = new JProgressBar(); progress.setIndeterminate(true); text.add(label); progBar.add(progress); button.add(cancel); all.add(text, "North"); all.add(progBar, "Center"); all.add(button, "South"); all.setOpaque(true); running.setContentPane(all); running.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = running.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; running.setLocation(x, y); running.setVisible(true); running.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); work = new File(directory); Runtime exec = Runtime.getRuntime(); try { Preferences biosimrc = Preferences.userRoot(); String output = ""; int exitValue = 0; if (biosimrc.get("biosim.verification.command", "").equals("")) { final Process ver = exec.exec(cmd, null, work); cancel.setActionCommand("Cancel"); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ver.destroy(); running.setCursor(null); running.dispose(); } }); biosim.getExitButton().setActionCommand("Exit program"); biosim.getExitButton().addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { ver.destroy(); running.setCursor(null); running.dispose(); } }); log.addText("Executing:\n" + cmd + "\n"); InputStream reb = ver.getInputStream(); InputStreamReader isr = new InputStreamReader(reb); BufferedReader br = new BufferedReader(isr); FileWriter out = new FileWriter(new File(directory + separator + "run.log")); while ((output = br.readLine()) != null) { out.write(output); out.write("\n"); } out.close(); br.close(); isr.close(); reb.close(); viewLog.setEnabled(true); exitValue = ver.waitFor(); } else { cmd = biosimrc.get("biosim.verification.command", "") + " " + options + " " + sourceFile.replaceAll(".lpn", ""); final Process ver = exec.exec(cmd, null, work); cancel.setActionCommand("Cancel"); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ver.destroy(); running.setCursor(null); running.dispose(); } }); biosim.getExitButton().setActionCommand("Exit program"); biosim.getExitButton().addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { ver.destroy(); running.setCursor(null); running.dispose(); } }); log.addText("Executing:\n" + cmd + "\n"); InputStream reb = ver.getInputStream(); InputStreamReader isr = new InputStreamReader(reb); BufferedReader br = new BufferedReader(isr); FileWriter out = new FileWriter(new File(directory + separator + "run.log")); while ((output = br.readLine()) != null) { out.write(output); out.write("\n"); } out.close(); br.close(); isr.close(); reb.close(); viewLog.setEnabled(true); exitValue = ver.waitFor(); } long time2 = System.nanoTime(); long minutes; long hours; long days; double secs = ((time2 - time1) / 1000000000.0); long seconds = ((time2 - time1) / 1000000000); secs = secs - seconds; minutes = seconds / 60; secs = seconds % 60 + secs; hours = minutes / 60; minutes = minutes % 60; days = hours / 24; hours = hours % 60; String time; String dayLabel; String hourLabel; String minuteLabel; String secondLabel; if (days == 1) { dayLabel = " day "; } else { dayLabel = " days "; } if (hours == 1) { hourLabel = " hour "; } else { hourLabel = " hours "; } if (minutes == 1) { minuteLabel = " minute "; } else { minuteLabel = " minutes "; } if (seconds == 1) { secondLabel = " second"; } else { secondLabel = " seconds"; } if (days != 0) { time = days + dayLabel + hours + hourLabel + minutes + minuteLabel + secs + secondLabel; } else if (hours != 0) { time = hours + hourLabel + minutes + minuteLabel + secs + secondLabel; } else if (minutes != 0) { time = minutes + minuteLabel + secs + secondLabel; } else { time = secs + secondLabel; } log.addText("Total Verification Time: " + time + "\n\n"); running.setCursor(null); running.dispose(); FileInputStream atacsLog = new FileInputStream(new File( directory + separator + "atacs.log")); InputStreamReader atacsReader = new InputStreamReader(atacsLog); BufferedReader atacsBuffer = new BufferedReader(atacsReader); boolean success = false; while ((output = atacsBuffer.readLine()) != null) { if (output.contains("Verification succeeded.")) { JOptionPane.showMessageDialog(Gui.frame, "Verification succeeded!", "Success", JOptionPane.INFORMATION_MESSAGE); success = true; break; } } if (exitValue == 143) { JOptionPane.showMessageDialog(Gui.frame, "Verification was" + " canceled by the user.", "Canceled Verification", JOptionPane.ERROR_MESSAGE); } if (!success) { if (new File(pargName).exists()) { Process parg = exec.exec("parg " + pargName); log.addText("parg " + pargName + "\n"); parg.waitFor(); } else if (new File(dotName).exists()) { String command; if (System.getProperty("os.name") .contentEquals("Linux")) { command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase() .startsWith("mac os")) { command = "open "; } else { command = "dotty "; } Process dot = exec.exec("open " + dotName); log.addText(command + dotName + "\n"); dot.waitFor(); } else { viewLog(); } } if (graph.isSelected()) { if (dot.isSelected()) { String command; if (System.getProperty("os.name") .contentEquals("Linux")) { command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase() .startsWith("mac os")) { command = "open "; } else { command = "dotty "; } exec.exec(command + dotName); log.addText("Executing:\n" + command + dotName + "\n"); } else { exec.exec("parg " + pargName); log.addText("Executing:\nparg " + pargName + "\n"); } } } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(Gui.frame, "Unable to verify model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { if (lhpn.isSelected()) { abstraction.save(tempDir + separator + abstFilename); biosim.addToTree(abstFilename); } else if (view.isSelected()) { abstraction.save(directory + separator + abstFilename); work = new File(directory + separator); try { String dotName = abstFilename.replace(".lpn", ".dot"); new File(directory + separator + dotName).delete(); Runtime exec = Runtime.getRuntime(); abstraction.printDot(directory + separator + dotName); if (new File(directory + separator + dotName).exists()) { String command; if (System.getProperty("os.name") .contentEquals("Linux")) { command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase() .startsWith("mac os")) { command = "open "; } else { command = "dotty "; } Process dot = exec.exec(command + dotName, null, work); log.addText(command + dotName + "\n"); dot.waitFor(); } else { JOptionPane.showMessageDialog(Gui.frame, "Unable to view LHPN.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e) { e.printStackTrace(); } } } } public void saveAs() { String newName = JOptionPane.showInputDialog(Gui.frame, "Enter Verification name:", "Verification Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".ver")) { newName = newName + ".ver"; } save(newName); } public void save() { save(verFile); } public void save(String filename) { try { Properties prop = new Properties(); FileInputStream in = new FileInputStream(new File(directory + separator + filename)); prop.load(in); in.close(); prop.setProperty("verification.file", verifyFile); if (!bddSize.equals("")) { prop.setProperty("verification.bddSize", this.bddSize.getText() .trim()); } if (!componentField.getText().trim().equals("")) { prop.setProperty("verification.component", componentField .getText().trim()); } else { prop.remove("verification.component"); } String[] components = componentList.getItems(); if (components.length == 0) { for (Object s : prop.keySet()) { if (s.toString().startsWith("verification.compList")) { prop.remove(s); } } } else { for (Integer i = 0; i < components.length; i++) { prop.setProperty("verification.compList" + i.toString(), components[i]); } } String[] lpns = lpnList.getItems(); if (lpns.length == 0) { for (Object s : prop.keySet()) { if (s.toString().startsWith("verification.lpnList")) { prop.remove(s); } } } else { for (Integer i = 0; i < lpns.length; i++) { prop.setProperty("verification.lpnList" + i.toString(), lpns[i]); } } if (none.isSelected()) { prop.setProperty("verification.abstraction", "none"); } else if (simplify.isSelected()) { prop.setProperty("verification.abstraction", "simplify"); } else { prop.setProperty("verification.abstraction", "abstract"); } if (atacs) { if (untimed.isSelected()) { prop.setProperty("verification.timing.methods", "untimed"); } else if (geometric.isSelected()) { prop .setProperty("verification.timing.methods", "geometric"); } else if (posets.isSelected()) { prop.setProperty("verification.timing.methods", "posets"); } else if (bag.isSelected()) { prop.setProperty("verification.timing.methods", "bag"); } else if (bap.isSelected()) { prop.setProperty("verification.timing.methods", "bap"); } else if (baptdc.isSelected()) { prop.setProperty("verification.timing.methods", "baptdc"); } else if (lhpn.isSelected()) { prop.setProperty("verification.timing.methods", "lhpn"); } else { prop.setProperty("verification.timing.methods", "view"); } } else { if (bdd.isSelected()) { prop.setProperty("verification.timing.methods", "bdd"); } else if (dbm.isSelected()) { prop.setProperty("verification.timing.methods", "dbm"); } else if (smt.isSelected()) { prop.setProperty("verification.timing.methods", "smt"); } else if (untimedStateSearch.isSelected()) { prop.setProperty("verification.timing.methods", "untimedStateSearch"); } else if (lhpn.isSelected()) { prop.setProperty("verification.timing.methods", "lhpn"); } else { prop.setProperty("verification.timing.methods", "view"); } } if (abst.isSelected()) { prop.setProperty("verification.Abst", "true"); } else { prop.setProperty("verification.Abst", "false"); } if (partialOrder.isSelected()) { prop.setProperty("verification.partial.order", "true"); } else { prop.setProperty("verification.partial.order", "false"); } if (dot.isSelected()) { prop.setProperty("verification.Dot", "true"); } else { prop.setProperty("verification.Dot", "false"); } if (verbose.isSelected()) { prop.setProperty("verification.Verb", "true"); } else { prop.setProperty("verification.Verb", "false"); } if (graph.isSelected()) { prop.setProperty("verification.Graph", "true"); } else { prop.setProperty("verification.Graph", "false"); } if (untimedPOR.isSelected()) { prop.setProperty("verification.UntimedPOR", "true"); } else { prop.setProperty("verification.UntimedPOR", "false"); } if (decomposeLPN.isSelected()) { prop.setProperty("verification.DecomposeLPN", "true"); } else { prop.setProperty("verification.DecomposeLPN", "false"); } if (multipleLPNs.isSelected()) { prop.setProperty("verification.MultipleLPNs", "true"); } else { prop.setProperty("verification.MultipleLPNs", "false"); } if (verify.isSelected()) { prop.setProperty("verification.algorithm", "verify"); } else if (vergate.isSelected()) { prop.setProperty("verification.algorithm", "vergate"); } else if (orbits.isSelected()) { prop.setProperty("verification.algorithm", "orbits"); } else if (search.isSelected()) { prop.setProperty("verification.algorithm", "search"); } else if (trace.isSelected()) { prop.setProperty("verification.algorithm", "trace"); } if (newTab.isSelected()) { prop.setProperty("verification.compilation.newTab", "true"); } else { prop.setProperty("verification.compilation.newTab", "false"); } if (postProc.isSelected()) { prop.setProperty("verification.compilation.postProc", "true"); } else { prop.setProperty("verification.compilation.postProc", "false"); } if (redCheck.isSelected()) { prop.setProperty("verification.compilation.redCheck", "true"); } else { prop.setProperty("verification.compilation.redCheck", "false"); } if (xForm2.isSelected()) { prop.setProperty("verification.compilation.xForm2", "true"); } else { prop.setProperty("verification.compilation.xForm2", "false"); } if (expandRate.isSelected()) { prop.setProperty("verification.compilation.expandRate", "true"); } else { prop .setProperty("verification.compilation.expandRate", "false"); } if (genrg.isSelected()) { prop.setProperty("verification.timing.genrg", "true"); } else { prop.setProperty("verification.timing.genrg", "false"); } if (timsubset.isSelected()) { prop.setProperty("verification.timing.subset", "true"); } else { prop.setProperty("verification.timing.subset", "false"); } if (superset.isSelected()) { prop.setProperty("verification.timing.superset", "true"); } else { prop.setProperty("verification.timing.superset", "false"); } if (infopt.isSelected()) { prop.setProperty("verification.timing.infopt", "true"); } else { prop.setProperty("verification.timing.infopt", "false"); } if (orbmatch.isSelected()) { prop.setProperty("verification.timing.orbmatch", "true"); } else { prop.setProperty("verification.timing.orbmatch", "false"); } if (interleav.isSelected()) { prop.setProperty("verification.timing.interleav", "true"); } else { prop.setProperty("verification.timing.interleav", "false"); } if (prune.isSelected()) { prop.setProperty("verification.timing.prune", "true"); } else { prop.setProperty("verification.timing.prune", "false"); } if (disabling.isSelected()) { prop.setProperty("verification.timing.disabling", "true"); } else { prop.setProperty("verification.timing.disabling", "false"); } if (nofail.isSelected()) { prop.setProperty("verification.timing.nofail", "true"); } else { prop.setProperty("verification.timing.nofail", "false"); } if (nofail.isSelected()) { prop.setProperty("verification.timing.noproj", "true"); } else { prop.setProperty("verification.timing.noproj", "false"); } if (keepgoing.isSelected()) { prop.setProperty("verification.timing.keepgoing", "true"); } else { prop.setProperty("verification.timing.keepgoing", "false"); } if (explpn.isSelected()) { prop.setProperty("verification.timing.explpn", "true"); } else { prop.setProperty("verification.timing.explpn", "false"); } if (nochecks.isSelected()) { prop.setProperty("verification.nochecks", "true"); } else { prop.setProperty("verification.nochecks", "false"); } if (reduction.isSelected()) { prop.setProperty("verification.reduction", "true"); } else { prop.setProperty("verification.reduction", "false"); } String intVars = ""; for (int i = 0; i < abstPane.listModel.getSize(); i++) { if (abstPane.listModel.getElementAt(i) != null) { intVars = intVars + abstPane.listModel.getElementAt(i) + " "; } } if (sListModel.size() > 0) { String list = ""; for (Object o : sListModel.toArray()) { list = list + o + " "; } list.trim(); prop.put("verification.sList", list); } else { prop.remove("verification.sList"); } if (!intVars.equals("")) { prop.setProperty("abstraction.interesting", intVars.trim()); } else { prop.remove("abstraction.interesting"); } for (Integer i=0; i<abstPane.preAbsModel.size(); i++) { prop.setProperty("abstraction.transform." + abstPane.preAbsModel.getElementAt(i).toString(), "preloop" + i.toString()); } for (Integer i=0; i<abstPane.loopAbsModel.size(); i++) { if (abstPane.preAbsModel.contains(abstPane.loopAbsModel.getElementAt(i))) { String value = prop.getProperty("abstraction.transform." + abstPane.loopAbsModel.getElementAt(i).toString()); value = value + "mainloop" + i.toString(); prop.setProperty("abstraction.transform." + abstPane.loopAbsModel.getElementAt(i).toString(), value); } else { prop.setProperty("abstraction.transform." + abstPane.loopAbsModel.getElementAt(i).toString(), "mainloop" + i.toString()); } } for (Integer i=0; i<abstPane.postAbsModel.size(); i++) { if (abstPane.preAbsModel.contains(abstPane.postAbsModel.getElementAt(i)) || abstPane.preAbsModel.contains(abstPane.postAbsModel.get(i))) { String value = prop.getProperty("abstraction.transform." + abstPane.postAbsModel.getElementAt(i).toString()); value = value + "postloop" + i.toString(); prop.setProperty("abstraction.transform." + abstPane.postAbsModel.getElementAt(i).toString(), value); } else { prop.setProperty("abstraction.transform." + abstPane.postAbsModel.getElementAt(i).toString(), "postloop" + i.toString()); } } for (String s : abstPane.transforms) { if (!abstPane.preAbsModel.contains(s) && !abstPane.loopAbsModel.contains(s) && !abstPane.postAbsModel.contains(s)) { prop.remove(s); } } if (!abstPane.factorField.getText().equals("")) { prop.setProperty("abstraction.factor", abstPane.factorField .getText()); } if (!abstPane.iterField.getText().equals("")) { prop.setProperty("abstraction.iterations", abstPane.iterField .getText()); } FileOutputStream out = new FileOutputStream(new File(directory + separator + verFile)); prop.store(out, verifyFile); out.close(); log.addText("Saving Parameter File:\n" + directory + separator + verFile + "\n"); change = false; oldBdd = bddSize.getText(); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(Gui.frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } for (String s : componentList.getItems()) { try { new File(directory + separator + s).createNewFile(); FileInputStream in = new FileInputStream(new File(root + separator + s)); FileOutputStream out = new FileOutputStream(new File(directory + separator + s)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } catch (IOException e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(Gui.frame, "Cannot add the selected component.", "Error", JOptionPane.ERROR_MESSAGE); } } for (String s : lpnList.getItems()) { try { new File(directory + separator + s).createNewFile(); FileInputStream in = new FileInputStream(new File(root + separator + s)); FileOutputStream out = new FileOutputStream(new File(directory + separator + s)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } catch (IOException e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(Gui.frame, "Cannot add the selected LPN.", "Error", JOptionPane.ERROR_MESSAGE); } } } public void reload(String newname) { } public void viewCircuit() { String[] getFilename; if (componentField.getText().trim().equals("")) { getFilename = verifyFile.split("\\."); } else { getFilename = new String[1]; getFilename[0] = componentField.getText().trim(); } String circuitFile = getFilename[0] + ".prs"; try { if (new File(circuitFile).exists()) { File log = new File(circuitFile); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(Gui.frame, scrolls, "Circuit View", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(Gui.frame, "No circuit view exists.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Unable to view circuit.", "Error", JOptionPane.ERROR_MESSAGE); } } public boolean getViewTraceEnabled() { return viewTrace.isEnabled(); } public boolean getViewLogEnabled() { return viewLog.isEnabled(); } public void viewTrace() { String[] getFilename = verifyFile.split("\\."); String traceFilename = getFilename[0] + ".trace"; try { if (new File(directory + separator + traceFilename).exists()) { File log = new File(directory + separator + traceFilename); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(Gui.frame, scrolls, "Trace View", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(Gui.frame, "No trace file exists.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane .showMessageDialog(Gui.frame, "Unable to view trace.", "Error", JOptionPane.ERROR_MESSAGE); } } public void viewLog() { try { if (new File(directory + separator + "run.log").exists()) { File log = new File(directory + separator + "run.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(Gui.frame, scrolls, "Run Log", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(Gui.frame, "No run log exists.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Unable to view run log.", "Error", JOptionPane.ERROR_MESSAGE); } } public boolean hasChanged() { if (!oldBdd.equals(bddSize.getText())) { return true; } return change; } public boolean isSimplify() { if (simplify.isSelected()) return true; return false; } public void copyFile() { String[] tempArray = verifyFile.split(separator); String sourceFile = tempArray[tempArray.length - 1]; String[] workArray = directory.split(separator); String workDir = ""; for (int i = 0; i < (workArray.length - 1); i++) { workDir = workDir + workArray[i] + separator; } try { File newFile = new File(directory + separator + sourceFile); newFile.createNewFile(); FileOutputStream copyin = new FileOutputStream(newFile); FileInputStream copyout = new FileInputStream(new File(workDir + separator + sourceFile)); int read = copyout.read(); while (read != -1) { copyin.write(read); read = copyout.read(); } copyin.close(); copyout.close(); } catch (IOException e) { JOptionPane.showMessageDialog(Gui.frame, "Cannot copy file " + sourceFile, "Copy Error", JOptionPane.ERROR_MESSAGE); } /* TODO Test Assembly File compilation */ if (sourceFile.endsWith(".s") || sourceFile.endsWith(".inst")) { biosim.copySFiles(verifyFile, directory); try { String preprocCmd; if (lema) { preprocCmd = System.getenv("LEMA") + "/bin/s2lpn " + verifyFile; } else if (atacs) { preprocCmd = System.getenv("ATACS") + "/bin/s2lpn " + verifyFile; } else { preprocCmd = System.getenv("BIOSIM") + "/bin/s2lpn " + verifyFile; } //for (Object o : sListModel.toArray()) { // preprocCmd = preprocCmd + " " + o.toString(); File work = new File(directory); Runtime exec = Runtime.getRuntime(); Process preproc = exec.exec(preprocCmd, null, work); log.addText("Executing:\n" + preprocCmd + "\n"); preproc.waitFor(); if (verifyFile.endsWith(".s")) { verifyFile.replace(".s", ".lpn"); } else { verifyFile.replace(".inst", ".lpn"); } } catch (Exception e) { JOptionPane.showMessageDialog(Gui.frame, "Error with preprocessing.", "Error", JOptionPane.ERROR_MESSAGE); //e.printStackTrace(); } } } public String getVerName() { String verName = verFile.replace(".ver", ""); return verName; } public AbstPane getAbstPane() { return abstPane; } /** * Calls the appropriate dot program to show the graph. * @param fileName The absolute file name. */ public void showGraph(String fileName) { File file = new File(fileName); File work = file.getParentFile(); try { Runtime exec = Runtime.getRuntime(); if (new File(fileName).exists()) { long kB = 1024; // number of bytes in a kilobyte. long fileSize = file.length()/kB; // Size of file in megabytes. // If the file is larger than a given amount of megabytes, // then give the user the chance to cancel the operation. int thresholdSize = 100; // Specifies the threshold for giving the // user the option to not attempt to open the file. if(fileSize > thresholdSize) { int answer = JOptionPane.showConfirmDialog(Gui.frame, "The size of the file exceeds " + thresholdSize + " kB." + "The file may not open. Do you want to continue?", "Do you want to continue?", JOptionPane.YES_NO_OPTION); if(answer == JOptionPane.NO_OPTION) { return; } } String command; if (System.getProperty("os.name") .contentEquals("Linux")) { command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase() .startsWith("mac os")) { command = "open "; } else { command = "dotty "; } Process dot = exec.exec(command + fileName, null, work); log.addText(command + fileName + "\n"); dot.waitFor(); } else { JOptionPane.showMessageDialog(Gui.frame, "Unable to view dot file.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e) { e.printStackTrace(); } } }
package com.elmakers.mine.bukkit.block; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.bukkit.Server; import org.bukkit.block.Block; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Entity; import org.bukkit.entity.FallingBlock; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.util.BlockVector; import com.elmakers.mine.bukkit.api.block.BlockData; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.block.batch.CleanupBlocksTask; import com.elmakers.mine.bukkit.block.batch.UndoBatch; /** * Implements a Collection of Blocks, for quick getting/putting while iterating * over a set or area of blocks. * * This stores BlockData objects, which are hashable via their Persisted * inheritance, and their LocationData id (which itself has a hash function * based on world name and BlockVector's hash function) * */ public class BlockList implements com.elmakers.mine.bukkit.api.block.BlockList { /** * Default serial id, in case you want to serialize this (probably shouldn't * though!) * * Persist it instead, once I've got that working. */ protected BoundingBox area; // HashMap backing and easy persistence - need an extra list for this right // now. protected ArrayList<BlockData> blockList; protected HashSet<Long> blockIdMap; protected int passesRemaining = 1; protected int timeToLive = 0; protected int taskId = 0; protected static Map<Long, BlockData> modified = new HashMap<Long, BlockData>(); protected Set<FallingBlock> fallingBlocks = new HashSet<FallingBlock>(); protected Set<Entity> explodingEntities = new HashSet<Entity>(); public BlockList() { } public BlockList(BlockList other) { for (BlockData block : other) { BlockData newBlock = new com.elmakers.mine.bukkit.block.BlockData(block); add(newBlock); } timeToLive = other.timeToLive; passesRemaining = other.passesRemaining; } public boolean add(Block block) { if (contains(block)) { return true; } BlockData newBlock = new com.elmakers.mine.bukkit.block.BlockData(block); return add(newBlock); } public boolean add(BlockData blockData) { // First do a sanity check with the map // Currently, we don't replace blocks! if (contains(blockData)) return true; if (blockIdMap == null) { blockIdMap = new HashSet<Long>(); } if (blockList == null) { blockList = new ArrayList<BlockData>(); } BlockVector blockLocation = blockData.getPosition(); if (area == null) { area = new BoundingBox(blockLocation, blockLocation); } else { area = area.contain(blockLocation); } blockIdMap.add(blockData.getId()); return blockList.add(blockData); } @Override public boolean addAll(Collection<? extends BlockData> blocks) { // Iterate to maintain BB area boolean added = true; for (BlockData block : blocks) { added = added && add(block); } return added; } @Override public void clear() { if (blockList == null) { return; } blockList.clear(); } public boolean contains(Block block) { if (blockIdMap == null) return false; return blockIdMap.contains(com.elmakers.mine.bukkit.block.BlockData.getBlockId(block)); } public boolean contains(BlockData blockData) { if (blockIdMap == null || blockData == null) { return false; } return blockIdMap.contains(blockData.getId()); } public boolean contains(Object arg0) { if (arg0 instanceof Block) { return contains((Block)arg0); } if (arg0 instanceof BlockData) { return contains((BlockData)arg0); } // Fall back to map return blockIdMap == null ? false : blockIdMap.contains(arg0); } public boolean containsAll(Collection<?> arg0) { if (blockIdMap == null) { return false; } return blockIdMap.containsAll(arg0); } // Collection interface- would be great if I could just extend HashSet and // have this "just work" // For now, this is here to keep the map up to date, and to pass through to // the blockList. public BoundingBox getArea() { return area; } public ArrayList<BlockData> getBlockList() { return blockList; } public boolean isEmpty() { if (blockList == null) { return true; } return blockList.isEmpty(); } public Iterator<BlockData> iterator() { if (blockList == null) { return null; } return blockList.iterator(); } public boolean remove(Object arg0) { // Note that we never shrink the BB! if (blockList == null) { return false; } return blockList.remove(arg0); } public boolean removeAll(Collection<?> arg0) { if (blockList == null) { return false; } return blockList.removeAll(arg0); } public boolean retainAll(Collection<?> arg0) { if (blockList == null) { return false; } return blockList.retainAll(arg0); } public void setArea(BoundingBox area) { this.area = area; } public void setBlockList(ArrayList<BlockData> blockList) { this.blockList = blockList; if (blockList != null) { blockIdMap = new HashSet<Long>(); for (BlockData block : blockList) { blockIdMap.add(block.getId()); } } } public void setRepetitions(int repeat) { passesRemaining = repeat; } public boolean isComplete() { return passesRemaining <= 0; } public void setTimeToLive(int ttl) { timeToLive = ttl; } public int getTimeToLive() { return timeToLive; } public int size() { if (blockList == null) { return 0; } return blockList.size(); } public BlockData get(int index) { if (blockList == null || index >= blockList.size()) { return null; } return blockList.get(index); } public Object[] toArray() { if (blockList == null) { return null; } return blockList.toArray(); } public <T> T[] toArray(T[] arg0) { if (blockList == null) { return null; } return blockList.toArray(arg0); } public void prepareForUndo() { if (blockList == null) return; for (BlockData blockData : blockList) { BlockData priorState = modified.get(blockData.getId()); if (priorState != null) { priorState.setNextState(blockData); blockData.setPriorState(priorState); } modified.put(blockData.getId(), blockData); } } public void commit() { if (blockList == null) return; for (BlockData block : blockList) { BlockData currentState = modified.get(block.getId()); if (currentState == block) { modified.remove(block.getId()); } block.commit(); } } public boolean undo(BlockData undoBlock) { if (undoBlock.undo()) { BlockData currentState = modified.get(undoBlock.getId()); if (currentState == undoBlock) { modified.put(undoBlock.getId(), undoBlock.getPriorState()); } undoBlock.undo(); return true; } return false; } public boolean undo(Mage mage) { if (blockList == null) return true; // This part doesn't happen asynchronously for (FallingBlock falling : fallingBlocks) { falling.remove(); } fallingBlocks.clear(); for (Entity entity : explodingEntities) { entity.remove(); } explodingEntities.clear(); UndoBatch batch = new UndoBatch(mage.getController(), this); if (!mage.addPendingBlockBatch(batch)) { return false; } passesRemaining return true; } public void load(ConfigurationSection node) { timeToLive = node.getInt("time_to_live", timeToLive); passesRemaining = node.getInt("passes_remaining", passesRemaining); List<String> blockData = node.getStringList("blocks"); if (blockData != null) { for (String blockString : blockData) { add(com.elmakers.mine.bukkit.block.BlockData.fromString(blockString)); } } } public void save(ConfigurationSection node) { node.set("time_to_live", (Integer)timeToLive); node.set("passes_remaining", (Integer)passesRemaining); List<String> blockData = new ArrayList<String>(); if (blockList != null) { for (BlockData block : blockList) { blockData.add(block.toString()); } node.set("blocks", blockData); } } public String getWorldName() { if (blockList.size() == 0) return null; return blockList.get(0).getWorldName(); } public void scheduleCleanup(Mage mage) { Plugin plugin = mage.getController().getPlugin(); Server server = plugin.getServer(); BukkitScheduler scheduler = server.getScheduler(); // scheduler works in ticks- 20 ticks per second. long ticksToLive = timeToLive * 20 / 1000; taskId = scheduler.scheduleSyncDelayedTask(plugin, new CleanupBlocksTask(mage, this), ticksToLive); } public boolean undoScheduled(Mage mage) { if (taskId > 0) { Plugin plugin = mage.getController().getPlugin(); Server server = plugin.getServer(); BukkitScheduler scheduler = server.getScheduler(); scheduler.cancelTask(taskId); taskId = 0; } return this.undo(mage); } public void add(Plugin plugin, FallingBlock fallingBlock) { fallingBlocks.add(fallingBlock); fallingBlock.setMetadata("MagicBlockList", new FixedMetadataValue(plugin, this)); } public void convert(FallingBlock fallingBlock, Block block) { fallingBlocks.remove(fallingBlock); add(block); } public void addExplodingEntity(Plugin plugin, Entity explodingEntity) { explodingEntities.add(explodingEntity); explodingEntity.setMetadata("MagicBlockList", new FixedMetadataValue(plugin, this)); } public void explode(Entity explodingEntity, List<Block> blocks) { explodingEntities.remove(explodingEntity); for (Block block : blocks) { add(block); } } public void cancelExplosion(Entity explodingEntity) { explodingEntities.remove(explodingEntity); } }
package verification; import java.awt.AWTError; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Properties; import java.util.prefs.Preferences; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import lpn.parser.Abstraction; import lpn.parser.LhpnFile; import lpn.parser.Place; import lpn.parser.Transition; import lpn.parser.Variable; import lpn.parser.LpnDecomposition.Component; import lpn.parser.LpnDecomposition.LpnComponentList; import lpn.parser.LpnDecomposition.LpnProcess; import main.Gui; import main.Log; import verification.platu.main.Options; import verification.platu.project.Project; import verification.timed_state_exploration.zoneProject.Zone; import biomodel.gui.PropertyList; import biomodel.util.Utility; /** * This class creates a GUI front end for the Verification tool. It provides the * necessary options to run an atacs simulation of the circuit and manage the * results from the BioSim GUI. * * @author Kevin Jones */ public class Verification extends JPanel implements ActionListener, Runnable { private static final long serialVersionUID = -5806315070287184299L; private JButton save, run, viewCircuit, viewTrace, viewLog, addComponent, removeComponent, addSFile, addLPN, removeLPN; private JLabel algorithm, timingMethod, timingOptions, otherOptions, otherOptions2, compilation, bddSizeLabel, advTiming, abstractLabel, listLabel; public JRadioButton untimed, geometric, posets, bag, bap, baptdc, verify, vergate, orbits, search, trace, bdd, dbm, smt, untimedStateSearch, lhpn, view, none, simplify, abstractLhpn, dbm2, splitZone; private JCheckBox abst, partialOrder, dot, verbose, graph, untimedPOR, decomposeLPN, multipleLPNs, genrg, timsubset, superset, infopt, orbmatch, interleav, prune, disabling, nofail, noproj, keepgoing, explpn, nochecks, reduction, newTab, postProc, redCheck, xForm2, expandRate, useGraphs; private JTextField bddSize, backgroundField, componentField; private JList sList; private DefaultListModel sListModel; private ButtonGroup timingMethodGroup, algorithmGroup, abstractionGroup; private String directory, separator, root, verFile, oldBdd, sourceFileNoPath; public String verifyFile; private boolean change, atacs, lema; private PropertyList componentList, lpnList; private AbstPane abstPane; private Log log; private Gui biosim; /** * This is the constructor for the Verification class. It initializes all * the input fields, puts them on panels, adds the panels to the frame, and * then displays the frame. */ public Verification(String directory, String verName, String filename, Log log, Gui biosim, boolean lema, boolean atacs) { if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } this.atacs = atacs; this.lema = lema; this.biosim = biosim; this.log = log; this.directory = directory; verFile = verName + ".ver"; String[] tempArray = filename.split("\\."); String traceFilename = tempArray[0] + ".trace"; File traceFile = new File(traceFilename); String[] tempDir = directory.split(separator); root = tempDir[0]; for (int i = 1; i < tempDir.length - 1; i++) { root = root + separator + tempDir[i]; } this.setMaximumSize(new Dimension(300,300)); this.setMinimumSize(new Dimension(300,300)); JPanel abstractionPanel = new JPanel(); abstractionPanel.setMaximumSize(new Dimension(1000, 35)); JPanel timingRadioPanel = new JPanel(); timingRadioPanel.setMaximumSize(new Dimension(1000, 35)); JPanel timingCheckBoxPanel = new JPanel(); timingCheckBoxPanel.setMaximumSize(new Dimension(1000, 30)); JPanel otherPanel = new JPanel(); otherPanel.setMaximumSize(new Dimension(1000, 35)); JPanel preprocPanel = new JPanel(); preprocPanel.setMaximumSize(new Dimension(1000, 700)); JPanel algorithmPanel = new JPanel(); algorithmPanel.setMaximumSize(new Dimension(1000, 35)); JPanel buttonPanel = new JPanel(); JPanel compilationPanel = new JPanel(); compilationPanel.setMaximumSize(new Dimension(1000, 35)); JPanel advancedPanel = new JPanel(); advancedPanel.setMaximumSize(new Dimension(1000, 35)); JPanel bddPanel = new JPanel(); bddPanel.setMaximumSize(new Dimension(1000, 35)); JPanel pruningPanel = new JPanel(); pruningPanel.setMaximumSize(new Dimension(1000, 35)); JPanel advTimingPanel = new JPanel(); advTimingPanel.setMaximumSize(new Dimension(1000, 62)); advTimingPanel.setPreferredSize(new Dimension(1000, 62)); bddSize = new JTextField(""); bddSize.setPreferredSize(new Dimension(40, 18)); oldBdd = bddSize.getText(); componentField = new JTextField(""); componentList = new PropertyList(""); lpnList = new PropertyList(""); abstractLabel = new JLabel("Abstraction:"); algorithm = new JLabel("Verification Algorithm:"); timingMethod = new JLabel("Timing Method:"); timingOptions = new JLabel("Timing Options:"); otherOptions = new JLabel("Other Options:"); otherOptions2 = new JLabel("Other Options:"); compilation = new JLabel("Compilation Options:"); bddSizeLabel = new JLabel("BDD Linkspace Size:"); advTiming = new JLabel("Timing Options:"); //preprocLabel = new JLabel("Preprocess Command:"); listLabel = new JLabel("Assembly Files:"); JPanel labelPane = new JPanel(); labelPane.add(listLabel); sListModel = new DefaultListModel(); sList = new JList(sListModel); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(260, 200)); scroll.setPreferredSize(new Dimension(276, 132)); scroll.setViewportView(sList); JPanel scrollPane = new JPanel(); scrollPane.add(scroll); addSFile = new JButton("Add File"); addSFile.addActionListener(this); JPanel buttonPane = new JPanel(); buttonPane.add(addSFile); //preprocStr = new JTextField(); //preprocStr.setPreferredSize(new Dimension(500, 18)); // Initializes the radio buttons and check boxes // Abstraction Options none = new JRadioButton("None"); simplify = new JRadioButton("Simplification"); abstractLhpn = new JRadioButton("Abstraction"); // Timing Methods if (atacs) { untimed = new JRadioButton("Untimed"); geometric = new JRadioButton("Geometric"); posets = new JRadioButton("POSETs"); bag = new JRadioButton("BAG"); bap = new JRadioButton("BAP"); baptdc = new JRadioButton("BAPTDC"); untimed.addActionListener(this); geometric.addActionListener(this); posets.addActionListener(this); bag.addActionListener(this); bap.addActionListener(this); baptdc.addActionListener(this); } else { untimedStateSearch = new JRadioButton("Untimed"); bdd = new JRadioButton("BDD"); dbm = new JRadioButton("DBM"); smt = new JRadioButton("SMT"); dbm2 = new JRadioButton("DBM2"); splitZone = new JRadioButton("Split Zone"); bdd.addActionListener(this); dbm.addActionListener(this); smt.addActionListener(this); dbm2.addActionListener(this); splitZone.addActionListener(this); } lhpn = new JRadioButton("LPN"); view = new JRadioButton("View"); lhpn.addActionListener(this); view.addActionListener(this); // Basic Timing Options abst = new JCheckBox("Abstract"); partialOrder = new JCheckBox("Partial Order"); abst.addActionListener(this); partialOrder.addActionListener(this); // Other Basic Options dot = new JCheckBox("Dot"); verbose = new JCheckBox("Verbose"); graph = new JCheckBox("Show State Graph"); untimedPOR = new JCheckBox("Use Partial Orders"); decomposeLPN = new JCheckBox("Decompose LPN into components"); multipleLPNs = new JCheckBox("Multiple LPNs"); dot.addActionListener(this); verbose.addActionListener(this); graph.addActionListener(this); untimedPOR.addActionListener(this); decomposeLPN.addActionListener(this); multipleLPNs.addActionListener(this); // Verification Algorithms verify = new JRadioButton("Verify"); vergate = new JRadioButton("Verify Gates"); orbits = new JRadioButton("Orbits"); search = new JRadioButton("Search"); trace = new JRadioButton("Trace"); verify.addActionListener(this); vergate.addActionListener(this); orbits.addActionListener(this); search.addActionListener(this); trace.addActionListener(this); // Compilations Options newTab = new JCheckBox("New Tab"); postProc = new JCheckBox("Post Processing"); redCheck = new JCheckBox("Redundancy Check"); xForm2 = new JCheckBox("Don't Use Transform 2"); expandRate = new JCheckBox("Expand Rate"); newTab.addActionListener(this); postProc.addActionListener(this); redCheck.addActionListener(this); xForm2.addActionListener(this); expandRate.addActionListener(this); // Advanced Timing Options genrg = new JCheckBox("Generate RG"); timsubset = new JCheckBox("Subsets"); superset = new JCheckBox("Supersets"); infopt = new JCheckBox("Infinity Optimization"); orbmatch = new JCheckBox("Orbits Match"); interleav = new JCheckBox("Interleave"); prune = new JCheckBox("Prune"); disabling = new JCheckBox("Disabling"); nofail = new JCheckBox("No fail"); noproj = new JCheckBox("No project"); keepgoing = new JCheckBox("Keep going"); explpn = new JCheckBox("Expand LPN"); useGraphs = new JCheckBox("Use Graph Storage"); genrg.addActionListener(this); timsubset.addActionListener(this); superset.addActionListener(this); infopt.addActionListener(this); orbmatch.addActionListener(this); interleav.addActionListener(this); prune.addActionListener(this); disabling.addActionListener(this); nofail.addActionListener(this); noproj.addActionListener(this); keepgoing.addActionListener(this); explpn.addActionListener(this); useGraphs.addActionListener(this); // Other Advanced Options nochecks = new JCheckBox("No checks"); reduction = new JCheckBox("Reduction"); nochecks.addActionListener(this); reduction.addActionListener(this); // Component List addComponent = new JButton("Add Component"); removeComponent = new JButton("Remove Component"); GridBagConstraints constraints = new GridBagConstraints(); JPanel componentPanel = Utility.createPanel(this, "Components", componentList, addComponent, removeComponent, null); constraints.gridx = 0; constraints.gridy = 1; // LPN List addLPN = new JButton("Add LPN"); removeLPN = new JButton("Remove LPN"); GridBagConstraints gridBagConstraints = new GridBagConstraints(); JPanel LPNPanel = Utility.createPanel(this, "LPNs", lpnList, addLPN, removeLPN, null); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; abstractionGroup = new ButtonGroup(); timingMethodGroup = new ButtonGroup(); algorithmGroup = new ButtonGroup(); none.setSelected(true); if (lema) { dbm.setSelected(true); } else if (atacs) { untimed.setSelected(true); } verify.setSelected(true); // Groups the radio buttons abstractionGroup.add(none); abstractionGroup.add(simplify); abstractionGroup.add(abstractLhpn); if (lema) { timingMethodGroup.add(untimedStateSearch); timingMethodGroup.add(splitZone); timingMethodGroup.add(bdd); timingMethodGroup.add(dbm); timingMethodGroup.add(smt); timingMethodGroup.add(dbm2); } else { timingMethodGroup.add(untimed); timingMethodGroup.add(geometric); timingMethodGroup.add(posets); timingMethodGroup.add(bag); timingMethodGroup.add(bap); timingMethodGroup.add(baptdc); } timingMethodGroup.add(lhpn); timingMethodGroup.add(view); algorithmGroup.add(verify); algorithmGroup.add(vergate); algorithmGroup.add(orbits); algorithmGroup.add(search); algorithmGroup.add(trace); JPanel basicOptions = new JPanel(); JPanel advOptions = new JPanel(); // Adds the buttons to their panels abstractionPanel.add(abstractLabel); abstractionPanel.add(none); abstractionPanel.add(simplify); abstractionPanel.add(abstractLhpn); timingRadioPanel.add(timingMethod); if (atacs) { timingRadioPanel.add(untimed); timingRadioPanel.add(geometric); timingRadioPanel.add(posets); timingRadioPanel.add(bag); timingRadioPanel.add(bap); timingRadioPanel.add(baptdc); } else { timingRadioPanel.add(untimedStateSearch); timingRadioPanel.add(splitZone); timingRadioPanel.add(bdd); timingRadioPanel.add(dbm); timingRadioPanel.add(smt); timingRadioPanel.add(dbm2); } timingRadioPanel.add(lhpn); timingRadioPanel.add(view); timingCheckBoxPanel.add(timingOptions); timingCheckBoxPanel.add(abst); timingCheckBoxPanel.add(partialOrder); otherPanel.add(otherOptions); otherPanel.add(dot); otherPanel.add(verbose); otherPanel.add(graph); otherPanel.add(untimedPOR); otherPanel.add(decomposeLPN); otherPanel.add(multipleLPNs); preprocPanel.add(labelPane); preprocPanel.add(scrollPane); preprocPanel.add(buttonPane); algorithmPanel.add(algorithm); algorithmPanel.add(verify); algorithmPanel.add(vergate); algorithmPanel.add(orbits); algorithmPanel.add(search); algorithmPanel.add(trace); compilationPanel.add(compilation); compilationPanel.add(newTab); compilationPanel.add(postProc); compilationPanel.add(redCheck); compilationPanel.add(xForm2); compilationPanel.add(expandRate); advTimingPanel.add(advTiming); advTimingPanel.add(genrg); advTimingPanel.add(timsubset); advTimingPanel.add(superset); advTimingPanel.add(infopt); advTimingPanel.add(orbmatch); advTimingPanel.add(interleav); advTimingPanel.add(prune); advTimingPanel.add(disabling); advTimingPanel.add(nofail); advTimingPanel.add(noproj); advTimingPanel.add(keepgoing); advTimingPanel.add(explpn); advTimingPanel.add(useGraphs); advancedPanel.add(otherOptions2); advancedPanel.add(nochecks); advancedPanel.add(reduction); bddPanel.add(bddSizeLabel); bddPanel.add(bddSize); // load parameters Properties load = new Properties(); verifyFile = ""; try { FileInputStream in = new FileInputStream(new File(directory + separator + verFile)); load.load(in); in.close(); if (load.containsKey("verification.file")) { verifyFile = load.getProperty("verification.file"); } if (load.containsKey("verification.bddSize")) { bddSize.setText(load.getProperty("verification .bddSize")); } if (load.containsKey("verification.component")) { componentField.setText(load .getProperty("verification.component")); } Integer i = 0; while (load.containsKey("verification.compList" + i.toString())) { componentList.addItem(load.getProperty("verification.compList" + i.toString())); i++; } Integer k = 0; while (load.containsKey("verification.lpnList" + k.toString())) { lpnList.addItem(load.getProperty("verification.lpnList" + k.toString())); k++; } if (load.containsKey("verification.abstraction")) { if (load.getProperty("verification.abstraction").equals("none")) { none.setSelected(true); } else if (load.getProperty("verification.abstraction").equals( "simplify")) { simplify.setSelected(true); } else { abstractLhpn.setSelected(true); } } abstPane = new AbstPane(root + separator + verName, this, log, lema, atacs); if (load.containsKey("verification.timing.methods")) { if (atacs) { if (load.getProperty("verification.timing.methods").equals( "untimed")) { untimed.setSelected(true); } else if (load.getProperty("verification.timing.methods") .equals("geometric")) { geometric.setSelected(true); } else if (load.getProperty("verification.timing.methods") .equals("posets")) { posets.setSelected(true); } else if (load.getProperty("verification.timing.methods") .equals("bag")) { bag.setSelected(true); } else if (load.getProperty("verification.timing.methods") .equals("bap")) { bap.setSelected(true); } else if (load.getProperty("verification.timing.methods") .equals("baptdc")) { baptdc.setSelected(true); } else if (load.getProperty("verification.timing.methods") .equals("lhpn")) { lhpn.setSelected(true); } else { view.setSelected(true); } } else { if (load.getProperty("verification.timing.methods").equals( "bdd")) { bdd.setSelected(true); } else if (load.getProperty("verification.timing.methods") .equals("dbm")) { dbm.setSelected(true); } else if (load.getProperty("verification.timing.methods") .equals("smt")) { smt.setSelected(true); } else if (load.getProperty("verification.timing.methods") .equals("untimedStateSearch")) { untimedStateSearch.setSelected(true); } else if (load.getProperty("verification.timing.methods") .equals("lhpn")) { lhpn.setSelected(true); } else { view.setSelected(true); } } } if (load.containsKey("verification.Abst")) { if (load.getProperty("verification.Abst").equals("true")) { abst.setSelected(true); } } if (load.containsKey("verification.partial.order")) { if (load.getProperty("verification.partial.order").equals( "true")) { partialOrder.setSelected(true); } } if (load.containsKey("verification.Dot")) { if (load.getProperty("verification.Dot").equals("true")) { dot.setSelected(true); } } if (load.containsKey("verification.Verb")) { if (load.getProperty("verification.Verb").equals("true")) { verbose.setSelected(true); } } if (load.containsKey("verification.Graph")) { if (load.getProperty("verification.Graph").equals("true")) { graph.setSelected(true); } } if (load.containsKey("verification.UntimedPOR")) { if (load.getProperty("verification.UntimedPOR").equals("true")) { untimedPOR.setSelected(true); } } if (load.containsKey("verification.DecomposeLPN")) { if (load.getProperty("verification.DecomposeLPN").equals("true")) { decomposeLPN.setSelected(true); } } if (load.containsKey("verification.MultipleLPNs")) { if (load.getProperty("verification.MultipleLPNs").equals("true")) { multipleLPNs.setSelected(true); } } if (load.containsKey("verification.partial.order")) { if (load.getProperty("verification.partial.order").equals( "true")) { partialOrder.setSelected(true); } } if (load.containsKey("verification.partial.order")) { if (load.getProperty("verification.partial.order").equals( "true")) { partialOrder.setSelected(true); } } if (load.containsKey("verification.algorithm")) { if (load.getProperty("verification.algorithm").equals("verify")) { verify.setSelected(true); } else if (load.getProperty("verification.algorithm").equals( "vergate")) { vergate.setSelected(true); } else if (load.getProperty("verification.algorithm").equals( "orbits")) { orbits.setSelected(true); } else if (load.getProperty("verification.algorithm").equals( "search")) { search.setSelected(true); } else if (load.getProperty("verification.algorithm").equals( "trace")) { trace.setSelected(true); } } if (load.containsKey("verification.compilation.newTab")) { if (load.getProperty("verification.compilation.newTab").equals( "true")) { newTab.setSelected(true); } } if (load.containsKey("verification.compilation.postProc")) { if (load.getProperty("verification.compilation.postProc") .equals("true")) { postProc.setSelected(true); } } if (load.containsKey("verification.compilation.redCheck")) { if (load.getProperty("verification.compilation.redCheck") .equals("true")) { redCheck.setSelected(true); } } if (load.containsKey("verification.compilation.xForm2")) { if (load.getProperty("verification.compilation.xForm2").equals( "true")) { xForm2.setSelected(true); } } if (load.containsKey("verification.compilation.expandRate")) { if (load.getProperty("verification.compilation.expandRate") .equals("true")) { expandRate.setSelected(true); } } if (load.containsKey("verification.timing.genrg")) { if (load.getProperty("verification.timing.genrg") .equals("true")) { genrg.setSelected(true); } } if (load.containsKey("verification.timing.subset")) { if (load.getProperty("verification.timing.subset").equals( "true")) { timsubset.setSelected(true); } } if (load.containsKey("verification.timing.superset")) { if (load.getProperty("verification.timing.superset").equals( "true")) { superset.setSelected(true); } } if (load.containsKey("verification.timing.infopt")) { if (load.getProperty("verification.timing.infopt").equals( "true")) { infopt.setSelected(true); } } if (load.containsKey("verification.timing.orbmatch")) { if (load.getProperty("verification.timing.orbmatch").equals( "true")) { orbmatch.setSelected(true); } } if (load.containsKey("verification.timing.interleav")) { if (load.getProperty("verification.timing.interleav").equals( "true")) { interleav.setSelected(true); } } if (load.containsKey("verification.timing.prune")) { if (load.getProperty("verification.timing.prune") .equals("true")) { prune.setSelected(true); } } if (load.containsKey("verification.timing.disabling")) { if (load.getProperty("verification.timing.disabling").equals( "true")) { disabling.setSelected(true); } } if (load.containsKey("verification.timing.nofail")) { if (load.getProperty("verification.timing.nofail").equals( "true")) { nofail.setSelected(true); } } if (load.containsKey("verification.timing.noproj")) { if (load.getProperty("verification.timing.noproj").equals( "true")) { nofail.setSelected(true); } } if (load.containsKey("verification.timing.explpn")) { if (load.getProperty("verification.timing.explpn").equals( "true")) { explpn.setSelected(true); } } if (load.containsKey("verification.nochecks")) { if (load.getProperty("verification.nochecks").equals("true")) { nochecks.setSelected(true); } } if (load.containsKey("verification.reduction")) { if (load.getProperty("verification.reduction").equals("true")) { reduction.setSelected(true); } } if (verifyFile.endsWith(".s")) { sListModel.addElement(verifyFile); } if (load.containsKey("verification.sList")) { String concatList = load.getProperty("verification.sList"); String[] list = concatList.split("\\s"); for (String s : list) { sListModel.addElement(s); } } if (load.containsKey("abstraction.interesting")) { String intVars = load.getProperty("abstraction.interesting"); String[] array = intVars.split(" "); for (String s : array) { if (!s.equals("")) { abstPane.addIntVar(s); } } } HashMap<Integer, String> preOrder = new HashMap<Integer, String>(); HashMap<Integer, String> loopOrder = new HashMap<Integer, String>(); HashMap<Integer, String> postOrder = new HashMap<Integer, String>(); boolean containsAbstractions = false; for (String s : abstPane.transforms) { if (load.containsKey(s)) { containsAbstractions = true; } } for (String s : abstPane.transforms) { if (load.containsKey("abstraction.transform." + s)) { if (load.getProperty("abstraction.transform." + s).contains("preloop")) { Pattern prePattern = Pattern.compile("preloop(\\d+)"); Matcher intMatch = prePattern.matcher(load .getProperty("abstraction.transform." + s)); if (intMatch.find()) { Integer index = Integer.parseInt(intMatch.group(1)); preOrder.put(index, s); } else { abstPane.addPreXform(s); } } else { abstPane.preAbsModel.removeElement(s); } if (load.getProperty("abstraction.transform." + s).contains("mainloop")) { Pattern loopPattern = Pattern .compile("mainloop(\\d+)"); Matcher intMatch = loopPattern.matcher(load .getProperty("abstraction.transform." + s)); if (intMatch.find()) { Integer index = Integer.parseInt(intMatch.group(1)); loopOrder.put(index, s); } else { abstPane.addLoopXform(s); } } else { abstPane.loopAbsModel.removeElement(s); } if (load.getProperty("abstraction.transform." + s).contains("postloop")) { Pattern postPattern = Pattern .compile("postloop(\\d+)"); Matcher intMatch = postPattern.matcher(load .getProperty("abstraction.transform." + s)); if (intMatch.find()) { Integer index = Integer.parseInt(intMatch.group(1)); postOrder.put(index, s); } else { abstPane.addPostXform(s); } } else { abstPane.postAbsModel.removeElement(s); } } else if (containsAbstractions) { abstPane.preAbsModel.removeElement(s); abstPane.loopAbsModel.removeElement(s); abstPane.postAbsModel.removeElement(s); } } if (preOrder.size() > 0) { abstPane.preAbsModel.removeAllElements(); } for (Integer j = 0; j < preOrder.size(); j++) { abstPane.preAbsModel.addElement(preOrder.get(j)); } if (loopOrder.size() > 0) { abstPane.loopAbsModel.removeAllElements(); } for (Integer j = 0; j < loopOrder.size(); j++) { abstPane.loopAbsModel.addElement(loopOrder.get(j)); } if (postOrder.size() > 0) { abstPane.postAbsModel.removeAllElements(); } for (Integer j = 0; j < postOrder.size(); j++) { abstPane.postAbsModel.addElement(postOrder.get(j)); } abstPane.preAbs.setListData(abstPane.preAbsModel.toArray()); abstPane.loopAbs.setListData(abstPane.loopAbsModel.toArray()); abstPane.postAbs.setListData(abstPane.postAbsModel.toArray()); if (load.containsKey("abstraction.transforms")) { String xforms = load.getProperty("abstraction.transforms"); String[] array = xforms.split(", "); for (String s : array) { if (!s.equals("")) { abstPane.addLoopXform(s.replace(",", "")); } } } if (load.containsKey("abstraction.factor")) { abstPane.factorField.setText(load .getProperty("abstraction.factor")); } if (load.containsKey("abstraction.iterations")) { abstPane.iterField.setText(load .getProperty("abstraction.iterations")); } tempArray = verifyFile.split(separator); sourceFileNoPath = tempArray[tempArray.length - 1]; backgroundField = new JTextField(sourceFileNoPath); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(Gui.frame, "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } // Creates the run button run = new JButton("Save and Verify"); run.addActionListener(this); buttonPanel.add(run); run.setMnemonic(KeyEvent.VK_S); // Creates the save button save = new JButton("Save Parameters"); save.addActionListener(this); buttonPanel.add(save); save.setMnemonic(KeyEvent.VK_P); // Creates the view circuit button viewCircuit = new JButton("View Circuit"); viewCircuit.addActionListener(this); viewCircuit.setMnemonic(KeyEvent.VK_C); // Creates the view trace button viewTrace = new JButton("View Trace"); viewTrace.addActionListener(this); buttonPanel.add(viewTrace); if (!traceFile.exists()) { viewTrace.setEnabled(false); } viewTrace.setMnemonic(KeyEvent.VK_T); // Creates the view log button viewLog = new JButton("View Log"); viewLog.addActionListener(this); buttonPanel.add(viewLog); viewLog.setMnemonic(KeyEvent.VK_V); viewLog.setEnabled(false); JPanel backgroundPanel = new JPanel(); JLabel backgroundLabel = new JLabel("Model File:"); tempArray = verifyFile.split(separator); JLabel componentLabel = new JLabel("Component:"); componentField.setPreferredSize(new Dimension(200, 20)); String sourceFile = tempArray[tempArray.length - 1]; backgroundField = new JTextField(sourceFile); backgroundField.setMaximumSize(new Dimension(200, 20)); backgroundField.setEditable(false); backgroundPanel.add(backgroundLabel); backgroundPanel.add(backgroundField); if (verifyFile.endsWith(".vhd")) { backgroundPanel.add(componentLabel); backgroundPanel.add(componentField); } backgroundPanel.setMaximumSize(new Dimension(500, 30)); basicOptions.add(backgroundPanel); basicOptions.add(abstractionPanel); basicOptions.add(timingRadioPanel); if (!lema) { basicOptions.add(timingCheckBoxPanel); } basicOptions.add(otherPanel); //if (lema) { // basicOptions.add(preprocPanel); if (!lema) { basicOptions.add(algorithmPanel); } if (verifyFile.endsWith(".vhd")) { basicOptions.add(componentPanel); } if (verifyFile.endsWith(".lpn")) { basicOptions.add(LPNPanel); } basicOptions.setLayout(new BoxLayout(basicOptions, BoxLayout.Y_AXIS)); basicOptions.add(Box.createVerticalGlue()); advOptions.add(compilationPanel); advOptions.add(advTimingPanel); advOptions.add(advancedPanel); advOptions.add(bddPanel); advOptions.setLayout(new BoxLayout(advOptions, BoxLayout.Y_AXIS)); advOptions.add(Box.createVerticalGlue()); JTabbedPane tab = new JTabbedPane(); tab.addTab("Basic Options", basicOptions); tab.addTab("Advanced Options", advOptions); tab.addTab("Abstraction Options", abstPane); tab.setPreferredSize(new Dimension(1000, 480)); this.setLayout(new BorderLayout()); this.add(tab, BorderLayout.PAGE_START); change = false; } /** * This method performs different functions depending on what menu items or * buttons are selected. * * @throws * @throws */ public void actionPerformed(ActionEvent e) { change = true; if (e.getSource() == run) { save(verFile); new Thread(this).start(); } else if (e.getSource() == save) { log.addText("Saving:\n" + directory + separator + verFile + "\n"); save(verFile); } else if (e.getSource() == viewCircuit) { viewCircuit(); } else if (e.getSource() == viewTrace) { viewTrace(); } else if (e.getSource() == viewLog) { viewLog(); } else if (e.getSource() == addComponent) { String[] vhdlFiles = new File(root).list(); ArrayList<String> tempFiles = new ArrayList<String>(); for (int i = 0; i < vhdlFiles.length; i++) { if (vhdlFiles[i].endsWith(".vhd") && !vhdlFiles[i].equals(sourceFileNoPath)) { tempFiles.add(vhdlFiles[i]); } } vhdlFiles = new String[tempFiles.size()]; for (int i = 0; i < vhdlFiles.length; i++) { vhdlFiles[i] = tempFiles.get(i); } String filename = (String) JOptionPane.showInputDialog(this, "", "Select Component", JOptionPane.PLAIN_MESSAGE, null, vhdlFiles, vhdlFiles[0]); if (filename != null) { String[] comps = componentList.getItems(); boolean contains = false; for (int i = 0; i < comps.length; i++) { if (comps[i].equals(filename)) { contains = true; } } if (!filename.endsWith(".vhd")) { JOptionPane.showMessageDialog(Gui.frame, "You must select a valid VHDL file.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (new File(directory + separator + filename).exists() || filename.equals(sourceFileNoPath) || contains) { JOptionPane .showMessageDialog( Gui.frame, "This component is already contained in this tool.", "Error", JOptionPane.ERROR_MESSAGE); return; } componentList.addItem(filename); return; } } else if (e.getSource() == removeComponent) { if (componentList.getSelectedValue() != null) { String selected = componentList.getSelectedValue().toString(); componentList.removeItem(selected); new File(directory + separator + selected).delete(); } } else if (e.getSource() == addSFile) { String sFile = JOptionPane.showInputDialog(this, "Enter Assembly File Name:", "Assembly File Name", JOptionPane.PLAIN_MESSAGE); if ((!sFile.endsWith(".s") && !sFile.endsWith(".inst")) || !(new File(sFile).exists())) { JOptionPane.showMessageDialog(this, "Invalid filename entered.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == addLPN) { String[] lpnFiles = new File(root).list(); ArrayList<String> tempFiles = new ArrayList<String>(); for (int i = 0; i < lpnFiles.length; i++) { if (lpnFiles[i].endsWith(".lpn") && !lpnFiles[i].equals(sourceFileNoPath)) { tempFiles.add(lpnFiles[i]); } } Object[] tempFilesArray = tempFiles.toArray(); Arrays.sort(tempFilesArray); lpnFiles = new String[tempFilesArray.length]; for (int i = 0; i < lpnFiles.length; i++) { lpnFiles[i] = (String) tempFilesArray[i]; } JList lpnListInCurDir = new JList(lpnFiles); JScrollPane scroll = new JScrollPane(lpnListInCurDir); String[] options = new String[]{"OK", "Cancel"}; int selection = JOptionPane.showOptionDialog(this, scroll, "Select LPN", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (selection == JOptionPane.YES_OPTION) { for (Object obj : lpnListInCurDir.getSelectedValues()) { String filename = (String) obj; if (filename != null) { String[] lpns = lpnList.getItems(); boolean contains = false; for (int i = 0; i < lpns.length; i++) { if (lpns[i].equals(filename)) { contains = true; } } if (!filename.endsWith(".lpn")) { JOptionPane.showMessageDialog(Gui.frame, "You must select a valid LPN file.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (new File(directory + separator + filename).exists() || filename.equals(sourceFileNoPath) || contains) { JOptionPane .showMessageDialog( Gui.frame, "This lpn is already contained in this tool.", "Error", JOptionPane.ERROR_MESSAGE); return; } lpnList.addItem(filename); } } } return; } else if (e.getSource() == removeLPN) { if (lpnList.getSelectedValue() != null) { String selected = lpnList.getSelectedValue().toString(); lpnList.removeItem(selected); new File(directory + separator + selected).delete(); } } } // private void printAllProcesses(HashMap<Transition, Integer> allProcessTrans) { // System.out.println("~~~~~~~~~~Begin~~~~~~~~~"); // Set<Transition> allTransitions = allProcessTrans.keySet(); // for (Iterator<Transition> allTransIter = allTransitions.iterator(); allTransIter.hasNext();) { // Transition curTran = allTransIter.next(); // System.out.println(curTran.getName() + "\t" + allProcessTrans.get(curTran)); // System.out.println("~~~~~~~~~~End~~~~~~~~~"); public void run() { copyFile(); String[] array = directory.split(separator); String tempDir = ""; String lpnFileName = ""; if (!verifyFile.endsWith("lpn")) { String[] temp = verifyFile.split("\\."); lpnFileName = temp[0] + ".lpn"; } else { lpnFileName = verifyFile; } if (untimedStateSearch.isSelected()) { LhpnFile lpn = new LhpnFile(); lpn.load(directory + separator + lpnFileName); Options.setLogName(lpn.getLabel()); boolean canPerformMarkovianAnalysisTemp = true; if (!canPerformMarkovianAnalysis(lpn)) canPerformMarkovianAnalysisTemp = false; if (!decomposeLPN.isSelected()) { ArrayList<LhpnFile> selectedLPNs = new ArrayList<LhpnFile>(); selectedLPNs.add(lpn); for (int i=0; i < lpnList.getSelectedValues().length; i++) { String curLPNname = (String) lpnList.getSelectedValues()[i]; LhpnFile curLPN = new LhpnFile(); curLPN.load(directory + separator + curLPNname); selectedLPNs.add(curLPN); if (!canPerformMarkovianAnalysis(curLPN)) canPerformMarkovianAnalysisTemp = false; } if (canPerformMarkovianAnalysisTemp) Options.setMarkovianModelFlag(); // for (int i=0; i<selectedLPNs.size(); i++) { // System.out.println(selectedLPNs.get(i).getLabel()); // ArrayList<LhpnFile> selectedLPNsManipulated = new ArrayList<LhpnFile>(selectedLPNs.size()); // System.out.println("size = " + selectedLPNsManipulated.size()); // String[] LPNlabels = new String[selectedLPNs.size()]; // for (int i=0; i<selectedLPNs.size(); i++) { // LPNlabels[i] = selectedLPNs.get(i).getLabel(); // System.out.println(i + " " + LPNlabels[i]); // System.out.println("selected index"); // for (int i=0; i<selectedLPNs.size(); i++) { // JList LpnLoadingOrderList = new JList(LPNlabels); // LpnLoadingOrderList.setVisibleRowCount(10); // JScrollPane ampleMethdsPane = new JScrollPane(LpnLoadingOrderList); // JPanel mainPanel0 = new JPanel(new BorderLayout()); // mainPanel0.add("North", new JLabel("Select a LPN:")); // mainPanel0.add("Center", ampleMethdsPane); // Object[] options0 = {"Select", "Cancel"}; // int optionRtVal0 = JOptionPane.showOptionDialog(Gui.frame, mainPanel0, "LPN order manipulation", // JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options0, options0[0]); // if (optionRtVal0 == 1) // Cancel // return; // System.out.println(LpnLoadingOrderList.getSelectedIndex() + " " + selectedLPNs.get(LpnLoadingOrderList.getSelectedIndex()).getLabel()); // selectedLPNsManipulated.add(selectedLPNs.get(LpnLoadingOrderList.getSelectedIndex())); // //Project untimed_dfs = new Project(selectedLPNsManipulated); Project untimed_dfs = new Project(selectedLPNs); //Options for printing out intermediate results during POR //Options.setDebugMode(true); Options.setDebugMode(false); if (Options.getDebugMode()) System.out.println("Debug mode is ON."); // if (untimedPOR.isSelected()) { // // Options for using trace-back in ample calculation // String[] ampleMethds = {"Use trace-back for ample computation", "No trace-back for ample computation"}; // JList ampleMethdsList = new JList(ampleMethds); // ampleMethdsList.setVisibleRowCount(2); // //cycleClosingList.addListSelectionListener(new ValueReporter()); // JScrollPane ampleMethdsPane = new JScrollPane(ampleMethdsList); // JPanel mainPanel0 = new JPanel(new BorderLayout()); // mainPanel0.add("North", new JLabel("Select an ample set computation method:")); // mainPanel0.add("Center", ampleMethdsPane); // Object[] options0 = {"Run", "Cancel"}; // int optionRtVal0 = JOptionPane.showOptionDialog(Gui.frame, mainPanel0, "Ample set computation methods selection", // JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options0, options0[0]); // if (optionRtVal0 == 1) { // // Cancel // return; // int ampleMethdsIndex = ampleMethdsList.getSelectedIndex(); // if (ampleMethdsIndex == 0) // Options.setPOR("tb"); // if (ampleMethdsIndex == 1) // Options.setPOR("tboff"); // // GUI for different cycle closing methods. // String[] entries = {"Use behavioral analysis", // "Use behavioral analysis and state trace-back", // "No cycle closing", // "Strong cycle condition"}; // JList cycleClosingList = new JList(entries); // cycleClosingList.setVisibleRowCount(4); // //cycleClosingList.addListSelectionListener(new ValueReporter()); // JScrollPane cycleClosingPane = new JScrollPane(cycleClosingList); // JPanel mainPanel = new JPanel(new BorderLayout()); // mainPanel.add("North", new JLabel("Select a cycle closing method:")); // mainPanel.add("Center", cycleClosingPane); // Object[] options = {"Run", "Cancel"}; // int optionRtVal = JOptionPane.showOptionDialog(Gui.frame, mainPanel, "Cycle closing methods selection", // JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); // if (optionRtVal == 1) { // // Cancel // return; // int cycleClosingMthdIndex = cycleClosingList.getSelectedIndex(); // if (cycleClosingMthdIndex == 0) { // Options.setCycleClosingMthd("behavioral"); // if (Options.getPOR().equals("tb")) { // String[] cycleClosingAmpleMethds = {"Use trace-back", "No trace-back"}; // JList cycleClosingAmpleList = new JList(cycleClosingAmpleMethds); // cycleClosingAmpleList.setVisibleRowCount(2); // JScrollPane cycleClosingAmpleMethdsPane = new JScrollPane(cycleClosingAmpleList); // JPanel mainPanel1 = new JPanel(new BorderLayout()); // mainPanel1.add("North", new JLabel("Select a cycle closing ample computation method:")); // mainPanel1.add("Center", cycleClosingAmpleMethdsPane); // Object[] options1 = {"Run", "Cancel"}; // int optionRtVal1 = JOptionPane.showOptionDialog(Gui.frame, mainPanel1, "Cycle closing ample computation method selection", // JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options1, options1[0]); // if (optionRtVal1 == 1) { // // Cancel // return; // int cycleClosingAmpleMethdIndex = cycleClosingAmpleList.getSelectedIndex(); // if (cycleClosingAmpleMethdIndex == 0) // Options.setCycleClosingAmpleMethd("cctb"); // if (cycleClosingAmpleMethdIndex == 1) // Options.setCycleClosingAmpleMethd("cctboff"); // else if (Options.getPOR().equals("tboff")) { // Options.setCycleClosingAmpleMethd("cctboff"); // else if (cycleClosingMthdIndex == 1) // Options.setCycleClosingMthd("state_search"); // else if (cycleClosingMthdIndex == 2) // Options.setCycleClosingMthd("no_cycleclosing"); // else if (cycleClosingMthdIndex == 3) // Options.setCycleClosingMthd("strong"); // if (dot.isSelected()) { // Options.setOutputSgFlag(true); // Options.setPrjSgPath(directory + separator); // // Options for printing the final numbers from search_dfs or search_dfsPOR. // Options.setOutputLogFlag(true); //// Options.setPrintLogToFile(false); // StateGraph[] stateGraphArray = untimed_dfs.searchPOR(); // if (dot.isSelected()) { // for (int i=0; i<stateGraphArray.length; i++) { // String graphFileName = stateGraphArray[i].getLpn().getLabel() + "POR_"+ Options.getCycleClosingMthd() + "_local_sg.dot"; // stateGraphArray[i].outputLocalStateGraph(directory + separator + graphFileName); // // Code for producing global state graph is in search_dfsPOR in the Analysis class. if (untimedPOR.isSelected()) { // Options for using trace-back in ample calculation // TODO: Only need to keep Trace-back (depQueue). String[] ampleMethds = {"Trace-back", "Trace-back (depQueue)","No trace-back for ample computation", "Behavioral Analysis"}; JList ampleMethdsList = new JList(ampleMethds); ampleMethdsList.setVisibleRowCount(4); //cycleClosingList.addListSelectionListener(new ValueReporter()); JScrollPane ampleMethdsPane = new JScrollPane(ampleMethdsList); JPanel mainPanel0 = new JPanel(new BorderLayout()); mainPanel0.add("North", new JLabel("Select an ample set computation method:")); mainPanel0.add("Center", ampleMethdsPane); Object[] options0 = {"Run", "Cancel"}; int optionRtVal0 = JOptionPane.showOptionDialog(Gui.frame, mainPanel0, "Ample set computation methods selection", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options0, options0[0]); if (optionRtVal0 == 1) { // Cancel return; } int ampleMethdsIndex = ampleMethdsList.getSelectedIndex(); if (ampleMethdsIndex == 0) { Options.setPOR("tb"); Options.setCycleClosingMthd("behavioral"); Options.setCycleClosingAmpleMethd("cctb"); } if (ampleMethdsIndex == 1) { Options.setPOR("tb"); Options.setCycleClosingMthd("behavioral"); Options.setCycleClosingAmpleMethd("cctb"); Options.setUseDependentQueue(); } if (ampleMethdsIndex == 2) { Options.setPOR("tboff"); Options.setCycleClosingMthd("behavioral"); Options.setCycleClosingAmpleMethd("cctboff"); } if (ampleMethdsIndex == 3) { Options.setPOR("behavioral"); Options.setCycleClosingMthd("behavioral"); Options.setCycleClosingAmpleMethd("cctboff"); } // TODO: Choose different cycle closing methods // int cycleClosingMthdIndex = cycleClosingList.getSelectedIndex(); // if (cycleClosingMthdIndex == 0) { // Options.setCycleClosingMthd("behavioral"); // if (Options.getPOR().equals("tb")) { // String[] cycleClosingAmpleMethds = {"Use trace-back", "No trace-back"}; // JList cycleClosingAmpleList = new JList(cycleClosingAmpleMethds); // cycleClosingAmpleList.setVisibleRowCount(2); // JScrollPane cycleClosingAmpleMethdsPane = new JScrollPane(cycleClosingAmpleList); // JPanel mainPanel1 = new JPanel(new BorderLayout()); // mainPanel1.add("North", new JLabel("Select a cycle closing ample computation method:")); // mainPanel1.add("Center", cycleClosingAmpleMethdsPane); // Object[] options1 = {"Run", "Cancel"}; // int optionRtVal1 = JOptionPane.showOptionDialog(Gui.frame, mainPanel1, "Cycle closing ample computation method selection", // JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options1, options1[0]); // if (optionRtVal1 == 1) { // // Cancel // return; // int cycleClosingAmpleMethdIndex = cycleClosingAmpleList.getSelectedIndex(); // if (cycleClosingAmpleMethdIndex == 0) // Options.setCycleClosingAmpleMethd("cctb"); // if (cycleClosingAmpleMethdIndex == 1) // Options.setCycleClosingAmpleMethd("cctboff"); // else if (Options.getPOR().equals("tboff")) { // Options.setCycleClosingAmpleMethd("cctboff"); // else if (cycleClosingMthdIndex == 1) // Options.setCycleClosingMthd("state_search"); // else if (cycleClosingMthdIndex == 2) // Options.setCycleClosingMthd("no_cycleclosing"); // else if (cycleClosingMthdIndex == 3) // Options.setCycleClosingMthd("strong"); if (dot.isSelected()) { Options.setOutputSgFlag(true); } Options.setPrjSgPath(directory + separator); // Options for printing the final numbers from search_dfs or search_dfsPOR. Options.setOutputLogFlag(true); //Options.setPrintLogToFile(false); untimed_dfs.searchWithPOR(); } else { // No POR Options.setPrjSgPath(directory + separator); // Options for printing the final numbers from search_dfs or search_dfsPOR. Options.setOutputLogFlag(true); // Options.setPrintLogToFile(false); if (dot.isSelected()) Options.setOutputSgFlag(true); untimed_dfs.search(); } return; } else if (decomposeLPN.isSelected() && verbose.isSelected() && lpnList.getSelectedValue() == null) { HashMap<Transition, Integer> allProcessTrans = new HashMap<Transition, Integer>(); // create an Abstraction object to get all processes in one LPN Abstraction abs = lpn.abstractLhpn(this); abs.decomposeLpnIntoProcesses(); allProcessTrans.putAll(abs.getTransWithProcIDs()); HashMap<Integer, LpnProcess> processMap = new HashMap<Integer, LpnProcess>(); for (Transition curTran: allProcessTrans.keySet()) { Integer procId = allProcessTrans.get(curTran); if (!processMap.containsKey(procId)) { LpnProcess newProcess = new LpnProcess(procId); newProcess.addTranToProcess(curTran); if (curTran.getPreset() != null) { for (Place p : curTran.getPreset()) { newProcess.addPlaceToProcess(p); } } processMap.put(procId, newProcess); } else { LpnProcess curProcess = processMap.get(procId); curProcess.addTranToProcess(curTran); if (curTran.getPreset() != null) { for (Place p : curTran.getPreset()) { curProcess.addPlaceToProcess(p); } } } } HashMap<String, ArrayList<Integer>> allProcessRead = abs.getProcessRead(); HashMap<String, ArrayList<Integer>> allProcessWrite = abs.getProcessWrite(); for (String curRead : allProcessRead.keySet()) { if (allProcessRead.get(curRead).size() == 1 && allProcessWrite.get(curRead).size() == 1) { if (allProcessRead.get(curRead).equals(allProcessWrite.get(curRead))) { // variable is read and written only by one single process Integer curProcessID = allProcessRead.get(curRead).get(0); ArrayList<Variable> processInternal = processMap.get(curProcessID).getProcessInternal(); if (!processInternal.contains(abs.getVariable(curRead))) processInternal.add(abs.getVariable(curRead)); } else { // variable is read in one process and written by another Integer curProcessID = allProcessRead.get(curRead).get(0); ArrayList<Variable> processInput = processMap.get(curProcessID).getProcessInput(); if (!processInput.contains(abs.getVariable(curRead))) processInput.add(abs.getVariable(curRead)); curProcessID = allProcessWrite.get(curRead).get(0); ArrayList<Variable> processOutput = processMap.get(curProcessID).getProcessOutput(); if (!processOutput.contains(abs.getVariable(curRead))) processOutput.add(abs.getVariable(curRead)); } } else if (allProcessRead.get(curRead).size() > 1 || allProcessWrite.get(curRead).size() > 1) { ArrayList<Integer> readList = allProcessRead.get(curRead); ArrayList<Integer> writeList = allProcessWrite.get(curRead); ArrayList<Integer> alreadyAssignedAsOutput = new ArrayList<Integer>(); for (int i=0; i<writeList.size(); i++) { Integer curProcessID = writeList.get(i); ArrayList<Variable> processOutput = processMap.get(curProcessID).getProcessOutput(); if (!processOutput.contains(abs.getVariable(curRead))) processOutput.add(abs.getVariable(curRead)); if (!alreadyAssignedAsOutput.contains(curProcessID)) alreadyAssignedAsOutput.add(curProcessID); } readList.removeAll(alreadyAssignedAsOutput); for (int i=0; i<readList.size(); i++) { Integer curProcessID = readList.get(i); ArrayList<Variable> processInput = processMap.get(curProcessID).getProcessInput(); if (!processInput.contains(abs.getVariable(curRead))) processInput.add(abs.getVariable(curRead)); } } else if (allProcessWrite.get(curRead).size() == 0) { // variable is only read, but never written if (allProcessRead.get(curRead).size() == 1) { // variable is read locally Integer curProcessID = allProcessRead.get(curRead).get(0); ArrayList<Variable> processInternal = processMap.get(curProcessID).getProcessInternal(); if (!processInternal.contains(abs.getVariable(curRead))) processInternal.add(abs.getVariable(curRead)); } else if (allProcessRead.get(curRead).size() > 1) { // variable is read globally by multiple processes for (int i=0; i < allProcessRead.get(curRead).size(); i++) { Integer curProcessID = allProcessRead.get(curRead).get(i); ArrayList<Variable> processInput = processMap.get(curProcessID).getProcessInput(); if (!processInput.contains(abs.getVariable(curRead))) processInput.add(abs.getVariable(curRead)); } } } else if (allProcessRead.get(curRead).size() == 0) { // variable is only written, but never read if (allProcessWrite.get(curRead).size() == 1) { // variable is written locally Integer curProcessID = allProcessWrite.get(curRead).get(0); ArrayList<Variable> processInternal = processMap.get(curProcessID).getProcessInternal(); if (!processInternal.contains(abs.getVariable(curRead))) processInternal.add(abs.getVariable(curRead)); } if (allProcessWrite.get(curRead).size() > 1) { // variable is written globally by multiple processes for (int i=0; i < allProcessWrite.get(curRead).size(); i++) { Integer curProcessID = allProcessWrite.get(curRead).get(i); ArrayList<Variable> processInput = processMap.get(curProcessID).getProcessInput(); if (!processInput.contains(abs.getVariable(curRead))) processInput.add(abs.getVariable(curRead)); } } } } // Options to get all possible decompositions or just one decomposition String[] decomposition = {"Get ALL decompositions", "Get ONE decomposition"}; JList decompositionList = new JList(decomposition); decompositionList.setVisibleRowCount(2); JScrollPane decompMethdsPane = new JScrollPane(decompositionList); JPanel mainPanel0 = new JPanel(new BorderLayout()); mainPanel0.add("North", new JLabel("Select a LPN decomposition method:")); mainPanel0.add("Center", decompMethdsPane); Object[] options0 = {"Run", "Cancel"}; int optionRtVal0 = JOptionPane.showOptionDialog(Gui.frame, mainPanel0, "LPN decomposition methods selection", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options0, options0[0]); if (optionRtVal0 == 1) { // Cancel return; } int decompMethdIndex = decompositionList.getSelectedIndex(); if (decompMethdIndex == 0) { // Automatically find all possible LPN partitions. // Find the process with least number of variables int leastNumVarsInOneProcess = lpn.getVariables().length; for (Integer curProcId : processMap.keySet()) { LpnProcess curProcess = processMap.get(curProcId); if (curProcess.getProcessVarSize() < leastNumVarsInOneProcess) { leastNumVarsInOneProcess = curProcess.getProcessVarSize(); } } Integer maxNumVarsInOneComp = leastNumVarsInOneProcess; Integer tryNumDecomps = processMap.size(); // The maximal number of decomposed LPNs is the number of all processes in the LPN. HashSet<Integer> possibleDecomps = new HashSet<Integer>(); //System.out.println("lpn.getVariables().length = " + lpn.getVariables().length); while(tryNumDecomps > 1) { LpnComponentList componentList = new LpnComponentList(maxNumVarsInOneComp); componentList.buildComponents(processMap, directory, lpn.getLabel()); HashMap<Integer, Component> compMap = componentList.getComponentMap(); tryNumDecomps = compMap.size(); if (tryNumDecomps == 1) break; if (!possibleDecomps.contains(compMap.size())) { possibleDecomps.add(compMap.size()); for (Component comp : compMap.values()) { LhpnFile lpnComp = new LhpnFile(); lpnComp = comp.buildLPN(lpnComp); lpnComp.save(root + separator + lpn.getLabel() + "_decomp" + maxNumVarsInOneComp + "vars" + comp.getComponentId() + ".lpn"); } } maxNumVarsInOneComp++; } System.out.println("possible decompositions for " + lpn.getLabel() + ".lpn: "); for (Integer i : possibleDecomps) { System.out.print(i + ", "); } System.out.println(); return; } if (decompMethdIndex ==1) { // User decides one LPN partition. // Find the process with the least number of variables int leastNumVarsInOneProcess = lpn.getVariables().length; for (Integer curProcId : processMap.keySet()) { LpnProcess curProcess = processMap.get(curProcId); if (curProcess.getProcessVarSize() < leastNumVarsInOneProcess) { leastNumVarsInOneProcess = curProcess.getProcessVarSize(); } } // Coalesce an array of processes into one LPN component. JPanel mainPanel = new JPanel(new BorderLayout()); JPanel maxVarsPanel = new JPanel(); JTextField maxVarsText = new JTextField(3); maxVarsText.setText("" + lpn.getVariables().length); maxVarsPanel.add(new JLabel("Enter the maximal number of variables allowed in one component:")); maxVarsPanel.add(maxVarsText); mainPanel.add("North", new JLabel("number of variables in this LPN: " + lpn.getVariables().length)); mainPanel.add("Center", new JLabel("number of variables in the smallest process: " + leastNumVarsInOneProcess)); mainPanel.add("South", maxVarsPanel); Object[] options = {"Run", "Cancel"}; int optionRtVal = JOptionPane.showOptionDialog(Gui.frame, mainPanel, "Assign the maximal number of variables in one component", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (optionRtVal == 1) { // Cancel return; } Integer maxNumVarsInOneComp = Integer.parseInt(maxVarsText.getText().trim());; if (leastNumVarsInOneProcess >= maxNumVarsInOneComp) { // The original LPN is decomposed into processes. // Store each process as individual LPN. for (Integer curProcId : processMap.keySet()) { LpnProcess curProcess = processMap.get(curProcId); LhpnFile lpnProc = new LhpnFile(); lpnProc = curProcess.buildLPN(lpnProc); lpnProc.save(root + separator + lpn.getLabel() + "_decomp" + maxNumVarsInOneComp + "vars" + curProcId + ".lpn"); //lpnProc.save(directory + separator + lpn.getLabel() + curProcId + ".lpn"); } JOptionPane.showMessageDialog( Gui.frame, "The entered maximal number of variables in one component is too small. The LPN was decomposed into processes.", "Warning", JOptionPane.WARNING_MESSAGE); return; } LpnComponentList componentList = new LpnComponentList(maxNumVarsInOneComp); componentList.buildComponents(processMap, directory, lpn.getLabel()); HashMap<Integer, Component> compMap = componentList.getComponentMap(); for (Component comp : compMap.values()) { LhpnFile lpnComp = new LhpnFile(); lpnComp = comp.buildLPN(lpnComp); //checkDecomposition(lpn, lpnComp); lpnComp.save(root + separator + lpn.getLabel() + "_decomp" + maxNumVarsInOneComp + "vars" + comp.getComponentId() + ".lpn"); } } } else if (multipleLPNs.isSelected() && lpnList.getSelectedValues().length < 1) { JOptionPane.showMessageDialog( Gui.frame, "Please select at least 1 more LPN.", "Error", JOptionPane.ERROR_MESSAGE); return; } } long time1 = System.nanoTime(); File work = new File(directory); /* if (!preprocStr.getText().equals("")) { try { String preprocCmd = preprocStr.getText(); Runtime exec = Runtime.getRuntime(); Process preproc = exec.exec(preprocCmd, null, work); log.addText("Executing:\n" + preprocCmd + "\n"); preproc.waitFor(); } catch (Exception e) { JOptionPane.showMessageDialog(Gui.frame, "Error with preprocessing.", "Error", JOptionPane.ERROR_MESSAGE); //e.printStackTrace(); } } */ try { if (verifyFile.endsWith(".lpn")) { Runtime.getRuntime().exec("atacs -llsl " + verifyFile, null, work); } else if (verifyFile.endsWith(".vhd")) { Runtime.getRuntime().exec("atacs -lvsl " + verifyFile, null, work); } else if (verifyFile.endsWith(".g")) { Runtime.getRuntime().exec("atacs -lgsl " + verifyFile, null, work); } else if (verifyFile.endsWith(".hse")) { Runtime.getRuntime().exec("atacs -lhsl " + verifyFile, null, work); } } catch (Exception e) { } for (int i = 0; i < array.length - 1; i++) { tempDir = tempDir + array[i] + separator; } LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(directory + separator + lpnFileName); Abstraction abstraction = lhpnFile.abstractLhpn(this); String abstFilename; if(dbm2.isSelected()) { try { verification.timed_state_exploration.dbm2.StateExploration.findStateGraph(lhpnFile, directory+separator, lpnFileName); } catch (FileNotFoundException e) { e.printStackTrace(); } return; } /** * If the splitZone option (labeled "Split Zone") is selected, * run the timed analysis. */ if(splitZone.isSelected()) { // Version prior to adding zones to the project states. // Uses the timed_state_exploration.zone infrastructure. // if(multipleLPNs.isSelected()) // else // LhpnFile lpn = new LhpnFile(); // lpn.load(directory + separator + lpnFileName); // // The full state graph is created for only one LPN. // /** // * This is what selects the timing analysis. // * The method setTimingAnalysisType sets a static variable // * in the Options class that is queried by the search method. // */ // Options.setTimingAnalsysisType("zone"); // ZoneType.setSubsetFlag(!timsubset.isSelected()); // ZoneType.setSupersetFlag(!superset.isSelected()); // Project_Timed timedStateSearch = new Project_Timed(lpn, // Options.getTimingAnalysisFlag(), false); // if(useGraphs.isSelected()){ // timedStateSearch = new Project_Timed(lpn, // Options.getTimingAnalysisFlag(), true); // StateGraph_timed[] stateGraphArray = timedStateSearch.search(); // String graphFileName = verifyFile.replace(".lpn", "") + "_sg.dot"; // if (stateGraphArray.length > 1) { // JOptionPane.showMessageDialog( // Gui.frame, // "Mutiple state graphs should not be produced.", // "Error", JOptionPane.ERROR_MESSAGE); // else { // if (dot.isSelected()) { // stateGraphArray[0].outputLocalStateGraph(directory + separator + graphFileName); // if(graph.isSelected()){ // showGraph(directory + separator + graphFileName); // Options.setTimingAnalsysisType("off"); // Zone.clearLexicon(); // return; // This is the code before the revision for allowing multiple LPNs // // Uses the timed_state_exploration.zoneProject infrastructure. // LhpnFile lpn = new LhpnFile(); // lpn.load(directory + separator + lpnFileName); // // The full state graph is created for only one LPN. // /** // * This is what selects the timing analysis. // * The method setTimingAnalysisType sets a static variable // * in the Options class that is queried by the search method. // */ // Options.setTimingAnalsysisType("zone"); // ZoneType.setSubsetFlag(!timsubset.isSelected()); // ZoneType.setSupersetFlag(!superset.isSelected()); // Project timedStateSearch = new Project(lpn); // StateGraph[] stateGraphArray = timedStateSearch.search(); // String graphFileName = verifyFile.replace(".lpn", "") + "_sg.dot"; // if (dot.isSelected()) { // stateGraphArray[0].outputLocalStateGraph(directory + separator + graphFileName); // if(graph.isSelected()){ // showGraph(directory + separator + graphFileName); // Options.setTimingAnalsysisType("off"); // Zone.clearLexicon(); // return; // Uses the timed_state_exploration.zoneProject infrastructure. LhpnFile lpn = new LhpnFile(); lpn.load(directory + separator + lpnFileName); Options.set_TimingLogFile(directory + separator + lpnFileName + ".tlog"); // Load any other listed LPNs. ArrayList<LhpnFile> selectedLPNs = new ArrayList<LhpnFile>(); // Add the current LPN to the list. selectedLPNs.add(lpn); // for (int i=0; i < lpnList.getSelectedValues().length; i++) { // String curLPNname = (String) lpnList.getSelectedValues()[i]; // LhpnFile curLPN = new LhpnFile(); // curLPN.load(directory + separator + curLPNname); // selectedLPNs.add(curLPN); String[] guiLPNList = lpnList.getItems(); for (int i=0; i < guiLPNList.length; i++) { String curLPNname = guiLPNList[i]; LhpnFile curLPN = new LhpnFile(); curLPN.load(directory + separator + curLPNname); selectedLPNs.add(curLPN); } // Extract boolean variables from continuous variable inequalities. for(int i=0; i<selectedLPNs.size(); i++){ selectedLPNs.get(i).parseBooleanInequalities(); } /** * This is what selects the timing analysis. * The method setTimingAnalysisType sets a static variable * in the Options class that is queried by the search method. */ Options.setTimingAnalsysisType("zone"); Zone.setSubsetFlag(!timsubset.isSelected()); Zone.setSupersetFlag(!superset.isSelected()); Project timedStateSearch = new Project(selectedLPNs); if (dot.isSelected()) { Options.setOutputSgFlag(true); Options.setPrjSgPath(directory + separator); } timedStateSearch.search(); String graphFileName = verifyFile.replace(".lpn", "") + "_sg.dot"; // if (dot.isSelected()) { // stateGraphArray[0].outputLocalStateGraph(directory + separator + graphFileName); if(graph.isSelected()){ showGraph(directory + separator + graphFileName); } Options.setTimingAnalsysisType("off"); BufferedWriter logFile = Zone.get_writeLogFile(); if(logFile != null){ try { logFile.close(); } catch (IOException e) { e.printStackTrace(); } } Zone.reset_writeLogFile(); return; } if (lhpn.isSelected()) { abstFilename = (String) JOptionPane.showInputDialog(this, "Please enter the file name for the abstracted LPN.", "Enter Filename", JOptionPane.PLAIN_MESSAGE); if (abstFilename != null) { if (!abstFilename.endsWith(".lpn")) { while (abstFilename.contains("\\.")) { abstFilename = (String) JOptionPane.showInputDialog(this, "Please enter a valid file name for the abstracted LPN.", "Invalid Filename", JOptionPane.PLAIN_MESSAGE); } abstFilename = abstFilename + ".lpn"; } } } else { abstFilename = lpnFileName.replace(".lpn", "_abs.lpn"); } String sourceFile; if (simplify.isSelected() || abstractLhpn.isSelected()) { String[] boolVars = lhpnFile.getBooleanVars(); String[] contVars = lhpnFile.getContVars(); String[] intVars = lhpnFile.getIntVars(); String[] variables = new String[boolVars.length + contVars.length + intVars.length]; int k = 0; for (int j = 0; j < contVars.length; j++) { variables[k] = contVars[j]; k++; } for (int j = 0; j < intVars.length; j++) { variables[k] = intVars[j]; k++; } for (int j = 0; j < boolVars.length; j++) { variables[k] = boolVars[j]; k++; } if (abstFilename != null) { if (!abstFilename.endsWith(".lpn")) abstFilename = abstFilename + ".lpn"; if (abstPane.loopAbsModel.contains("Remove Variables")) { abstraction.abstractVars(abstPane.getIntVars()); } abstraction.abstractSTG(true); } if (!lhpn.isSelected() && !view.isSelected()) { abstraction.save(directory + separator + abstFilename); } sourceFile = abstFilename; } else { String[] tempArray = verifyFile.split(separator); sourceFile = tempArray[tempArray.length - 1]; } if (!lhpn.isSelected() && !view.isSelected()) { abstraction.save(directory + separator + abstFilename); } if (!lhpn.isSelected() && !view.isSelected()) { String[] tempArray = verifyFile.split("\\."); String traceFilename = tempArray[0] + ".trace"; File traceFile = new File(traceFilename); String pargName = ""; String dotName = ""; if (componentField.getText().trim().equals("")) { if (verifyFile.endsWith(".g")) { pargName = directory + separator + sourceFile.replace(".g", ".prg"); dotName = directory + separator + sourceFile.replace(".g", ".dot"); } else if (verifyFile.endsWith(".lpn")) { pargName = directory + separator + sourceFile.replace(".lpn", ".prg"); dotName = directory + separator + sourceFile.replace(".lpn", ".dot"); } else if (verifyFile.endsWith(".vhd")) { pargName = directory + separator + sourceFile.replace(".vhd", ".prg"); dotName = directory + separator + sourceFile.replace(".vhd", ".dot"); } } else { pargName = directory + separator + componentField.getText().trim() + ".prg"; dotName = directory + separator + componentField.getText().trim() + ".dot"; } File pargFile = new File(pargName); File dotFile = new File(dotName); if (traceFile.exists()) { traceFile.delete(); } if (pargFile.exists()) { pargFile.delete(); } if (dotFile.exists()) { dotFile.delete(); } for (String s : componentList.getItems()) { try { FileInputStream in = new FileInputStream(new File(root + separator + s)); FileOutputStream out = new FileOutputStream(new File( directory + separator + s)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } catch (IOException e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(Gui.frame, "Cannot update the file " + s + ".", "Error", JOptionPane.ERROR_MESSAGE); } } for (String s : lpnList.getItems()) { try { FileInputStream in = new FileInputStream(new File(root + separator + s)); FileOutputStream out = new FileOutputStream(new File( directory + separator + s)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } catch (IOException e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(Gui.frame, "Cannot update the file " + s + ".", "Error", JOptionPane.ERROR_MESSAGE); } } String options = ""; // BDD Linkspace Size if (!bddSize.getText().equals("") && !bddSize.getText().equals("0")) { options = options + "-L" + bddSize.getText() + " "; } options = options + "-oq"; // Timing method if (atacs) { if (untimed.isSelected()) { options = options + "tu"; } else if (geometric.isSelected()) { options = options + "tg"; } else if (posets.isSelected()) { options = options + "ts"; } else if (bag.isSelected()) { options = options + "tg"; } else if (bap.isSelected()) { options = options + "tp"; } else { options = options + "tt"; } } else { if (bdd.isSelected()) { options = options + "tB"; } else if (dbm.isSelected()) { options = options + "tL"; } else if (smt.isSelected()) { options = options + "tM"; } } // Timing Options if (abst.isSelected()) { options = options + "oa"; } if (partialOrder.isSelected()) { options = options + "op"; } // Other Options if (dot.isSelected()) { options = options + "od"; } if (verbose.isSelected()) { options = options + "ov"; } // Advanced Timing Options if (genrg.isSelected()) { options = options + "oG"; } if (timsubset.isSelected()) { options = options + "oS"; } if (superset.isSelected()) { options = options + "oU"; } if (infopt.isSelected()) { options = options + "oF"; } if (orbmatch.isSelected()) { options = options + "oO"; } if (interleav.isSelected()) { options = options + "oI"; } if (prune.isSelected()) { options = options + "oP"; } if (disabling.isSelected()) { options = options + "oD"; } if (nofail.isSelected()) { options = options + "of"; } if (noproj.isSelected()) { options = options + "oj"; } if (keepgoing.isSelected()) { options = options + "oK"; } if (explpn.isSelected()) { options = options + "oL"; } // Other Advanced Options if (nochecks.isSelected()) { options = options + "on"; } if (reduction.isSelected()) { options = options + "oR"; } // Compilation Options if (newTab.isSelected()) { options = options + "cN"; } if (postProc.isSelected()) { options = options + "cP"; } if (redCheck.isSelected()) { options = options + "cR"; } if (xForm2.isSelected()) { options = options + "cT"; } if (expandRate.isSelected()) { options = options + "cE"; } // Load file type if (verifyFile.endsWith(".g")) { options = options + "lg"; } else if (verifyFile.endsWith(".lpn")) { options = options + "ll"; } else if (verifyFile.endsWith(".vhd") || verifyFile.endsWith(".vhdl")) { options = options + "lvslll"; } // Verification Algorithms if (verify.isSelected()) { options = options + "va"; } else if (vergate.isSelected()) { options = options + "vg"; } else if (orbits.isSelected()) { options = options + "vo"; } else if (search.isSelected()) { options = options + "vs"; } else if (trace.isSelected()) { options = options + "vt"; } if (graph.isSelected()) { options = options + "ps"; } String cmd = "atacs " + options; String[] components = componentList.getItems(); for (String s : components) { cmd = cmd + " " + s; } cmd = cmd + " " + sourceFile; if (!componentField.getText().trim().equals("")) { cmd = cmd + " " + componentField.getText().trim(); } final JButton cancel = new JButton("Cancel"); final JFrame running = new JFrame("Progress"); WindowListener w = new WindowListener() { public void windowClosing(WindowEvent arg0) { cancel.doClick(); running.dispose(); } public void windowOpened(WindowEvent arg0) { } public void windowClosed(WindowEvent arg0) { } public void windowIconified(WindowEvent arg0) { } public void windowDeiconified(WindowEvent arg0) { } public void windowActivated(WindowEvent arg0) { } public void windowDeactivated(WindowEvent arg0) { } }; running.addWindowListener(w); JPanel text = new JPanel(); JPanel progBar = new JPanel(); JPanel button = new JPanel(); JPanel all = new JPanel(new BorderLayout()); JLabel label = new JLabel("Running..."); JProgressBar progress = new JProgressBar(); progress.setIndeterminate(true); text.add(label); progBar.add(progress); button.add(cancel); all.add(text, "North"); all.add(progBar, "Center"); all.add(button, "South"); all.setOpaque(true); running.setContentPane(all); running.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = running.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; running.setLocation(x, y); running.setVisible(true); running.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); work = new File(directory); Runtime exec = Runtime.getRuntime(); try { Preferences biosimrc = Preferences.userRoot(); String output = ""; int exitValue = 0; if (biosimrc.get("biosim.verification.command", "").equals("")) { final Process ver = exec.exec(cmd, null, work); cancel.setActionCommand("Cancel"); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ver.destroy(); running.setCursor(null); running.dispose(); } }); biosim.getExitButton().setActionCommand("Exit program"); biosim.getExitButton().addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { ver.destroy(); running.setCursor(null); running.dispose(); } }); log.addText("Executing:\n" + cmd + "\n"); InputStream reb = ver.getInputStream(); InputStreamReader isr = new InputStreamReader(reb); BufferedReader br = new BufferedReader(isr); FileWriter out = new FileWriter(new File(directory + separator + "run.log")); while ((output = br.readLine()) != null) { out.write(output); out.write("\n"); } out.close(); br.close(); isr.close(); reb.close(); viewLog.setEnabled(true); exitValue = ver.waitFor(); } else { cmd = biosimrc.get("biosim.verification.command", "") + " " + options + " " + sourceFile.replaceAll(".lpn", ""); final Process ver = exec.exec(cmd, null, work); cancel.setActionCommand("Cancel"); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ver.destroy(); running.setCursor(null); running.dispose(); } }); biosim.getExitButton().setActionCommand("Exit program"); biosim.getExitButton().addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { ver.destroy(); running.setCursor(null); running.dispose(); } }); log.addText("Executing:\n" + cmd + "\n"); InputStream reb = ver.getInputStream(); InputStreamReader isr = new InputStreamReader(reb); BufferedReader br = new BufferedReader(isr); FileWriter out = new FileWriter(new File(directory + separator + "run.log")); while ((output = br.readLine()) != null) { out.write(output); out.write("\n"); } out.close(); br.close(); isr.close(); reb.close(); viewLog.setEnabled(true); exitValue = ver.waitFor(); } long time2 = System.nanoTime(); long minutes; long hours; long days; double secs = ((time2 - time1) / 1000000000.0); long seconds = ((time2 - time1) / 1000000000); secs = secs - seconds; minutes = seconds / 60; secs = seconds % 60 + secs; hours = minutes / 60; minutes = minutes % 60; days = hours / 24; hours = hours % 60; String time; String dayLabel; String hourLabel; String minuteLabel; String secondLabel; if (days == 1) { dayLabel = " day "; } else { dayLabel = " days "; } if (hours == 1) { hourLabel = " hour "; } else { hourLabel = " hours "; } if (minutes == 1) { minuteLabel = " minute "; } else { minuteLabel = " minutes "; } if (seconds == 1) { secondLabel = " second"; } else { secondLabel = " seconds"; } if (days != 0) { time = days + dayLabel + hours + hourLabel + minutes + minuteLabel + secs + secondLabel; } else if (hours != 0) { time = hours + hourLabel + minutes + minuteLabel + secs + secondLabel; } else if (minutes != 0) { time = minutes + minuteLabel + secs + secondLabel; } else { time = secs + secondLabel; } log.addText("Total Verification Time: " + time + "\n\n"); running.setCursor(null); running.dispose(); FileInputStream atacsLog = new FileInputStream(new File( directory + separator + "atacs.log")); InputStreamReader atacsReader = new InputStreamReader(atacsLog); BufferedReader atacsBuffer = new BufferedReader(atacsReader); boolean success = false; while ((output = atacsBuffer.readLine()) != null) { if (output.contains("Verification succeeded.")) { JOptionPane.showMessageDialog(Gui.frame, "Verification succeeded!", "Success", JOptionPane.INFORMATION_MESSAGE); success = true; break; } } if (exitValue == 143) { JOptionPane.showMessageDialog(Gui.frame, "Verification was" + " canceled by the user.", "Canceled Verification", JOptionPane.ERROR_MESSAGE); } if (!success) { if (new File(pargName).exists()) { Process parg = exec.exec("parg " + pargName); log.addText("parg " + pargName + "\n"); parg.waitFor(); } else if (new File(dotName).exists()) { String command; if (System.getProperty("os.name") .contentEquals("Linux")) { command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase() .startsWith("mac os")) { command = "open "; } else { command = "dotty "; } Process dot = exec.exec("open " + dotName); log.addText(command + dotName + "\n"); dot.waitFor(); } else { viewLog(); } } if (graph.isSelected()) { if (dot.isSelected()) { String command; if (System.getProperty("os.name") .contentEquals("Linux")) { command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase() .startsWith("mac os")) { command = "open "; } else { command = "dotty "; } exec.exec(command + dotName); log.addText("Executing:\n" + command + dotName + "\n"); } else { exec.exec("parg " + pargName); log.addText("Executing:\nparg " + pargName + "\n"); } } } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(Gui.frame, "Unable to verify model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { if (lhpn.isSelected()) { abstraction.save(tempDir + separator + abstFilename); biosim.addToTree(abstFilename); } else if (view.isSelected()) { abstraction.save(directory + separator + abstFilename); work = new File(directory + separator); try { String dotName = abstFilename.replace(".lpn", ".dot"); new File(directory + separator + dotName).delete(); Runtime exec = Runtime.getRuntime(); abstraction.printDot(directory + separator + dotName); if (new File(directory + separator + dotName).exists()) { String command; if (System.getProperty("os.name") .contentEquals("Linux")) { command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase() .startsWith("mac os")) { command = "open "; } else { command = "dotty "; } Process dot = exec.exec(command + dotName, null, work); log.addText(command + dotName + "\n"); dot.waitFor(); } else { JOptionPane.showMessageDialog(Gui.frame, "Unable to view LHPN.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e) { e.printStackTrace(); } } } } private void checkDecomposition(LhpnFile lpn, LhpnFile lpnComp) { // Places for (String placeName : lpnComp.getPlaceList()) { if (lpn.getPlace(placeName) == null) System.out.println("Place " + placeName + "of component "+ lpnComp.getLabel() +" does not exist in LPN" + lpn.getLabel()); if (lpnComp.getInitialMarking(placeName) != lpn.getInitialMarking(placeName)) System.out.println("Initial marking for place " + placeName + "of component "+ lpnComp.getLabel() +" is not equal to that of " + lpn.getLabel()); } // Transitions for (Transition tran : lpnComp.getAllTransitions()) { if (lpn.getTransition(tran.getLabel()) == null) System.out.println("Transition " + tran.getFullLabel() + "does not exist in LPN" + lpn.getLabel()); else { Transition tranInLpn = lpn.getTransition(tran.getLabel()); if (!tran.equals(tranInLpn)) { System.out.println("Transition " + tran.getFullLabel() + "is not equal to " + tranInLpn.getFullLabel()); } } } // Variables for (String varName : lpnComp.getVariables()) { if (lpn.getVariable(varName) == null) System.out.println("Variable " + varName + "of component "+ lpnComp.getLabel() +" does not exist in LPN" + lpn.getLabel()); else { if (!lpnComp.getVariable(varName).equals(lpn.getVariable(varName))) System.out.println("Variable " + varName + "of component "+ lpnComp.getLabel() +" is not equal to that in LPN " + lpn.getLabel()); } } } public void saveAs() { String newName = JOptionPane.showInputDialog(Gui.frame, "Enter Verification name:", "Verification Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".ver")) { newName = newName + ".ver"; } save(newName); } public void save() { save(verFile); } public void save(String filename) { try { Properties prop = new Properties(); FileInputStream in = new FileInputStream(new File(directory + separator + filename)); prop.load(in); in.close(); prop.setProperty("verification.file", verifyFile); if (!bddSize.equals("")) { prop.setProperty("verification.bddSize", this.bddSize.getText() .trim()); } if (!componentField.getText().trim().equals("")) { prop.setProperty("verification.component", componentField .getText().trim()); } else { prop.remove("verification.component"); } String[] components = componentList.getItems(); if (components.length == 0) { for (Object s : prop.keySet()) { if (s.toString().startsWith("verification.compList")) { prop.remove(s); } } } else { for (Integer i = 0; i < components.length; i++) { prop.setProperty("verification.compList" + i.toString(), components[i]); } } String[] lpns = lpnList.getItems(); if (lpns.length == 0) { for (Object s : prop.keySet()) { if (s.toString().startsWith("verification.lpnList")) { prop.remove(s); } } } else { for (Integer i = 0; i < lpns.length; i++) { prop.setProperty("verification.lpnList" + i.toString(), lpns[i]); } } if (none.isSelected()) { prop.setProperty("verification.abstraction", "none"); } else if (simplify.isSelected()) { prop.setProperty("verification.abstraction", "simplify"); } else { prop.setProperty("verification.abstraction", "abstract"); } if (atacs) { if (untimed.isSelected()) { prop.setProperty("verification.timing.methods", "untimed"); } else if (geometric.isSelected()) { prop .setProperty("verification.timing.methods", "geometric"); } else if (posets.isSelected()) { prop.setProperty("verification.timing.methods", "posets"); } else if (bag.isSelected()) { prop.setProperty("verification.timing.methods", "bag"); } else if (bap.isSelected()) { prop.setProperty("verification.timing.methods", "bap"); } else if (baptdc.isSelected()) { prop.setProperty("verification.timing.methods", "baptdc"); } else if (lhpn.isSelected()) { prop.setProperty("verification.timing.methods", "lhpn"); } else { prop.setProperty("verification.timing.methods", "view"); } } else { if (bdd.isSelected()) { prop.setProperty("verification.timing.methods", "bdd"); } else if (dbm.isSelected()) { prop.setProperty("verification.timing.methods", "dbm"); } else if (smt.isSelected()) { prop.setProperty("verification.timing.methods", "smt"); } else if (untimedStateSearch.isSelected()) { prop.setProperty("verification.timing.methods", "untimedStateSearch"); } else if (lhpn.isSelected()) { prop.setProperty("verification.timing.methods", "lhpn"); } else { prop.setProperty("verification.timing.methods", "view"); } } if (abst.isSelected()) { prop.setProperty("verification.Abst", "true"); } else { prop.setProperty("verification.Abst", "false"); } if (partialOrder.isSelected()) { prop.setProperty("verification.partial.order", "true"); } else { prop.setProperty("verification.partial.order", "false"); } if (dot.isSelected()) { prop.setProperty("verification.Dot", "true"); } else { prop.setProperty("verification.Dot", "false"); } if (verbose.isSelected()) { prop.setProperty("verification.Verb", "true"); } else { prop.setProperty("verification.Verb", "false"); } if (graph.isSelected()) { prop.setProperty("verification.Graph", "true"); } else { prop.setProperty("verification.Graph", "false"); } if (untimedPOR.isSelected()) { prop.setProperty("verification.UntimedPOR", "true"); } else { prop.setProperty("verification.UntimedPOR", "false"); } if (decomposeLPN.isSelected()) { prop.setProperty("verification.DecomposeLPN", "true"); } else { prop.setProperty("verification.DecomposeLPN", "false"); } if (multipleLPNs.isSelected()) { prop.setProperty("verification.MultipleLPNs", "true"); } else { prop.setProperty("verification.MultipleLPNs", "false"); } if (verify.isSelected()) { prop.setProperty("verification.algorithm", "verify"); } else if (vergate.isSelected()) { prop.setProperty("verification.algorithm", "vergate"); } else if (orbits.isSelected()) { prop.setProperty("verification.algorithm", "orbits"); } else if (search.isSelected()) { prop.setProperty("verification.algorithm", "search"); } else if (trace.isSelected()) { prop.setProperty("verification.algorithm", "trace"); } if (newTab.isSelected()) { prop.setProperty("verification.compilation.newTab", "true"); } else { prop.setProperty("verification.compilation.newTab", "false"); } if (postProc.isSelected()) { prop.setProperty("verification.compilation.postProc", "true"); } else { prop.setProperty("verification.compilation.postProc", "false"); } if (redCheck.isSelected()) { prop.setProperty("verification.compilation.redCheck", "true"); } else { prop.setProperty("verification.compilation.redCheck", "false"); } if (xForm2.isSelected()) { prop.setProperty("verification.compilation.xForm2", "true"); } else { prop.setProperty("verification.compilation.xForm2", "false"); } if (expandRate.isSelected()) { prop.setProperty("verification.compilation.expandRate", "true"); } else { prop .setProperty("verification.compilation.expandRate", "false"); } if (genrg.isSelected()) { prop.setProperty("verification.timing.genrg", "true"); } else { prop.setProperty("verification.timing.genrg", "false"); } if (timsubset.isSelected()) { prop.setProperty("verification.timing.subset", "true"); } else { prop.setProperty("verification.timing.subset", "false"); } if (superset.isSelected()) { prop.setProperty("verification.timing.superset", "true"); } else { prop.setProperty("verification.timing.superset", "false"); } if (infopt.isSelected()) { prop.setProperty("verification.timing.infopt", "true"); } else { prop.setProperty("verification.timing.infopt", "false"); } if (orbmatch.isSelected()) { prop.setProperty("verification.timing.orbmatch", "true"); } else { prop.setProperty("verification.timing.orbmatch", "false"); } if (interleav.isSelected()) { prop.setProperty("verification.timing.interleav", "true"); } else { prop.setProperty("verification.timing.interleav", "false"); } if (prune.isSelected()) { prop.setProperty("verification.timing.prune", "true"); } else { prop.setProperty("verification.timing.prune", "false"); } if (disabling.isSelected()) { prop.setProperty("verification.timing.disabling", "true"); } else { prop.setProperty("verification.timing.disabling", "false"); } if (nofail.isSelected()) { prop.setProperty("verification.timing.nofail", "true"); } else { prop.setProperty("verification.timing.nofail", "false"); } if (nofail.isSelected()) { prop.setProperty("verification.timing.noproj", "true"); } else { prop.setProperty("verification.timing.noproj", "false"); } if (keepgoing.isSelected()) { prop.setProperty("verification.timing.keepgoing", "true"); } else { prop.setProperty("verification.timing.keepgoing", "false"); } if (explpn.isSelected()) { prop.setProperty("verification.timing.explpn", "true"); } else { prop.setProperty("verification.timing.explpn", "false"); } if (nochecks.isSelected()) { prop.setProperty("verification.nochecks", "true"); } else { prop.setProperty("verification.nochecks", "false"); } if (reduction.isSelected()) { prop.setProperty("verification.reduction", "true"); } else { prop.setProperty("verification.reduction", "false"); } String intVars = ""; for (int i = 0; i < abstPane.listModel.getSize(); i++) { if (abstPane.listModel.getElementAt(i) != null) { intVars = intVars + abstPane.listModel.getElementAt(i) + " "; } } if (sListModel.size() > 0) { String list = ""; for (Object o : sListModel.toArray()) { list = list + o + " "; } list.trim(); prop.put("verification.sList", list); } else { prop.remove("verification.sList"); } if (!intVars.equals("")) { prop.setProperty("abstraction.interesting", intVars.trim()); } else { prop.remove("abstraction.interesting"); } for (Integer i=0; i<abstPane.preAbsModel.size(); i++) { prop.setProperty("abstraction.transform." + abstPane.preAbsModel.getElementAt(i).toString(), "preloop" + i.toString()); } for (Integer i=0; i<abstPane.loopAbsModel.size(); i++) { if (abstPane.preAbsModel.contains(abstPane.loopAbsModel.getElementAt(i))) { String value = prop.getProperty("abstraction.transform." + abstPane.loopAbsModel.getElementAt(i).toString()); value = value + "mainloop" + i.toString(); prop.setProperty("abstraction.transform." + abstPane.loopAbsModel.getElementAt(i).toString(), value); } else { prop.setProperty("abstraction.transform." + abstPane.loopAbsModel.getElementAt(i).toString(), "mainloop" + i.toString()); } } for (Integer i=0; i<abstPane.postAbsModel.size(); i++) { if (abstPane.preAbsModel.contains(abstPane.postAbsModel.getElementAt(i)) || abstPane.preAbsModel.contains(abstPane.postAbsModel.get(i))) { String value = prop.getProperty("abstraction.transform." + abstPane.postAbsModel.getElementAt(i).toString()); value = value + "postloop" + i.toString(); prop.setProperty("abstraction.transform." + abstPane.postAbsModel.getElementAt(i).toString(), value); } else { prop.setProperty("abstraction.transform." + abstPane.postAbsModel.getElementAt(i).toString(), "postloop" + i.toString()); } } for (String s : abstPane.transforms) { if (!abstPane.preAbsModel.contains(s) && !abstPane.loopAbsModel.contains(s) && !abstPane.postAbsModel.contains(s)) { prop.remove(s); } } if (!abstPane.factorField.getText().equals("")) { prop.setProperty("abstraction.factor", abstPane.factorField .getText()); } if (!abstPane.iterField.getText().equals("")) { prop.setProperty("abstraction.iterations", abstPane.iterField .getText()); } FileOutputStream out = new FileOutputStream(new File(directory + separator + verFile)); prop.store(out, verifyFile); out.close(); log.addText("Saving Parameter File:\n" + directory + separator + verFile + "\n"); change = false; oldBdd = bddSize.getText(); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(Gui.frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } for (String s : componentList.getItems()) { try { new File(directory + separator + s).createNewFile(); FileInputStream in = new FileInputStream(new File(root + separator + s)); FileOutputStream out = new FileOutputStream(new File(directory + separator + s)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } catch (IOException e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(Gui.frame, "Cannot add the selected component.", "Error", JOptionPane.ERROR_MESSAGE); } } for (String s : lpnList.getItems()) { try { new File(directory + separator + s).createNewFile(); FileInputStream in = new FileInputStream(new File(root + separator + s)); FileOutputStream out = new FileOutputStream(new File(directory + separator + s)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } catch (IOException e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(Gui.frame, "Cannot add the selected LPN.", "Error", JOptionPane.ERROR_MESSAGE); } } } public void reload(String newname) { } public void viewCircuit() { String[] getFilename; if (componentField.getText().trim().equals("")) { getFilename = verifyFile.split("\\."); } else { getFilename = new String[1]; getFilename[0] = componentField.getText().trim(); } String circuitFile = getFilename[0] + ".prs"; try { if (new File(circuitFile).exists()) { File log = new File(circuitFile); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(Gui.frame, scrolls, "Circuit View", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(Gui.frame, "No circuit view exists.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Unable to view circuit.", "Error", JOptionPane.ERROR_MESSAGE); } } public boolean getViewTraceEnabled() { return viewTrace.isEnabled(); } public boolean getViewLogEnabled() { return viewLog.isEnabled(); } public void viewTrace() { String[] getFilename = verifyFile.split("\\."); String traceFilename = getFilename[0] + ".trace"; try { if (new File(directory + separator + traceFilename).exists()) { File log = new File(directory + separator + traceFilename); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(Gui.frame, scrolls, "Trace View", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(Gui.frame, "No trace file exists.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane .showMessageDialog(Gui.frame, "Unable to view trace.", "Error", JOptionPane.ERROR_MESSAGE); } } public void viewLog() { try { if (new File(directory + separator + "run.log").exists()) { File log = new File(directory + separator + "run.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(Gui.frame, scrolls, "Run Log", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(Gui.frame, "No run log exists.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Unable to view run log.", "Error", JOptionPane.ERROR_MESSAGE); } } public boolean hasChanged() { if (!oldBdd.equals(bddSize.getText())) { return true; } return change; } public boolean isSimplify() { if (simplify.isSelected()) return true; return false; } public void copyFile() { String[] tempArray = verifyFile.split(separator); String sourceFile = tempArray[tempArray.length - 1]; String[] workArray = directory.split(separator); String workDir = ""; for (int i = 0; i < (workArray.length - 1); i++) { workDir = workDir + workArray[i] + separator; } try { File newFile = new File(directory + separator + sourceFile); newFile.createNewFile(); FileOutputStream copyin = new FileOutputStream(newFile); FileInputStream copyout = new FileInputStream(new File(workDir + separator + sourceFile)); int read = copyout.read(); while (read != -1) { copyin.write(read); read = copyout.read(); } copyin.close(); copyout.close(); } catch (IOException e) { JOptionPane.showMessageDialog(Gui.frame, "Cannot copy file " + sourceFile, "Copy Error", JOptionPane.ERROR_MESSAGE); } /* TODO Test Assembly File compilation */ if (sourceFile.endsWith(".s") || sourceFile.endsWith(".inst")) { biosim.copySFiles(verifyFile, directory); try { String preprocCmd; if (lema) { preprocCmd = System.getenv("LEMA") + "/bin/s2lpn " + verifyFile; } else if (atacs) { preprocCmd = System.getenv("ATACS") + "/bin/s2lpn " + verifyFile; } else { preprocCmd = System.getenv("BIOSIM") + "/bin/s2lpn " + verifyFile; } //for (Object o : sListModel.toArray()) { // preprocCmd = preprocCmd + " " + o.toString(); File work = new File(directory); Runtime exec = Runtime.getRuntime(); Process preproc = exec.exec(preprocCmd, null, work); log.addText("Executing:\n" + preprocCmd + "\n"); preproc.waitFor(); if (verifyFile.endsWith(".s")) { verifyFile.replace(".s", ".lpn"); } else { verifyFile.replace(".inst", ".lpn"); } } catch (Exception e) { JOptionPane.showMessageDialog(Gui.frame, "Error with preprocessing.", "Error", JOptionPane.ERROR_MESSAGE); //e.printStackTrace(); } } } public String getVerName() { String verName = verFile.replace(".ver", ""); return verName; } public AbstPane getAbstPane() { return abstPane; } /** * Calls the appropriate dot program to show the graph. * @param fileName The absolute file name. */ public void showGraph(String fileName) { File file = new File(fileName); File work = file.getParentFile(); try { Runtime exec = Runtime.getRuntime(); if (new File(fileName).exists()) { long kB = 1024; // number of bytes in a kilobyte. long fileSize = file.length()/kB; // Size of file in megabytes. // If the file is larger than a given amount of megabytes, // then give the user the chance to cancel the operation. int thresholdSize = 100; // Specifies the threshold for giving the // user the option to not attempt to open the file. if(fileSize > thresholdSize) { int answer = JOptionPane.showConfirmDialog(Gui.frame, "The size of the file exceeds " + thresholdSize + " kB." + "The file may not open. Do you want to continue?", "Do you want to continue?", JOptionPane.YES_NO_OPTION); if(answer == JOptionPane.NO_OPTION) { return; } } String command; if (System.getProperty("os.name") .contentEquals("Linux")) { command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase() .startsWith("mac os")) { command = "open "; } else { command = "dotty "; } Process dot = exec.exec(command + fileName, null, work); log.addText(command + fileName + "\n"); dot.waitFor(); } else { JOptionPane.showMessageDialog(Gui.frame, "Unable to view dot file.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e) { e.printStackTrace(); } } public boolean canPerformMarkovianAnalysis(LhpnFile lpn) { for (String trans : lpn.getTransitionList()) { if (!lpn.isExpTransitionRateTree(trans)) { // JOptionPane.showMessageDialog(Gui.frame, "LPN has transitions without exponential delay.", // "Unable to Perform Markov Chain Analysis", JOptionPane.ERROR_MESSAGE); return false; } for (String var : lpn.getVariables()) { if (lpn.isRandomBoolAssignTree(trans, var)) { // JOptionPane.showMessageDialog(Gui.frame, "LPN has assignments containing random functions.", // "Unable to Perform Markov Chain Analysis", JOptionPane.ERROR_MESSAGE); return false; } if (lpn.isRandomContAssignTree(trans, var)) { // JOptionPane.showMessageDialog(Gui.frame, "LPN has assignments containing random functions.", // "Unable to Perform Markov Chain Analysis", JOptionPane.ERROR_MESSAGE); return false; } if (lpn.isRandomIntAssignTree(trans, var)) { // JOptionPane.showMessageDialog(Gui.frame, "LPN has assignments containing random functions.", // "Unable to Perform Markov Chain Analysis", JOptionPane.ERROR_MESSAGE); return false; } } } if (lpn.getContVars().length > 0) { // JOptionPane.showMessageDialog(Gui.frame, "LPN contains continuous variables.", // "Unable to Perform Markov Chain Analysis", JOptionPane.ERROR_MESSAGE); return false; } return true; } }
package org.apache.lenya.cms.workflow; import java.io.File; import java.util.List; import java.util.Map; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; import org.apache.cocoon.environment.Session; import org.apache.lenya.cms.ac.Role; import org.apache.lenya.cms.publication.Document; import org.apache.lenya.cms.publication.Publication; import org.apache.lenya.workflow.*; import org.apache.lenya.workflow.Workflow; import org.apache.lenya.workflow.impl.WorkflowBuilder; /** * * @author andreas */ public class WorkflowFactory { public static final String WORKFLOW_DIRECTORY = "config/workflow".replace('/', File.separatorChar); /** Creates a new instance of WorkflowFactory */ protected WorkflowFactory() { } /** * Returns an instance of the workflow factory. * @return A workflow factory. */ public static WorkflowFactory newInstance() { return new WorkflowFactory(); } /** * Creates a new workflow instance. * @param document The document to create the instance for. * @return A workflow instance. * @throws WorkflowException when something went wrong. */ public WorkflowInstance buildInstance(Document document) throws WorkflowException { assert document != null; return new CMSHistory(document).getInstance(); } /** * Checks if a workflow is assigned to the document. * This is done by looking for the workflow history file. * @param document The document to check. * @return <code>true</code> if the document has a workflow, <code>false</code> otherwise. */ public boolean hasWorkflow(Document document) { return new CMSHistory(document).isInitialized(); } /** * Builds a workflow for a given publication. * @param publication The publication. * @param workflowFileName The workflow definition filename. * @return A workflow object. * @throws WorkflowException when something went wrong. */ protected static Workflow buildWorkflow(Publication publication, String workflowFileName) throws WorkflowException { assert publication != null; assert workflowFileName != null && !"".equals(workflowFileName); File workflowDirectory = new File(publication.getDirectory(), WORKFLOW_DIRECTORY); File workflowFile = new File(workflowDirectory, workflowFileName); Workflow workflow = WorkflowBuilder.buildWorkflow(workflowFile); return workflow; } /** * Creates a new workflow situation. * @param roles The roles of the situation. * @return A situation. * @throws WorkflowException when something went wrong. */ public Situation buildSituation(Role roles[]) throws WorkflowException { return new CMSSituation(roles); } /** * Creates a situation for a Cocoon object model. * @param objectModel The object model. * @return A workflow situation. * @throws WorkflowException when something went wrong. */ public Situation buildSituation(Map objectModel) throws WorkflowException { Request request = ObjectModelHelper.getRequest(objectModel); Session session = request.getSession(true); List roleList = (List) request.getAttribute(Role.class.getName()); if (roleList == null) { throw new WorkflowException("Request does not contain roles!"); } Role[] roles = (Role[]) roleList.toArray(new Role[roleList.size()]); return buildSituation(roles); } /** * Initializes the history of a document. * @param document The document object. * @param workflowId The ID of the workflow. * @throws WorkflowException When something goes wrong. */ public static void initHistory(Document document, String workflowId) throws WorkflowException { new CMSHistory(document).initialize(workflowId); } }
package org.apache.james.remotemanager; import org.apache.java.lang.*; import org.apache.avalon.interfaces.*; import org.apache.james.*; import org.apache.james.transport.*; import org.apache.james.usermanager.*; import java.net.*; import java.io.*; import java.util.*; /** * Provides a really rude network interface to administer James. * Allow to add accounts. * TODO: -improve protocol * -add remove user * -much more... * @version 1.0.0, 24/04/1999 * @author Federico Barbieri <scoobie@pop.systemy.it> */ public class RemoteManager implements SocketServer.SocketHandler, TimeServer.Bell, Composer, Configurable { private ComponentManager comp; private Configuration conf; private Logger logger; private UsersRepository userManager; private TimeServer timeServer; private BufferedReader in; private InputStream socketIn; private PrintWriter out; private OutputStream r_out; private Hashtable admaccount; private Socket socket; public void setConfiguration(Configuration conf) { this.conf = conf; } public void setComponentManager(ComponentManager comp) { this.comp = comp; } public void init() throws Exception { logger = (Logger) comp.getComponent(Interfaces.LOGGER); logger.log("RemoteManager init...", "RemoteAdmin", logger.INFO); this.timeServer = (TimeServer) comp.getComponent(Interfaces.TIME_SERVER); SocketServer socketServer = (SocketServer) comp.getComponent(Interfaces.SOCKET_SERVER); socketServer.openListener("JAMESRemoteControlListener", SocketServer.DEFAULT, conf.getConfiguration("port", "4554").getValueAsInt(), this); admaccount = new Hashtable(); for (Enumeration e = conf.getConfigurations("administrator_accounts.account"); e.hasMoreElements();) { Configuration c = (Configuration) e.nextElement(); admaccount.put(c.getAttribute("login"), c.getAttribute("password")); } if (admaccount.isEmpty()) { logger.log("No Administrative account defined", "RemoteAdmin", logger.WARNING); } UserManager manager = (UserManager) comp.getComponent(Resources.USERS_MANAGER); userManager = (UsersRepository) manager.getUserRepository("LocalUsers"); logger.log("RemoteManager ...init end", "RemoteAdmin", logger.INFO); } public void parseRequest(Socket s) { timeServer.setAlarm("RemoteManager", this, conf.getConfiguration("connectiontimeout", "120000").getValueAsLong()); socket = s; String remoteHost = s.getInetAddress().getHostName(); String remoteIP = s.getInetAddress().getHostAddress(); try { socketIn = s.getInputStream(); in = new BufferedReader(new InputStreamReader(socketIn)); r_out = s.getOutputStream(); out = new PrintWriter(r_out, true); logger.log("Access from " + remoteHost + "(" + remoteIP + ")", "RemoteAdmin", logger.INFO); out.println("JAMES RemoteAdministration Tool " + Constants.SOFTWARE_VERSION); out.println("Please enter your login and password"); String login = in.readLine(); String password = in.readLine(); while (!password.equals(admaccount.get(login))) { out.println("Login failed for " + login); logger.log("Login for " + login + " failed", "RemoteAdmin", logger.INFO); login = in.readLine(); password = in.readLine(); } timeServer.resetAlarm("RemoteManager"); out.println("Welcome " + login + ". HELP for a list of commands"); logger.log("Login for " + login + " succesful", "RemoteAdmin", logger.INFO); while (parseCommand(in.readLine())) { timeServer.resetAlarm("RemoteManager"); } logger.log("Logout for " + login + ".", "RemoteAdmin", logger.INFO); s.close(); } catch (IOException e) { out.println("Error. Closing connection"); out.flush(); logger.log("Exception during connection from " + remoteHost + " (" + remoteIP + ")", "RemoteAdmin", logger.ERROR); } timeServer.removeAlarm("RemoteManager"); } public void wake(String name, String memo) { logger.log("Connection timeout on socket", "RemoteAdmin", logger.ERROR); try { out.println("Connection timeout. Closing connection"); socket.close(); } catch (IOException e) { } } private boolean parseCommand(String command) { if (command == null) return false; StringTokenizer commandLine = new StringTokenizer(command.trim(), " "); int arguments = commandLine.countTokens(); if (arguments == 0) { return true; } else if(arguments > 0) { command = commandLine.nextToken(); } String argument = (String) null; if(arguments > 1) { argument = commandLine.nextToken(); } String argument1 = (String) null; if(arguments > 2) { argument1 = commandLine.nextToken(); } if (command.equalsIgnoreCase("ADDUSER")) { String user = argument; String passwd = argument1; try { if (user.equals("") || passwd.equals("")) { out.println("usage: adduser [username] [password]"); return true; } } catch (NullPointerException e) { out.println("usage: adduser [username] [password]"); return true; } if (userManager.contains(user)) { out.println("user " + user + " already exist"); } else { userManager.addUser(user, passwd); out.println("User " + user + " added"); logger.log("User " + user + " added", "RemoteAdmin", logger.INFO); } out.flush(); } else if (command.equalsIgnoreCase("DELUSER")) { String user = argument; if (user.equals("")) { out.println("usage: deluser [username]"); return true; } try { userManager.removeUser(user); } catch (Exception e) { out.println("Error deleting user " + user + " : " + e.getMessage()); return true; } out.println("User " + user + " deleted"); logger.log("User " + user + " deleted", "RemoteAdmin", logger.INFO); } else if (command.equalsIgnoreCase("LISTUSERS")) { out.println("Existing accounts " + userManager.countUsers()); for (Enumeration e = userManager.list(); e.hasMoreElements();) { out.println("user: " + (String) e.nextElement()); } } else if (command.equalsIgnoreCase("COUNTUSERS")) { out.println("Existing accounts " + userManager.countUsers()); } else if (command.equalsIgnoreCase("VERIFY")) { String user = argument; if (user.equals("")) { out.println("usage: verify [username]"); return true; } if (userManager.contains(user)) { out.println("User " + user + " exist"); } else { out.println("User " + user + " does not exist"); } } else if (command.equalsIgnoreCase("HELP")) { out.println("Currently implemented commans:"); out.println("help display this help"); out.println("adduser [username] [password] add a new user"); out.println("deluser [username] delete existing user"); out.println("listusers display existing accounts"); out.println("countusers display the number of existing accounts"); out.println("verify [username] verify if specified user exist"); out.println("quit close connection"); out.flush(); } else if (command.equalsIgnoreCase("QUIT")) { out.println("bye"); return false; } else { out.println("unknown command " + command); } return true; } public void destroy() { } }
package joshua.decoder.ff.lm.berkeley_lm; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.StreamCorruptedException; import java.util.Arrays; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import joshua.decoder.JoshuaConfiguration; import joshua.decoder.ff.lm.AbstractLM; import edu.berkeley.nlp.lm.ArrayEncodedNgramLanguageModel; import edu.berkeley.nlp.lm.ConfigOptions; import edu.berkeley.nlp.lm.WordIndexer; import edu.berkeley.nlp.lm.StringWordIndexer; import edu.berkeley.nlp.lm.cache.ArrayEncodedCachingLmWrapper; import edu.berkeley.nlp.lm.io.LmReaders; import edu.berkeley.nlp.lm.util.StrUtils; /** * This class wraps Berkeley LM. * * @author adpauls@gmail.com */ public class LMGrammarBerkeley extends AbstractLM { private ArrayEncodedNgramLanguageModel<String> lm; private static final Logger logger = Logger.getLogger(LMGrammarBerkeley.class.getName()); private int[] vocabIdToMyIdMapping; private ThreadLocal<int[]> arrayScratch = new ThreadLocal<int[]>() { @Override protected int[] initialValue() { return new int[5]; } }; private int mappingLength = 0; private final int unkIndex; private static boolean logRequests = false; private static Handler logHandler = null; public LMGrammarBerkeley(int order, String lm_file) { super(order); vocabIdToMyIdMapping = new int[10]; // determine whether the file is in its binary format boolean fileIsBinary = true; try { ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(new File(lm_file)))); } catch (StreamCorruptedException e) { fileIsBinary = false; } catch (IOException e) { System.err.println("Can't read file '" + lm_file + "'"); System.exit(1); } if (logRequests) { logger.addHandler(logHandler); logger.setLevel(Level.FINEST); logger.setUseParentHandlers(false); } if (fileIsBinary) { logger.info("Loading Berkeley LM from binary " + lm_file); lm = (ArrayEncodedNgramLanguageModel<String>) LmReaders.<String>readLmBinary(lm_file); } else { ConfigOptions opts = new ConfigOptions(); opts.unknownWordLogProb = -1.0f * JoshuaConfiguration.lm_ceiling_cost; logger.info("Loading Berkeley LM from ARPA file " + lm_file); final StringWordIndexer wordIndexer = new StringWordIndexer(); ArrayEncodedNgramLanguageModel<String> berkeleyLm = LmReaders.readArrayEncodedLmFromArpa(lm_file, false, wordIndexer, opts, order); lm = ArrayEncodedCachingLmWrapper.wrapWithCacheThreadSafe(berkeleyLm); } lm.setOovWordLogProb((float) (-1.0f * JoshuaConfiguration.lm_ceiling_cost)); this.unkIndex = lm.getWordIndexer().getOrAddIndex(lm.getWordIndexer().getUnkSymbol()); } @Override public boolean registerWord(String token, int id) { int myid = lm.getWordIndexer().getIndexPossiblyUnk(token); if (myid < 0) return false; if (id >= vocabIdToMyIdMapping.length) { vocabIdToMyIdMapping = Arrays.copyOf(vocabIdToMyIdMapping, Math.max(id + 1, vocabIdToMyIdMapping.length * 2)); } mappingLength = Math.max(mappingLength, id + 1); vocabIdToMyIdMapping[id] = myid == unkIndex ? -1 : myid; return false; } @Override protected double ngramLogProbability_helper(int[] ngram, int order) { int[] mappedNgram = arrayScratch.get(); if (mappedNgram.length < ngram.length) { arrayScratch.set(mappedNgram = new int[mappedNgram.length * 2]); } for (int i = 0; i < ngram.length; ++i) { mappedNgram[i] = (ngram[i] == unkIndex || ngram[i] >= mappingLength) ? -1 : vocabIdToMyIdMapping[ngram[i]]; } if (logRequests) { final int[] copyOf = Arrays.copyOf(mappedNgram, ngram.length); for (int i = 0; i < copyOf.length; ++i) if (copyOf[i] < 0) copyOf[i] = unkIndex; logger.finest(StrUtils.join(WordIndexer.StaticMethods.toList(lm.getWordIndexer(),copyOf))); } final float res = lm.getLogProb(mappedNgram, 0, ngram.length); return res; } @Override protected double logProbabilityOfBackoffState_helper(int[] ngram, int order, int qtyAdditionalBackoffWeight) { throw new UnsupportedOperationException( "probabilityOfBackoffState_helper undefined for Berkeley lm"); } public static void setLogRequests(Handler handler) { logRequests = true; logHandler = handler; } }
package org.apache.xerces.impl.xs; import org.apache.xerces.impl.RevalidationHandler; import org.apache.xerces.impl.dv.XSSimpleType; import org.apache.xerces.impl.dv.ValidatedInfo; import org.apache.xerces.impl.dv.DatatypeException; import org.apache.xerces.impl.dv.InvalidDatatypeValueException; import org.apache.xerces.impl.xs.identity.*; import org.apache.xerces.impl.Constants; import org.apache.xerces.impl.validation.ValidationManager; import org.apache.xerces.util.XMLGrammarPoolImpl; import org.apache.xerces.impl.XMLErrorReporter; import org.apache.xerces.impl.xs.traversers.XSAttributeChecker; import org.apache.xerces.impl.xs.models.CMBuilder; import org.apache.xerces.impl.xs.models.XSCMValidator; import org.apache.xerces.impl.xs.psvi.XSConstants; import org.apache.xerces.impl.xs.psvi.XSObjectList; import org.apache.xerces.impl.msg.XMLMessageFormatter; import org.apache.xerces.impl.validation.ValidationState; import org.apache.xerces.impl.XMLEntityManager; import org.apache.xerces.util.AugmentationsImpl; import org.apache.xerces.util.NamespaceSupport; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.util.XMLChar; import org.apache.xerces.util.IntStack; import org.apache.xerces.util.XMLResourceIdentifierImpl; import org.apache.xerces.xni.Augmentations; import org.apache.xerces.xni.QName; import org.apache.xerces.xni.XMLString; import org.apache.xerces.xni.XMLAttributes; import org.apache.xerces.xni.XMLDocumentHandler; import org.apache.xerces.xni.parser.XMLDocumentFilter; import org.apache.xerces.xni.XMLLocator; import org.apache.xerces.xni.XMLResourceIdentifier; import org.apache.xerces.xni.XNIException; import org.apache.xerces.xni.parser.XMLComponent; import org.apache.xerces.xni.parser.XMLComponentManager; import org.apache.xerces.xni.parser.XMLConfigurationException; import org.apache.xerces.xni.parser.XMLEntityResolver; import org.apache.xerces.xni.parser.XMLInputSource; import org.apache.xerces.xni.grammars.XMLGrammarPool; import org.apache.xerces.xni.grammars.Grammar; import org.apache.xerces.xni.grammars.XMLGrammarDescription; import org.apache.xerces.xni.psvi.ElementPSVI; import org.apache.xerces.xni.psvi.AttributePSVI; import org.xml.sax.InputSource ; import java.util.Enumeration; import java.util.Hashtable; import java.util.Stack; import java.util.Vector; import java.io.IOException; public class XMLSchemaValidator implements XMLComponent, XMLDocumentFilter, FieldActivator, RevalidationHandler { // Constants private static final boolean DEBUG = false; // feature identifiers protected static final String NAMESPACES = Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE; /** Feature identifier: validation. */ protected static final String VALIDATION = Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE; /** Feature identifier: validation. */ protected static final String SCHEMA_VALIDATION = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_VALIDATION_FEATURE; /** Feature identifier: schema full checking*/ protected static final String SCHEMA_FULL_CHECKING = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_FULL_CHECKING; /** Feature identifier: dynamic validation. */ protected static final String DYNAMIC_VALIDATION = Constants.XERCES_FEATURE_PREFIX + Constants.DYNAMIC_VALIDATION_FEATURE; /** Feature identifier: expose schema normalized value */ protected static final String NORMALIZE_DATA = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_NORMALIZED_VALUE; /** Feature identifier: send element default value via characters() */ protected static final String SCHEMA_ELEMENT_DEFAULT = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_ELEMENT_DEFAULT; // property identifiers /** Property identifier: symbol table. */ public static final String SYMBOL_TABLE = Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY; /** Property identifier: error reporter. */ public static final String ERROR_REPORTER = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY; /** Property identifier: entity resolver. */ public static final String ENTITY_RESOLVER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY; /** Property identifier: grammar pool. */ public static final String XMLGRAMMAR_POOL = Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY; protected static final String VALIDATION_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY; protected static final String ENTITY_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_MANAGER_PROPERTY; /** Property identifier: schema location. */ protected static final String SCHEMA_LOCATION = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_LOCATION; /** Property identifier: no namespace schema location. */ protected static final String SCHEMA_NONS_LOCATION = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_NONS_LOCATION; /** Property identifier: JAXP schema source. */ protected static final String JAXP_SCHEMA_SOURCE = Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE; // recognized features and properties /** Recognized features. */ protected static final String[] RECOGNIZED_FEATURES = { VALIDATION, NAMESPACES, SCHEMA_VALIDATION, DYNAMIC_VALIDATION, SCHEMA_FULL_CHECKING, }; /** Recognized properties. */ protected static final String[] RECOGNIZED_PROPERTIES = { SYMBOL_TABLE, ERROR_REPORTER, ENTITY_RESOLVER, VALIDATION_MANAGER, SCHEMA_LOCATION, SCHEMA_NONS_LOCATION, JAXP_SCHEMA_SOURCE }; // Data protected boolean fSeenRoot = false; // features // REVISIT: what does it mean if namespaces is off // while schema validation is on? protected boolean fNamespaces = false; /** PSV infoset information for element */ protected final ElementPSVImpl fElemPSVI = new ElementPSVImpl(); /** current PSVI element info */ protected ElementPSVImpl fCurrentPSVI = null; // since it is the responsibility of each component to an // Augmentations parameter if one is null, to save ourselves from // having to create this object continually, it is created here. // If it is not present in calls that we're passing on, we *must* // clear this before we introduce it into the pipeline. protected final AugmentationsImpl fAugmentations = new AugmentationsImpl(); // this is included for the convenience of handleEndElement protected XMLString fDefaultValue; /** Validation. */ protected boolean fValidation = false; protected boolean fDynamicValidation = false; protected boolean fDoValidation = false; protected boolean fFullChecking = false; protected boolean fNormalizeData = true; protected boolean fSchemaElementDefault = true; protected boolean fEntityRef = false; protected boolean fInCDATA = false; // properties /** Symbol table. */ protected SymbolTable fSymbolTable; /** * A wrapper of the standard error reporter. We'll store all schema errors * in this wrapper object, so that we can get all errors (error codes) of * a specific element. This is useful for PSVI. */ class XSIErrorReporter { // the error reporter property XMLErrorReporter fErrorReporter; // store error codes; starting position of the errors for each element; // number of element (depth); and whether to record error Vector fErrors = new Vector(INITIAL_STACK_SIZE, INC_STACK_SIZE); int[] fContext = new int[INITIAL_STACK_SIZE]; int fContextCount; // set the external error reporter, clear errors public void reset(XMLErrorReporter errorReporter) { fErrorReporter = errorReporter; fErrors.removeAllElements(); fContextCount = 0; } // should be called on startElement: store the starting position // for the current element public void pushContext() { // resize array if necessary if (fContextCount == fContext.length) { int newSize = fContextCount + INC_STACK_SIZE; int[] newArray = new int[newSize]; System.arraycopy(fContext, 0, newArray, 0, fContextCount); fContext = newArray; } fContext[fContextCount++] = fErrors.size(); } // should be called on endElement: get all errors of the current element public String[] popContext() { // get starting position of the current element int contextPos = fContext[--fContextCount]; // number of errors of the current element int size = fErrors.size() - contextPos; // if no errors, return null if (size == 0) return null; // copy errors from the list to an string array String[] errors = new String[size]; for (int i = 0; i < size; i++) { errors[i] = (String)fErrors.elementAt(contextPos + i); } // remove errors of the current element fErrors.setSize(contextPos); return errors; } public void reportError(String domain, String key, Object[] arguments, short severity) throws XNIException { fErrorReporter.reportError(domain, key, arguments, severity); fErrors.addElement(key); } // reportError(String,String,Object[],short) public void reportError(XMLLocator location, String domain, String key, Object[] arguments, short severity) throws XNIException { fErrorReporter.reportError(location, domain, key, arguments, severity); fErrors.addElement(key); } // reportError(XMLLocator,String,String,Object[],short) } /** Error reporter. */ protected XSIErrorReporter fXSIErrorReporter = new XSIErrorReporter(); /** Entity resolver */ protected XMLEntityResolver fEntityResolver; // updated during reset protected ValidationManager fValidationManager = null; protected ValidationState fValidationState = new ValidationState(); protected XMLGrammarPool fGrammarPool; // schema location property values protected String fExternalSchemas = null; protected String fExternalNoNamespaceSchema = null; //JAXP Schema Source property protected Object fJaxpSchemaSource = null ; //ResourceIdentifier for use in calling EntityResolver XMLResourceIdentifierImpl fResourceIdentifier = new XMLResourceIdentifierImpl(); /** Schema Grammar Description passed, to give a chance to application to supply the Grammar */ protected final XSDDescription fXSDDescription = new XSDDescription() ; protected final Hashtable fLocationPairs = new Hashtable() ; protected final XMLSchemaLoader.LocationArray fNoNamespaceLocationArray = new XMLSchemaLoader.LocationArray(); /** Base URI for the DOM revalidation*/ protected String fBaseURI = null; // handlers /** Document handler. */ protected XMLDocumentHandler fDocumentHandler; // XMLComponent methods /** * Returns a list of feature identifiers that are recognized by * this component. This method may return null if no features * are recognized by this component. */ public String[] getRecognizedFeatures() { return RECOGNIZED_FEATURES; } // getRecognizedFeatures():String[] /** * Sets the state of a feature. This method is called by the component * manager any time after reset when a feature changes state. * <p> * <strong>Note:</strong> Components should silently ignore features * that do not affect the operation of the component. * * @param featureId The feature identifier. * @param state The state of the feature. * * @throws SAXNotRecognizedException The component should not throw * this exception. * @throws SAXNotSupportedException The component should not throw * this exception. */ public void setFeature(String featureId, boolean state) throws XMLConfigurationException { } // setFeature(String,boolean) /** * Returns a list of property identifiers that are recognized by * this component. This method may return null if no properties * are recognized by this component. */ public String[] getRecognizedProperties() { return RECOGNIZED_PROPERTIES; } // getRecognizedProperties():String[] /** * Sets the value of a property. This method is called by the component * manager any time after reset when a property changes value. * <p> * <strong>Note:</strong> Components should silently ignore properties * that do not affect the operation of the component. * * @param propertyId The property identifier. * @param value The value of the property. * * @throws SAXNotRecognizedException The component should not throw * this exception. * @throws SAXNotSupportedException The component should not throw * this exception. */ public void setProperty(String propertyId, Object value) throws XMLConfigurationException { } // setProperty(String,Object) // XMLDocumentSource methods /** * Sets the document handler to receive information about the document. * * @param documentHandler The document handler. */ public void setDocumentHandler(XMLDocumentHandler documentHandler) { fDocumentHandler = documentHandler; } // setDocumentHandler(XMLDocumentHandler) // XMLDocumentHandler methods /** * The start of the document. * * @param locator The system identifier of the entity if the entity * is external, null otherwise. * @param encoding The auto-detected IANA encoding name of the entity * stream. This value will be null in those situations * where the entity encoding is not auto-detected (e.g. * internal entities or a document entity that is * parsed from a java.io.Reader). * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startDocument(XMLLocator locator, String encoding, Augmentations augs) throws XNIException { handleStartDocument(locator, encoding); // call handlers if (fDocumentHandler != null) { fDocumentHandler.startDocument(locator, encoding, augs); } } // startDocument(XMLLocator,String) /** * Notifies of the presence of an XMLDecl line in the document. If * present, this method will be called immediately following the * startDocument call. * * @param version The XML version. * @param encoding The IANA encoding name of the document, or null if * not specified. * @param standalone The standalone value, or null if not specified. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void xmlDecl(String version, String encoding, String standalone, Augmentations augs) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.xmlDecl(version, encoding, standalone, augs); } } // xmlDecl(String,String,String) /** * Notifies of the presence of the DOCTYPE line in the document. * * @param rootElement The name of the root element. * @param publicId The public identifier if an external DTD or null * if the external DTD is specified using SYSTEM. * @param systemId The system identifier if an external DTD, null * otherwise. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void doctypeDecl(String rootElement, String publicId, String systemId, Augmentations augs) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.doctypeDecl(rootElement, publicId, systemId, augs); } } // doctypeDecl(String,String,String) /** * The start of a namespace prefix mapping. This method will only be * called when namespace processing is enabled. * * @param prefix The namespace prefix. * @param uri The URI bound to the prefix. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startPrefixMapping(String prefix, String uri, Augmentations augs) throws XNIException { if (DEBUG) { System.out.println("startPrefixMapping("+prefix+","+uri+")"); } handleStartPrefix(prefix, uri); // call handlers if (fDocumentHandler != null) { fDocumentHandler.startPrefixMapping(prefix, uri, augs); } } // startPrefixMapping(String,String) /** * The start of an element. * * @param element The name of the element. * @param attributes The element attributes. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { Augmentations modifiedAugs = handleStartElement(element, attributes, augs); // call handlers if (fDocumentHandler != null) { fDocumentHandler.startElement(element, attributes, modifiedAugs ); } } // startElement(QName,XMLAttributes, Augmentations) /** * An empty element. * * @param element The name of the element. * @param attributes The element attributes. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void emptyElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { Augmentations modifiedAugs = handleStartElement(element, attributes, augs); // we need to save PSVI information: because it will be reset in the // handleEndElement(): decl, type, notation, validation context XSElementDecl decl = fCurrentPSVI.fDeclaration; XSTypeDecl type = fCurrentPSVI.fTypeDecl; XSNotationDecl notation = fCurrentPSVI.fNotation; String vContext = fCurrentPSVI.fValidationContext; // in the case where there is a {value constraint}, and the element // doesn't have any text content, change emptyElement call to // start + characters + end modifiedAugs = handleEndElement(element, modifiedAugs); // call handlers if (fDocumentHandler != null) { fCurrentPSVI.fDeclaration = decl; fCurrentPSVI.fTypeDecl = type; fCurrentPSVI.fNotation = notation; fCurrentPSVI.fValidationContext = vContext; if (!fSchemaElementDefault || fDefaultValue == null) { fDocumentHandler.emptyElement(element, attributes, modifiedAugs); } else { fDocumentHandler.startElement(element, attributes, modifiedAugs); fDocumentHandler.characters(fDefaultValue, modifiedAugs); fDocumentHandler.endElement(element, modifiedAugs); } } } // emptyElement(QName,XMLAttributes, Augmentations) /** * Character content. * * @param text The content. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void characters(XMLString text, Augmentations augs) throws XNIException { boolean emptyAug = false; if (augs == null) { emptyAug = true; augs = fAugmentations; augs.clear(); } // get PSVI object fCurrentPSVI = (ElementPSVImpl)augs.getItem(Constants.ELEMENT_PSVI); if (fCurrentPSVI == null) { fCurrentPSVI = fElemPSVI; augs.putItem(Constants.ELEMENT_PSVI, fCurrentPSVI); } else { fCurrentPSVI.reset(); } handleCharacters(text); // call handlers if (fDocumentHandler != null) { if (fUnionType) { // for union types we can't normalize data // thus we only need to send augs information if any; // the normalized data for union will be send // after normalization is performed (at the endElement()) if (!emptyAug) { fDocumentHandler.characters(fEmptyXMLStr, augs); } } else { fDocumentHandler.characters(text, augs); } } } // characters(XMLString) /** * Ignorable whitespace. For this method to be called, the document * source must have some way of determining that the text containing * only whitespace characters should be considered ignorable. For * example, the validator can determine if a length of whitespace * characters in the document are ignorable based on the element * content model. * * @param text The ignorable whitespace. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void ignorableWhitespace(XMLString text, Augmentations augs) throws XNIException { handleIgnorableWhitespace(text); // call handlers if (fDocumentHandler != null) { fDocumentHandler.ignorableWhitespace(text, augs); } } // ignorableWhitespace(XMLString) /** * The end of an element. * * @param element The name of the element. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endElement(QName element, Augmentations augs) throws XNIException { // in the case where there is a {value constraint}, and the element // doesn't have any text content, add a characters call. Augmentations modifiedAugs = handleEndElement(element, augs); // call handlers if (fDocumentHandler != null) { if (fSchemaElementDefault || fDefaultValue == null) { fDocumentHandler.endElement(element, modifiedAugs); } else { fDocumentHandler.characters(fDefaultValue, modifiedAugs); fDocumentHandler.endElement(element, modifiedAugs); } } } // endElement(QName, Augmentations) /** * The end of a namespace prefix mapping. This method will only be * called when namespace processing is enabled. * * @param prefix The namespace prefix. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endPrefixMapping(String prefix, Augmentations augs) throws XNIException { if (DEBUG) { System.out.println("endPrefixMapping("+prefix+")"); } // call handlers if (fDocumentHandler != null) { fDocumentHandler.endPrefixMapping(prefix, augs); } } // endPrefixMapping(String) /** * The start of a CDATA section. * * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startCDATA(Augmentations augs) throws XNIException { // REVISIT: what should we do here if schema normalization is on?? fInCDATA = true; // call handlers if (fDocumentHandler != null) { fDocumentHandler.startCDATA(augs); } } // startCDATA() /** * The end of a CDATA section. * * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endCDATA(Augmentations augs) throws XNIException { // call handlers fInCDATA = false; if (fDocumentHandler != null) { fDocumentHandler.endCDATA(augs); } } // endCDATA() /** * The end of the document. * * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endDocument(Augmentations augs) throws XNIException { handleEndDocument(); // call handlers if (fDocumentHandler != null) { fDocumentHandler.endDocument(augs); } } // endDocument(Augmentations) // DOMRevalidationHandler methods public void setBaseURI (String base){ fBaseURI = base; } public boolean characterData(String data, Augmentations augs){ // REVISIT: this methods basically duplicates implementation of // handleCharacters(). We should be able to reuse some code boolean allWhiteSpace = true; String normalizedStr = null; if (augs == null) { augs = fAugmentations; augs.clear(); } // get PSVI object fCurrentPSVI = (ElementPSVImpl)augs.getItem(Constants.ELEMENT_PSVI); if (fCurrentPSVI == null) { fCurrentPSVI = fElemPSVI; augs.putItem(Constants.ELEMENT_PSVI, fCurrentPSVI); } else { fCurrentPSVI.reset(); } if (fNormalizeData && !fEntityRef && !fInCDATA) { // if whitespace == -1 skip normalization, because it is a complexType if (fWhiteSpace != -1 && fWhiteSpace != XSSimpleType.WS_PRESERVE) { // normalize data int spaces = normalizeWhitespace(data, fWhiteSpace == XSSimpleType.WS_COLLAPSE); normalizedStr = fNormalizedStr.toString(); fCurrentPSVI.fNormalizedValue = normalizedStr; } } boolean mixed = false; if (fCurrentType != null && fCurrentType.getTypeCategory() == XSTypeDecl.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType; if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) { mixed = true; } } if (DEBUG) { System.out.println("==>characters("+data+")," +fCurrentType.getName()+","+mixed); } if (mixed || fWhiteSpace !=-1 || fUnionType) { // don't check characters: since it is either // a) mixed content model - we don't care if there were some characters // b) simpleType/simpleContent - in which case it is data in ELEMENT content } else { // data outside of element content for (int i=0; i< data.length(); i++) { if (!XMLChar.isSpace(data.charAt(i))) { allWhiteSpace = false; break; } } } // we saw first chunk of characters fFirstChunk = false; // save normalized value for validation purposes if (fNil) { // if element was nil and there is some character data // we should expose it to the user // otherwise error does not make much sense fCurrentPSVI.fNormalizedValue = null; fBuffer.append(data); } if (normalizedStr != null) { fBuffer.append(normalizedStr); } else { fBuffer.append(data); } if (!allWhiteSpace) { fSawCharacters = true; } // call all active identity constraints // REVISIT -IC: we need a matcher.characters(String) int count = fMatcherStack.getMatcherCount(); XMLString text = null; if (count > 0) { //REVISIT-IC: Should we pass normalize data? int bufLen = data.length(); char [] chars = new char[bufLen]; data.getChars(0, bufLen, chars, 0); text = new XMLString(chars, 0, bufLen); } for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.characters(text); } return allWhiteSpace; } public void elementDefault(String data){ // no-op } // XMLDocumentHandler and XMLDTDHandler methods /** * This method notifies the start of a general entity. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param name The name of the general entity. * @param identifier The resource identifier. * @param encoding The auto-detected IANA encoding name of the entity * stream. This value will be null in those situations * where the entity encoding is not auto-detected (e.g. * internal entities or a document entity that is * parsed from a java.io.Reader). * @param augs Additional information that may include infoset augmentations * * @exception XNIException Thrown by handler to signal an error. */ public void startGeneralEntity(String name, XMLResourceIdentifier identifier, String encoding, Augmentations augs) throws XNIException { // REVISIT: what should happen if normalize_data_ is on?? fEntityRef = true; // call handlers if (fDocumentHandler != null) { fDocumentHandler.startGeneralEntity(name, identifier, encoding, augs); } } // startEntity(String,String,String,String,String) /** * Notifies of the presence of a TextDecl line in an entity. If present, * this method will be called immediately following the startEntity call. * <p> * <strong>Note:</strong> This method will never be called for the * document entity; it is only called for external general entities * referenced in document content. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param version The XML version, or null if not specified. * @param encoding The IANA encoding name of the entity. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void textDecl(String version, String encoding, Augmentations augs) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.textDecl(version, encoding, augs); } } // textDecl(String,String) /** * A comment. * * @param text The text in the comment. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by application to signal an error. */ public void comment(XMLString text, Augmentations augs) throws XNIException { // record the fact that there is a comment child. fSawChildren = true; // call handlers if (fDocumentHandler != null) { fDocumentHandler.comment(text, augs); } } // comment(XMLString) /** * A processing instruction. Processing instructions consist of a * target name and, optionally, text data. The data is only meaningful * to the application. * <p> * Typically, a processing instruction's data will contain a series * of pseudo-attributes. These pseudo-attributes follow the form of * element attributes but are <strong>not</strong> parsed or presented * to the application as anything other than text. The application is * responsible for parsing the data. * * @param target The target. * @param data The data or null if none specified. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void processingInstruction(String target, XMLString data, Augmentations augs) throws XNIException { // record the fact that there is a PI child. fSawChildren = true; // call handlers if (fDocumentHandler != null) { fDocumentHandler.processingInstruction(target, data, augs); } } // processingInstruction(String,XMLString) /** * This method notifies the end of a general entity. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param name The name of the entity. * @param augs Additional information that may include infoset augmentations * * @exception XNIException * Thrown by handler to signal an error. */ public void endGeneralEntity(String name, Augmentations augs) throws XNIException { // call handlers fEntityRef = false; if (fDocumentHandler != null) { fDocumentHandler.endGeneralEntity(name, augs); } } // endEntity(String) // constants static final int INITIAL_STACK_SIZE = 8; static final int INC_STACK_SIZE = 8; // some constants that'll be added into the symbol table String XMLNS; String URI_XSI; String XSI_SCHEMALOCATION; String XSI_NONAMESPACESCHEMALOCATION; String XSI_TYPE; String XSI_NIL; String URI_SCHEMAFORSCHEMA; // Data // Schema Normalization private static final boolean DEBUG_NORMALIZATION = false; // temporary empty string buffer. private final XMLString fEmptyXMLStr = new XMLString(null, 0, -1); // temporary character buffer, and empty string buffer. private static final int BUFFER_SIZE = 20; private char[] fCharBuffer = new char[BUFFER_SIZE]; private final StringBuffer fNormalizedStr = new StringBuffer(); private final XMLString fXMLString = new XMLString(fCharBuffer, 0, -1); private boolean fFirstChunk = true; // got first chunk in characters() (SAX) private boolean fTrailing = false; // Previous chunk had a trailing space private short fWhiteSpace = -1; //whiteSpace: preserve/replace/collapse private boolean fUnionType = false; /** Schema grammar resolver. */ final XSGrammarBucket fGrammarBucket; final SubstitutionGroupHandler fSubGroupHandler; // Schema grammar loader final XMLSchemaLoader fSchemaLoader; /** Namespace support. */ final NamespaceSupport fNamespaceSupport = new NamespaceSupport(); /** this flag is used to indicate whether the next prefix binding * should start a new context (.pushContext) */ boolean fPushForNextBinding; /** the DV usd to convert xsi:type to a QName */ // REVISIT: in new simple type design, make things in DVs static, // so that we can QNameDV.getCompiledForm() final XSSimpleType fQNameDV = (XSSimpleType)SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_QNAME); /** used to build content models */ // REVISIT: create decl pool, and pass it to each traversers final CMBuilder fCMBuilder = new CMBuilder(); // state /** String representation of the validation root. */ // REVISIT: what do we store here? QName, XPATH, some ID? use rawname now. String fValidationRoot; /** Skip validation. */ int fSkipValidationDepth; /** Partial validation depth */ int fPartialValidationDepth; /** Element depth. */ int fElementDepth; /** Child count. */ int fChildCount; /** Element decl stack. */ int[] fChildCountStack = new int[INITIAL_STACK_SIZE]; /** Current element declaration. */ XSElementDecl fCurrentElemDecl; /** Element decl stack. */ XSElementDecl[] fElemDeclStack = new XSElementDecl[INITIAL_STACK_SIZE]; /** nil value of the current element */ boolean fNil; /** nil value stack */ boolean[] fNilStack = new boolean[INITIAL_STACK_SIZE]; /** Current type. */ XSTypeDecl fCurrentType; /** type stack. */ XSTypeDecl[] fTypeStack = new XSTypeDecl[INITIAL_STACK_SIZE]; /** Current content model. */ XSCMValidator fCurrentCM; /** Content model stack. */ XSCMValidator[] fCMStack = new XSCMValidator[INITIAL_STACK_SIZE]; /** the current state of the current content model */ int[] fCurrCMState; /** stack to hold content model states */ int[][] fCMStateStack = new int[INITIAL_STACK_SIZE][]; /** Temporary string buffers. */ final StringBuffer fBuffer = new StringBuffer(); /** Did we see non-whitespace character data? */ boolean fSawCharacters = false; /** Stack to record if we saw character data outside of element content*/ boolean[] fStringContent = new boolean[INITIAL_STACK_SIZE]; /** Did we see children that are neither characters nor elements? */ boolean fSawChildren = false; /** Stack to record if we other children that character or elements */ boolean[] fSawChildrenStack = new boolean[INITIAL_STACK_SIZE]; /** temprory qname */ final QName fTempQName = new QName(); /** temprory validated info */ ValidatedInfo fValidatedInfo = new ValidatedInfo(); // used to validate default/fixed values against xsi:type // only need to check facets, so we set extraChecking to false (in reset) private ValidationState fState4XsiType = new ValidationState(); // used to apply default/fixed values // only need to check id/idref/entity, so we set checkFacets to false private ValidationState fState4ApplyDefault = new ValidationState(); // identity constraint information /** * Stack of active XPath matchers for identity constraints. All * active XPath matchers are notified of startElement, characters * and endElement callbacks in order to perform their matches. * <p> * For each element with identity constraints, the selector of * each identity constraint is activated. When the selector matches * its XPath, then all the fields of the identity constraint are * activated. * <p> * <strong>Note:</strong> Once the activation scope is left, the * XPath matchers are automatically removed from the stack of * active matchers and no longer receive callbacks. */ protected XPathMatcherStack fMatcherStack = new XPathMatcherStack(); /** Cache of value stores for identity constraint fields. */ protected ValueStoreCache fValueStoreCache = new ValueStoreCache(); // Constructors /** Default constructor. */ public XMLSchemaValidator() { fGrammarBucket = new XSGrammarBucket(); fSubGroupHandler = new SubstitutionGroupHandler(fGrammarBucket); // initialize the schema loader fSchemaLoader = new XMLSchemaLoader(fXSIErrorReporter.fErrorReporter, fGrammarBucket, fSubGroupHandler, fCMBuilder); } // <init>() /* * Resets the component. The component can query the component manager * about any features and properties that affect the operation of the * component. * * @param componentManager The component manager. * * @throws SAXException Thrown by component on finitialization error. * For example, if a feature or property is * required for the operation of the component, the * component manager may throw a * SAXNotRecognizedException or a * SAXNotSupportedException. */ public void reset(XMLComponentManager componentManager) throws XMLConfigurationException { // get error reporter fXSIErrorReporter.reset((XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER)); fSchemaLoader.setProperty(ERROR_REPORTER, fXSIErrorReporter.fErrorReporter); // get symbol table. if it's a new one, add symbols to it. SymbolTable symbolTable = (SymbolTable)componentManager.getProperty(SYMBOL_TABLE); if (symbolTable != fSymbolTable) { XMLNS = symbolTable.addSymbol(SchemaSymbols.O_XMLNS); URI_XSI = symbolTable.addSymbol(SchemaSymbols.URI_XSI); XSI_SCHEMALOCATION = symbolTable.addSymbol(SchemaSymbols.OXSI_SCHEMALOCATION); XSI_NONAMESPACESCHEMALOCATION = symbolTable.addSymbol(SchemaSymbols.OXSI_NONAMESPACESCHEMALOCATION); XSI_TYPE = symbolTable.addSymbol(SchemaSymbols.OXSI_TYPE); XSI_NIL = symbolTable.addSymbol(SchemaSymbols.OXSI_NIL); URI_SCHEMAFORSCHEMA = symbolTable.addSymbol(SchemaSymbols.OURI_SCHEMAFORSCHEMA); fSchemaLoader.setProperty(SYMBOL_TABLE, symbolTable); } fSymbolTable = symbolTable; // sax features try { fNamespaces = componentManager.getFeature(NAMESPACES); } catch (XMLConfigurationException e) { fNamespaces = true; } try { fValidation = componentManager.getFeature(VALIDATION); } catch (XMLConfigurationException e) { fValidation = false; } // Xerces features try { fValidation = fValidation && componentManager.getFeature(SCHEMA_VALIDATION); } catch (XMLConfigurationException e) { fValidation = false; } try { fFullChecking = componentManager.getFeature(SCHEMA_FULL_CHECKING); } catch (XMLConfigurationException e) { fFullChecking = false; } // the validator will do full checking anyway; the loader should // not (and in fact cannot) concern itself with this. fSchemaLoader.setFeature(SCHEMA_FULL_CHECKING, false); try { fDynamicValidation = componentManager.getFeature(DYNAMIC_VALIDATION); } catch (XMLConfigurationException e) { fDynamicValidation = false; } try { fNormalizeData = componentManager.getFeature(NORMALIZE_DATA); } catch (XMLConfigurationException e) { fNormalizeData = false; } try { fSchemaElementDefault = componentManager.getFeature(SCHEMA_ELEMENT_DEFAULT); } catch (XMLConfigurationException e) { fSchemaElementDefault = false; } fEntityResolver = (XMLEntityResolver)componentManager.getProperty(ENTITY_MANAGER); fSchemaLoader.setEntityResolver(fEntityResolver); // initialize namespace support fNamespaceSupport.reset(fSymbolTable); fPushForNextBinding = true; fValidationManager = (ValidationManager)componentManager.getProperty(VALIDATION_MANAGER); fValidationManager.addValidationState(fValidationState); fValidationState.setNamespaceSupport(fNamespaceSupport); fValidationState.setSymbolTable(fSymbolTable); // get schema location properties try { fExternalSchemas = (String)componentManager.getProperty(SCHEMA_LOCATION); fExternalNoNamespaceSchema = (String)componentManager.getProperty(SCHEMA_NONS_LOCATION); } catch (XMLConfigurationException e) { fExternalSchemas = null; fExternalNoNamespaceSchema = null; } fSchemaLoader.setProperty(SCHEMA_LOCATION, fExternalSchemas); fSchemaLoader.setProperty(SCHEMA_NONS_LOCATION, fExternalNoNamespaceSchema); try { fJaxpSchemaSource = componentManager.getProperty(JAXP_SCHEMA_SOURCE); } catch (XMLConfigurationException e){ fJaxpSchemaSource = null; } fSchemaLoader.setProperty(JAXP_SCHEMA_SOURCE, fJaxpSchemaSource); fResourceIdentifier.clear(); // clear grammars, and put the one for schema namespace there try { fGrammarPool = (XMLGrammarPool)componentManager.getProperty(XMLGRAMMAR_POOL); } catch (XMLConfigurationException e){ fGrammarPool = null; } fSchemaLoader.setProperty(XMLGRAMMAR_POOL, fGrammarPool); // clear grammars, and put the one for schema namespace there // logic for resetting grammar-related components moved // to schema loader fSchemaLoader.reset(); //reset XSDDescription fXSDDescription.reset() ; fLocationPairs.clear(); fNoNamespaceLocationArray.resize(0 , 2) ; // initialize state fCurrentElemDecl = null; fNil = false; fCurrentPSVI = null; fCurrentType = null; fCurrentCM = null; fCurrCMState = null; fBuffer.setLength(0); fSawCharacters=false; fSawChildren=false; fValidationRoot = null; fSkipValidationDepth = -1; fPartialValidationDepth = -1; fElementDepth = -1; fChildCount = 0; // datatype normalization fFirstChunk = true; fTrailing = false; fNormalizedStr.setLength(0); fWhiteSpace = -1; fUnionType = false; fWhiteSpace = -1; fAugmentations.clear(); fEntityRef = false; fInCDATA = false; fMatcherStack.clear(); fBaseURI = null; fValueStoreCache = new ValueStoreCache(); fState4XsiType.setExtraChecking(false); fState4XsiType.setSymbolTable(symbolTable); fState4XsiType.setSymbolTable(symbolTable); fState4XsiType.setNamespaceSupport(fNamespaceSupport); fState4ApplyDefault.setFacetChecking(false); fState4ApplyDefault.setSymbolTable(symbolTable); fState4ApplyDefault.setSymbolTable(symbolTable); fState4ApplyDefault.setNamespaceSupport(fNamespaceSupport); } // reset(XMLComponentManager) // FieldActivator methods /** * Start the value scope for the specified identity constraint. This * method is called when the selector matches in order to initialize * the value store. * * @param identityConstraint The identity constraint. */ public void startValueScopeFor(IdentityConstraint identityConstraint) throws XNIException { for (int i=0; i<identityConstraint.getFieldCount(); i++) { Field field = identityConstraint.getFieldAt(i); ValueStoreBase valueStore = fValueStoreCache.getValueStoreFor(field); valueStore.startValueScope(); } } // startValueScopeFor(IdentityConstraint identityConstraint) /** * Request to activate the specified field. This method returns the * matcher for the field. * * @param field The field to activate. */ public XPathMatcher activateField(Field field) throws XNIException { ValueStore valueStore = fValueStoreCache.getValueStoreFor(field); field.setMayMatch(true); XPathMatcher matcher = field.createMatcher(valueStore); fMatcherStack.addMatcher(matcher); matcher.startDocumentFragment(fSymbolTable); return matcher; } // activateField(Field):XPathMatcher /** * Ends the value scope for the specified identity constraint. * * @param identityConstraint The identity constraint. */ public void endValueScopeFor(IdentityConstraint identityConstraint) throws XNIException { ValueStoreBase valueStore = fValueStoreCache.getValueStoreFor(identityConstraint); valueStore.endValueScope(); } // endValueScopeFor(IdentityConstraint) // a utility method for Idnetity constraints private void activateSelectorFor(IdentityConstraint ic) throws XNIException { Selector selector = ic.getSelector(); FieldActivator activator = this; if (selector == null) return; XPathMatcher matcher = selector.createMatcher(activator); fMatcherStack.addMatcher(matcher); matcher.startDocumentFragment(fSymbolTable); } // Protected methods /** ensure element stack capacity */ void ensureStackCapacity() { if (fElementDepth == fElemDeclStack.length) { int newSize = fElementDepth + INC_STACK_SIZE; int[] newArrayI = new int[newSize]; System.arraycopy(fChildCountStack, 0, newArrayI, 0, fElementDepth); fChildCountStack = newArrayI; XSElementDecl[] newArrayE = new XSElementDecl[newSize]; System.arraycopy(fElemDeclStack, 0, newArrayE, 0, fElementDepth); fElemDeclStack = newArrayE; boolean[] newArrayB = new boolean[newSize]; System.arraycopy(fNilStack, 0, newArrayB, 0, fElementDepth); fNilStack = newArrayB; XSTypeDecl[] newArrayT = new XSTypeDecl[newSize]; System.arraycopy(fTypeStack, 0, newArrayT, 0, fElementDepth); fTypeStack = newArrayT; XSCMValidator[] newArrayC = new XSCMValidator[newSize]; System.arraycopy(fCMStack, 0, newArrayC, 0, fElementDepth); fCMStack = newArrayC; boolean[] newArrayD = new boolean[newSize]; System.arraycopy(fStringContent, 0, newArrayD, 0, fElementDepth); fStringContent = newArrayD; newArrayD = new boolean[newSize]; System.arraycopy(fSawChildrenStack, 0, newArrayD, 0, fElementDepth); fSawChildrenStack = newArrayD; int[][] newArrayIA = new int[newSize][]; System.arraycopy(fCMStateStack, 0, newArrayIA, 0, fElementDepth); fCMStateStack = newArrayIA; } } // ensureStackCapacity // handle start document void handleStartDocument(XMLLocator locator, String encoding) { if (fValidation) fValueStoreCache.startDocument(); } // handleStartDocument(XMLLocator,String) void handleEndDocument() { if (fValidation) fValueStoreCache.endDocument(); } // handleEndDocument() // handle character contents void handleCharacters(XMLString text) { fCurrentPSVI.fNormalizedValue = null; if (fSkipValidationDepth >= 0) return; String normalizedStr = null; boolean allWhiteSpace = true; // find out if type is union, what is whitespace, // determine if there is a need to do normalization if (fNormalizeData && !fEntityRef && !fInCDATA) { // if whitespace == -1 skip normalization, because it is a complexType if (fWhiteSpace != -1 && !fUnionType && fWhiteSpace != XSSimpleType.WS_PRESERVE) { // normalize data int spaces = normalizeWhitespace(text, fWhiteSpace == XSSimpleType.WS_COLLAPSE); int length = fNormalizedStr.length(); if (length > 0) { if (!fFirstChunk && (fWhiteSpace==XSSimpleType.WS_COLLAPSE) ) { if (fTrailing) { // previous chunk ended on whitespace // insert whitespace fNormalizedStr.insert(0, ' '); } else if (spaces == 1 || spaces == 3) { // previous chunk ended on character, // this chunk starts with whitespace fNormalizedStr.insert(0, ' '); } } } normalizedStr = fNormalizedStr.toString(); fCurrentPSVI.fNormalizedValue = normalizedStr; fTrailing = (spaces > 1)?true:false; } } boolean mixed = false; if (fCurrentType != null && fCurrentType.getTypeCategory() == XSTypeDecl.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType; if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) { mixed = true; } } if (DEBUG) { System.out.println("==>characters("+text.toString()+")," +fCurrentType.getName()+","+mixed); } if (mixed || fWhiteSpace !=-1 || fUnionType) { // don't check characters: since it is either // a) mixed content model - we don't care if there were some characters // b) simpleType/simpleContent - in which case it is data in ELEMENT content } else { // data outside of element content for (int i=text.offset; i< text.offset+text.length; i++) { if (!XMLChar.isSpace(text.ch[i])) { allWhiteSpace = false; break; } } } // we saw first chunk of characters fFirstChunk = false; // save normalized value for validation purposes if (fNil) { // if element was nil and there is some character data // we should expose it to the user // otherwise error does not make much sense fCurrentPSVI.fNormalizedValue = null; fBuffer.append(text.ch, text.offset, text.length); } if (normalizedStr != null) { fBuffer.append(normalizedStr); } else { fBuffer.append(text.ch, text.offset, text.length); } if (!allWhiteSpace) { fSawCharacters = true; } // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.characters(text); } } // handleCharacters(XMLString) /** * Normalize whitespace in an XMLString according to the rules defined * in XML Schema specifications. * @param value The string to normalize. * @param collapse replace or collapse * @returns 0 if no triming is done or if there is neither leading nor * trailing whitespace, * 1 if there is only leading whitespace, * 2 if there is only trailing whitespace, * 3 if there is both leading and trailing whitespace. */ private int normalizeWhitespace( XMLString value, boolean collapse) { boolean skipSpace = collapse; boolean sawNonWS = false; int leading = 0; int trailing = 0; int c; int size = value.offset+value.length; fNormalizedStr.setLength(0); for (int i = value.offset; i < size; i++) { c = value.ch[i]; if (c == 0x20 || c == 0x0D || c == 0x0A || c == 0x09) { if (!skipSpace) { // take the first whitespace as a space and skip the others fNormalizedStr.append(' '); skipSpace = collapse; } if (!sawNonWS) { // this is a leading whitespace, record it leading = 1; } } else { fNormalizedStr.append((char)c); skipSpace = false; sawNonWS = true; } } if (skipSpace) { c = fNormalizedStr.length(); if ( c != 0) { // if we finished on a space trim it but also record it fNormalizedStr.setLength (--c); trailing = 2; } else if (leading != 0 && !sawNonWS) { // if all we had was whitespace we skipped record it as // trailing whitespace as well trailing = 2; } } return collapse ? leading + trailing : 0; } private int normalizeWhitespace( String value, boolean collapse) { boolean skipSpace = collapse; boolean sawNonWS = false; int leading = 0; int trailing = 0; int c; int size = value.length(); fNormalizedStr.setLength(0); for (int i = 0; i < size; i++) { c = value.charAt(i); if (c == 0x20 || c == 0x0D || c == 0x0A || c == 0x09) { if (!skipSpace) { // take the first whitespace as a space and skip the others fNormalizedStr.append(' '); skipSpace = collapse; } if (!sawNonWS) { // this is a leading whitespace, record it leading = 1; } } else { fNormalizedStr.append((char)c); skipSpace = false; sawNonWS = true; } } if (skipSpace) { c = fNormalizedStr.length(); if ( c != 0) { // if we finished on a space trim it but also record it fNormalizedStr.setLength (--c); trailing = 2; } else if (leading != 0 && !sawNonWS) { // if all we had was whitespace we skipped record it as // trailing whitespace as well trailing = 2; } } return collapse ? leading + trailing : 0; } // handle ignorable whitespace void handleIgnorableWhitespace(XMLString text) { if (fSkipValidationDepth >= 0) return; // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.characters(text); } } // handleIgnorableWhitespace(XMLString) /** Handle element. */ Augmentations handleStartElement(QName element, XMLAttributes attributes, Augmentations augs) { if (DEBUG) { System.out.println("==>handleStartElement: " +element); } // should really determine whether a null augmentation is to // be returned on a case-by-case basis, rather than assuming // this method will always produce augmentations... if(augs == null) { augs = fAugmentations; augs.clear(); } // we receive prefix binding events before this one, // so at this point, the prefix bindings for this element is done, // and we need to push context when we receive another prefix binding. // but if fPushForNextBinding is still true, that means there has // been no prefix binding for this element. we still need to push // context, because the context is always popped in end element. if (fPushForNextBinding) fNamespaceSupport.pushContext(); else fPushForNextBinding = true; // root element if (fElementDepth == -1) { // at this point we assume that no XML schemas found in the instance document // thus we will not validate in the case dynamic feature is on or we found dtd grammar fDoValidation = fValidation && !(fValidationManager.isGrammarFound() || fDynamicValidation); //store the external schema locations, these locations will be set at root element, so any other // schemaLocation declaration for the same namespace will be effectively ignored.. becuase we // choose to take first location hint available for a particular namespace. storeLocations(fExternalSchemas, fExternalNoNamespaceSchema) ; } fCurrentPSVI = (ElementPSVImpl)augs.getItem(Constants.ELEMENT_PSVI); if (fCurrentPSVI == null) { fCurrentPSVI = fElemPSVI; augs.putItem(Constants.ELEMENT_PSVI, fCurrentPSVI); } fCurrentPSVI.reset(); // get xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes, // parse them to get the grammars String sLocation = attributes.getValue(URI_XSI, XSI_SCHEMALOCATION); String nsLocation = attributes.getValue(URI_XSI, XSI_NONAMESPACESCHEMALOCATION); //store the location hints.. we need to do it so that we can defer the loading of grammar until //there is a reference to a component from that namespace. To provide location hints to the //application for a namespace storeLocations(sLocation, nsLocation) ; //REVISIT: We should do the same in XSDHandler also... we should not //load the actual grammar (eg. import) unless there is reference to it. // REVISIT: we should not rely on presence of // schemaLocation or noNamespaceSchemaLocation // attributes if (sLocation !=null || nsLocation !=null) { // if we found grammar we should attempt to validate // based on values of validation & schema features // only fDoValidation = fValidation; } // update normalization flags if (fNormalizeData) { // reset values fFirstChunk = true; fUnionType = false; fWhiteSpace = -1; } // if we are in the content of "skip", then just skip this element // REVISIT: is this the correct behaviour for ID constraints? -NG if (fSkipValidationDepth >= 0) { fElementDepth++; return augs; } // if we are not skipping this element, and there is a content model, // we try to find the corresponding decl object for this element. // the reason we move this part of code here is to make sure the // error reported here (if any) is stored within the parent element's // context, instead of that of the current element. Object decl = null; if (fSkipValidationDepth < 0 && fCurrentCM != null) { decl = fCurrentCM.oneTransition(element, fCurrCMState, fSubGroupHandler); // it could be an element decl or a wildcard decl if (fCurrCMState[0] == XSCMValidator.FIRST_ERROR && fDoValidation) { XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType; //REVISIT: is it the only case we will have particle = null? if (ctype.fParticle != null) { reportSchemaError("cvc-complex-type.2.4.a", new Object[]{element.rawname, ctype.fParticle.toString()}); } else { reportSchemaError("cvc-complex-type.2.4.a", new Object[]{element.rawname, "mixed with no element content"}); } } } // push error reporter context: record the current position fXSIErrorReporter.pushContext(); // if it's not the root element, we push the current states in the stacks if (fElementDepth != -1) { ensureStackCapacity(); fChildCountStack[fElementDepth] = fChildCount+1; fChildCount = 0; fElemDeclStack[fElementDepth] = fCurrentElemDecl; fNilStack[fElementDepth] = fNil; fTypeStack[fElementDepth] = fCurrentType; fCMStack[fElementDepth] = fCurrentCM; fCMStateStack[fElementDepth] = fCurrCMState; fStringContent[fElementDepth] = fSawCharacters; fSawChildrenStack[fElementDepth] = fSawChildren; } // increase the element depth after we've saved // all states for the parent element fElementDepth++; fCurrentElemDecl = null; XSWildcardDecl wildcard = null; fCurrentType = null; fNil = false; // and the buffer to hold the value of the element fBuffer.setLength(0); fSawCharacters = false; fSawChildren = false; // check what kind of declaration the "decl" from // oneTransition() maps to if (decl != null) { if (decl instanceof XSElementDecl) { fCurrentElemDecl = (XSElementDecl)decl; } else { wildcard = (XSWildcardDecl)decl; } } // if the wildcard is skip, then return if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_SKIP) { fSkipValidationDepth = fElementDepth; return augs; } // try again to get the element decl: // case 1: find declaration for root element // case 2: find declaration for element from another namespace if (fCurrentElemDecl == null) { //try to find schema grammar by different means.. SchemaGrammar sGrammar = findSchemaGrammar(XSDDescription.CONTEXT_ELEMENT , element.uri , null , element, attributes ) ; if (sGrammar != null){ fCurrentElemDecl = sGrammar.getGlobalElementDecl(element.localpart); } } // Element Locally Valid (Element) // 2 Its {abstract} must be false. if (fCurrentElemDecl != null && fCurrentElemDecl.getIsAbstract()) reportSchemaError("cvc-elt.2", new Object[]{element.rawname}); if (fCurrentElemDecl != null) { // then get the type fCurrentType = fCurrentElemDecl.fType; } // get type from xsi:type String xsiType = attributes.getValue(URI_XSI, XSI_TYPE); if (xsiType != null) fCurrentType = getAndCheckXsiType(element, xsiType, attributes); // if the element decl is not found if (fCurrentType == null) { if (fDoValidation) { // if this is the validation root, report an error, because // we can't find eith decl or type for this element // REVISIT: should we report error, or warning? if (fElementDepth == 0) { // report error, because it's root element reportSchemaError("cvc-elt.1", new Object[]{element.rawname}); } // if wildcard = strict, report error else if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_STRICT) { // report error, because wilcard = strict reportSchemaError("cvc-complex-type.2.4.c", new Object[]{element.rawname}); } } // no element decl or type found for this element. // Allowed by the spec, we can choose to either laxly assess this // element, or to skip it. Now we choose lax assessment. // REVISIT: IMO, we should perform lax assessment when validation // feature is on, and skip when dynamic validation feature is on. fCurrentType = SchemaGrammar.fAnyType; } // make the current element validation root if (fElementDepth == 0) { fValidationRoot = element.rawname; } // PSVI: add validation context fCurrentPSVI.fValidationContext = fValidationRoot; // PSVI: add element declaration fCurrentPSVI.fDeclaration = fCurrentElemDecl; // PSVI: add element type fCurrentPSVI.fTypeDecl = fCurrentType; // Element Locally Valid (Type) // 2 Its {abstract} must be false. if (fCurrentType.getTypeCategory() == XSTypeDecl.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType; if (ctype.getIsAbstract()) { reportSchemaError("cvc-type.2", new Object[]{"Element " + element.rawname + " is declared with a type that is abstract. Use xsi:type to specify a non-abstract type"}); } if (fNormalizeData) { // find out if the content type is simple and if variety is union // to be able to do character normalization if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (ctype.fXSSimpleType.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = ctype.fXSSimpleType.getWhitespace(); } catch (DatatypeException e){ // do nothing } } } } } // normalization if (fNormalizeData && fCurrentType.getTypeCategory() == XSTypeDecl.SIMPLE_TYPE) { // if !union type XSSimpleType dv = (XSSimpleType)fCurrentType; if (dv.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = dv.getWhitespace(); } catch (DatatypeException e){ // do nothing } } } // then try to get the content model fCurrentCM = null; if (fCurrentType.getTypeCategory() == XSTypeDecl.COMPLEX_TYPE) { fCurrentCM = ((XSComplexTypeDecl)fCurrentType).getContentModel(fCMBuilder); } // and get the initial content model state fCurrCMState = null; if (fCurrentCM != null) fCurrCMState = fCurrentCM.startContentModel(); // get information about xsi:nil String xsiNil = attributes.getValue(URI_XSI, XSI_NIL); // only deal with xsi:nil when there is an element declaration if (xsiNil != null && fCurrentElemDecl != null) fNil = getXsiNil(element, xsiNil); // now validate everything related with the attributes // first, get the attribute group XSAttributeGroupDecl attrGrp = null; if (fCurrentType.getTypeCategory() == XSTypeDecl.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType; attrGrp = ctype.fAttrGrp; } processAttributes(element, attributes, attrGrp); // activate identity constraints if (fDoValidation) { fValueStoreCache.startElement(); fMatcherStack.pushContext(); if (fCurrentElemDecl != null) { fValueStoreCache.initValueStoresFor(fCurrentElemDecl); int icCount = fCurrentElemDecl.fIDCPos; int uniqueOrKey = 0; for (;uniqueOrKey < icCount; uniqueOrKey++) { if (fCurrentElemDecl.fIDConstraints[uniqueOrKey].getCategory() != IdentityConstraint.IC_KEYREF) { activateSelectorFor(fCurrentElemDecl.fIDConstraints[uniqueOrKey]); } else break; } for (int keyref = uniqueOrKey; keyref < icCount; keyref++) { activateSelectorFor((IdentityConstraint)fCurrentElemDecl.fIDConstraints[keyref]); } } // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.startElement(element, attributes, fCurrentElemDecl); } } return augs; } // handleStartElement(QName,XMLAttributes,boolean) /** * Handle end element. If there is not text content, and there is a * {value constraint} on the corresponding element decl, then * set the fDefaultValue XMLString representing the default value. */ Augmentations handleEndElement(QName element, Augmentations augs) { if (DEBUG) { System.out.println("==>handleEndElement:" +element); } if(augs == null) { // again, always assume adding augmentations... augs = fAugmentations; augs.clear(); } fCurrentPSVI = (ElementPSVImpl)augs.getItem(Constants.ELEMENT_PSVI); if (fCurrentPSVI == null) { fCurrentPSVI = fElemPSVI; augs.putItem(Constants.ELEMENT_PSVI, fCurrentPSVI); } fCurrentPSVI.reset(); // if we are skipping, return if (fSkipValidationDepth >= 0) { // but if this is the top element that we are skipping, // restore the states. if (fSkipValidationDepth == fElementDepth && fSkipValidationDepth > 0) { // set the partial validation depth to the depth of parent fPartialValidationDepth = fSkipValidationDepth-1; fSkipValidationDepth = -1; fElementDepth fChildCount = fChildCountStack[fElementDepth]; fCurrentElemDecl = fElemDeclStack[fElementDepth]; fNil = fNilStack[fElementDepth]; fCurrentType = fTypeStack[fElementDepth]; fCurrentCM = fCMStack[fElementDepth]; fCurrCMState = fCMStateStack[fElementDepth]; fSawCharacters = fStringContent[fElementDepth]; fSawChildren = fSawChildrenStack[fElementDepth]; } else { fElementDepth } // need to pop context so that the bindings for this element is // discarded. fNamespaceSupport.popContext(); // pop error reporter context: get all errors for the current // element, and remove them from the error list // String[] errors = fXSIErrorReporter.popContext(); // PSVI: validation attempted: // use default values in psvi item for // validation attempted, validity, and error codes // check extra schema constraints on root element if (fElementDepth == -1 && fDoValidation && fFullChecking) { XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fXSIErrorReporter.fErrorReporter); } fDefaultValue = null; return augs; } // now validate the content of the element XMLString defaultValue = processElementContent(element); // Element Locally Valid (Element) // 6 The element information item must be valid with respect to each of the {identity-constraint definitions} as per Identity-constraint Satisfied (3.11.4). // call matchers and de-activate context int oldCount = fMatcherStack.getMatcherCount(); for (int i = oldCount - 1; i >= 0; i XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.endElement(element, fCurrentElemDecl); } if (fMatcherStack.size() > 0) { fMatcherStack.popContext(); } int newCount = fMatcherStack.getMatcherCount(); // handle everything *but* keyref's. for (int i = oldCount - 1; i >= newCount; i XPathMatcher matcher = fMatcherStack.getMatcherAt(i); IdentityConstraint id; if ((id = matcher.getIDConstraint()) != null && id.getCategory() != IdentityConstraint.IC_KEYREF) { matcher.endDocumentFragment(); fValueStoreCache.transplant(id); } else if (id == null) matcher.endDocumentFragment(); } // now handle keyref's/... for (int i = oldCount - 1; i >= newCount; i XPathMatcher matcher = fMatcherStack.getMatcherAt(i); IdentityConstraint id; if ((id = matcher.getIDConstraint()) != null && id.getCategory() == IdentityConstraint.IC_KEYREF) { ValueStoreBase values = fValueStoreCache.getValueStoreFor(id); if (values != null) // nothing to do if nothing matched! values.endDocumentFragment(); matcher.endDocumentFragment(); } } fValueStoreCache.endElement(); // PSVI: validation attempted if (fElementDepth <= fPartialValidationDepth) { // the element had child with a content skip. fCurrentPSVI.fValidationAttempted = ElementPSVI.VALIDATION_PARTIAL; if (fElementDepth == fPartialValidationDepth) { // set depth to the depth of the parent fPartialValidationDepth } } else { fCurrentPSVI.fValidationAttempted = ElementPSVI.VALIDATION_FULL; } // decrease element depth and restore states fElementDepth // have we reached the end tag of the validation root? if (fElementDepth == -1) { if (fDoValidation) { // 7 If the element information item is the validation root, it must be valid per Validation Root Valid (ID/IDREF) (3.3.4). String invIdRef = fValidationState.checkIDRefID(); if (invIdRef != null) { reportSchemaError("cvc-id.1", new Object[]{invIdRef}); } // check extra schema constraints if (fFullChecking) { XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fXSIErrorReporter.fErrorReporter); } } fValidationState.resetIDTables(); SchemaGrammar[] grammars = fGrammarBucket.getGrammars(); // return the final set of grammars validator ended up with if (fGrammarPool != null) { fGrammarPool.cacheGrammars(XMLGrammarDescription.XML_SCHEMA, grammars); } // store [schema information] in the PSVI fCurrentPSVI.fSchemaInformation = new XSModelImpl(grammars); } else { // get the states for the parent element. fChildCount = fChildCountStack[fElementDepth]; fCurrentElemDecl = fElemDeclStack[fElementDepth]; fNil = fNilStack[fElementDepth]; fCurrentType = fTypeStack[fElementDepth]; fCurrentCM = fCMStack[fElementDepth]; fCurrCMState = fCMStateStack[fElementDepth]; fSawCharacters = fStringContent[fElementDepth]; fSawChildren = fSawChildrenStack[fElementDepth]; } // need to pop context so that the bindings for this element is // discarded. fNamespaceSupport.popContext(); // pop error reporter context: get all errors for the current // element, and remove them from the error list String[] errors = fXSIErrorReporter.popContext(); // PSVI: error codes fCurrentPSVI.fErrorCodes = errors; // PSVI: validity fCurrentPSVI.fValidity = (errors == null) ? ElementPSVI.VALIDITY_VALID : ElementPSVI.VALIDITY_INVALID; fDefaultValue = defaultValue; // reset normalization values if (fNormalizeData) { fTrailing = false; fUnionType = false; fWhiteSpace = -1; } return augs; } // handleEndElement(QName,boolean)*/ void handleStartPrefix(String prefix, String uri) { // push namespace context if necessary if (fPushForNextBinding) { fNamespaceSupport.pushContext(); fPushForNextBinding = false; } // add prefix declaration to the namespace support fNamespaceSupport.declarePrefix(prefix, uri.length() != 0 ? uri : null); } void storeLocations(String sLocation, String nsLocation){ if (sLocation != null) { if(!XMLSchemaLoader.tokenizeSchemaLocationStr(sLocation, fLocationPairs)) { // error! fXSIErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, "SchemaLocation", new Object[]{sLocation}, XMLErrorReporter.SEVERITY_WARNING); } } if (nsLocation != null) { fNoNamespaceLocationArray.addLocation(nsLocation); fLocationPairs.put(XMLSchemaLoader.EMPTY_STRING, fNoNamespaceLocationArray); } }//storeLocations //this is the function where logic of retrieving grammar is written , parser first tries to get the grammar from //the local pool, if not in local pool, it gives chance to application to be able to retrieve the grammar, then it //tries to parse the grammar using location hints from the give namespace. SchemaGrammar findSchemaGrammar(short contextType , String namespace , QName enclosingElement, QName triggeringComponet, XMLAttributes attributes ){ SchemaGrammar grammar = null ; //get the grammar from local pool... grammar = fGrammarBucket.getGrammar(namespace); if (grammar == null){ fXSDDescription.reset(); fXSDDescription.fContextType = contextType ; fXSDDescription.fTargetNamespace = namespace ; fXSDDescription.fEnclosedElementName = enclosingElement ; fXSDDescription.fTriggeringComponent = triggeringComponet ; fXSDDescription.fAttributes = attributes ; if (fBaseURI != null) { fXSDDescription.setBaseSystemId(fBaseURI); } String[] temp = null ; if( namespace != null){ Object locationArray = fLocationPairs.get(namespace) ; if(locationArray != null) temp = ((XMLSchemaLoader.LocationArray)locationArray).getLocationArray() ; }else{ temp = fNoNamespaceLocationArray.getLocationArray() ; } if (temp != null && temp.length != 0) { fXSDDescription.fLocationHints = new String [temp.length] ; System.arraycopy(temp, 0 , fXSDDescription.fLocationHints, 0, temp.length ); } // give a chance to application to be able to retreive the grammar. if (fGrammarPool != null){ grammar = (SchemaGrammar)fGrammarPool.retrieveGrammar(fXSDDescription); if (grammar != null) { // put this grammar into the bucket, along with grammars // imported by it (directly or indirectly) if (!fGrammarBucket.putGrammar(grammar, true)) { // REVISIT: a conflict between new grammar(s) and grammars // in the bucket. What to do? A warning? An exception? fXSIErrorReporter.fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, "GrammarConflict", null, XMLErrorReporter.SEVERITY_WARNING); grammar = null; } } } if (grammar == null) { // try to parse the grammar using location hints from that namespace.. fLocationPairs.put("", fNoNamespaceLocationArray); try { XMLInputSource xis = XMLSchemaLoader.resolveDocument(fXSDDescription, fLocationPairs, fEntityResolver); grammar = fSchemaLoader.loadSchema(fXSDDescription, xis, fLocationPairs); } catch (IOException ex) { fXSIErrorReporter.fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, "schema_reference.4", new Object[]{fXSDDescription.getLocationHints()[0]}, XMLErrorReporter.SEVERITY_WARNING); } } } return grammar ; }//findSchemaGrammar XSTypeDecl getAndCheckXsiType(QName element, String xsiType, XMLAttributes attributes) { // This method also deals with clause 1.2.1.2 of the constraint // Validation Rule: Schema-Validity Assessment (Element) // Element Locally Valid (Element) // 4.1 The normalized value of that attribute information item must be valid with respect to the built-in QName simple type, as defined by String Valid (3.14.4); QName typeName = null; try { typeName = (QName)fQNameDV.validate(xsiType, fValidationState, null); } catch (InvalidDatatypeValueException e) { reportSchemaError(e.getKey(), e.getArgs()); reportSchemaError("cvc-elt.4.1", new Object[]{element.rawname, URI_XSI+","+XSI_TYPE, xsiType}); return null; } // 4.2 The local name and namespace name (as defined in QName Interpretation (3.15.3)), of the actual value of that attribute information item must resolve to a type definition, as defined in QName resolution (Instance) (3.15.4) XSTypeDecl type = null; // if the namespace is schema namespace, first try built-in types if (typeName.uri == URI_SCHEMAFORSCHEMA) { type = SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(typeName.localpart); } // if it's not schema built-in types, then try to get a grammar if (type == null) { //try to find schema grammar by different means.... SchemaGrammar grammar = findSchemaGrammar( XSDDescription.CONTEXT_XSITYPE , typeName.uri , element , typeName , attributes); if (grammar != null) type = grammar.getGlobalTypeDecl(typeName.localpart); } // still couldn't find the type, report an error if (type == null) { reportSchemaError("cvc-elt.4.2", new Object[]{element.rawname, xsiType}); return null; } // if there is no current type, set this one as current. // and we don't need to do extra checking if (fCurrentType != null) { // 4.3 The local type definition must be validly derived from the {type definition} given the union of the {disallowed substitutions} and the {type definition}'s {prohibited substitutions}, as defined in Type Derivation OK (Complex) (3.4.6) (if it is a complex type definition), or given {disallowed substitutions} as defined in Type Derivation OK (Simple) (3.14.6) (if it is a simple type definition). short block = fCurrentElemDecl.fBlock; if (fCurrentType.getTypeCategory() == XSTypeDecl.COMPLEX_TYPE) block |= ((XSComplexTypeDecl)fCurrentType).fBlock; if (!XSConstraints.checkTypeDerivationOk(type, fCurrentType, block)) reportSchemaError("cvc-elt.4.3", new Object[]{element.rawname, xsiType}); } return type; }//getAndCheckXsiType boolean getXsiNil(QName element, String xsiNil) { // Element Locally Valid (Element) // 3 The appropriate case among the following must be true: if (fCurrentElemDecl != null && !fCurrentElemDecl.getIsNillable()) { reportSchemaError("cvc-elt.3.1", new Object[]{element.rawname, URI_XSI+","+XSI_NIL}); } // 3.2 If {nillable} is true and there is such an attribute information item and its actual value is true , then all of the following must be true: // 3.2.2 There must be no fixed {value constraint}. else { String value = xsiNil.trim(); if (value.equals(SchemaSymbols.ATTVAL_TRUE) || value.equals(SchemaSymbols.ATTVAL_TRUE_1)) { if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED) { reportSchemaError("cvc-elt.3.2.2", new Object[]{element.rawname, URI_XSI+","+XSI_NIL}); } return true; } } return false; } void processAttributes(QName element, XMLAttributes attributes, XSAttributeGroupDecl attrGrp) { // REVISIT: should we assume that XMLAttributeImpl removes // all augmentations from Augmentations? if yes.. we loose objects // if no - we always produce attribute psvi objects which may not be filled in // in this case we need to create/reset here all objects Augmentations augs = null; AttributePSVImpl attrPSVI = null; if (DEBUG) { System.out.println("==>processAttributes: " +attributes.getLength()); } for (int k=0;k<attributes.getLength();k++) { augs = attributes.getAugmentations(k); attrPSVI = (AttributePSVImpl) augs.getItem(Constants.ATTRIBUTE_PSVI); if (attrPSVI != null) { attrPSVI.reset(); } else { attrPSVI= new AttributePSVImpl(); augs.putItem(Constants.ATTRIBUTE_PSVI, attrPSVI); } // PSVI attribute: validation context attrPSVI.fValidationContext = fValidationRoot; } // add default attributes if (attrGrp != null) { addDefaultAttributes(element, attributes, attrGrp); } // if we don't do validation, we don't need to validate the attributes if (!fDoValidation || attributes.getLength() == 0){ // PSVI: validity is unknown, and validation attempted is none // this is a default value thus we should not set anything else here. return; } // Element Locally Valid (Type) // 3.1.1 The element information item's [attributes] must be empty, excepting those // whose [local name] is one of type, nil, schemaLocation or noNamespaceSchemaLocation. if (fCurrentType == null || fCurrentType.getTypeCategory() == XSTypeDecl.SIMPLE_TYPE) { int attCount = attributes.getLength(); for (int index = 0; index < attCount; index++) { if (DEBUG) { System.out.println("==>process attribute: "+fTempQName); } attributes.getName(index, fTempQName); // get attribute PSVI attrPSVI = (AttributePSVImpl)attributes.getAugmentations(index).getItem(Constants.ATTRIBUTE_PSVI); // for the 4 xsi attributes, get appropriate decl, and validate if (fTempQName.uri == URI_XSI) { XSAttributeDecl attrDecl = null; if (fTempQName.localpart == XSI_SCHEMALOCATION) attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(XSI_SCHEMALOCATION); else if (fTempQName.localpart == XSI_NONAMESPACESCHEMALOCATION) attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(XSI_NONAMESPACESCHEMALOCATION); else if (fTempQName.localpart == XSI_NIL) attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(XSI_NIL); else if (fTempQName.localpart == XSI_TYPE) attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(XSI_TYPE); if (attrDecl != null) { processOneAttribute(element, attributes.getValue(index), attrDecl, null, attrPSVI); continue; } } // for all other attributes, no_validation/unknow_validity if (fTempQName.rawname != XMLNS && !fTempQName.rawname.startsWith("xmlns:")) { reportSchemaError("cvc-type.3.1.1", new Object[]{element.rawname}); } } return; } XSObjectList attrUses = attrGrp.getAttributeUses(); int useCount = attrUses.getListLength(); XSWildcardDecl attrWildcard = attrGrp.fAttributeWC; // whether we have seen a Wildcard ID. String wildcardIDName = null; // for each present attribute int attCount = attributes.getLength(); // Element Locally Valid (Complex Type) // get the corresponding attribute decl for (int index = 0; index < attCount; index++) { attributes.getName(index, fTempQName); if (DEBUG) { System.out.println("==>process attribute: "+fTempQName); } // get attribute PSVI attrPSVI = (AttributePSVImpl)attributes.getAugmentations(index).getItem(Constants.ATTRIBUTE_PSVI); // for the 4 xsi attributes, get appropriate decl, and validate if (fTempQName.uri == URI_XSI) { XSAttributeDecl attrDecl = null; if (fTempQName.localpart == XSI_SCHEMALOCATION) attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(XSI_SCHEMALOCATION); else if (fTempQName.localpart == XSI_NONAMESPACESCHEMALOCATION) attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(XSI_NONAMESPACESCHEMALOCATION); else if (fTempQName.localpart == XSI_NIL) attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(XSI_NIL); else if (fTempQName.localpart == XSI_TYPE) attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(XSI_TYPE); if (attrDecl != null) { processOneAttribute(element, attributes.getValue(index), attrDecl, null, attrPSVI); continue; } } // for namespace attributes, no_validation/unknow_validity if (fTempQName.rawname == XMLNS || fTempQName.rawname.startsWith("xmlns:")) { continue; } // it's not xmlns, and not xsi, then we need to find a decl for it XSAttributeUseImpl currUse = null, oneUse; for (int i = 0; i < useCount; i++) { oneUse = (XSAttributeUseImpl)attrUses.getItem(i); if (oneUse.fAttrDecl.fName == fTempQName.localpart && oneUse.fAttrDecl.fTargetNamespace == fTempQName.uri) { currUse = oneUse; break; } } // 3.2 otherwise all of the following must be true: // 3.2.1 There must be an {attribute wildcard}. // 3.2.2 The attribute information item must be valid with respect to it as defined in Item Valid (Wildcard) (3.10.4). // if failed, get it from wildcard if (currUse == null) { //if (attrWildcard == null) // reportSchemaError("cvc-complex-type.3.2.1", new Object[]{element.rawname, fTempQName.rawname}); if (attrWildcard == null || !attrWildcard.allowNamespace(fTempQName.uri)) { // so this attribute is not allowed reportSchemaError("cvc-complex-type.3.2.2", new Object[]{element.rawname, fTempQName.rawname}); continue; } } XSAttributeDecl currDecl = null; if (currUse != null) { currDecl = currUse.fAttrDecl; } else { // which means it matches a wildcard // skip it if processContents is skip if (attrWildcard.fProcessContents == XSWildcardDecl.PC_SKIP) continue; //try to find grammar by different means... SchemaGrammar grammar = findSchemaGrammar( XSDDescription.CONTEXT_ATTRIBUTE , fTempQName.uri , element , fTempQName , attributes); if (grammar != null){ currDecl = grammar.getGlobalAttributeDecl(fTempQName.localpart); } // if can't find if (currDecl == null) { // if strict, report error if (attrWildcard.fProcessContents == XSWildcardDecl.PC_STRICT){ reportSchemaError("cvc-complex-type.3.2.2", new Object[]{element.rawname, fTempQName.rawname}); } // then continue to the next attribute continue; } else { // 5 Let [Definition:] the wild IDs be the set of all attribute information item to which clause 3.2 applied and whose validation resulted in a context-determined declaration of mustFind or no context-determined declaration at all, and whose [local name] and [namespace name] resolve (as defined by QName resolution (Instance) (3.15.4)) to an attribute declaration whose {type definition} is or is derived from ID. Then all of the following must be true: // 5.1 There must be no more than one item in wild IDs. if (currDecl.fType.getTypeCategory() == XSTypeDecl.SIMPLE_TYPE && ((XSSimpleType)currDecl.fType).isIDType()) { if (wildcardIDName != null){ reportSchemaError("cvc-complex-type.5.1", new Object[]{element.rawname, currDecl.fName, wildcardIDName}); // PSVI: attribute is invalid, record errors attrPSVI.fValidity = AttributePSVI.VALIDITY_INVALID; attrPSVI.addErrorCode("cvc-complex-type.5.1"); } else wildcardIDName = currDecl.fName; } } } processOneAttribute(element, attributes.getValue(index), currDecl, currUse, attrPSVI); } // end of for (all attributes) // 5.2 If wild IDs is non-empty, there must not be any attribute uses among the {attribute uses} whose {attribute declaration}'s {type definition} is or is derived from ID. if (attrGrp.fIDAttrName != null && wildcardIDName != null){ // PSVI: attribute is invalid, record errors reportSchemaError("cvc-complex-type.5.2", new Object[]{element.rawname, wildcardIDName, attrGrp.fIDAttrName}); } } //processAttributes void processOneAttribute(QName element, String attrValue, XSAttributeDecl currDecl, XSAttributeUseImpl currUse, AttributePSVImpl attrPSVI) { // Attribute Locally Valid // For an attribute information item to be locally valid with respect to an attribute declaration all of the following must be true: // 1 The declaration must not be absent (see Missing Sub-components (5.3) for how this can fail to be the case). // 2 Its {type definition} must not be absent. // 3 The item's normalized value must be locally valid with respect to that {type definition} as per String Valid (3.14.4). // get simple type XSSimpleType attDV = currDecl.fType; // PSVI: attribute declaration attrPSVI.fDeclaration = currDecl; // PSVI: attribute type attrPSVI.fTypeDecl = attDV; // PSVI: validation attempted: attrPSVI.fValidationAttempted = AttributePSVI.VALIDATION_FULL; attrPSVI.fValidity = AttributePSVI.VALIDITY_VALID; Object actualValue = null; try { actualValue = attDV.validate(attrValue, fValidationState, fValidatedInfo); // PSVI: attribute memberType attrPSVI.fMemberType = fValidatedInfo.memberType; // PSVI: element notation if (attDV.getVariety() == XSSimpleType.VARIETY_ATOMIC && attDV.getPrimitiveKind() == XSSimpleType.PRIMITIVE_NOTATION){ QName qName = (QName)actualValue; SchemaGrammar grammar = fGrammarBucket.getGrammar(qName.uri); //REVISIT: is it possible for the notation to be in different namespace than the attribute //with which it is associated, CHECK !! <fof n1:att1 = "n2:notation1" ..> // should we give chance to the application to be able to retrieve a grammar - nb //REVISIT: what would be the triggering component here.. if it is attribute value that // triggered the loading of grammar ?? -nb if (grammar != null) fCurrentPSVI.fNotation = grammar.getGlobalNotationDecl(qName.localpart); } } catch (InvalidDatatypeValueException idve) { // PSVI: attribute is invalid, record errors attrPSVI.fValidity = AttributePSVI.VALIDITY_INVALID; attrPSVI.addErrorCode("cvc-attribute.3"); reportSchemaError(idve.getKey(), idve.getArgs()); reportSchemaError("cvc-attribute.3", new Object[]{element.rawname, fTempQName.rawname, attrValue}); } // PSVI: attribute normalized value // NOTE: we always store the normalized value, even if it's invlid, // because it might still be useful to the user. But when the it's // not valid, the normalized value is not trustable. attrPSVI.fNormalizedValue = fValidatedInfo.normalizedValue; // get the value constraint from use or decl // 4 The item's actual value must match the value of the {value constraint}, if it is present and fixed. // now check the value against the simpleType if (actualValue != null && currDecl.getConstraintType() == XSConstants.VC_FIXED) { if (!attDV.isEqual(actualValue, currDecl.fDefault.actualValue)){ // PSVI: attribute is invalid, record errors attrPSVI.fValidity = AttributePSVI.VALIDITY_INVALID; attrPSVI.addErrorCode("cvc-attribute.4"); reportSchemaError("cvc-attribute.4", new Object[]{element.rawname, fTempQName.rawname, attrValue}); } } // 3.1 If there is among the {attribute uses} an attribute use with an {attribute declaration} whose {name} matches the attribute information item's [local name] and whose {target namespace} is identical to the attribute information item's [namespace name] (where an absent {target namespace} is taken to be identical to a [namespace name] with no value), then the attribute information must be valid with respect to that attribute use as per Attribute Locally Valid (Use) (3.5.4). In this case the {attribute declaration} of that attribute use is the context-determined declaration for the attribute information item with respect to Schema-Validity Assessment (Attribute) (3.2.4) and Assessment Outcome (Attribute) (3.2.5). if (actualValue != null && currUse != null && currUse.fConstraintType == XSConstants.VC_FIXED) { if (!attDV.isEqual(actualValue, currUse.fDefault.actualValue)){ // PSVI: attribute is invalid, record errors attrPSVI.fValidity = AttributePSVI.VALIDITY_INVALID; attrPSVI.addErrorCode("cvc-complex-type.3.1"); reportSchemaError("cvc-complex-type.3.1", new Object[]{element.rawname, fTempQName.rawname, attrValue}); } } } void addDefaultAttributes(QName element, XMLAttributes attributes, XSAttributeGroupDecl attrGrp) { // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // REVISIT: should we check prohibited attributes? // (2) report error for PROHIBITED attrs that are present (V_TAGc) // (3) add default attrs (FIXED and NOT_FIXED) if (DEBUG) { System.out.println("==>addDefaultAttributes: " + element); } XSObjectList attrUses = attrGrp.getAttributeUses(); int useCount = attrUses.getListLength(); XSAttributeUseImpl currUse; XSAttributeDecl currDecl; short constType; ValidatedInfo defaultValue; boolean isSpecified; QName attName; // for each attribute use for (int i = 0; i < useCount; i++) { currUse = (XSAttributeUseImpl)attrUses.getItem(i); currDecl = currUse.fAttrDecl; // get value constraint constType = currUse.fConstraintType; defaultValue = currUse.fDefault; if (constType == XSConstants.VC_NONE) { constType = currDecl.getConstraintType(); defaultValue = currDecl.fDefault; } // whether this attribute is specified isSpecified = attributes.getValue(currDecl.fTargetNamespace, currDecl.fName) != null; // Element Locally Valid (Complex Type) // 4 The {attribute declaration} of each attribute use in the {attribute uses} whose // {required} is true matches one of the attribute information items in the element // information item's [attributes] as per clause 3.1 above. if (currUse.fUse == SchemaSymbols.USE_REQUIRED) { if (!isSpecified) reportSchemaError("cvc-complex-type.4", new Object[]{element.rawname, currDecl.fName}); } // if the attribute is not specified, then apply the value constraint if (!isSpecified && constType != XSConstants.VC_NONE) { attName = new QName(null, currDecl.fName, currDecl.fName, currDecl.fTargetNamespace); int attrIndex = attributes.addAttribute(attName, "CDATA", (defaultValue!=null)?defaultValue.normalizedValue:""); // PSVI: attribute is "schema" specified Augmentations augs = attributes.getAugmentations(attrIndex); AttributePSVImpl attrPSVI = (AttributePSVImpl)augs.getItem(Constants.ATTRIBUTE_PSVI); // check if PSVIAttribute was added to Augmentations. // it is possible that we just created new chunck of attributes // in this case PSVI attribute are not there. if (attrPSVI != null) { attrPSVI.reset(); } else { attrPSVI = new AttributePSVImpl(); augs.putItem(Constants.ATTRIBUTE_PSVI, attrPSVI); } attrPSVI.fSpecified = false; // PSVI attribute: validation context attrPSVI.fValidationContext = fValidationRoot; } } // for } // addDefaultAttributes /** * If there is not text content, and there is a * {value constraint} on the corresponding element decl, then return * an XMLString representing the default value. */ XMLString processElementContent(QName element) { // fCurrentElemDecl: default value; ... XMLString defaultValue = null; // 1 If the item is ?valid? with respect to an element declaration as per Element Locally Valid (Element) (?3.3.4) and the {value constraint} is present, but clause 3.2 of Element Locally Valid (Element) (?3.3.4) above is not satisfied and the item has no element or character information item [children], then schema. Furthermore, the post-schema-validation infoset has the canonical lexical representation of the {value constraint} value as the item's [schema normalized value] property. if (fCurrentElemDecl != null && fCurrentElemDecl.fDefault != null && fBuffer.toString().length() == 0 && fChildCount == 0 && !fNil) { // PSVI: specified fCurrentPSVI.fSpecified = false; int bufLen = fCurrentElemDecl.fDefault.normalizedValue.length(); char [] chars = new char[bufLen]; fCurrentElemDecl.fDefault.normalizedValue.getChars(0, bufLen, chars, 0); defaultValue = new XMLString(chars, 0, bufLen); // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.characters(defaultValue); } } // fixed values are handled later, after xsi:type determined. if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_DEFAULT) { } if (fDoValidation) { String content = fBuffer.toString(); // Element Locally Valid (Element) // 3.2.1 The element information item must have no character or element information item [children]. if (fNil) { if (fChildCount != 0 || content.length() != 0){ reportSchemaError("cvc-elt.3.2.1", new Object[]{element.rawname, URI_XSI+","+XSI_NIL}); // PSVI: nil fCurrentPSVI.fNil = false; } else { fCurrentPSVI.fNil = true; } } // 5 The appropriate case among the following must be true: // 5.1 If the declaration has a {value constraint}, the item has neither element nor character [children] and clause 3.2 has not applied, then all of the following must be true: if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() != XSConstants.VC_NONE && fChildCount == 0 && content.length() == 0 && !fNil) { // 5.1.1 If the actual type definition is a local type definition then the canonical lexical representation of the {value constraint} value must be a valid default for the actual type definition as defined in Element Default Valid (Immediate) (3.3.6). if (fCurrentType != fCurrentElemDecl.fType) { //REVISIT:we should pass ValidatedInfo here. if (XSConstraints.ElementDefaultValidImmediate(fCurrentType, fCurrentElemDecl.fDefault.normalizedValue, fState4XsiType, null) == null) reportSchemaError("cvc-elt.5.1.1", new Object[]{element.rawname, fCurrentType.getName(), fCurrentElemDecl.fDefault.normalizedValue}); } // 5.1.2 The element information item with the canonical lexical representation of the {value constraint} value used as its normalized value must be valid with respect to the actual type definition as defined by Element Locally Valid (Type) (3.3.4). // REVISIT: don't use toString, but validateActualValue instead // use the fState4ApplyDefault elementLocallyValidType(element, fCurrentElemDecl.fDefault.normalizedValue); } else { // The following method call also deal with clause 1.2.2 of the constraint // Validation Rule: Schema-Validity Assessment (Element) // 5.2 If the declaration has no {value constraint} or the item has either element or character [children] or clause 3.2 has applied, then all of the following must be true: // 5.2.1 The element information item must be valid with respect to the actual type definition as defined by Element Locally Valid (Type) (3.3.4). Object actualValue = elementLocallyValidType(element, content); // 5.2.2 If there is a fixed {value constraint} and clause 3.2 has not applied, all of the following must be true: if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED && !fNil) { // 5.2.2.1 The element information item must have no element information item [children]. if (fChildCount != 0) reportSchemaError("cvc-elt.5.2.2.1", new Object[]{element.rawname}); // 5.2.2.2 The appropriate case among the following must be true: if (fCurrentType.getTypeCategory() == XSTypeDecl.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType; // 5.2.2.2.1 If the {content type} of the actual type definition is mixed, then the initial value of the item must match the canonical lexical representation of the {value constraint} value. if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) { // REVISIT: how to get the initial value, does whiteSpace count? if (!fCurrentElemDecl.fDefault.normalizedValue.equals(content)) reportSchemaError("cvc-elt.5.2.2.2.1", new Object[]{element.rawname, content, fCurrentElemDecl.fDefault.normalizedValue}); } // 5.2.2.2.2 If the {content type} of the actual type definition is a simple type definition, then the actual value of the item must match the canonical lexical representation of the {value constraint} value. else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (actualValue != null && !ctype.fXSSimpleType.isEqual(actualValue, fCurrentElemDecl.fDefault.actualValue)) reportSchemaError("cvc-elt.5.2.2.2.2", new Object[]{element.rawname, content, fCurrentElemDecl.fDefault.normalizedValue}); } } else if (fCurrentType.getTypeCategory() == XSTypeDecl.SIMPLE_TYPE) { XSSimpleType sType = (XSSimpleType)fCurrentType; if (actualValue != null && !sType.isEqual(actualValue, fCurrentElemDecl.fDefault.actualValue)) // REVISIT: the spec didn't mention this case: fixed // value with simple type reportSchemaError("cvc-elt.5.2.2.2.2", new Object[]{element.rawname, content, fCurrentElemDecl.fDefault.normalizedValue}); } } } } // if fDoValidation return defaultValue; } // processElementContent Object elementLocallyValidType(QName element, String textContent) { if (fCurrentType == null) return null; if (fUnionType) { // for union types we need to send data because we delayed sending this data // when we received it in the characters() call. // XMLString will inlude non-normalized value, PSVIElement will include // normalized value int bufLen = textContent.length(); if (bufLen >= BUFFER_SIZE) { fCharBuffer = new char[bufLen*2]; } textContent.getChars(0, bufLen, fCharBuffer, 0); fXMLString.setValues(fCharBuffer, 0, bufLen); } Object retValue = null; // Element Locally Valid (Type) // 3 The appropriate case among the following must be true: // 3.1 If the type definition is a simple type definition, then all of the following must be true: if (fCurrentType.getTypeCategory() == XSTypeDecl.SIMPLE_TYPE) { // 3.1.2 The element information item must have no element information item [children]. if (fChildCount != 0) reportSchemaError("cvc-type.3.1.2", new Object[]{element.rawname}); // 3.1.3 If clause 3.2 of Element Locally Valid (Element) (3.3.4) did not apply, then the normalized value must be valid with respect to the type definition as defined by String Valid (3.14.4). if (!fNil) { XSSimpleType dv = (XSSimpleType)fCurrentType; try { if (!fNormalizeData || fUnionType) { fValidationState.setNormalizationRequired(true); } retValue = dv.validate(textContent, fValidationState, fValidatedInfo); // PSVI: schema normalized value fCurrentPSVI.fNormalizedValue = fValidatedInfo.normalizedValue; // PSVI: memberType fCurrentPSVI.fMemberType = fValidatedInfo.memberType; if (fDocumentHandler != null && fUnionType) { // send normalized values // at this point we should only rely on normalized value // available via PSVI fAugmentations.putItem(Constants.ELEMENT_PSVI, fCurrentPSVI); fDocumentHandler.characters(fXMLString, fAugmentations); } } catch (InvalidDatatypeValueException e) { if (fDocumentHandler != null && fUnionType) { fCurrentPSVI.fNormalizedValue = null; fAugmentations.putItem(Constants.ELEMENT_PSVI, fCurrentPSVI); fDocumentHandler.characters(fXMLString, fAugmentations); } reportSchemaError(e.getKey(), e.getArgs()); reportSchemaError("cvc-type.3.1.3", new Object[]{element.rawname, textContent}); } } } else { // 3.2 If the type definition is a complex type definition, then the element information item must be valid with respect to the type definition as per Element Locally Valid (Complex Type) (3.4.4); retValue = elementLocallyValidComplexType(element, textContent); } return retValue; } // elementLocallyValidType Object elementLocallyValidComplexType(QName element, String textContent) { Object actualValue = null; XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType; // Element Locally Valid (Complex Type) // For an element information item to be locally valid with respect to a complex type definition all of the following must be true: // 1 {abstract} is false. // 2 If clause 3.2 of Element Locally Valid (Element) (3.3.4) did not apply, then the appropriate case among the following must be true: if (!fNil) { // 2.1 If the {content type} is empty, then the element information item has no character or element information item [children]. if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_EMPTY && (fChildCount != 0 || textContent.length() != 0 || fSawChildren)) { reportSchemaError("cvc-complex-type.2.1", new Object[]{element.rawname}); } // 2.2 If the {content type} is a simple type definition, then the element information item has no element information item [children], and the normalized value of the element information item is valid with respect to that simple type definition as defined by String Valid (3.14.4). else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (fChildCount != 0) reportSchemaError("cvc-complex-type.2.2", new Object[]{element.rawname}); XSSimpleType dv = ctype.fXSSimpleType; try { if (!fNormalizeData || fUnionType) { fValidationState.setNormalizationRequired(true); } actualValue = dv.validate(textContent, fValidationState, fValidatedInfo); // PSVI: schema normalized value fCurrentPSVI.fNormalizedValue = fValidatedInfo.normalizedValue; // PSVI: memberType fCurrentPSVI.fMemberType = fValidatedInfo.memberType; if (fDocumentHandler != null && fUnionType) { fDocumentHandler.characters(fXMLString, fAugmentations); } } catch (InvalidDatatypeValueException e) { if (fDocumentHandler != null && fUnionType) { fCurrentPSVI.fNormalizedValue = null; fDocumentHandler.characters(fXMLString, fAugmentations); } reportSchemaError(e.getKey(), e.getArgs()); reportSchemaError("cvc-complex-type.2.2", new Object[]{element.rawname}); } // REVISIT: eventually, this method should return the same actualValue as elementLocallyValidType... // obviously it'll return null when the content is complex. } // 2.3 If the {content type} is element-only, then the element information item has no character information item [children] other than those whose [character code] is defined as a white space in [XML 1.0 (Second Edition)]. else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT) { if (fSawCharacters) { reportSchemaError("cvc-complex-type.2.3", new Object[]{element.rawname}); } } // 2.4 If the {content type} is element-only or mixed, then the sequence of the element information item's element information item [children], if any, taken in order, is valid with respect to the {content type}'s particle, as defined in Element Sequence Locally Valid (Particle) (3.9.4). if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT || ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) { // if the current state is a valid state, check whether // it's one of the final states. if (DEBUG) { System.out.println(fCurrCMState); } if (fCurrCMState[0] >= 0 && !fCurrentCM.endContentModel(fCurrCMState)) { reportSchemaError("cvc-complex-type.2.4.b", new Object[]{element.rawname, ctype.fParticle.toString()}); } } } return actualValue; } // elementLocallyValidComplexType void reportSchemaError(String key, Object[] arguments) { if (fDoValidation) fXSIErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, key, arguments, XMLErrorReporter.SEVERITY_ERROR); } // xpath matcher information /** * Stack of XPath matchers for identity constraints. * * @author Andy Clark, IBM */ protected static class XPathMatcherStack { // Data /** Active matchers. */ protected XPathMatcher[] fMatchers = new XPathMatcher[4]; /** Count of active matchers. */ protected int fMatchersCount; /** Offset stack for contexts. */ protected IntStack fContextStack = new IntStack(); // Constructors public XPathMatcherStack() { } // <init>() // Public methods /** Resets the XPath matcher stack. */ public void clear() { for (int i = 0; i < fMatchersCount; i++) { fMatchers[i] = null; } fMatchersCount = 0; fContextStack.clear(); } // clear() /** Returns the size of the stack. */ public int size() { return fContextStack.size(); } // size():int /** Returns the count of XPath matchers. */ public int getMatcherCount() { return fMatchersCount; } // getMatcherCount():int /** Adds a matcher. */ public void addMatcher(XPathMatcher matcher) { ensureMatcherCapacity(); fMatchers[fMatchersCount++] = matcher; } // addMatcher(XPathMatcher) /** Returns the XPath matcher at the specified index. */ public XPathMatcher getMatcherAt(int index) { return fMatchers[index]; } // getMatcherAt(index):XPathMatcher /** Pushes a new context onto the stack. */ public void pushContext() { fContextStack.push(fMatchersCount); } // pushContext() /** Pops a context off of the stack. */ public void popContext() { fMatchersCount = fContextStack.pop(); } // popContext() // Private methods /** Ensures the size of the matchers array. */ private void ensureMatcherCapacity() { if (fMatchersCount == fMatchers.length) { XPathMatcher[] array = new XPathMatcher[fMatchers.length * 2]; System.arraycopy(fMatchers, 0, array, 0, fMatchers.length); fMatchers = array; } } // ensureMatcherCapacity() } // class XPathMatcherStack // value store implementations /** * Value store implementation base class. There are specific subclasses * for handling unique, key, and keyref. * * @author Andy Clark, IBM */ protected abstract class ValueStoreBase implements ValueStore { // Constants /** Not a value (Unicode: #FFFF). */ protected IDValue NOT_AN_IDVALUE = new IDValue("\uFFFF", null); // Data /** Identity constraint. */ protected IdentityConstraint fIdentityConstraint; /** Current data values. */ protected final OrderedHashtable fValues = new OrderedHashtable(); /** Current data value count. */ protected int fValuesCount; /** Data value tuples. */ protected final Vector fValueTuples = new Vector(); // Constructors /** Constructs a value store for the specified identity constraint. */ protected ValueStoreBase(IdentityConstraint identityConstraint) { fIdentityConstraint = identityConstraint; } // <init>(IdentityConstraint) // Public methods // destroys this ValueStore; useful when, for instance, a // locally-scoped ID constraint is involved. public void destroy() { fValuesCount = 0; fValues.clear(); fValueTuples.removeAllElements(); } // end destroy():void // appends the contents of one ValueStore to those of us. public void append(ValueStoreBase newVal) { for (int i = 0; i < newVal.fValueTuples.size(); i++) { OrderedHashtable o = (OrderedHashtable)newVal.fValueTuples.elementAt(i); if (!contains(o)) fValueTuples.addElement(o); } } // append(ValueStoreBase) /** Start scope for value store. */ public void startValueScope() throws XNIException { fValuesCount = 0; int count = fIdentityConstraint.getFieldCount(); for (int i = 0; i < count; i++) { fValues.put(fIdentityConstraint.getFieldAt(i), NOT_AN_IDVALUE); } } // startValueScope() /** Ends scope for value store. */ public void endValueScope() throws XNIException { // is there anything to do? // REVISIT: This check solves the problem with field matchers // that get activated because they are at the same // level as the declaring element (e.g. selector xpath // is ".") but never match. // However, this doesn't help us catch the problem // when we expect a field value but never see it. A // better solution has to be found. -Ac // REVISIT: Is this a problem? -Ac // Yes - NG if (fValuesCount == 0) { if (fIdentityConstraint.getCategory() == IdentityConstraint.IC_KEY) { String code = "AbsentKeyValue"; String eName = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{eName}); } return; } // do we have enough values? if (fValuesCount != fIdentityConstraint.getFieldCount()) { switch (fIdentityConstraint.getCategory()) { case IdentityConstraint.IC_UNIQUE: { String code = "UniqueNotEnoughValues"; String ename = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{ename}); break; } case IdentityConstraint.IC_KEY: { String code = "KeyNotEnoughValues"; UniqueOrKey key = (UniqueOrKey)fIdentityConstraint; String ename = fIdentityConstraint.getElementName(); String kname = key.getIdentityConstraintName(); reportSchemaError(code, new Object[]{ename,kname}); break; } case IdentityConstraint.IC_KEYREF: { String code = "KeyRefNotEnoughValues"; KeyRef keyref = (KeyRef)fIdentityConstraint; String ename = fIdentityConstraint.getElementName(); String kname = (keyref.getKey()).getIdentityConstraintName(); reportSchemaError(code, new Object[]{ename,kname}); break; } } return; } } // endValueScope() // This is needed to allow keyref's to look for matched keys // in the correct scope. Unique and Key may also need to // override this method for purposes of their own. // This method is called whenever the DocumentFragment // of an ID Constraint goes out of scope. public void endDocumentFragment() throws XNIException { } // endDocumentFragment():void /** * Signals the end of the document. This is where the specific * instances of value stores can verify the integrity of the * identity constraints. */ public void endDocument() throws XNIException { } // endDocument() // ValueStore methods /* reports an error if an element is matched * has nillable true and is matched by a key. */ public void reportNilError(IdentityConstraint id) { if (id.getCategory() == IdentityConstraint.IC_KEY) { String code = "KeyMatchesNillable"; reportSchemaError(code, new Object[]{id.getElementName()}); } } // reportNilError /** * Adds the specified value to the value store. * * @param value The value to add. * @param field The field associated to the value. This reference * is used to ensure that each field only adds a value * once within a selection scope. */ public void addValue(Field field, IDValue value) { if (!field.mayMatch()) { String code = "FieldMultipleMatch"; reportSchemaError(code, new Object[]{field.toString()}); } // do we even know this field? int index = fValues.indexOf(field); if (index == -1) { String code = "UnknownField"; reportSchemaError(code, new Object[]{field.toString()}); return; } // store value IDValue storedValue = fValues.valueAt(index); if (storedValue.isDuplicateOf(NOT_AN_IDVALUE)) { fValuesCount++; } fValues.put(field, value); if (fValuesCount == fValues.size()) { // is this value as a group duplicated? if (contains(fValues)) { duplicateValue(fValues); } // store values OrderedHashtable values = (OrderedHashtable)fValues.clone(); fValueTuples.addElement(values); } } // addValue(String,Field) /** * Returns true if this value store contains the specified * values tuple. */ public boolean contains(OrderedHashtable tuple) { // do sizes match? int tcount = tuple.size(); // iterate over tuples to find it int count = fValueTuples.size(); LOOP: for (int i = 0; i < count; i++) { OrderedHashtable vtuple = (OrderedHashtable)fValueTuples.elementAt(i); // compare values for (int j = 0; j < tcount; j++) { IDValue value1 = vtuple.valueAt(j); IDValue value2 = tuple.valueAt(j); if (!(value1.isDuplicateOf(value2))) { continue LOOP; } } // found it return true; } // didn't find it return false; } // contains(Hashtable):boolean // Protected methods /** * Called when a duplicate value is added. Subclasses should override * this method to perform error checking. * * @param tuple The duplicate value tuple. */ protected void duplicateValue(OrderedHashtable tuple) throws XNIException { // no-op } // duplicateValue(Hashtable) /** Returns a string of the specified values. */ protected String toString(OrderedHashtable tuple) { // no values int size = tuple.size(); if (size == 0) { return ""; } // construct value string StringBuffer str = new StringBuffer(); for (int i = 0; i < size; i++) { if (i > 0) { str.append(','); } str.append(tuple.valueAt(i)); } return str.toString(); } // toString(OrderedHashtable):String // Object methods /** Returns a string representation of this object. */ public String toString() { String s = super.toString(); int index1 = s.lastIndexOf('$'); if (index1 != -1) { s = s.substring(index1 + 1); } int index2 = s.lastIndexOf('.'); if (index2 != -1) { s = s.substring(index2 + 1); } return s + '[' + fIdentityConstraint + ']'; } // toString():String } // class ValueStoreBase /** * Unique value store. * * @author Andy Clark, IBM */ protected class UniqueValueStore extends ValueStoreBase { // Constructors /** Constructs a unique value store. */ public UniqueValueStore(UniqueOrKey unique) { super(unique); } // <init>(Unique) // ValueStoreBase protected methods /** * Called when a duplicate value is added. * * @param tuple The duplicate value tuple. */ protected void duplicateValue(OrderedHashtable tuple) throws XNIException { String code = "DuplicateUnique"; String value = toString(tuple); String ename = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{value,ename}); } // duplicateValue(Hashtable) } // class UniqueValueStore /** * Key value store. * * @author Andy Clark, IBM */ protected class KeyValueStore extends ValueStoreBase { // REVISIT: Implement a more efficient storage mechanism. -Ac // Constructors /** Constructs a key value store. */ public KeyValueStore(UniqueOrKey key) { super(key); } // <init>(Key) // ValueStoreBase protected methods /** * Called when a duplicate value is added. * * @param tuple The duplicate value tuple. */ protected void duplicateValue(OrderedHashtable tuple) throws XNIException { String code = "DuplicateKey"; String value = toString(tuple); String ename = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{value,ename}); } // duplicateValue(Hashtable) } // class KeyValueStore /** * Key reference value store. * * @author Andy Clark, IBM */ protected class KeyRefValueStore extends ValueStoreBase { // Data /** Key value store. */ protected ValueStoreBase fKeyValueStore; // Constructors /** Constructs a key value store. */ public KeyRefValueStore(KeyRef keyRef, KeyValueStore keyValueStore) { super(keyRef); fKeyValueStore = keyValueStore; } // <init>(KeyRef) // ValueStoreBase methods // end the value Scope; here's where we have to tie // up keyRef loose ends. public void endDocumentFragment () throws XNIException { // do all the necessary management... super.endDocumentFragment (); // verify references // get the key store corresponding (if it exists): fKeyValueStore = (ValueStoreBase)fValueStoreCache.fGlobalIDConstraintMap.get(((KeyRef)fIdentityConstraint).getKey()); if (fKeyValueStore == null) { // report error String code = "KeyRefOutOfScope"; String value = fIdentityConstraint.toString(); reportSchemaError(code, new Object[]{value}); return; } int count = fValueTuples.size(); for (int i = 0; i < count; i++) { OrderedHashtable values = (OrderedHashtable)fValueTuples.elementAt(i); if (!fKeyValueStore.contains(values)) { String code = "KeyNotFound"; String value = toString(values); String element = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{value,element}); } } } // endDocumentFragment() /** End document. */ public void endDocument() throws XNIException { super.endDocument(); } // endDocument() } // class KeyRefValueStore // value store management /** * Value store cache. This class is used to store the values for * identity constraints. * * @author Andy Clark, IBM */ protected class ValueStoreCache { // Data // values stores /** stores all global Values stores. */ protected final Vector fValueStores = new Vector(); /** Values stores associated to specific identity constraints. */ protected final Hashtable fIdentityConstraint2ValueStoreMap = new Hashtable(); // sketch of algorithm: // - when a constraint is first encountered, its // values are stored in the (local) fIdentityConstraint2ValueStoreMap; // - Once it is validated (i.e., wen it goes out of scope), // its values are merged into the fGlobalIDConstraintMap; // - as we encounter keyref's, we look at the global table to // validate them. // the fGlobalIDMapStack has the following structure: // - validation always occurs against the fGlobalIDConstraintMap // (which comprises all the "eligible" id constraints); // When an endelement is found, this Hashtable is merged with the one // below in the stack. // When a start tag is encountered, we create a new // fGlobalIDConstraintMap. // i.e., the top of the fGlobalIDMapStack always contains // the preceding siblings' eligible id constraints; // the fGlobalIDConstraintMap contains descendants+self. // keyrefs can only match descendants+self. protected final Stack fGlobalMapStack = new Stack(); protected final Hashtable fGlobalIDConstraintMap = new Hashtable(); // Constructors /** Default constructor. */ public ValueStoreCache() { } // <init>() // Public methods /** Resets the identity constraint cache. */ public void startDocument() throws XNIException { fValueStores.removeAllElements(); fIdentityConstraint2ValueStoreMap.clear(); fGlobalIDConstraintMap.clear(); fGlobalMapStack.removeAllElements(); } // startDocument() // startElement: pushes the current fGlobalIDConstraintMap // onto fGlobalMapStack and clears fGlobalIDConstraint map. public void startElement() { fGlobalMapStack.push(fGlobalIDConstraintMap.clone()); fGlobalIDConstraintMap.clear(); } // startElement(void) // endElement(): merges contents of fGlobalIDConstraintMap with the // top of fGlobalMapStack into fGlobalIDConstraintMap. public void endElement() { if (fGlobalMapStack.isEmpty()) return; // must be an invalid doc! Hashtable oldMap = (Hashtable)fGlobalMapStack.pop(); Enumeration keys = oldMap.keys(); while (keys.hasMoreElements()) { IdentityConstraint id = (IdentityConstraint)keys.nextElement(); ValueStoreBase oldVal = (ValueStoreBase)oldMap.get(id); if (oldVal != null) { ValueStoreBase currVal = (ValueStoreBase)fGlobalIDConstraintMap.get(id); if (currVal == null) fGlobalIDConstraintMap.put(id, oldVal); else { currVal.append(oldVal); fGlobalIDConstraintMap.put(id, currVal); } } } } // endElement() /** * Initializes the value stores for the specified element * declaration. */ public void initValueStoresFor(XSElementDecl eDecl) throws XNIException { // initialize value stores for unique fields IdentityConstraint [] icArray = eDecl.fIDConstraints; int icCount = eDecl.fIDCPos; for (int i = 0; i < icCount; i++) { switch (icArray[i].getCategory()) { case (IdentityConstraint.IC_UNIQUE): // initialize value stores for unique fields UniqueOrKey unique = (UniqueOrKey)icArray[i]; UniqueValueStore uniqueValueStore = (UniqueValueStore)fIdentityConstraint2ValueStoreMap.get(unique); if (uniqueValueStore != null) { // NOTE: If already initialized, don't need to // do it again. -Ac continue; } uniqueValueStore = new UniqueValueStore(unique); fValueStores.addElement(uniqueValueStore); fIdentityConstraint2ValueStoreMap.put(unique, uniqueValueStore); break; case (IdentityConstraint.IC_KEY): // initialize value stores for key fields UniqueOrKey key = (UniqueOrKey)icArray[i]; KeyValueStore keyValueStore = (KeyValueStore)fIdentityConstraint2ValueStoreMap.get(key); if (keyValueStore != null) { // NOTE: If already initialized, don't need to // do it again. -Ac continue; } keyValueStore = new KeyValueStore(key); fValueStores.addElement(keyValueStore); fIdentityConstraint2ValueStoreMap.put(key, keyValueStore); break; case (IdentityConstraint.IC_KEYREF): // initialize value stores for key reference fields KeyRef keyRef = (KeyRef)icArray[i]; KeyRefValueStore keyRefValueStore = (KeyRefValueStore)fIdentityConstraint2ValueStoreMap.get(keyRef); if (keyRefValueStore != null) { // NOTE: If already initialized, don't need to // do it again. -Ac continue; } keyRefValueStore = new KeyRefValueStore(keyRef, null); fValueStores.addElement(keyRefValueStore); fIdentityConstraint2ValueStoreMap.put(keyRef, keyRefValueStore); break; } } } // initValueStoresFor(XSElementDecl) /** Returns the value store associated to the specified field. */ public ValueStoreBase getValueStoreFor(Field field) { IdentityConstraint identityConstraint = field.getIdentityConstraint(); return(ValueStoreBase)fIdentityConstraint2ValueStoreMap.get(identityConstraint); } // getValueStoreFor(Field):ValueStoreBase /** Returns the value store associated to the specified IdentityConstraint. */ public ValueStoreBase getValueStoreFor(IdentityConstraint id) { return(ValueStoreBase)fIdentityConstraint2ValueStoreMap.get(id); } // getValueStoreFor(IdentityConstraint):ValueStoreBase /** Returns the global value store associated to the specified IdentityConstraint. */ public ValueStoreBase getGlobalValueStoreFor(IdentityConstraint id) { return(ValueStoreBase)fGlobalIDConstraintMap.get(id); } // getValueStoreFor(IdentityConstraint):ValueStoreBase // This method takes the contents of the (local) ValueStore // associated with id and moves them into the global // hashtable, if id is a <unique> or a <key>. // If it's a <keyRef>, then we leave it for later. public void transplant(IdentityConstraint id) { if (id.getCategory() == IdentityConstraint.IC_KEYREF) return; ValueStoreBase newVals = (ValueStoreBase)fIdentityConstraint2ValueStoreMap.get(id); fIdentityConstraint2ValueStoreMap.remove(id); ValueStoreBase currVals = (ValueStoreBase)fGlobalIDConstraintMap.get(id); if (currVals != null) { currVals.append(newVals); fGlobalIDConstraintMap.put(id, currVals); } else fGlobalIDConstraintMap.put(id, newVals); } // transplant(id) /** Check identity constraints. */ public void endDocument() throws XNIException { int count = fValueStores.size(); for (int i = 0; i < count; i++) { ValueStoreBase valueStore = (ValueStoreBase)fValueStores.elementAt(i); valueStore.endDocument(); } } // endDocument() // Object methods /** Returns a string representation of this object. */ public String toString() { String s = super.toString(); int index1 = s.lastIndexOf('$'); if (index1 != -1) { return s.substring(index1 + 1); } int index2 = s.lastIndexOf('.'); if (index2 != -1) { return s.substring(index2 + 1); } return s; } // toString():String } // class ValueStoreCache // utility classes /** * Ordered hashtable. This class acts as a hashtable with * <code>put()</code> and <code>get()</code> operations but also * allows values to be queried via the order that they were * added to the hashtable. * <p> * <strong>Note:</strong> This class does not perform any error * checking. * <p> * <strong>Note:</strong> This class is <em>not</em> efficient but * is assumed to be used for a very small set of values. * * @author Andy Clark, IBM */ static final class OrderedHashtable implements Cloneable { // Data /** Size. */ private int fSize; /** Hashtable entries. */ private Entry[] fEntries = null; // Public methods /** Returns the number of entries in the hashtable. */ public int size() { return fSize; } // size():int /** Puts an entry into the hashtable. */ public void put(Field key, IDValue value) { int index = indexOf(key); if (index == -1) { ensureCapacity(fSize); index = fSize++; fEntries[index].key = key; } fEntries[index].value = value; } // put(Field,String) /** Returns the value associated to the specified key. */ public IDValue get(Field key) { return fEntries[indexOf(key)].value; } // get(Field):String /** Returns the index of the entry with the specified key. */ public int indexOf(Field key) { for (int i = 0; i < fSize; i++) { // NOTE: Only way to be sure that the keys are the // same is by using a reference comparison. In // order to rely on the equals method, each // field would have to take into account its // position in the identity constraint, the // identity constraint, the declaring element, // and the grammar that it is defined in. // Otherwise, you have the possibility that // the equals method would return true for two // fields that look *very* similar. // The reference compare isn't bad, actually, // because the field objects are cacheable. -Ac if (fEntries[i].key == key) { return i; } } return -1; } // indexOf(Field):int /** Returns the key at the specified index. */ public Field keyAt(int index) { return fEntries[index].key; } // keyAt(int):Field /** Returns the value at the specified index. */ public IDValue valueAt(int index) { return fEntries[index].value; } // valueAt(int):String /** Removes all of the entries from the hashtable. */ public void clear() { fSize = 0; } // clear() // Private methods /** Ensures the capacity of the entries array. */ private void ensureCapacity(int size) { // sizes int osize = -1; int nsize = -1; // create array if (fEntries == null) { osize = 0; nsize = 2; fEntries = new Entry[nsize]; } // resize array else if (fEntries.length <= size) { osize = fEntries.length; nsize = 2 * osize; Entry[] array = new Entry[nsize]; System.arraycopy(fEntries, 0, array, 0, osize); fEntries = array; } // create new entries for (int i = osize; i < nsize; i++) { fEntries[i] = new Entry(); } } // ensureCapacity(int) // Cloneable methods /** Clones this object. */ public Object clone() { OrderedHashtable hashtable = new OrderedHashtable(); for (int i = 0; i < fSize; i++) { hashtable.put(fEntries[i].key, fEntries[i].value); } return hashtable; } // clone():Object // Object methods /** Returns a string representation of this object. */ public String toString() { if (fSize == 0) { return "[]"; } StringBuffer str = new StringBuffer(); str.append('['); for (int i = 0; i < fSize; i++) { if (i > 0) { str.append(','); } str.append('{'); str.append(fEntries[i].key); str.append(','); str.append(fEntries[i].value); str.append('}'); } str.append(']'); return str.toString(); } // toString():String // Classes /** * Hashtable entry. */ public static final class Entry { // Data /** Key. */ public Field key; /** Value. */ public IDValue value; } // class Entry } // class OrderedHashtable } // class SchemaValidator
package edu.ur.ir.web.action.file.storage; import java.util.Set; import org.apache.log4j.Logger; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.Preparable; import edu.ur.file.db.FileDatabase; import edu.ur.file.db.FileServer; import edu.ur.file.db.FileServerService; import edu.ur.file.db.FolderInfo; import edu.ur.file.db.LocationAlreadyExistsException; /** * Class for managing file database information. * * @author Nathan Sarr * */ public class ManageFileDatabase extends ActionSupport implements Preparable{ /** Eclipse generated id */ private static final long serialVersionUID = -1712815183938029916L; /** Logger for managing content types*/ private static final Logger log = Logger.getLogger(ManageFileDatabase.class); /** Service for dealing with file servers */ private FileServerService fileServerService; /** id of a specific file server */ private Long fileServerId; /** name for the database */ private String name; /** Path for the database */ private String path; /** id of the file database */ private Long fileDatabaseId; /** description of the file server */ private String description; /** File Server for file access */ private FileServer fileServer; /** File database */ private FileDatabase fileDatabase; /** Message that can be displayed to the user. */ private String message; /** Indicates the file database has been added*/ private boolean added = false; /** Indicates the file database has been deleted*/ private boolean deleted = false; public String get() { return "get"; } /** * View a specific file database. * * @return view if the database exists */ public String view() { return "view"; } /** * View a specific file database for a file server. * * @return Success */ public String getAll() { return "getAll"; } /** * Delete a specific file server. * * @return Success */ public String update() { log.debug("update called"); added = true; if( fileDatabase != null) { fileDatabase.setDescription(description); fileServerService.saveFileServer(fileServer); } return "added"; } /** * Delete a specific file server. * * @return Success */ @SuppressWarnings("unchecked") public String delete() { log.debug("delete called"); if( fileDatabase != null) { deleted = true; Set<FolderInfo> folders = (Set<FolderInfo>)fileDatabase.getRootFolders(); // only delete if there are no folders - otherwise a user could delete all of // their files if(folders == null || folders.size() == 0) { fileServer.deleteDatabase(fileDatabase.getName()); fileServerService.saveFileServer(fileServer); } } return "deleted"; } /** * Create a specified file server. * * @return */ public String create() { log.debug("creating a file database = " + name + " path = " + path); added = false; FileDatabase other = fileServerService.getDatabaseByName(fileServerId, name); if( other == null) { try { fileDatabase = fileServer.createFileDatabase(name, name, path, description); fileServerService.saveFileServer(fileServer); added = true; } catch (LocationAlreadyExistsException e) { message = getText("folderLocationAlreadyExists", new String[]{fileServer.getName()}); addFieldError("folderLocationAlreadyExists", message); } } else { message = getText("fileDatabaseNameError", new String[]{fileServer.getName()}); addFieldError("fileDatabaseAlreadyExists", message); } return "added"; } public FileServerService getFileServerService() { return fileServerService; } public void setFileServerService(FileServerService fileServerService) { this.fileServerService = fileServerService; } public Long getFileServerId() { return fileServerId; } public void setFileServerId(Long fileServerId) { this.fileServerId = fileServerId; } public FileServer getFileServer() { return fileServer; } public void setFileServer(FileServer fileServer) { this.fileServer = fileServer; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public boolean isAdded() { return added; } public void setAdded(boolean added) { this.added = added; } public void prepare() throws Exception { log.debug("perpare called fileServerId = " + fileServerId + " fileDatabaseId = " + fileDatabaseId); if( fileServerId != null) { fileServer = fileServerService.getFileServer(fileServerId, false); if(fileDatabaseId != null) { fileDatabase = fileServer.getFileDatabase(fileDatabaseId); } } } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean getDeleted() { return deleted; } public void setDeleted(boolean deleted) { this.deleted = deleted; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public Long getFileDatabaseId() { return fileDatabaseId; } public void setFileDatabaseId(Long fileDatabaseId) { this.fileDatabaseId = fileDatabaseId; } public FileDatabase getFileDatabase() { return fileDatabase; } public void setFileDatabase(FileDatabase fileDatabase) { this.fileDatabase = fileDatabase; } }
package org.rti.webgenome.service.plot; import java.awt.Color; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.rti.webgenome.domain.Experiment; import org.rti.webgenome.domain.GenomeInterval; import org.rti.webgenome.domain.QuantitationType; import org.rti.webgenome.graphics.PlotBoundaries; import org.rti.webgenome.graphics.event.EventHandlerGraphicBoundaries; import org.rti.webgenome.graphics.event.MouseOverStripes; import org.rti.webgenome.graphics.io.ClickBoxes; import org.rti.webgenome.graphics.widget.Axis; import org.rti.webgenome.graphics.widget.Background; import org.rti.webgenome.graphics.widget.Caption; import org.rti.webgenome.graphics.widget.Grid; import org.rti.webgenome.graphics.widget.Legend; import org.rti.webgenome.graphics.widget.PlotPanel; import org.rti.webgenome.graphics.widget.ScatterPlot; import org.rti.webgenome.service.util.ChromosomeArrayDataGetter; import org.rti.webgenome.units.BpUnits; import org.rti.webgenome.units.HorizontalAlignment; import org.rti.webgenome.units.Location; import org.rti.webgenome.units.Orientation; import org.rti.webgenome.units.VerticalAlignment; /** * Manages the painting scatter plots by getting * data and assembling plot widgets. * @author dhall * */ public class ScatterPlotPainter extends PlotPainter { // Constants /** Grid color. */ private static final Color GRID_COLOR = Color.WHITE; /** Background color. */ private static final Color BG_COLOR = new Color(235, 235, 235); // Constructors /** * Constructor. * @param chromosomeArrayDataGetter Chromosome array data getter */ public ScatterPlotPainter( final ChromosomeArrayDataGetter chromosomeArrayDataGetter) { super(chromosomeArrayDataGetter); } // Business methods /** * Paints a plot on the given plot panel. * @param panel Plot panel to add the scatter plot to * @param experiments Experiments to plot * @param params Plotting parameters specified * by user * @return Boundaries of event handler regions. */ public final EventHandlerGraphicBoundaries paintPlot( final PlotPanel panel, final Collection<Experiment> experiments, final ScatterPlotParameters params) { // Check args if (experiments == null || panel == null) { throw new IllegalArgumentException( "Experiments and panel cannot be null"); } if (params.getGenomeIntervals() == null || params.getGenomeIntervals().size() < 1) { throw new IllegalArgumentException( "No genome intervals specified"); } RowAdder rowAdder = new RowAdder(experiments, params, this.getChromosomeArrayDataGetter()); int rowCount = 1; while (rowAdder.hasMore()) { PlotPanel row = panel.newChildPlotPanel(); rowAdder.addRow(row); VerticalAlignment va = null; if (rowCount++ == 1) { va = VerticalAlignment.TOP_JUSTIFIED; } else { va = VerticalAlignment.BELOW; } panel.add(row, HorizontalAlignment.LEFT_JUSTIFIED, va); } // Legend Legend legend = new Legend(experiments, params.getWidth()); panel.add(legend, HorizontalAlignment.CENTERED, VerticalAlignment.BELOW); // Gather up click boxes and mouseover stripes Set<ClickBoxes> boxes = new HashSet<ClickBoxes>(); Set<MouseOverStripes> stripes = new HashSet<MouseOverStripes>(); for (ScatterPlot plot : rowAdder.getPlotsCreated()) { boxes.add(plot.getClickBoxes()); stripes.add(plot.getMouseOverStripes()); } return new EventHandlerGraphicBoundaries(stripes, boxes); } /** * Helper class that adds a new row to the overall plot. * @author dhall */ static final class RowAdder { // A T T R I B U T E S /** Experiments containing data to plot. */ private Collection<Experiment> experiments = new ArrayList<Experiment>(); /** Index variable that points to next genome interval to plot. */ private int idx = 0; /** Plots created since object instantiated. */ private Collection<ScatterPlot> plots = new ArrayList<ScatterPlot>(); /** Plotting parameters. */ private ScatterPlotParameters params = null;; /** Genome intervals to plot. */ private List<GenomeInterval> genomeIntervals = new ArrayList<GenomeInterval>(); /** * Quantitation type of left Y-axis. Two Y-axes * are needed for co-visualization (i.e. copy number * and expression data) plots. */ private QuantitationType leftYAxisQuantitationType = null; /** * Quantitation type of right Y-axis. Two Y-axes * are needed for co-visualization (i.e. copy number * and expression data) plots. This will remain null * unless the plot is co-visualization. */ private QuantitationType rightYAxisQuantitationType = null; /** * Minimum value on left Y-axis. Two Y-axes * are needed for co-visualization (i.e. copy number * and expression data) plots. */ private double leftYAxisMinValue = Double.NaN; /** * Maximum value on left Y-axis. Two Y-axes * are needed for co-visualization (i.e. copy number * and expression data) plots. */ private double leftYAxisMaxValue = Double.NaN; /** * Minimum value on right Y-axis. Two Y-axes * are needed for co-visualization (i.e. copy number * and expression data) plots. This will remain * NaN unless plot is co-visualization. */ private double rightYAxisMinValue; /** * Maximum value on right Y-axis. Two Y-axes * are needed for co-visualization (i.e. copy number * and expression data) plots. This will remain * NaN unless plot is co-visualization. */ private double rightYAxisMaxValue; /** Sizes individual genome interval scatter plots. */ private ScatterPlotSizer sizer; /** Getter for data. */ private ChromosomeArrayDataGetter chromosomeArrayDataGetter; // C O N S T R U C T O R S /** * Constructor. * @param experiments Experiments to plot. * @param params Plotting parameters * @param chromosomeArrayDataGetter Data getter */ private RowAdder(final Collection<Experiment> experiments, final ScatterPlotParameters params, final ChromosomeArrayDataGetter chromosomeArrayDataGetter) { this.experiments.addAll(experiments); this.params = params; this.genomeIntervals.addAll(params.getGenomeIntervals()); Collections.sort(this.genomeIntervals); QuantitationType copyNumberQT = Experiment.getCopyNumberQuantitationType(experiments); if (copyNumberQT != null) { this.leftYAxisQuantitationType = copyNumberQT; String label = Experiment.getCopyNumberQuantitationLabel(experiments) ; if ( label != null ) // will only usually be non-null for Other value this.leftYAxisQuantitationType.setOtherValue( label ) ; this.leftYAxisMaxValue = params.getCopyNumberMaxY(); this.leftYAxisMinValue = params.getCopyNumberMinY(); } QuantitationType expressionQT = Experiment.getExpressionQuantitationType(experiments); if (expressionQT != null) { if (this.leftYAxisQuantitationType == null) { this.leftYAxisQuantitationType = expressionQT; String label = Experiment.getCopyNumberQuantitationLabel(experiments) ; if ( label != null ) // will only usually be non-null for Other value this.leftYAxisQuantitationType.setOtherValue( label ) ; this.leftYAxisMaxValue = params.getExpressionMaxY(); this.leftYAxisMinValue = params.getExpressionMinY(); } else { this.rightYAxisQuantitationType = expressionQT; this.rightYAxisMaxValue = params.getExpressionMaxY(); this.rightYAxisMinValue = params.getExpressionMinY(); } } if (copyNumberQT != null && expressionQT != null) { this.mergeAxesRanges(); } this.sizer = new ScatterPlotSizer(params); this.chromosomeArrayDataGetter = chromosomeArrayDataGetter; } /** * For co-visualization of copy number/LOH and expression data, * both Y-axes should have the same range. This method merges * those ranges. */ private void mergeAxesRanges() { double maxY = Double.NaN; double minY = Double.NaN; if (this.leftYAxisMaxValue > this.rightYAxisMaxValue) { maxY = this.leftYAxisMaxValue; } else { maxY = this.rightYAxisMaxValue; } if (this.leftYAxisMinValue < this.rightYAxisMinValue) { minY = this.leftYAxisMinValue; } else { minY = this.rightYAxisMinValue; } this.leftYAxisMaxValue = maxY; this.rightYAxisMaxValue = maxY; this.leftYAxisMinValue = minY; this.rightYAxisMinValue = minY; } // B U S I N E S S M E T H O D S /** * Add new "row" to given panel. The row will consist * of a number of widgets layed out on the given panel * that show one or more scatter plots to different * genome intervals. * @param row Panel on which to draw row. */ private void addRow(final PlotPanel row) { if (this.idx < this.genomeIntervals.size()) { Axis yAxis = new Axis(this.leftYAxisMinValue, this.leftYAxisMaxValue, this.sizer.height(), Orientation.VERTICAL, Location.LEFT_OF, row.getDrawingCanvas()); int endIdx = this.idx + this.params.getNumPlotsPerRow(); if (endIdx > this.genomeIntervals.size()) { endIdx = this.genomeIntervals.size(); } for (int i = this.idx; i < endIdx; i++) { this.addGenomeIntervalPlot(row, this.genomeIntervals.get(i), yAxis, i == this.idx); } this.addLeftYAxis(row, yAxis); if (this.rightYAxisQuantitationType != null) { this.addRightYAxis(row); } this.idx = endIdx; } } /** * Add left Y-axis to row. * @param row Panel to draw axis on * @param yAxis Axis to add */ private void addLeftYAxis(final PlotPanel row, final Axis yAxis) { // Other value will be set for when Quantitation Type is 'Other'. String name = leftYAxisQuantitationType.getOtherValue() != null ? leftYAxisQuantitationType.getOtherValue() : leftYAxisQuantitationType.getName() ; Caption yCaption = new Caption( name, Orientation.HORIZONTAL, true, row.getDrawingCanvas()); row.add(yAxis, HorizontalAlignment.LEFT_JUSTIFIED, VerticalAlignment.BOTTOM_JUSTIFIED); row.add(yCaption, HorizontalAlignment.LEFT_OF, VerticalAlignment.CENTERED); } /** * Co-visualization plots require two Y-axes. This * method adds a second Y-axis to the right of the * given row of plots. * @param row Panel containing row of plots */ private void addRightYAxis(final PlotPanel row) { Axis yAxis = new Axis(this.rightYAxisMinValue, this.rightYAxisMaxValue, this.sizer.height(), Orientation.VERTICAL, Location.RIGHT_OF, row.getDrawingCanvas()); Caption yCaption = new Caption( rightYAxisQuantitationType.getName(), Orientation.HORIZONTAL, true, row.getDrawingCanvas()); // TODO: (Above) Not sure whether Caption for Other (Quantitation Type) is needed row.add(yAxis, HorizontalAlignment.RIGHT_JUSTIFIED, VerticalAlignment.BOTTOM_JUSTIFIED); row.add(yCaption, HorizontalAlignment.RIGHT_OF, VerticalAlignment.CENTERED); } /** * Add plot of a single genome interval to the given row panel. * @param row Row panel * @param gi Genome interval to graph * @param referenceYAxis Reference Y-axis, which will always * be the left Y-axis * @param leftJustify Should plot be left justified related * to other widgets? This is typically done if the plot * is the first on a row. */ private void addGenomeIntervalPlot(final PlotPanel row, final GenomeInterval gi, final Axis referenceYAxis, final boolean leftJustify) { PlotPanel col = row.newChildPlotPanel(); BpUnits units = this.params.getUnits(); long start = units.fromBp(gi.getStartLocation()); long end = units.fromBp(gi.getEndLocation()); Axis xAxis = new Axis(start, end, this.sizer.width(gi), Orientation.HORIZONTAL, Location.BELOW, col.getDrawingCanvas()); // Background Background bg = new Background(this.sizer.width(gi), this.sizer.height(), BG_COLOR); col.add(bg, true); // Grid lines if (this.params.isDrawVertGridLines()) { Grid vertGrid = xAxis.newGrid(this.sizer.width(gi), this.sizer.height(), GRID_COLOR, col); col.add(vertGrid, HorizontalAlignment.LEFT_JUSTIFIED, VerticalAlignment.TOP_JUSTIFIED); } if (this.params.isDrawHorizGridLines()) { Grid horizGrid = referenceYAxis.newGrid(this.sizer.width(gi), this.sizer.height(), GRID_COLOR, col); col.add(horizGrid, HorizontalAlignment.LEFT_JUSTIFIED, VerticalAlignment.TOP_JUSTIFIED); } // Add scatter plot ScatterPlot scatterPlot = this.newScatterPlot(gi); col.add(scatterPlot, HorizontalAlignment.LEFT_JUSTIFIED, VerticalAlignment.TOP_JUSTIFIED); // X-axis stuff String captionText = "Chromosome " + gi.getChromosome() + " (" + this.params.getUnits().getName() + ")"; Caption xCaption = new Caption(captionText, Orientation.HORIZONTAL, false, row.getDrawingCanvas()); col.add(xAxis, HorizontalAlignment.LEFT_JUSTIFIED, VerticalAlignment.BOTTOM_JUSTIFIED); col.add(xCaption, HorizontalAlignment.CENTERED, VerticalAlignment.BELOW); // Add all widgets to row HorizontalAlignment ha = null; if (leftJustify) { ha = HorizontalAlignment.LEFT_JUSTIFIED; } else { ha = HorizontalAlignment.RIGHT_OF; } row.add(col, ha, VerticalAlignment.BOTTOM_JUSTIFIED); this.plots.add(scatterPlot); } /** * Are there more rows to plot? * @return T/F */ private boolean hasMore() { return this.idx < this.genomeIntervals.size(); } /** * Get all individual scatter plots created since this * object was instantiated. * @return Plot created */ private Collection<ScatterPlot> getPlotsCreated() { return this.plots; } /** * Instantiate new scatter plot of given genome interval. * @param gi Interval to plot * @return New scatter plot */ private ScatterPlot newScatterPlot(final GenomeInterval gi) { // Create plot boundaries PlotBoundaries expressionPlotBoundaries = null; PlotBoundaries copyNumberPlotBoundaries = null; if (Experiment.getExpressionQuantitationType(this.experiments) != null) { expressionPlotBoundaries = new PlotBoundaries( gi.getStartLocation(), this.params.getExpressionMinY(), gi.getEndLocation(), this.params.getExpressionMaxY()); } if (Experiment.getCopyNumberQuantitationType(experiments) != null) { copyNumberPlotBoundaries = new PlotBoundaries( gi.getStartLocation(), this.params.getCopyNumberMinY(), gi.getEndLocation(), this.params.getCopyNumberMaxY()); } // If co-visualizing copy number/LOH and expression data, // union boundaries together so plotting space same if (expressionPlotBoundaries != null && copyNumberPlotBoundaries != null) { expressionPlotBoundaries.union(copyNumberPlotBoundaries); copyNumberPlotBoundaries.union(expressionPlotBoundaries); } // Create and configure plot ScatterPlot scatterPlot = new ScatterPlot(this.experiments, gi.getChromosome(), this.chromosomeArrayDataGetter, this.sizer.width(gi), this.sizer.height, expressionPlotBoundaries, copyNumberPlotBoundaries); scatterPlot.setDrawErrorBars(this.params.isDrawErrorBars()); scatterPlot.setInterpolationType( this.params.getInterpolationType()); scatterPlot.setDrawPoints(this.params.isDrawPoints()); scatterPlot.setDrawRawLohProbabilities( this.params.isDrawRawLohProbabilities()); scatterPlot.setInterpolateLohEndpoints( this.params.isInterpolateLohEndpoints()); scatterPlot.setLohThreshold(this.params.getLohThreshold()); scatterPlot.setShowAnnotation(this.params.isShowAnnotation()); scatterPlot.setShowGenes(this.params.isShowGenes()); scatterPlot.setShowReporterNames( this.params.isShowReporterNames()); scatterPlot.setShowStem(this.params.isDrawStems()); return scatterPlot; } } /** * Class that is responsible for calculating * the width and height of scatter plot widgets. * When there is only a single * genome interval to plot, the dimensions of the * single scatter plot widget are equal to the width * and height passed in through the scatter plot parameters * web form. * For multiple genome intervals, the sum of widths and * heights of the individual scatter plot widgets * for the widest row of plots is * less than or equal to these parameters, respectively. */ private static final class ScatterPlotSizer { /** Scale of native units to pixels. */ private final double scale; /** Height of all plots in pixels. */ private final int height; /** * Constructor. * @param params Plot parameters */ private ScatterPlotSizer(final ScatterPlotParameters params) { List<GenomeInterval> intervals = new ArrayList<GenomeInterval>(params.getGenomeIntervals()); int numRows = (int) Math.ceil((double) intervals.size() / (double) params.getNumPlotsPerRow()); this.height = params.getHeight() / numRows; long longestInterval = 0; int p = 0; while (p < intervals.size()) { int q = p + params.getNumPlotsPerRow(); if (q > intervals.size()) { q = intervals.size(); } long candidateLongest = 0; for (int i = p; i < q; i++) { candidateLongest += intervals.get(i).length(); } if (candidateLongest > longestInterval) { longestInterval = candidateLongest; } p = q; } this.scale = (double) params.getWidth() / (double) longestInterval; } /** * Get width for plot. * @param interval Genome interval * @return Width in pixels */ private int width(final GenomeInterval interval) { return (int) (this.scale * (interval.getEndLocation() - interval.getStartLocation())); } /** * Get height for plot. * @return Height in pixels. */ private int height() { return this.height; } } }
package com.foundationdb.sql.optimizer; import com.foundationdb.server.error.AmbiguousColumNameException; import com.foundationdb.server.error.CorrelationNameAlreadyUsedException; import com.foundationdb.server.error.JoinNodeAdditionException; import com.foundationdb.server.error.NoSuchColumnException; import com.foundationdb.server.error.NoSuchFunctionException; import com.foundationdb.server.error.NoSuchTableException; import com.foundationdb.server.error.ProcedureCalledAsFunctionException; import com.foundationdb.server.error.SQLParserInternalException; import com.foundationdb.server.error.SelectExistsErrorException; import com.foundationdb.server.error.SubqueryOneColumnException; import com.foundationdb.server.error.TableIsBadSubqueryException; import com.foundationdb.server.error.ViewHasBadSubqueryException; import com.foundationdb.server.error.WholeGroupQueryException; import com.foundationdb.sql.StandardException; import com.foundationdb.sql.parser.*; import com.foundationdb.sql.views.ViewDefinition; import com.foundationdb.ais.model.AkibanInformationSchema; import com.foundationdb.ais.model.Column; import com.foundationdb.ais.model.Columnar; import com.foundationdb.ais.model.Join; import com.foundationdb.ais.model.JoinColumn; import com.foundationdb.ais.model.Routine; import com.foundationdb.ais.model.Table; import com.foundationdb.ais.model.View; import java.util.*; public class AISBinder implements Visitor { private AkibanInformationSchema ais; private String defaultSchemaName; private Deque<BindingContext> bindingContexts; private Set<QueryTreeNode> visited; private boolean resultColumnsAvailableBroadly; private boolean allowSubqueryMultipleColumns; private Set<ValueNode> havingClauses; private AISBinderContext context; private boolean expandViews; private FunctionDefined functionDefined; public AISBinder(AkibanInformationSchema ais, String defaultSchemaName) { this.ais = ais; this.defaultSchemaName = defaultSchemaName; } public String getDefaultSchemaName() { return defaultSchemaName; } public void setDefaultSchemaName(String defaultSchemaName) { this.defaultSchemaName = defaultSchemaName; } public boolean isResultColumnsAvailableBroadly() { return resultColumnsAvailableBroadly; } public void setResultColumnsAvailableBroadly(boolean resultColumnsAvailableBroadly) { this.resultColumnsAvailableBroadly = resultColumnsAvailableBroadly; } public boolean isAllowSubqueryMultipleColumns() { return allowSubqueryMultipleColumns; } public void setAllowSubqueryMultipleColumns(boolean allowSubqueryMultipleColumns) { this.allowSubqueryMultipleColumns = allowSubqueryMultipleColumns; } public interface FunctionDefined { public boolean isDefined(String name); } public void setFunctionDefined(FunctionDefined functionDefined) { this.functionDefined = functionDefined; } public AISBinderContext getContext() { return context; } protected void setContext(AISBinderContext context) { this.context = context; } public void bind(StatementNode stmt) throws StandardException { bind(stmt, true); } public void bind(QueryTreeNode node, boolean expandViews) throws StandardException { this.expandViews = expandViews; visited = new HashSet<>(); bindingContexts = new ArrayDeque<>(); havingClauses = new HashSet<>(); try { node.accept(this); } finally { visited = null; bindingContexts = null; } } /* Hierarchical Visitor */ public boolean visitBefore(QueryTreeNode node) { boolean first = visited.add(node); if (first) { switch (node.getNodeType()) { case NodeTypes.SUBQUERY_NODE: subqueryNode((SubqueryNode)node); break; case NodeTypes.SELECT_NODE: selectNode((SelectNode)node); break; case NodeTypes.COLUMN_REFERENCE: columnReference((ColumnReference)node); break; case NodeTypes.INSERT_NODE: case NodeTypes.UPDATE_NODE: case NodeTypes.DELETE_NODE: dmlModStatementNode((DMLModStatementNode)node); break; case NodeTypes.UNION_NODE: unionNode((UnionNode)node); break; case NodeTypes.JAVA_TO_SQL_VALUE_NODE: javaValueNode(((JavaToSQLValueNode)node).getJavaValueNode()); } } switch (node.getNodeType()) { case NodeTypes.CURSOR_NODE: case NodeTypes.DELETE_NODE: case NodeTypes.INSERT_NODE: case NodeTypes.UPDATE_NODE: pushBindingContext(((DMLStatementNode)node).getResultSetNode()); break; case NodeTypes.FROM_SUBQUERY: pushBindingContext(((FromSubquery)node).getSubquery()); break; case NodeTypes.SUBQUERY_NODE: pushBindingContext(((SubqueryNode)node).getResultSet()); break; case NodeTypes.ORDER_BY_LIST: case NodeTypes.GROUP_BY_LIST: getBindingContext().resultColumnsAvailableContext = node; break; default: if (havingClauses.contains(node)) // No special node type. getBindingContext().resultColumnsAvailableContext = node; break; } return first; } public void visitAfter(QueryTreeNode node) { switch (node.getNodeType()) { case NodeTypes.CURSOR_NODE: case NodeTypes.FROM_SUBQUERY: case NodeTypes.SUBQUERY_NODE: case NodeTypes.DELETE_NODE: case NodeTypes.INSERT_NODE: case NodeTypes.UPDATE_NODE: popBindingContext(); break; case NodeTypes.ORDER_BY_LIST: case NodeTypes.GROUP_BY_LIST: getBindingContext().resultColumnsAvailableContext = null; break; default: if (havingClauses.contains(node)) getBindingContext().resultColumnsAvailableContext = null; break; } } /* Specific node types */ protected void subqueryNode(SubqueryNode subqueryNode) { // The LHS of a subquery operator is bound in the outer context. if (subqueryNode.getLeftOperand() != null) { try { subqueryNode.getLeftOperand().accept(this); } catch (StandardException ex) { throw new SQLParserInternalException(ex); } } ResultSetNode resultSet = subqueryNode.getResultSet(); ResultColumnList resultColumns = resultSet.getResultColumns(); // The parser does not enforce the fact that a subquery can only // return a single column, so we must check here. if (resultColumns.size() != 1) { switch (subqueryNode.getSubqueryType()) { case IN: case NOT_IN: break; case EXPRESSION: if (allowSubqueryMultipleColumns) break; /* else falls through */ default: throw new SubqueryOneColumnException(); } } SubqueryNode.SubqueryType subqueryType = subqueryNode.getSubqueryType(); /* Verify the usage of "*" in the select list: * o Only valid in EXISTS subqueries * o If the AllResultColumn is qualified, then we have to verify * that the qualification is a valid exposed name. * NOTE: The exposed name can come from an outer query block. */ verifySelectStarSubquery(resultSet, subqueryType); /* For an EXISTS subquery: * o If the SELECT list is a "*", then we convert it to a true. * (We need to do the conversion since we don't want the "*" to * get expanded.) */ if (subqueryType == SubqueryNode.SubqueryType.EXISTS) { try { resultSet = setResultToBooleanTrueNode(resultSet); } catch (StandardException ex) { throw new SQLParserInternalException(ex); } subqueryNode.setResultSet(resultSet); } } protected void verifySelectStarSubquery(ResultSetNode resultSet, SubqueryNode.SubqueryType subqueryType) { if (resultSet instanceof SetOperatorNode) { SetOperatorNode setOperatorNode = (SetOperatorNode)resultSet; verifySelectStarSubquery(setOperatorNode.getLeftResultSet(), subqueryType); verifySelectStarSubquery(setOperatorNode.getRightResultSet(), subqueryType); return; } if (!(resultSet.getResultColumns().get(0) instanceof AllResultColumn)) { return; } // Select * currently only valid for EXISTS/NOT EXISTS. if ((subqueryType != SubqueryNode.SubqueryType.EXISTS) && (!allowSubqueryMultipleColumns || (subqueryType != SubqueryNode.SubqueryType.EXPRESSION))) { throw new SelectExistsErrorException (); } } /** * Set the result column for the subquery to a boolean true, * Useful for transformations such as * changing: * where exists (select ... from ...) * to: * where (select true from ...) * * NOTE: No transformation is performed if the ResultColumn.expression is * already the correct boolean constant. * * This method is used during binding of EXISTS predicates to map * a subquery's result column list into a single TRUE node. For * SELECT and VALUES subqueries this transformation is pretty * straightforward. But for set operators (ex. INTERSECT) we have * to do some extra work. To see why, assume we have the following * query: * * select * from ( values 'BAD' ) as T * where exists ((values 1) intersect (values 2)) * * If we treated the INTERSECT in this query the same way that we * treat SELECT/VALUES subqueries then the above query would get * transformed into: * * select * from ( values 'BAD' ) as T * where exists ((values TRUE) intersect (values TRUE)) * * Since both children of the INTERSECT would then have the same value, * the result of set operation would be a single value (TRUE), which * means the WHERE clause would evaluate to TRUE and thus the query * would return one row with value 'BAD'. That would be wrong. * * To avoid this problem, we internally wrap this SetOperatorNode * inside a "SELECT *" subquery and then we change the new SelectNode's * result column list (as opposed to *this* nodes' result column list) * to a singe boolean true node: * * select * from ( values 'BAD' ) as T where exists * SELECT TRUE FROM ((values 1) intersect (values 2)) * * In this case the left and right children of the INTERSECT retain * their values, which ensures that the result of the intersect * operation will be correct. Since (1 intersect 2) is an empty * result set, the internally generated SELECT node will return * zero rows, which in turn means the WHERE predicate will return * NULL (an empty result set from a SubqueryNode is treated as NULL * at execution time; see impl/sql/execute/AnyResultSet). Since * NULL is not the same as TRUE the query will correctly return * zero rows. DERBY-2370. * * @exception StandardException Thrown on error */ public ResultSetNode setResultToBooleanTrueNode(ResultSetNode resultSet) throws StandardException { NodeFactory nodeFactory = resultSet.getNodeFactory(); SQLParserContext parserContext = resultSet.getParserContext(); if (resultSet instanceof SetOperatorNode) { // First create a FromList to hold this node (and only this node). FromList fromList = (FromList)nodeFactory.getNode(NodeTypes.FROM_LIST, parserContext); fromList.addFromTable((SetOperatorNode)resultSet); // Now create a ResultColumnList that simply holds the "*". ResultColumnList rcl = (ResultColumnList) nodeFactory.getNode(NodeTypes.RESULT_COLUMN_LIST, parserContext); ResultColumn allResultColumn = (ResultColumn) nodeFactory.getNode(NodeTypes.ALL_RESULT_COLUMN, null, parserContext); rcl.addResultColumn(allResultColumn); /* Create a new SELECT node of the form: * SELECT * FROM <thisSetOperatorNode> */ resultSet = (ResultSetNode) nodeFactory.getNode(NodeTypes.SELECT_NODE, rcl, // ResultColumns null, // AGGREGATE list fromList, // FROM list null, // WHERE clause null, // GROUP BY list null, // having clause null, /* window list */ parserContext); /* And finally, transform the "*" in the new SELECT node * into a TRUE constant node. This ultimately gives us: * * SELECT TRUE FROM <thisSetOperatorNode> * * which has a single result column that is a boolean TRUE * constant. So we're done. */ } ResultColumnList resultColumns = resultSet.getResultColumns(); ResultColumn resultColumn = resultColumns.get(0); if (resultColumns.get(0) instanceof AllResultColumn) { resultColumn = (ResultColumn)nodeFactory.getNode(NodeTypes.RESULT_COLUMN, "", null, parserContext); } else if (resultColumn.getExpression().isBooleanTrue()) { // Nothing to do if query is already select TRUE ... return resultSet; } BooleanConstantNode booleanNode = (BooleanConstantNode) nodeFactory.getNode(NodeTypes.BOOLEAN_CONSTANT_NODE, Boolean.TRUE, parserContext); resultColumn.setExpression(booleanNode); resultColumn.setType(booleanNode.getType()); resultColumns.set(0, resultColumn); return resultSet; } protected void selectNode(SelectNode selectNode) { FromList fromList = selectNode.getFromList(); int size = fromList.size(); for (int i = 0; i < size; i++) { FromTable fromTable = fromList.get(i); FromTable newFromTable = fromTable(fromTable, false); if (newFromTable != fromTable) fromList.set(i, newFromTable); } for (int i = 0; i < size; i++) { addFromTable(fromList.get(i)); } expandAllsAndNameColumns(selectNode.getResultColumns(), fromList); if (selectNode.getHavingClause() != null) havingClauses.add(selectNode.getHavingClause()); } // Process a FROM list table, finding the table binding. protected FromTable fromTable(FromTable fromTable, boolean nullable) { switch (fromTable.getNodeType()) { case NodeTypes.FROM_BASE_TABLE: return fromBaseTable((FromBaseTable)fromTable, nullable); case NodeTypes.JOIN_NODE: return joinNode((JoinNode)fromTable, nullable); case NodeTypes.HALF_OUTER_JOIN_NODE: return joinNode((HalfOuterJoinNode)fromTable, nullable); case NodeTypes.FROM_SUBQUERY: return fromSubquery((FromSubquery)fromTable); default: // Subqueries in SELECT don't see earlier FROM list tables. try { return (FromTable)fromTable.accept(this); } catch (StandardException e) { throw new TableIsBadSubqueryException (fromTable.getOrigTableName().getSchemaName(), fromTable.getOrigTableName().getTableName(), e.getMessage()); } } } protected FromTable fromBaseTable(FromBaseTable fromBaseTable, boolean nullable) { TableName origName = fromBaseTable.getOrigTableName(); String schemaName = origName.getSchemaName(); if (schemaName == null) schemaName = defaultSchemaName; String tableName = origName.getTableName(); Columnar table = null; View view = ais.getView(schemaName, tableName); if (view != null) { if (!context.isAccessible(view.getName())) { view = null; } else if (expandViews) { ViewDefinition viewdef = context.getViewDefinition(view); FromSubquery viewSubquery; try { viewSubquery = viewdef.copySubquery(fromBaseTable.getParserContext()); } catch (StandardException ex) { throw new ViewHasBadSubqueryException(origName.toString(), ex.getMessage()); } if (fromBaseTable.getCorrelationName() != null) tableName = fromBaseTable.getCorrelationName(); viewSubquery.setCorrelationName(tableName); return fromTable(viewSubquery, false); } else { table = view; // Shallow reference within another view definition. } } if (table == null) table = lookupTableName(origName, schemaName, tableName); origName.setUserData(table); fromBaseTable.setUserData(new TableBinding(table, nullable)); return fromBaseTable; } protected FromTable joinNode(JoinNode joinNode, boolean nullable) { joinNode.setLeftResultSet(fromTable((FromTable)joinNode.getLeftResultSet(), nullable)); joinNode.setRightResultSet(fromTable((FromTable)joinNode.getRightResultSet(), nullable)); return joinNode; } protected FromTable joinNode(HalfOuterJoinNode joinNode, boolean nullable) { joinNode.setLeftResultSet(fromTable((FromTable)joinNode.getLeftResultSet(), nullable || joinNode.isRightOuterJoin())); joinNode.setRightResultSet(fromTable((FromTable)joinNode.getRightResultSet(), nullable || !joinNode.isRightOuterJoin())); return joinNode; } protected FromSubquery fromSubquery(FromSubquery fromSubquery) { // Do the subquery body first to get types, etc. try { fromSubquery.accept(this); if (fromSubquery.getResultColumns() == null) { ResultSetNode inner = fromSubquery.getSubquery(); ResultColumnList innerRCL = inner.getResultColumns(); if (innerRCL != null) { NodeFactory nodeFactory = fromSubquery.getNodeFactory(); SQLParserContext parserContext = fromSubquery.getParserContext(); ResultColumnList outerRCL = (ResultColumnList) nodeFactory.getNode(NodeTypes.RESULT_COLUMN_LIST, parserContext); int ncols = 0; for (ResultColumn innerColumn : innerRCL) { guaranteeColumnName(innerColumn); ValueNode valueNode = (ValueNode) nodeFactory.getNode(NodeTypes.VIRTUAL_COLUMN_NODE, inner, innerColumn, ++ncols, parserContext); ResultColumn outerColumn = (ResultColumn) nodeFactory.getNode(NodeTypes.RESULT_COLUMN, innerColumn.getName(), valueNode, parserContext); outerRCL.addResultColumn(outerColumn); //valueNode.setUserData(new ColumnBinding(inner, innerColumn)); } fromSubquery.setResultColumns(outerRCL); } } } catch (StandardException e) { throw new TableIsBadSubqueryException("", fromSubquery.getExposedName(), e.getMessage()); } return fromSubquery; } protected void addFromTable(FromTable fromTable) { if (fromTable instanceof JoinNode) { try { addJoinNode((JoinNode)fromTable); } catch (StandardException e) { throw new JoinNodeAdditionException (fromTable.getOrigTableName().getSchemaName(), fromTable.getOrigTableName().getTableName(), e.getMessage()); } return; } BindingContext bindingContext = getBindingContext(); bindingContext.tables.add(fromTable); if (fromTable.getCorrelationName() != null) { FromTable prevTable = bindingContext.correlationNames.put(fromTable.getCorrelationName(), fromTable); if ((prevTable != null) && bindingContext.tables.contains(prevTable)) { // Other occurrence in this same context. throw new CorrelationNameAlreadyUsedException(fromTable.getCorrelationName()); } } } protected void addJoinNode(JoinNode joinNode) throws StandardException { FromTable fromLeft = (FromTable)joinNode.getLeftResultSet(); FromTable fromRight = (FromTable)joinNode.getRightResultSet(); addFromTable(fromLeft); addFromTable(fromRight); if ((joinNode.getUsingClause() != null) || joinNode.isNaturalJoin()) { // Replace USING clause with equivalent equality predicates, all bound up. NodeFactory nodeFactory = joinNode.getNodeFactory(); SQLParserContext parserContext = joinNode.getParserContext(); ValueNode conditions = null; if (joinNode.getUsingClause() != null) { for (ResultColumn rc : joinNode.getUsingClause()) { String columnName = rc.getName(); ColumnBinding leftBinding = getColumnBinding(fromLeft, columnName); if (leftBinding == null) throw new NoSuchColumnException(columnName, rc); ColumnBinding rightBinding = getColumnBinding(fromRight, columnName); if (rightBinding == null) throw new NoSuchColumnException(columnName, rc); conditions = addJoinEquality(conditions, columnName, leftBinding, rightBinding, nodeFactory, parserContext); } } else if (joinNode.isNaturalJoin()) { Map<String,ColumnBinding> leftCols = new HashMap<>(); getUniqueColumnBindings(fromLeft, leftCols); Map<String,ColumnBinding> rightCols = new HashMap<>(); getUniqueColumnBindings(fromRight, rightCols); for (String columnName : leftCols.keySet()) { ColumnBinding rightBinding = rightCols.get(columnName); if (rightBinding == null) continue; ColumnBinding leftBinding = leftCols.get(columnName); conditions = addJoinEquality(conditions, columnName, leftBinding, rightBinding, nodeFactory, parserContext); } } if (joinNode.getJoinClause() == null) { joinNode.setJoinClause(conditions); } else { joinNode.setJoinClause((AndNode)nodeFactory.getNode(NodeTypes.AND_NODE, joinNode.getJoinClause(), conditions, parserContext)); } joinNode.setUsingClause(null); } // Take care of any remaining column bindings in the ON clause. if (joinNode.getJoinClause() != null) joinNode.getJoinClause().accept(this); } protected ValueNode addJoinEquality(ValueNode conditions, String columnName, ColumnBinding leftBinding, ColumnBinding rightBinding, NodeFactory nodeFactory, SQLParserContext parserContext) throws StandardException { ColumnReference leftCR = (ColumnReference) nodeFactory.getNode(NodeTypes.COLUMN_REFERENCE, columnName, leftBinding.getFromTable().getTableName(), parserContext); ColumnReference rightCR = (ColumnReference) nodeFactory.getNode(NodeTypes.COLUMN_REFERENCE, columnName, rightBinding.getFromTable().getTableName(), parserContext); ValueNode condition = (ValueNode) nodeFactory.getNode(NodeTypes.BINARY_EQUALS_OPERATOR_NODE, leftCR, rightCR, parserContext); if (conditions == null) { conditions = condition; } else { conditions = (AndNode)nodeFactory.getNode(NodeTypes.AND_NODE, conditions, condition, parserContext); } return conditions; } protected void columnReference(ColumnReference columnReference) { ColumnBinding columnBinding = (ColumnBinding)columnReference.getUserData(); if (columnBinding != null) return; String columnName = columnReference.getColumnName(); if (columnReference.getTableNameNode() != null) { FromTable fromTable = findFromTable(columnReference.getTableNameNode()); columnBinding = getColumnBinding(fromTable, columnName); if (columnBinding == null) throw new NoSuchColumnException(columnName, columnReference); } else { if (resultColumnsAvailable(getBindingContext().resultColumnsAvailableContext, columnReference)) { ResultColumnList resultColumns = getBindingContext().resultColumns; if (resultColumns != null) { ResultColumn resultColumn = resultColumns.getResultColumn(columnName); if (resultColumn != null) { if (resultColumn.getExpression() instanceof ColumnReference) { columnBinding = (ColumnBinding)((ColumnReference)resultColumn.getExpression()).getUserData(); } if (columnBinding == null) columnBinding = new ColumnBinding(null, resultColumn); } } } if (columnBinding == null) { boolean ambiguous = false; outer: for (BindingContext bindingContext : bindingContexts) { ColumnBinding contextBinding = null; for (FromTable fromTable : bindingContext.tables) { ColumnBinding tableBinding = getColumnBinding(fromTable, columnName); if (tableBinding != null) { if (contextBinding != null) { ambiguous = true; break outer; } contextBinding = tableBinding; } } if (contextBinding != null) { columnBinding = contextBinding; break; } } if (columnBinding == null) { if (ambiguous) throw new AmbiguousColumNameException(columnName, columnReference); else throw new NoSuchColumnException(columnName, columnReference); } } } columnReference.setUserData(columnBinding); } protected boolean resultColumnsAvailable(QueryTreeNode context, ColumnReference columnReference) { if (context == null) return false; if (!resultColumnsAvailableBroadly) { if (NodeTypes.ORDER_BY_LIST != context.getNodeType()) return false; // The column ref must be immediately in the order by list, not in a // sub-expression. for (OrderByColumn column : ((OrderByList)context)) { if (column.getExpression() == columnReference) { return true; } } return false; } return true; } protected Table lookupTableName(TableName origName, String schemaName, String tableName) { Table result = ais.getTable(schemaName, tableName); if ((result == null) || ((context != null) && !context.isAccessible(result.getName()))) throw new NoSuchTableException(schemaName, tableName, origName); return result; } protected FromTable findFromTable(TableName tableNameNode){ String schemaName = tableNameNode.getSchemaName(); String tableName = tableNameNode.getTableName(); if (schemaName == null) { FromTable fromTable = getBindingContext().correlationNames.get(tableName); if (fromTable != null) return fromTable; schemaName = defaultSchemaName; } for (BindingContext bindingContext : bindingContexts) { for (FromTable fromTable : bindingContext.tables) { if ((fromTable instanceof FromBaseTable) && // Not allowed to reference correlated by underlying name. (fromTable.getCorrelationName() == null)) { FromBaseTable fromBaseTable = (FromBaseTable)fromTable; TableBinding tableBinding = (TableBinding)fromBaseTable.getUserData(); assert (tableBinding != null) : "table not bound yet"; Columnar table = tableBinding.getTable(); if (table.getName().getSchemaName().equalsIgnoreCase(schemaName) && table.getName().getTableName().equalsIgnoreCase(tableName)) { return fromBaseTable; } } } } throw new NoSuchTableException(schemaName, tableName, tableNameNode); } protected void getUniqueColumnBindings(FromTable fromTable, Map<String,ColumnBinding> bindings) throws StandardException { if (fromTable instanceof FromBaseTable) { FromBaseTable fromBaseTable = (FromBaseTable)fromTable; TableBinding tableBinding = (TableBinding)fromBaseTable.getUserData(); assert (tableBinding != null) : "table not bound yet"; Columnar table = tableBinding.getTable(); for (Column column : table.getColumns()) { ColumnBinding prev = bindings.put(column.getName().toLowerCase(), new ColumnBinding(fromTable, column, tableBinding.isNullable())); if (prev != null) throw new StandardException("Duplicate column name " + column.getName() + " not allowed with NATURAL JOIN"); } } else if (fromTable instanceof FromSubquery) { FromSubquery fromSubquery = (FromSubquery)fromTable; for (ResultColumn resultColumn : fromSubquery.getResultColumns()) { ColumnBinding prev = bindings.put(resultColumn.getName().toLowerCase(), new ColumnBinding(fromTable, resultColumn)); if (prev != null) throw new StandardException("Duplicate column name " + resultColumn.getName() + " not allowed with NATURAL JOIN"); } } else if (fromTable instanceof JoinNode) { JoinNode joinNode = (JoinNode)fromTable; getUniqueColumnBindings((FromTable)joinNode.getLeftResultSet(), bindings); getUniqueColumnBindings((FromTable)joinNode.getRightResultSet(), bindings); } } protected ColumnBinding getColumnBinding(FromTable fromTable, String columnName) { if (fromTable instanceof FromBaseTable) { FromBaseTable fromBaseTable = (FromBaseTable)fromTable; TableBinding tableBinding = (TableBinding)fromBaseTable.getUserData(); assert (tableBinding != null) : "table not bound yet"; Columnar table = tableBinding.getTable(); Column column = table.getColumn(columnName); if (column == null) return null; return new ColumnBinding(fromTable, column, tableBinding.isNullable()); } else if (fromTable instanceof FromSubquery) { FromSubquery fromSubquery = (FromSubquery)fromTable; ResultColumnList columns = fromSubquery.getResultColumns(); if (columns == null) columns = fromSubquery.getSubquery().getResultColumns(); ResultColumn resultColumn = columns.getResultColumn(columnName); if (resultColumn == null) return null; return new ColumnBinding(fromTable, resultColumn); } else if (fromTable instanceof JoinNode) { JoinNode joinNode = (JoinNode)fromTable; ColumnBinding leftBinding = getColumnBinding((FromTable)joinNode.getLeftResultSet(), columnName); if (leftBinding != null) return leftBinding; return getColumnBinding((FromTable)joinNode.getRightResultSet(), columnName); } else { assert false; return null; } } /** * Expand any *'s in the ResultColumnList. In addition, we will guarantee that * each ResultColumn has a name. (All generated names will be unique across the * entire statement.) * * @exception StandardException Thrown on error */ public void expandAllsAndNameColumns(ResultColumnList rcl, FromList fromList) { if (rcl == null) return; boolean expanded = false; ResultColumnList allExpansion; TableName fullTableName; for (int index = 0; index < rcl.size(); index++) { ResultColumn rc = rcl.get(index); if (rc instanceof AllResultColumn) { AllResultColumn arc = (AllResultColumn)rc; expanded = true; fullTableName = arc.getTableNameObject(); boolean recursive = arc.isRecursive(); if (recursive && !allowSubqueryMultipleColumns) { throw new WholeGroupQueryException(); } allExpansion = expandAll(fullTableName, fromList, recursive); // Make sure that every column has a name. for (ResultColumn nrc : allExpansion) { guaranteeColumnName(nrc); } // Replace the AllResultColumn with the expanded list. rcl.remove(index); for (int inner = 0; inner < allExpansion.size(); inner++) { rcl.add(index + inner, allExpansion.get(inner)); } index += allExpansion.size() - 1; // TODO: This is where Derby remembered the original size in // case other things get added to the RCL. } else { // Make sure that every column has a name. guaranteeColumnName(rc); } } } /** * Generate a unique (across the entire statement) column name for unnamed * ResultColumns * * @exception StandardException Thrown on error */ protected void guaranteeColumnName(ResultColumn rc) { if (rc.getName() == null) { rc.setName(((SQLParser)rc.getParserContext()).generateColumnName()); rc.setNameGenerated(true); } } /** * Expand a "*" into the appropriate ResultColumnList. If the "*" * is unqualified it will expand into a list of all columns in all * of the base tables in the from list at the current nesting level; * otherwise it will expand into a list of all of the columns in the * base table that matches the qualification. * * @param allTableName The qualification on the "*" as a String * @param fromList The select list * * @return ResultColumnList representing expansion * * @exception StandardException Thrown on error */ protected ResultColumnList expandAll(TableName allTableName, FromList fromList, boolean recursive) { ResultColumnList resultColumnList = null; ResultColumnList tempRCList = null; for (FromTable fromTable : fromList) { tempRCList = getAllResultColumns(allTableName, fromTable, recursive); if (tempRCList == null) continue; /* Expand the column list and append to the list that * we will return. */ if (resultColumnList == null) resultColumnList = tempRCList; else resultColumnList.addAll(tempRCList); // If the "*" is qualified, then we can stop the expansion as // soon as we find the matching table. if (allTableName != null) break; } // Give an error if the qualification name did not match an exposed name. if (resultColumnList == null) { throw new NoSuchTableException(allTableName.getSchemaName(), allTableName.getTableName(), allTableName); } return resultColumnList; } protected ResultColumnList getAllResultColumns(TableName allTableName, ResultSetNode fromTable, boolean recursive) { try { switch (fromTable.getNodeType()) { case NodeTypes.FROM_BASE_TABLE: return getAllResultColumns(allTableName, (FromBaseTable)fromTable, recursive); case NodeTypes.JOIN_NODE: case NodeTypes.HALF_OUTER_JOIN_NODE: return getAllResultColumns(allTableName, (JoinNode)fromTable, recursive); case NodeTypes.FROM_SUBQUERY: return getAllResultColumns(allTableName, (FromSubquery)fromTable); default: return null; } } catch (StandardException ex) { throw new SQLParserInternalException(ex); } } protected ResultColumnList getAllResultColumns(TableName allTableName, FromBaseTable fromTable, boolean recursive) throws StandardException { TableName exposedName = fromTable.getExposedTableName(); if ((allTableName != null) && !allTableName.equals(exposedName)) return null; NodeFactory nodeFactory = fromTable.getNodeFactory(); SQLParserContext parserContext = fromTable.getParserContext(); ResultColumnList rcList = (ResultColumnList) nodeFactory.getNode(NodeTypes.RESULT_COLUMN_LIST, parserContext); TableBinding tableBinding = (TableBinding)fromTable.getUserData(); Columnar table = tableBinding.getTable(); for (Column column : table.getColumns()) { String columnName = column.getName(); ValueNode valueNode = (ValueNode) nodeFactory.getNode(NodeTypes.COLUMN_REFERENCE, columnName, exposedName, parserContext); ResultColumn resultColumn = (ResultColumn) nodeFactory.getNode(NodeTypes.RESULT_COLUMN, columnName, valueNode, parserContext); rcList.addResultColumn(resultColumn); // Easy to do binding right here. valueNode.setUserData(new ColumnBinding(fromTable, column, tableBinding.isNullable())); } if (recursive && (table instanceof Table)) { for (Join child : ((Table)table).getChildJoins()) { rcList.addResultColumn(childJoinSubquery(fromTable, child)); } } return rcList; } protected ResultColumnList getAllResultColumns(TableName allTableName, JoinNode fromJoin, boolean recursive) throws StandardException { ResultColumnList leftRCL = getAllResultColumns(allTableName, fromJoin.getLogicalLeftResultSet(), recursive); ResultColumnList rightRCL = getAllResultColumns(allTableName, fromJoin.getLogicalRightResultSet(), recursive); if (leftRCL == null) return rightRCL; else if (rightRCL == null) return leftRCL; if (fromJoin.getUsingClause() == null) { leftRCL.addAll(rightRCL); return leftRCL; } // USING is tricky case, since join columns do not repeat in expansion. ResultColumnList joinRCL = leftRCL.getJoinColumns(fromJoin.getUsingClause()); leftRCL.removeJoinColumns(fromJoin.getUsingClause()); joinRCL.addAll(leftRCL); rightRCL.removeJoinColumns(fromJoin.getUsingClause()); joinRCL.addAll(rightRCL); return joinRCL; } protected ResultColumnList getAllResultColumns(TableName allTableName, FromSubquery fromSubquery) throws StandardException { NodeFactory nodeFactory = fromSubquery.getNodeFactory(); SQLParserContext parserContext = fromSubquery.getParserContext(); TableName exposedName = (TableName) nodeFactory.getNode(NodeTypes.TABLE_NAME, null, fromSubquery.getExposedName(), parserContext); if ((allTableName != null) && !allTableName.equals(exposedName)) return null; ResultColumnList rcList = (ResultColumnList) nodeFactory.getNode(NodeTypes.RESULT_COLUMN_LIST, parserContext); for (ResultColumn resultColumn : fromSubquery.getResultColumns()) { String columnName = resultColumn.getName(); boolean isNameGenerated = resultColumn.isNameGenerated(); TableName tableName = exposedName; ValueNode valueNode = (ValueNode) nodeFactory.getNode(NodeTypes.COLUMN_REFERENCE, columnName, tableName, parserContext); resultColumn = (ResultColumn) nodeFactory.getNode(NodeTypes.RESULT_COLUMN, columnName, valueNode, parserContext); resultColumn.setNameGenerated(isNameGenerated); rcList.add(resultColumn); } return rcList; } /** Make a nested result set for this child (and so on recursively). */ protected ResultColumn childJoinSubquery(FromBaseTable parentTable, Join child) throws StandardException { NodeFactory nodeFactory = parentTable.getNodeFactory(); SQLParserContext parserContext = parentTable.getParserContext(); Table childAisTable = child.getChild(); Object childName = nodeFactory.getNode(NodeTypes.TABLE_NAME, childAisTable.getName().getSchemaName(), childAisTable.getName().getTableName(), parserContext); FromBaseTable childTable = (FromBaseTable) nodeFactory.getNode(NodeTypes.FROM_BASE_TABLE, childName, childAisTable.getName().getTableName(), null, null, null, parserContext); childTable.setUserData(new TableBinding(childAisTable, false)); ValueNode whereClause = null; for (JoinColumn join : child.getJoinColumns()) { ColumnReference parentPK = (ColumnReference) nodeFactory.getNode(NodeTypes.COLUMN_REFERENCE, join.getParent().getName(), parentTable.getTableName(), parserContext); parentPK.setUserData(new ColumnBinding(parentTable, join.getParent(), false)); ColumnReference childFK = (ColumnReference) nodeFactory.getNode(NodeTypes.COLUMN_REFERENCE, join.getChild().getName(), childName, parserContext); childFK.setUserData(new ColumnBinding(childTable, join.getChild(), false)); ValueNode equals = (ValueNode) nodeFactory.getNode(NodeTypes.BINARY_EQUALS_OPERATOR_NODE, parentPK, childFK, parserContext); if (whereClause == null) { whereClause = equals; } else { whereClause = (ValueNode) nodeFactory.getNode(NodeTypes.AND_NODE, whereClause, equals, parserContext); } } FromList fromList = (FromList) nodeFactory.getNode(NodeTypes.FROM_LIST, parserContext); fromList.addFromTable(childTable); ResultColumnList rcl = getAllResultColumns(null, childTable, true); SelectNode selectNode = (SelectNode) nodeFactory.getNode(NodeTypes.SELECT_NODE, rcl, null, fromList, whereClause, null, null, null, parserContext); SubqueryNode subquery = (SubqueryNode) nodeFactory.getNode(NodeTypes.SUBQUERY_NODE, selectNode, SubqueryNode.SubqueryType.EXPRESSION, null, null, null, null, parserContext); ResultColumn resultColumn = (ResultColumn) nodeFactory.getNode(NodeTypes.RESULT_COLUMN, childAisTable.getNameForOutput(), subquery, parserContext); return resultColumn; } protected void dmlModStatementNode(DMLModStatementNode node) { TableName tableName = node.getTargetTableName(); String schemaName = tableName.getSchemaName(); if (schemaName == null) schemaName = defaultSchemaName; Table table = lookupTableName(tableName, schemaName, tableName.getTableName()); tableName.setUserData(table); ResultColumnList targetColumns = null; if (node instanceof InsertNode) targetColumns = ((InsertNode)node).getTargetColumnList(); else targetColumns = node.getResultSetNode().getResultColumns(); if (targetColumns != null) { for (ResultColumn targetColumn : targetColumns) { ColumnReference columnReference = targetColumn.getReference(); String columnName = columnReference.getColumnName(); Column column = table.getColumn(columnName); if (column == null) throw new NoSuchColumnException(columnName, columnReference); ColumnBinding columnBinding = new ColumnBinding(null, column, false); columnReference.setUserData(columnBinding); } } if (node.getReturningList() != null) { ResultColumnList rcl = node.getReturningList(); NodeFactory nodeFactory = node.getNodeFactory(); SQLParserContext parserContext = node.getParserContext(); FromBaseTable fromTable = null; FromList fromList = null; try { fromTable = (FromBaseTable)nodeFactory.getNode(NodeTypes.FROM_BASE_TABLE, tableName, null, rcl, null, null, parserContext); fromTable.setUserData(new TableBinding(table, false)); fromList = (FromList)nodeFactory.getNode(NodeTypes.FROM_LIST, Boolean.FALSE, parserContext); fromList.add(fromTable); } catch (StandardException ex) { throw new SQLParserInternalException(ex); } node.setUserData(fromTable); for (int index = 0; index < rcl.size(); index ++) { ResultColumn rc = rcl.get(index); if (rc instanceof AllResultColumn) { AllResultColumn arc = (AllResultColumn)rc; ResultColumnList allExpansion = expandAll(tableName, fromList, false); // Make sure that every column has a name. for (ResultColumn nrc : allExpansion) { guaranteeColumnName(nrc); } // Replace the AllResultColumn with the expanded list. rcl.remove(index); for (int inner = 0; inner < allExpansion.size(); inner++) { rcl.add(index + inner, allExpansion.get(inner)); } index += allExpansion.size() - 1; } else { // Make sure that every column has a name. guaranteeColumnName(rc); } } pushBindingContext(null); getBindingContext().tables.add(fromTable); try { rcl.accept(this); } catch (StandardException ex) { throw new SQLParserInternalException(ex); } popBindingContext(); } } protected void unionNode(UnionNode node) { pushBindingContext(null); try { node.getLeftResultSet().accept(this); node.setResultColumns(node.copyResultColumnsFromLeft()); } catch (StandardException ex) { throw new SQLParserInternalException(ex); } popBindingContext(); pushBindingContext(null); try { node.getRightResultSet().accept(this); } catch (StandardException ex) { throw new SQLParserInternalException(ex); } popBindingContext(); } protected void javaValueNode(JavaValueNode javaValue) { if ((javaValue instanceof StaticMethodCallNode) && (functionDefined != null)) { StaticMethodCallNode methodCall = (StaticMethodCallNode)javaValue; Routine routine = null; if ((methodCall.getProcedureName() != null) && (methodCall.getProcedureName().hasSchema())) { // Qualified name is always a routine and an immediate error if not. routine = ais.getRoutine(methodCall.getProcedureName().getSchemaName(), methodCall.getProcedureName().getTableName()); if ((routine == null) || !context.isAccessible(routine.getName())) { throw new NoSuchFunctionException(methodCall.getProcedureName().toString()); } } else if (!functionDefined.isDefined(methodCall.getMethodName())) { // Unqualified only if not a built-in function and error deferred. routine = ais.getRoutine(defaultSchemaName, methodCall.getMethodName()); if ((routine != null) && !context.isAccessible(routine.getName())) { routine = null; } } if (routine != null) { if (routine.getReturnValue() == null) { throw new ProcedureCalledAsFunctionException(routine.getName()); } methodCall.setUserData(routine); } } } protected static class BindingContext { Collection<FromTable> tables = new ArrayList<>(); Map<String,FromTable> correlationNames = new HashMap<>(); ResultColumnList resultColumns; QueryTreeNode resultColumnsAvailableContext; } protected BindingContext getBindingContext() { return bindingContexts.peek(); } protected void pushBindingContext(ResultSetNode resultSet) { BindingContext next = new BindingContext(); if (!bindingContexts.isEmpty()) { // Initially inherit all the same correlation names (but can overwrite). next.correlationNames.putAll(bindingContexts.peek().correlationNames); } if (resultSet != null) { next.resultColumns = resultSet.getResultColumns(); } bindingContexts.push(next); } protected void popBindingContext() { bindingContexts.pop(); } /* Visitor interface. This is messy. Perhaps there should be an abstract class which makes the common Visitor interface into a Hierarchical Vistor pattern. */ // To understand why this works, see QueryTreeNode.accept(). public Visitable visit(Visitable node) { visitAfter((QueryTreeNode)node); return node; } public boolean skipChildren(Visitable node) { return ! visitBefore((QueryTreeNode)node); } public boolean visitChildrenFirst(Visitable node) { return true; } public boolean stopTraversal() { return false; } }
package com.intellij.ide.projectWizard; import com.intellij.framework.addSupport.FrameworkSupportInModuleProvider; import com.intellij.ide.util.PropertiesComponent; import com.intellij.ide.util.frameworkSupport.FrameworkRole; import com.intellij.ide.util.frameworkSupport.FrameworkSupportUtil; import com.intellij.ide.util.newProjectWizard.*; import com.intellij.ide.util.newProjectWizard.impl.FrameworkSupportModelBase; import com.intellij.ide.util.projectWizard.*; import com.intellij.ide.wizard.CommitStepException; import com.intellij.internal.statistic.eventLog.FeatureUsageData; import com.intellij.internal.statistic.service.fus.collectors.FUCounterUsageLogger; import com.intellij.internal.statistic.utils.PluginInfoDetectorKt; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.module.WebModuleTypeBase; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.roots.ui.configuration.ModulesProvider; import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesContainer; import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesContainerFactory; import com.intellij.openapi.ui.popup.ListItemDescriptorAdapter; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.text.StringUtil; import com.intellij.platform.ProjectTemplate; import com.intellij.platform.ProjectTemplateEP; import com.intellij.platform.ProjectTemplatesFactory; import com.intellij.platform.templates.*; import com.intellij.psi.impl.DebugUtil; import com.intellij.ui.CollectionListModel; import com.intellij.ui.ListSpeedSearch; import com.intellij.ui.SingleSelectionModel; import com.intellij.ui.components.JBLabel; import com.intellij.ui.components.JBList; import com.intellij.ui.popup.list.GroupedItemsListRenderer; import com.intellij.util.Function; import com.intellij.util.PlatformUtils; import com.intellij.util.containers.*; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.update.UiNotifyConnector; import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import java.awt.*; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.*; /** * @author Dmitry Avdeev */ @SuppressWarnings("unchecked") public class ProjectTypeStep extends ModuleWizardStep implements SettingsStep, Disposable { private static final Logger LOG = Logger.getInstance(ProjectTypeStep.class); private static final Convertor<FrameworkSupportInModuleProvider,String> PROVIDER_STRING_CONVERTOR = o -> o.getId(); private static final Function<FrameworkSupportNode, String> NODE_STRING_FUNCTION = FrameworkSupportNodeBase::getId; private static final String TEMPLATES_CARD = "templates card"; private static final String FRAMEWORKS_CARD = "frameworks card"; private static final String PROJECT_WIZARD_GROUP = "project.wizard.group"; private final WizardContext myContext; private final NewProjectWizard myWizard; private final ModulesProvider myModulesProvider; private final AddSupportForFrameworksPanel myFrameworksPanel; private final ModuleBuilder.ModuleConfigurationUpdater myConfigurationUpdater; private final Map<ProjectTemplate, ModuleBuilder> myBuilders = FactoryMap.create(key -> (ModuleBuilder)key.createModuleBuilder()); private final Map<String, ModuleWizardStep> myCustomSteps = new THashMap<>(); private final MultiMap<TemplatesGroup,ProjectTemplate> myTemplatesMap; private JPanel myPanel; private JPanel myOptionsPanel; private JBList<TemplatesGroup> myProjectTypeList; private ProjectTemplateList myTemplatesList; private JPanel myFrameworksPanelPlaceholder; private JPanel myHeaderPanel; private JBLabel myFrameworksLabel; @Nullable private ModuleWizardStep mySettingsStep; private String myCurrentCard; private TemplatesGroup myLastSelectedGroup; public ProjectTypeStep(WizardContext context, NewProjectWizard wizard, ModulesProvider modulesProvider) { myContext = context; myWizard = wizard; myTemplatesMap = new ConcurrentMultiMap<>(); final List<TemplatesGroup> groups = fillTemplatesMap(context); LOG.debug("groups=" + groups); myProjectTypeList.setModel(new CollectionListModel<>(groups)); myProjectTypeList.setSelectionModel(new SingleSelectionModel()); myProjectTypeList.addListSelectionListener(__ -> updateSelection()); myProjectTypeList.setCellRenderer(new GroupedItemsListRenderer<TemplatesGroup>(new ListItemDescriptorAdapter<TemplatesGroup>() { @Nullable @Override public String getTextFor(TemplatesGroup value) { return value.getName(); } @Nullable @Override public String getTooltipFor(TemplatesGroup value) { return value.getDescription(); } @Nullable @Override public Icon getIconFor(TemplatesGroup value) { return value.getIcon(); } @Override public boolean hasSeparatorAboveOf(TemplatesGroup value) { int index = groups.indexOf(value); if (index < 1) return false; TemplatesGroup upper = groups.get(index - 1); if (upper.getParentGroup() == null && value.getParentGroup() == null) return true; return !Comparing.equal(upper.getParentGroup(), value.getParentGroup()) && !Comparing.equal(upper.getName(), value.getParentGroup()); } }) { @Override protected JComponent createItemComponent() { JComponent component = super.createItemComponent(); myTextLabel.setBorder(JBUI.Borders.empty(3)); return component; } }); new ListSpeedSearch(myProjectTypeList) { @Override protected String getElementText(Object element) { return ((TemplatesGroup)element).getName(); } }; myModulesProvider = modulesProvider; Project project = context.getProject(); final LibrariesContainer container = LibrariesContainerFactory.createContainer(context, modulesProvider); FrameworkSupportModelBase model = new FrameworkSupportModelBase(project, null, container) { @NotNull @Override public String getBaseDirectoryForLibrariesPath() { ModuleBuilder builder = getSelectedBuilder(); return StringUtil.notNullize(builder.getContentEntryPath()); } @Override public ModuleBuilder getModuleBuilder() { return getSelectedBuilder(); } }; myFrameworksPanel = new AddSupportForFrameworksPanel(Collections.emptyList(), model, true, myHeaderPanel); Disposer.register(this, myFrameworksPanel); myFrameworksPanelPlaceholder.add(myFrameworksPanel.getMainPanel()); myFrameworksLabel.setLabelFor(myFrameworksPanel.getFrameworksTree()); myFrameworksLabel.setBorder(JBUI.Borders.empty(3)); myConfigurationUpdater = new ModuleBuilder.ModuleConfigurationUpdater() { @Override public void update(@NotNull Module module, @NotNull ModifiableRootModel rootModel) { if (isFrameworksMode()) { myFrameworksPanel.addSupport(module, rootModel); } } }; myProjectTypeList.getSelectionModel().addListSelectionListener(__ -> projectTypeChanged()); myTemplatesList.addListSelectionListener(__ -> updateSelection()); for (TemplatesGroup templatesGroup : myTemplatesMap.keySet()) { ModuleBuilder builder = templatesGroup.getModuleBuilder(); if (builder != null) { myWizard.getSequence().addStepsForBuilder(builder, context, modulesProvider); } for (ProjectTemplate template : myTemplatesMap.get(templatesGroup)) { myWizard.getSequence().addStepsForBuilder(myBuilders.get(template), context, modulesProvider); } } final String groupId = PropertiesComponent.getInstance().getValue(PROJECT_WIZARD_GROUP); LOG.debug("saved groupId=" + groupId); if (groupId != null) { TemplatesGroup group = ContainerUtil.find(groups, group1 -> groupId.equals(group1.getId())); if (group != null) { myProjectTypeList.setSelectedValue(group, true); } } if (myProjectTypeList.getSelectedValue() == null) { myProjectTypeList.setSelectedIndex(0); } myTemplatesList.restoreSelection(); } private static ModuleType getModuleType(TemplatesGroup group) { ModuleBuilder moduleBuilder = group.getModuleBuilder(); return moduleBuilder == null ? null : moduleBuilder.getModuleType(); } private static boolean matchFramework(ProjectCategory projectCategory, FrameworkSupportInModuleProvider framework) { FrameworkRole[] roles = framework.getRoles(); if (roles.length == 0) return true; List<FrameworkRole> acceptable = Arrays.asList(projectCategory.getAcceptableFrameworkRoles()); return ContainerUtil.intersects(Arrays.asList(roles), acceptable); } private static MultiMap<TemplatesGroup, ProjectTemplate> getTemplatesMap(WizardContext context) { ProjectTemplatesFactory[] factories = ProjectTemplatesFactory.EP_NAME.getExtensions(); final MultiMap<TemplatesGroup, ProjectTemplate> groups = new MultiMap<>(); for (ProjectTemplatesFactory factory : factories) { for (String group : factory.getGroups()) { ProjectTemplate[] templates = factory.createTemplates(group, context); List<ProjectTemplate> values = Arrays.asList(templates); if (!values.isEmpty()) { Icon icon = factory.getGroupIcon(group); String parentGroup = factory.getParentGroup(group); TemplatesGroup templatesGroup = new TemplatesGroup(group, null, icon, factory.getGroupWeight(group), parentGroup, group, null); templatesGroup.setPluginInfo(PluginInfoDetectorKt.getPluginInfo(factory.getClass())); groups.putValues(templatesGroup, values); } } } return groups; } private boolean isFrameworksMode() { return FRAMEWORKS_CARD.equals(myCurrentCard) && getSelectedBuilder().equals(myContext.getProjectBuilder()); } private List<TemplatesGroup> fillTemplatesMap(WizardContext context) { List<ModuleBuilder> builders = ModuleBuilder.getAllBuilders(); if (context.isCreatingNewProject()) { builders.add(new EmptyModuleBuilder()); } Map<String, TemplatesGroup> groupMap = new HashMap<>(); for (ModuleBuilder builder : builders) { BuilderBasedTemplate template = new BuilderBasedTemplate(builder); if (builder.isTemplate()) { TemplatesGroup group = groupMap.get(builder.getGroupName()); if (group == null) { group = new TemplatesGroup(builder); } myTemplatesMap.putValue(group, template); } else { TemplatesGroup group = new TemplatesGroup(builder); groupMap.put(group.getName(), group); myTemplatesMap.put(group, new ArrayList<>()); } } MultiMap<TemplatesGroup, ProjectTemplate> map = getTemplatesMap(context); myTemplatesMap.putAllValues(map); for (ProjectCategory category : ProjectCategory.EXTENSION_POINT_NAME.getExtensions()) { TemplatesGroup group = new TemplatesGroup(category); myTemplatesMap.remove(group); myTemplatesMap.put(group, new ArrayList<>()); } if (context.isCreatingNewProject()) { MultiMap<String, ProjectTemplate> localTemplates = loadLocalTemplates(); for (TemplatesGroup group : myTemplatesMap.keySet()) { myTemplatesMap.putValues(group, localTemplates.get(group.getId())); } } List<TemplatesGroup> groups = new ArrayList<>(myTemplatesMap.keySet()); // sorting by module type popularity final MultiMap<ModuleType, TemplatesGroup> moduleTypes = new MultiMap<>(); for (TemplatesGroup group : groups) { ModuleType type = getModuleType(group); moduleTypes.putValue(type, group); } Collections.sort(groups, (o1, o2) -> { int i = o2.getWeight() - o1.getWeight(); if (i != 0) return i; int i1 = moduleTypes.get(getModuleType(o2)).size() - moduleTypes.get(getModuleType(o1)).size(); if (i1 != 0) return i1; return o1.compareTo(o2); }); Set<String> groupNames = ContainerUtil.map2Set(groups, TemplatesGroup::getParentGroup); // move subgroups MultiMap<String, TemplatesGroup> subGroups = new MultiMap<>(); for (ListIterator<TemplatesGroup> iterator = groups.listIterator(); iterator.hasNext(); ) { TemplatesGroup group = iterator.next(); String parentGroup = group.getParentGroup(); if (parentGroup != null && groupNames.contains(parentGroup) && !group.getName().equals(parentGroup) && groupMap.containsKey(parentGroup)) { subGroups.putValue(parentGroup, group); iterator.remove(); } } for (ListIterator<TemplatesGroup> iterator = groups.listIterator(); iterator.hasNext(); ) { TemplatesGroup group = iterator.next(); for (TemplatesGroup subGroup : subGroups.get(group.getName())) { iterator.add(subGroup); } } // remove Static Web group in IDEA Community if no specific templates found (IDEA-120593) if (PlatformUtils.isIdeaCommunity()) { for (ListIterator<TemplatesGroup> iterator = groups.listIterator(); iterator.hasNext(); ) { TemplatesGroup group = iterator.next(); if (WebModuleTypeBase.WEB_MODULE.equals(group.getId()) && myTemplatesMap.get(group).isEmpty()) { iterator.remove(); break; } } } return groups; } // new TemplatesGroup selected private void projectTypeChanged() { TemplatesGroup group = getSelectedGroup(); if (group == null || group == myLastSelectedGroup) return; myLastSelectedGroup = group; PropertiesComponent.getInstance().setValue(PROJECT_WIZARD_GROUP, group.getId() ); if (LOG.isDebugEnabled()) { LOG.debug("projectTypeChanged: " + group.getId() + " " + DebugUtil.currentStackTrace()); } ModuleBuilder groupModuleBuilder = group.getModuleBuilder(); mySettingsStep = null; myHeaderPanel.removeAll(); if (groupModuleBuilder != null && groupModuleBuilder.getModuleType() != null) { mySettingsStep = groupModuleBuilder.modifyProjectTypeStep(this); } if (groupModuleBuilder == null || groupModuleBuilder.isTemplateBased()) { showTemplates(group); } else if (!showCustomOptions(groupModuleBuilder)){ List<FrameworkSupportInModuleProvider> providers = FrameworkSupportUtil.getProviders(groupModuleBuilder); final ProjectCategory category = group.getProjectCategory(); if (category != null) { List<FrameworkSupportInModuleProvider> filtered = ContainerUtil.filter(providers, provider -> matchFramework(category, provider)); // add associated Map<String, FrameworkSupportInModuleProvider> map = ContainerUtil.newMapFromValues(providers.iterator(), PROVIDER_STRING_CONVERTOR); Set<FrameworkSupportInModuleProvider> set = new HashSet<>(filtered); for (FrameworkSupportInModuleProvider provider : filtered) { for (FrameworkSupportInModuleProvider.FrameworkDependency depId : provider.getDependenciesFrameworkIds()) { FrameworkSupportInModuleProvider dependency = map.get(depId.getFrameworkId()); if (dependency == null) { if (!depId.isOptional()) { LOG.error("Cannot find provider '" + depId.getFrameworkId() + "' which is required for '" + provider.getId() + "'"); } continue; } set.add(dependency); } } myFrameworksPanel.setProviders(new ArrayList<>(set), new HashSet<>(Arrays.asList(category.getAssociatedFrameworkIds())), new HashSet<>(Arrays.asList(category.getPreselectedFrameworkIds()))); } else { myFrameworksPanel.setProviders(providers); } getSelectedBuilder().addModuleConfigurationUpdater(myConfigurationUpdater); showCard(FRAMEWORKS_CARD); } myHeaderPanel.setVisible(myHeaderPanel.getComponentCount() > 0); // align header labels List<JLabel> labels = UIUtil.findComponentsOfType(myHeaderPanel, JLabel.class); int width = 0; for (JLabel label : labels) { int width1 = label.getPreferredSize().width; width = Math.max(width, width1); } for (JLabel label : labels) { label.setPreferredSize(new Dimension(width, label.getPreferredSize().height)); } myHeaderPanel.revalidate(); myHeaderPanel.repaint(); updateSelection(); } private void showCard(String card) { ((CardLayout)myOptionsPanel.getLayout()).show(myOptionsPanel, card); myCurrentCard = card; } private void showTemplates(TemplatesGroup group) { Collection<ProjectTemplate> templates = myTemplatesMap.get(group); setTemplatesList(group, templates, false); showCard(TEMPLATES_CARD); } private void setTemplatesList(TemplatesGroup group, Collection<? extends ProjectTemplate> templates, boolean preserveSelection) { List<ProjectTemplate> list = new ArrayList<>(templates); ModuleBuilder moduleBuilder = group.getModuleBuilder(); if (moduleBuilder != null && !(moduleBuilder instanceof TemplateModuleBuilder)) { list.add(0, new BuilderBasedTemplate(moduleBuilder)); } myTemplatesList.setTemplates(list, preserveSelection); } private boolean showCustomOptions(@NotNull ModuleBuilder builder) { String card = builder.getBuilderId(); if (!myCustomSteps.containsKey(card)) { ModuleWizardStep step = builder.getCustomOptionsStep(myContext, this); if (step == null) return false; step.updateStep(); myCustomSteps.put(card, step); myOptionsPanel.add(step.getComponent(), card); } showCard(card); return true; } @Nullable private ModuleWizardStep getCustomStep() { return myCustomSteps.get(myCurrentCard); } private TemplatesGroup getSelectedGroup() { return myProjectTypeList.getSelectedValue(); } @Nullable private ProjectTemplate getSelectedTemplate() { return myCurrentCard == TEMPLATES_CARD ? myTemplatesList.getSelectedTemplate() : null; } private ModuleBuilder getSelectedBuilder() { ProjectTemplate template = getSelectedTemplate(); if (template != null) { return myBuilders.get(template); } return getSelectedGroup().getModuleBuilder(); } public Collection<ProjectTemplate> getAvailableTemplates() { if (myCurrentCard != FRAMEWORKS_CARD) { return Collections.emptyList(); } else { Collection<ProjectTemplate> templates = myTemplatesMap.get(getSelectedGroup()); List<FrameworkSupportNode> nodes = myFrameworksPanel.getSelectedNodes(); if (nodes.isEmpty()) return templates; final List<String> selectedFrameworks = ContainerUtil.map(nodes, NODE_STRING_FUNCTION); return ContainerUtil.filter(templates, template -> { if (!(template instanceof ArchivedProjectTemplate)) return true; List<String> frameworks = ((ArchivedProjectTemplate)template).getFrameworks(); return frameworks.containsAll(selectedFrameworks); }); } } @Override public void onWizardFinished() throws CommitStepException { if (isFrameworksMode()) { boolean ok = myFrameworksPanel.downloadLibraries(myWizard.getContentComponent()); if (!ok) { throw new CommitStepException(null); } } reportStatistics("finish"); } @Override public JComponent getComponent() { return myPanel; } @Override public void updateDataModel() { ModuleBuilder builder = getSelectedBuilder(); if (builder != null) { myWizard.getSequence().addStepsForBuilder(builder, myContext, myModulesProvider); } ModuleWizardStep step = getCustomStep(); if (step != null) { step.updateDataModel(); } if (mySettingsStep != null) { mySettingsStep.updateDataModel(); } } @Override public boolean validate() throws ConfigurationException { if (mySettingsStep != null) { if (!mySettingsStep.validate()) return false; } ModuleWizardStep step = getCustomStep(); if (step != null && !step.validate()) { return false; } if (isFrameworksMode() && !myFrameworksPanel.validate()) { return false; } return super.validate(); } @Override public JComponent getPreferredFocusedComponent() { return myProjectTypeList; } @Override public void dispose() { myLastSelectedGroup = null; mySettingsStep = null; myTemplatesMap.clear(); myBuilders.clear(); myCustomSteps.clear(); } @Override public void disposeUIResources() { Disposer.dispose(this); } private MultiMap<String, ProjectTemplate> loadLocalTemplates() { ConcurrentMultiMap<String, ProjectTemplate> map = new ConcurrentMultiMap<>(); ProjectTemplateEP[] extensions = ProjectTemplateEP.EP_NAME.getExtensions(); for (ProjectTemplateEP ep : extensions) { ClassLoader classLoader = ep.getLoaderForClass(); URL url = classLoader.getResource(ep.templatePath); if (url != null) { try { LocalArchivedTemplate template = new LocalArchivedTemplate(url, classLoader); if (ep.category) { TemplateBasedCategory category = new TemplateBasedCategory(template, ep.projectType); myTemplatesMap.putValue(new TemplatesGroup(category), template); } else { map.putValue(ep.projectType, template); } } catch (Exception e) { LOG.error("Error loading template from URL '" + ep.templatePath + "' [Plugin: " + ep.getPluginId() + "]", e); } } else { LOG.error("Can't find resource for project template '" + ep.templatePath + "' [Plugin: " + ep.getPluginId() + "]"); } } return map; } void loadRemoteTemplates(final ChooseTemplateStep chooseTemplateStep) { if (!ApplicationManager.getApplication().isUnitTestMode()) { UiNotifyConnector.doWhenFirstShown(myPanel, () -> startLoadingRemoteTemplates(chooseTemplateStep)); } else { startLoadingRemoteTemplates(chooseTemplateStep); } } private void startLoadingRemoteTemplates(ChooseTemplateStep chooseTemplateStep) { myTemplatesList.setPaintBusy(true); chooseTemplateStep.getTemplateList().setPaintBusy(true); ProgressManager.getInstance().run(new Task.Backgroundable(myContext.getProject(), "Loading Templates") { @Override public void run(@NotNull ProgressIndicator indicator) { RemoteTemplatesFactory factory = new RemoteTemplatesFactory(); for (String group : factory.getGroups()) { ProjectTemplate[] templates = factory.createTemplates(group, myContext); for (ProjectTemplate template : templates) { String id = ((ArchivedProjectTemplate)template).getCategory(); for (TemplatesGroup templatesGroup : myTemplatesMap.keySet()) { if (Comparing.equal(id, templatesGroup.getId()) || Comparing.equal(group, templatesGroup.getName())) { myTemplatesMap.putValue(templatesGroup, template); } } } } } @Override public void onSuccess() { super.onSuccess(); TemplatesGroup group = getSelectedGroup(); if (group == null) return; Collection<ProjectTemplate> templates = myTemplatesMap.get(group); setTemplatesList(group, templates, true); chooseTemplateStep.updateStep(); } @Override public void onFinished() { myTemplatesList.setPaintBusy(false); chooseTemplateStep.getTemplateList().setPaintBusy(false); } }); } private void updateSelection() { ProjectTemplate template = getSelectedTemplate(); if (template != null) { myContext.setProjectTemplate(template); } ModuleBuilder builder = getSelectedBuilder(); LOG.debug("builder=" + builder + "; template=" + template + "; group=" + getSelectedGroup() + "; groupIndex=" + myProjectTypeList.getMinSelectionIndex()); myContext.setProjectBuilder(builder); if (builder != null) { myWizard.getSequence().setType(builder.getBuilderId()); } myWizard.setDelegate(builder instanceof WizardDelegate ? (WizardDelegate)builder : null); myWizard.updateWizardButtons(); } @TestOnly public String availableTemplateGroupsToString() { ListModel model = myProjectTypeList.getModel(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < model.getSize(); i++) { if (builder.length() > 0) { builder.append(", "); } builder.append(((TemplatesGroup)model.getElementAt(i)).getName()); } return builder.toString(); } @TestOnly public boolean setSelectedTemplate(@NotNull String group, @Nullable String name) { ListModel model = myProjectTypeList.getModel(); for (int i = 0; i < model.getSize(); i++) { TemplatesGroup templatesGroup = (TemplatesGroup)model.getElementAt(i); if (group.equals(templatesGroup.getName())) { myProjectTypeList.setSelectedIndex(i); if (name == null) { return getSelectedGroup().getName().equals(group); } else { setTemplatesList(templatesGroup, myTemplatesMap.get(templatesGroup), false); return myTemplatesList.setSelectedTemplate(name); } } } return false; } public static void resetGroupForTests() { PropertiesComponent.getInstance().setValue(PROJECT_WIZARD_GROUP, null); } @TestOnly public AddSupportForFrameworksPanel getFrameworksPanel() { return myFrameworksPanel; } @Override public WizardContext getContext() { return myContext; } @Override public void addSettingsField(@NotNull String label, @NotNull JComponent field) { ProjectSettingsStep.addField(label, field, myHeaderPanel); } @Override public void addSettingsComponent(@NotNull JComponent component) { } @Override public void addExpertPanel(@NotNull JComponent panel) { } @Override public void addExpertField(@NotNull String label, @NotNull JComponent field) { } @Override public JTextField getModuleNameField() { return null; } @Override public String getHelpId() { if (getCustomStep() != null && getCustomStep().getHelpId() != null) { return getCustomStep().getHelpId(); } return myContext.isCreatingNewProject() ? "Project_Category_and_Options" : "Module_Category_and_Options"; } @Override public void onStepLeaving() { reportStatistics("attempt"); } private void reportStatistics(String eventId) { TemplatesGroup group = myProjectTypeList.getSelectedValue(); FeatureUsageData data = new FeatureUsageData(); data.addData("projectType", group.getId()); data.addPluginInfo(group.getPluginInfo()); myFrameworksPanel.reportSelectedFrameworks(eventId, data); ModuleWizardStep step = getCustomStep(); if (step instanceof StatisticsAwareModuleWizardStep) { ((StatisticsAwareModuleWizardStep) step).addCustomFeatureUsageData(eventId, data); } FUCounterUsageLogger.getInstance().logEvent("new.project.wizard", eventId, data); } }
package com.github.marschal.svndiffstat; import java.util.Date; import org.jfree.chart.axis.DateTickUnitType; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.Week; import org.joda.time.DateTime; import org.joda.time.Days; import org.joda.time.LocalDate; import org.joda.time.Months; import static org.jfree.chart.axis.DateTickUnitType.DAY; import static org.jfree.chart.axis.DateTickUnitType.MONTH; import static org.jfree.chart.axis.DateTickUnitType.YEAR; import static org.joda.time.DateTimeConstants.MONDAY; final class YearWeek extends TimeAxisKey implements Comparable<YearWeek> { private final short year; private final byte week; YearWeek(short year, byte week) { this.year = year; this.week = week; } static final class YearMonthFactory implements TimeAxisKeyFactory { @Override public YearWeek fromDate(Date date) { return YearWeek.fromDate(date); } } static YearWeek fromDate(Date date) { LocalDate localDate = new DateTime(date.getTime()).toLocalDate(); return fromLocalDate(localDate); } static YearWeek fromLocalDate(LocalDate localDate) { return new YearWeek((short) localDate.getWeekyear(), (byte) localDate.getWeekOfWeekyear()); } @Override RegularTimePeriod toPeriod() { return new Week(this.week, this.year); } LocalDate toLocalDate() { // TODO is this really correct for end of year / start year // split weeks? return new LocalDate() .withWeekyear(this.year) .withWeekOfWeekyear(this.week) .withDayOfWeek(MONDAY); } @Override int unitsBetween(TimeAxisKey key, DateTickUnitType type) { YearWeek other = (YearWeek) key; if (type == YEAR) { return other.year - this.year; } else if (type == MONTH) { Months monthsBetween = Months.monthsBetween(this.toLocalDate(), other.toLocalDate()); return monthsBetween.getMonths(); } else if (type == DAY) { Days daysBetween = Days.daysBetween(this.toLocalDate(), other.toLocalDate()); return daysBetween.getDays(); } else { throw new IllegalArgumentException("unsupported tick type: " + type); } } @Override YearWeek previous() { LocalDate localDate = this.toLocalDate(); int week = localDate.getWeekOfWeekyear(); if (week == localDate.weekOfWeekyear().getMinimumValue()) { LocalDate previoursYear = localDate.withWeekyear(localDate.getWeekyear() - 1); return fromLocalDate(previoursYear.withWeekOfWeekyear(previoursYear.weekOfWeekyear().getMaximumValue())); } else { return fromLocalDate(localDate.withWeekOfWeekyear(week - 1)); } } @Override YearWeek next() { LocalDate localDate = this.toLocalDate(); int week = localDate.getWeekOfWeekyear(); if (week == localDate.weekOfWeekyear().getMaximumValue()) { LocalDate nextYear = localDate.withWeekyear(localDate.getWeekyear() + 1); return fromLocalDate(nextYear.withWeekOfWeekyear(nextYear.weekOfWeekyear().getMinimumValue())); } else { return fromLocalDate(localDate.withWeekOfWeekyear(week + 1)); } } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof YearWeek)) { return false; } YearWeek other = (YearWeek) obj; return this.year == other.year && this.week == other.week; } @Override public int hashCode() { // this should be a perfect hash function (no collisions before modulo / shift / divide) return this.year << 8 | this.week; } @Override public int compareTo(YearWeek o) { int yearDiff = this.year - o.year; if (yearDiff != 0) { return yearDiff; } return this.week - o.week; } @Override public String toString() { return "" + this.year + '-' + this.week; } }
package com.github.mreutegg.laszip4j.clib; import com.github.mreutegg.laszip4j.laszip.MyDefs; import java.io.BufferedOutputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.io.RandomAccessFile; public final class Cstdio { private Cstdio() { } public static void fprintf(PrintStream ps, String msg, Object... args) { ps.printf(msg, args); } public static int fputc(int b, OutputStream out) { try { out.write(b); return b; } catch (IOException e) { return -1; } } public static InputStream fopenR(char[] filename, String mode) { return fopenR(new String(filename), mode); } public static InputStream fopenR(String filename, String mode) { File f = new File(filename); if (f.exists() && !f.delete()) { return null; } try { if (f.createNewFile()) { return new FileInputStream(filename); } } catch (IOException ignore) { } return null; } public static OutputStream fopen(String filename, String mode) { File f = new File(filename); if (f.exists() && !f.delete()) { return null; } try { return new BufferedOutputStream(new FileOutputStream(f)); } catch (FileNotFoundException e) { return null; } } public static OutputStream fopen(char[] filename, String mode) { return fopen(new String(filename), mode); } public static RandomAccessFile fopenRAF(char[] filename, String mode) { File f = new File(new String(filename)); if (mode.contains("w") && f.exists() && !f.delete()) { return null; } try { mode = mode.replace("b", ""); return new RandomAccessFile(f, mode); } catch (FileNotFoundException e) { return null; } } public static int fclose(Closeable c) { try { c.close(); return 0; } catch (IOException e) { return -1; } } public static long ftell(PrintStream file) { return -1; } public static long ftell(RandomAccessFile file) { try { return file.getFilePointer(); } catch (IOException e) { return -1; } } public static int sprintf(StringBuilder str, String format, Object... args) { String s = String.format(format, args); str.append(s); return s.length(); } public static int sprintf(byte[] str, String format, Object... args) { StringBuilder sb = new StringBuilder(); sprintf(sb, format, args); byte[] data = MyDefs.asByteArray(sb.toString()); System.arraycopy(data, 0, str, 0, data.length); str[data.length] = '\0'; return sb.length(); } public static int sprintf(char[] str, String format, Object... args) { return sprintf(str, 0, format, args); } public static int sprintf(char[] str, int offset, String format, Object... args) { String s = String.format(format, args); System.arraycopy(s.toCharArray(), 0, str, offset, s.length()); str[offset + s.length()] = '\0'; return s.length(); } }
package com.slugterra.inventory; import com.slugterra.item.slugs.ItemSlug; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.text.ITextComponent; public class SlugRackInventory implements IInventory { private final String name = "Slug Rack"; private final String tagName = "SlugRack"; /** Define the inventory size here for easy reference */ public static final int INV_SIZE = 20; /** Inventory's size must be same as number of slots you add to the Container class */ private ItemStack[] inventory = new ItemStack[INV_SIZE]; public SlugRackInventory() { } @Override public int getSizeInventory() { return inventory.length; } @Override public ItemStack getStackInSlot(int slot) { return inventory[slot]; } @Override public ItemStack decrStackSize(int slot, int amount) { ItemStack stack = getStackInSlot(slot); if (stack != ItemStack.EMPTY) { if (stack.getCount() > amount) { stack = stack.splitStack(amount); if (stack.getCount() == 0) { setInventorySlotContents(slot, ItemStack.EMPTY); } } else { setInventorySlotContents(slot, ItemStack.EMPTY); } this.markDirty(); } return stack; } @Override public void setInventorySlotContents(int slot, ItemStack itemstack) { this.inventory[slot] = itemstack; if (itemstack != ItemStack.EMPTY && itemstack.getCount() <= this.getInventoryStackLimit()) { itemstack.setCount(this.getInventoryStackLimit()); } this.markDirty(); } @Override public String getName() { return name; } @Override public boolean hasCustomName() { return name.length() > 0; } @Override public int getInventoryStackLimit() { return 1; } @Override public void markDirty() { for (int i = 0; i < this.getSizeInventory(); ++i) { if (this.getStackInSlot(i) != ItemStack.EMPTY && this.getStackInSlot(i).getCount() == 0){ this.setInventorySlotContents(i, ItemStack.EMPTY); } } } @Override public boolean isUsableByPlayer(EntityPlayer entityplayer) { return true; } @Override public void openInventory(EntityPlayer player) {} @Override public void closeInventory(EntityPlayer player) {} /** * This method doesn't seem to do what it claims to do, as * items can still be left-clicked and placed in the inventory * even when this returns false */ @Override public boolean isItemValidForSlot(int slot, ItemStack itemstack) { return itemstack.getItem() instanceof ItemSlug; } public void writeToNBT(NBTTagCompound compound) { NBTTagList items = new NBTTagList(); for (int i = 0; i < getSizeInventory(); ++i) { if (getStackInSlot(i) != null) { NBTTagCompound item = new NBTTagCompound(); item.setByte("Slot", (byte) i); getStackInSlot(i).writeToNBT(item); items.appendTag(item); } } compound.setTag(tagName, items); } public void readFromNBT(NBTTagCompound compound) { NBTTagList items = compound.getTagList(tagName, 10); this.inventory = new ItemStack[this.INV_SIZE]; for (int i = 0; i < items.tagCount(); ++i) { NBTTagCompound item = (NBTTagCompound) items.getCompoundTagAt(i); byte slot = item.getByte("Slot"); if (slot >= 0 && slot < getSizeInventory()) { inventory[slot] = new ItemStack(item); } } } @Override public ITextComponent getDisplayName() { return null; } @Override public boolean isEmpty() { return false; } @Override public ItemStack removeStackFromSlot(int index) { inventory[index] = ItemStack.EMPTY; return ItemStack.EMPTY; } @Override public int getField(int id) { return id; } @Override public void setField(int id, int value) { } @Override public int getFieldCount() { return 0; } @Override public void clear() { } }
package org.griphyn.cPlanner.transfer.sls; import org.griphyn.cPlanner.classes.PlannerOptions; import org.griphyn.cPlanner.classes.PegasusBag; import org.griphyn.cPlanner.transfer.SLS; import org.griphyn.cPlanner.common.PegasusProperties; import org.griphyn.common.util.DynamicLoader; /** * A factory class to load the appropriate type of SLS Implementation to do * the Second Level Staging. * * @author Karan Vahi * @version $Revision$ */ public class SLSFactory { /** * The default package where the all the implementing classes are supposed to * reside. */ public static final String DEFAULT_PACKAGE_NAME = "org.griphyn.cPlanner.transfer.sls"; /** * The name of the class implementing the condor code generator. */ public static final String DEFAULT_SLS_IMPL_CLASS = "Transfer"; /** * This method loads the appropriate implementing code generator as specified * by the user at runtime. If the megadag mode is specified in the options, * then that is used to load the implementing class, overriding the submit * mode specified in the properties file. * * * @param bag the bag of initialization objects. * * @return the instance of the class implementing this interface. * * @exception CodeGeneratorFactoryException that nests any error that * might occur during the instantiation of the implementation. * * @see #DEFAULT_PACKAGE_NAME * @see org.griphyn.cPlanner.common.PegasusProperties#getDAXCallback() * * @throws SLSFactoryException */ public static SLS loadInstance( PegasusBag bag ) throws SLSFactoryException{ PegasusProperties properties = bag.getPegasusProperties(); PlannerOptions options = bag.getPlannerOptions(); //sanity check if(properties == null){ throw new SLSFactoryException( "Invalid properties passed" ); } if(options == null){ throw new SLSFactoryException( "Invalid Options specified" ); } String className = properties.getSLSTransferImplementation(); if( className == null ){ className = DEFAULT_SLS_IMPL_CLASS; //to be picked up from properties eventually } return loadInstance( bag, className ); } /** * This method loads the appropriate code generator as specified by the * user at runtime. * * * @param bag the bag of initialization objects. * @param className the name of the implementing class. * * @return the instance of the class implementing this interface. * * @exception CodeGeneratorFactoryException that nests any error that * might occur during the instantiation of the implementation. * * @see #DEFAULT_PACKAGE_NAME * * @throws SLSFactoryException */ public static SLS loadInstance( PegasusBag bag, String className) throws SLSFactoryException{ PegasusProperties properties = bag.getPegasusProperties(); PlannerOptions options = bag.getPlannerOptions(); //sanity check if (properties == null) { throw new SLSFactoryException( "Invalid properties passed" ); } if (className == null) { throw new SLSFactoryException( "Invalid className specified" ); } //prepend the package name if classname is actually just a basename className = (className.indexOf('.') == -1) ? //pick up from the default package DEFAULT_PACKAGE_NAME + "." + className : //load directly className; //try loading the class dynamically SLS sls = null; try { DynamicLoader dl = new DynamicLoader( className ); sls = ( SLS ) dl.instantiate( new Object[0] ); //initialize the loaded code generator sls.initialize( bag ); } catch ( Exception e ) { throw new SLSFactoryException( "Instantiating SLS Implementor ", className, e ); } return sls; } }
package com.jaamsim.BasicObjects; import com.jaamsim.input.EntityInput; import com.jaamsim.input.Input; import com.jaamsim.input.InputErrorException; import com.jaamsim.input.Keyword; import com.jaamsim.input.Output; import com.jaamsim.input.StringInput; import com.jaamsim.states.StateEntity; import com.jaamsim.units.DimensionlessUnit; import com.jaamsim.units.RateUnit; import com.jaamsim.units.TimeUnit; import com.sandwell.JavaSimulation3D.DisplayEntity; /** * LinkedComponents are used to form a chain of components that process DisplayEntities that pass through the system. * Sub-classes for EntityGenerator, Server, and EntitySink. */ public abstract class LinkedComponent extends StateEntity { @Keyword(description = "The prototype for entities that will be received by this object.\n" + "This input must be set if the expression 'this.obj' is used in the input to any keywords.", example = "Statistics1 TestEntity { Proto }") protected final EntityInput<DisplayEntity> testEntity; @Keyword(description = "The next object to which the processed DisplayEntity is passed.", example = "EntityGenerator1 NextComponent { Server1 }") protected final EntityInput<LinkedComponent> nextComponentInput; @Keyword(description = "The state to be assigned to each entity on arrival at this object.\n" + "No state is assigned if the entry is blank.", example = "Server1 StateAssignment { Service }") protected final StringInput stateAssignment; private int numberAdded; // Number of entities added to this component from upstream private int numberProcessed; // Number of entities processed by this component private DisplayEntity receivedEntity; // Entity most recently received by this component private double releaseTime = Double.NaN; { testEntity = new EntityInput<DisplayEntity>(DisplayEntity.class, "TestEntity", "Key Inputs", null); this.addInput(testEntity); nextComponentInput = new EntityInput<LinkedComponent>(LinkedComponent.class, "NextComponent", "Key Inputs", null); this.addInput(nextComponentInput); stateAssignment = new StringInput("StateAssignment", "Key Inputs", ""); this.addInput(stateAssignment); } @Override public void updateForInput(Input<?> in) { super.updateForInput(in); if (in == testEntity) { receivedEntity = testEntity.getValue(); return; } } @Override public void validate() { super.validate(); // Confirm that the next entity in the chain has been specified if (!nextComponentInput.getHidden() && nextComponentInput.getValue() == null) { throw new InputErrorException("The keyword NextComponent must be set."); } // If a state is to be assigned, ensure that the prototype is a StateEntity if (testEntity.getValue() != null && !stateAssignment.getValue().isEmpty()) { if (!(testEntity.getValue() instanceof StateEntity)) { throw new InputErrorException("Only a SimEntity can be specified for the TestEntity keyword if a state is be be assigned."); } } } @Override public void earlyInit() { super.earlyInit(); numberAdded = 0; numberProcessed = 0; receivedEntity = null; releaseTime = Double.NaN; } @Override public String getInitialState() { return "None"; } @Override public boolean isValidState(String state) { return true; } /** * Receives the specified entity from an upstream component. * @param ent - the entity received from upstream. */ public void addDisplayEntity(DisplayEntity ent) { receivedEntity = ent; numberAdded++; // Assign a new state to the received entity if (!stateAssignment.getValue().isEmpty() && ent instanceof StateEntity) ((StateEntity)ent).setPresentState(stateAssignment.getValue()); } /** * Sends the specified entity to the next component downstream. * @param ent - the entity to be sent downstream. */ public void sendToNextComponent(DisplayEntity ent) { numberProcessed++; releaseTime = this.getSimTime(); if( nextComponentInput.getValue() != null ) nextComponentInput.getValue().addDisplayEntity(ent); } // OUTPUT METHODS @Output(name = "obj", description = "The entity that was received most recently.") public DisplayEntity getReceivedEntity(double simTime) { return receivedEntity; } @Output(name = "NumberAdded", description = "The number of entities received from upstream.", unitType = DimensionlessUnit.class, reportable = true) public Double getNumberAdded(double simTime) { return (double)numberAdded; } @Output(name = "NumberProcessed", description = "The number of entities processed by this component.", unitType = DimensionlessUnit.class, reportable = true) public Double getNumberProcessed(double simTime) { return (double)numberProcessed; } @Output(name = "ProcessingRate", description = "The number of entities processed per unit time by this component.", unitType = RateUnit.class, reportable = true) public Double getProcessingRate( double simTime) { return numberProcessed/simTime; } @Output(name = "ReleaseTime", description = "The time at which the last entity was released.", unitType = TimeUnit.class) public Double getReleaseTime(double simTime) { return releaseTime; } }
package com.matt.forgehax.asm.patches; import com.matt.forgehax.asm.helper.AsmHelper; import com.matt.forgehax.asm.helper.AsmMethod; import com.matt.forgehax.asm.helper.transforming.ClassTransformer; import com.matt.forgehax.asm.helper.transforming.MethodTransformer; import com.matt.forgehax.asm.helper.transforming.RegisterMethodTransformer; import com.matt.forgehax.asm.helper.transforming.Inject; import net.minecraft.util.math.AxisAlignedBB; import org.objectweb.asm.tree.*; import java.util.List; import java.util.Objects; import static org.objectweb.asm.Opcodes.*; public class BlockPatch extends ClassTransformer { public final AsmMethod CAN_RENDER_IN_LAYER = new AsmMethod() .setName("canRenderInLayer") .setObfuscatedName("canRenderInLayer") .setArgumentTypes(NAMES.IBLOCKSTATE, NAMES.BLOCK_RENDER_LAYER) .setReturnType(boolean.class) .setHooks(NAMES.ON_RENDERBLOCK_INLAYER); public final AsmMethod ADD_COLLISION_BOX_TO_LIST = new AsmMethod() .setName("addCollisionBoxToList") .setObfuscatedName("a") .setArgumentTypes(NAMES.BLOCKPOS, NAMES.AXISALIGNEDBB, List.class, NAMES.AXISALIGNEDBB) .setReturnType(void.class); public BlockPatch() { super("net/minecraft/block/Block"); } @RegisterMethodTransformer private class CanRenderInLayer extends MethodTransformer { @Override public AsmMethod getMethod() { return CAN_RENDER_IN_LAYER; } @Inject(description = "Changes in layer code so that we can change it") public void inject(MethodNode main) { AbstractInsnNode node = AsmHelper.findPattern(main.instructions.getFirst(), new int[]{INVOKEVIRTUAL}, "x"); Objects.requireNonNull(node, "Find pattern failed for node"); InsnList insnList = new InsnList(); // starting after INVOKEVIRTUAL on Block.getBlockLayer() insnList.add(new VarInsnNode(ASTORE, 3)); // store the result from getBlockLayer() insnList.add(new VarInsnNode(ALOAD, 0)); // push this insnList.add(new VarInsnNode(ALOAD, 1)); // push block state insnList.add(new VarInsnNode(ALOAD, 3)); // push this.getBlockLayer() result insnList.add(new VarInsnNode(ALOAD, 2)); // push the block layer of the block we are comparing to insnList.add(new MethodInsnNode(INVOKESTATIC, NAMES.ON_RENDERBLOCK_INLAYER.getParentClass().getRuntimeName(), NAMES.ON_RENDERBLOCK_INLAYER.getRuntimeName(), NAMES.ON_RENDERBLOCK_INLAYER.getDescriptor(), false )); // now our result is on the stack main.instructions.insert(node, insnList); } } @RegisterMethodTransformer private class AddCollisionBoxToList extends MethodTransformer { @Override public AsmMethod getMethod() { return ADD_COLLISION_BOX_TO_LIST; } @Inject(description = "Inserts hook call") public void inject(MethodNode main) { AbstractInsnNode node = main.instructions.getFirst(); AbstractInsnNode end = AsmHelper.findPattern(main.instructions.getFirst(), new int[] { RETURN }, "x"); Objects.requireNonNull(node, "Find pattern failed for node"); Objects.requireNonNull(end, "Find pattern failed for end"); LabelNode jumpPast = new LabelNode(); InsnList insnList = new InsnList(); //BlockPos pos, AxisAlignedBB entityBox, List<AxisAlignedBB> collidingBoxes, @Nullable AxisAlignedBB blockBox insnList.add(new VarInsnNode(ALOAD, 0)); //pos insnList.add(new VarInsnNode(ALOAD, 1)); //entityBox insnList.add(new VarInsnNode(ALOAD, 2)); //collidingBoxes insnList.add(new VarInsnNode(ALOAD, 3)); //blockBox insnList.add(new MethodInsnNode(INVOKESTATIC, NAMES.ON_BLOCK_ADD_COLLISION.getParentClass().getRuntimeName(), NAMES.ON_BLOCK_ADD_COLLISION.getRuntimeName(), NAMES.ON_BLOCK_ADD_COLLISION.getDescriptor(), false )); insnList.add(new JumpInsnNode(IFNE, jumpPast)); main.instructions.insertBefore(end, jumpPast); main.instructions.insertBefore(node, insnList); } } }
package com.nx.util.jme3.lemur.tween; import com.jme3.audio.AudioNode; import com.jme3.math.FastMath; import com.simsilica.lemur.anim.AbstractTween; import com.simsilica.lemur.anim.Tween; import com.simsilica.lemur.anim.Tweens; public final class AudioTweens { private AudioTweens() { } public static Tween play(AudioNode target) { return Tweens.callMethod(target, "play"); } /** * * @deprecated because of it doesn't make much sense. The tweens are usually created each time the effect is called * so a new instance is already being created with the normal play action. */ @Deprecated public static Tween playInstance(AudioNode target) { return Tweens.callMethod(target, "playInstance"); } public static Tween stop(AudioNode target) { return Tweens.callMethod(target, "stop"); } public static Tween fade(AudioNode target, Float fromAlpha, Float toAlpha, double length ) { if( fromAlpha == null ) { fromAlpha = target.getVolume(); } if( toAlpha == null ) { toAlpha = target.getVolume(); } return new Fade(target, fromAlpha, toAlpha, length); } private static class Fade extends AbstractTween { private final AudioNode target; private final float from; private final float to; public Fade( AudioNode target, float from, float to, double length ) { super(length); this.target = target; this.from = from; this.to = to; } @Override protected void doInterpolate( double t ) { float value = FastMath.interpolateLinear((float)t, from, to); target.setVolume(value); } } }
package com.orctom.mojo.was; import com.orctom.was.model.Command; import com.orctom.was.model.WebSphereModel; import com.orctom.was.model.WebSphereServiceException; import com.orctom.was.service.impl.AbstractWebSphereServiceImpl; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.cli.*; import java.io.File; public class WebSphereServiceImpl extends AbstractWebSphereServiceImpl { public WebSphereServiceImpl(WebSphereModel model, String targetDir) { super(model, targetDir); } @Override protected void executeCommand(Command command) { try { Commandline commandLine = new Commandline(); commandLine.setExecutable(command.getExecutable()); commandLine.setWorkingDirectory(command.getWorkingDir()); for (String arg : command.getArgs().keySet()) { commandLine.createArg().setLine(arg); if (!Strings.isNullOrEmpty(command.getArgs().get( arg ))) { commandLine.createArg().setLine(StringUtils.quoteAndEscape( command.getArgs().get( arg ),'"' ) ); } } StringStreamConsumer outConsumer = new StringStreamConsumer(); StringStreamConsumer errConsumer = new StringStreamConsumer(); executeCommand(commandLine, outConsumer, errConsumer, model.isVerbose()); String out = outConsumer.getOutput(); FileUtils.fileWrite(new File(command.getBuildScriptPath() + ".log"), out); if (model.isFailOnError() && ( out.contains("com.ibm.ws.scripting.ScriptingException") || out.contains("com.ibm.bsf.BSFException"))) { throw new WebSphereServiceException("Failed to execute the task, Please see the log for more details"); } String error = errConsumer.getOutput(); if (StringUtils.isNotEmpty(error)) { System.err.println(error); } } catch (CommandLineTimeOutException e) { throw new WebSphereServiceException("Failed to execute the task." + "Please ensure remote WAS or Deployment Manager is running. " + e.getMessage(), e); } catch (Exception e) { throw new WebSphereServiceException(e.getMessage(), e); } } public static void executeCommand(Commandline commandline, StreamConsumer outConsumer, StreamConsumer errorConsumer, boolean isVerbose) throws CommandLineException { if (isVerbose) { System.out.println("Executing command:\n" + StringUtils.join(commandline.getShellCommandline(), " ")); } int returnCode = CommandLineUtils.executeCommandLine(commandline, outConsumer, errorConsumer, 1800); if (returnCode != 0) { String msg = "Failed to deploy, return code: " + returnCode + ". Please make sure target WAS is alive and reachable."; throw new WebSphereServiceException(msg); } else { System.out.println("Return code: " + returnCode); } } class StringStreamConsumer implements StreamConsumer { private String ls = System.getProperty("line.separator"); private StringBuffer string = new StringBuffer(); public void consumeLine(String line) { string.append(line).append(ls); System.out.println(line); } public String getOutput() { return string.toString(); } } }
package com.pearson.statsagg.webui; import java.io.PrintWriter; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.pearson.statsagg.globals.GlobalVariables; import com.pearson.statsagg.utilities.StackTrace; import com.pearson.statsagg.utilities.StringUtilities; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Jeffrey Schmidt */ @WebServlet(name = "ForgetMetrics", urlPatterns = {"/ForgetMetrics"}) public class ForgetMetrics extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(ForgetMetrics.class.getName()); public static final String PAGE_NAME = "Forget Metrics(s)"; /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) { processGetRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) { processPostRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return PAGE_NAME; } protected void processGetRequest(HttpServletRequest request, HttpServletResponse response) { if ((request == null) || (response == null)) { return; } try { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } PrintWriter out = null; try { StringBuilder htmlBuilder = new StringBuilder(); StatsAggHtmlFramework statsAggHtmlFramework = new StatsAggHtmlFramework(); String htmlHeader = statsAggHtmlFramework.createHtmlHeader("StatsAgg - " + PAGE_NAME, ""); String htmlBodyContents = buildForgetMetricsHtml(); String htmlBody = statsAggHtmlFramework.createHtmlBody(htmlBodyContents); htmlBuilder.append("<!DOCTYPE html>\n<html>\n").append(htmlHeader).append(htmlBody).append("</html>"); Document htmlDocument = Jsoup.parse(htmlBuilder.toString()); String htmlFormatted = htmlDocument.toString(); out = response.getWriter(); out.println(htmlFormatted); } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } finally { if (out != null) { out.close(); } } } protected void processPostRequest(HttpServletRequest request, HttpServletResponse response) { if ((request == null) || (response == null)) { return; } try { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } PrintWriter out = null; try { String result = parseParametersAndReturnResultMessage(request); StringBuilder htmlBuilder = new StringBuilder(); StatsAggHtmlFramework statsAggHtmlFramework = new StatsAggHtmlFramework(); String htmlHeader = statsAggHtmlFramework.createHtmlHeader("StatsAgg - " + PAGE_NAME, ""); String htmlBodyContent = statsAggHtmlFramework.buildHtmlBodyForPostResult(PAGE_NAME, result, "ForgetMetrics", PAGE_NAME); String htmlBody = statsAggHtmlFramework.createHtmlBody(htmlBodyContent); htmlBuilder.append("<!DOCTYPE html>\n<html>\n").append(htmlHeader).append(htmlBody).append("</html>"); Document htmlDocument = Jsoup.parse(htmlBuilder.toString()); String htmlFormatted = htmlDocument.toString(); out = response.getWriter(); out.println(htmlFormatted); } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } finally { if (out != null) { out.close(); } } } private String buildForgetMetricsHtml() { StringBuilder htmlBody = new StringBuilder(); htmlBody.append( "<div id=\"page-content-wrapper\">\n" + " <!-- Keep all page content within the page-content inset div! -->\n" + " <div class=\"page-content inset statsagg_page_content_font\">\n" + " <div class=\"content-header\"> \n" + " <div class=\"pull-left content-header-h2-min-width-statsagg\"> <h2> " + PAGE_NAME + " </h2> </div>\n" + " </div> " + " <form action=\"ForgetMetrics\" method=\"POST\">\n"); htmlBody.append( "<div class=\"form-group\">\n" + " <label class=\"label_small_margin\">Forget individual metric</label>\n" + " <input class=\"form-control-statsagg\" placeholder=\"Enter the exact metric key for the metric you want to 'forget'.\" name=\"ForgetMetric\" > " + "</div>\n"); htmlBody.append( "<div class=\"form-group\">\n" + " <label class=\"label_small_margin\">Forget metrics that match a regular expression</label>\n" + "<a id=\"ForgetMetricsPreview\" name=\"ForgetMetricsPreview\" class=\"iframe cboxElement statsagg_forget_metrics_preview pull-right\" href=\"#\" onclick=\"generateForgetMetricsPreviewLink();\">Preview Regex Matches</a>" + " <input class=\"form-control-statsagg\" placeholder=\"Enter a regex that matches the metric(s) that you want to 'forgot'.\" name=\"ForgetMetricRegex\" id=\"ForgetMetricRegex\">" + "</div>\n"); htmlBody.append( " <button type=\"submit\" class=\"btn btn-default statsagg_page_content_font\">Submit</button>\n" + "</form>\n" + "</div>\n" + "</div>\n"); return htmlBody.toString(); } private String parseParametersAndReturnResultMessage(HttpServletRequest request) { if (request == null) { return null; } getForgetMetricsParameters(request); String returnString = "The specified metrics will be forgotten shortly."; return returnString; } private void getForgetMetricsParameters(HttpServletRequest request) { if (request == null) { return; } try { String parameter; parameter = request.getParameter("ForgetMetric"); if ((parameter != null) && !parameter.isEmpty()) { String trimmedParameter = parameter.trim(); GlobalVariables.immediateCleanupMetrics.put(trimmedParameter, trimmedParameter); String cleanMetricKey = StringUtilities.removeNewlinesFromString(trimmedParameter); logger.info("Action=ForgetMetrics, " + "MetricKey=\"" + cleanMetricKey + "\""); if (GlobalVariables.cleanupInvokerThread != null) GlobalVariables.cleanupInvokerThread.runCleanupThread(); } parameter = request.getParameter("ForgetMetricRegex"); if ((parameter != null) && !parameter.isEmpty()) { String trimmedParameter = parameter.trim(); Thread forgetMetrics_RegexThread = new Thread(new ForgetMetrics_RegexThread(trimmedParameter)); forgetMetrics_RegexThread.setPriority(Thread.MIN_PRIORITY); forgetMetrics_RegexThread.start(); String cleanRegex = StringUtilities.removeNewlinesFromString(trimmedParameter); logger.info("Action=ForgetMetrics, " + "Rexex=\"" + cleanRegex + "\""); } } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } } }
package com.s24.redjob.queue; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.PostConstruct; import org.slf4j.MDC; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import com.s24.redjob.worker.AbstractWorker; import com.s24.redjob.worker.Execution; import com.s24.redjob.worker.Worker; import com.s24.redjob.worker.WorkerState; import com.s24.redjob.worker.events.WorkerError; import com.s24.redjob.worker.events.WorkerNext; import com.s24.redjob.worker.events.WorkerPoll; import com.s24.redjob.worker.events.WorkerStart; import com.s24.redjob.worker.events.WorkerStopped; /** * Base implementation of {@link Worker} for queues. */ public abstract class AbstractQueueWorker extends AbstractWorker implements Runnable, QueueWorker { /** * Queues to listen to. */ private List<String> queues; /** * Dummy execution to avoid "not null" checks. */ private static final Execution NO_EXECUTION = new Execution(-1, "dummy"); /** * Currently processed execution, if any. */ private volatile Execution execution = NO_EXECUTION; /** * Worker thread. */ private Thread thread; /** * Should worker pause?. */ protected final AtomicBoolean pause = new AtomicBoolean(false); /** * Init. */ @PostConstruct public void afterPropertiesSet() throws Exception { Assert.notEmpty(queues, "Precondition violated: queues not empty."); super.afterPropertiesSet(); } /** * Create name for this worker. */ protected String createName() { return super.createName() + ":" + StringUtils.collectionToCommaDelimitedString(queues); } @Override public void start() { thread = new Thread(this, getName()); thread.start(); } @Override public void destroy() { super.destroy(); log.info("Waiting for worker to shutdown."); if (thread != null) { try { thread.interrupt(); thread.join(); } catch (InterruptedException e) { // Ignore } } log.info("Worker has been shut down."); } @Override public void run() { try { MDC.put("worker", getName()); log.info("Starting worker {}.", getName()); state = new WorkerState(); setWorkerState(WorkerState.RUNNING); eventBus.publishEvent(new WorkerStart(this)); startup(); poll(); } catch (Throwable t) { log.error("Uncaught exception in worker. Worker stopped.", name, t); eventBus.publishEvent(new WorkerError(this, t)); } finally { log.info("Stop worker {}.", getName()); eventBus.publishEvent(new WorkerStopped(this)); workerDao.stop(name); } } /** * Startup initialization. */ protected void startup() throws Throwable { for (String queue : queues) { restoreInflight(queue); } } @Override public void pause(boolean pause) { synchronized (this.pause) { this.pause.set(pause); this.pause.notifyAll(); } } /** * Block work thread while worker is paused. */ private void blockWhilePaused() throws InterruptedException { synchronized (this.pause) { while (pause.get()) { try { setWorkerState(WorkerState.PAUSED); this.pause.wait(); } finally { setWorkerState(WorkerState.RUNNING); } } } } /** * Main poll loop. */ protected void poll() throws InterruptedException { while (run.get()) { blockWhilePaused(); try { pollQueues(); } catch (InterruptedException e) { // Just to be sure clear interrupt flag before starting over (if worker has not been requested to stop). Thread.interrupted(); log.debug("Thread has been interrupted."); } catch (Throwable e) { log.error("Polling queues for jobs failed.", e); } } } /** * Poll all queues. * * @throws Throwable * In case of errors. */ protected void pollQueues() throws Throwable { for (String queue : queues) { try { MDC.put("queue", queue); WorkerPoll workerPoll = new WorkerPoll(this, queue); eventBus.publishEvent(workerPoll); if (workerPoll.isVeto()) { log.debug("Queue poll vetoed."); } else if (pollQueue(queue)) { // Event popped and executed -> Start over with polling. return; } } finally { eventBus.publishEvent(new WorkerNext(this, queue)); MDC.remove("queue"); } } Thread.sleep(emptyQueuesSleepMillis); } /** * Poll the given queue. * * @param queue * Queue name. * @return Has a job been polled and executed?. * @throws Throwable * In case of errors. */ protected boolean pollQueue(String queue) throws Throwable { Execution execution = doPollQueue(queue); if (execution == null) { log.debug("Queue is empty."); return false; } boolean restore = false; try { this.execution = execution; MDC.put("execution", Long.toString(execution.getId())); MDC.put("job", execution.getJob().getClass().getSimpleName()); restore = process(queue, execution); return true; } catch (Throwable t) { log.error("Job processing failed.", t); return true; } finally { synchronized (this.execution) { this.execution = NO_EXECUTION; } try { if (restore) { restoreInflight(queue); } else { removeInflight(queue); } } finally { MDC.remove("job"); MDC.remove("execution"); } } } @Override public void stop(long id) { synchronized (this.execution) { if (execution.getId() == id) { if (thread != null) { thread.interrupt(); } } } } /** * Poll the given queue. * * @param queue * Queue name. * @return Execution or null, if queue is empty. * @throws Throwable * In case of errors. */ protected abstract Execution doPollQueue(String queue) throws Throwable; /** * Remove executed (or maybe aborted) job from the inflight queue. * * @param queue * Queue name. * @throws Throwable * In case of errors. */ protected abstract void removeInflight(String queue) throws Throwable; /** * Restore skipped job from the inflight queue. * * @param queue * Queue name. * @throws Throwable * In case of errors. */ protected abstract void restoreInflight(String queue) throws Throwable; @Override protected void run(String queue, Execution execution, Runnable runner, Object unwrappedRunner) { try { // Save start time. update(execution); super.run(queue, execution, runner, unwrappedRunner); } finally { // Save stop time. update(execution); } } // Injections. /** * Queues to listen to. */ @Override public List<String> getQueues() { return queues; } /** * Queues to listen to. */ public void setQueues(String... queues) { setQueues(Arrays.asList(queues)); } /** * Queues to listen to. */ public void setQueues(List<String> queues) { this.queues = queues; } }
package org.objectweb.asm.commons; import org.objectweb.asm.Handle; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; /** * A {@link MethodVisitor} providing a more detailed API to generate and * transform instructions. * * @author Eric Bruneton */ public class InstructionAdapter extends MethodVisitor { public final static Type OBJECT_TYPE = Type.getType("Ljava/lang/Object;"); public InstructionAdapter(final MethodVisitor mv) { this(Opcodes.ASM5, mv); if (getClass() != InstructionAdapter.class) { throw new IllegalStateException(); } } /** * Creates a new {@link InstructionAdapter}. * * @param api * the ASM API version implemented by this visitor. Must be one * of {@link Opcodes#ASM4} or {@link Opcodes#ASM5}. * @param mv * the method visitor to which this adapter delegates calls. */ protected InstructionAdapter(final int api, final MethodVisitor mv) { super(api, mv); } @Override public void visitInsn(final int opcode) { switch (opcode) { case Opcodes.NOP: nop(); break; case Opcodes.ACONST_NULL: aconst(null); break; case Opcodes.ICONST_M1: case Opcodes.ICONST_0: case Opcodes.ICONST_1: case Opcodes.ICONST_2: case Opcodes.ICONST_3: case Opcodes.ICONST_4: case Opcodes.ICONST_5: iconst(opcode - Opcodes.ICONST_0); break; case Opcodes.LCONST_0: case Opcodes.LCONST_1: lconst(opcode - Opcodes.LCONST_0); break; case Opcodes.FCONST_0: case Opcodes.FCONST_1: case Opcodes.FCONST_2: fconst(opcode - Opcodes.FCONST_0); break; case Opcodes.DCONST_0: case Opcodes.DCONST_1: dconst(opcode - Opcodes.DCONST_0); break; case Opcodes.IALOAD: aload(Type.INT_TYPE); break; case Opcodes.LALOAD: aload(Type.LONG_TYPE); break; case Opcodes.FALOAD: aload(Type.FLOAT_TYPE); break; case Opcodes.DALOAD: aload(Type.DOUBLE_TYPE); break; case Opcodes.AALOAD: aload(OBJECT_TYPE); break; case Opcodes.BALOAD: aload(Type.BYTE_TYPE); break; case Opcodes.CALOAD: aload(Type.CHAR_TYPE); break; case Opcodes.SALOAD: aload(Type.SHORT_TYPE); break; case Opcodes.IASTORE: astore(Type.INT_TYPE); break; case Opcodes.LASTORE: astore(Type.LONG_TYPE); break; case Opcodes.FASTORE: astore(Type.FLOAT_TYPE); break; case Opcodes.DASTORE: astore(Type.DOUBLE_TYPE); break; case Opcodes.AASTORE: astore(OBJECT_TYPE); break; case Opcodes.BASTORE: astore(Type.BYTE_TYPE); break; case Opcodes.CASTORE: astore(Type.CHAR_TYPE); break; case Opcodes.SASTORE: astore(Type.SHORT_TYPE); break; case Opcodes.POP: pop(); break; case Opcodes.POP2: pop2(); break; case Opcodes.DUP: dup(); break; case Opcodes.DUP_X1: dupX1(); break; case Opcodes.DUP_X2: dupX2(); break; case Opcodes.DUP2: dup2(); break; case Opcodes.DUP2_X1: dup2X1(); break; case Opcodes.DUP2_X2: dup2X2(); break; case Opcodes.SWAP: swap(); break; case Opcodes.IADD: add(Type.INT_TYPE); break; case Opcodes.LADD: add(Type.LONG_TYPE); break; case Opcodes.FADD: add(Type.FLOAT_TYPE); break; case Opcodes.DADD: add(Type.DOUBLE_TYPE); break; case Opcodes.ISUB: sub(Type.INT_TYPE); break; case Opcodes.LSUB: sub(Type.LONG_TYPE); break; case Opcodes.FSUB: sub(Type.FLOAT_TYPE); break; case Opcodes.DSUB: sub(Type.DOUBLE_TYPE); break; case Opcodes.IMUL: mul(Type.INT_TYPE); break; case Opcodes.LMUL: mul(Type.LONG_TYPE); break; case Opcodes.FMUL: mul(Type.FLOAT_TYPE); break; case Opcodes.DMUL: mul(Type.DOUBLE_TYPE); break; case Opcodes.IDIV: div(Type.INT_TYPE); break; case Opcodes.LDIV: div(Type.LONG_TYPE); break; case Opcodes.FDIV: div(Type.FLOAT_TYPE); break; case Opcodes.DDIV: div(Type.DOUBLE_TYPE); break; case Opcodes.IREM: rem(Type.INT_TYPE); break; case Opcodes.LREM: rem(Type.LONG_TYPE); break; case Opcodes.FREM: rem(Type.FLOAT_TYPE); break; case Opcodes.DREM: rem(Type.DOUBLE_TYPE); break; case Opcodes.INEG: neg(Type.INT_TYPE); break; case Opcodes.LNEG: neg(Type.LONG_TYPE); break; case Opcodes.FNEG: neg(Type.FLOAT_TYPE); break; case Opcodes.DNEG: neg(Type.DOUBLE_TYPE); break; case Opcodes.ISHL: shl(Type.INT_TYPE); break; case Opcodes.LSHL: shl(Type.LONG_TYPE); break; case Opcodes.ISHR: shr(Type.INT_TYPE); break; case Opcodes.LSHR: shr(Type.LONG_TYPE); break; case Opcodes.IUSHR: ushr(Type.INT_TYPE); break; case Opcodes.LUSHR: ushr(Type.LONG_TYPE); break; case Opcodes.IAND: and(Type.INT_TYPE); break; case Opcodes.LAND: and(Type.LONG_TYPE); break; case Opcodes.IOR: or(Type.INT_TYPE); break; case Opcodes.LOR: or(Type.LONG_TYPE); break; case Opcodes.IXOR: xor(Type.INT_TYPE); break; case Opcodes.LXOR: xor(Type.LONG_TYPE); break; case Opcodes.I2L: cast(Type.INT_TYPE, Type.LONG_TYPE); break; case Opcodes.I2F: cast(Type.INT_TYPE, Type.FLOAT_TYPE); break; case Opcodes.I2D: cast(Type.INT_TYPE, Type.DOUBLE_TYPE); break; case Opcodes.L2I: cast(Type.LONG_TYPE, Type.INT_TYPE); break; case Opcodes.L2F: cast(Type.LONG_TYPE, Type.FLOAT_TYPE); break; case Opcodes.L2D: cast(Type.LONG_TYPE, Type.DOUBLE_TYPE); break; case Opcodes.F2I: cast(Type.FLOAT_TYPE, Type.INT_TYPE); break; case Opcodes.F2L: cast(Type.FLOAT_TYPE, Type.LONG_TYPE); break; case Opcodes.F2D: cast(Type.FLOAT_TYPE, Type.DOUBLE_TYPE); break; case Opcodes.D2I: cast(Type.DOUBLE_TYPE, Type.INT_TYPE); break; case Opcodes.D2L: cast(Type.DOUBLE_TYPE, Type.LONG_TYPE); break; case Opcodes.D2F: cast(Type.DOUBLE_TYPE, Type.FLOAT_TYPE); break; case Opcodes.I2B: cast(Type.INT_TYPE, Type.BYTE_TYPE); break; case Opcodes.I2C: cast(Type.INT_TYPE, Type.CHAR_TYPE); break; case Opcodes.I2S: cast(Type.INT_TYPE, Type.SHORT_TYPE); break; case Opcodes.LCMP: lcmp(); break; case Opcodes.FCMPL: cmpl(Type.FLOAT_TYPE); break; case Opcodes.FCMPG: cmpg(Type.FLOAT_TYPE); break; case Opcodes.DCMPL: cmpl(Type.DOUBLE_TYPE); break; case Opcodes.DCMPG: cmpg(Type.DOUBLE_TYPE); break; case Opcodes.IRETURN: areturn(Type.INT_TYPE); break; case Opcodes.LRETURN: areturn(Type.LONG_TYPE); break; case Opcodes.FRETURN: areturn(Type.FLOAT_TYPE); break; case Opcodes.DRETURN: areturn(Type.DOUBLE_TYPE); break; case Opcodes.ARETURN: areturn(OBJECT_TYPE); break; case Opcodes.RETURN: areturn(Type.VOID_TYPE); break; case Opcodes.ARRAYLENGTH: arraylength(); break; case Opcodes.ATHROW: athrow(); break; case Opcodes.MONITORENTER: monitorenter(); break; case Opcodes.MONITOREXIT: monitorexit(); break; default: throw new IllegalArgumentException(); } } @Override public void visitIntInsn(final int opcode, final int operand) { switch (opcode) { case Opcodes.BIPUSH: iconst(operand); break; case Opcodes.SIPUSH: iconst(operand); break; case Opcodes.NEWARRAY: switch (operand) { case Opcodes.T_BOOLEAN: newarray(Type.BOOLEAN_TYPE); break; case Opcodes.T_CHAR: newarray(Type.CHAR_TYPE); break; case Opcodes.T_BYTE: newarray(Type.BYTE_TYPE); break; case Opcodes.T_SHORT: newarray(Type.SHORT_TYPE); break; case Opcodes.T_INT: newarray(Type.INT_TYPE); break; case Opcodes.T_FLOAT: newarray(Type.FLOAT_TYPE); break; case Opcodes.T_LONG: newarray(Type.LONG_TYPE); break; case Opcodes.T_DOUBLE: newarray(Type.DOUBLE_TYPE); break; default: throw new IllegalArgumentException(); } break; default: throw new IllegalArgumentException(); } } @Override public void visitVarInsn(final int opcode, final int var) { switch (opcode) { case Opcodes.ILOAD: load(var, Type.INT_TYPE); break; case Opcodes.LLOAD: load(var, Type.LONG_TYPE); break; case Opcodes.FLOAD: load(var, Type.FLOAT_TYPE); break; case Opcodes.DLOAD: load(var, Type.DOUBLE_TYPE); break; case Opcodes.ALOAD: load(var, OBJECT_TYPE); break; case Opcodes.ISTORE: store(var, Type.INT_TYPE); break; case Opcodes.LSTORE: store(var, Type.LONG_TYPE); break; case Opcodes.FSTORE: store(var, Type.FLOAT_TYPE); break; case Opcodes.DSTORE: store(var, Type.DOUBLE_TYPE); break; case Opcodes.ASTORE: store(var, OBJECT_TYPE); break; case Opcodes.RET: ret(var); break; default: throw new IllegalArgumentException(); } } @Override public void visitTypeInsn(final int opcode, final String type) { Type t = Type.getObjectType(type); switch (opcode) { case Opcodes.NEW: anew(t); break; case Opcodes.ANEWARRAY: newarray(t); break; case Opcodes.CHECKCAST: checkcast(t); break; case Opcodes.INSTANCEOF: instanceOf(t); break; default: throw new IllegalArgumentException(); } } @Override public void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) { switch (opcode) { case Opcodes.GETSTATIC: getstatic(owner, name, desc); break; case Opcodes.PUTSTATIC: putstatic(owner, name, desc); break; case Opcodes.GETFIELD: getfield(owner, name, desc); break; case Opcodes.PUTFIELD: putfield(owner, name, desc); break; default: throw new IllegalArgumentException(); } } @Deprecated @Override public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc) { if (api >= Opcodes.ASM5) { super.visitMethodInsn(opcode, owner, name, desc); return; } doVisitMethodInsn(opcode, owner, name, desc, opcode == Opcodes.INVOKEINTERFACE); } @Override public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc, final boolean itf) { if (api < Opcodes.ASM5) { super.visitMethodInsn(opcode, owner, name, desc, itf); return; } doVisitMethodInsn(opcode, owner, name, desc, itf); } private void doVisitMethodInsn(int opcode, final String owner, final String name, final String desc, final boolean itf) { switch (opcode) { case Opcodes.INVOKESPECIAL: invokespecial(owner, name, desc, itf); break; case Opcodes.INVOKEVIRTUAL: invokevirtual(owner, name, desc, itf); break; case Opcodes.INVOKESTATIC: invokestatic(owner, name, desc, itf); break; case Opcodes.INVOKEINTERFACE: invokeinterface(owner, name, desc); break; default: throw new IllegalArgumentException(); } } @Override public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) { invokedynamic(name, desc, bsm, bsmArgs); } @Override public void visitJumpInsn(final int opcode, final Label label) { switch (opcode) { case Opcodes.IFEQ: ifeq(label); break; case Opcodes.IFNE: ifne(label); break; case Opcodes.IFLT: iflt(label); break; case Opcodes.IFGE: ifge(label); break; case Opcodes.IFGT: ifgt(label); break; case Opcodes.IFLE: ifle(label); break; case Opcodes.IF_ICMPEQ: ificmpeq(label); break; case Opcodes.IF_ICMPNE: ificmpne(label); break; case Opcodes.IF_ICMPLT: ificmplt(label); break; case Opcodes.IF_ICMPGE: ificmpge(label); break; case Opcodes.IF_ICMPGT: ificmpgt(label); break; case Opcodes.IF_ICMPLE: ificmple(label); break; case Opcodes.IF_ACMPEQ: ifacmpeq(label); break; case Opcodes.IF_ACMPNE: ifacmpne(label); break; case Opcodes.GOTO: goTo(label); break; case Opcodes.JSR: jsr(label); break; case Opcodes.IFNULL: ifnull(label); break; case Opcodes.IFNONNULL: ifnonnull(label); break; default: throw new IllegalArgumentException(); } } @Override public void visitLabel(final Label label) { mark(label); } @Override public void visitLdcInsn(final Object cst) { if (cst instanceof Integer) { int val = ((Integer) cst).intValue(); iconst(val); } else if (cst instanceof Byte) { int val = ((Byte) cst).intValue(); iconst(val); } else if (cst instanceof Character) { int val = ((Character) cst).charValue(); iconst(val); } else if (cst instanceof Short) { int val = ((Short) cst).intValue(); iconst(val); } else if (cst instanceof Boolean) { int val = ((Boolean) cst).booleanValue() ? 1 : 0; iconst(val); } else if (cst instanceof Float) { float val = ((Float) cst).floatValue(); fconst(val); } else if (cst instanceof Long) { long val = ((Long) cst).longValue(); lconst(val); } else if (cst instanceof Double) { double val = ((Double) cst).doubleValue(); dconst(val); } else if (cst instanceof String) { aconst(cst); } else if (cst instanceof Type) { tconst((Type) cst); } else if (cst instanceof Handle) { hconst((Handle) cst); } else { throw new IllegalArgumentException(); } } @Override public void visitIincInsn(final int var, final int increment) { iinc(var, increment); } @Override public void visitTableSwitchInsn(final int min, final int max, final Label dflt, final Label... labels) { tableswitch(min, max, dflt, labels); } @Override public void visitLookupSwitchInsn(final Label dflt, final int[] keys, final Label[] labels) { lookupswitch(dflt, keys, labels); } @Override public void visitMultiANewArrayInsn(final String desc, final int dims) { multianewarray(desc, dims); } public void nop() { mv.visitInsn(Opcodes.NOP); } public void aconst(final Object cst) { if (cst == null) { mv.visitInsn(Opcodes.ACONST_NULL); } else { mv.visitLdcInsn(cst); } } public void iconst(final int cst) { if (cst >= -1 && cst <= 5) { mv.visitInsn(Opcodes.ICONST_0 + cst); } else if (cst >= Byte.MIN_VALUE && cst <= Byte.MAX_VALUE) { mv.visitIntInsn(Opcodes.BIPUSH, cst); } else if (cst >= Short.MIN_VALUE && cst <= Short.MAX_VALUE) { mv.visitIntInsn(Opcodes.SIPUSH, cst); } else { mv.visitLdcInsn(new Integer(cst)); } } public void lconst(final long cst) { if (cst == 0L || cst == 1L) { mv.visitInsn(Opcodes.LCONST_0 + (int) cst); } else { mv.visitLdcInsn(new Long(cst)); } } public void fconst(final float cst) { int bits = Float.floatToIntBits(cst); if (bits == 0L || bits == 0x3f800000 || bits == 0x40000000) { mv.visitInsn(Opcodes.FCONST_0 + (int) cst); } else { mv.visitLdcInsn(new Float(cst)); } } public void dconst(final double cst) { long bits = Double.doubleToLongBits(cst); if (bits == 0L || bits == 0x3ff0000000000000L) { // +0.0d and 1.0d mv.visitInsn(Opcodes.DCONST_0 + (int) cst); } else { mv.visitLdcInsn(new Double(cst)); } } public void tconst(final Type type) { mv.visitLdcInsn(type); } public void hconst(final Handle handle) { mv.visitLdcInsn(handle); } public void load(final int var, final Type type) { mv.visitVarInsn(type.getOpcode(Opcodes.ILOAD), var); } public void aload(final Type type) { mv.visitInsn(type.getOpcode(Opcodes.IALOAD)); } public void store(final int var, final Type type) { mv.visitVarInsn(type.getOpcode(Opcodes.ISTORE), var); } public void astore(final Type type) { mv.visitInsn(type.getOpcode(Opcodes.IASTORE)); } public void pop() { mv.visitInsn(Opcodes.POP); } public void pop2() { mv.visitInsn(Opcodes.POP2); } public void dup() { mv.visitInsn(Opcodes.DUP); } public void dup2() { mv.visitInsn(Opcodes.DUP2); } public void dupX1() { mv.visitInsn(Opcodes.DUP_X1); } public void dupX2() { mv.visitInsn(Opcodes.DUP_X2); } public void dup2X1() { mv.visitInsn(Opcodes.DUP2_X1); } public void dup2X2() { mv.visitInsn(Opcodes.DUP2_X2); } public void swap() { mv.visitInsn(Opcodes.SWAP); } public void add(final Type type) { mv.visitInsn(type.getOpcode(Opcodes.IADD)); } public void sub(final Type type) { mv.visitInsn(type.getOpcode(Opcodes.ISUB)); } public void mul(final Type type) { mv.visitInsn(type.getOpcode(Opcodes.IMUL)); } public void div(final Type type) { mv.visitInsn(type.getOpcode(Opcodes.IDIV)); } public void rem(final Type type) { mv.visitInsn(type.getOpcode(Opcodes.IREM)); } public void neg(final Type type) { mv.visitInsn(type.getOpcode(Opcodes.INEG)); } public void shl(final Type type) { mv.visitInsn(type.getOpcode(Opcodes.ISHL)); } public void shr(final Type type) { mv.visitInsn(type.getOpcode(Opcodes.ISHR)); } public void ushr(final Type type) { mv.visitInsn(type.getOpcode(Opcodes.IUSHR)); } public void and(final Type type) { mv.visitInsn(type.getOpcode(Opcodes.IAND)); } public void or(final Type type) { mv.visitInsn(type.getOpcode(Opcodes.IOR)); } public void xor(final Type type) { mv.visitInsn(type.getOpcode(Opcodes.IXOR)); } public void iinc(final int var, final int increment) { mv.visitIincInsn(var, increment); } public void cast(final Type from, final Type to) { if (from != to) { if (from == Type.DOUBLE_TYPE) { if (to == Type.FLOAT_TYPE) { mv.visitInsn(Opcodes.D2F); } else if (to == Type.LONG_TYPE) { mv.visitInsn(Opcodes.D2L); } else { mv.visitInsn(Opcodes.D2I); cast(Type.INT_TYPE, to); } } else if (from == Type.FLOAT_TYPE) { if (to == Type.DOUBLE_TYPE) { mv.visitInsn(Opcodes.F2D); } else if (to == Type.LONG_TYPE) { mv.visitInsn(Opcodes.F2L); } else { mv.visitInsn(Opcodes.F2I); cast(Type.INT_TYPE, to); } } else if (from == Type.LONG_TYPE) { if (to == Type.DOUBLE_TYPE) { mv.visitInsn(Opcodes.L2D); } else if (to == Type.FLOAT_TYPE) { mv.visitInsn(Opcodes.L2F); } else { mv.visitInsn(Opcodes.L2I); cast(Type.INT_TYPE, to); } } else { if (to == Type.BYTE_TYPE) { mv.visitInsn(Opcodes.I2B); } else if (to == Type.CHAR_TYPE) { mv.visitInsn(Opcodes.I2C); } else if (to == Type.DOUBLE_TYPE) { mv.visitInsn(Opcodes.I2D); } else if (to == Type.FLOAT_TYPE) { mv.visitInsn(Opcodes.I2F); } else if (to == Type.LONG_TYPE) { mv.visitInsn(Opcodes.I2L); } else if (to == Type.SHORT_TYPE) { mv.visitInsn(Opcodes.I2S); } } } } public void lcmp() { mv.visitInsn(Opcodes.LCMP); } public void cmpl(final Type type) { mv.visitInsn(type == Type.FLOAT_TYPE ? Opcodes.FCMPL : Opcodes.DCMPL); } public void cmpg(final Type type) { mv.visitInsn(type == Type.FLOAT_TYPE ? Opcodes.FCMPG : Opcodes.DCMPG); } public void ifeq(final Label label) { mv.visitJumpInsn(Opcodes.IFEQ, label); } public void ifne(final Label label) { mv.visitJumpInsn(Opcodes.IFNE, label); } public void iflt(final Label label) { mv.visitJumpInsn(Opcodes.IFLT, label); } public void ifge(final Label label) { mv.visitJumpInsn(Opcodes.IFGE, label); } public void ifgt(final Label label) { mv.visitJumpInsn(Opcodes.IFGT, label); } public void ifle(final Label label) { mv.visitJumpInsn(Opcodes.IFLE, label); } public void ificmpeq(final Label label) { mv.visitJumpInsn(Opcodes.IF_ICMPEQ, label); } public void ificmpne(final Label label) { mv.visitJumpInsn(Opcodes.IF_ICMPNE, label); } public void ificmplt(final Label label) { mv.visitJumpInsn(Opcodes.IF_ICMPLT, label); } public void ificmpge(final Label label) { mv.visitJumpInsn(Opcodes.IF_ICMPGE, label); } public void ificmpgt(final Label label) { mv.visitJumpInsn(Opcodes.IF_ICMPGT, label); } public void ificmple(final Label label) { mv.visitJumpInsn(Opcodes.IF_ICMPLE, label); } public void ifacmpeq(final Label label) { mv.visitJumpInsn(Opcodes.IF_ACMPEQ, label); } public void ifacmpne(final Label label) { mv.visitJumpInsn(Opcodes.IF_ACMPNE, label); } public void goTo(final Label label) { mv.visitJumpInsn(Opcodes.GOTO, label); } public void jsr(final Label label) { mv.visitJumpInsn(Opcodes.JSR, label); } public void ret(final int var) { mv.visitVarInsn(Opcodes.RET, var); } public void tableswitch(final int min, final int max, final Label dflt, final Label... labels) { mv.visitTableSwitchInsn(min, max, dflt, labels); } public void lookupswitch(final Label dflt, final int[] keys, final Label[] labels) { mv.visitLookupSwitchInsn(dflt, keys, labels); } public void areturn(final Type t) { mv.visitInsn(t.getOpcode(Opcodes.IRETURN)); } public void getstatic(final String owner, final String name, final String desc) { mv.visitFieldInsn(Opcodes.GETSTATIC, owner, name, desc); } public void putstatic(final String owner, final String name, final String desc) { mv.visitFieldInsn(Opcodes.PUTSTATIC, owner, name, desc); } public void getfield(final String owner, final String name, final String desc) { mv.visitFieldInsn(Opcodes.GETFIELD, owner, name, desc); } public void putfield(final String owner, final String name, final String desc) { mv.visitFieldInsn(Opcodes.PUTFIELD, owner, name, desc); } @Deprecated public void invokevirtual(final String owner, final String name, final String desc) { if (api >= Opcodes.ASM5) { invokevirtual(owner, name, desc, false); return; } mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, owner, name, desc); } public void invokevirtual(final String owner, final String name, final String desc, final boolean itf) { if (api < Opcodes.ASM5) { if (itf) { throw new IllegalArgumentException( "INVOKEVIRTUAL on interfaces require ASM 5"); } invokevirtual(owner, name, desc); return; } mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, owner, name, desc, itf); } @Deprecated public void invokespecial(final String owner, final String name, final String desc) { if (api >= Opcodes.ASM5) { invokespecial(owner, name, desc, false); return; } mv.visitMethodInsn(Opcodes.INVOKESPECIAL, owner, name, desc, false); } public void invokespecial(final String owner, final String name, final String desc, final boolean itf) { if (api < Opcodes.ASM5) { if (itf) { throw new IllegalArgumentException( "INVOKESPECIAL on interfaces require ASM 5"); } invokespecial(owner, name, desc); return; } mv.visitMethodInsn(Opcodes.INVOKESPECIAL, owner, name, desc, itf); } @Deprecated public void invokestatic(final String owner, final String name, final String desc) { if (api >= Opcodes.ASM5) { invokestatic(owner, name, desc, false); return; } mv.visitMethodInsn(Opcodes.INVOKESTATIC, owner, name, desc, false); } public void invokestatic(final String owner, final String name, final String desc, final boolean itf) { if (api < Opcodes.ASM5) { if (itf) { throw new IllegalArgumentException( "INVOKESTATIC on interfaces require ASM 5"); } invokestatic(owner, name, desc); return; } mv.visitMethodInsn(Opcodes.INVOKESTATIC, owner, name, desc, itf); } public void invokeinterface(final String owner, final String name, final String desc) { mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, owner, name, desc, true); } public void invokedynamic(String name, String desc, Handle bsm, Object[] bsmArgs) { mv.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs); } public void anew(final Type type) { mv.visitTypeInsn(Opcodes.NEW, type.getInternalName()); } public void newarray(final Type type) { int typ; switch (type.getSort()) { case Type.BOOLEAN: typ = Opcodes.T_BOOLEAN; break; case Type.CHAR: typ = Opcodes.T_CHAR; break; case Type.BYTE: typ = Opcodes.T_BYTE; break; case Type.SHORT: typ = Opcodes.T_SHORT; break; case Type.INT: typ = Opcodes.T_INT; break; case Type.FLOAT: typ = Opcodes.T_FLOAT; break; case Type.LONG: typ = Opcodes.T_LONG; break; case Type.DOUBLE: typ = Opcodes.T_DOUBLE; break; default: mv.visitTypeInsn(Opcodes.ANEWARRAY, type.getInternalName()); return; } mv.visitIntInsn(Opcodes.NEWARRAY, typ); } public void arraylength() { mv.visitInsn(Opcodes.ARRAYLENGTH); } public void athrow() { mv.visitInsn(Opcodes.ATHROW); } public void checkcast(final Type type) { mv.visitTypeInsn(Opcodes.CHECKCAST, type.getInternalName()); } public void instanceOf(final Type type) { mv.visitTypeInsn(Opcodes.INSTANCEOF, type.getInternalName()); } public void monitorenter() { mv.visitInsn(Opcodes.MONITORENTER); } public void monitorexit() { mv.visitInsn(Opcodes.MONITOREXIT); } public void multianewarray(final String desc, final int dims) { mv.visitMultiANewArrayInsn(desc, dims); } public void ifnull(final Label label) { mv.visitJumpInsn(Opcodes.IFNULL, label); } public void ifnonnull(final Label label) { mv.visitJumpInsn(Opcodes.IFNONNULL, label); } public void mark(final Label label) { mv.visitLabel(label); } }
package com.sandwell.JavaSimulation; import java.util.ArrayList; import com.jaamsim.ui.FrameBox; import com.sandwell.JavaSimulation3D.EventViewer; import com.sandwell.JavaSimulation3D.GUIFrame; /** * Class EventManager - Sandwell Discrete Event Simulation * <p> * The EventManager is responsible for scheduling future events, controlling * conditional event evaluation, and advancing the simulation time. Events are * scheduled in based on: * <ul> * <li>1 - The execution time scheduled for the event * <li>2 - The priority of the event (if scheduled to occur at the same time) * <li>3 - If both 1) and 2) are equal, the order in which the event was * scheduled (FILO - Stack ordering) * </ul> * <p> * The event time is scheduled using a backing long value. Double valued time is * taken in by the scheduleWait function and scaled to the nearest long value * using the simTimeFactor. * <p> * The EventManager thread is always the bottom thread on the threadStack, so * that after each event has finished, along with any spawned events, the * program control will pass back to the EventManager. * <p> * The runnable interface is implemented so that the eventManager runs as a * separate thread. * <p> * EventManager is held as a static member of class entity, this ensures that * all entities will schedule themselves with the same event manager. */ public final class EventManager implements Runnable { private static final ArrayList<EventManager> definedManagers; static final EventManager rootManager; boolean traceEvents = false; private static int eventState; static final int EVENTS_STOPPED = 0; static final int EVENTS_RUNNING = 1; static final int EVENTS_RUNONE = 2; static final int EVENTS_TIMESTEP = 3; static final int EVENTS_UNTILTIME = 4; final String name; private final EventManager parent; private final ArrayList<EventManager> children; private final Object lockObject; // Object used as global lock for synchronization private final ArrayList<Event> eventStack; /* * eventStack is a list of all future events for this eventManager in order * of execution. The next event to be executed is found at position 0. */ private final ArrayList<Process> conditionalList; // List of all conditionally waiting processes private final Thread eventManagerThread; private int activeChildCount; // The number of currently executing child eventManagers private long currentTick; // Master simulation time (long) private long targetTick; // The time a child eventManager will run to before waking the parent eventManager // Real time execution state private boolean executeRealTime; private int realTimeFactor; private long previousInternalTime; private long previousWallTime; private EventTraceRecord traceRecord; private EventViewer currentViewer; /* * TODO: eventViewer needs to show events for all eventManagers, not just a * single eventManager */ private boolean wasPaused; // Holds the state of the model when an eventViewer was opened private long debuggingTime; /* * TODO: rename this to better reflect its function. Used by the eventViewer in * doOneEvent, doEventsAtTime, runToTime * * event time to debug, implements the run to time functionality */ static final int PRIO_DEFAULT = 5; static final int PRIO_LASTLIFO = 11; static final int PRIO_LASTFIFO = 12; static final int STATE_WAITING = 0; static final int STATE_EXITED = 1; static final int STATE_INTERRUPTED = 2; static final int STATE_TERMINATED = 3; /* * Used to communicate with the eventViewer about the status of a given event */ static { eventState = EVENTS_STOPPED; definedManagers = new ArrayList<EventManager>(); rootManager = new EventManager(null, "DefaultEventManager"); definedManagers.add(rootManager); rootManager.start(); } /** * Allocates a new EventManager with the given parent and name * * @param parent the connection point for this EventManager in the tree * @param name the name this EventManager should use */ EventManager(EventManager parent, String name) { // Basic initialization this.name = name; lockObject = new Object(); // Initialize the tree structure for multiple EventManagers this.parent = parent; if (this.parent != null) { this.parent.addChild(this); } children = new ArrayList<EventManager>(); activeChildCount = 0; // Initialize the thread which processes events from this EventManager eventManagerThread = new Thread(this, "evt-" + name); traceRecord = new EventTraceRecord(); // Initialize and event lists and timekeeping variables currentTick = 0; targetTick = 0; eventStack = new ArrayList<Event>(); conditionalList = new ArrayList<Process>(); executeRealTime = false; realTimeFactor = 1; previousInternalTime = -1; } void start() { eventManagerThread.start(); } static void defineEventManager(String name) { EventManager evt = new EventManager(rootManager, name); definedManagers.add(evt); evt.start(); } static EventManager getDefinedManager(String name) { for (EventManager each : definedManagers) { if (each.name.equals(name)) { return each; } } return null; } private void addChild(EventManager child) { synchronized (lockObject) { children.add(child); activeChildCount++; } } void basicInit() { targetTick = Long.MAX_VALUE; currentTick = 0; traceRecord.clearLevel(); traceRecord.clear(); } // Initialize the eventManager. This method is needed only for re-initialization. // It is not used when the eventManager is first created. void initialize() { traceEvents = false; synchronized (lockObject) { // Kill threads on the event stack for (Event each : eventStack) { if (each.process.testFlag(Process.ACTIVE)) { throw new ErrorException( "Cannot terminate an active thread" ); } each.process.setFlag(Process.TERMINATE); each.process.interrupt(); } eventStack.clear(); // Kill conditional threads for (Process each : conditionalList) { if (each.testFlag(Process.ACTIVE)) { throw new ErrorException( "Cannot terminate an active thread" ); } each.setFlag(Process.TERMINATE); each.interrupt(); } conditionalList.clear(); } } private void evaluateConditionals() { // All conditional events if time advanced synchronized (lockObject) { if (conditionalList.size() == 0) { return; } // Loop through the conditions in reverse order and add to the linked // list of active threads for (int i = 0; i < conditionalList.size() - 1; i++) { conditionalList.get(i).setNextProcess(conditionalList.get(i + 1)); } conditionalList.get(conditionalList.size() - 1).setNextProcess(null); // Wake up the first conditional thread to be tested // at this point, nextThread == conditionalList.get(0) switchThread(conditionalList.get(0)); } } private void doDebug() { synchronized (lockObject) { EventManager.setEventState(EventManager.EVENTS_STOPPED); } Simulation.setSimState(Simulation.SIM_STATE_PAUSED); GUIFrame.instance().updateForSimulationState(); // update the event display if there is one present if (currentViewer != null) currentViewer.update(); } // Notify the parent eventManager than this eventManager has completed all its // events up to some specified simulation time. private void wakeParent() { synchronized (lockObject) { // For the top level eventManager, notify the simulation object if (parent == null) { // Stop the eventManager's thread threadWait(); } // For an eventManager that does have a parent else { // Wake up the parent and stop this eventManager's thread parent.wake(); threadWait(); } } } // Called by child eventManager to restart its parent eventManager private void wake() { synchronized (lockObject) { // Decrement the number of active child eventManagers // (note that this must be done here and not when the child calls this // method because the parent's lockobject must be held to modify its property) activeChildCount if (activeChildCount == 0) { eventManagerThread.interrupt(); } } } // Restart executing future events for each child eventManager // @nextTime - maximum simulation time to execute until private void updateChildren(long nextTick) { synchronized (lockObject) { // Temporary debug code to account for racy initialization if (activeChildCount != 0) { System.out.println("Child count corrupt:"+activeChildCount); activeChildCount = 0; } // Loop through the child eventManagers for (EventManager child : children) { // Increment the number of active children and restart the // child eventManager activeChildCount++; synchronized (child.lockObject) { child.targetTick = nextTick; child.eventManagerThread.interrupt(); } } if (activeChildCount > 0) threadWait(); } } /** * Main event processing loop for the eventManager. * * Each eventManager runs its loop continuous throughout the simulation run * with its own thread. The loop for each eventManager is never terminated. * It is only paused and restarted as required. The run method is called by * eventManager.start(). */ @Override public void run() { // Loop continuously while (true) { // 1) Check whether the model has been paused if (parent == null && EventManager.getEventState() == EventManager.EVENTS_STOPPED) { synchronized (lockObject) { this.threadWait(); } continue; } // 2) Execute the next event at the present simulation time // Is there another event at this simulation time? if (eventStack.size() > 0 && eventStack.get(0).schedTick == currentTick) { // Remove the event from the future events Event nextEvent = eventStack.remove(0); this.retireEvent(nextEvent, STATE_EXITED); // If required, track the events for this entity if (nextEvent.caller.testFlag(Entity.FLAG_TRACKEVENTS)) { System.out.println(String.format("TRACK caller: %s at:%d[%.3f]", nextEvent.caller.getName(), currentTick, currentTick/Process.getSimTimeFactor())); } // Pass control to this event's thread nextEvent.process.setNextProcess(null); switchThread(nextEvent.process); continue; } // 3) Check to see if the target simulation time has been reached if (currentTick == targetTick) { // Notify the parent eventManager that this child has finished this.wakeParent(); continue; } // 4) Advance to the next event time // (at this point, there are no more events at the present event time) // Check all the conditional events this.evaluateConditionals(); // Determine the next event time long nextTick; if (eventStack.size() > 0) { nextTick = Math.min(eventStack.get(0).schedTick, targetTick); } else { nextTick = targetTick; } // Update all the child eventManagers to this next event time this.updateChildren(nextTick); // Only the top-level eventManager should update the master simulation // time if (parent == null) this.updateTime(nextTick); // Set the present time for this eventManager to the next event time if (eventStack.size() > 0 && eventStack.get(0).schedTick < nextTick) { System.out.format("Big trouble:%s %d %d\n", name, nextTick, eventStack.get(0).schedTick); nextTick = eventStack.get(0).schedTick; } currentTick = nextTick; if (EventManager.getEventState() == EventManager.EVENTS_RUNONE) { doDebug(); } else if (EventManager.getEventState() == EventManager.EVENTS_TIMESTEP) { if (eventStack.get(0).schedTick != debuggingTime) { doDebug(); } } else if (EventManager.getEventState() == EventManager.EVENTS_UNTILTIME) { if (eventStack.get(0).schedTick >= debuggingTime) { doDebug(); } } } } private void updateTime(long nextTime) { if (executeRealTime) { // Account for pausing the model/restarting if (previousInternalTime == -1) { previousInternalTime = nextTime; previousWallTime = System.currentTimeMillis(); } // Calculate number of milliseconds between events long millisToWait = (long)((((nextTime - previousInternalTime) / Process.getSimTimeFactor()) * 3600 * 1000) / realTimeFactor); long targetMillis = previousWallTime + millisToWait; long currentWallTime = 0; // cache the internal time and the current RealTimeFactor in case they // are written while doing the pause long prevIntTime = previousInternalTime; while ((currentWallTime = System.currentTimeMillis()) < targetMillis) { this.threadPause(20); double modelSecs = ((currentWallTime - previousWallTime) * realTimeFactor) / 1000.0d; long modelTicks = Process.secondsToTicks(modelSecs); modelTicks += prevIntTime; if (modelTicks < nextTime) FrameBox.timeUpdate(Process.ticksToSeconds(modelTicks)); // If realtime was disabled, break out if (!executeRealTime || previousInternalTime == -1) break; } } FrameBox.timeUpdate(Process.ticksToSeconds(nextTime)); } /** * Called when a process has finished invoking a model method and unwinds * the threadStack one level. */ void releaseProcess() { traceProcess(null, null); synchronized (lockObject) { assertNotWaitUntil(); Process next = Process.current().getNextProcess(); if (next != null) { next.interrupt(); } else { // TODO: check for the switching of eventmanagers Process.current().getEventManager().eventManagerThread.interrupt(); } } } // Pause the current active thread and restart the next thread on the // active thread list. For this case, a future event or conditional event // has been created for the current thread. Called by // eventManager.scheduleWait() and related methods, and by // eventManager.waitUntil(). // restorePreviousActiveThread() private void popThread() { synchronized (lockObject) { Process next = Process.current().getNextProcess(); Process.current().clearFlag(Process.ACTIVE); if (next != null) { Process.current().setNextProcess(null); switchThread(next); } else { // TODO: check for the switching of eventmanagers switchThread(Process.current().getEventManager().eventManagerThread); } Process.current().wake(this); } } void switchThread(Thread next) { synchronized (lockObject) { next.interrupt(); threadWait(); } } /** * Calculate the time for an event taking into account numeric overflow. */ private long calculateEventTime(long base, long waitLength) { // Check for numeric overflow of internal time long nextEventTime = base + waitLength; if (nextEventTime < 0) nextEventTime = Long.MAX_VALUE; return nextEventTime; } private void raw_scheduleWait(long waitLength, int eventPriority, Entity caller) { assertNotWaitUntil(); if (!Process.current().getEventManager().isParentOf(this)) { System.out.format("Crossing eventManager boundary dst:%s src:%s\n", name, Process.current().getEventManager().name); long time = Process.current().getEventManager().currentTick() + waitLength; if (eventStack.size() > 0 && eventStack.get(0).schedTick > time) System.out.format("Next Event:%d This Event:%d\n", eventStack.get(0).schedTick, time); } long nextEventTime = calculateEventTime(Process.currentTick(), waitLength); Event temp = new Event(currentTick(), nextEventTime, eventPriority, caller, Process.current()); Process.current().getEventManager().traceEvent(temp, STATE_WAITING); addEventToStack(temp); popThread(); } private void raw_scheduleProcess(long waitLength, int eventPriority, Entity caller, String methodName, Object[] args) { assertNotWaitUntil(); // Take a process from the pool Process newProcess = Process.allocate(this, caller, methodName, args); long eventTime = calculateEventTime(Process.currentTick(), waitLength); // Create an event for the new process at the present time, and place it on the event stack Event newEvent = new Event(this.currentTick(), eventTime, eventPriority, caller, newProcess); Process.current().getEventManager().traceSchedProcess(newEvent); addEventToStack(newEvent); } void scheduleProcess(long waitLength, int eventPriority, Entity caller, String methodName, Object[] args) { raw_scheduleProcess(waitLength, eventPriority, caller, methodName, args); } void scheduleSingleProcess(long waitLength, int eventPriority, Entity caller, String methodName, Object[] args) { long eventTime = calculateEventTime(Process.currentTick(), waitLength); synchronized (lockObject) { for (int i = 0; i < eventStack.size(); i++) { Event each = eventStack.get(i); // We passed where any duplicate could be, break out to the // insertion part if (each.schedTick > eventTime) break; // if we have an exact match, do not schedule another event if (each.schedTick == eventTime && each.priority == eventPriority && each.caller == caller && EventManager.getClassMethod(each).endsWith(methodName)) { //System.out.println("Suppressed duplicate event:" + Process.currentProcess().getEventManager().currentLongTime); Process.current().getEventManager().traceSchedProcess(each); return; } } raw_scheduleProcess(waitLength, eventPriority, caller, methodName, args); } } /** * Schedules a future event to occur with a given priority. Lower priority * events will be executed preferentially over higher priority. This is * by lower priority events being placed higher on the event stack. * @param ticks the number of discrete ticks from now to schedule the event. * @param priority the priority of the scheduled event: 1 is the highest priority (default is priority 5) */ void waitTicks(long ticks, int priority, Entity caller) { // Test for negative duration schedule wait length if(ticks < 0) throw new ErrorException("Negative duration wait is invalid (wait length specified to be %d )", ticks); raw_scheduleWait(ticks, priority, caller); } /** * Schedules a future event to occur with a given priority. Lower priority * events will be executed preferentially over higher priority. This is * by lower priority events being placed higher on the event stack. * @param waitLength the length of time from now to schedule the event. * @param eventPriority the priority of the scheduled event: 1 is the highest priority (default is priority 5) */ void scheduleWait(long waitLength, int eventPriority, Entity caller) { // Test for zero duration scheduled wait length if (waitLength == 0) { return; } // Test for negative duration schedule wait length if(waitLength < 0) { throw new ErrorException("Negative duration wait is invalid (wait length specified to be %d )", waitLength); } raw_scheduleWait(waitLength, eventPriority, caller); } void scheduleLastFIFO( Entity caller ) { raw_scheduleWait(0, PRIO_LASTFIFO, caller); } /** * Schedules an event to happen as the last event at the current time in LIFO. * Additional calls to scheduleLast will place a new event as the last event, * in fron of other 'last' events. */ void scheduleLastLIFO( Entity caller ) { raw_scheduleWait(0, PRIO_LASTLIFO, caller); } /** * Adds a new event to the event stack. This method will add an event to * the event stack based on its scheduled time, priority, and in stack * order otherwise. Called from scheduleWait in order to abstract the * underlying data structure and event scheduling routines if necessary. * This implementation utilizes a stack structure, but his could be * replaced with a heap or other basic structure. * @param waitLength is the length of time in the future to schedule the * event. * @param eventPriority is the priority of the event, default 0 */ private void addEventToStack(Event newEvent) { synchronized (lockObject) { if (newEvent.schedTick < currentTick) { System.out.println("Time travel detected - whoops"); throw new ErrorException("Going back in time"); } int i; // skip all event that happen before the new event for (i = 0; i < eventStack.size(); i++) { if (eventStack.get(i).schedTick < newEvent.schedTick) { continue; } else { break; } } // skip all events at an equal time that have higher priority for (; i < eventStack.size(); i++) { // next stack event happens at a later time, i is the insertion index if (eventStack.get(i).schedTick > newEvent.schedTick) { break; } // skip the higher priority events at the same time if (eventStack.get(i).priority < newEvent.priority) { continue; } // scheduleLastFIFO is special because it adds in queue, rather // than stack ordering, so keep going until we find an event that // happens at a later time without regard to priority if (newEvent.priority != PRIO_LASTFIFO) { break; } } // Insert the event in the stack eventStack.add(i, newEvent); } } /** * Debugging aid to test that we are not executing a conditional event, useful * to try and catch places where a waitUntil was missing a waitUntilEnded. * While not fatal, it will print out a stack dump to try and find where the * waitUntilEnded was missed. */ private void assertNotWaitUntil() { Process process = Process.current(); if (process.testFlag(Process.COND_WAIT)) { System.out.println("AUDIT - waitUntil without waitUntilEnded " + process); for (StackTraceElement elem : process.getStackTrace()) { System.out.println(elem.toString()); } } } /** * Used to achieve conditional waits in the simulation. Adds the calling * thread to the conditional stack, then wakes the next waiting thread on * the thread stack. */ void waitUntil(Entity caller) { synchronized (lockObject) { if (!conditionalList.contains(Process.current())) { Process.current().getEventManager().traceWaitUntil(0); Process.current().setFlag(Process.COND_WAIT); conditionalList.add(Process.current()); } } popThread(); } void waitUntilEnded(Entity caller) { synchronized (lockObject) { if (!conditionalList.remove(Process.current())) { // Do not wait at all if we never actually were on the waitUntilStack // ie. we never called waitUntil return; } else { traceWaitUntil(1); Process.current().clearFlag(Process.COND_WAIT); scheduleLastFIFO(caller); } } } /** * Removes the thread from the pending list and executes it immediately */ void interrupt( Process intThread ) { synchronized (lockObject) { if (intThread.testFlag(Process.ACTIVE)) { throw new ErrorException( "Cannot interrupt an active thread" ); } assertNotWaitUntil(); for (int i = 0; i < eventStack.size(); i++) { if (eventStack.get(i).process == intThread) { Event interruptEvent = eventStack.remove(i); retireEvent(interruptEvent, STATE_INTERRUPTED); interruptEvent.process.setNextProcess(Process.current()); switchThread(interruptEvent.process); return; } } throw new ErrorException("Tried to interrupt a thread in %s that couldn't be found", name); } } void terminateThread( Process killThread ) { synchronized (lockObject) { if (killThread.testFlag(Process.ACTIVE)) { throw new ErrorException( "Cannot terminate an active thread" ); } assertNotWaitUntil(); if (conditionalList.remove(killThread)) { killThread.setFlag(Process.TERMINATE); killThread.interrupt(); return; } for( int i = 0; i < eventStack.size(); i++ ) { if (eventStack.get(i).process == killThread) { Event temp = eventStack.remove(i); retireEvent(temp, STATE_TERMINATED); killThread.setFlag(Process.TERMINATE); killThread.interrupt(); return; } } //if (parent != null) { // parent.terminateThread(killThread); // return; } System.out.format("Threadevt:%s", killThread.getEventManager().name); throw new ErrorException("Tried to terminate a thread in %s that couldn't be found", name); } private void retireEvent(Event retired, int reason) { if (currentViewer != null) currentViewer.addRetiredEvent(getEventData(retired, reason), reason); traceEvent(retired, reason); } long currentTick() { return currentTick; } void setExecuteRealTime(boolean useRealTime, int factor) { executeRealTime = useRealTime; realTimeFactor = factor; if (useRealTime) previousInternalTime = -1; } /** * Locks the calling thread in an inactive state to the global lock. * When a new thread is created, and the current thread has been pushed * onto the inactive thread stack it must be put to sleep to preserve * program ordering. * <p> * The function takes no parameters, it puts the calling thread to sleep. * This method is NOT static as it requires the use of wait() which cannot * be called from a static context * <p> * There is a synchronized block of code that will acquire the global lock * and then wait() the current thread. */ private void threadWait() { // Ensure that the thread owns the global thread lock synchronized( lockObject ) { try { /* * Halt the thread and only wake up by being interrupted. * * The infinite loop is _absolutely_ necessary to prevent * spurious wakeups from waking us early....which causes the * model to get into an inconsistent state causing crashes. */ while (true) { lockObject.wait(); } } // Catch the exception when the thread is interrupted catch( InterruptedException e ) {} } } private void threadPause(long millisToWait) { // Ensure that the thread owns the global thread lock synchronized( lockObject ) { try { /* * Halt the thread and allow timeouts to wake us. */ lockObject.wait(millisToWait); } // Catch the exception when the thread is interrupted catch( InterruptedException e ) {} } } private boolean isParentOf(EventManager child) { // Allow trivial case where we check against ourself EventManager temp = child; while (temp != null) { if (this == temp) { return true; } else { temp = temp.parent; } } return false; } /** * This method will create a new process from outside the simulation. * For example, it is used when pressing F5 to start an avi capture. */ void startExternalProcess(Entity target, String methodName, Object[] arguments) { // Take a process from the pool Process newProcess = Process.allocate(this, target, methodName, arguments); // Create an event for the new process at the present time, and place it on the event stack Event newEvent = new Event(currentTick, currentTick, PRIO_DEFAULT, target, newProcess); this.traceSchedProcess(newEvent); addEventToStack(newEvent); } private static synchronized int getEventState() { return eventState; } private static synchronized void setEventState(int state) { eventState = state; } /** * Sets the value that is tested in the doProcess loop to determine if the * next event should be executed. If set to false, the eventManager will * execute a threadWait() and wait until an interrupt is generated. It is * guaranteed in this state that there is an empty thread stack and the * thread referenced in activeThread is the eventManager thread. */ void pause() { EventManager.setEventState(EventManager.EVENTS_STOPPED); } /** * Sets the value that is tested in the doProcess loop to determine if the * next event should be executed. Generates an interrupt of activeThread * in case the eventManager thread has already been paused and needs to * resume the event execution loop. This prevents the model being resumed * from an inconsistent state. */ void resume() { previousInternalTime = -1; if (EventManager.getEventState() != EventManager.EVENTS_STOPPED) return; // cannot resume if viewing events if( currentViewer != null ) return; synchronized( lockObject ) { EventManager.setEventState(EventManager.EVENTS_RUNNING); eventManagerThread.interrupt(); } } public void registerEventViewer( EventViewer ev ) { currentViewer = ev; wasPaused = (EventManager.getEventState() == EventManager.EVENTS_STOPPED); pause(); } public void unregisterEventViewer( EventViewer ev ) { currentViewer = null; if( !wasPaused ) resume(); } public void nextOneEvent() { EventManager.setEventState(EventManager.EVENTS_RUNONE); startDebugging(); } public void nextEventTime() { debuggingTime = eventStack.get(0).schedTick; EventManager.setEventState(EventManager.EVENTS_TIMESTEP); startDebugging(); } public void runToTime( double stopTime ) { debuggingTime = ((long)(stopTime * Process.getSimTimeFactor())); EventManager.setEventState(EventManager.EVENTS_UNTILTIME); Simulation.setSimState(Simulation.SIM_STATE_RUNNING); startDebugging(); } public void startDebugging() { synchronized( lockObject ) { if (eventStack.size() == 0) return; eventManagerThread.interrupt(); } } private void traceEvent(Event evt, int reason) { if (traceEvents) traceRecord.formatEventTrace(name, evt, reason); } void traceProcess(Entity target, String methodName) { if (traceEvents) traceRecord.formatProcessTrace(name, currentTick, target, methodName); } private void traceSchedProcess(Event target) { if (traceEvents) traceRecord.formatSchedProcessTrace(name, currentTick, target); } private void traceWaitUntil(int reason) { if (traceEvents) traceRecord.formatWaitUntilTrace(name, currentTick, reason); } /** * Holder class for event data used by the event monitor to schedule future * events. */ static class Event { final long addedTick; // The tick at which this event was queued to execute final long schedTick; // The tick at which this event will execute final int priority; // The schedule priority of this event final Process process; final Entity caller; /** * Constructs a new event object. * @param currentTick the current simulation tick * @param scheduleTick the simulation tick the event is schedule for * @param prio the event priority for scheduling purposes * @param caller * @param process */ Event(long currentTick, long scheduleTick, int prio, Entity caller, Process process) { addedTick = currentTick; schedTick = scheduleTick; priority = prio; this.process = process; this.caller = caller; } } static String getClassMethod(Event evt) { StackTraceElement[] callStack = evt.process.getStackTrace(); for (int i = 0; i < callStack.length; i++) { if (callStack[i].getClassName().equals("com.sandwell.JavaSimulation.Entity")) { return String.format("%s.%s", evt.caller.getClass().getSimpleName(), callStack[i + 1].getMethodName()); } } // Possible the process hasn't started running yet, check the Process target // state return evt.process.getClassMethod(); } static String getFileLine(Event evt) { StackTraceElement[] callStack = evt.process.getStackTrace(); for (int i = 0; i < callStack.length; i++) { if (callStack[i].getClassName().equals("com.sandwell.JavaSimulation.Entity")) { return String.format("%s:%s", callStack[i + 1].getFileName(), callStack[i + 1].getLineNumber()); } } return "Unknown method state"; } String[] getEventData(Event evt, int state) { String[] data = new String[10]; data[0] = String.format("%15d", evt.schedTick); data[1] = String.format("%15.3f", evt.schedTick / Process.getSimTimeFactor()); data[2] = String.format("%5d", evt.priority); data[3] = String.format("%s", evt.caller.getName()); data[4] = String.format("%s", evt.caller.getInputName()); data[5] = String.format("%s", ""); data[6] = EventManager.getClassMethod(evt); data[7] = EventManager.getFileLine(evt); data[8] = String.format("%15.3f", evt.addedTick / Process.getSimTimeFactor()); data[9] = "Unknown"; switch (state) { case EventManager.STATE_WAITING: data[9] = "Waiting"; break; case EventManager.STATE_EXITED: data[9] = "Ran Normally"; break; case EventManager.STATE_INTERRUPTED: data[9] = "Interrupted"; break; case EventManager.STATE_TERMINATED: data[9] = "Terminated"; break; } return data; } public String[] getViewerHeaders() { String[] headerNames = new String[10]; headerNames[0] = "Event Time"; headerNames[1] = "Simulation Time"; headerNames[2] = "Priority"; headerNames[3] = "Entity"; headerNames[4] = "Region"; headerNames[5] = "Description"; headerNames[6] = "Class.Method"; headerNames[7] = "File:Line"; headerNames[8] = "Creation Time"; headerNames[9] = "State"; return headerNames; } public String[][] getViewerData() { synchronized (lockObject) { String[][] data = new String[eventStack.size()][]; for (int i = 0; i < eventStack.size(); i++) { data[i] = getEventData(eventStack.get(i), EventManager.STATE_WAITING); if (i > 0 && eventStack.get(i).schedTick == eventStack.get(i - 1).schedTick) { data[i][0] = ""; data[i][1] = ""; } } return data; } } @Override public String toString() { return name; } }
package org.objectweb.proactive.core.rmi; import org.apache.log4j.Logger; import org.objectweb.proactive.core.util.UrlBuilder; import java.net.UnknownHostException; public class ClassServer implements Runnable { protected static Logger logger = Logger.getLogger(ClassServer.class.getName()); public static final int DEFAULT_SERVER_BASE_PORT = 2010; protected static int DEFAULT_SERVER_PORT_INCREMENT = 20; protected static int MAX_RETRY = 50; private static java.util.Random random = new java.util.Random(); protected static int port; static { String newport; if(System.getProperty("proactive.http.port") != null){ newport = System.getProperty("proactive.http.port"); } else { newport = new Integer(DEFAULT_SERVER_BASE_PORT).toString(); System.setProperty("proactive.http.port", newport); } } protected String hostname; private java.net.ServerSocket server = null; protected String paths; /** * Constructs a ClassServer that listens on a random port. The port number * used is the first one found free starting from a default base port. * obtains a class's bytecodes using the method <b>getBytes</b>. * @exception java.io.IOException if the ClassServer could not listen on any port. */ protected ClassServer() throws java.io.IOException { this(0, null); } protected ClassServer(int port_) throws java.io.IOException { if (port == 0) { port = boundServerSocket(Integer.parseInt(System.getProperty("proactive.http.port")), MAX_RETRY); } else { port = port_; server = new java.net.ServerSocket(port); } hostname = java.net.InetAddress.getLocalHost().getHostAddress(); newListener(); // if (logger.isInfoEnabled()) { // logger.info("communication protocol = " +System.getProperty("proactive.communication.protocol")+", http server port = " + port); } /** * Constructs a ClassServer that listens on <b>port</b> and * obtains a class's bytecodes using the method <b>getBytes</b>. * @param port the port number * @exception java.io.IOException if the ClassServer could not listen * on <b>port</b>. */ protected ClassServer(int port_, String paths) throws java.io.IOException { this(port_); this.paths = paths; printMessage(); } /** * Constructs a ClassFileServer. * @param classpath the classpath where the server locates classes */ public ClassServer(String paths) throws java.io.IOException { this(0, paths); } public static boolean isPortAlreadyBound(int port) { java.net.Socket socket = null; try { socket = new java.net.Socket(java.net.InetAddress.getLocalHost(), port); // if we can connect to the port it means the server already exists return true; } catch (java.io.IOException e) { return false; } finally { try { if (socket != null) { socket.close(); } } catch (java.io.IOException e) { } } } private void printMessage() { if (logger.isDebugEnabled()) { logger.debug( "To use this ClassFileServer set the property java.rmi.server.codebase to http: hostname + ":" + port + "/"); } if (this.paths == null) { logger.info( " --> This ClassFileServer is reading resources from classpath"); } else { logger.info( " --> This ClassFileServer is reading resources from the following paths"); //for (int i = 0; i < codebases.length; i++) { logger.info(paths); //codebases[i].getAbsolutePath()); } } public static int getServerSocketPort() { return port; } public String getHostname() { return hostname; } public static String getUrl() { try { return UrlBuilder.buildUrl(java.net.InetAddress.getLocalHost().getCanonicalHostName(), "", "http:", port); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } return UrlBuilder.buildUrl("localhost", "", "http:", port); } /** * The "listen" thread that accepts a connection to the * server, parses the header to obtain the class file name * and sends back the bytecodes for the class (or error * if the class is not found or the response was malformed). */ public void run() { java.net.Socket socket = null; // accept a connection while (true) { try { socket = server.accept(); HTTPRequestHandler service = (new HTTPRequestHandler(socket, paths)); service.start(); } catch (java.io.IOException e) { System.out.println("Class Server died: " + e.getMessage()); e.printStackTrace(); return; } } } private void newListener() { (new Thread(this, "ClassServer-" + hostname + ":" + port)).start(); } private int boundServerSocket(int basePortNumber, int numberOfTry) throws java.io.IOException { for (int i = 0; i < numberOfTry; i++) { try { server = new java.net.ServerSocket(basePortNumber); return basePortNumber; } catch (java.io.IOException e) { basePortNumber += random.nextInt(DEFAULT_SERVER_PORT_INCREMENT); System.setProperty("proactive.http.port", basePortNumber + ""); } } throw new java.io.IOException( "ClassServer cannot create a ServerSocket after " + numberOfTry + " attempts !!!"); } }
package com.skidsdev.fyrestone.item; import net.minecraft.item.Item; import net.minecraft.item.Item.ToolMaterial; import net.minecraftforge.common.util.EnumHelper; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.oredict.OreDictionary; public final class ItemRegister { public static Item itemShard; public static Item itemFyrestoneIngot; public static Item itemEarthstoneIngot; public static Item itemMysticalOrb; public static Item itemFyrestoneSword; public static Item itemEarthstoneSword; public static Item itemFyrestoneCatalyst; public static ToolMaterial FYRESTONE = EnumHelper.addToolMaterial("FYRESTONE", 2, 500, 10.0F, 2.0F, 18); public static ToolMaterial EARTHSTONE = EnumHelper.addToolMaterial("EARTHSTONE", 3, 2500, 14.0F, 1.4F, 22); public static final void createItems() { GameRegistry.register(itemShard = new ItemBaseShard()); GameRegistry.register(itemFyrestoneIngot = new BaseItem("itemFyrestoneIngot")); GameRegistry.register(itemEarthstoneIngot = new BaseItem("itemEarthstoneIngot")); GameRegistry.register(itemMysticalOrb = new BaseItem("itemMysticalOrb")); GameRegistry.register(itemFyrestoneCatalyst = new BaseItem("itemFyrestoneCatalyst")); GameRegistry.register(itemFyrestoneSword = new ItemFyrestoneSword("itemFyrestoneSword", FYRESTONE)); GameRegistry.register(itemEarthstoneSword = new ItemEarthstoneSword("itemEarthstoneSword", EARTHSTONE)); OreDictionary.registerOre("ingotFyrestone", itemFyrestoneIngot); OreDictionary.registerOre("ingotEarthstone", itemEarthstoneIngot); OreDictionary.registerOre("itemMysticalOrb", itemMysticalOrb); OreDictionary.registerOre("itemFyrestoneCatalyst", itemFyrestoneCatalyst); } }
package org.opencms.workplace.explorer; import org.opencms.file.CmsProperty; import org.opencms.file.CmsPropertyDefinition; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.i18n.CmsEncoder; import org.opencms.jsp.CmsJspActionElement; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.util.CmsStringUtil; import org.opencms.workplace.CmsWorkplace; import org.opencms.workplace.CmsWorkplaceException; import org.opencms.xml.CmsXmlException; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.commons.fileupload.FileItem; import org.apache.commons.logging.Log; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.io.DocumentResult; import org.dom4j.io.DocumentSource; /** * The new resource upload dialog handles the upload of cvs files. They are converted in a first step to xml * and in a second step transformed via a xsl stylesheet.<p> * * The following files use this class: * <ul> * <li>/commons/newcvsfile_upload.jsp * </ul> * <p> * * @author Jan Baudisch * * @version $Revision: 1.18 $ * * @since 6.0.0 */ public class CmsNewCsvFile extends CmsNewResourceUpload { /** Constant for automatically selecting the best fitting delimiter. */ public static final String BEST_DELIMITER = "best"; /** Constant for the height of the dialog frame. */ public static final String FRAMEHEIGHT = "450"; /** Request parameter name for the CSV content. */ public static final String PARAM_CSVCONTENT = "csvcontent"; /** Request parameter name for the delimiter. */ public static final String PARAM_DELIMITER = "delimiter"; /** Request parameter name for the XSLT file. */ public static final String PARAM_XSLTFILE = "xsltfile"; /** Constant for the xslt file suffix for table transformations. */ public static final String TABLE_XSLT_SUFFIX = ".table.xslt"; /** Constant for the tab-value inside delimiter the select. */ public static final String TABULATOR = "tab"; /** The delimiter to separate the text. */ public static final char TEXT_DELIMITER = '"'; /** the delimiters, the csv data can be separated with.*/ static final String[] DELIMITERS = {";", ",", "\t"}; /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsNewCsvFile.class); /** The pasted CSV content. */ private String m_paramCsvContent; /** The delimiter to separate the CSV values. */ private String m_paramDelimiter; /** The XSLT File to transform the table with. */ private String m_paramXsltFile; /** * Public constructor with JSP action element.<p> * * @param jsp an initialized JSP action element */ public CmsNewCsvFile(CmsJspActionElement jsp) { super(jsp); } /** * Public constructor with JSP variables.<p> * * @param context the JSP page context * @param req the JSP request * @param res the JSP response */ public CmsNewCsvFile(PageContext context, HttpServletRequest req, HttpServletResponse res) { this(new CmsJspActionElement(context, req, res)); } /** * Converts CSV data to xml.<p> * * @return a XML representation of the csv data * * @param csvData the csv data to convert * @param colGroup the format definitions for the table columns, can be null * @param delimiter the delimiter to separate the values with * * @throws IOException if there is an IO problem */ private String getTableHtml() throws IOException { String csvData = getParamCsvContent(); String lineSeparator = System.getProperty("line.separator"); String formatString = csvData.substring(0, csvData.indexOf(lineSeparator)); String delimiter = getParamDelimiter(); int[] headerColSpan = null; StringBuffer xml = new StringBuffer("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><table>"); if (isFormattingInformation(formatString, delimiter)) { // transform formatting to HTML colgroup xml.append(getColGroup(formatString, delimiter)); // cut of first line csvData = csvData.substring(formatString.length() + lineSeparator.length()); headerColSpan = getColSpans(formatString, delimiter); } // first line String line; BufferedReader br = new BufferedReader(new StringReader(csvData)); if ((line = br.readLine()) != null) { xml.append("<tr>\n"); String[] words = CmsStringUtil.splitAsArray(line, delimiter); for (int i = 0; i < words.length; i++) { xml.append("\t<td align=\"center\""); if ((headerColSpan != null) && (headerColSpan.length > i) && (headerColSpan[i] > 1)) { xml.append(" colspan=\"").append(headerColSpan[i]).append("\""); } xml.append(">").append(removeStringDelimiters(words[i])).append("</td>\n"); } xml.append("</tr>\n"); while ((line = br.readLine()) != null) { xml.append("<tr>\n"); words = CmsStringUtil.splitAsArray(line, delimiter); for (int i = 0; i < words.length; i++) { xml.append("\t<td>").append(removeStringDelimiters(words[i])).append("</td>\n"); } xml.append("</tr>\n"); } } return xml.append("</table>").toString(); } /** * Removes the string delimiters from a key (as well as any white space * outside the delimiters).<p> * * @param key the key (including delimiters) * * @return the key without delimiters */ private static String removeStringDelimiters(String key) { String k = key.trim(); if (CmsStringUtil.isNotEmpty(k)) { if (k.charAt(0) == TEXT_DELIMITER) { k = k.substring(1); } if (k.charAt(k.length() - 1) == TEXT_DELIMITER) { k = k.substring(0, k.length() - 1); } } return k; } /** * Uploads the specified file and transforms it to HTML.<p> * * @throws JspException if inclusion of error dialog fails */ public void actionUpload() throws JspException { String newResname = ""; try { if (CmsStringUtil.isNotEmpty(getParamCsvContent())) { // csv content is pasted in the textarea newResname = "csvcontent.html"; setParamNewResourceName(""); } else { setParamCsvContent(new String(getFileContentFromUpload(), CmsEncoder.ENCODING_ISO_8859_1)); newResname = getCms().getRequestContext().getFileTranslator().translateResource( CmsResource.getName(getParamResource().replace('\\', '/'))); newResname = CmsStringUtil.changeFileNameSuffixTo(newResname, "html"); setParamNewResourceName(newResname); } setParamResource(newResname); setParamResource(computeFullResourceName()); int resTypeId = OpenCms.getResourceManager().getDefaultTypeForName(newResname).getTypeId(); CmsProperty styleProp = CmsProperty.getNullProperty(); // set the delimiter String delimiter = getParamDelimiter(); if (TABULATOR.equals(delimiter)) { delimiter = "\t"; } else if (BEST_DELIMITER.equals(delimiter)) { delimiter = getPreferredDelimiter(getParamCsvContent()); } setParamDelimiter(delimiter); // transform csv to html String xmlContent = ""; try { xmlContent = getTableHtml(); } catch (IOException e) { throw new CmsXmlException(Messages.get().container(Messages.ERR_CSV_XML_TRANSFORMATION_FAILED_0)); } // if xslt file parameter is set, transform the raw html and set the css stylesheet property // of the converted file to that of the stylesheet if (CmsStringUtil.isNotEmpty(getParamXsltFile())) { xmlContent = applyXslTransformation2(getParamXsltFile(), xmlContent); styleProp = getCms().readPropertyObject(getParamXsltFile(), CmsPropertyDefinition.PROPERTY_STYLESHEET, true); } byte[] content = xmlContent.getBytes(); try { // create the resource getCms().createResource(getParamResource(), resTypeId, content, Collections.EMPTY_LIST); } catch (CmsException e) { // resource was present, overwrite it getCms().lockResource(getParamResource()); getCms().replaceResource(getParamResource(), resTypeId, content, null); } // copy xslt stylesheet-property to the new resource if (!styleProp.isNullProperty()) { getCms().writePropertyObject(getParamResource(), styleProp); } } catch (Throwable e) { // error uploading file, show error dialog setParamMessage(Messages.get().getBundle(getLocale()).key(Messages.ERR_TABLE_IMPORT_FAILED_0)); includeErrorpage(this, e); } } /** * Tests if the given string is a <code>delimiter</code> separated list of Formatting Information.<p> * * @param formatString the string to check * @param delimiter the list separators * * @return true if the string is a <code>delimiter</code> separated list of Formatting Information */ private static boolean isFormattingInformation(String formatString, String delimiter) { String[] formatStrings = formatString.split(delimiter); for (int i = 0; i < formatStrings.length; i++) { if (!formatStrings[i].trim().matches("[lcr][1-9]?")) { return false; } } return true; } /** * Converts a delimiter separated format string int o colgroup html fragment.<p> * @param formatString the formatstring to convert * @param delimiter the delimiter the formats (l,r or c) are delimited with * * @return the resulting colgroup HTML */ private static String getColGroup(String formatString, String delimiter) { StringBuffer colgroup = new StringBuffer(128); String[] formatStrings = formatString.split(delimiter); colgroup.append("<colgroup>"); for (int i = 0; i < formatStrings.length; i++) { colgroup.append("<col align=\""); char align = formatStrings[i].trim().charAt(0); switch (align) { case 'l': colgroup.append("left"); break; case 'c': colgroup.append("center"); break; case 'r': colgroup.append("right"); break; default: throw new RuntimeException("invalid format option"); } colgroup.append("\"/>"); } return colgroup.append("</colgroup>").toString(); } /** * Converts a delimiter separated format string int o colgroup html fragment.<p> * @param formatString the formatstring to convert * @param delimiter the delimiter the formats (l,r or c) are delimited with * * @return the resulting colgroup HTML */ private static int[] getColSpans(String formatString, String delimiter) { String[] formatStrings = formatString.split(delimiter); int[] colSpans = new int[formatStrings.length]; for (int i = 0; i < formatStrings.length; i++) { String colSpan = formatStrings[i].trim().substring(1); if (CmsStringUtil.isEmpty(colSpan)) { colSpans[i] = 1; continue; } else { colSpans[i] = Integer.parseInt(colSpan); } } return colSpans; } /** * Applies a XSLT Transformation to the xmlContent.<p> * * @param xsltFile the XSLT transformation file * @param xmlContent the XML content to transform * * @return the transformed xml * * @throws Exception if something goes wrong */ public String applyXslTransformation(String xsltFile, String xmlContent) throws Exception { TransformerFactory factory = TransformerFactory.newInstance(); InputStream stylesheet = new ByteArrayInputStream(getCms().readFile(xsltFile).getContents()); Transformer transformer = factory.newTransformer(new StreamSource(stylesheet)); //transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); Document document = DocumentHelper.parseText(xmlContent); DocumentSource source = new DocumentSource(document); DocumentResult streamResult = new DocumentResult(); // transform the xml with the xslt stylesheet transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); // we want to pretty format the XML output // note : this is broken in jdk1.5 beta! transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(source, streamResult); String result = streamResult.getDocument().asXML(); return result; } /** * Applies a XSLT Transformation to the xmlContent.<p> * * @param xsltFile the XSLT transformation file * @param xmlContent the XML content to transform * * @return the transformed xml * * @throws Exception if something goes wrong */ public String applyXslTransformation2(String xsltFile, String xmlContent) throws Exception { // JAXP reads data Source xmlSource = new StreamSource(new StringReader(xmlContent)); String xsltString = new String(getCms().readFile(xsltFile).getContents()); Source xsltSource = new StreamSource(new StringReader(xsltString)); TransformerFactory transFact = TransformerFactory.newInstance(); Transformer trans = transFact.newTransformer(xsltSource); StringWriter writer = new StringWriter(); trans.transform(xmlSource, new StreamResult(writer)); String result = writer.toString(); return result; } /** * Builds a html select for Delimiters. * * @return html select code with the possible available xslt files */ public String buildDelimiterSelect() { Object[] optionStrings = new Object[] { key("input.bestmatching"), key("input.semicolon"), key("input.comma"), key("input.tab")}; List options = new ArrayList(Arrays.asList(optionStrings)); List values = new ArrayList(Arrays.asList(new Object[] {"best", ";", ",", "tab"})); String parameters = "name=\"" + PARAM_DELIMITER + "\" class=\"maxwidth\""; return buildSelect(parameters, options, values, 0); } /** * Builds a html select for the XSLT files. * * @return html select code with the possible available xslt files */ public String buildXsltSelect() { // read all xslt files List xsltFiles = getXsltFiles(); if (xsltFiles.size() > 0) { List options = new ArrayList(); List values = new ArrayList(); options.add(key("input.nostyle")); values.add(""); CmsResource resource; CmsProperty titleProp = null; Iterator i = xsltFiles.iterator(); while (i.hasNext()) { resource = (CmsResource)i.next(); try { titleProp = getCms().readPropertyObject( resource.getRootPath(), CmsPropertyDefinition.PROPERTY_TITLE, false); } catch (CmsException e) { if (LOG.isWarnEnabled()) { LOG.warn(e); } } values.add(resource.getRootPath()); // display the title if set or otherwise the filename if (titleProp.isNullProperty()) { options.add("[" + resource.getName() + "]"); } else { options.add(titleProp.getValue()); } } StringBuffer result = new StringBuffer(512); // build a select box and a table row around result.append("<tr><td style=\"white-space: nowrap;\" unselectable=\"on\">"); result.append(key("input.xsltfile")); result.append("</td><td class=\"maxwidth\">"); String parameters = "class=\"maxwidth\" name=\"" + PARAM_XSLTFILE + "\""; result.append(buildSelect(parameters, options, values, 0)); result.append("</td><tr>"); return result.toString(); } else { return ""; } } /** * Returns the content of the file upload and sets the resource name.<p> * * @return the byte content of the uploaded file * @throws CmsWorkplaceException if the filesize if greater that maxFileSizeBytes or if the upload file cannot be found */ public byte[] getFileContentFromUpload() throws CmsWorkplaceException { byte[] content; // get the file item from the multipart request Iterator i = getMultiPartFileItems().iterator(); FileItem fi = null; while (i.hasNext()) { fi = (FileItem)i.next(); if (fi.getName() != null) { // found the file object, leave iteration break; } else { // this is no file object, check next item continue; } } if (fi != null) { long size = fi.getSize(); if (size == 0) { throw new CmsWorkplaceException(Messages.get().container(Messages.ERR_UPLOAD_FILE_NOT_FOUND_0)); } long maxFileSizeBytes = OpenCms.getWorkplaceManager().getFileBytesMaxUploadSize(getCms()); // check file size if (maxFileSizeBytes > 0 && size > maxFileSizeBytes) { throw new CmsWorkplaceException(Messages.get().container( Messages.ERR_UPLOAD_FILE_SIZE_TOO_HIGH_1, new Long(maxFileSizeBytes / 1024))); } content = fi.get(); fi.delete(); setParamResource(fi.getName()); } else { throw new CmsWorkplaceException(Messages.get().container(Messages.ERR_UPLOAD_FILE_NOT_FOUND_0)); } return content; } /** * Returns the height of the head frameset.<p> * * @return the height of the head frameset */ public String getHeadFrameSetHeight() { return FRAMEHEIGHT; } /** * Returns the pasted csv content.<p> * * @return the csv content */ public String getParamCsvContent() { return m_paramCsvContent; } /** * Returns the delimiter to separate the CSV values.<p> * * @return the delimiter to separate the CSV values */ public String getParamDelimiter() { return m_paramDelimiter; } /** * Returns the xslt file to transform the xml with.<p> * * @return the path to the xslt file to transform the xml with or null if it is not set */ public String getParamXsltFile() { return m_paramXsltFile; } /** * returns the Delimiter that most often occures in the CSV content.<p> * * @param csvData the comma separated values * * @return the delimiter, that is best applicable for the csvData */ public String getPreferredDelimiter(String csvData) { String bestMatch = ""; int bestMatchCount = 0; // find for each delimiter, how often it occures in the String csvData for (int i = 0; i < DELIMITERS.length; i++) { int currentCount = csvData.split(DELIMITERS[i]).length; if (currentCount > bestMatchCount) { bestMatch = DELIMITERS[i]; bestMatchCount = currentCount; } } return bestMatch; } /** * Returns a list of CmsResources with the xslt files in the modules folder.<p> * * @return a list of the available xslt files */ public List getXsltFiles() { List result = new ArrayList(); try { int resourceTypeGenericXmlContent = OpenCms.getResourceManager().getResourceType("xmlcontent").getTypeId(); // find all files of generic xmlcontent in the modules folder Iterator xmlFiles = getCms().readResources( CmsWorkplace.VFS_PATH_MODULES, CmsResourceFilter.DEFAULT_FILES.addRequireType(resourceTypeGenericXmlContent), true).iterator(); while (xmlFiles.hasNext()) { CmsResource xmlFile = (CmsResource)xmlFiles.next(); // filter all files with the suffix .table.xml if (xmlFile.getName().endsWith(TABLE_XSLT_SUFFIX)) { result.add(xmlFile); } } } catch (CmsException e) { LOG.error(e); } return result; } /** * Sets the pasted csv content.<p> * * @param csvContent the csv content to set */ public void setParamCsvContent(String csvContent) { m_paramCsvContent = csvContent; } /** * Sets the delimiter to separate the CSV values.<p> * * @param delimiter the delimiter to separate the CSV values. */ public void setParamDelimiter(String delimiter) { m_paramDelimiter = delimiter; } /** * Sets the path to the xslt file.<p> * * @param xsltFile the file to transform the xml with. */ public void setParamXsltFile(String xsltFile) { m_paramXsltFile = xsltFile; } }
package com.sportdataconnect.geometry; import com.google.common.collect.ImmutableList; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * * @author sportdataconnect */ public final class Triangle2D implements Polygon2D { private static final Logger LOG = LogManager.getLogger(Triangle2D.class); private Point2D pt1; private Point2D pt2; private Point2D pt3; private ImmutableList<Triangle2D> thisAsList = null; public Triangle2D(final Point2D pt1, final Point2D pt2, final Point2D pt3) { this.pt1 = pt1; this.pt2 = pt2; this.pt3 = pt3; } public Point2D getPt1() { return pt1; } public Point2D getPt2() { return pt2; } public Point2D getPt3() { return pt3; } public Point2D get(final int ix) { switch (ix) { case 0: return pt1; case 1: return pt2; case 2: return pt3; default: throw new IndexOutOfBoundsException("Expected point index of 0..2 but encountered " + ix); } } public int numPoints() { return 3; } public List<Triangle2D> toTriangles() { if (thisAsList == null) { thisAsList = ImmutableList.of(this); } return thisAsList; } public boolean contains(final Point2D pt) { Point2D ab = pt2.subtract(pt1); Point2D bc = pt3.subtract(pt2); Point2D ca = pt1.subtract(pt3); Point2D ap = pt.subtract(pt1); Point2D bp = pt.subtract(pt2); Point2D cp = pt.subtract(pt3); double cpa = ab.crossProduct(ap); double cpb = bc.crossProduct(bp); double cpc = ca.crossProduct(cp); if (cpa < 0 && cpb < 0 && cpc < 0) { return true; } else { return (cpa > 0 && cpb > 0 && cpc > 0); } } public Bounds2D getBounds() { double minX = Math.min(pt1.getX(), Math.min(pt2.getX(), pt3.getX())); double minY = Math.min(pt1.getY(), Math.min(pt2.getY(), pt3.getY())); double maxX = Math.max(pt1.getX(), Math.max(pt2.getX(), pt3.getX())); double maxY = Math.max(pt1.getY(), Math.max(pt2.getY(), pt3.getY())); return new Bounds2D(minX, maxX, minY, maxY); } }
package com.yammer.metrics; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; public class Meter implements Metered { private static final long TICK_INTERVAL = TimeUnit.SECONDS.toNanos(5); private final EWMA m1Rate = EWMA.oneMinuteEWMA(); private final EWMA m5Rate = EWMA.fiveMinuteEWMA(); private final EWMA m15Rate = EWMA.fifteenMinuteEWMA(); private final AtomicLong count = new AtomicLong(); private final long startTime; private final AtomicLong lastTick; private final Clock clock; /** * Creates a new {@link Meter}. */ public Meter() { this(Clock.defaultClock()); } /** * Creates a new {@link Meter}. * * @param clock the clock to use for the meter ticks */ Meter(Clock clock) { this.clock = clock; this.startTime = this.clock.getTick(); this.lastTick = new AtomicLong(startTime); } /** * Mark the occurrence of an event. */ public void mark() { mark(1); } /** * Mark the occurrence of a given number of events. * * @param n the number of events */ public void mark(long n) { tickIfNecessary(); count.addAndGet(n); m1Rate.update(n); m5Rate.update(n); m15Rate.update(n); } private void tickIfNecessary() { final long oldTick = lastTick.get(); final long newTick = clock.getTick(); final long age = newTick - oldTick; if (age > TICK_INTERVAL && lastTick.compareAndSet(oldTick, newTick)) { final long requiredTicks = age / TICK_INTERVAL; for (long i = 0; i < requiredTicks; i++) { m1Rate.tick(); m5Rate.tick(); m15Rate.tick(); } } } @Override public long getCount() { return count.get(); } @Override public double getFifteenMinuteRate() { tickIfNecessary(); return m15Rate.getRate(TimeUnit.SECONDS); } @Override public double getFiveMinuteRate() { tickIfNecessary(); return m5Rate.getRate(TimeUnit.SECONDS); } @Override public double getMeanRate() { if (getCount() == 0) { return 0.0; } else { final long elapsed = (clock.getTick() - startTime); return convertNsRate(getCount() / (double) elapsed); } } @Override public double getOneMinuteRate() { tickIfNecessary(); return m1Rate.getRate(TimeUnit.SECONDS); } private double convertNsRate(double ratePerNs) { return ratePerNs * (double) TimeUnit.SECONDS.toNanos(1); } }
package com.telecomsys.cmc.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonRootName; /** * The schedule message model. This encapsulates the request and response sent when the client requests details about a * scheduled message. */ @JsonRootName("schedulemessage") @JsonIgnoreProperties(ignoreUnknown = true) @JsonPropertyOrder(alphabetic = true) public class ScheduleMessage { /** * Message id of the scheduled message. */ @JsonProperty("messageID") private Long messageId; /** * Message data. */ private Message message; /** * Schedule data. */ private Schedule schedule; /** * @return the messageId */ public Long getMessageId() { return messageId; } /** * @param messageId the messageId to set */ public void setMessageId(Long messageId) { this.messageId = messageId; } /** * @return the schedule */ public Schedule getSchedule() { return schedule; } /** * @param schedule the schedule to set */ public void setSchedule(Schedule schedule) { this.schedule = schedule; } /** * @return the message */ public Message getMessage() { return message; } /** * @param message the message to set */ public void setMessage(Message message) { this.message = message; } }
// AddToAny.java // blogwt package com.willshex.blogwt.client.part; import java.util.List; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.AnchorElement; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.ScriptElement; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; import com.willshex.blogwt.client.controller.PropertyController; import com.willshex.blogwt.shared.helper.PropertyHelper; import com.willshex.blogwt.shared.helper.TagHelper; /** * @author William Shakour (billy1380) * */ public class AddToAny extends Composite { private static AddToAnyUiBinder uiBinder = GWT .create(AddToAnyUiBinder.class); interface AddToAnyUiBinder extends UiBinder<Widget, AddToAny> {} @UiField AnchorElement lnkAddToAny; @UiField Element elAddToAny; private ScriptElement elAddToAnyScript; private String title; private String url; public AddToAny () { initWidget(uiBinder.createAndBindUi(this)); String share = PropertyController.get().stringProperty( PropertyHelper.POST_SHARE_ENABLED); if (!PropertyHelper.NONE_VALUE.equals(share)) { List<String> shareWith = TagHelper.convertToTagList(share); AnchorElement anchor; Document doc = Document.get(); for (String service : shareWith) { anchor = doc.createAnchorElement(); anchor.setClassName("a2a_button_" + service); elAddToAny.appendChild(anchor); } } } /** * @param url */ public void setUrl (String url) { this.url = url; refresh(); } /* (non-Javadoc) * * @see com.google.gwt.user.client.ui.UIObject#setTitle(java.lang.String) */ @Override public void setTitle (String title) { this.title = title; refresh(); } public void refresh () { configureAddToAny(url, title); installAddToAny(url, title); } private static native void configureAddToAny (String url, String title) /*-{ $wnd.a2a_config = $wnd.a2a_config || {}; $wnd.a2a_config.linkname = title; $wnd.a2a_config.linkurl = url; }-*/; private void installAddToAny (String url, String title) { removeAddToAny(); lnkAddToAny.setHref("https: + url + "&linkname=" + title + ""); elAddToAnyScript = Document.get().createScriptElement(); elAddToAnyScript.setType("text/javascript"); elAddToAnyScript.setSrc("//static.addtoany.com/menu/page.js"); Document.get().getBody().appendChild(elAddToAnyScript); } private void removeAddToAny () { if (elAddToAnyScript != null && elAddToAnyScript.hasParentElement()) { elAddToAnyScript.removeFromParent(); } } }
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc5933.Rosieppbs.commands; import edu.wpi.first.wpilibj.I2C; import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc5933.Rosieppbs.Robot; public class LIDAR extends Command { static final int LIDARLite_ADDRESS = 0x62; static final int MEASURE_REGISTER = 0x00; static final int MEASURE_VALUE = 0x04; static final int REGISTER_HIGHLOWB = 0x8f; static final int RESPONSE_LENGTH = 2; public LIDAR() { } private int makeUnsignedByte(byte b) { return (int) b & 0xFF; } // Called just before this Command runs the first time public void getRange() { I2C LIDARDevice; LIDARDevice = new I2C(I2C.Port.kOnboard, LIDARLite_ADDRESS); System.err.println(I2C.Port.kOnboard +" " + LIDARLite_ADDRESS); byte[] initiateCommand = {MEASURE_REGISTER, MEASURE_VALUE}; byte[] readMeasurement = new byte[RESPONSE_LENGTH]; try { boolean z = LIDARDevice.writeBulk(initiateCommand); Thread.sleep(20); boolean y = LIDARDevice.write(REGISTER_HIGHLOWB,0x0); Thread.sleep(20); boolean x = LIDARDevice.readOnly(readMeasurement, RESPONSE_LENGTH); System.out.println(z + " " + y + " " + x); System.out.println(readMeasurement[0] + ", " + readMeasurement[1]); int range = (makeUnsignedByte(readMeasurement[0])<<8) + makeUnsignedByte(readMeasurement[1]); System.out.println("Range is: " + range); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // Called repeatedly when this Command is scheduled to run protected void execute() { } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } @Override protected void initialize() { // TODO Auto-generated method stub } }
package com.yahoo.sketches.hllmap; import static com.yahoo.sketches.hllmap.MapDistribution.BASE_GROWTH_FACTOR; import static com.yahoo.sketches.hllmap.MapDistribution.BASE_TGT_ENTRIES; import static com.yahoo.sketches.hllmap.MapDistribution.HLL_RESIZE_FACTOR; import static com.yahoo.sketches.hllmap.MapDistribution.NUM_LEVELS; import static com.yahoo.sketches.hllmap.MapDistribution.NUM_TRAVERSE_LEVELS; @SuppressWarnings("unused") public class UniqueCountMap { private final int targetSizeBytes_; private final int keySizeBytes_; private final int k_; // coupon is a 16-bit value similar to HLL sketch value: 10-bit address, // 6-bit number of leading zeroes in a 64-bit hash of the key + 1 // prime size, double hash, no deletes, 1-bit state array // state: 0 - value is a coupon (if used), 1 - value is a level number // same growth rule as for the next levels private final SingleCouponMap baseLevelMap; // TraverseCouponMap or HashCouponMap instances private final CouponMap[] intermediateLevelMaps; // this map has a fixed slotSize (row size). No shrinking. // Similar growth algorithm to SingleCouponMap, maybe different constants. // needs to keep 2 double values and 1 float value for HIP estimator private HllMap lastLevelMap; //@param keySizeBytes must be at least 4 bytes. public UniqueCountMap(final int targetSizeBytes, final int keySizeBytes, final int k) { Util.checkK(k); Util.checkKeySizeBytes(keySizeBytes); k_ = k; //TODO: figure out how to distribute that size between the levels targetSizeBytes_ = targetSizeBytes; keySizeBytes_ = keySizeBytes; baseLevelMap = SingleCouponMap.getInstance(BASE_TGT_ENTRIES, keySizeBytes, BASE_GROWTH_FACTOR); intermediateLevelMaps = new CouponMap[NUM_LEVELS]; } // This class will decide the transition points of when to promote between types of maps. public double update(final byte[] key, final byte[] identifier) { if (key == null) return Double.NaN; if (key.length != keySizeBytes_) { throw new IllegalArgumentException("Key must be " + keySizeBytes_ + " bytes long"); } if (identifier == null) return getEstimate(key); short coupon = (short) Map.coupon16(identifier, k_); final int baseLevelIndex = baseLevelMap.findOrInsertKey(key); if (baseLevelIndex < 0) { //this is a new key for the baseLevelMap. Set the coupon, keep the state bit clear. baseLevelMap.setCoupon(~baseLevelIndex, coupon, false); return 1; } final short baseLevelMapCoupon = baseLevelMap.getCoupon(baseLevelIndex); if (baseLevelMap.isCoupon(baseLevelIndex)) { if (baseLevelMapCoupon == coupon) return 1; //duplicate // promote from the base level baseLevelMap.setCoupon(baseLevelIndex, (short) 1, true); //set coupon = Level 1; state = 1 if (intermediateLevelMaps[0] == null) { intermediateLevelMaps[0] = new CouponTraverseMap(keySizeBytes_, 2); } intermediateLevelMaps[0].update(key, baseLevelMapCoupon); intermediateLevelMaps[0].update(key, coupon); return 2; } int level = baseLevelMapCoupon; if (level <= NUM_LEVELS) { final CouponMap map = intermediateLevelMaps[level - 1]; final int index = map.findOrInsertKey(key); final double estimate = map.findOrInsertCoupon(index, coupon); if (estimate > 0) return estimate; // promote to the next level level++; baseLevelMap.setCoupon(baseLevelIndex, (short) level, true); //very dangerous; state = 1 final int newLevelCapacity = 1 << level; if (level <= NUM_LEVELS) { //System.out.println("promoting to level " + level + " with capacity of " + newLevelCapacity); if (intermediateLevelMaps[level - 1] == null) { if (level <= NUM_TRAVERSE_LEVELS) { intermediateLevelMaps[level - 1] = new CouponTraverseMap(keySizeBytes_, newLevelCapacity); } else { intermediateLevelMaps[level - 1] = CouponHashMap.getInstance(17, keySizeBytes_, newLevelCapacity, k_, 2F); } } final CouponMap newMap = intermediateLevelMaps[level - 1]; final CouponsIterator it = map.getCouponsIterator(key); final int newMapIndex = newMap.findOrInsertKey(key); int num = 0; while (it.next()) { final double est = newMap.findOrInsertCoupon(newMapIndex, it.getValue()); assert(est > 0); num++; } newMap.updateEstimate(newMapIndex, -estimate); map.deleteKey(index); //System.out.println("promoted coupons: " + num + ", estimate: " + -estimate); final double newEstimate = newMap.findOrInsertCoupon(newMapIndex, coupon); assert(newEstimate > 0); // this must be positive since we have just promoted return newEstimate; } else { // promoting to the last level //System.out.println("promoting to the last level"); if (lastLevelMap == null) { lastLevelMap = HllMap.getInstance(100, keySizeBytes_, k_, HLL_RESIZE_FACTOR); } final CouponsIterator it = map.getCouponsIterator(key); final int lastLevelIndex = lastLevelMap.findOrInsertKey(key); int num = 0; while (it.next()) { lastLevelMap.findOrInsertCoupon(lastLevelIndex, it.getValue()); num++; } //System.out.println("promoted coupons: " + num + ", estimate: " + -estimate); lastLevelMap.updateEstimate(lastLevelIndex, -estimate); map.deleteKey(index); final double newEstimate = lastLevelMap.findOrInsertCoupon(lastLevelIndex, coupon); assert(newEstimate > 0); // this must be positive since we have just promoted return newEstimate; } } return lastLevelMap.update(key, coupon); } public double getEstimate(final byte[] key) { if (key == null) return Double.NaN; if (key.length != keySizeBytes_) throw new IllegalArgumentException("Key must be " + keySizeBytes_ + " bytes long"); final int index = baseLevelMap.findKey(key); if (index < 0) return 0; if (baseLevelMap.isCoupon(index)) return 1; final short level = baseLevelMap.getCoupon(index); if (level <= NUM_LEVELS) { final Map map = intermediateLevelMaps[level - 1]; return map.getEstimate(key); } return lastLevelMap.getEstimate(key); } }
package com.yammer.schedulizer.entities; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableSet; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.NotEmpty; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.util.HashSet; import java.util.Set; @Entity @Table(name = "employees", uniqueConstraints = @UniqueConstraint(columnNames = {"yammer_id"})) public class Employee extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(name = "yammer_id") @NotEmpty private String yammerId; @Column(name = "name") @NotBlank private String name; @Column(name = "global_admin") @NotNull private boolean globalAdmin = false; @Column(name = "image_url_template") private String imageUrlTemplate; @OneToMany(mappedBy = "employee") @Cascade({CascadeType.DELETE}) private Set<Membership> memberships = new HashSet<>(); @OneToMany(mappedBy = "employee") @Cascade({CascadeType.DELETE}) private Set<DayRestriction> dayRestrictions = new HashSet<>(); @OneToMany(mappedBy = "employee") private Set<Assignment> assignments = new HashSet<>(); @OneToOne(mappedBy = "employee", fetch = FetchType.EAGER) @JsonIgnore private User user; /* package private */ Employee() { // Required by Hibernate } public Employee(String name, String yammerId) { this.name = name; this.yammerId = yammerId; } public Employee(String yammerId) { this.yammerId = yammerId; } public long getId() { return id; } @JsonProperty("extAppId") public String getYammerId() { return yammerId; } public void setYammerId(String yammerId) { this.yammerId = yammerId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isGlobalAdmin() { return globalAdmin; } public void setGlobalAdmin(boolean globalAdmin) { this.globalAdmin = globalAdmin; } public String getImageUrlTemplate() { return imageUrlTemplate; } public void setImageUrlTemplate(String imageUrlTemplate) { this.imageUrlTemplate = imageUrlTemplate; } @JsonIgnore public Set<Membership> getMemberships() { return ImmutableSet.copyOf(memberships); } @JsonIgnore public Set<Group> getGroups() { ImmutableSet.Builder<Group> groups = new ImmutableSet.Builder<>(); for (Membership membership : memberships) { groups.add(membership.getGroup()); } return groups.build(); } @JsonIgnore public Set<Assignment> getAssignments() { return ImmutableSet.copyOf(assignments); } public void setAssignments(Set<Assignment> assignments) { this.assignments = ImmutableSet.copyOf(assignments); } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @JsonIgnore public Set<DayRestriction> getDayRestrictions() { return ImmutableSet.copyOf(dayRestrictions); } public void setDayRestrictions(Set<DayRestriction> dayRestrictions) { this.dayRestrictions = ImmutableSet.copyOf(dayRestrictions); } }
package info.limpet.ui.xy_plot; import info.limpet.IDocument; import info.limpet.IStoreItem; import info.limpet.impl.LocationDocument; import info.limpet.impl.NumberDocument; import info.limpet.operations.CollectionComplianceTests; import info.limpet.operations.CollectionComplianceTests.TimePeriod; import info.limpet.ui.Activator; import info.limpet.ui.PlottingHelpers; import info.limpet.ui.core_view.CoreAnalysisView; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.measure.converter.UnitConverter; import javax.measure.quantity.Duration; import javax.measure.unit.SI; import javax.measure.unit.Unit; import org.eclipse.january.MetadataException; import org.eclipse.january.dataset.DoubleDataset; import org.eclipse.january.dataset.ILazyDataset; import org.eclipse.january.metadata.AxesMetadata; import org.eclipse.jface.action.Action; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IActionBars; import org.swtchart.Chart; import org.swtchart.IAxis; import org.swtchart.IAxis.Position; import org.swtchart.ILineSeries; import org.swtchart.ILineSeries.PlotSymbolType; import org.swtchart.ISeries; import org.swtchart.ISeries.SeriesType; import org.swtchart.ITitle; import org.swtchart.LineStyle; import org.swtchart.ext.InteractiveChart; /** * display analysis overview of selection * * @author ian * */ public class XyPlotView extends CoreAnalysisView { private static final int MAX_SIZE = 10000; /** * The ID of the view as specified by the extension. */ public static final String ID = "info.limpet.ui.XyPlotView"; private final CollectionComplianceTests aTests = new CollectionComplianceTests(); private Chart chart; private Action switchAxes; public XyPlotView() { super(ID, "XY plot view"); } @Override protected boolean appliesToMe(final List<IStoreItem> res, final CollectionComplianceTests tests) { final boolean allNonQuantity = tests.allNonQuantity(res); final boolean allCollections = tests.allCollections(res); final boolean allQuantity = tests.allQuantity(res); final boolean allLocation = tests.allLocation(res); final boolean suitableIndex = tests.allEqualIndexed(res) || tests.allNonIndexed(res) || allLocation; return allCollections && suitableIndex && (allQuantity || allNonQuantity); } private void clearChart() { // clear the graph final ISeries[] series = chart.getSeriesSet().getSeries(); for (int i = 0; i < series.length; i++) { final ISeries iSeries = series[i]; chart.getSeriesSet().deleteSeries(iSeries.getId()); } } private void clearGraph() { // clear the graph final ISeries[] series = chart.getSeriesSet().getSeries(); for (int i = 0; i < series.length; i++) { final ISeries iSeries = series[i]; chart.getSeriesSet().deleteSeries(iSeries.getId()); // and clear any series final IAxis[] yA = chart.getAxisSet().getYAxes(); for (int j = 1; j < yA.length; j++) { final IAxis iAxis = yA[j]; chart.getAxisSet().deleteYAxis(iAxis.getId()); } } } @Override protected void contributeToActionBars() { super.contributeToActionBars(); final IActionBars bars = getViewSite().getActionBars(); bars.getToolBarManager().add(switchAxes); bars.getMenuManager().add(switchAxes); } /** * This is a callback that will allow us to create the viewer and initialize it. */ @Override public void createPartControl(final Composite parent) { makeActions(); contributeToActionBars(); // create a chart chart = new InteractiveChart(parent, SWT.NONE); // set titles chart.getAxisSet().getXAxis(0).getTitle().setText("Value"); chart.getAxisSet().getYAxis(0).getTitle().setText("Value"); chart.getTitle().setVisible(false); // adjust the axis range chart.getAxisSet().adjustRange(); chart.getLegend().setPosition(SWT.BOTTOM); // register as selection listener setupListener(); } @Override protected void datasetDataChanged(final IStoreItem subject) { final String name; final IDocument<?> coll = (IDocument<?>) subject; if (coll.isQuantity()) { final NumberDocument cq = (NumberDocument) coll; final Unit<?> units = cq.getUnits(); name = seriesNameFor(cq, units); } else { name = coll.getName(); } final ISeries match = chart.getSeriesSet().getSeries(name); if (match != null) { chart.getSeriesSet().deleteSeries(name); } else { clearChart(); } } @Override public void display(final List<IStoreItem> res) { if (res.size() == 0) { chart.setVisible(false); } else { // check they're all one dim if (aTests.allOneDim(res)) { showOneDim(res); } else if (aTests.allTwoDim(res) && res.size() == 1) { // ok, it's a single two-dim dataset showTwoDim(res.get(0)); } } } @Override protected String getTextForClipboard() { return "Pending"; } /** * produce the graph's title text * * @param xTimeData * @param indexUnits * @return */ private String getTitleFor(final Date[] xTimeData, final Unit<?> indexUnits) { String xTitle = null; if (xTimeData != null) { xTitle = "Time"; } else { final String titlePrefix; final String theDim = indexUnits != null ? indexUnits.getDimension().toString() : "N/A"; switch (theDim) { case "[L]": titlePrefix = "Length"; break; case "[M]": titlePrefix = "Mass"; break; case "[T]": titlePrefix = "Time"; break; default: titlePrefix = theDim; break; } final String indexText = indexUnits != null ? " (" + indexUnits.toString() + ")" : ""; xTitle = titlePrefix + indexText; } return xTitle; } private double[] getYData(final int longestColl, final IDocument<?> coll, final NumberDocument thisQ) { final double[] yData; if (coll.size() == 1) { // singleton = insert it's value at every point yData = new double[longestColl]; final Number thisValue = thisQ.getValueAt(0); final double dVal = thisValue.doubleValue(); for (int i = 0; i < longestColl; i++) { yData[i] = dVal; } } else { yData = new double[thisQ.size()]; final Iterator<Double> values = thisQ.getIterator(); int ctr = 0; while (values.hasNext()) { yData[ctr++] = values.next(); } } return yData; } @Override protected void makeActions() { super.makeActions(); switchAxes = new Action("Switch axes", SWT.TOGGLE) { @Override public void run() { if (switchAxes.isChecked()) { chart.setOrientation(SWT.VERTICAL); } else { chart.setOrientation(SWT.HORIZONTAL); } } }; switchAxes.setText("Switch axes"); switchAxes.setToolTipText("Switch X and Y axes"); switchAxes.setImageDescriptor(Activator .getImageDescriptor("icons/angle.png")); } private void putOnAxis(final Chart chart, final ILineSeries newSeries, final Unit<?> newUnits) { final String unitStr = newUnits.toString(); // special case. at start we just have an empty y axis final IAxis[] yAxes = chart.getAxisSet().getYAxes(); if (yAxes.length == 1 && yAxes[0].getTitle().getText() == "") { // ok, we're only just opened. Use this one yAxes[0].getTitle().setText(unitStr); newSeries.setYAxisId(yAxes[0].getId()); } else { int leftCount = 0; int rightCount = 0; // clear the axis id, we're going to rely on it final int INVALID_ID = -10000; newSeries.setYAxisId(INVALID_ID); // ok, work through the axes for (final IAxis t : yAxes) { if (t.getTitle().getText().equals(unitStr)) { // ok, this will do newSeries.setYAxisId(t.getId()); } else { // just keep track of the count switch (t.getPosition()) { case Primary: leftCount++; break; case Secondary: default: rightCount++; break; } } } // did we store it? if (newSeries.getYAxisId() == INVALID_ID) { final Position toUse; // choose the side with the fewest, or the x if none. if (leftCount == 0) { toUse = Position.Primary; } else if (leftCount > rightCount) { toUse = Position.Secondary; } else { toUse = Position.Primary; } // create the axis final int newAxisId = chart.getAxisSet().createYAxis(); final IAxis newAxis = chart.getAxisSet().getYAxis(newAxisId); newAxis.getTitle().setText(unitStr); newAxis.setPosition(toUse); // and tell the series to use it newSeries.setYAxisId(newAxisId); } } } private String seriesNameFor(final NumberDocument thisQ, final Unit<?> theseUnits) { final String seriesName = thisQ.getName() + " (" + theseUnits + ")"; return seriesName; } @Override public void setFocus() { chart.setFocus(); } private void showIndexedQuantity(final List<IStoreItem> res) { clearGraph(); Unit<?> existingUnits = null; final List<IDocument<?>> docList = aTests.getDocumentsIn(res); // get the outer time period (used for plotting singletons) final List<IDocument<?>> safeColl = new ArrayList<IDocument<?>>(); safeColl.addAll(docList); final TimePeriod outerPeriod = aTests.getBoundingRange(res); for (final IDocument<?> coll : docList) { if (coll.isQuantity() && coll.size() >= 1 && coll.size() < MAX_SIZE) { final NumberDocument thisQ = (NumberDocument) coll; final Unit<?> theseUnits = thisQ.getUnits(); final Unit<?> indexUnits; if (thisQ.isIndexed()) { indexUnits = thisQ.getIndexUnits(); } else { indexUnits = null; } final String seriesName = seriesNameFor(thisQ, theseUnits); // do we need to create this series final ISeries match = chart.getSeriesSet().getSeries(seriesName); if (match != null) { continue; } final ILineSeries newSeries = (ILineSeries) chart.getSeriesSet().createSeries(SeriesType.LINE, seriesName); newSeries.setLineColor(PlottingHelpers.colorFor(seriesName)); // extract & store the data, but track any change to the units existingUnits = storeIndexedData(existingUnits, outerPeriod, coll, thisQ, theseUnits, indexUnits, newSeries); // adjust the axis range chart.getAxisSet().adjustRange(); final IAxis xAxis = chart.getAxisSet().getXAxis(0); xAxis.enableCategory(false); chart.redraw(); } } } private void showLocations(final List<IStoreItem> res) { clearChart(); // now loop through boolean chartUpdated = false; for (final IStoreItem document : res) { final IDocument<?> coll = (IDocument<?>) document; if (!coll.isQuantity() && coll.size() >= 1 && coll.size() < MAX_SIZE) { final String seriesName = coll.getName(); final ILineSeries newSeries = (ILineSeries) chart.getSeriesSet().createSeries(SeriesType.LINE, seriesName); newSeries.setSymbolType(PlotSymbolType.NONE); newSeries.setLineColor(PlottingHelpers.colorFor(seriesName)); newSeries.setSymbolColor(PlottingHelpers.colorFor(seriesName)); final double[] xData = new double[coll.size()]; final double[] yData = new double[coll.size()]; final LocationDocument loc = (LocationDocument) coll; int ctr = 0; final Iterator<Point2D> lIter = loc.getLocationIterator(); while (lIter.hasNext()) { final Point2D geom = lIter.next(); xData[ctr] = geom.getX(); yData[ctr++] = geom.getY(); } // clear the axis labels chart.getAxisSet().getXAxis(0).getTitle().setText(""); chart.getAxisSet().getYAxis(0).getTitle().setText(""); newSeries.setXSeries(xData); newSeries.setYSeries(yData); newSeries.setSymbolType(PlotSymbolType.CROSS); // adjust the axis range chart.getAxisSet().adjustRange(); chartUpdated = true; } } if (chartUpdated) { chart.redraw(); } } private void showOneDim(final List<IStoreItem> res) { // transform them to a lsit of documents final List<IDocument<?>> docList = aTests.getDocumentsIn(res); // they're all the same type - check the first one final Iterator<IDocument<?>> iter = docList.iterator(); final IDocument<?> first = iter.next(); // do a bit of y axis tidying. We rely on the first // axis having blank text to know when we're overwriting // the initial empty (template) dataset chart.getAxisSet().getYAxes()[0].getTitle().setText(""); // sort out what type of data this is. if (first.isQuantity()) { if (aTests.allIndexedOrSingleton(res)) { showIndexedQuantity(res); } else { showQuantity(res); } chart.setVisible(true); } else { // exception - show locations if (aTests.allLocation(res)) { showLocations(res); chart.setVisible(true); } else { chart.setVisible(false); } } } private void showQuantity(final List<IStoreItem> items) { clearGraph(); Unit<?> existingUnits = null; // get the longest collection length (used for plotting singletons) final int longestColl = aTests.getLongestCollectionLength(items); boolean chartUpdated = false; for (final IStoreItem item : items) { final IDocument<?> coll = (IDocument<?>) item; if (coll.isQuantity() && coll.size() >= 1 && coll.size() < MAX_SIZE) { final NumberDocument thisQ = (NumberDocument) coll; final Unit<?> theseUnits = thisQ.getUnits(); final String seriesName = seriesNameFor(thisQ, theseUnits); // do we need to create this series final ISeries match = chart.getSeriesSet().getSeries(seriesName); if (match != null) { continue; } existingUnits = showThisNumberDocument(existingUnits, longestColl, coll, thisQ, theseUnits, seriesName); chartUpdated = true; } } if (chartUpdated) { chart.redraw(); } } private Unit<?> showThisNumberDocument(final Unit<?> existingUnits, final int longestColl, final IDocument<?> coll, final NumberDocument thisQ, final Unit<?> theseUnits, final String seriesName) { final Unit<?> NewUnits = existingUnits; final ILineSeries newSeries = (ILineSeries) chart.getSeriesSet().createSeries(SeriesType.LINE, seriesName); final PlotSymbolType theSym; // if it's a singleton, show the symbol // markers if (thisQ.size() > 100 || thisQ.size() == 1) { theSym = PlotSymbolType.NONE; } else { theSym = PlotSymbolType.CIRCLE; } newSeries.setSymbolType(theSym); newSeries.setLineColor(PlottingHelpers.colorFor(seriesName)); newSeries.setSymbolColor(PlottingHelpers.colorFor(seriesName)); // get the data, depending on if it's a singleton or not final double[] yData = getYData(longestColl, coll, thisQ); // loop through the axes, see if we have suitable putOnAxis(chart, newSeries, theseUnits); // // ok, do we have existing data? // if (existingUnits != null && !existingUnits.equals(theseUnits)) // // create second Y axis // final int axisId = chart.getAxisSet().createYAxis(); // // set the properties of second Y axis // final IAxis yAxis2 = chart.getAxisSet().getYAxis(axisId); // yAxis2.getTitle().setText(theseUnits.toString()); // yAxis2.setPosition(Position.Secondary); // newSeries.setYAxisId(axisId); // else // chart.getAxisSet().getYAxes()[0].getTitle() // .setText(theseUnits.toString()); // NewUnits = theseUnits; newSeries.setYSeries(yData); // if it's a monster line, we won't plot // markers if (thisQ.size() > 90) { newSeries.setSymbolType(PlotSymbolType.NONE); newSeries.setLineWidth(2); } else { newSeries.setSymbolType(PlotSymbolType.CROSS); } chart.getAxisSet().getXAxis(0).getTitle().setText("Count"); // adjust the axis range chart.getAxisSet().adjustRange(); final IAxis xAxis = chart.getAxisSet().getXAxis(0); xAxis.enableCategory(false); return NewUnits; } private void showTwoDim(final IStoreItem item) { final NumberDocument thisQ = (NumberDocument) item; clearGraph(); final String seriesName = thisQ.getName(); final ILineSeries newSeries = (ILineSeries) chart.getSeriesSet().createSeries(SeriesType.LINE, seriesName); final PlotSymbolType theSym; // if it's a singleton, show the symbol // markers if (thisQ.size() > 500 || thisQ.size() == 1) { theSym = PlotSymbolType.NONE; } else { theSym = PlotSymbolType.CIRCLE; } newSeries.setSymbolType(theSym); newSeries.setLineStyle(LineStyle.NONE); newSeries.setSymbolColor(PlottingHelpers.colorFor(seriesName)); // ok, show this 2d dataset final NumberDocument nd = (NumberDocument) item; try { // sort out the axes final List<AxesMetadata> amList = nd.getDataset().getMetadata(AxesMetadata.class); final AxesMetadata am = amList.get(0); final ILazyDataset[] axes = am.getAxes(); if (axes.length == 2) { final DoubleDataset aOne = (DoubleDataset) axes[0]; final DoubleDataset aTwo = (DoubleDataset) axes[1]; final double[] aIndices = aOne.getData(); final double[] bIndices = aTwo.getData(); // loop through the data final List<Double> xValues = new ArrayList<Double>(); final List<Double> yValues = new ArrayList<Double>(); final DoubleDataset dataset = (DoubleDataset) nd.getDataset(); // process the data for (int i = 0; i < aIndices.length; i++) { for (int j = 0; j < bIndices.length; j++) { final Double thisVal = dataset.get(i, j); if (!thisVal.equals(Double.NaN)) { xValues.add(aIndices[i]); yValues.add(bIndices[j]); } } } final double[] xArr = toArray(xValues); final double[] yArr = toArray(yValues); newSeries.setXSeries(xArr); newSeries.setYSeries(yArr); chart.getAxisSet().getYAxes()[0].getTitle().setText( "" + nd.getIndexUnits()); chart.getAxisSet().getXAxes()[0].getTitle().setText( "" + nd.getIndexUnits()); // adjust the axis range chart.getAxisSet().adjustRange(); } } catch (final MetadataException e) { e.printStackTrace(); // ok, just drop out } } private Unit<?> storeIndexedData(final Unit<?> existingUnits, final TimePeriod outerPeriod, final IDocument<?> coll, final NumberDocument thisQ, final Unit<?> theseUnits, final Unit<?> indexUnits, final ILineSeries newSeries) { final Unit<?> newUnits = existingUnits; final Date[] xTimeData; final double[] xData; final double[] yData; if (coll.isIndexed()) { // sort out the destination data type final boolean isTemporal = indexUnits != null && indexUnits.getDimension() != null && indexUnits.getDimension().equals(SI.SECOND.getDimension()); if (isTemporal) { xTimeData = new Date[thisQ.size()]; xData = null; } else { xData = new double[thisQ.size()]; xTimeData = null; } yData = new double[thisQ.size()]; storeListOfIndexedData(coll, thisQ, indexUnits, xTimeData, xData, yData, isTemporal); } else { // non temporal, include it as a marker line // must be non temporal xTimeData = new Date[2]; xData = null; yData = new double[2]; // get the singleton value final Double theValue = thisQ.getIterator().next(); // create the marker line xTimeData[0] = new Date((long) outerPeriod.getStartTime()); yData[0] = theValue; xTimeData[1] = new Date((long) outerPeriod.getEndTime()); yData[1] = theValue; } if (xTimeData != null) { newSeries.setXDateSeries(xTimeData); } else if (xData != null) { newSeries.setXSeries(xData); } else { System.err.println("We haven't correctly collated data"); } newSeries.setYSeries(yData); // loop through the axes, see if we have suitable putOnAxis(chart, newSeries, theseUnits); // if it's a monster line, we won't plot // markers if (thisQ.size() > 90) { newSeries.setSymbolType(PlotSymbolType.NONE); newSeries.setLineWidth(2); } else { newSeries.setSymbolType(PlotSymbolType.CROSS); } // and the x axis title final String xTitleStr = getTitleFor(xTimeData, indexUnits); final ITitle xTitle = chart.getAxisSet().getXAxis(0).getTitle(); if (!xTitleStr.equals(xTitle.getText())) { xTitle.setText(xTitleStr); } return newUnits; } private void storeListOfIndexedData(final IDocument<?> coll, final NumberDocument thisQ, final Unit<?> indexUnits, final Date[] xTimeData, final double[] xData, final double[] yData, final boolean isTemporal) { // must be temporal final Iterator<Double> index = coll.getIndex(); final Iterator<Double> values = thisQ.getIterator(); int ctr = 0; final Unit<Duration> millis = SI.SECOND.divide(1000); while (values.hasNext()) { final double t = index.next(); if (isTemporal) { final long value; if (indexUnits.equals(millis)) { value = (long) t; } else { // do we need to convert to millis? final UnitConverter converter = indexUnits.getConverterTo(millis); value = (long) converter.convert(t); } xTimeData[ctr] = new Date(value); } else { xData[ctr] = t; } yData[ctr++] = values.next(); } } private double[] toArray(final List<Double> xData) { final double[] res = new double[xData.size()]; for (int i = 0; i < xData.size(); i++) { res[i] = xData.get(i); } return res; } }
// 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.microsoft.aad.adal; import java.io.Serializable; import java.util.Date; import static com.microsoft.aad.adal.TelemetryUtils.CliTelemInfo; /** * Result class to keep code, token and other info Serializable properties Mark * temp properties as Transient if you dont want to keep them in serialization. */ public class AuthenticationResult implements Serializable { /** * Serial version number for serialization. */ private static final long serialVersionUID = 2243372613182536368L; /** * Status for authentication. */ public enum AuthenticationStatus { /** * User cancelled login activity. */ Cancelled, /** * request has errors. */ Failed, /** * token is acquired. */ Succeeded, } private String mCode; private String mAccessToken; private String mRefreshToken; private String mTokenType; private Date mExpiresOn; private String mErrorCode; private String mErrorDescription; private String mErrorCodes; private boolean mIsMultiResourceRefreshToken; private UserInfo mUserInfo; private String mTenantId; private String mIdToken; private AuthenticationStatus mStatus = AuthenticationStatus.Failed; private boolean mInitialRequest; private String mFamilyClientId; private boolean mIsExtendedLifeTimeToken = false; private Date mExtendedExpiresOn; private String mAuthority; private CliTelemInfo mCliTelemInfo; AuthenticationResult() { mCode = null; } AuthenticationResult(String code) { mCode = code; mStatus = AuthenticationStatus.Succeeded; mAccessToken = null; mRefreshToken = null; } AuthenticationResult(String accessToken, String refreshToken, Date expires, boolean isBroad, UserInfo userInfo, String tenantId, String idToken, Date extendedExpires) { mCode = null; mAccessToken = accessToken; mRefreshToken = refreshToken; mExpiresOn = expires; mIsMultiResourceRefreshToken = isBroad; mStatus = AuthenticationStatus.Succeeded; mUserInfo = userInfo; mTenantId = tenantId; mIdToken = idToken; mExtendedExpiresOn = extendedExpires; } AuthenticationResult(String accessToken, String refreshToken, Date expires, boolean isBroad, Date extendedExpires) { mCode = null; mAccessToken = accessToken; mRefreshToken = refreshToken; mExpiresOn = expires; mIsMultiResourceRefreshToken = isBroad; mStatus = AuthenticationStatus.Succeeded; mExtendedExpiresOn = extendedExpires; } AuthenticationResult(String errorCode, String errDescription, String errorCodes) { mErrorCode = errorCode; mErrorDescription = errDescription; mErrorCodes = errorCodes; mStatus = AuthenticationStatus.Failed; } /** * Creates result from {@link TokenCacheItem}. * * @param cacheItem TokenCacheItem to be converted. * @return AuthenticationResult */ static AuthenticationResult createResult(final TokenCacheItem cacheItem) { if (cacheItem == null) { AuthenticationResult result = new AuthenticationResult(); result.mStatus = AuthenticationStatus.Failed; return result; } final AuthenticationResult result = new AuthenticationResult(cacheItem.getAccessToken(), cacheItem.getRefreshToken(), cacheItem.getExpiresOn(), cacheItem.getIsMultiResourceRefreshToken(), cacheItem.getUserInfo(), cacheItem.getTenantId(), cacheItem.getRawIdToken(), cacheItem.getExtendedExpiresOn()); return result; } static AuthenticationResult createResultForInitialRequest() { AuthenticationResult result = new AuthenticationResult(); result.mInitialRequest = true; return result; } static AuthenticationResult createExtendedLifeTimeResult(final TokenCacheItem accessTokenItem) { final AuthenticationResult retryResult = createResult(accessTokenItem); retryResult.setExpiresOn(retryResult.getExtendedExpiresOn()); retryResult.setIsExtendedLifeTimeToken(true); return retryResult; } /** * Uses access token to create header for web requests. * * @return AuthorizationHeader */ public String createAuthorizationHeader() { return AuthenticationConstants.AAD.BEARER + " " + getAccessToken(); } /** * Access token to send to the service in Authorization Header. * * @return Access token */ public String getAccessToken() { return mAccessToken; } /** * Refresh token to get new tokens. * * @return Refresh token */ public String getRefreshToken() { return mRefreshToken; } /** * Token type. * * @return access token type */ public String getAccessTokenType() { return mTokenType; } /** * Epoch time for expiresOn. * * @return expiresOn {@link Date} */ public Date getExpiresOn() { return Utility.getImmutableDateObject(mExpiresOn); } /** * Multi-resource refresh tokens can be used to request token for another * resource. * * @return multi resource refresh token status */ public boolean getIsMultiResourceRefreshToken() { return mIsMultiResourceRefreshToken; } /** * UserInfo returned from IdToken. * * @return {@link UserInfo} */ public UserInfo getUserInfo() { return mUserInfo; } /** * Set userinfo after refresh from previous idtoken. * * @param userinfo latest user info. */ void setUserInfo(UserInfo userinfo) { mUserInfo = userinfo; } /** * Gets tenantId. * * @return TenantId */ public String getTenantId() { return mTenantId; } /** * Gets status. * * @return {@link AuthenticationStatus} */ public AuthenticationStatus getStatus() { return mStatus; } String getCode() { return mCode; } void setCode(String code) { mCode = code; } /** * Gets error code. * * @return Error code */ public String getErrorCode() { return mErrorCode; } /** * Gets error description. * * @return error description */ public String getErrorDescription() { return mErrorDescription; } /** * Gets error log info. * * @return log info */ public String getErrorLogInfo() { return " ErrorCode:" + getErrorCode() + " ErrorDescription:" + getErrorDescription(); } /** * Checks expiration time. * * @return true if expired */ public boolean isExpired() { if (mIsExtendedLifeTimeToken) { return TokenCacheItem.isTokenExpired(getExtendedExpiresOn()); } return TokenCacheItem.isTokenExpired(getExpiresOn()); } // The token returned is cached with this authority as key. // We expect the subsequent requests to AcquireToken will use this authority as the authority parameter else // AcquireTokenSilent will fail public final String getAuthority() { return mAuthority; } String[] getErrorCodes() { return (mErrorCodes != null) ? mErrorCodes.replaceAll("[\\[\\]]", "").split("([^,]),") : null; } boolean isInitialRequest() { return mInitialRequest; } /** * Get raw idtoken. * * @return IdToken */ public String getIdToken() { return mIdToken; } /** * Gets if the returned token is valid in terms of extended lifetime. * * @return True if the returned token is valid in terms of extended lifetime */ public boolean isExtendedLifeTimeToken() { return mIsExtendedLifeTimeToken; } /** * Sets the flag to indicate whether the token being returned is a token only * valid in terms of extended lifetime. * * @param isExtendedLifeTimeToken */ final void setIsExtendedLifeTimeToken(final boolean isExtendedLifeTimeToken) { mIsExtendedLifeTimeToken = isExtendedLifeTimeToken; } final void setExtendedExpiresOn(final Date extendedExpiresOn) { mExtendedExpiresOn = extendedExpiresOn; } final Date getExtendedExpiresOn() { return mExtendedExpiresOn; } final void setExpiresOn(final Date expiresOn) { mExpiresOn = expiresOn; } void setIdToken(String idToken) { this.mIdToken = idToken; } void setTenantId(String tenantid) { mTenantId = tenantid; } void setRefreshToken(String refreshToken) { mRefreshToken = refreshToken; } final String getFamilyClientId() { return mFamilyClientId; } final void setFamilyClientId(final String familyClientId) { mFamilyClientId = familyClientId; } final void setAuthority(final String authority) { if (!StringExtensions.isNullOrBlank(authority)) { mAuthority = authority; } } final CliTelemInfo getCliTelemInfo() { return mCliTelemInfo; } final void setCliTelemInfo(final CliTelemInfo cliTelemInfo) { mCliTelemInfo = cliTelemInfo; } }
package org.openecard.addon; import java.io.File; import java.io.IOException; import java.nio.file.ClosedWatchServiceException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Path; import static java.nio.file.StandardWatchEventKinds.*; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.Set; import org.openecard.addon.manifest.AddonSpecification; import org.openecard.common.util.FileUtils; import org.openecard.ws.marshal.WSMarshallerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Filesystem monitor for the addon directory. * This implementation is based on the Java 7 {@link WatchService} based implementation. * * @author Tobias Wich */ public class AddonFileSystemMonitor { private static final Logger logger = LoggerFactory.getLogger(AddonFileSystemMonitor.class.getName()); private final FileRegistry fileRegistry; private final AddonManager manager; private final Path addonDir; private WatchService ws; private Thread t; public AddonFileSystemMonitor(FileRegistry fileRegistry, AddonManager manager) throws IOException, SecurityException { this.fileRegistry = fileRegistry; this.manager = manager; addonDir = FileUtils.getAddonsDir().toPath(); } /** * Starts watching the addon directory. * This function starts a thread which evaluates the events. * * @throws IOException Thrown when the directory does not provide the functionality to register the monitor. * @throws SecurityException Thrown when there are missing privileges to start the monitor. */ public void start() throws IOException, SecurityException { if (t != null) { String msg = "Trying to start already running file watcher."; logger.error(msg); throw new IllegalStateException(msg); } else { FileSystem fs = FileSystems.getDefault(); ws = fs.newWatchService(); addonDir.register(ws, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); // start thread taking care of the updates t = new Thread(new Runner(), "Addon-File-Watcher"); t.setDaemon(true); t.start(); } } /** * Stops the filesystem monitor. * This method waits for at most one second and then tries to kill the thread by force. */ public void stop() { if (t == null) { String msg = "Trying to stop idling file watcher."; logger.error(msg); throw new IllegalStateException(msg); } else { // try to terminate thread with stop flag, if that fails kill it explicitly try { ws.close(); t.join(1000); // check if thread is still alive if (t.isAlive()) { t.interrupt(); } } catch (IOException ex) { logger.error("Failed to close file watcher, trying to close by force."); t.interrupt(); } catch (InterruptedException ex) { logger.error("File watcher failed to terminate in time, killing it forcedly."); t.interrupt(); } } } private class Runner implements Runnable { @Override public void run() { try { while (true) { WatchKey wk = ws.take(); for (WatchEvent<?> evt : wk.pollEvents()) { Object ctx = evt.context(); if (ctx instanceof Path) { Path p = (Path) ctx; p = addonDir.resolve(p); // TODO: add code to find out if the files are currently being written to and only perform // an action when this is not the case String evtName = evt.kind().name(); logger.debug("Hit file watcher event {}.", evtName); if (ENTRY_CREATE.name().equals(evtName)) { addAddon(p); } else if (ENTRY_DELETE.name().equals(evtName)) { removeAddon(p); } else if (ENTRY_MODIFY.name().equals(evtName)) { replaceAddon(p); } } } // reset key and try again wk.reset(); } } catch (WSMarshallerException ex) { logger.error("Failed to deserialize Addon manifest, Terminating file monitor."); } catch (ClosedWatchServiceException ex) { logger.info("Watch service closed while waiting for changes."); } catch (InterruptedException ex) { logger.info("Watch service closed while waiting for changes."); } } } private void addAddon(Path file) throws WSMarshallerException { logger.info("Trying to register addon {}.", file.getFileName()); String fName = file.toFile().getName(); try { AddonSpecification spec = extractSpec(file); if (spec != null) { fileRegistry.register(spec, file.toFile()); manager.loadLoadOnStartupActions(spec); logger.info("Successfully registered {} as addon.", fName); } else { logger.error("The jar file {} does not seem to be an add-on.", fName); } } catch (MultipleAddonRegistration ex) { logger.error("The jar file {} is an already registered add-on.", fName); } } private void removeAddon(Path file) { logger.info("Trying to remove addon {}.", file.getFileName()); // check if we are dealing with a registered jar file AddonSpecification spec = getCurrentSpec(file); if (spec != null) { // call the destroy method of all actions and protocols manager.unloadAddon(spec); // remove configuration file AddonProperties addonProps = new AddonProperties(spec); addonProps.removeConfiguration(); // remove from file registry fileRegistry.unregister(file.toFile()); logger.info("Succesfully removed add-on {}.", file.toFile().getName()); } } private void replaceAddon(Path file) throws WSMarshallerException { try { // try to look up spec, only perform replace if there is not already a registered addon with the same id AddonSpecification spec = extractSpec(file); if (spec != null) { removeAddon(file); addAddon(file); } } catch (MultipleAddonRegistration ex) { // addon is already registered properly, so do nothing String fName = file.toFile().getName(); logger.error("The jar file {} is an already registered add-on.", fName); } } private AddonSpecification extractSpec(Path file) throws WSMarshallerException, MultipleAddonRegistration { if (isJarFile(file, true)) { // now check if there is a manifest ManifestExtractor mfEx = new ManifestExtractor(); AddonSpecification spec = mfEx.getAddonSpecificationFromFile(file.toFile()); // return the manifest if a valid addon file was found if (spec != null) { Set<AddonSpecification> plugins = fileRegistry.listAddons(); // check that there is not already a registered instance // TODO: this is in general a problem, because it may replace the addon on next start for (AddonSpecification desc : plugins) { if (desc.getId().equals(spec.getId())) { String msg = String.format("The addon with id %s is already registered.", desc.getId()); logger.debug("Addon '{}' is already registered by another bundle.", file.toFile().getName()); throw new MultipleAddonRegistration(msg, spec); } } return spec; } } return null; } private AddonSpecification getCurrentSpec(Path file) { if (isJarFile(file, false)) { AddonSpecification spec = fileRegistry.getAddonSpecByFileName(file.toFile().getName()); return spec; } return null; } private boolean isJarFile(Path path, boolean testType) { File file = path.toFile(); boolean result = new JARFileFilter().accept(file); if (testType) { result = result && file.isFile(); } return result; } }
package dyvil.tools.parsing.lexer; import dyvil.tools.parsing.Name; import dyvil.tools.parsing.TokenIterator; import dyvil.tools.parsing.marker.MarkerList; import dyvil.tools.parsing.marker.SyntaxError; import dyvil.tools.parsing.position.CodePosition; import dyvil.tools.parsing.position.ICodePosition; import dyvil.tools.parsing.token.*; import static dyvil.tools.parsing.lexer.BaseSymbols.*; import static dyvil.tools.parsing.lexer.Tokens.*; public final class DyvilLexer { private MarkerList markers; private Symbols symbols; private String code; private int length; private TokenIterator tokens; private StringBuilder buffer = new StringBuilder(); private int parseIndex; private int lineNumber = 1; private int stringParens; public DyvilLexer(MarkerList markers, Symbols symbols) { this.markers = markers; this.symbols = symbols; } public TokenIterator tokenize(String code) { this.tokens = new TokenIterator(); this.code = code; this.length = code.length(); while (true) { final int currentChar = this.codePoint(); if (currentChar == 0) { break; } this.parseCharacter(currentChar); } this.tokens.append(new EndToken(this.parseIndex, this.lineNumber)); this.tokens.reset(); return this.tokens; } // Parsing private void parseCharacter(int currentChar) { switch (currentChar) { case '`': this.parseBacktickIdentifier(); return; case '"': this.parseDoubleString(false); return; case '\'': this.parseSingleString(); return; case '@': if (this.nextCodePoint() == '"') { this.parseVerbatimString(); return; } this.parseIdentifier('@', MOD_SYMBOL); return; case '/': switch (this.nextCodePoint()) { case '*': this.parseBlockComment(); return; case '/': this.parseLineComment(); return; } this.parseIdentifier('/', MOD_SYMBOL); return; case '(': if (this.stringParens > 0) { this.stringParens++; } this.tokens.append(new SymbolToken(INSTANCE, OPEN_PARENTHESIS, this.lineNumber, this.parseIndex++)); return; case ')': if (this.stringParens > 0 && --this.stringParens == 0) { this.parseDoubleString(true); return; } this.tokens.append(new SymbolToken(INSTANCE, CLOSE_PARENTHESIS, this.lineNumber, this.parseIndex++)); return; case '[': this.tokens.append(new SymbolToken(INSTANCE, OPEN_SQUARE_BRACKET, this.lineNumber, this.parseIndex++)); return; case ']': this.tokens.append(new SymbolToken(INSTANCE, CLOSE_SQUARE_BRACKET, this.lineNumber, this.parseIndex++)); return; case '{': this.tokens.append(new SymbolToken(INSTANCE, OPEN_CURLY_BRACKET, this.lineNumber, this.parseIndex++)); return; case '}': this.tokens.append(new SymbolToken(INSTANCE, CLOSE_CURLY_BRACKET, this.lineNumber, this.parseIndex++)); return; case '.': { final int n = this.nextCodePoint(); if (LexerUtil.isIdentifierSymbol(n) || n == '.') { this.parseIdentifier('.', MOD_DOT); return; } this.tokens.append(new SymbolToken(INSTANCE, DOT, this.lineNumber, this.parseIndex++)); return; } case ';': this.tokens.append(new SymbolToken(INSTANCE, SEMICOLON, this.lineNumber, this.parseIndex++)); return; case ',': this.tokens.append(new SymbolToken(INSTANCE, COMMA, this.lineNumber, this.parseIndex++)); return; case '_': case '$': this.parseIdentifier(currentChar, MOD_SYMBOL | MOD_LETTER); return; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': this.parseNumberLiteral(currentChar); return; case '\n': this.lineNumber++; // Fallthrough case ' ': case '\t': this.parseIndex++; return; } if (LexerUtil.isIdentifierSymbol(currentChar)) { this.parseIdentifier(currentChar, MOD_SYMBOL); return; } if (LexerUtil.isIdentifierPart(currentChar)) { this.parseIdentifier(currentChar, MOD_LETTER); return; } this.advance(currentChar); } private void parseBacktickIdentifier() { // assert this.codePoint() == '`'; final int startIndex = this.parseIndex++; final int startLine = this.lineNumber; this.clearBuffer(); while (true) { final int currentChar = this.codePoint(); switch (currentChar) { case '\n': this.lineNumber++; case '\t': case '\b': continue; case EOF: this.error("identifier.backtick.unclosed"); // Fallthrough case '`': this.parseIndex++; this.tokens.append( new IdentifierToken(Name.getSpecial(this.buffer.toString()), SPECIAL_IDENTIFIER, startLine, startIndex, this.parseIndex)); return; } this.buffer.appendCodePoint(currentChar); this.advance(currentChar); } } private void parseSingleString() { // assert this.codePoint() == '\''; final int startIndex = this.parseIndex++; final int startLine = this.lineNumber; this.clearBuffer(); while (true) { final int currentChar = this.codePoint(); switch (currentChar) { case '\\': this.parseEscape(this.nextCodePoint()); continue; case '\t': case '\b': continue; case '\n': this.lineNumber++; this.error("string.single.newline"); continue; case EOF: this.error("string.single.unclosed"); // Fallthrough case '\'': this.parseIndex++; this.tokens.append(new StringToken(this.buffer.toString(), SINGLE_QUOTED_STRING, startLine, startIndex, this.parseIndex + 1)); return; } this.buffer.appendCodePoint(currentChar); this.advance(currentChar); } } private void parseDoubleString(boolean stringPart) { // assert this.codePoint() == (stringPart ? ')' : '"'); final int startIndex = this.parseIndex++; final int startLine = this.lineNumber; this.clearBuffer(); while (true) { final int currentChar = this.codePoint(); switch (currentChar) { case '\\': final int nextChar = this.nextCodePoint(); if (nextChar == '(') { this.parseIndex += 2; if (this.stringParens > 0) { this.error("string.double.interpolation.nested"); continue; // parse the rest of the string as normal } this.tokens.append( new StringToken(this.buffer.toString(), stringPart ? STRING_PART : STRING_START, startLine, startIndex, this.parseIndex + 1)); this.stringParens = 1; return; } this.parseEscape(nextChar); continue; case EOF: this.error("string.double.unclosed"); // Fallthrough case '"': this.parseIndex++; this.tokens.append( new StringToken(this.buffer.toString(), stringPart ? STRING_END : STRING, startLine, startIndex, this.parseIndex)); return; case '\n': this.lineNumber++; break; case '\t': this.parseIndex++; continue; } this.buffer.appendCodePoint(currentChar); this.advance(currentChar); } } private void parseVerbatimString() { // assert this.codePoint() == '@'; final int startIndex = this.parseIndex; final int startLine = this.lineNumber; // assert this.nextCodePoint() == '"'; this.parseIndex += 2; this.clearBuffer(); while (true) { final int currentChar = this.codePoint(); switch (currentChar) { case EOF: this.error("string.verbatim.unclosed"); // Fallthrough case '"': this.parseIndex++; this.tokens.append( new StringToken(this.buffer.toString(), VERBATIM_STRING, startLine, startIndex, this.parseIndex)); return; case '\n': this.lineNumber++; this.parseIndex++; continue; case '\t': this.parseIndex++; continue; } this.buffer.appendCodePoint(currentChar); this.advance(currentChar); } } private void parseNumberLiteral(int currentChar) { final int radix; this.clearBuffer(); if (currentChar == '0') { switch (this.nextCodePoint()) { case 'o': case 'O': this.parseIndex++; radix = 8; break; case 'x': case 'X': this.parseIndex++; radix = 16; break; case 'b': case 'B': this.parseIndex++; radix = 2; break; default: this.buffer.append('0'); radix = 10; } } else { this.buffer.append((char) currentChar); radix = 10; } int startIndex = this.parseIndex++; byte type = 0; // 0 -> int, 1 -> long, 2 -> float, 3 -> double while (true) { currentChar = this.codePoint(); switch (currentChar) { case EOF: break; case '0': case '1': this.buffer.append((char) currentChar); this.parseIndex++; continue; case '2': case '3': case '4': case '5': case '6': case '7': if (radix >= 8) { this.buffer.append((char) currentChar); this.parseIndex++; continue; } break; case '8': case '9': if (radix >= 10) { this.buffer.append((char) currentChar); this.parseIndex++; continue; } break; case 'a': case 'b': case 'c': if (radix == 16) { this.buffer.append((char) currentChar); this.parseIndex++; continue; } break; case '_': this.parseIndex++; continue; case 'd': case 'D': if (radix == 16) { this.buffer.append((char) currentChar); this.parseIndex++; continue; } // Fallthrough if (radix >= 10 && !LexerUtil.isIdentifierPart(this.nextCodePoint())) { this.parseIndex++; type = 3; // double continue; } break; case '.': if (radix == 10 && LexerUtil.isDigit(this.nextCodePoint())) { this.buffer.append('.'); this.parseIndex++; type = 3; // double continue; } break; case 'e': case 'E': if (radix == 16) { this.buffer.append((char) currentChar); this.parseIndex++; continue; } if (radix == 10) { int n = this.nextCodePoint(); if (LexerUtil.isDigit(n)) { this.buffer.append((char) currentChar); this.parseIndex++; type = 3; // double continue; } if (n == '-') { this.buffer.append('e').append('-'); this.parseIndex += 2; type = 3; // double continue; } } break; case 'f': case 'F': if (radix == 16) { this.buffer.append((char) currentChar); this.parseIndex++; continue; } if (radix >= 10 && !LexerUtil.isIdentifierPart(this.nextCodePoint())) { this.parseIndex++; type = 2; // float continue; } break; case 'l': case 'L': if (!LexerUtil.isIdentifierPart(this.nextCodePoint())) { this.parseIndex++; type = 1; // long continue; } break; case 'p': case 'P': if (radix == 16) { this.buffer.append((char) currentChar); this.parseIndex++; type = 3; // float continue; } break; } switch (type) { case 0: // int { final IntToken token = new IntToken(0, this.lineNumber, startIndex, this.parseIndex); try { token.setValue(Integer.parseInt(this.buffer.toString(), radix)); } catch (NumberFormatException ex) { this.error(token, "literal.integer.invalid"); } this.tokens.append(token); return; } case 1: // long { final LongToken token = new LongToken(0, this.lineNumber, startIndex, this.parseIndex); try { token.setValue(Long.parseLong(this.buffer.toString(), radix)); } catch (NumberFormatException ex) { this.error(token, "literal.long.invalid"); } this.tokens.append(token); return; } case 2: // float { final FloatToken token = new FloatToken(0, this.lineNumber, startIndex, this.parseIndex); try { token.setValue(Float.parseFloat(this.buffer.toString())); } catch (NumberFormatException ex) { this.error(token, "literal.float.invalid"); } this.tokens.append(token); return; } case 3: // double { final DoubleToken token = new DoubleToken(0, this.lineNumber, startIndex, this.parseIndex); try { if (radix == 16) { this.buffer.insert(0, "0x"); } token.setValue(Double.parseDouble(this.buffer.toString())); } catch (NumberFormatException ex) { this.error(token, "literal.double.invalid"); } this.tokens.append(token); return; } } return; } } private void parseLineComment() { // assert this.codePoint() == '/'; // assert this.nextCodePoint() == '/'; this.parseIndex += 2; while (true) { final int currentChar = this.codePoint(); if (currentChar == EOF) { return; } if (currentChar == '\n') { this.parseIndex++; this.lineNumber++; return; } this.advance(currentChar); } } private void parseBlockComment() { // assert this.codePoint() == '/'; // assert this.nextCodePoint() == '*'; int level = 1; this.parseIndex += 2; while (true) { final int currentChar = this.codePoint(); switch (currentChar) { case EOF: this.error("comment.block.unclosed"); return; case '\n': this.lineNumber++; this.parseIndex++; continue; case '/': if (this.nextCodePoint() == '*') { level++; this.parseIndex += 2; continue; } this.parseIndex++; continue; case '*': if (this.nextCodePoint() == '/') { level this.parseIndex += 2; if (level == 0) { return; } continue; } this.parseIndex++; continue; } this.advance(currentChar); } } private void parseIdentifier(int currentChar, int subtype) { final int startIndex = this.parseIndex; this.clearBuffer(); this.buffer.appendCodePoint(currentChar); this.advance(currentChar); while (true) { currentChar = this.codePoint(); switch (subtype) { case MOD_LETTER: { if (currentChar == '_' || currentChar == '$') { this.buffer.append((char) currentChar); this.parseIndex++; subtype = MOD_LETTER | MOD_SYMBOL; continue; } if (LexerUtil.isIdentifierPart(currentChar)) // also matches digits { this.buffer.appendCodePoint(currentChar); this.advance(currentChar); continue; } final String id = this.buffer.toString(); final int keyword = this.symbols.getKeywordType(id); if (keyword != 0) { this.tokens.append(new SymbolToken(this.symbols, keyword, this.lineNumber, startIndex)); return; } this.tokens.append( new IdentifierToken(Name.get(id), Tokens.LETTER_IDENTIFIER, this.lineNumber, startIndex, this.parseIndex)); return; } case MOD_DOT: if (currentChar == '.') { this.buffer.append('.'); this.parseIndex++; continue; } // Fallthrough case MOD_SYMBOL: if (currentChar == '_' || currentChar == '$') { this.buffer.append((char) currentChar); this.parseIndex++; subtype = MOD_LETTER | MOD_SYMBOL; continue; } if (LexerUtil.isIdentifierSymbol(currentChar)) { this.buffer.appendCodePoint(currentChar); this.parseIndex++; subtype = MOD_SYMBOL; continue; } break; case MOD_LETTER | MOD_SYMBOL: if (currentChar == '_' || currentChar == '$') { this.buffer.append((char) currentChar); this.parseIndex++; continue; } if (LexerUtil.isIdentifierPart(currentChar)) { this.buffer.appendCodePoint(currentChar); this.advance(currentChar); subtype = MOD_LETTER; continue; } if (LexerUtil.isIdentifierSymbol(currentChar)) { this.buffer.appendCodePoint(currentChar); this.advance(currentChar); subtype = MOD_SYMBOL; continue; } break; } final String id = this.buffer.toString(); final int symbol = this.symbols.getSymbolType(id); if (symbol != 0) { this.tokens.append(new SymbolToken(this.symbols, symbol, this.lineNumber, startIndex)); return; } this.tokens.append(new IdentifierToken(Name.get(id), Tokens.SYMBOL_IDENTIFIER, this.lineNumber, startIndex, this.parseIndex)); return; } } private void parseEscape(int nextChar) { switch (nextChar) { case '"': case '\'': case '\\': this.buffer.append((char) nextChar); this.parseIndex += 2; return; case 'n': this.buffer.append('\n'); this.parseIndex += 2; return; case 't': this.buffer.append('\t'); this.parseIndex += 2; return; case 'r': this.buffer.append('\r'); this.parseIndex += 2; return; case 'b': this.buffer.append('\b'); this.parseIndex += 2; return; case 'f': this.buffer.append('\f'); this.parseIndex += 2; return; case 'v': this.buffer.append('\u000B'); // U+000B VERTICAL TABULATION this.parseIndex += 2; return; case 'a': this.buffer.append('\u0007'); // U+0007 BELL this.parseIndex += 2; return; case 'e': this.buffer.append('\u001B'); // U+001B ESCAPE this.parseIndex += 2; return; case '0': this.buffer.append('\0'); // U+0000 NULL this.parseIndex += 2; return; case 'u': int buf = 0; this.parseIndex += 2; if (this.codePoint() != '{') { this.error("escape.unicode.open_brace"); return; } this.parseIndex++; loop: while (true) { int codePoint = this.codePoint(); switch (codePoint) { case '\n': this.error("escape.unicode.newline"); this.lineNumber++; // Fallthrough case ' ': case '_': case '\t': this.parseIndex++; continue; case '}': this.parseIndex++; break loop; } if (!LexerUtil.isHexDigit(codePoint)) { this.error("escape.unicode.close_brace"); break; } buf <<= 4; buf += Character.digit(codePoint, 16); this.parseIndex++; } this.buffer.appendCodePoint(buf); return; } this.parseIndex++; this.error("escape.invalid"); this.parseIndex++; } // Utility Methods private int codePoint() { return this.parseIndex >= this.length ? 0 : this.code.codePointAt(this.parseIndex); } private int nextCodePoint() { return this.parseIndex + 1 >= this.length ? 0 : this.code.codePointAt(this.parseIndex + 1); } private void advance(int currentChar) { this.parseIndex += Character.charCount(currentChar); } private void clearBuffer() { this.buffer.delete(0, this.buffer.length()); } private void error(String key) { this.error(new CodePosition(this.lineNumber, this.parseIndex, this.parseIndex + 1), key); } private void error(ICodePosition position, String key) { this.markers.add(new SyntaxError(position, this.markers.getI18n().getString(key))); } }
package de.dhbw.humbuch.model; import java.util.LinkedHashSet; import java.util.Set; import de.dhbw.humbuch.model.entity.ProfileType; public final class ProfileTypeHandler { public static Set<ProfileType> createProfile(String[] languageInformation, String religionInformation){ Set<ProfileType> profileTypeSet = new LinkedHashSet<ProfileType>(); for(int i = 0; i < languageInformation.length; i++){ if(languageInformation[i].equals("E")){ profileTypeSet.add(ProfileType.STANDARD); } if(languageInformation[i].equals("F")){ if(i == 1){ profileTypeSet.add(ProfileType.FRENCH2); } else if(i == 2){ profileTypeSet.add(ProfileType.FRENCH3); } } if(languageInformation[i].equals("L")){ profileTypeSet.add(ProfileType.LATIN); } if(i == 2 && languageInformation.equals("")){ profileTypeSet.add(ProfileType.SCIENCE); } } if(religionInformation.equals("rk")){ profileTypeSet.add(ProfileType.ROMANCATHOLIC); } else if(religionInformation.equals("ev")){ profileTypeSet.add(ProfileType.EVANGELIC); } else if(religionInformation.equals("Ethik")){ profileTypeSet.add(ProfileType.ETHICS); } return profileTypeSet; } public static String getLanguageProfile(Set<ProfileType> profileTypeParam){ String languageProfile = ""; for(ProfileType profileType : profileTypeParam){ if(profileType.equals(ProfileType.STANDARD)){ languageProfile = "E"; } else if(profileType.equals(ProfileType.FRENCH2) || (profileType.equals(ProfileType.FRENCH3))){ if(languageProfile.equals("")){ languageProfile = languageProfile + "F"; } else{ languageProfile = languageProfile + " F"; } } else if(profileType.equals(ProfileType.LATIN)){ if(languageProfile.equals("")){ languageProfile = languageProfile + "L"; } else{ languageProfile = languageProfile + " L"; } } } System.out.println(profileTypeParam); System.out.println(languageProfile); return languageProfile; } public static String getReligionProfile(Set<ProfileType> profileTypeParam){ for(ProfileType profileType : profileTypeParam){ if(profileType.equals(ProfileType.EVANGELIC)){ return "ev"; } else if(profileType.equals(ProfileType.ROMANCATHOLIC)){ return "rk"; } else if(profileType.equals(ProfileType.ETHICS)){ return "Ethik"; } } return null; } }
package org.intermine.web; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletContext; import java.util.LinkedHashMap; import java.util.Map; import java.util.ArrayList; import java.util.List; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMessages; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionError; import org.apache.struts.Globals; import org.intermine.metadata.Model; import org.intermine.objectstore.query.ResultsInfo; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.ObjectStoreQueryDurationException; /** * Implementation of <strong>Action</strong> that saves a Query from a session. * * @author Richard Smith * @author Matthew Wakeling */ public class SaveQueryAction extends Action { /** * Process the specified HTTP request, and create the corresponding HTTP * response (or forward to another web component that will create it). * Return an <code>ActionForward</code> instance describing where and how * control should be forwarded, or <code>null</code> if the response has * already been completed. * * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return an ActionForward object defining where control goes next * * @exception Exception if the application business logic throws * an exception */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); Map qNodes = (Map) session.getAttribute(Constants.QUERY); List view = (List) session.getAttribute(Constants.VIEW); String queryName = ((SaveQueryForm) form).getQueryName(); try { ResultsInfo resultsInfo = ViewHelper.makeEstimate(request); saveQuery(request, queryName, qNodes, view, resultsInfo); } catch (ObjectStoreException e) { ActionMessages actionMessages = new ActionMessages(); String key = (e instanceof ObjectStoreQueryDurationException) ? "errors.query.estimatetimetoolong" : "errors.query.objectstoreerror"; ActionError error = new ActionError(key); actionMessages.add(ActionMessages.GLOBAL_MESSAGE, error); saveMessages(request, actionMessages); } return mapping.findForward("query"); } /** * 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 qNodes the actual query * @param view the paths in the SELECT list * @param resultsInfo the resultsInfo for the query */ public static void saveQuery(HttpServletRequest request, String queryName, Map qNodes, List view, ResultsInfo resultsInfo) { HttpSession session = request.getSession(); ServletContext servletContext = session.getServletContext(); Model model = (Model) servletContext.getAttribute(Constants.MODEL); Map savedQueries = (Map) session.getAttribute(Constants.SAVED_QUERIES); if (savedQueries == null) { savedQueries = new LinkedHashMap(); session.setAttribute(Constants.SAVED_QUERIES, savedQueries); } savedQueries.put(queryName, new QueryInfo(qNodes, view, resultsInfo)); session.setAttribute(Constants.QUERY, SaveQueryHelper.clone(qNodes, model)); session.setAttribute(Constants.VIEW, new ArrayList(view)); ActionMessages messages = new ActionMessages(); ActionMessage message = new ActionMessage("saveQuery.message", queryName); messages.add("saveQuery", message); request.setAttribute(Globals.MESSAGE_KEY, messages); } }
package de.tblsoft.solr.pipeline.filter; import de.tblsoft.solr.pipeline.AbstractFilter; import de.tblsoft.solr.pipeline.bean.Document; import de.tblsoft.solr.util.IOUtils; import de.tblsoft.solr.util.OutputStreamStringBuilder; import java.io.IOException; import java.io.OutputStream; public class N3Writer extends AbstractFilter { private String absoluteFilename; private OutputStream outputStream; private OutputStreamStringBuilder outputStreamStringBuilder; @Override public void init() { String relativeFilename = getProperty("filename", null); absoluteFilename = IOUtils.getAbsoluteFile(getBaseDir(), relativeFilename); verify(absoluteFilename, "For the FileLineWriter a filname must be defined."); try { outputStream = IOUtils.getOutputStream(absoluteFilename); outputStreamStringBuilder = new OutputStreamStringBuilder(outputStream); } catch (IOException e) { throw new RuntimeException(e); } super.init(); } @Override public void document(Document document) { try { String subject = document.getFieldValue("subject"); String predicate = document.getFieldValue("predicate"); String object = document.getFieldValue("object"); outputStreamStringBuilder.append("<").append(subject).append(">").append("\t"); outputStreamStringBuilder.append("<").append(predicate).append(">").append("\t"); outputStreamStringBuilder.append("\"").append(object).append("\""); outputStreamStringBuilder.append("\n"); } catch (Exception e) { throw new RuntimeException(e); } super.document(document); } @Override public void end() { try { outputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } super.end(); } }
package jodd.db.oom.sqlgen.chunks; import jodd.db.oom.DbEntityDescriptor; import jodd.db.oom.DbEntityColumnDescriptor; import jodd.db.oom.sqlgen.DbSqlBuilderException; import jodd.db.oom.sqlgen.TemplateData; import jodd.util.CharUtil; /** * SQL chunk defines part of the SQL query that can be processed. */ public abstract class SqlChunk implements Cloneable { public static final int COLS_NA = 0; // using explicit reference. public static final int COLS_ONLY_EXISTING = 1; // using only existing columns i.e. that are not-null public static final int COLS_ONLY_IDS = 2; // using only identity columns public static final int COLS_ALL = 3; // using all available columns protected final int chunkType; // chunk type public static final int CHUNK_RAW = -1; public static final int CHUNK_SELECT_COLUMNS = 1; public static final int CHUNK_TABLE = 2; public static final int CHUNK_REFERENCE = 3; public static final int CHUNK_MATCH = 4; public static final int CHUNK_VALUE = 5; public static final int CHUNK_INSERT = 5; public static final int CHUNK_UPDATE = 6; protected SqlChunk(int chunkType) { this.chunkType = chunkType; } protected SqlChunk previousChunk; /** * Returns previous chunk. */ public SqlChunk getPreviousChunk() { return previousChunk; } protected SqlChunk nextChunk; /** * Returns next chunk. */ public SqlChunk getNextChunk() { return nextChunk; } /** * Appends chunk to previous one and maintaince the double-linked list of the previous chunk. * Current surrounding connections of this chunk will be cut-off. */ public void insertChunkAfter(SqlChunk previous) { SqlChunk next = previous.nextChunk; previous.nextChunk = this; this.previousChunk = previous; if (next != null) { next.previousChunk = this; this.nextChunk = next; } } /** * Returns <code>true</code> if previous chunk is of provided type. */ public boolean isPreviousChunkOfType(int type) { if (previousChunk == null) { return false; } return previousChunk.chunkType == type; } /** * Returns <code>true</code> if previous chunk is of the same type. */ public boolean isPreviousChunkOfSameType() { if (previousChunk == null) { return false; } return previousChunk.chunkType == chunkType; } /** * Returns <code>true</code> if previous chunk is not raw. */ public boolean isPreviousMacroChunk() { if (previousChunk == null) { return false; } return previousChunk.chunkType != CHUNK_RAW; } public boolean isPreviousRawChunk() { if (previousChunk == null) { return false; } return previousChunk.chunkType == CHUNK_RAW; } protected TemplateData templateData; // working template context /** * Initializes chunk. Assigns {@link jodd.db.oom.sqlgen.TemplateData} to chunk. * If chunk needs some pre-processing, they should be done here. */ public void init(TemplateData templateData) { this.templateData = templateData; } /** * Process the chunk and appends data to the output. */ public abstract void process(StringBuilder out); /** * Lookups for entity name and throws exception if entity name not found. */ protected DbEntityDescriptor lookupName(String entityName) { DbEntityDescriptor ded = templateData.getDbOomManager().lookupName(entityName); if (ded == null) { throw new DbSqlBuilderException("Entity name '" + entityName + "' is not registered with DbOomManager."); } return ded; } /** * Lookups for entity name and throws an exception if entity type is invalid. */ protected DbEntityDescriptor lookupType(Class entity) { DbEntityDescriptor ded = templateData.getDbOomManager().lookupType(entity); if (ded == null) { throw new DbSqlBuilderException("Invalid or not-persistent entity type: '" + entity.getName() + "'."); } return ded; } /** * Lookups for table reference and throws an exception if table reference not found. */ protected DbEntityDescriptor lookupTableRef(String tableRef) { return lookupTableRef(tableRef, true); } /** * Lookups for table reference and optionally throws an exception if table reference not found. */ protected DbEntityDescriptor lookupTableRef(String tableRef, boolean throwExceptionIfNotFound) { DbEntityDescriptor ded = templateData.getTableDescriptor(tableRef); if (ded == null) { if (throwExceptionIfNotFound) { throw new DbSqlBuilderException("Invalid table reference: '" + tableRef + "'."); } } return ded; } /** * Resolves table name or alias that will be used in the query. */ protected String resolveTable(String tableRef, DbEntityDescriptor ded) { String tableAlias = templateData.getTableAlias(tableRef); if (tableAlias != null) { return tableAlias; } return ded.getTableName(); } /** * Defines parameter with name and its value. */ protected void defineParameter(StringBuilder query, String name, Object value, DbEntityColumnDescriptor dec) { if (name == null) { name = templateData.getNextParameterName(); } query.append(':').append(name); templateData.addParameter(name, value, dec); } /** * Resolves object to a class. */ protected static Class resolveClass(Object object) { Class type = object.getClass(); return type == Class.class ? (Class) object : type; } /** * Appends missing space if the output doesn't end with whitespace. */ protected void appendMissingSpace(StringBuilder out) { int len = out.length(); if (len == 0) { return; } len if (CharUtil.isWhitespace(out.charAt(len)) == false) { out.append(' '); } } /** * Separates from previous chunk by comma if is of the same type. */ protected void separateByCommaOrSpace(StringBuilder out) { if (isPreviousChunkOfSameType()) { out.append(',').append(' '); } else { appendMissingSpace(out); } } /** * Clones all parsed chunk data to an instance that is ready for processing. */ @Override public abstract SqlChunk clone(); }
package editor.gui.inventory; import java.awt.BorderLayout; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Frame; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.List; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.function.Consumer; import java.util.zip.ZipInputStream; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.KeyStroke; import javax.swing.SwingWorker; import javax.swing.WindowConstants; /** * Class for downloading and decompressing the inventory, displaying progress in a * popup dialog. */ public abstract class InventoryDownloader { /** * Download the inventory from the Internet and decompress it. Display a dialog showing * progress and allowing cancellation. * * @param owner frame for setting the location of the dialog * @param site web site to download the inventory from * @param file file to store the inventory in * @return <code>true</code> if the file was successfully downloaded and decompressed, * and <code>false</code> otherwise. * @throws IOException if the download worker can't connect to the inventory site. */ public static boolean downloadInventory(Frame owner, URL site, File file) throws IOException { File zip = new File(file.getPath() + ".zip"); File tmp = new File(zip.getPath() + ".tmp"); JDialog dialog = new JDialog(owner, "Update", Dialog.ModalityType.APPLICATION_MODAL); dialog.setPreferredSize(new Dimension(350, 115)); dialog.setResizable(false); dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); UnzipWorker unzipper = new UnzipWorker(zip, file); // Content panel JPanel contentPanel = new JPanel(new BorderLayout(0, 2)); contentPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); dialog.setContentPane(contentPanel); // Stage progress label JLabel progressLabel = new JLabel("Downloading inventory..."); contentPanel.add(progressLabel, BorderLayout.NORTH); // Overall progress bar JProgressBar progressBar = new JProgressBar(); progressBar.setIndeterminate(true); contentPanel.add(progressBar, BorderLayout.CENTER); DownloadWorker downloader = new DownloadWorker(site, tmp); if (downloader.size() >= 0) progressBar.setMaximum(downloader.size()); downloader.setUpdateFunction((downloaded) -> { StringBuilder progress = new StringBuilder(); progress.append("Downloading inventory... " + formatDownload(downloaded)); if (downloader.size() < 0) progressBar.setVisible(false); else { progressBar.setIndeterminate(false); progressBar.setValue(downloaded); progress.append("B/" + formatDownload(downloader.size())); } progress.append("B downloaded."); progressLabel.setText(progress.toString()); }); // Cancel button JPanel cancelPanel = new JPanel(); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener((e) -> { downloader.cancel(true); unzipper.cancel(true); }); cancelPanel.add(cancelButton); contentPanel.add(cancelPanel, BorderLayout.SOUTH); dialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { downloader.cancel(true); unzipper.cancel(true); } }); dialog.getRootPane().registerKeyboardAction((e) -> { downloader.cancel(true); unzipper.cancel(true); }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); dialog.pack(); dialog.setLocationRelativeTo(owner); var future = Executors.newSingleThreadExecutor().submit(() -> { downloader.execute(); try { downloader.get(); } catch (InterruptedException | ExecutionException e) { JOptionPane.showMessageDialog(owner, "Error downloading " + zip.getName() + ": " + e.getCause().getMessage() + ".", "Error", JOptionPane.ERROR_MESSAGE); tmp.delete(); dialog.setVisible(false); return false; } catch (CancellationException e) { tmp.delete(); dialog.setVisible(false); return false; } try { Files.move(tmp.toPath(), zip.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { JOptionPane.showMessageDialog(owner, "Could not replace temporary file: " + e.getMessage() + ".", "Error", JOptionPane.ERROR_MESSAGE); dialog.setVisible(false); return false; } progressLabel.setText("Unzipping archive..."); unzipper.execute(); try { unzipper.get(); } catch (InterruptedException | ExecutionException e) { JOptionPane.showMessageDialog(owner, "Error decompressing " + zip.getName() + ": " + e.getCause().getMessage() + ".", "Error", JOptionPane.ERROR_MESSAGE); dialog.setVisible(false); return false; } catch (CancellationException e) { dialog.setVisible(false); file.delete(); return false; } finally { zip.delete(); } dialog.setVisible(false); return true; }); dialog.setVisible(true); try { return future.get(); } catch (InterruptedException | ExecutionException e) { return false; } finally { dialog.dispose(); } } /** * Format an integer into a string indicating a number of bytes, kilobytes, or * megabytes. * * @param n integer to format * @return A formatted string. */ private static String formatDownload(int n) { if (n < 0) return ""; else if (n <= 1024) return String.format("%d", n); else if (n <= 1048576) return String.format("%.1fk", n/1024.0); else return String.format("%.2fM", n/1048576.0); } /** * This class represents a worker which downloads the inventory from a website * in the background. It is tied to a dialog which blocks input until the * download is complete. * * @author Alec Roelke */ private static class DownloadWorker extends SwingWorker<Void, Integer> { /** File to store the inventory file in. */ private File file; /** Connection to the inventory site. */ private URLConnection connection; /** Number of bytes to download from the inventory site. */ private int size; /** Function for updating the GUI with the number of bytes downloaded. */ private Consumer<Integer> updater; /** * Create a new InventoryDownloadWorker. A new one must be created each time * a file is to be downloaded. * * @param s URL to download the file from * @param f File to store it locally in */ public DownloadWorker(URL s, File f) throws IOException { super(); file = f; connection = s.openConnection(); size = connection.getContentLength(); updater = (i) -> {}; } /** * @return The number of bytes to be downloaded. */ public int size() { return size; } /** * {@inheritDoc} * Connect to the site to download the file from, and the download the file, * periodically reporting how many bytes have been downloaded. */ @Override protected Void doInBackground() throws Exception { try { try (BufferedInputStream in = new BufferedInputStream((connection.getInputStream()))) { try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { byte[] data = new byte[1024]; int size = 0; int x; while (!isCancelled() && (x = in.read(data)) > 0) { size += x; out.write(data, 0, x); publish(size); } } } } finally {} return null; } /** * Set the function to be used when updating the GUI about download progress. * * @param u download update function */ public void setUpdateFunction(Consumer<Integer> u) { updater = u; } /** * {@inheritDoc} * Tell the dialog how many bytes were downloaded, sometimes in kB or MB * if it is too large. */ @Override protected void process(List<Integer> chunks) { updater.accept(chunks.get(chunks.size() - 1)); } } /** * This class represents a worker which unzips a zipped archive of the inventory. * * @author Alec Roelke */ private static class UnzipWorker extends SwingWorker<Void, Void> { /** * Zip file containing the inventory. */ private File zipfile; /** * File to write the unzipped inventory to. */ private File outfile; /** * Create a new InventoryUnzipWorker to unzip a file. * * @param z file to unzip * @param o file to store the result to */ public UnzipWorker(File z, File o) { zipfile = z; outfile = o; } /** * {@inheritDoc} * Open the zip file, decompress it, and store the result back to disk. */ @Override protected Void doInBackground() throws Exception { try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipfile))) { zis.getNextEntry(); try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outfile))) { byte[] data = new byte[1024]; int x; while (!isCancelled() && (x = zis.read(data)) > 0) out.write(data, 0, x); } } return null; } } }
package edu.wvu.stat.rc2.persistence; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Optional; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.ResultSetMapper; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; /** RCWorkspace is mostly-immutable. All properties are immutable. The only thing that is mutable is the list of files. It is stored internally as an immutable copy of the argument to setFiles(). So the workspace itself is immutable, but the file list isn't. */ @AutoValue @JsonIgnoreProperties(value={"files"}, allowGetters=true) public abstract class RCWorkspace { @JsonCreator public static RCWorkspace create( @JsonProperty("id") int id, @JsonProperty("version") int version, @JsonProperty("projectId") int projectId, @JsonProperty("uniqueId") String uniqueId, @JsonProperty("name") String name) { return new AutoValue_RCWorkspace(id, version, projectId, uniqueId, name); } public abstract @JsonProperty int getId(); public abstract @JsonProperty int getVersion(); public abstract @JsonProperty int getProjectId(); public abstract @JsonProperty String getUniqueId(); public abstract @JsonProperty String getName(); static RCWorkspace createFromResultSet(ResultSet rs) throws SQLException { return new AutoValue_RCWorkspace(rs.getInt("id"), rs.getInt("version"), rs.getInt("projectId"), rs.getString("uniqueId"), rs.getString("name")); } private List<RCFile> _files; public List<RCFile> getFiles() { return _files; } public void setFiles(List<RCFile> files) { _files = ImmutableList.copyOf(files); } private RCProject _project; @JsonIgnore public RCProject getProject() { return _project; } public void setProject(RCProject p) { _project = p; } public Optional<RCFile> getFileWithId(int fileId) { return _files.stream().filter(f -> f.getId() == fileId).findFirst(); } public static class RCWorkspaceMapper implements ResultSetMapper<RCWorkspace> { public RCWorkspaceMapper() {} public RCWorkspace map(int index, ResultSet rs, StatementContext ctx) throws SQLException { return RCWorkspace.createFromResultSet(rs); } } //queries in RCWorkspaceQueries }
package fr.liglab.mining.internals; import java.util.Arrays; import java.util.Iterator; import java.util.PriorityQueue; import javax.xml.ws.Holder; import fr.liglab.mining.CountersHandler; import fr.liglab.mining.CountersHandler.TopLCMCounters; import fr.liglab.mining.io.PerItemTopKCollector; import fr.liglab.mining.util.ItemAndSupport; import fr.liglab.mining.util.ItemsetsFactory; import gnu.trove.iterator.TIntIntIterator; import gnu.trove.map.hash.TIntIntHashMap; public class DenseCounters extends Counters { /** * Support count, per item having a support count in [minSupport; 100% [ * Items having a support count below minSupport are considered infrequent, * those at 100% belong to closure, for both supportCounts[i] = 0 - except * if renaming happened, in which case such items no longer exists. * * Indexes above maxFrequent should be considered valid. * * TODO private+accessor */ private int[] supportCounts; /** * For each item having a support count in [minSupport; 100% [ , gives how * many distinct transactions contained this item. It's like supportCounts * if all transactions have a weight equal to 1 * * Indexes above maxFrequent should be considered valid. * * TODO private+accessor */ private int[] distinctTransactionsCounts; /** * will be set to true if arrays have been compacted, ie. if supportCounts * and distinctTransactionsCounts don't contain any zero. */ private boolean compactedArrays = false; /** * We use our own map, although it will contain a single item most of the * time, because ThreadLocal causes (huge) memory leaks when used as a * non-static field. * * @see getLocalFrequentsIterator */ private static final ThreadLocal<FrequentIterator> localFrequentsIterator = new ThreadLocal<FrequentIterator>() { @Override protected FrequentIterator initialValue() { return new FrequentIterator(); } }; @Override final void eraseItem(int i) { this.supportCounts[i] = 0; this.distinctTransactionsCounts[i] = 0; } @Override public boolean compactedRenaming() { return this.compactedArrays; } /** * Does item counting over a projected dataset * * @param minimumSupport * @param transactions * extension's support * @param extension * the item on which we're projecting - it won't appear in *any* * counter (not even 'closure') * @param ignoredItems * may be null, if it's not contained items won't appear in any * counter either * @param maxItem * biggest index among items to be found in "transactions" * @param reuseReverseRenaming * @param parentPattern */ public DenseCounters(int minimumSupport, Iterator<TransactionReader> transactions, int extension, int[] ignoredItems, final int maxItem, int[] reuseReverseRenaming, int[] parentPattern) { CountersHandler.increment(TopLCMCounters.NbCounters); this.reverseRenaming = reuseReverseRenaming; this.minSupport = minimumSupport; this.supportCounts = new int[maxItem + 1]; this.distinctTransactionsCounts = new int[maxItem + 1]; // item support and transactions counting int weightsSum = 0; int transactionsCount = 0; while (transactions.hasNext()) { TransactionReader transaction = transactions.next(); int weight = transaction.getTransactionSupport(); if (weight > 0) { if (transaction.hasNext()) { weightsSum += weight; transactionsCount++; } while (transaction.hasNext()) { int item = transaction.next(); // need to check this because of views if (item <= maxItem) { this.supportCounts[item] += weight; this.distinctTransactionsCounts[item]++; } } } } this.transactionsCount = weightsSum; this.distinctTransactionsCount = transactionsCount; // ignored items this.eraseItem(extension); this.maxCandidate = extension; if (ignoredItems != null) { for (int item : ignoredItems) { if (item <= maxItem) { this.eraseItem(item); } } } // item filtering and final computations : some are infrequent, some // belong to closure ItemsetsFactory closureBuilder = new ItemsetsFactory(); int remainingDistinctTransLengths = 0; int remainingFrequents = 0; int biggestItemID = 0; for (int i = 0; i < this.supportCounts.length; i++) { if (this.supportCounts[i] < minimumSupport) { this.supportCounts[i] = 0; this.distinctTransactionsCounts[i] = 0; } else if (this.supportCounts[i] == this.transactionsCount) { closureBuilder.add(i); this.supportCounts[i] = 0; this.distinctTransactionsCounts[i] = 0; } else { biggestItemID = Math.max(biggestItemID, i); remainingFrequents++; remainingDistinctTransLengths += this.distinctTransactionsCounts[i]; } } this.closure = closureBuilder.get(); if (parentPattern.length == 0 && extension >= this.reverseRenaming.length) { this.pattern = Arrays.copyOf(this.closure, this.closure.length); for (int i = 0; i < this.pattern.length; i++) { this.pattern[i] = this.reverseRenaming[this.pattern[i]]; } } else { this.pattern = ItemsetsFactory.extendRename(this.closure, extension, parentPattern, this.reverseRenaming); } this.distinctTransactionLengthSum = remainingDistinctTransLengths; this.nbFrequents = remainingFrequents; this.maxFrequent = biggestItemID; } /** * Does item counting over an initial dataset : it will only ignore * infrequent items, and it doesn't know what's biggest item ID. IT ALSO * IGNORES TRANSACTIONS WEIGHTS ! (assuming it's 1 everywhere) /!\ It will * perform an absolute renaming : items are renamed (and, likely, * re-ordered) by decreasing support count. For instance 0 will be the most * frequent item. * * Indexes in arrays will refer items' new names, except for closure. * * @param minimumSupport * @param transactions */ DenseCounters(int minimumSupport, Iterator<TransactionReader> transactions, Holder<int[]> renamingHolder) { // no nbCounters because this one is not in a PLCMThread this.minSupport = minimumSupport; TIntIntHashMap supportsMap = new TIntIntHashMap(); int biggestItemID = 0; // item support and transactions counting int transactionsCounter = 0; while (transactions.hasNext()) { TransactionReader transaction = transactions.next(); transactionsCounter++; while (transaction.hasNext()) { int item = transaction.next(); biggestItemID = Math.max(biggestItemID, item); supportsMap.adjustOrPutValue(item, 1, 1); } } this.transactionsCount = transactionsCounter; this.distinctTransactionsCount = transactionsCounter; renamingHolder.value = new int[biggestItemID + 1]; Arrays.fill(renamingHolder.value, -1); // item filtering and final computations : some are infrequent, some // belong to closure final PriorityQueue<ItemAndSupport> renamingHeap = new PriorityQueue<ItemAndSupport>(); ItemsetsFactory closureBuilder = new ItemsetsFactory(); TIntIntIterator iterator = supportsMap.iterator(); while (iterator.hasNext()) { iterator.advance(); final int item = iterator.key(); final int supportCount = iterator.value(); if (supportCount == this.transactionsCount) { closureBuilder.add(item); } else if (supportCount >= minimumSupport) { renamingHeap.add(new ItemAndSupport(item, supportCount)); } // otherwise item is infrequent : its renaming is already -1, ciao } this.closure = closureBuilder.get(); this.pattern = this.closure; this.nbFrequents = renamingHeap.size(); this.maxFrequent = this.nbFrequents - 1; this.maxCandidate = this.maxFrequent + 1; this.supportCounts = new int[this.nbFrequents]; this.distinctTransactionsCounts = new int[this.nbFrequents]; this.reverseRenaming = new int[this.nbFrequents]; int remainingSupportsSum = 0; ItemAndSupport entry = renamingHeap.poll(); int newItemID = 0; while (entry != null) { final int item = entry.item; final int support = entry.support; renamingHolder.value[item] = newItemID; this.reverseRenaming[newItemID] = item; this.supportCounts[newItemID] = support; this.distinctTransactionsCounts[newItemID] = support; remainingSupportsSum += support; entry = renamingHeap.poll(); newItemID++; } this.compactedArrays = true; this.distinctTransactionLengthSum = remainingSupportsSum; } private DenseCounters(int minSupport, int transactionsCount, int distinctTransactionsCount, int distinctTransactionLengthSum, int[] supportCounts, int[] distinctTransactionsCounts, int[] closure, int[] pattern, int nbFrequents, int maxFrequent, int[] reverseRenaming, boolean compactedArrays, int maxCandidate) { super(); this.minSupport = minSupport; this.transactionsCount = transactionsCount; this.distinctTransactionsCount = distinctTransactionsCount; this.distinctTransactionLengthSum = distinctTransactionLengthSum; this.supportCounts = supportCounts; this.distinctTransactionsCounts = distinctTransactionsCounts; this.closure = closure; this.pattern = pattern; this.nbFrequents = nbFrequents; this.maxFrequent = maxFrequent; this.reverseRenaming = reverseRenaming; this.compactedArrays = compactedArrays; this.maxCandidate = maxCandidate; } @Override protected DenseCounters clone() { return new DenseCounters(minSupport, transactionsCount, distinctTransactionsCount, distinctTransactionLengthSum, Arrays.copyOf(supportCounts, supportCounts.length), Arrays.copyOf( distinctTransactionsCounts, distinctTransactionsCounts.length), Arrays.copyOf(closure, closure.length), Arrays.copyOf(pattern, pattern.length), nbFrequents, maxFrequent, Arrays.copyOf(reverseRenaming, reverseRenaming.length), compactedArrays, maxCandidate); } /** * Will compress an older renaming, by removing infrequent items. Contained * arrays (except closure) will refer new item IDs * * @param olderReverseRenaming * reverseRenaming from the dataset that fed this Counter * @return the translation from the old renaming to the compressed one * (gives -1 for removed items) */ public int[] compressRenaming(int[] olderReverseRenaming) { if (olderReverseRenaming == null) { olderReverseRenaming = this.reverseRenaming; } int[] renaming = new int[Math.max(olderReverseRenaming.length, this.supportCounts.length)]; this.reverseRenaming = new int[this.nbFrequents]; // we will always have newItemID <= item int newItemID = 0; int greatestBelowMaxCandidate = Integer.MIN_VALUE; for (int item = 0; item < this.supportCounts.length; item++) { if (this.supportCounts[item] > 0) { renaming[item] = newItemID; this.reverseRenaming[newItemID] = olderReverseRenaming[item]; this.distinctTransactionsCounts[newItemID] = this.distinctTransactionsCounts[item]; this.supportCounts[newItemID] = this.supportCounts[item]; if (item < this.maxCandidate) { greatestBelowMaxCandidate = newItemID; } newItemID++; } else { renaming[item] = -1; } } this.maxCandidate = greatestBelowMaxCandidate + 1; Arrays.fill(renaming, this.supportCounts.length, renaming.length, -1); this.maxFrequent = newItemID - 1; this.compactedArrays = true; return renaming; } private void quickSortOnSup(int start, int end) { if (start >= end - 1) { // size 0 or 1 return; } else if (end - start == 2) { if (this.supportCounts[start] < this.supportCounts[start + 1]) { this.swap(start, start + 1); } } else { // pick pivot at the middle and put it at the end int pivotPos = start + ((end - start) / 2); int pivotVal = this.supportCounts[pivotPos]; this.swap(pivotPos, end - 1); int insertInf = start; int insertSup = end - 2; for (int i = start; i <= insertSup;) { if (this.supportCounts[i] > pivotVal || this.supportCounts[i] == pivotVal && i < pivotPos) { insertInf++; i++; } else { this.swap(i, insertSup); insertSup } } this.swap(end - 1, insertSup + 1); quickSortOnSup(start, insertInf); quickSortOnSup(insertSup + 2, end); } } final public boolean raiseMinimumSupport(PerItemTopKCollector topKcoll, boolean careAboutFutureExtensions) { int updatedMinSupport = Integer.MAX_VALUE; for (int item : this.pattern) { int bound = topKcoll.getBound(item); if (bound <= this.transactionsCount) { updatedMinSupport = Math.min(updatedMinSupport, bound); if (updatedMinSupport <= this.minSupport) { return false; } } } if (careAboutFutureExtensions) { for (int i = 0; i < this.maxCandidate; i++) { int count = this.getSupportCount(i); if (count != 0) { int bound = topKcoll.getBound(this.reverseRenaming[i]); if (bound <= count) { updatedMinSupport = Math.min(updatedMinSupport, bound); if (updatedMinSupport <= this.minSupport) { return false; } } } } } int remainingDistinctTransLengths = 0; int remainingFrequents = 0; int biggestItemID = 0; this.minSupport = updatedMinSupport; for (int i = 0; i <= this.maxFrequent; i++) { int count = this.getSupportCount(i); if (count != 0) { if (count < this.minSupport) { this.eraseItem(i); } else { biggestItemID = Math.max(biggestItemID, i); remainingFrequents++; remainingDistinctTransLengths += count; } } } CountersHandler.add(TopLCMCounters.DatasetReductionByEpsilonRaising, this.distinctTransactionLengthSum - remainingDistinctTransLengths); this.distinctTransactionLengthSum = remainingDistinctTransLengths; this.nbFrequents = remainingFrequents; this.maxFrequent = biggestItemID; return true; } final public int insertUnclosedPatterns(PerItemTopKCollector topKcoll, boolean outputPatternsForFutureExtensions) { int[] topKDistinctSupports = new int[topKcoll.getK()]; int[] topKCorrespondingItems = new int[topKcoll.getK()]; boolean highestUnique = false; // split between extension candidates and others ? // set a max because some items will never be able to raise their // threshold anyway? for (int i = 0; i < this.maxCandidate; i++) { int count = this.getSupportCount(i); if (count != 0) { if (outputPatternsForFutureExtensions) { topKcoll.collectUnclosedForItem(count, this.pattern, this.reverseRenaming[i]); } highestUnique = updateTopK(topKDistinctSupports, topKCorrespondingItems, i, count, highestUnique); } } for (int i = this.maxCandidate; i <= this.maxFrequent; i++) { int count = this.getSupportCount(i); if (count != 0) { highestUnique = updateTopK(topKDistinctSupports, topKCorrespondingItems, i, count, highestUnique); } } boolean highest = true; int lastInsertSupport = this.minSupport; for (int i = topKDistinctSupports.length - 1; i >= 0; i if (topKDistinctSupports[i] == 0) { // AKA I didn't find k distinct supports lastInsertSupport = -1; break; } else { int[] newPattern = Arrays.copyOf(this.pattern, this.pattern.length + 1); newPattern[pattern.length] = this.reverseRenaming[topKCorrespondingItems[i]]; topKcoll.collect(topKDistinctSupports[i], newPattern, highest && highestUnique); lastInsertSupport = topKDistinctSupports[i]; } highest = false; } return lastInsertSupport; } private void swap(int i, int j) { int temp; temp = this.supportCounts[i]; this.supportCounts[i] = this.supportCounts[j]; this.supportCounts[j] = temp; temp = this.reverseRenaming[i]; this.reverseRenaming[i] = this.reverseRenaming[j]; this.reverseRenaming[j] = temp; temp = this.distinctTransactionsCounts[i]; this.distinctTransactionsCounts[i] = this.distinctTransactionsCounts[j]; this.distinctTransactionsCounts[j] = temp; } /** * Will compress an older renaming, by removing infrequent items. Contained * arrays (except closure) will refer new item IDs * * @param olderReverseRenaming * reverseRenaming from the dataset that fed this Counter * @param items * below this parameter will be renamed by decreasing frequency * @return the translation from the old renaming to the compressed one * (gives -1 for removed items) */ public int[] compressSortRenaming(int[] olderReverseRenaming) { if (olderReverseRenaming == null) { olderReverseRenaming = this.reverseRenaming; } this.reverseRenaming = new int[this.nbFrequents]; // first, compact // we will always have newItemID <= item int newItemID = 0; int greatestBelowMaxCandidate = Integer.MIN_VALUE; // after this loop we have // reverseRenaming: NewBase (index) -> PreviousDatasetBase (value) // supportCounts: NewBase (index) -> Support (value) // distinctTransactionCount: NewBase (index) -> Count (value) for (int item = 0; item < this.supportCounts.length; item++) { if (this.supportCounts[item] > 0) { this.reverseRenaming[newItemID] = item; this.supportCounts[newItemID] = this.supportCounts[item]; this.distinctTransactionsCounts[newItemID] = this.distinctTransactionsCounts[item]; if (item < this.maxCandidate) { greatestBelowMaxCandidate = newItemID; } newItemID++; } } this.maxCandidate = greatestBelowMaxCandidate + 1; this.maxFrequent = newItemID - 1; // now, sort up to the pivot this.quickSortOnSup(0, this.maxCandidate); int[] renaming = new int[Math.max(olderReverseRenaming.length, this.supportCounts.length)]; Arrays.fill(renaming, -1); // after this loop we have // reverseRenaming: NewBase (index) -> OriginalBase (value) // renaming: PreviousDatasetBase (index) -> NewBase (value) for (int i = 0; i <= this.maxFrequent; i++) { renaming[this.reverseRenaming[i]] = i; this.reverseRenaming[i] = olderReverseRenaming[this.reverseRenaming[i]]; } this.compactedArrays = true; return renaming; } /** * Notice: enumerated item IDs are in local base, use this.reverseRenaming * * @return an iterator over frequent items (in ascending order) */ public FrequentsIterator getLocalFrequentsIterator(final int from, final int to) { FrequentIterator iterator = localFrequentsIterator.get(); iterator.recycle(from, to, this); return iterator; } public final int getDistinctTransactionsCount(int item) { return distinctTransactionsCounts[item]; } public final int getSupportCount(int item) { return this.supportCounts[item]; } }
package hudson.plugins.analysis.core; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.exception.ExceptionUtils; import hudson.FilePath; import hudson.FilePath.FileCallable; import hudson.plugins.analysis.Messages; import hudson.plugins.analysis.util.FileFinder; import hudson.plugins.analysis.util.ModuleDetector; import hudson.plugins.analysis.util.NullModuleDetector; import hudson.plugins.analysis.util.PluginLogger; import hudson.plugins.analysis.util.StringPluginLogger; import hudson.plugins.analysis.util.model.FileAnnotation; import hudson.remoting.VirtualChannel; /** * Parses files that match the specified pattern and creates a corresponding * {@link ParserResult} with a collection of annotations. * * @author Ulli Hafner */ public class FilesParser implements FileCallable<ParserResult> { private static final long serialVersionUID = -6415863872891783891L; /** Logs into a string. @since 1.20 */ @edu.umd.cs.findbugs.annotations.SuppressWarnings("Se") private transient StringPluginLogger stringLogger; /** Ant file-set pattern to scan for. */ private final String filePattern; /** Parser to be used to process the workspace files. */ private final AnnotationParser parser; /** Determines whether this build uses maven. */ private final boolean isMavenBuild; /** The predefined module name, might be empty. */ private final String moduleName; /** Determines whether module names should be derived from Maven or Ant. */ private boolean shouldDetectModules = true; private final String pluginId; /** * Creates a new instance of {@link FilesParser}. * @param filePattern * ant file-set pattern to scan for files to parse * @param parser * the parser to apply on the found files * @param isMavenBuild * determines whether this build uses maven */ private FilesParser(final String filePattern, final AnnotationParser parser, final boolean isMavenBuild, final String moduleName) { this.filePattern = filePattern; this.parser = parser; this.isMavenBuild = isMavenBuild; this.moduleName = moduleName; pluginId = "[ANALYSIS] "; } /** * Creates a new instance of {@link FilesParser}. * * @param logger * the logger * @param filePattern * ant file-set pattern to scan for files to parse * @param parser * the parser to apply on the found files * @param isMavenBuild * determines whether this build uses maven * @deprecated Use * {@link #FilesParser(String, String, AnnotationParser, boolean, boolean)} */ @Deprecated @SuppressWarnings("PMD") public FilesParser(final PluginLogger logger, final String filePattern, final AnnotationParser parser, final boolean isMavenBuild) { this(filePattern, parser, isMavenBuild, StringUtils.EMPTY); } /** * Creates a new instance of {@link FilesParser}. Assumes that this is a * Maven build with the specified module name. * * @param logger * the logger * @param filePattern * ant file-set pattern to scan for files to parse * @param parser * the parser to apply on the found files * @param moduleName * the name of the module to use for all files * @deprecated Use * {@link #FilesParser(String, String, AnnotationParser, boolean, boolean)} */ @Deprecated @SuppressWarnings("PMD") public FilesParser(final PluginLogger logger, final String filePattern, final AnnotationParser parser, final String moduleName) { this(filePattern, parser, true, moduleName); } /** * Creates a new instance of {@link FilesParser}. Assumes that this is a * Maven build with the specified module name. * * @param logger * the logger * @param filePattern * ant file-set pattern to scan for files to parse * @param parser * the parser to apply on the found files * @deprecated Use * {@link #FilesParser(String, String, AnnotationParser, boolean, boolean)} */ @Deprecated @SuppressWarnings("PMD") public FilesParser(final PluginLogger logger, final String filePattern, final AnnotationParser parser) { this(filePattern, parser, true, StringUtils.EMPTY); shouldDetectModules = false; } /** * Creates a new instance of {@link FilesParser}. * * @param logger * the logger * @param filePattern * ant file-set pattern to scan for files to parse * @param parser * the parser to apply on the found files * @param moduleName * the name of the module to use for all files * @deprecated Use * {@link #FilesParser(String, String, AnnotationParser, boolean, boolean)} */ @Deprecated @SuppressWarnings("PMD") public FilesParser(final StringPluginLogger logger, final String filePattern, final AnnotationParser parser, final String moduleName) { this(filePattern, parser, true, moduleName); } /** * Creates a new instance of {@link FilesParser}. * * @param logger * the logger * @param filePattern * ant file-set pattern to scan for files to parse * @param parser * the parser to apply on the found files * @param shouldDetectModules * determines whether modules should be detected from pom.xml or * build.xml files * @param isMavenBuild * determines whether this build uses maven * @deprecated Use * {@link #FilesParser(String, String, AnnotationParser, boolean, boolean)} */ @Deprecated @SuppressWarnings("PMD") public FilesParser(final StringPluginLogger logger, final String filePattern, final AnnotationParser parser, final boolean shouldDetectModules, final boolean isMavenBuild) { this(filePattern, parser, isMavenBuild, StringUtils.EMPTY); } /** * Creates a new instance of {@link FilesParser}. * @param filePattern * ant file-set pattern to scan for files to parse * @param parser * the parser to apply on the found files * @param shouldDetectModules * determines whether modules should be detected from pom.xml or * build.xml files * @param isMavenBuild * determines whether this build uses maven * @param moduleName * the name of the module to use for all files */ private FilesParser(final String pluginId, final String filePattern, final AnnotationParser parser, final boolean shouldDetectModules, final boolean isMavenBuild, final String moduleName) { this.pluginId = pluginId; this.filePattern = filePattern; this.parser = parser; this.isMavenBuild = isMavenBuild; this.moduleName = moduleName; this.shouldDetectModules = shouldDetectModules; } /** * Creates a new instance of {@link FilesParser}. * * @param pluginId * the ID of the plug-in that uses this parser * @param filePattern * ant file-set pattern to scan for files to parse * @param parser * the parser to apply on the found files * @param moduleName * the name of the module to use for all files */ public FilesParser(final String pluginId, final String filePattern, final AnnotationParser parser, final String moduleName) { this(pluginId, filePattern, parser, true, true, moduleName); } /** * Creates a new instance of {@link FilesParser}. * * @param pluginId * the ID of the plug-in that uses this parser * @param filePattern * ant file-set pattern to scan for files to parse * @param parser * the parser to apply on the found files * @param shouldDetectModules * determines whether modules should be detected from pom.xml or * build.xml files * @param isMavenBuild * determines whether this build uses maven */ public FilesParser(final String pluginId, final String filePattern, final AnnotationParser parser, final boolean shouldDetectModules, final boolean isMavenBuild) { this(pluginId, filePattern, parser, shouldDetectModules, isMavenBuild, StringUtils.EMPTY); } /** * Logs the specified message. * * @param message the message */ protected void log(final String message) { if (stringLogger == null) { stringLogger = new StringPluginLogger(pluginId); } stringLogger.log(message); } /** {@inheritDoc} */ public ParserResult invoke(final File workspace, final VirtualChannel channel) throws IOException { ParserResult result = new ParserResult(new FilePath(workspace)); try { String[] fileNames = new FileFinder(filePattern).find(workspace); if (fileNames.length == 0) { if (isMavenBuild) { log("No files found in " + workspace.getAbsolutePath() + " for pattern: " + filePattern); } else { result.addErrorMessage(Messages.FilesParser_Error_NoFiles()); } } else { log("Parsing " + fileNames.length + " files in " + workspace.getAbsolutePath()); parseFiles(workspace, fileNames, result); } } catch (InterruptedException exception) { log("Parsing has been canceled."); } if (stringLogger != null) { result.setLog(stringLogger.toString()); } for (FileAnnotation annotation : result.getAnnotations()) { annotation.setPathName(workspace.getAbsolutePath()); } return result; } /** * Parses the specified collection of files and appends the results to the * provided container. * * @param workspace * the workspace root * @param fileNames * the names of the file to parse * @param result * the result of the parsing * @throws InterruptedException * if the user cancels the parsing */ private void parseFiles(final File workspace, final String[] fileNames, final ParserResult result) throws InterruptedException { ModuleDetector detector = createModuleDetector(workspace); for (String fileName : fileNames) { File file = new File(workspace, fileName); String module = getModuleName(detector, file); if (!file.canRead()) { String message = Messages.FilesParser_Error_NoPermission(module, file); log(message); result.addErrorMessage(module, message); continue; } if (file.length() <= 0) { String message = Messages.FilesParser_Error_EmptyFile(module, file); log(message); result.addErrorMessage(module, message); continue; } parseFile(file, module, result); result.addModule(module); } } private ModuleDetector createModuleDetector(final File workspace) { if (shouldDetectModules) { return new ModuleDetector(workspace); } else { return new NullModuleDetector(); } } private String getModuleName(final ModuleDetector detector, final File file) { String module; if (StringUtils.isBlank(moduleName)) { module = detector.guessModuleName(file.getAbsolutePath()); } else { module = moduleName; } return module; } /** * Parses the specified file and stores all found annotations. If the file * could not be parsed then an error message is appended to the result. * * @param file * the file to parse * @param module * the associated module * @param result * the result of the parser * @throws InterruptedException * if the user cancels the parsing */ private void parseFile(final File file, final String module, final ParserResult result) throws InterruptedException { try { Collection<FileAnnotation> annotations = parser.parse(file, module); result.addAnnotations(annotations); log("Successfully parsed file " + file + " of module " + module + " with " + annotations.size() + " warnings."); } catch (InvocationTargetException exception) { String errorMessage = Messages.FilesParser_Error_Exception(file) + "\n\n" + ExceptionUtils.getStackTrace((Throwable)ObjectUtils.defaultIfNull(exception.getCause(), exception)); result.addErrorMessage(module, errorMessage); log(errorMessage); } } }
package info.faceland.loot.items; import com.tealcube.minecraft.bukkit.facecore.shade.hilt.HiltItemStack; import com.tealcube.minecraft.bukkit.facecore.utilities.TextUtils; import info.faceland.loot.LootPlugin; import info.faceland.loot.api.items.ItemBuilder; import info.faceland.loot.api.items.ItemGenerationReason; import info.faceland.loot.api.tier.Tier; import info.faceland.loot.math.LootRandom; import org.bukkit.Material; import org.bukkit.inventory.ItemFlag; import java.util.ArrayList; import java.util.List; import java.util.Set; public final class LootItemBuilder implements ItemBuilder { private final LootPlugin plugin; private boolean built = false; private Tier tier; private Material material; private ItemGenerationReason itemGenerationReason = ItemGenerationReason.MONSTER; private LootRandom random; private double distance; public LootItemBuilder(LootPlugin plugin) { this.plugin = plugin; this.random = new LootRandom(System.currentTimeMillis()); } @Override public boolean isBuilt() { return built; } @Override public HiltItemStack build() { if (isBuilt()) { throw new IllegalStateException("already built"); } built = true; HiltItemStack hiltItemStack; int attempts = 0; while (tier == null && attempts < 10) { tier = chooseTier(); if (material != null && tier != null && !tier.getAllowedMaterials().contains(material)) { tier = null; } attempts++; } if (tier == null) { throw new IllegalStateException("tier is null"); } if (material == null) { Set<Material> set = tier.getAllowedMaterials(); Material[] array = set.toArray(new Material[set.size()]); if (array.length == 0) { throw new RuntimeException("array length is 0 for tier: " + tier.getName()); } material = array[random.nextInt(array.length)]; } hiltItemStack = new HiltItemStack(material); hiltItemStack.setUnbreakable(true); hiltItemStack.getItemMeta().addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_UNBREAKABLE); hiltItemStack.setName(tier.getDisplayColor() + plugin.getNameManager().getRandomPrefix() + " " + plugin .getNameManager().getRandomSuffix() + tier.getIdentificationColor()); List<String> lore = new ArrayList<>(tier.getBaseLore()); lore.addAll(plugin.getSettings().getStringList("corestats." + material.name(), new ArrayList<String>())); int bonusLore = random.nextIntRange(tier.getMinimumBonusLore(), tier.getMaximumBonusLore()); for (int i = 0; i < bonusLore; i++) { lore.add(tier.getBonusLore().get(random.nextInt(tier.getBonusLore().size()))); } if (tier.isEnchantable()) { lore.add("<blue>(Enchantable)"); } int sockets = random.nextIntRange(tier.getMinimumSockets(), tier.getMaximumSockets()); for (int i = 0; i < sockets; i++) { lore.add("<gold>(Socket)"); } if (random.nextDouble() < tier.getExtendableChance()) { lore.add("<dark aqua>(+)"); } hiltItemStack.setLore(TextUtils.color(lore)); return hiltItemStack; } @Override public ItemBuilder withTier(Tier t) { tier = t; return this; } @Override public ItemBuilder withMaterial(Material m) { material = m; return this; } @Override public ItemBuilder withItemGenerationReason(ItemGenerationReason reason) { itemGenerationReason = reason; return this; } @Override public ItemBuilder withDistance(double d) { distance = d; return this; } private Tier chooseTier() { if (itemGenerationReason == ItemGenerationReason.IDENTIFYING) { double totalWeight = 0D; for (Tier t : plugin.getTierManager().getLoadedTiers()) { totalWeight += t.getIdentifyWeight() + ((distance / 10000D) * t.getDistanceWeight()); } double chosenWeight = random.nextDouble() * totalWeight; double currentWeight = 0D; for (Tier t : plugin.getTierManager().getLoadedTiers()) { currentWeight += t.getIdentifyWeight() + ((distance / 10000D) * t.getDistanceWeight()); if (currentWeight >= chosenWeight) { return t; } } return null; } return plugin.getTierManager().getRandomTier(true, distance); } }
package io.asfjava.ui.core.form; import java.util.HashMap; public class TitleMapsAdapter { public Map<String,Object> getPossibleValues(){ return null; } }
package io.foobot.maven.plugins.docker; import java.io.File; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.util.List; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Resource; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.settings.Settings; import org.codehaus.plexus.util.DirectoryScanner; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.model.BuildResponseItem; import com.github.dockerjava.core.DefaultDockerClientConfig; import com.github.dockerjava.core.DockerClientBuilder; import com.github.dockerjava.core.DockerClientConfig; import com.github.dockerjava.core.command.BuildImageResultCallback; @Mojo(name = "build") public class BuildMojo extends AbstractMojo { @Parameter(name = "${mojoExecution}", readonly = true) protected MojoExecution execution; @Parameter(name = "${session}", readonly = true) protected MavenSession session; @Parameter(name = "${settings}", readonly = true) protected Settings settings; @Parameter(property = "project.build.directory") protected File buildDirectory; @Parameter(property = "skipDocker", defaultValue = "false") private boolean skipDocker; @Parameter(property = "directory") private File directory; @Parameter(property = "forceRm", defaultValue = "false") private boolean forceRm; @Parameter(property = "noCache", defaultValue = "false") private boolean noCache; @Parameter(property = "pull", defaultValue = "false") private boolean pull; @Parameter(property = "imageName") private String imageName; @Parameter(property = "imageTags") private List<String> imageTags; @Parameter(property = "resources") private List<Resource> resources; public void execute() throws MojoExecutionException, MojoFailureException { if (skipDocker) { getLog().info("Docker is skipped."); return; } validateParameters(); DockerClientConfig dockerClientConfig = DefaultDockerClientConfig.createDefaultConfigBuilder() .withDockerHost("unix:///var/run/docker.sock").withDockerTlsVerify(false).build(); DockerClient dockerClient = null; try { dockerClient = DockerClientBuilder.getInstance(dockerClientConfig).build(); build(dockerClient); } catch (Exception e) { throw new MojoExecutionException("Error during plugin execution", e); } finally { if (dockerClient != null) { try { dockerClient.close(); } catch (IOException e) { } } } } private void validateParameters() throws MojoExecutionException { if (directory == null) { throw new MojoExecutionException("missing option 'directory'"); } if (imageName == null) { throw new MojoExecutionException("missing option 'imageName'"); } } private void build(DockerClient dockerClient) throws IOException { getLog().info("Copying resources"); Resource dockerResource = new Resource(); dockerResource.setDirectory(directory.toString()); resources.add(dockerResource); Path buildPath = Paths.get(buildDirectory.toString(), "docker"); for (Resource resource : resources) { List<String> includes = resource.getIncludes(); List<String> excludes = resource.getExcludes(); DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(new File(resource.getDirectory())); scanner.setIncludes(includes.isEmpty() ? null : includes.toArray(new String[includes.size()])); scanner.setExcludes(excludes.isEmpty() ? null : excludes.toArray(new String[excludes.size()])); scanner.scan(); String[] includedFiles = scanner.getIncludedFiles(); if (includedFiles.length == 0) continue; boolean copyDirectory = includes.isEmpty() && excludes.isEmpty() && (resource.getTargetPath() != null); if (copyDirectory) { Path source = Paths.get(resource.getDirectory()); Path destination = Paths.get(buildPath.toString(), resource.getTargetPath()); Files.createDirectories(destination); Files.walkFileTree(source, new CopyDirectory(source, destination)); } else { for (String file : includedFiles) { Path source = Paths.get(resource.getDirectory()).resolve(file); Path destination = Paths.get(buildPath.toString(), (resource.getTargetPath() == null ? "" : resource.getTargetPath())).resolve(file); Files.createDirectories(destination.getParent()); Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); } } } getLog().info("Building image " + imageName); BuildImageResultCallback callback = new BuildImageResultCallback() { @Override public void onNext(BuildResponseItem item) { if (item.getStream() != null) { getLog().info(item.getStream().trim()); } super.onNext(item); } }; String imageId = dockerClient.buildImageCmd(buildPath.toFile()).withForcerm(forceRm).withNoCache(noCache) .withPull(pull).exec(callback).awaitImageId(); getLog().info("Tagging image " + imageName); dockerClient.tagImageCmd(imageId, imageName, "latest").exec(); for (String imageTag : imageTags) { dockerClient.tagImageCmd(imageId, imageName, imageTag).exec(); } } private static class CopyDirectory extends SimpleFileVisitor<Path> { private Path sourcePath; private Path destinationPath; public CopyDirectory(Path sourcePath, Path destinationPath) { this.sourcePath = sourcePath; this.destinationPath = destinationPath; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Path target = destinationPath.resolve(sourcePath.relativize(dir)); if (Files.notExists(target)) { Files.createDirectories(destinationPath.resolve(sourcePath.relativize(dir))); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.copy(file, destinationPath.resolve(sourcePath.relativize(file)), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); return FileVisitResult.CONTINUE; } } }
package io.github.mzmine.util.adap; import com.google.common.collect.Range; import dulab.adap.datamodel.BetterPeak; import dulab.adap.datamodel.Chromatogram; import dulab.adap.datamodel.Component; import dulab.adap.datamodel.Peak; import dulab.adap.datamodel.PeakInfo; import io.github.mzmine.datamodel.DataPoint; import io.github.mzmine.datamodel.FeatureStatus; import io.github.mzmine.datamodel.IsotopePattern; import io.github.mzmine.datamodel.RawDataFile; import io.github.mzmine.datamodel.Scan; import io.github.mzmine.datamodel.featuredata.IonTimeSeries; import io.github.mzmine.datamodel.featuredata.impl.SimpleIonTimeSeries; import io.github.mzmine.datamodel.features.Feature; import io.github.mzmine.datamodel.features.FeatureListRow; import io.github.mzmine.datamodel.features.ModularFeature; import io.github.mzmine.datamodel.features.ModularFeatureList; import io.github.mzmine.datamodel.impl.SimpleDataPoint; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.TreeMap; import org.jetbrains.annotations.NotNull; /** * @author aleksandrsmirnov */ public class ADAPInterface { public static Component getComponent(final FeatureListRow row) { if (row.getNumberOfFeatures() == 0) { throw new IllegalArgumentException("No peaks found"); } NavigableMap<Double, Double> spectrum = new TreeMap<>(); // Read Spectrum information IsotopePattern ip = row.getBestIsotopePattern(); if (ip != null) { for (DataPoint dataPoint : ip) { spectrum.put(dataPoint.getMZ(), dataPoint.getIntensity()); } } // Read Chromatogram final Feature peak = row.getBestFeature(); final RawDataFile dataFile = peak.getRawDataFile(); NavigableMap<Double, Double> chromatogram = new TreeMap<>(); List<DataPoint> dataPoints = peak.getDataPoints(); for (int i = 0; i < dataPoints.size(); i++) { final DataPoint dataPoint = dataPoints.get(i); if (dataPoint != null) { float rt = peak.getRetentionTimeAtIndex(i); chromatogram.put(Double.valueOf(String.valueOf(rt)), dataPoint.getIntensity()); } } return new Component(null, new Peak(chromatogram, new PeakInfo().mzValue(peak.getMZ()).peakID(row.getID())), spectrum, null); } @NotNull public static ModularFeature peakToFeature(@NotNull ModularFeatureList featureList, @NotNull RawDataFile file, @NotNull BetterPeak peak) { Chromatogram chromatogram = peak.chromatogram; List<Scan> scanNumbers = new ArrayList<>(chromatogram.length); int count = 0; double startRetTime = chromatogram.getFirstRetTime(); double endRetTime = chromatogram.getLastRetTimes(); for (Scan scan : file.getScans()) { double retTime = scan.getRetentionTime(); if (retTime < startRetTime || retTime > endRetTime) continue; scanNumbers.add(scan); if (scanNumbers.size() == chromatogram.length) break; } // Calculate peak area double area = 0.0; for (int i = 1; i < chromatogram.length; ++i) { double base = (chromatogram.xs[i] - chromatogram.xs[i - 1]) * 60d; double height = 0.5 * (chromatogram.ys[i] + chromatogram.ys[i - 1]); area += base * height; } //Get mzs values from peak and intensities from chromatogram final double[] newMzs = new double[scanNumbers.size()]; final double[] newIntensities = new double[scanNumbers.size()]; for (int i = 0; i < newMzs.length; i++) { newMzs[i] = peak.getMZ(); newIntensities[i] = chromatogram.ys[i]; } SimpleIonTimeSeries simpleIonTimeSeries = new SimpleIonTimeSeries(null, newMzs, newIntensities, scanNumbers); return new ModularFeature(featureList, file, simpleIonTimeSeries, FeatureStatus.ESTIMATED); } @NotNull public static Feature peakToFeature(@NotNull ModularFeatureList featureList, @NotNull RawDataFile file, @NotNull Peak peak) { NavigableMap<Double, Double> chromatogram = peak.getChromatogram(); double[] retTimes = new double[chromatogram.size()]; double[] intensities = new double[chromatogram.size()]; int index = 0; for (Entry<Double, Double> e : chromatogram.entrySet()) { retTimes[index] = e.getKey(); intensities[index] = e.getValue(); ++index; } BetterPeak betterPeak = new BetterPeak(peak.getInfo().peakID, new Chromatogram(retTimes, intensities), peak.getInfo()); return peakToFeature(featureList, file, betterPeak); } }
package io.sniffy.servlet; import io.sniffy.Sniffer; import io.sniffy.Spy; import io.sniffy.Threads; import io.sniffy.sql.StatementMetaData; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.nio.charset.Charset; import java.util.List; import java.util.UUID; import static io.sniffy.servlet.SnifferFilter.HEADER_NUMBER_OF_QUERIES; import static io.sniffy.servlet.SnifferFilter.HEADER_REQUEST_DETAILS; import static io.sniffy.servlet.SnifferFilter.HEADER_TIME_TO_FIRST_BYTE; class SniffyRequestProcessor implements BufferedServletResponseListener { private final SnifferFilter snifferFilter; private final ServletRequest request; private final ServletResponse response; private final Spy<? extends Spy> spy; private final String requestId; private final RequestStats requestStats = new RequestStats(); private long startMillis; private long timeToFirstByte; private long elapsedTime; public void initStartMillis() { startMillis = System.currentTimeMillis(); } public long getTimeToFirstByte() { if (0 == timeToFirstByte) timeToFirstByte = System.currentTimeMillis() - startMillis; return timeToFirstByte; } public long getElapsedTime() { if (0 == elapsedTime) elapsedTime = System.currentTimeMillis() - startMillis; return elapsedTime; } public SniffyRequestProcessor(SnifferFilter snifferFilter, ServletRequest request, ServletResponse response) { this.snifferFilter = snifferFilter; this.request = request; this.response = response; spy = Sniffer.spy(); requestId = UUID.randomUUID().toString(); } public void process(FilterChain chain) throws IOException, ServletException { // extract some basic data from request and response HttpServletRequest httpServletRequest; HttpServletResponse httpServletResponse; String contextPath; String relativeUrl; try { httpServletRequest = (HttpServletRequest) request; httpServletResponse = (HttpServletResponse) response; contextPath = httpServletRequest.getContextPath(); relativeUrl = null == httpServletRequest.getRequestURI() ? null : httpServletRequest.getRequestURI().substring(contextPath.length()); } catch (Exception e) { snifferFilter.servletContext.log("Exception in SniffyRequestProcessor; calling original chain", e); chain.doFilter(request, response); return; } // if excluded by pattern return immediately if (null != snifferFilter.excludePattern && null != relativeUrl && snifferFilter.excludePattern.matcher(relativeUrl).matches()) { chain.doFilter(request, response); return; } // create response wrapper BufferedServletResponseWrapper responseWrapper; try { responseWrapper = new BufferedServletResponseWrapper(httpServletResponse, this); } catch (Exception e) { snifferFilter.servletContext.log("Exception in SniffyRequestProcessor; calling original chain", e); chain.doFilter(request, response); return; } // call chain try { initStartMillis(); chain.doFilter(request, responseWrapper); } finally { try { requestStats.setElapsedTime(getElapsedTime()); updateRequestCache(); responseWrapper.flushIfPossible(); } catch (Exception e) { snifferFilter.servletContext.log("Exception in SniffyRequestProcessor; original chain was already called", e); } } } private void updateRequestCache() { List<StatementMetaData> executedStatements = spy.getExecutedStatements(Threads.CURRENT); if (null != executedStatements && !executedStatements.isEmpty()) { requestStats.setExecutedStatements(executedStatements); snifferFilter.cache.put(requestId, requestStats); } } /** * Flag indicating that current response looks like HTML and capable of injecting sniffer widget */ private boolean isHtmlPage = false; @Override public void onBeforeCommit(BufferedServletResponseWrapper wrapper, Buffer buffer) throws IOException { // TODO: can this method be called multiple times? wrapper.addCorsHeadersHeaderIfRequired(); wrapper.addIntHeader(HEADER_NUMBER_OF_QUERIES, spy.executedStatements(Threads.CURRENT)); wrapper.addHeader(HEADER_TIME_TO_FIRST_BYTE, Long.toString(getTimeToFirstByte())); wrapper.addHeader(HEADER_REQUEST_DETAILS, snifferFilter.contextPath + SnifferFilter.REQUEST_URI_PREFIX + requestId); if (snifferFilter.injectHtml) { String contentType = wrapper.getContentType(); String contentEncoding = wrapper.getContentEncoding(); if (null != buffer && null == contentEncoding && null != contentType && contentType.startsWith("text/html")) { // adjust content length with the size of injected content int contentLength = wrapper.getContentLength(); if (contentLength > 0) { wrapper.setContentLength(contentLength + maximumInjectSize(snifferFilter.contextPath)); } isHtmlPage = true; String characterEncoding = wrapper.getCharacterEncoding(); if (null == characterEncoding) { characterEncoding = Charset.defaultCharset().name(); } String snifferHeader = generateHeaderHtml(snifferFilter.contextPath, requestId).toString(); HtmlInjector htmlInjector = new HtmlInjector(buffer, characterEncoding); htmlInjector.injectAtTheBeginning(snifferHeader); } } } @Override // TODO: can this method be called multiple times? public void beforeClose(BufferedServletResponseWrapper wrapper, Buffer buffer) throws IOException { updateRequestCache(); if (snifferFilter.injectHtml && isHtmlPage) { String characterEncoding = wrapper.getCharacterEncoding(); if (null == characterEncoding) { characterEncoding = Charset.defaultCharset().name(); } String snifferWidget = generateAndPadFooterHtml(spy.executedStatements(Threads.CURRENT), getElapsedTime()); HtmlInjector htmlInjector = new HtmlInjector(buffer, characterEncoding); htmlInjector.injectAtTheEnd(snifferWidget); } } protected StringBuilder generateHeaderHtml(String contextPath, String requestId) { return new StringBuilder(). append("<script id=\"sniffy-header\" type=\"application/javascript\" data-request-id=\""). append(requestId). append("\" src=\""). append(contextPath). append(SnifferFilter.JAVASCRIPT_URI). append("\"></script>"); } private int maximumInjectSize; protected int maximumInjectSize(String contextPath) { if (maximumInjectSize == 0) { maximumInjectSize = maximumFooterSize() + generateHeaderHtml(contextPath, UUID.randomUUID().toString()).length(); } return maximumInjectSize; } private int maximumFooterSize() { return generateFooterHtml(Integer.MAX_VALUE, Long.MAX_VALUE).length(); } protected String generateAndPadFooterHtml(int executedQueries, long serverTime) { StringBuilder sb = generateFooterHtml(executedQueries, serverTime); for (int i = sb.length(); i < maximumFooterSize(); i++) { sb.append(" "); } return sb.toString(); } /** * Generates following HTML snippet * <pre> * {@code * <data id="sniffy" data-sql-queries="5"/> * } * </pre> * @param executedQueries number of executed queries * @return StringBuilder with generated HTML */ protected StringBuilder generateFooterHtml(int executedQueries, long serverTime) { return new StringBuilder(). append("<data id=\"sniffy\" data-sql-queries=\""). append(executedQueries). append("\" data-server-time=\""). append(serverTime) .append("\"/>"); } }
package javaslang.collection; import javaslang.Lazy; import javaslang.Tuple; import javaslang.Tuple2; import javaslang.control.None; import javaslang.control.Option; import javaslang.control.Some; import java.io.Serializable; import java.util.Objects; public interface HashArrayMappedTrie<K, V> extends java.lang.Iterable<Tuple2<K, V>> { static <K, V> HashArrayMappedTrie<K, V> empty() { return EmptyNode.instance(); } default boolean isEmpty() { return this == EmptyNode.INSTANCE; } int size(); default Option<V> get(K key) { return ((AbstractNode<K, V>) this).lookup(0, key); } default boolean containsKey(K key) { return get(key).isDefined(); } default HashArrayMappedTrie<K, V> put(K key, V value) { return ((AbstractNode<K, V>) this).modify(0, key, new Some<>(value)); } default HashArrayMappedTrie<K, V> remove(K key) { return ((AbstractNode<K, V>) this).modify(0, key, None.instance()); } // this is a javaslang.collection.Iterator! @Override Iterator<Tuple2<K, V>> iterator(); /** * TODO: javadoc * * @param <K> Key type * @param <V> Value type */ abstract class AbstractNode<K, V> implements HashArrayMappedTrie<K, V> { static final int SIZE = 5; static final int BUCKET_SIZE = 1 << SIZE; static final int MAX_INDEX_NODE = BUCKET_SIZE / 2; static final int MIN_ARRAY_NODE = BUCKET_SIZE / 4; private static final int M1 = 0x55555555; private static final int M2 = 0x33333333; private static final int M4 = 0x0f0f0f0f; private final transient Lazy<Integer> hashCode = Lazy.of(() -> Traversable.hash(this)); int bitCount(int x) { x = x - ((x >> 1) & M1); x = (x & M2) + ((x >> 2) & M2); x = (x + (x >> 4)) & M4; x = x + (x >> 8); x = x + (x >> 16); return x & 0x7f; } int hashFragment(int shift, int hash) { return (hash >>> shift) & (BUCKET_SIZE - 1); } int toBitmap(int hash) { return 1 << hash; } int fromBitmap(int bitmap, int bit) { return bitCount(bitmap & (bit - 1)); } abstract boolean isLeaf(); abstract Option<V> lookup(int shift, K key); abstract AbstractNode<K, V> modify(int shift, K key, Option<V> value); @Override public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof HashArrayMappedTrie) { final Iterator<?> iter1 = this.iterator(); final Iterator<?> iter2 = ((HashArrayMappedTrie<?, ?>) o).iterator(); while (iter1.hasNext() && iter2.hasNext()) { if (!Objects.equals(iter1.next(), iter2.next())) { return false; } } return !iter1.hasNext() && !iter2.hasNext(); } else { return false; } } @Override public int hashCode() { return hashCode.get(); } @Override public String toString() { return List.ofAll(this).mkString(", ", "HashMap(", ")"); } } /** * TODO: javadoc * * @param <K> Key type * @param <V> Value type */ class EmptyNode<K, V> extends AbstractNode<K, V> implements Serializable { private static final long serialVersionUID = 1L; private static final EmptyNode<?, ?> INSTANCE = new EmptyNode<>(); private EmptyNode() { } @SuppressWarnings("unchecked") static <K, V> EmptyNode<K, V> instance() { return (EmptyNode<K, V>) INSTANCE; } @Override Option<V> lookup(int shift, K key) { return None.instance(); } @Override AbstractNode<K, V> modify(int shift, K key, Option<V> value) { return value.isEmpty() ? this : new LeafNode<>(key.hashCode(), key, value.get()); } @Override boolean isLeaf() { return true; } @Override public int size() { return 0; } @Override public Iterator<Tuple2<K, V>> iterator() { return Iterator.empty(); } /** * Instance control for object serialization. * * @return The singleton instance of EmptyNode. * @see java.io.Serializable */ private Object readResolve() { return INSTANCE; } } /** * TODO: javadoc * * @param <K> Key type * @param <V> Value type */ class LeafNode<K, V> extends AbstractNode<K, V> implements Serializable { private static final long serialVersionUID = 1L; private final int hash; private final int size; private final List<Tuple2<K, V>> entries; private LeafNode(int hash, K key, V value) { this(hash, 1, List.of(Tuple.of(key, value))); } private LeafNode(int hash, int size, List<Tuple2<K, V>> entries) { this.hash = hash; this.size = size; this.entries = entries; } private AbstractNode<K, V> update(K key, Option<V> value) { List<Tuple2<K, V>> filtered = entries.removeFirst(t -> t._1.equals(key)); if (value.isEmpty()) { return filtered.isEmpty() ? EmptyNode.instance() : new LeafNode<>(hash, filtered.length(), filtered); } else { return new LeafNode<>(hash, filtered.length() + 1, filtered.prepend(Tuple.of(key, value.get()))); } } @Override Option<V> lookup(int shift, K key) { if (hash != key.hashCode()) { return None.instance(); } return entries.findFirst(t -> t._1.equals(key)).map(t -> t._2); } @Override AbstractNode<K, V> modify(int shift, K key, Option<V> value) { if (key.hashCode() == hash) { return update(key, value); } else { return value.isEmpty() ? this : mergeLeaves(shift, new LeafNode<>(key.hashCode(), key, value.get())); } } AbstractNode<K, V> mergeLeaves(int shift, LeafNode<K, V> other) { final int h1 = this.hash; final int h2 = other.hash; if (h1 == h2) { return new LeafNode<>(h1, size + other.size, other.entries.foldLeft(entries, List::prepend)); } final int subH1 = hashFragment(shift, h1); final int subH2 = hashFragment(shift, h2); final int newBitmap = toBitmap(subH1) | toBitmap(subH2); if(subH1 == subH2) { AbstractNode<K, V> newLeaves = mergeLeaves(shift + SIZE, other); return new IndexedNode<>(newBitmap, newLeaves.size(), List.of(newLeaves)); } else { return new IndexedNode<>(newBitmap, size + other.size, subH1 < subH2 ? List.of(this, other) : List.of(other, this)); } } @Override boolean isLeaf() { return true; } @Override public int size() { return size; } @Override public Iterator<Tuple2<K, V>> iterator() { return entries.iterator(); } } /** * TODO: javadoc * * @param <K> Key type * @param <V> Value type */ class IndexedNode<K, V> extends AbstractNode<K, V> implements Serializable { private static final long serialVersionUID = 1L; private final int bitmap; private final int size; private final List<AbstractNode<K, V>> subNodes; private IndexedNode(int bitmap, int size, List<AbstractNode<K, V>> subNodes) { this.bitmap = bitmap; this.size = size; this.subNodes = subNodes; } @Override Option<V> lookup(int shift, K key) { int h = key.hashCode(); int frag = hashFragment(shift, h); int bit = toBitmap(frag); return ((bitmap & bit) != 0) ? subNodes.get(fromBitmap(bitmap, bit)).lookup(shift + SIZE, key) : None.instance(); } @Override AbstractNode<K, V> modify(int shift, K key, Option<V> value) { final int frag = hashFragment(shift, key.hashCode()); final int bit = toBitmap(frag); final int indx = fromBitmap(bitmap, bit); final int mask = bitmap; final boolean exists = (mask & bit) != 0; final AbstractNode<K, V> atIndx = exists ? subNodes.get(indx) : null; AbstractNode<K, V> child = exists ? atIndx.modify(shift + SIZE, key, value) : EmptyNode.<K, V> instance().modify(shift + SIZE, key, value); boolean removed = exists && child.isEmpty(); boolean added = !exists && !child.isEmpty(); int newBitmap = removed ? mask & ~bit : added ? mask | bit : mask; if (newBitmap == 0) { return EmptyNode.instance(); } else if (removed) { if (subNodes.length() <= 2 && subNodes.get(indx ^ 1).isLeaf()) { return subNodes.get(indx ^ 1); // collapse } else { return new IndexedNode<>(newBitmap, size - atIndx.size(), subNodes.removeAt(indx)); } } else if (added) { if (subNodes.length() >= MAX_INDEX_NODE) { return expand(frag, child, mask, subNodes); } else { return new IndexedNode<>(newBitmap, size + child.size(), subNodes.insert(indx, child)); } } else { if (!exists) { return this; } else { return new IndexedNode<>(newBitmap, size - atIndx.size() + child.size(), subNodes.update(indx, child)); } } } ArrayNode<K, V> expand(int frag, AbstractNode<K, V> child, int mask, List<AbstractNode<K, V>> subNodes) { int bit = mask; int count = 0; List<AbstractNode<K, V>> sub = subNodes; final Object[] arr = new Object[BUCKET_SIZE]; for (int i = 0; i < BUCKET_SIZE; i++) { if ((bit & 1) != 0) { arr[i] = sub.head(); sub = sub.tail(); count++; } else if (i == frag) { arr[i] = child; count++; } else { arr[i] = EmptyNode.instance(); } bit = bit >>> 1; } return new ArrayNode<>(count, size + child.size(), Array.wrap(arr)); } @Override boolean isLeaf() { return false; } @Override public int size() { return size; } @Override public Iterator<Tuple2<K, V>> iterator() { return Iterator.ofIterables(subNodes); } } /** * TODO: javadoc * * @param <K> Key type * @param <V> Value type */ class ArrayNode<K, V> extends AbstractNode<K, V> implements Serializable { private static final long serialVersionUID = 1L; private final Array<AbstractNode<K, V>> subNodes; private final int count; private final int size; private ArrayNode(int count, int size, Array<AbstractNode<K, V>> subNodes) { this.subNodes = subNodes; this.count = count; this.size = size; } @Override Option<V> lookup(int shift, K key) { int frag = hashFragment(shift, key.hashCode()); AbstractNode<K, V> child = subNodes.get(frag); return child.lookup(shift + SIZE, key); } @Override AbstractNode<K, V> modify(int shift, K key, Option<V> value) { int frag = hashFragment(shift, key.hashCode()); AbstractNode<K, V> child = subNodes.get(frag); AbstractNode<K, V> newChild = child.modify(shift + SIZE, key, value); if (child.isEmpty() && !newChild.isEmpty()) { return new ArrayNode<>(count + 1, size + newChild.size(), subNodes.update(frag, newChild)); } else if (!child.isEmpty() && newChild.isEmpty()) { if (count - 1 <= MIN_ARRAY_NODE) { return pack(frag, subNodes); } else { return new ArrayNode<>(count - 1, size - child.size(), subNodes.update(frag, EmptyNode.instance())); } } else { return new ArrayNode<>(count, size - child.size() + newChild.size(), subNodes.update(frag, newChild)); } } IndexedNode<K, V> pack(int idx, Array<AbstractNode<K, V>> elements) { List<AbstractNode<K, V>> arr = List.empty(); int bitmap = 0; int size = 0; for (int i = BUCKET_SIZE - 1; i >= 0; i AbstractNode<K, V> elem = elements.get(i); if (i != idx && elem != empty()) { size += elem.size(); arr = arr.prepend(elem); bitmap = bitmap | (1 << i); } } return new IndexedNode<>(bitmap, size, arr); } @Override boolean isLeaf() { return false; } @Override public int size() { return size; } @Override public Iterator<Tuple2<K, V>> iterator() { return Iterator.ofIterables(subNodes); } } }
// @@author A0130195M package jfdi.logic.commands; import jfdi.logic.events.FilesReplacedEvent; import jfdi.logic.events.MoveDirectoryDoneEvent; import jfdi.logic.events.MoveDirectoryFailedEvent; import jfdi.logic.interfaces.Command; import jfdi.storage.exceptions.FilesReplacedException; import jfdi.storage.exceptions.InvalidFilePathException; /** * @author Liu Xinan */ public class MoveDirectoryCommand extends Command { private String oldDirectory; private String newDirectory; private MoveDirectoryCommand(Builder builder) { this.newDirectory = builder.newDirectory; } public static class Builder { String newDirectory; public Builder setNewDirectory(String newDirectory) { this.newDirectory = newDirectory; return this; } public MoveDirectoryCommand build() { return new MoveDirectoryCommand(this); } } public String getOldDirectory() { return oldDirectory; } public String getNewDirectory() { return newDirectory; } @Override public void execute() { try { oldDirectory = mainStorage.getCurrentDirectory(); mainStorage.changeDirectory(newDirectory); pushToUndoStack(); eventBus.post(new MoveDirectoryDoneEvent(newDirectory)); } catch (FilesReplacedException e) { eventBus.post(new MoveDirectoryDoneEvent(newDirectory)); eventBus.post(new FilesReplacedEvent(newDirectory, e.getReplacedFilePairs())); } catch (InvalidFilePathException e) { eventBus.post(new MoveDirectoryFailedEvent(newDirectory, MoveDirectoryFailedEvent.Error.INVALID_PATH)); } } @Override public void undo() { try { mainStorage.changeDirectory(oldDirectory); pushToRedoStack(); } catch (InvalidFilePathException e) { assert false; } catch (FilesReplacedException e) { eventBus.post(new FilesReplacedEvent(oldDirectory, e.getReplacedFilePairs())); } } }
package me.moocar.logbackgelf.util; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; public class InternetUtils { private static final String REGEX_IP_ADDRESS = "\\d+(\\.\\d+){3}"; private InternetUtils() { } /** * Retrieves the local host's hostname. If found, the fully qualified domain name (FQDN) will be returned, * otherwise it will fallback to the unqualified domain name. E.g prefer guerrero.moocar.me over guerrero. */ public static String getLocalHostName() throws SocketException, UnknownHostException { try { final String canonicalHostName = InetAddress.getLocalHost().getCanonicalHostName(); if (isFQDN(canonicalHostName)) { return canonicalHostName; } else { return InetAddress.getLocalHost().getHostName(); } } catch (UnknownHostException e) { NetworkInterface networkInterface = NetworkInterface.getNetworkInterfaces().nextElement(); if (networkInterface == null) throw e; InetAddress ipAddress = networkInterface.getInetAddresses().nextElement(); if (ipAddress == null) throw e; return ipAddress.getHostAddress(); } } /** * Returns true is the hostname is a Fully Qualified Domain Name (FQDN) */ private static boolean isFQDN(String hostname) { return hostname.contains(".") && !hostname.matches(REGEX_IP_ADDRESS); } /** * Gets the Inet address for the graylog2ServerHost and gives a specialised error message if an exception is thrown * * @return The Inet address for graylog2ServerHost */ public static InetAddress getInetAddress(String hostName) { try { return InetAddress.getByName(hostName); } catch (UnknownHostException e) { throw new IllegalStateException("Unknown host: " + e.getMessage() + ". Make sure you have specified the 'graylog2ServerHost' property correctly in your logback.xml'"); } } }
package me.prettyprint.cassandra.service; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import me.prettyprint.cassandra.model.HectorException; import me.prettyprint.cassandra.model.HectorPoolException; import me.prettyprint.cassandra.service.CassandraClient.FailoverPolicy; import org.apache.cassandra.thrift.Cassandra; import org.apache.cassandra.thrift.TokenRange; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A cluster instance the client side representation of a cassandra server cluster. * * The cluster is usually the main entry point for programs using hector. To start operating on * cassandra cluster you first get or create a cluster, then a keyspace operator for the keyspace * you're interested in and then create mutations of queries * <code> * //get a cluster: * Cluster cluster = getOrCreateCluster("MyCluster", "127.0.0.1:9170"); * //get a keyspace from this cluster: * KeyspaceOperator ko = createKeyspaceOperator("Keyspace1", cluster); * //Create a mutator: * Mutator m = createMutator(ko); * // Make a mutation: * MutationResult mr = m.insert("key", cf, createColumn("name", "value", extractor, extractor)); * </code> * * THREAD SAFETY: This class is thread safe. * * @author Ran Tavory * @author zznate */ public final class Cluster { private final Logger log = LoggerFactory.getLogger(Cluster.class); private static final String KEYSPACE_SYSTEM = "system"; private final CassandraClientPool pool; private final String name; private final CassandraHostConfigurator configurator; private TimestampResolution timestampResolution = CassandraHost.DEFAULT_TIMESTAMP_RESOLUTION; private final FailoverPolicy failoverPolicy; private final CassandraClientMonitor cassandraClientMonitor; private Set<String> knownClusterHosts; private Set<CassandraHost> knownPoolHosts; private final ExceptionsTranslator xtrans; public Cluster(String clusterName, CassandraHostConfigurator cassandraHostConfigurator) { pool = CassandraClientPoolFactory.INSTANCE.createNew(cassandraHostConfigurator); name = clusterName; configurator = cassandraHostConfigurator; failoverPolicy = FailoverPolicy.ON_FAIL_TRY_ALL_AVAILABLE; cassandraClientMonitor = JmxMonitor.getInstance().getCassandraMonitor(); xtrans = new ExceptionsTranslatorImpl(); } public Cluster(String clusterName, CassandraClientPool pool) { this.pool = pool; name = clusterName; configurator = null; failoverPolicy = FailoverPolicy.ON_FAIL_TRY_ALL_AVAILABLE; cassandraClientMonitor = JmxMonitor.getInstance().getCassandraMonitor(); xtrans = new ExceptionsTranslatorImpl(); } public Set<CassandraHost> getKnownPoolHosts(boolean refresh) { if (refresh || knownPoolHosts == null) { knownPoolHosts = pool.getKnownHosts(); log.info("found knownPoolHosts: {}", knownPoolHosts); } return knownPoolHosts; } /** * These are all the hosts known to the cluster * @param refresh * @return */ public Set<String> getClusterHosts(boolean refresh) { if (refresh || knownClusterHosts == null) { CassandraClient client = borrowClient(); try { knownClusterHosts = new HashSet<String>(buildHostNames(client.getCassandra())); } finally { releaseClient(client); } } return knownClusterHosts; } /** * Adds the host to this Cluster. Unless skipApplyConfig is set to true, the settings in * the CassandraHostConfigurator will be applied to the provided CassandraHost * @param cassandraHost * @param skipApplyConfig */ public void addHost(CassandraHost cassandraHost, boolean skipApplyConfig) { if (!skipApplyConfig && configurator != null) { configurator.applyConfig(cassandraHost); } pool.addCassandraHost(cassandraHost); pool.updateKnownHosts(); } /** * Descriptive name of the cluster. * This name is used to identify the cluster. * @return */ public String getName() { return name; } // rest of the methods from the current CassandraCluster public CassandraClient borrowClient() throws HectorPoolException { return pool.borrowClient(); } public void releaseClient(CassandraClient client) { pool.releaseClient(client); } @Override public String toString() { return String.format("Cluster(%s,%s)", name, pool.toString()); } public TimestampResolution getTimestampResolution() { return timestampResolution; } public Cluster setTimestampResolution(TimestampResolution timestampResolution) { this.timestampResolution = timestampResolution; return this; } public long createTimestamp() { return timestampResolution.createTimestamp(); } public Set<String> describeKeyspaces() throws HectorException { Operation<Set<String>> op = new Operation<Set<String>>(OperationType.META_READ) { @Override public Set<String> execute(Cassandra.Client cassandra) throws HectorException { try { return cassandra.describe_keyspaces(); } catch (Exception e) { throw xtrans.translate(e); } } }; operateWithFailover(op); return op.getResult(); } public String describeClusterName() throws HectorException { Operation<String> op = new Operation<String>(OperationType.META_READ) { @Override public String execute(Cassandra.Client cassandra) throws HectorException { try { return cassandra.describe_cluster_name(); } catch (Exception e) { throw xtrans.translate(e); } } }; operateWithFailover(op); return op.getResult(); } public String describeThriftVersion() throws HectorException { Operation<String> op = new Operation<String>(OperationType.META_READ) { @Override public String execute(Cassandra.Client cassandra) throws HectorException { try { return cassandra.describe_version(); } catch (Exception e) { throw xtrans.translate(e); } } }; operateWithFailover(op); return op.getResult(); } public Map<String, Map<String, String>> describeKeyspace(final String keyspace) throws HectorException { Operation<Map<String, Map<String, String>>> op = new Operation<Map<String, Map<String, String>>>( OperationType.META_READ) { @Override public Map<String, Map<String, String>> execute(Cassandra.Client cassandra) throws HectorException { try { return cassandra.describe_keyspace(keyspace); } catch (org.apache.cassandra.thrift.NotFoundException nfe) { setException(xtrans.translate(nfe)); return null; } catch (Exception e) { throw xtrans.translate(e); } } }; operateWithFailover(op); return op.getResult(); } public String getClusterName() throws HectorException { log.info("in execute with client"); Operation<String> op = new Operation<String>(OperationType.META_READ) { @Override public String execute(Cassandra.Client cassandra) throws HectorException { try { log.info("in execute with client {}", cassandra); return cassandra.describe_cluster_name(); } catch (Exception e) { throw xtrans.translate(e); } } }; operateWithFailover(op); return op.getResult(); } public List<TokenRange> describeRing(final String keyspace) throws HectorException { Operation<List<TokenRange>> op = new Operation<List<TokenRange>>(OperationType.META_READ) { @Override public List<TokenRange> execute(Cassandra.Client cassandra) throws HectorException { try { return cassandra.describe_ring(keyspace); } catch (Exception e) { throw xtrans.translate(e); } } }; operateWithFailover(op); return op.getResult(); } private void operateWithFailover(Operation<?> op) throws HectorException { CassandraClient client = null; try { client = borrowClient(); FailoverOperator operator = new FailoverOperator(failoverPolicy, cassandraClientMonitor, client, pool, null); client = operator.operate(op); } finally { try { releaseClient(client); } catch (Exception e) { log.error("Unable to release a client", e); } } } private Set<String> buildHostNames(Cassandra.Client cassandra) throws HectorException { try { Set<String> hostnames = new HashSet<String>(); for (String keyspace : cassandra.describe_keyspaces()) { if (!keyspace.equals(KEYSPACE_SYSTEM)) { List<TokenRange> tokenRanges = cassandra.describe_ring(keyspace); for (TokenRange tokenRange : tokenRanges) { for (String host : tokenRange.getEndpoints()) { hostnames.add(host); } } break; } } return hostnames; } catch (Exception e) { throw xtrans.translate(e); } } }
package net.darkhax.bookshelf.lib.util; import java.util.*; import org.apache.commons.lang3.SystemUtils; import org.apache.commons.lang3.text.WordUtils; import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.enchantment.Enchantment; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntityHorse; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.potion.Potion; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.fluids.IFluidBlock; import cpw.mods.fml.common.network.simpleimpl.*; import cpw.mods.fml.common.registry.GameData; import cpw.mods.fml.common.registry.VillagerRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.darkhax.bookshelf.common.network.AbstractMessage; import net.darkhax.bookshelf.handler.BookshelfHooks; import net.darkhax.bookshelf.lib.Constants; import net.darkhax.bookshelf.lib.Tuple; public final class Utilities { /** * Array of names for the vanilla villagers. */ private static String[] vanillaVillagers = { "farmer", "librarian", "priest", "blacksmith", "butcher" }; /** * An array of all keys used in ChestGenHooks for the vanilla chests. */ public static String[] vanillaLootChests = new String[] { "dungeonChest", "bonusChest", "villageBlacksmith", "strongholdCrossing", "strongholdLibrary", "strongholdCorridor", "pyramidJungleDispenser", "pyramidJungleChest", "pyramidDesertyChest", "mineshaftCorridor" }; /** * An array of formatting codes used to create rainbow text. */ public static String[] rainbowChars = new String[] { "4", "6", "e", "a", "9", "5" }; /** * A List of all available enchantments. Needs to occasionally be updated using * updateAvailableEnchantments. */ private static List<Enchantment> availableEnchantments; /** * This method will take a string and break it down into multiple lines based on a provided * line length. The separate strings are then added to the list provided. This method is * useful for adding a long description to an item tool tip and having it wrap. This method * is similar to wrap in Apache WordUtils however it uses a List making it easier to use * when working with Minecraft. * * @param string: The string being split into multiple lines. It's recommended to use * StatCollector.translateToLocal() for this so multiple languages will be * supported. * @param lnLength: The ideal size for each line of text. * @param wrapLongWords: If true the ideal size will be exact, potentially splitting words * on the end of each line. * @param list: A list to add each line of text to. An good example of such list would be * the list of tooltips on an item. * @return List: The same List instance provided however the string provided will be * wrapped to the ideal line length and then added. */ public static List<String> wrapStringToList (String string, int lnLength, boolean wrapLongWords, List<String> list) { String lines[] = WordUtils.wrap(string, lnLength, null, wrapLongWords).split(SystemUtils.LINE_SEPARATOR); list.addAll(Arrays.asList(lines)); return list; } /** * This method will take a string and break it down into multiple lines based on a provided * line length. The separate strings are then added to the list provided. This method is * useful for adding a long description to an item tool tip and having it wrap. This method * is similar to wrap in Apache WordUtils however it uses a List making it easier to use * when working with Minecraft. * * @param string: The string being split into multiple lines. It's recommended to use * StatCollector.translateToLocal() for this so multiple languages will be * supported. * @param lnLength: The ideal size for each line of text. * @param wrapLongWords: If true the ideal size will be exact, potentially splitting words * on the end of each line. * @param format: A list to add each line of text to. An good example of such list would be * the list of tooltips on an item. * @param color: An EnumChatFormatting to apply to all lines added to the list. * @return List: The same List instance provided however the string provided will be * wrapped to the ideal line length and then added. */ public static List<String> wrapStringToListWithFormat (String string, int lnLength, boolean wrapLongWords, List<String> list, EnumChatFormatting format) { String lines[] = WordUtils.wrap(string, lnLength, null, wrapLongWords).split(SystemUtils.LINE_SEPARATOR); for (String line : lines) list.add(format + line); return list; } /** * Checks if a block is a fluid or not. * * @param block: An instance of the block being checked. * @return boolean: If the block is a fluid, true will be returned. If not, false will be * returned. */ public static boolean isFluid (Block block) { return (block == Blocks.lava || block == Blocks.water || block instanceof IFluidBlock); } /** * A blend between the itemRegistry.getObject and bockRegistry.getObject methods. Used for * grabbing something from an ID, when you have no clue what it might be. * * @param name: The ID of the thing you're looking for. Domains are often preferred. * @return Object: Hopefully the thing you're looking for. */ public static Object getThingByName (String name) { Object thing = Item.itemRegistry.getObject(name); if (thing != null) return thing; thing = Block.blockRegistry.getObject(name); if (thing != null) return thing; return null; } /** * A basic check to see if two classes are the same. For the classes to be the same, * neither can be null, and they must share the same name. * * @param class1: The first class to compare. * @param class2: The second class to compare. * @return boolean: True if neither class is null, and both share the same name. */ public static boolean compareClasses (Class class1, Class class2) { return (class1 != null && class2 != null && class1.getName().equalsIgnoreCase(class2.getName())); } /** * Compares the class of an Object with another class. Useful for comparing a TileEntity or * Item. * * @param obj: The Object to compare. * @param clazz: The class to compare the Object to. * @return boolean: True if the Object is of the same class as the one provided. */ public static boolean compareObjectToClass (Object obj, Class clazz) { return compareClasses(obj.getClass(), clazz); } /** * Makes the first character of a string upper case. Useful for taking raw text data and * turning it into part of a sentence or other display data. * * @param text: The text to convert. * @return String: The same string that was passed, however the first character has been * made upper case. */ public static String makeUpperCased (String text) { return Character.toString(text.charAt(0)).toUpperCase() + text.substring(1); } /** * Provides a safe way to get a class by its name. This is essentially the same as * Class.forName however it will handle any ClassNotFoundException automatically. * * @param name: The name of the class you are trying to get. Example: java.lang.String * @return Class: If a class could be found, it will be returned. Otherwise, null. */ public static Class getClassFromString (String name) { try { return Class.forName(name); } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } } /** * A check to see if an entity is wearing a full suit of the armor. This check is based on * the class names of armor. * * @param living: The living entity to check the armor of. * @param armorClass: The class of the armor to check against. * @return boolean: True if every piece of armor the entity is wearing are the same class * as the provied armor class. */ public static boolean isWearingFullSet (EntityLivingBase living, Class armorClass) { for (int armorSlot = 1; armorSlot <= 4; armorSlot++) { ItemStack armor = living.getEquipmentInSlot(armorSlot); if (armor == null || !armor.getItem().getClass().equals(armorClass)) return false; } return true; } /** * Retrieves the ItemStack placed in an EntityHorse's custom armor inventory slot. * * @param horse: An instance of the EntityHorse to grab the armor ItemStack from. * @return ItemStack: The ItemStack in the horses custom armor slot. This ItemStack maybe * null, and won't always be an instance of ItemHorseArmor. */ public static ItemStack getCustomHorseArmor (EntityHorse horse) { return horse.getDataWatcher().getWatchableObjectItemStack(23); } /** * Allows for a custom ItemStack to be set to an EntityHorse's custom armor inventory slot. * * @param horse: An instance of the EntityHorse to set the ItemStack to. * @param stack: An ItemStack you want to set to an EntityHorse's custom armor inventory * slot. */ public static void setCustomHorseArmor (EntityHorse horse, ItemStack stack) { horse.getDataWatcher().updateObject(23, stack); } /** * Retrieves the name of the mod that added the item to the game. * * @param item: The Item to get the mod name from. * @return String: The name of the mod which added the provided item to the game. */ public static String getModName (Item item) { String itemID = GameData.getItemRegistry().getNameForObject(item); return itemID.substring(0, itemID.indexOf(':')); } /** * Retrieves the name of the mod that added the block to the game. * * @param block: The Block to get the mod name from. * @return String: The name of the mod which added the provided block. */ public static String getModName (Block block) { String blockID = GameData.getBlockRegistry().getNameForObject(block); return blockID.substring(0, blockID.indexOf(':')); } /** * A safe way to grab an enchantment by its numeric ID. This is to help prevent crashes * when working with ids above the default maximum. * * @param id: The ID of the enchantment you wish to grab. * @return Enchantment: The enchantment that is assigned to the provided ID. Id the ID is * invalid, or the enchantment does not exist, you will get null. */ public static Enchantment getEnchantment (int id) { return (id >= 0 && id <= Enchantment.enchantmentsList.length) ? Enchantment.enchantmentsList[id] : null; } /** * A safe way to grab a Potion by its numeric ID. This is to help prevent crashes when * working with IDs above the default maximum. * * @param id: The ID of the Potion you wish to grab. * @return Potion: The Potion that was assigned the the passed ID. If it can't be found, is * null, or out of range, you will get null. */ public static Potion getPotion (int id) { return (id >= 0 && id <= Potion.potionTypes.length) ? Potion.potionTypes[id] : null; } /** * Updates the available enchantment array to contain all current enchantments. */ public static void updateAvailableEnchantments () { List<Enchantment> foundEnchantments = new ArrayList<Enchantment>(); for (Enchantment enchantment : Enchantment.enchantmentsList) if (enchantment != null) foundEnchantments.add(enchantment); availableEnchantments = foundEnchantments; } /** * Provides a list of all enchantments that are currently available. If the list has not * yet been initialized, this will do it automatically. * * @return List<Enchantment>: A list of all the enchantments that were found in the * enchantment list. */ public static List<Enchantment> getAvailableEnchantments () { if (availableEnchantments == null) updateAvailableEnchantments(); return availableEnchantments; } /** * Registers an AbstractMessage to your SimpleNetworkWrapper. * * @param network: The SimpleNetworkWrapper to register to. * @param clazz: The class of your AbstractMessage. * @param id: And ID for your AbstractMessage. * @param side: The side to send these messages towards. */ public static <T extends AbstractMessage<T> & IMessageHandler<T, IMessage>> void registerMessage (SimpleNetworkWrapper network, Class<T> clazz, int id, Side side) { network.registerMessage(clazz, clazz, id, side); } /** * Spawns a particle into the world, in a basic ring pattern. The center of the ring is * focused around the provided XYZ coordinates. * * @param world: The world to spawn the particles in. * @param name: The name of the particle to spawn. VanillaParticle has a list of these. * @param x: The x position to spawn the particle around. * @param y: The y position to spawn the particle around. * @param z: The z position to spawn the particle around. * @param velocityX: The velocity of the particle, in the x direction. * @param velocityY: The velocity of the particle, in the y direction. * @param velocityZ: The velocity of the particle, in the z direction. * @param step: The distance in degrees, between each particle. The maximum is 2 * PI, * which will create 1 particle per ring. 0.15 is a nice value. */ public static void spawnParticleRing (World world, String name, double x, double y, double z, double velocityX, double velocityY, double velocityZ, double step) { for (double degree = 0.0d; degree < 2 * Math.PI; degree += step) world.spawnParticle(name, x + Math.cos(degree), y, z + Math.sin(degree), velocityX, velocityY, velocityZ); } /** * Spawns a particle into the world, in a basic ring pattern. The center of the ring is * focused around the provided XYZ coordinates. * * @param world: The world to spawn the particles in. * @param name: The name of the particle to spawn. VanillaParticle has a list of these. * @param percent: The percentage of the ring to render. * @param x: The x position to spawn the particle around. * @param y: The y position to spawn the particle around. * @param z: The z position to spawn the particle around. * @param velocityX: The velocity of the particle, in the x direction. * @param velocityY: The velocity of the particle, in the y direction. * @param velocityZ: The velocity of the particle, in the z direction. * @param step: The distance in degrees, between each particle. The maximum is 2 * PI, * which will create 1 particle per ring. 0.15 is a nice value. */ public static void spawnParticleRing (World world, String name, float percentage, double x, double y, double z, double velocityX, double velocityY, double velocityZ, double step) { for (double degree = 0.0d; degree < (2 * Math.PI * percentage); degree += step) world.spawnParticle(name, x + Math.cos(degree), y, z + Math.sin(degree), velocityX, velocityY, velocityZ); } /** * Retrieves a unique string related to the texture name of a villager. This allows for * villagers to be differentiated based on their profession rather than their ID. * * @param id : The ID of the villager being looked up. * @return String: The texture name, minus file path and extension. */ @SideOnly(Side.CLIENT) public static String getVillagerName (int id) { ResourceLocation skin = VillagerRegistry.getVillagerSkin(id, null); return (id >= 0 && id <= 4) ? vanillaVillagers[id] : (skin != null) ? skin.getResourceDomain() + "." + skin.getResourcePath().substring(skin.getResourcePath().lastIndexOf("/") + 1, skin.getResourcePath().length() - 4) : "misingno"; } public static String generateRainbowTest (String text) { String output = ""; int offsetCount = 0; for (int index = 0; index < text.length(); index++) { if (text.charAt(index) == ' ') { output += " "; offsetCount++; } else output += "" + rainbowChars[index % rainbowChars.length - offsetCount] + text.charAt(index); } return output + "r"; } /** * Searches through the array of CreativeTabs and finds the first tab with the same label * as the one passed. * * @param label: The label of the tab you are looking for. * @return CreativeTabs: A CreativeTabs with the same label as the one passed. If this is * not found, you will get null. */ @SideOnly(Side.CLIENT) public static CreativeTabs getTabFromLabel (String label) { for (CreativeTabs tab : CreativeTabs.creativeTabArray) if (tab.getTabLabel().equalsIgnoreCase(label)) return tab; return null; } /** * Checks the list of duplicate potion IDs, and recommends suggestions to the user based on * what IDs are available. This will also crash the player, if the crash is not disabled in * the config. */ public static void checkDuplicatePotions () { if (!BookshelfHooks.conflictingPotions.isEmpty()) { Constants.LOG.error(BookshelfHooks.conflictingPotions.size() + " overlapping potions have been detected."); for (Tuple tuple : BookshelfHooks.conflictingPotions) { final String modName = (String) tuple.getFirstObject(); final Potion potion = (Potion) tuple.getSecondObject(); Constants.LOG.error("The " + potion.getName() + " effect from " + modName + " is using an overlapping ID. ID: " + potion.id); } int index = 1; List<Integer> unused = new ArrayList<Integer>(); for (int id = 32; id < Potion.potionTypes.length; id++) { if (index <= BookshelfHooks.conflictingPotions.size() + 5 && Utilities.getPotion(id) == null) { unused.add(id); index++; } } Constants.LOG.error((unused.isEmpty() || unused.size() < BookshelfHooks.conflictingPotions.size()) ? "You have ran out of available potion IDs. This is a serious problem." : "Here are a few recommended potion IDs which are not being used: " + unused.toString()); } } }
package net.imagej.patcher; import ij.ImagePlus; import ij.Macro; import ij.gui.DialogListener; import ij.plugin.filter.PlugInFilterRunner; import java.awt.Button; import java.awt.Checkbox; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.awt.Insets; import java.awt.Panel; import java.awt.TextArea; import java.awt.event.FocusEvent; import java.util.ArrayList; import java.util.List; import java.util.Vector; /** * Rump implementation of a pseudo dialog intended to stand in for the * {@link ij.gui.GenericDialog} in headless mode. This class is inserted as the * <i>superclass</i> to <code>GenericDialog</code>, cutting off its AWT * inheritance. Then the methods of this class are given precedence, effectively * reverse-overriding its subclass. * <p> * The guidelines for whether or not an {@link ij.gui.GenericDialog} method * should be overridden by this class or not are: * <ul> * <li>If the method is not public, it does not need to be overridden.</li> * <li>If the method is inherited from an AWT superclass it will automatically * be converted to a stub and does not need to be overridden.</li> * <li>If the method is explicitly stubified by {@link LegacyHeadless}, it does * not need to be overridden.</li> * <li>If the method is public but can still function as normal while headless, * it does not need to be overridden.</li> * <p> * All other public methods should be overridden. * </p> * </ul> * </p> * * @author Johannes Schindelin */ @SuppressWarnings("unused") public class HeadlessGenericDialog { protected List<Double> numbers; protected List<String> strings; protected List<Boolean> checkboxes; protected List<String> choices; protected List<Integer> choiceIndices; protected String textArea1, textArea2; protected List<String> radioButtons; protected int numberfieldIndex = 0, stringfieldIndex = 0, checkboxIndex = 0, choiceIndex = 0, textAreaIndex = 0, radioButtonIndex = 0; protected boolean invalidNumber; protected String errorMessage; protected DialogListener listener; public HeadlessGenericDialog() { if (Macro.getOptions() == null) throw new RuntimeException("Cannot instantiate headless dialog except in macro mode"); numbers = new ArrayList<Double>(); strings = new ArrayList<String>(); checkboxes = new ArrayList<Boolean>(); choices = new ArrayList<String>(); choiceIndices = new ArrayList<Integer>(); radioButtons = new ArrayList<String>(); } public void addCheckbox(String label, boolean defaultValue) { checkboxes.add(getMacroParameter(label, defaultValue)); } public void addCheckboxGroup(int rows, int columns, String[] labels, boolean[] defaultValues) { for (int i = 0; i < labels.length; i++) addCheckbox(labels[i], defaultValues[i]); } public void addCheckboxGroup(int rows, int columns, String[] labels, boolean[] defaultValues, String[] headings) { addCheckboxGroup(rows, columns, labels, defaultValues); } public void addChoice(String label, String[] items, String defaultItem) { String item = getMacroParameter(label, defaultItem); int index = 0; for (int i = 0; i < items.length; i++) if (items[i].equals(item)) { index = i; break; } choiceIndices.add(index); choices.add(items[index]); } public void addNumericField(String label, double defaultValue, int digits) { numbers.add(getMacroParameter(label, defaultValue)); } public void addNumericField(String label, double defaultValue, int digits, int columns, String units) { addNumericField(label, defaultValue, digits); } public void addSlider(String label, double minValue, double maxValue, double defaultValue) { numbers.add(getMacroParameter(label, defaultValue)); } public void addStringField(String label, String defaultText) { strings.add(getMacroParameter(label, defaultText)); } public void addStringField(String label, String defaultText, int columns) { addStringField(label, defaultText); } public void addTextAreas(String text1, String text2, int rows, int columns) { textArea1 = text1; textArea2 = text2; } public boolean getNextBoolean() { return checkboxes.get(checkboxIndex++); } public String getNextChoice() { return choices.get(choiceIndex++); } public int getNextChoiceIndex() { return choiceIndices.get(choiceIndex++); } public double getNextNumber() { return numbers.get(numberfieldIndex++); } /** Returns the contents of the next text field. */ public String getNextString() { return strings.get(stringfieldIndex++); } public String getNextText() { switch (textAreaIndex++) { case 0: return textArea1; case 1: return textArea2; } return null; } /** Adds a radio button group. */ public void addRadioButtonGroup(String label, String[] items, int rows, int columns, String defaultItem) { radioButtons.add(getMacroParameter(label, defaultItem)); } public Vector<String> getRadioButtonGroups() { return new Vector<String>(radioButtons); } /** Returns the selected item in the next radio button group. */ public String getNextRadioButton() { return radioButtons.get(radioButtonIndex++); } public boolean invalidNumber() { boolean wasInvalid = invalidNumber; invalidNumber = false; return wasInvalid; } public void showDialog() { if (Macro.getOptions() == null) throw new RuntimeException("Cannot run dialog headlessly"); resetCounters(); // NB: ImageJ 1.x has logic to call the first DialogListener at least once, // in case the plugin _only_ updates its values via the dialogItemChanged // method. See the bottom of the ij.gui.GenericDialog#showDialog() method. if (listener != null) { // NB: Thanks to Javassist, this class _will_ be a GenericDialog object. listener.dialogItemChanged((ij.gui.GenericDialog) (Object) this, null); resetCounters(); } } /** * Resets the counters before reading the dialog parameters. */ private void resetCounters() { numberfieldIndex = 0; stringfieldIndex = 0; checkboxIndex = 0; choiceIndex = 0; textAreaIndex = 0; } public boolean wasCanceled() { return false; } public boolean wasOKed() { return true; } public void dispose() {} public void addDialogListener(DialogListener dl) { if (listener != null) return; // NB: Save the first DialogListener, for access during showDialog(). listener = dl; } public void addHelp(String url) {} public void addImage(ImagePlus image) {} public void addMessage(String text) {} public void addMessage(String text, Font font) {} public void addMessage(String text, Font font, Color color) {} public void addPanel(Panel panel) {} public void addPanel(Panel panel, int contraints, Insets insets) {} public void addPreviewCheckbox(PlugInFilterRunner pfr) {} public void addPreviewCheckbox(PlugInFilterRunner pfr, String label) {} public void centerDialog(boolean b) {} public void setSmartRecording(boolean smartRecording) {} public void enableYesNoCancel() {} public void enableYesNoCancel(String yesLabel, String noLabel) {} public void focusGained(FocusEvent e) {} public void focusLost(FocusEvent e) {} public Button[] getButtons() { return null; } public Vector<?> getCheckboxes() { return null; } public Vector<?> getChoices() { return null; } public String getErrorMessage() { return errorMessage; } public Insets getInsets() { return null; } public Component getMessage() { return null; } public Vector<?> getNumericFields() { return null; } public Checkbox getPreviewCheckbox() { return null; } public Vector<?> getSliders() { return null; } public Vector<?> getStringFields() { return null; } public TextArea getTextArea1() { return null; } public TextArea getTextArea2() { return null; } public void hideCancelButton() {} public void previewRunning(boolean isRunning) {} public void setEchoChar(char echoChar) {} public void setHelpLabel(String label) {} public void setInsets(int top, int left, int bottom) {} public void setOKLabel(String label) {} protected void setup() {} public void accessTextFields() {} public void showHelp() {} public void setLocation(int x, int y) {} public boolean isPreviewActive() { return false; } /** * Gets a macro parameter of type <i>boolean</i>. * * @param label * the name of the macro parameter * @param defaultValue * the default value * @return the boolean value */ private static boolean getMacroParameter(String label, boolean defaultValue) { return findBooleanMacroParameter(label); } /** * Looks whether a boolean was specified in the macro parameters. * * @param label * the label to look for * @return whether the label was found */ private static boolean findBooleanMacroParameter(final String labelString) { final String optionsString = Macro.getOptions(); if (optionsString == null) { return false; } final char[] options = optionsString.toCharArray(); final char[] label = Macro.trimKey(labelString).toCharArray(); for (int i = 0; i < options.length; i++) { boolean match = true; // match at start or after space for (char c : label) { if (c != options[i]) { match = false; break; } i++; } if (match && (i >= options.length || options[i] == ' ')) { return true; } // look for next space while (i < options.length && options[i] != ' ') { // skip literal if (options[i] == '[') { while (i < options.length && options[i] != ']') { i++; } } i++; } } return false; } /** * Gets a macro parameter of type <i>double</i>. * * @param label * the name of the macro parameter * @param defaultValue * the default value * @return the double value */ private static double getMacroParameter(String label, double defaultValue) { String value = Macro.getValue(Macro.getOptions(), label, null); return value != null ? Double.parseDouble(value) : defaultValue; } /** * Gets a macro parameter of type {@link String}. * * @param label * the name of the macro parameter * @param defaultValue * the default value * @return the value */ private static String getMacroParameter(String label, String defaultValue) { return Macro.getValue(Macro.getOptions(), label, defaultValue); } }
package net.minecraftforge.oredict; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import net.minecraft.block.BlockPrismarine; import net.minecraft.util.ResourceLocation; import org.apache.logging.log4j.Level; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.IRecipe; import net.minecraft.item.crafting.ShapedRecipes; import net.minecraft.item.crafting.ShapelessRecipes; import net.minecraftforge.common.MinecraftForge; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.eventhandler.Event; import net.minecraftforge.fml.common.registry.GameData; public class OreDictionary { private static boolean hasInit = false; private static List<String> idToName = new ArrayList<String>(); private static Map<String, Integer> nameToId = new HashMap<String, Integer>(128); private static List<List<ItemStack>> idToStack = Lists.newArrayList(); private static List<List<ItemStack>> idToStackUn = Lists.newArrayList(); private static Map<Integer, List<Integer>> stackToId = Maps.newHashMapWithExpectedSize((int)(128 * 0.75)); public static final ImmutableList<ItemStack> EMPTY_LIST = ImmutableList.of(); /** * Minecraft changed from -1 to Short.MAX_VALUE in 1.5 release for the "block wildcard". Use this in case it * changes again. */ public static final int WILDCARD_VALUE = Short.MAX_VALUE; static { initVanillaEntries(); } public static void initVanillaEntries() { if (!hasInit) { // tree- and wood-related things registerOre("logWood", new ItemStack(Blocks.log, 1, WILDCARD_VALUE)); registerOre("logWood", new ItemStack(Blocks.log2, 1, WILDCARD_VALUE)); registerOre("plankWood", new ItemStack(Blocks.planks, 1, WILDCARD_VALUE)); registerOre("slabWood", new ItemStack(Blocks.wooden_slab, 1, WILDCARD_VALUE)); registerOre("stairWood", Blocks.oak_stairs); registerOre("stairWood", Blocks.spruce_stairs); registerOre("stairWood", Blocks.birch_stairs); registerOre("stairWood", Blocks.jungle_stairs); registerOre("stairWood", Blocks.acacia_stairs); registerOre("stairWood", Blocks.dark_oak_stairs); registerOre("stickWood", Items.stick); registerOre("treeSapling", new ItemStack(Blocks.sapling, 1, WILDCARD_VALUE)); registerOre("treeLeaves", new ItemStack(Blocks.leaves, 1, WILDCARD_VALUE)); registerOre("treeLeaves", new ItemStack(Blocks.leaves2, 1, WILDCARD_VALUE)); registerOre("vine", Blocks.vine); // Ores registerOre("oreGold", Blocks.gold_ore); registerOre("oreIron", Blocks.iron_ore); registerOre("oreLapis", Blocks.lapis_ore); registerOre("oreDiamond", Blocks.diamond_ore); registerOre("oreRedstone", Blocks.redstone_ore); registerOre("oreEmerald", Blocks.emerald_ore); registerOre("oreQuartz", Blocks.quartz_ore); registerOre("oreCoal", Blocks.coal_ore); // ingots/nuggets registerOre("ingotIron", Items.iron_ingot); registerOre("ingotGold", Items.gold_ingot); registerOre("ingotBrick", Items.brick); registerOre("ingotBrickNether", Items.netherbrick); registerOre("nuggetGold", Items.gold_nugget); // gems and dusts registerOre("gemDiamond", Items.diamond); registerOre("gemEmerald", Items.emerald); registerOre("gemQuartz", Items.quartz); registerOre("gemPrismarine", Items.prismarine_shard); registerOre("dustPrismarine", Items.prismarine_crystals); registerOre("dustRedstone", Items.redstone); registerOre("dustGlowstone", Items.glowstone_dust); registerOre("gemLapis", new ItemStack(Items.dye, 1, 4)); // storage blocks registerOre("blockGold", Blocks.gold_block); registerOre("blockIron", Blocks.iron_block); registerOre("blockLapis", Blocks.lapis_block); registerOre("blockDiamond", Blocks.diamond_block); registerOre("blockRedstone", Blocks.redstone_block); registerOre("blockEmerald", Blocks.emerald_block); registerOre("blockQuartz", Blocks.quartz_block); registerOre("blockCoal", Blocks.coal_block); // crops registerOre("cropWheat", Items.wheat); registerOre("cropPotato", Items.potato); registerOre("cropCarrot", Items.carrot); registerOre("cropNetherWart", Items.nether_wart); registerOre("sugarcane", Items.reeds); registerOre("blockCactus", Blocks.cactus); // misc materials registerOre("dye", new ItemStack(Items.dye, 1, WILDCARD_VALUE)); registerOre("paper", new ItemStack(Items.paper)); // mob drops registerOre("slimeball", Items.slime_ball); registerOre("enderpearl", Items.ender_pearl); registerOre("bone", Items.bone); registerOre("gunpowder", Items.gunpowder); registerOre("string", Items.string); registerOre("netherStar", Items.nether_star); registerOre("leather", Items.leather); registerOre("feather", Items.feather); registerOre("egg", Items.egg); // records registerOre("record", Items.record_13); registerOre("record", Items.record_cat); registerOre("record", Items.record_blocks); registerOre("record", Items.record_chirp); registerOre("record", Items.record_far); registerOre("record", Items.record_mall); registerOre("record", Items.record_mellohi); registerOre("record", Items.record_stal); registerOre("record", Items.record_strad); registerOre("record", Items.record_ward); registerOre("record", Items.record_11); registerOre("record", Items.record_wait); // blocks registerOre("dirt", Blocks.dirt); registerOre("grass", Blocks.grass); registerOre("stone", Blocks.stone); registerOre("cobblestone", Blocks.cobblestone); registerOre("gravel", Blocks.gravel); registerOre("sand", new ItemStack(Blocks.sand, 1, WILDCARD_VALUE)); registerOre("sandstone", new ItemStack(Blocks.sandstone, 1, WILDCARD_VALUE)); registerOre("sandstone", new ItemStack(Blocks.red_sandstone, 1, WILDCARD_VALUE)); registerOre("netherrack", Blocks.netherrack); registerOre("obsidian", Blocks.obsidian); registerOre("glowstone", Blocks.glowstone); registerOre("endstone", Blocks.end_stone); registerOre("torch", Blocks.torch); registerOre("workbench", Blocks.crafting_table); registerOre("blockSlime", Blocks.slime_block); registerOre("blockPrismarine", new ItemStack(Blocks.prismarine, 1, BlockPrismarine.EnumType.ROUGH.getMetadata())); registerOre("blockPrismarineBrick", new ItemStack(Blocks.prismarine, 1, BlockPrismarine.EnumType.BRICKS.getMetadata())); registerOre("blockPrismarineDark", new ItemStack(Blocks.prismarine, 1, BlockPrismarine.EnumType.DARK.getMetadata())); registerOre("stoneGranite", new ItemStack(Blocks.stone, 1, 1)); registerOre("stoneGranitePolished", new ItemStack(Blocks.stone, 1, 2)); registerOre("stoneDiorite", new ItemStack(Blocks.stone, 1, 3)); registerOre("stoneDioritePolished", new ItemStack(Blocks.stone, 1, 4)); registerOre("stoneAndesite", new ItemStack(Blocks.stone, 1, 5)); registerOre("stoneAndesitePolished", new ItemStack(Blocks.stone, 1, 6)); registerOre("blockGlassColorless", Blocks.glass); registerOre("blockGlass", Blocks.glass); registerOre("blockGlass", new ItemStack(Blocks.stained_glass, 1, WILDCARD_VALUE)); //blockGlass{Color} is added below with dyes registerOre("paneGlassColorless", Blocks.glass_pane); registerOre("paneGlass", Blocks.glass_pane); registerOre("paneGlass", new ItemStack(Blocks.stained_glass_pane, 1, WILDCARD_VALUE)); //paneGlass{Color} is added below with dyes // chests registerOre("chest", Blocks.chest); registerOre("chest", Blocks.ender_chest); registerOre("chest", Blocks.trapped_chest); registerOre("chestWood", Blocks.chest); registerOre("chestEnder", Blocks.ender_chest); registerOre("chestTrapped", Blocks.trapped_chest); } // Build our list of items to replace with ore tags Map<ItemStack, String> replacements = new HashMap<ItemStack, String>(); // wood-related things replacements.put(new ItemStack(Items.stick), "stickWood"); replacements.put(new ItemStack(Blocks.planks), "plankWood"); replacements.put(new ItemStack(Blocks.planks, 1, WILDCARD_VALUE), "plankWood"); replacements.put(new ItemStack(Blocks.wooden_slab, 1, WILDCARD_VALUE), "slabWood"); // ingots/nuggets replacements.put(new ItemStack(Items.gold_ingot), "ingotGold"); replacements.put(new ItemStack(Items.iron_ingot), "ingotIron"); // gems and dusts replacements.put(new ItemStack(Items.diamond), "gemDiamond"); replacements.put(new ItemStack(Items.emerald), "gemEmerald"); replacements.put(new ItemStack(Items.prismarine_shard), "gemPrismarine"); replacements.put(new ItemStack(Items.prismarine_crystals), "dustPrismarine"); replacements.put(new ItemStack(Items.redstone), "dustRedstone"); replacements.put(new ItemStack(Items.glowstone_dust), "dustGlowstone"); // crops replacements.put(new ItemStack(Items.reeds), "sugarcane"); replacements.put(new ItemStack(Blocks.cactus), "blockCactus"); // misc materials replacements.put(new ItemStack(Items.paper), "paper"); // mob drops replacements.put(new ItemStack(Items.slime_ball), "slimeball"); replacements.put(new ItemStack(Items.string), "string"); replacements.put(new ItemStack(Items.leather), "leather"); replacements.put(new ItemStack(Items.ender_pearl), "enderpearl"); replacements.put(new ItemStack(Items.gunpowder), "gunpowder"); replacements.put(new ItemStack(Items.nether_star), "netherStar"); replacements.put(new ItemStack(Items.feather), "feather"); replacements.put(new ItemStack(Items.bone), "bone"); replacements.put(new ItemStack(Items.egg), "egg"); // blocks replacements.put(new ItemStack(Blocks.stone), "stone"); replacements.put(new ItemStack(Blocks.cobblestone), "cobblestone"); replacements.put(new ItemStack(Blocks.cobblestone, 1, WILDCARD_VALUE), "cobblestone"); replacements.put(new ItemStack(Blocks.glowstone), "glowstone"); replacements.put(new ItemStack(Blocks.glass), "blockGlassColorless"); replacements.put(new ItemStack(Blocks.prismarine), "prismarine"); replacements.put(new ItemStack(Blocks.stone, 1, 1), "stoneGranite"); replacements.put(new ItemStack(Blocks.stone, 1, 2), "stoneGranitePolished"); replacements.put(new ItemStack(Blocks.stone, 1, 3), "stoneDiorite"); replacements.put(new ItemStack(Blocks.stone, 1, 4), "stoneDioritePolished"); replacements.put(new ItemStack(Blocks.stone, 1, 5), "stoneAndesite"); replacements.put(new ItemStack(Blocks.stone, 1, 6), "stoneAndesitePolished"); // chests replacements.put(new ItemStack(Blocks.chest), "chestWood"); replacements.put(new ItemStack(Blocks.ender_chest), "chestEnder"); replacements.put(new ItemStack(Blocks.trapped_chest), "chestTrapped"); // Register dyes String[] dyes = { "Black", "Red", "Green", "Brown", "Blue", "Purple", "Cyan", "LightGray", "Gray", "Pink", "Lime", "Yellow", "LightBlue", "Magenta", "Orange", "White" }; for(int i = 0; i < 16; i++) { ItemStack dye = new ItemStack(Items.dye, 1, i); ItemStack block = new ItemStack(Blocks.stained_glass, 1, 15 - i); ItemStack pane = new ItemStack(Blocks.stained_glass_pane, 1, 15 - i); if (!hasInit) { registerOre("dye" + dyes[i], dye); registerOre("blockGlass" + dyes[i], block); registerOre("paneGlass" + dyes[i], pane); } replacements.put(dye, "dye" + dyes[i]); replacements.put(block, "blockGlass" + dyes[i]); replacements.put(pane, "paneGlass" + dyes[i]); } hasInit = true; ItemStack[] replaceStacks = replacements.keySet().toArray(new ItemStack[replacements.keySet().size()]); // Ignore recipes for the following items ItemStack[] exclusions = new ItemStack[] { new ItemStack(Blocks.lapis_block), new ItemStack(Items.cookie), new ItemStack(Blocks.stonebrick), new ItemStack(Blocks.stone_slab, 1, WILDCARD_VALUE), new ItemStack(Blocks.stone_stairs), new ItemStack(Blocks.cobblestone_wall), new ItemStack(Blocks.oak_fence), new ItemStack(Blocks.oak_fence_gate), new ItemStack(Blocks.oak_stairs), new ItemStack(Blocks.spruce_fence), new ItemStack(Blocks.spruce_fence_gate), new ItemStack(Blocks.spruce_stairs), new ItemStack(Blocks.birch_fence), new ItemStack(Blocks.birch_fence_gate), new ItemStack(Blocks.birch_stairs), new ItemStack(Blocks.jungle_fence), new ItemStack(Blocks.jungle_fence_gate), new ItemStack(Blocks.jungle_stairs), new ItemStack(Blocks.acacia_fence), new ItemStack(Blocks.acacia_fence_gate), new ItemStack(Blocks.acacia_stairs), new ItemStack(Blocks.dark_oak_fence), new ItemStack(Blocks.dark_oak_fence_gate), new ItemStack(Blocks.dark_oak_stairs), new ItemStack(Blocks.wooden_slab), new ItemStack(Blocks.glass_pane), null //So the above can have a comma and we don't have to keep editing extra lines. }; List<IRecipe> recipes = CraftingManager.getInstance().getRecipeList(); List<IRecipe> recipesToRemove = new ArrayList<IRecipe>(); List<IRecipe> recipesToAdd = new ArrayList<IRecipe>(); // Search vanilla recipes for recipes to replace for(Object obj : recipes) { if(obj instanceof ShapedRecipes) { ShapedRecipes recipe = (ShapedRecipes)obj; ItemStack output = recipe.getRecipeOutput(); if (output != null && containsMatch(false, exclusions, output)) { continue; } if(containsMatch(true, recipe.recipeItems, replaceStacks)) { recipesToRemove.add(recipe); recipesToAdd.add(new ShapedOreRecipe(recipe, replacements)); } } else if(obj instanceof ShapelessRecipes) { ShapelessRecipes recipe = (ShapelessRecipes)obj; ItemStack output = recipe.getRecipeOutput(); if (output != null && containsMatch(false, exclusions, output)) { continue; } if(containsMatch(true, (ItemStack[])recipe.recipeItems.toArray(new ItemStack[recipe.recipeItems.size()]), replaceStacks)) { recipesToRemove.add((IRecipe)obj); IRecipe newRecipe = new ShapelessOreRecipe(recipe, replacements); recipesToAdd.add(newRecipe); } } } recipes.removeAll(recipesToRemove); recipes.addAll(recipesToAdd); if (recipesToRemove.size() > 0) { FMLLog.info("Replaced %d ore recipies", recipesToRemove.size()); } } /** * Gets the integer ID for the specified ore name. * If the name does not have a ID it assigns it a new one. * * @param name The unique name for this ore 'oreIron', 'ingotIron', etc.. * @return A number representing the ID for this ore type */ public static int getOreID(String name) { Integer val = nameToId.get(name); if (val == null) { idToName.add(name); val = idToName.size() - 1; //0 indexed nameToId.put(name, val); List<ItemStack> back = Lists.newArrayList(); idToStack.add(back); idToStackUn.add(Collections.unmodifiableList(back)); } return val; } /** * Reverse of getOreID, will not create new entries. * * @param id The ID to translate to a string * @return The String name, or "Unknown" if not found. */ public static String getOreName(int id) { return (id >= 0 && id < idToName.size()) ? idToName.get(id) : "Unknown"; } /** * Gets all the integer ID for the ores that the specified item stakc is registered to. * If the item stack is not linked to any ore, this will return an empty array and no new entry will be created. * * @param stack The item stack of the ore. * @return An array of ids that this ore is registerd as. */ public static int[] getOreIDs(ItemStack stack) { if (stack == null || stack.getItem() == null) throw new IllegalArgumentException("Stack can not be null!"); Set<Integer> set = new HashSet<Integer>(); // HACK: use the registry name's ID. It is unique and it knows about substitutions. Fallback to a -1 value (what Item.getIDForItem would have returned) in the case where the registry is not aware of the item yet // IT should be noted that -1 will fail the gate further down, if an entry already exists with value -1 for this name. This is what is broken and being warned about. // APPARENTLY it's quite common to do this. OreDictionary should be considered alongside Recipes - you can't make them properly until you've registered with the game. ResourceLocation registryName = stack.getItem().delegate.getResourceName(); int id; if (registryName == null) { FMLLog.log(Level.DEBUG, "Attempted to find the oreIDs for an unregistered object (%s). This won't work very well.", stack); return new int[0]; } else { id = GameData.getItemRegistry().getId(registryName); } List<Integer> ids = stackToId.get(id); if (ids != null) set.addAll(ids); ids = stackToId.get(id | ((stack.getItemDamage() + 1) << 16)); if (ids != null) set.addAll(ids); Integer[] tmp = set.toArray(new Integer[set.size()]); int[] ret = new int[tmp.length]; for (int x = 0; x < tmp.length; x++) ret[x] = tmp[x]; return ret; } /** * Retrieves the ArrayList of items that are registered to this ore type. * Creates the list as empty if it did not exist. * * The returned List is unmodifiable, but will be updated if a new ore * is registered using registerOre * * @param name The ore name, directly calls getOreID * @return An arrayList containing ItemStacks registered for this ore */ public static List<ItemStack> getOres(String name) { return getOres(getOreID(name)); } /** * Retrieves the List of items that are registered to this ore type at this instant. * If the flag is TRUE, then it will create the list as empty if it did not exist. * * This option should be used by modders who are doing blanket scans in postInit. * It greatly reduces clutter in the OreDictionary is the responsible and proper * way to use the dictionary in a large number of cases. * * The other function above is utilized in OreRecipe and is required for the * operation of that code. * * @param name The ore name, directly calls getOreID if the flag is TRUE * @param alwaysCreateEntry Flag - should a new entry be created if empty * @return An arraylist containing ItemStacks registered for this ore */ public static List<ItemStack> getOres(String name, boolean alwaysCreateEntry) { if (alwaysCreateEntry) { return getOres(getOreID(name)); } return nameToId.get(name) != null ? getOres(getOreID(name)) : EMPTY_LIST; } /** * Returns whether or not an oreName exists in the dictionary. * This function can be used to safely query the Ore Dictionary without * adding needless clutter to the underlying map structure. * * Please use this when possible and appropriate. * * @param name The ore name * @return Whether or not that name is in the Ore Dictionary. */ public static boolean doesOreNameExist(String name) { return nameToId.get(name) != null; } /** * Retrieves a list of all unique ore names that are already registered. * * @return All unique ore names that are currently registered. */ public static String[] getOreNames() { return idToName.toArray(new String[idToName.size()]); } /** * Retrieves the List of items that are registered to this ore type. * Creates the list as empty if it did not exist. * * @param id The ore ID, see getOreID * @return An List containing ItemStacks registered for this ore */ private static List<ItemStack> getOres(int id) { return idToStackUn.size() > id ? idToStackUn.get(id) : EMPTY_LIST; } private static boolean containsMatch(boolean strict, ItemStack[] inputs, ItemStack... targets) { for (ItemStack input : inputs) { for (ItemStack target : targets) { if (itemMatches(target, input, strict)) { return true; } } } return false; } public static boolean containsMatch(boolean strict, List<ItemStack> inputs, ItemStack... targets) { for (ItemStack input : inputs) { for (ItemStack target : targets) { if (itemMatches(target, input, strict)) { return true; } } } return false; } public static boolean itemMatches(ItemStack target, ItemStack input, boolean strict) { if (input == null && target != null || input != null && target == null) { return false; } return (target.getItem() == input.getItem() && ((target.getItemDamage() == WILDCARD_VALUE && !strict) || target.getItemDamage() == input.getItemDamage())); } //Convenience functions that make for cleaner code mod side. They all drill down to registerOre(String, int, ItemStack) public static void registerOre(String name, Item ore){ registerOre(name, new ItemStack(ore)); } public static void registerOre(String name, Block ore){ registerOre(name, new ItemStack(ore)); } public static void registerOre(String name, ItemStack ore){ registerOreImpl(name, ore); } /** * Registers a ore item into the dictionary. * Raises the registerOre function in all registered handlers. * * @param name The name of the ore * @param ore The ore's ItemStack */ private static void registerOreImpl(String name, ItemStack ore) { if ("Unknown".equals(name)) return; //prevent bad IDs. if (ore == null || ore.getItem() == null) { FMLLog.bigWarning("Invalid registration attempt for an Ore Dictionary item with name %s has occurred. The registration has been denied to prevent crashes. The mod responsible for the registration needs to correct this.", name); return; //prevent bad ItemStacks. } int oreID = getOreID(name); // HACK: use the registry name's ID. It is unique and it knows about substitutions. Fallback to a -1 value (what Item.getIDForItem would have returned) in the case where the registry is not aware of the item yet // IT should be noted that -1 will fail the gate further down, if an entry already exists with value -1 for this name. This is what is broken and being warned about. // APPARENTLY it's quite common to do this. OreDictionary should be considered alongside Recipes - you can't make them properly until you've registered with the game. ResourceLocation registryName = ore.getItem().delegate.getResourceName(); int hash; if (registryName == null) { FMLLog.bigWarning("A broken ore dictionary registration with name %s has occurred. It adds an item (type: %s) which is currently unknown to the game registry. This dictionary item can only support a single value when" + " registered with ores like this, and NO I am not going to turn this spam off. Just register your ore dictionary entries after the GameRegistry.\n" + "TO USERS: YES this is a BUG in the mod "+Loader.instance().activeModContainer().getName()+" report it to them!", name, ore.getItem().getClass()); hash = -1; } else { hash = GameData.getItemRegistry().getId(registryName); } if (ore.getItemDamage() != WILDCARD_VALUE) { hash |= ((ore.getItemDamage() + 1) << 16); // +1 so 0 is significant } //Add things to the baked version, and prevent duplicates List<Integer> ids = stackToId.get(hash); if (ids != null && ids.contains(oreID)) return; if (ids == null) { ids = Lists.newArrayList(); stackToId.put(hash, ids); } ids.add(oreID); //Add to the unbaked version ore = ore.copy(); idToStack.get(oreID).add(ore); MinecraftForge.EVENT_BUS.post(new OreRegisterEvent(name, ore)); } public static class OreRegisterEvent extends Event { public final String Name; public final ItemStack Ore; public OreRegisterEvent(String name, ItemStack ore) { this.Name = name; this.Ore = ore; } } public static void rebakeMap() { //System.out.println("Baking OreDictionary:"); stackToId.clear(); for (int id = 0; id < idToStack.size(); id++) { List<ItemStack> ores = idToStack.get(id); if (ores == null) continue; for (ItemStack ore : ores) { // HACK: use the registry name's ID. It is unique and it knows about substitutions ResourceLocation name = ore.getItem().delegate.getResourceName(); int hash; if (name == null) { FMLLog.log(Level.DEBUG, "Defaulting unregistered ore dictionary entry for ore dictionary %s: type %s to -1", getOreName(id), ore.getItem().getClass()); hash = -1; } else { hash = GameData.getItemRegistry().getId(name); } if (ore.getItemDamage() != WILDCARD_VALUE) { hash |= ((ore.getItemDamage() + 1) << 16); // +1 so meta 0 is significant } List<Integer> ids = stackToId.get(hash); if (ids == null) { ids = Lists.newArrayList(); stackToId.put(hash, ids); } ids.add(id); //System.out.println(id + " " + getOreName(id) + " " + Integer.toHexString(hash) + " " + ore); } } } }
package net.mingsoft.cms.biz.impl; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.bean.copier.CopyOptions; import cn.hutool.core.date.DateUtil; import cn.hutool.core.io.FileUtil; import net.mingsoft.basic.constant.Const; import net.mingsoft.basic.holder.DataHolder; import net.mingsoft.basic.util.BasicUtil; import net.mingsoft.cms.bean.CategoryBean; import net.mingsoft.cms.bean.ContentBean; import net.mingsoft.cms.dao.ICategoryDao; import net.mingsoft.cms.entity.CategoryEntity; import net.mingsoft.cms.entity.ContentEntity; import net.mingsoft.cms.util.CmsParserUtil; import net.mingsoft.mdiy.bean.AttributeBean; import net.mingsoft.mdiy.bean.PageBean; import net.mingsoft.mdiy.entity.ModelEntity; import net.mingsoft.mdiy.util.ParserUtil; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import net.mingsoft.base.biz.impl.BaseBizImpl; import net.mingsoft.base.dao.IBaseDao; import java.io.IOException; import java.util.*; import net.mingsoft.cms.biz.IContentBiz; import net.mingsoft.cms.dao.IContentDao; /** * * @author * 2019-11-28 15:12:32<br/> * <br/> */ @Service("cmscontentBizImpl") public class ContentBizImpl extends BaseBizImpl<IContentDao, ContentEntity> implements IContentBiz { /* * log4j */ protected final Logger LOG = LoggerFactory.getLogger(this.getClass()); @Autowired private IContentDao contentDao; @Autowired private ICategoryDao categoryDao; @Override protected IBaseDao getDao() { // TODO Auto-generated method stub return contentDao; } @Override public List<CategoryBean> queryIdsByCategoryIdForParser(ContentBean contentBean) { contentBean.setAppId(BasicUtil.getAppId()); return this.contentDao.queryIdsByCategoryIdForParser(contentBean); } @Override public int getSearchCount(ModelEntity contentModel, List diyList, Map whereMap, int appId, String categoryIds) { if (contentModel!=null) { return contentDao.getSearchCount(contentModel.getModelTableName(),diyList,whereMap, appId,categoryIds); } return contentDao.getSearchCount(null,null,whereMap, appId,categoryIds); } public void staticizeTask(Integer appId, String tmpFileName, String generateFileName) { LOG.info("", new Date()); try { //appId //appId DataHolder.set(net.mingsoft.basic.constant.Const.APP_ID, appId); genernateColumn(); generaterIndex(tmpFileName, generateFileName); generateArticle(DateUtil.format(DateUtil.yesterday(), "yyyy-MM-dd")); LOG.info("", new Date()); } catch (IOException e) { LOG.info("", new Date()); e.printStackTrace(); } } private void generateArticle(String dateTime) throws IOException { List<CategoryBean> articleIdList = null; List<CategoryEntity> categoryList = null; AttributeBean attributeBean = new AttributeBean(); ContentBean contentBean = new ContentBean(); contentBean.setBeginTime(dateTime); Map<String, Object> map = new HashMap<>(); map.put(net.mingsoft.basic.constant.Const.APP_ID, BasicUtil.getAppId()); PageBean page = new PageBean(); map.put(ParserUtil.HTML, ParserUtil.HTML); map.put(ParserUtil.URL, BasicUtil.getUrl()); map.put(ParserUtil.PAGE, page); CategoryEntity categoryEntity = new CategoryEntity(); categoryList = categoryDao.query(categoryEntity); for(CategoryEntity category : categoryList){ contentBean.setContentCategoryId(category.getId()); if(category.getCategoryType().equals("1")){ if (!FileUtil.exist(ParserUtil.buildTempletPath(category.getCategoryListUrl())) || StringUtils.isEmpty(category.getCategoryListUrl())) { LOG.error("{}",category.getCategoryUrl()); continue; } ParserUtil.read(category.getCategoryListUrl(),map, page,attributeBean); contentBean.setFlag(attributeBean.getFlag()); contentBean.setNoflag(attributeBean.getNoflag()); contentBean.setOrder(attributeBean.getOrder()); contentBean.setOrderBy(attributeBean.getOrderby()); } articleIdList = queryIdsByCategoryIdForParser(contentBean); if (articleIdList.size() > 0) { CmsParserUtil.generateBasic(articleIdList); } } } private void genernateColumn() throws IOException { List<CategoryEntity> columns = new ArrayList<>(); CategoryEntity categoryEntity=new CategoryEntity(); categoryEntity.setAppId(BasicUtil.getAppId()); columns = categoryDao.query(categoryEntity); List<CategoryBean> articleIdList = null; for (CategoryEntity column : columns) { ContentBean contentBean = new ContentBean(); contentBean.setContentCategoryId(column.getId()); if(column.getCategoryType().equals("1")) { if (!FileUtil.exist(ParserUtil.buildTempletPath(column.getCategoryListUrl()))) { LOG.error("{}", column.getCategoryUrl()); continue; } Map<String, Object> map = new HashMap<>(); map.put(net.mingsoft.basic.constant.Const.APP_ID, BasicUtil.getAppId()); PageBean page = new PageBean(); map.put(ParserUtil.HTML, ParserUtil.HTML); map.put(ParserUtil.URL, BasicUtil.getUrl()); map.put(ParserUtil.PAGE, page); AttributeBean attributeBean = new AttributeBean(); ParserUtil.read(column.getCategoryListUrl(), map, page, attributeBean); contentBean.setFlag(attributeBean.getFlag()); contentBean.setNoflag(attributeBean.getNoflag()); contentBean.setOrder(attributeBean.getOrder()); contentBean.setOrderBy(attributeBean.getOrderby()); } articleIdList = contentDao.queryIdsByCategoryIdForParser(contentBean); switch (column.getCategoryType()) { //TODO case "1": CmsParserUtil.generateList(column, articleIdList.size()); break; case "2": if(articleIdList.size()==0){ CategoryBean columnArticleIdBean=new CategoryBean(); CopyOptions copyOptions=CopyOptions.create(); copyOptions.setIgnoreError(true); BeanUtil.copyProperties(column,columnArticleIdBean,copyOptions); articleIdList.add(columnArticleIdBean); } CmsParserUtil.generateBasic(articleIdList); break; } } } private void generaterIndex(String templatePath, String targetPath) throws IOException { if (!FileUtil.exist(ParserUtil.buildTempletPath())) { LOG.info(""); return; } Map<String, Object> map = new HashMap<String, Object>(); map.put(ParserUtil.IS_DO, false); CategoryEntity column = new CategoryEntity(); map.put(ParserUtil.COLUMN, column); if (ParserUtil.IS_SINGLE) { map.put(ParserUtil.URL, BasicUtil.getUrl()); } map.put(ParserUtil.HTML, ParserUtil.HTML); map.put(Const.APP_ID, BasicUtil.getAppId()); String read = ParserUtil.read(templatePath, map); FileUtil.writeString(read, ParserUtil.buildHtmlPath(targetPath), net.mingsoft.base.constant.Const.UTF8); } }
package net.ucanaccess.commands; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import net.ucanaccess.converters.LoadJet; import net.ucanaccess.converters.SQLConverter; import net.ucanaccess.converters.SQLConverter.DDLType; import net.ucanaccess.jdbc.UcanaccessConnection; import net.ucanaccess.jdbc.UcanaccessSQLException; import net.ucanaccess.jdbc.UcanaccessSQLException.ExceptionMessages; import com.healthmarketscience.jackcess.Database; public class DDLCommandEnlist { private String[] types; private String[] defaults; private Boolean[] notNulls; private HashMap<String,String> columnMap= new HashMap<String,String>(); private void enlistCreateTable(String sql, DDLType ddlType) throws SQLException { String tn = ddlType.getDBObjectName(sql); UcanaccessConnection ac = UcanaccessConnection.getCtxConnection(); String execId = UcanaccessConnection.getCtxExcId(); Connection hsqlConn = ac.getHSQLDBConnection(); Database db = ac.getDbIO(); LoadJet lfa = new LoadJet(hsqlConn, db); String ntn=tn; if(tn.startsWith("[")&&tn.endsWith("]")){ ntn=SQLConverter.escapeIdentifier(tn.substring(1, tn.length()-1)); } lfa.synchronisationTriggers(ntn, true,true); CreateTableCommand c4io; if(ddlType.equals(DDLType.CREATE_TABLE)){ parseTypesFromCreateStatement(sql); c4io=new CreateTableCommand( tn, execId,this.columnMap, this.types,this.defaults,this.notNulls); } else { c4io=new CreateTableCommand(tn, execId); } ac.add(c4io); if(!ac.getAutoCommit()){ ac.commit(); } } public void enlistDDLCommand(String sql, DDLType ddlType) throws SQLException { switch (ddlType) { case CREATE_TABLE: case CREATE_TABLE_AS_SELECT: enlistCreateTable(sql, ddlType); break; case DROP_TABLE: enlistDropTable(sql, ddlType); break; } } private void enlistDropTable(String sql, DDLType ddlType) { String tn = ddlType.getDBObjectName(sql); String execId = UcanaccessConnection.getCtxExcId(); UcanaccessConnection ac = UcanaccessConnection.getCtxConnection(); DropTableCommand c4io = new DropTableCommand(tn, execId); ac.add(c4io); } //getting AUTOINCREMENT and GUID private void parseTypesFromCreateStatement(String sql) throws SQLException { int startDecl = sql.indexOf('('); int endDecl = sql.lastIndexOf(')'); if (startDecl >= endDecl) { throw new UcanaccessSQLException(ExceptionMessages.INVALID_CREATE_STATEMENT); } String decl = sql.substring(startDecl + 1, endDecl); String[] tokens = decl.split(","); ArrayList<String> typeList = new ArrayList<String>() ; ArrayList<String> defaultList = new ArrayList<String>() ; this.columnMap = new HashMap<String,String>() ; ArrayList<Boolean> notNullList = new ArrayList<Boolean>() ; for (int j = 0; j < tokens.length; ++j) { String tknt=tokens[j].trim(); String[] colDecls = tknt.split("[\\s\n\r]+"); if(colDecls[0].startsWith("[")&&tknt.substring(1).indexOf("]")>0){ for(int k=0;k<colDecls.length;k++){ if(colDecls[k].endsWith("]")){ String[] colDecls0=new String[colDecls.length-k]; colDecls0[0]=tknt.substring(1,tknt.indexOf("]")); for(int y=1;y<colDecls0.length;y++){ colDecls0[y]=colDecls[y+k]; } colDecls=colDecls0; break; } } } String escaped=(SQLConverter.isListedAsKeyword(colDecls[0].toUpperCase()))? colDecls[0].toUpperCase():SQLConverter.basicEscapingIdentifier(colDecls[0]); columnMap.put(escaped,colDecls[0]); boolean reset=false; if(tknt.matches("[\\s\n\r]*\\d+[\\s\n\r]*\\).*")){ reset=true; tknt=tknt.substring(tknt.indexOf(")")+1).trim(); colDecls = tknt.split("[\\s\n\r]+"); } if (!reset&&colDecls.length< 2) { continue; } boolean decDef=false; if(!reset){ if(colDecls[1]!=null&&colDecls[1].toUpperCase().startsWith("NUMERIC(")){ colDecls[1]="NUMERIC"; decDef=true; } typeList.add(colDecls[1]); } if(colDecls.length>2 &&"not".equalsIgnoreCase(colDecls[colDecls.length-2]) &&"null".equalsIgnoreCase(colDecls[colDecls.length-1]) ){ notNullList.add(true); }else if(!decDef){ notNullList.add(false); } if(!decDef){ defaultList.add(value(SQLConverter.getDDLDefault(tknt))); } this.types= (String[])typeList.toArray(new String[typeList.size()]); this.defaults=(String[])defaultList.toArray(new String[defaultList.size()]); this.notNulls=(Boolean[])notNullList.toArray(new Boolean[notNullList.size()]); } } private String value(String value) { if(value==null)return null; if(value.startsWith("\"")&&value.endsWith("\"")){ return value.substring(1, value.length()-1).replaceAll("\"\"", "\""); } if(value.startsWith("'")&&value.endsWith("'")){ return (value.substring(1, value.length()-1).replaceAll("''", "'")); } return value; } }
package nl.tudelft.lifetiles.graph.view; import nl.tudelft.lifetiles.annotation.model.ResistanceAnnotation; import javafx.scene.Group; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.control.Tooltip; /** * A bookmark is the equivalent of a annotation mapped onto the graph. * * @author Jos * */ public class Bookmark extends Rectangle { /** * The standard opacity of the bookmark overlay. */ private static final double OPACITY = 0.5; /** * The standard color of the bookmark overlay. */ private static final Color STANDARD_COLOR = Color.YELLOW; /** * Constructs a bookmark from a vertex, a annotation and a segment position. * * @param vertex * The vertex the bookmark is placed on. * @param annotation * The annotation which is visualized using this bookmark. * @param segmentPosition * The position of the bookmark on the segment. */ public Bookmark(final VertexView vertex, final ResistanceAnnotation annotation, final long segmentPosition) { super(vertex.HORIZONTALSCALE, vertex.getHeight()); setLayoutX(vertex.getLayoutX() + segmentPosition * vertex.HORIZONTALSCALE); setLayoutY(vertex.getLayoutY()); setOpacity(OPACITY); setFill(STANDARD_COLOR); Tooltip tooltip = new Tooltip(annotation.toString()); Tooltip.install(this, tooltip); } }
package org.aesh.command.map; import java.util.Objects; import org.aesh.command.impl.internal.ProcessedCommand; import org.aesh.command.impl.internal.ProcessedOption; import org.aesh.command.impl.parser.CommandLineParser; import org.aesh.command.populator.CommandPopulator; import org.aesh.command.validator.OptionValidatorException; import org.aesh.console.AeshContext; import org.aesh.command.invocation.InvocationProviders; import org.aesh.command.Command; import org.aesh.command.parser.CommandLineParserException; /** * * Populator for MapCommand. * * @author jdenise@redhat.com */ class MapCommandPopulator implements CommandPopulator<Object, Command> { private final MapCommand instance; MapCommandPopulator(MapCommand instance) { Objects.requireNonNull(instance); this.instance = instance; } @Override public void populateObject(ProcessedCommand<Command> processedCommand, InvocationProviders invocationProviders, AeshContext aeshContext, CommandLineParser.Mode validate) throws CommandLineParserException, OptionValidatorException { if (processedCommand.parserExceptions().size() > 0) { throw processedCommand.parserExceptions().get(0); } for (ProcessedOption option : processedCommand.getOptions()) { if (option.getValue() != null) { instance.setValue(option.name(), option.doConvert(option.getValue(), invocationProviders, instance, aeshContext, validate == CommandLineParser.Mode.VALIDATE)); } else { instance.resetValue(option.name()); } } if (processedCommand.getArguments() != null) { if (processedCommand.getArguments().getValues().size() > 0) { String val = processedCommand.getArguments().getValue(); if (val != null) { instance.setValue(processedCommand.getArguments().name(), processedCommand.getArguments(). doConvert(val, invocationProviders, instance, aeshContext, validate == CommandLineParser.Mode.VALIDATE)); } else { instance.resetValue(processedCommand.getArguments().name()); } } else { instance.resetValue(processedCommand.getArguments().name()); } } if (processedCommand.getArgument() != null) { if (processedCommand.getArgument().getValues().size() > 0) { String val = processedCommand.getArgument().getValue(); if (val != null) { instance.setValue(processedCommand.getArgument().name(), processedCommand.getArgument(). doConvert(val, invocationProviders, instance, aeshContext, validate == CommandLineParser.Mode.VALIDATE)); } else { instance.resetValue(processedCommand.getArgument().name()); } } else { instance.resetValue(processedCommand.getArgument().name()); } } } @Override public Object getObject() { return instance; } }
package org.ambraproject.rhino.model; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import java.util.Collection; import java.util.Date; import java.util.Optional; @Entity @Table(name = "articleItem") public class ArticleItem implements Timestamped { @Id @GeneratedValue @Column private long itemId; @JoinColumn(name = "ingestionId", nullable = false) @ManyToOne private ArticleIngestion ingestion; @Column private String doi; @Column(name = "articleItemType") private String itemType; @Cascade(CascadeType.SAVE_UPDATE) @OneToMany(targetEntity = ArticleFile.class, mappedBy = "item", fetch = FetchType.EAGER) private Collection<ArticleFile> files; @Column private Date created; public long getItemId() { return itemId; } public void setItemId(long itemId) { this.itemId = itemId; } public ArticleIngestion getIngestion() { return ingestion; } public void setIngestion(ArticleIngestion ingestion) { this.ingestion = ingestion; } public String getDoi() { return doi; } public void setDoi(String doi) { this.doi = doi; } public String getItemType() { return itemType; } public void setItemType(String itemType) { this.itemType = itemType; } public Collection<ArticleFile> getFiles() { return files; } public void setFiles(Collection<ArticleFile> files) { this.files = files; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } @Transient @Override public Date getLastModified() { return getCreated(); } private transient ImmutableMap<String, ArticleFile> fileMap; @Transient private ImmutableMap<String, ArticleFile> getFileMap() { return (fileMap != null) ? fileMap : (fileMap = Maps.uniqueIndex(getFiles(), ArticleFile::getFileType)); } @Transient public Optional<ArticleFile> getFile(String fileType) { return Optional.ofNullable(getFileMap().get(fileType)); } @Transient public ImmutableSet<String> getFileTypes() { return getFileMap().keySet(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ArticleItem that = (ArticleItem) o; if (ingestion != null ? !ingestion.equals(that.ingestion) : that.ingestion != null) return false; return doi != null ? doi.equals(that.doi) : that.doi == null; } @Override public int hashCode() { int result = ingestion != null ? ingestion.hashCode() : 0; result = 31 * result + (doi != null ? doi.hashCode() : 0); return result; } }
package org.amc.game.chessserver; import com.google.gson.Gson; import org.amc.game.chess.IllegalMoveException; import org.amc.game.chess.Move; import org.amc.game.chess.Player; import org.amc.game.chessserver.JsonChessGameView.JsonChessGame; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.handler.annotation.DestinationVariable; import org.springframework.messaging.handler.annotation.Header; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.Payload; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.messaging.simp.annotation.SendToUser; import org.springframework.stereotype.Controller; import java.security.Principal; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import static org.springframework.messaging.simp.SimpMessageHeaderAccessor.SESSION_ATTRIBUTES; /** * Handles a WebSocket message received for a move in a chess game * * @author Adrian Mclaughlin * */ @Controller public class StompController { private static final Logger logger = Logger.getLogger(StompController.class); private Map<Long, ServerChessGame> gameMap; /** * STOMP messaging object to send stomp message to objects */ private SimpMessagingTemplate template; private static final String ERROR_MSG_NOT_ENOUGH_PLAYERS = "Error:Move on game(%d) which hasn't got two players"; private static final String ERROR_MSG_GAME_OVER = "Error:Move on game(%d) which has finished"; @MessageMapping("/move/{gameUUID}") @SendToUser(value = "/queue/updates", broadcast = false) public void registerMove(Principal user, @Header(SESSION_ATTRIBUTES) Map<String, Object> wsSession, @DestinationVariable long gameUUID, @Payload String moveString) { logger.debug(String.format("USER(%s)'s move received for game:%d", user.getName(), gameUUID)); Player player = (Player) wsSession.get("PLAYER"); logger.debug("PLAYER:" + player); ServerChessGame game = gameMap.get(gameUUID); String message = ""; if (game.getCurrentStatus().equals(ServerChessGame.ServerGameStatus.IN_PROGRESS)) { message = moveChessPiece(game, player, moveString); } else if (game.getCurrentStatus().equals(ServerChessGame.ServerGameStatus.AWAITING_PLAYER)) { message = String.format(ERROR_MSG_NOT_ENOUGH_PLAYERS, gameUUID); } else if (game.getCurrentStatus().equals(ServerChessGame.ServerGameStatus.FINISHED)) { message = String.format(ERROR_MSG_GAME_OVER, gameUUID); } logger.error(message); MessageType type = message.equals("") ? MessageType.INFO : MessageType.ERROR; sendMessageToUser(user, message, type); } private String moveChessPiece(ServerChessGame game, Player player, String moveString) { String message = ""; try { game.move(player, getMoveFromString(moveString)); } catch (IllegalMoveException e) { message = "Error:" + e.getMessage(); } catch (MalformedMoveException mme) { message = "Error:" + mme.getMessage(); } return message; } private Move getMoveFromString(String moveString) { MoveEditor convertor = new MoveEditor(); convertor.setAsText(moveString); logger.debug(convertor.getValue()); return (Move) convertor.getValue(); } /** * Sends a reply to the user * * @param user * User to receive message * @param message * containing either an error message or information update */ private void sendMessageToUser(Principal user, String message, MessageType type) { template.convertAndSendToUser(user.getName(), "/queue/updates", message, getHeaders(type)); } private Map<String, Object> getHeaders(MessageType type) { Map<String, Object> headers = new HashMap<String, Object>(); headers.put(StompConstants.MESSAGE_HEADER_TYPE.getValue(), type); return headers; } @MessageMapping("/get/{gameUUID}") @SendToUser(value = "/queue/updates", broadcast = false) public void getChessBoard(Principal user, @Header(SESSION_ATTRIBUTES) Map<String, Object> wsSession, @DestinationVariable long gameUUID, @Payload String message) { ServerChessGame serverGame = gameMap.get(gameUUID); Gson gson = new Gson(); JsonChessGame jcb = new JsonChessGame(serverGame.getChessGame()); logger.debug(wsSession.get("PLAYER") + " requested update for game:" + gameUUID); sendMessageToUser(user, gson.toJson(jcb), MessageType.UPDATE); } @Resource(name = "gameMap") public void setGameMap(Map<Long, ServerChessGame> gameMap) { this.gameMap = gameMap; } /** * For adding a {@link SimpMessagingTemplate} object to be used for send * STOMP messages * * @param template * SimpMessagingTemplate */ @Autowired public void setTemplate(SimpMessagingTemplate template) { this.template = template; } }
package org.b3log.symphony.event; import org.apache.commons.lang.StringUtils; import org.b3log.latke.Keys; import org.b3log.latke.Latkes; import org.b3log.latke.event.AbstractEventListener; import org.b3log.latke.event.Event; import org.b3log.latke.event.EventException; import org.b3log.latke.ioc.inject.Inject; import org.b3log.latke.ioc.inject.Named; import org.b3log.latke.ioc.inject.Singleton; import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Logger; import org.b3log.latke.model.Pagination; import org.b3log.latke.model.User; import org.b3log.latke.repository.*; import org.b3log.latke.service.LangPropsService; import org.b3log.symphony.model.*; import org.b3log.symphony.processor.advice.validate.UserRegisterValidation; import org.b3log.symphony.processor.channel.ArticleChannel; import org.b3log.symphony.processor.channel.ArticleListChannel; import org.b3log.symphony.repository.CommentRepository; import org.b3log.symphony.repository.UserRepository; import org.b3log.symphony.service.*; import org.b3log.symphony.util.Emotions; import org.b3log.symphony.util.JSONs; import org.b3log.symphony.util.Markdowns; import org.b3log.symphony.util.Symphonys; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.safety.Whitelist; import java.util.HashSet; import java.util.List; import java.util.Set; @Named @Singleton public class CommentNotifier extends AbstractEventListener<JSONObject> { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(CommentNotifier.class); /** * Comment repository. */ @Inject private CommentRepository commentRepository; /** * User repository. */ @Inject private UserRepository userRepository; /** * Notification management service. */ @Inject private NotificationMgmtService notificationMgmtService; /** * Article query service. */ @Inject private ArticleQueryService articleQueryService; /** * User query service. */ @Inject private UserQueryService userQueryService; /** * Avatar query service. */ @Inject private AvatarQueryService avatarQueryService; /** * Short link query service. */ @Inject private ShortLinkQueryService shortLinkQueryService; /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Timeline management service. */ @Inject private TimelineMgmtService timelineMgmtService; /** * Pointtransfer management service. */ @Inject private PointtransferMgmtService pointtransferMgmtService; /** * Comment query service. */ @Inject private CommentQueryService commentQueryService; /** * Follow query service. */ @Inject private FollowQueryService followQueryService; @Override public void action(final Event<JSONObject> event) throws EventException { final JSONObject data = event.getData(); LOGGER.log(Level.TRACE, "Processing an event[type={0}, data={1}] in listener[className={2}]", new Object[]{event.getType(), data, CommentNotifier.class.getName()}); try { final JSONObject originalArticle = data.getJSONObject(Article.ARTICLE); final JSONObject originalComment = data.getJSONObject(Comment.COMMENT); final boolean fromClient = data.optBoolean(Common.FROM_CLIENT); final int commentViewMode = data.optInt(UserExt.USER_COMMENT_VIEW_MODE); final String articleId = originalArticle.optString(Keys.OBJECT_ID); final String commentId = originalComment.optString(Keys.OBJECT_ID); final String originalCmtId = originalComment.optString(Comment.COMMENT_ORIGINAL_COMMENT_ID); final String commenterId = originalComment.optString(Comment.COMMENT_AUTHOR_ID); final String commentContent = originalComment.optString(Comment.COMMENT_CONTENT); final JSONObject commenter = userQueryService.getUser(commenterId); final String commenterName = commenter.optString(User.USER_NAME); // 0. Data channel (WebSocket) final JSONObject chData = JSONs.clone(originalComment); chData.put(Comment.COMMENT_T_COMMENTER, commenter); chData.put(Keys.OBJECT_ID, commentId); chData.put(Article.ARTICLE_T_ID, articleId); chData.put(Comment.COMMENT_T_ID, commentId); chData.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, originalCmtId); String originalCmtAuthorId = null; if (StringUtils.isNotBlank(originalCmtId)) { final Query numQuery = new Query() .setPageSize(Integer.MAX_VALUE).setCurrentPageNum(1).setPageCount(1); switch (commentViewMode) { case UserExt.USER_COMMENT_VIEW_MODE_C_TRADITIONAL: numQuery.setFilter(CompositeFilterOperator.and( new PropertyFilter(Comment.COMMENT_ON_ARTICLE_ID, FilterOperator.EQUAL, articleId), new PropertyFilter(Keys.OBJECT_ID, FilterOperator.LESS_THAN_OR_EQUAL, originalCmtId) )).addSort(Keys.OBJECT_ID, SortDirection.ASCENDING); break; case UserExt.USER_COMMENT_VIEW_MODE_C_REALTIME: numQuery.setFilter(CompositeFilterOperator.and( new PropertyFilter(Comment.COMMENT_ON_ARTICLE_ID, FilterOperator.EQUAL, articleId), new PropertyFilter(Keys.OBJECT_ID, FilterOperator.GREATER_THAN_OR_EQUAL, originalCmtId) )).addSort(Keys.OBJECT_ID, SortDirection.DESCENDING); break; } final long num = commentRepository.count(numQuery); final int page = (int) ((num / Symphonys.getInt("articleCommentsPageSize")) + 1); chData.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, page); final JSONObject originalCmt = commentRepository.get(originalCmtId); originalCmtAuthorId = originalCmt.optString(Comment.COMMENT_AUTHOR_ID); final JSONObject originalCmtAuthor = userRepository.get(originalCmtAuthorId); if (Comment.COMMENT_ANONYMOUS_C_PUBLIC == originalCmt.optInt(Comment.COMMENT_ANONYMOUS)) { chData.put(Comment.COMMENT_T_ORIGINAL_AUTHOR_THUMBNAIL_URL, avatarQueryService.getAvatarURLByUser( UserExt.USER_AVATAR_VIEW_MODE_C_ORIGINAL, originalCmtAuthor, "20")); } else { chData.put(Comment.COMMENT_T_ORIGINAL_AUTHOR_THUMBNAIL_URL, avatarQueryService.getDefaultAvatarURL("20")); } } if (Comment.COMMENT_ANONYMOUS_C_PUBLIC == originalComment.optInt(Comment.COMMENT_ANONYMOUS)) { chData.put(Comment.COMMENT_T_AUTHOR_NAME, commenterName); chData.put(Comment.COMMENT_T_AUTHOR_THUMBNAIL_URL, avatarQueryService.getAvatarURLByUser( UserExt.USER_AVATAR_VIEW_MODE_C_ORIGINAL, commenter, "48")); } else { chData.put(Comment.COMMENT_T_AUTHOR_NAME, UserExt.ANONYMOUS_USER_NAME); chData.put(Comment.COMMENT_T_AUTHOR_THUMBNAIL_URL, avatarQueryService.getDefaultAvatarURL("48")); } chData.put(Common.THUMBNAIL_UPDATE_TIME, commenter.optLong(UserExt.USER_UPDATE_TIME)); chData.put(Common.TIME_AGO, langPropsService.get("justNowLabel")); String thankTemplate = langPropsService.get("thankConfirmLabel"); thankTemplate = thankTemplate.replace("{point}", String.valueOf(Symphonys.getInt("pointThankComment"))) .replace("{user}", commenterName); chData.put(Comment.COMMENT_T_THANK_LABEL, thankTemplate); String cc = shortLinkQueryService.linkArticle(commentContent); cc = shortLinkQueryService.linkTag(cc); cc = Emotions.convert(cc); cc = Markdowns.toHTML(cc); cc = Markdowns.clean(cc, ""); if (fromClient) { // "<i class='ft-small'>by 88250</i>" String syncCommenterName = StringUtils.substringAfter(cc, "<i class=\"ft-small\">by "); syncCommenterName = StringUtils.substringBefore(syncCommenterName, "</i>"); if (UserRegisterValidation.invalidUserName(syncCommenterName)) { syncCommenterName = UserExt.ANONYMOUS_USER_NAME; } cc = cc.replaceAll("<i class=\"ft-small\">by .*</i>", ""); chData.put(Comment.COMMENT_T_AUTHOR_NAME, syncCommenterName); } chData.put(Comment.COMMENT_CONTENT, cc); chData.put(Comment.COMMENT_UA, originalComment.optString(Comment.COMMENT_UA)); chData.put(Common.FROM_CLIENT, fromClient); ArticleChannel.notifyComment(chData); // + Article Heat final JSONObject articleHeat = new JSONObject(); articleHeat.put(Article.ARTICLE_T_ID, articleId); articleHeat.put(Common.OPERATION, "+"); ArticleListChannel.notifyHeat(articleHeat); ArticleChannel.notifyHeat(articleHeat); final boolean isDiscussion = originalArticle.optInt(Article.ARTICLE_TYPE) == Article.ARTICLE_TYPE_C_DISCUSSION; // Timeline if (!isDiscussion && Comment.COMMENT_ANONYMOUS_C_PUBLIC == originalComment.optInt(Comment.COMMENT_ANONYMOUS)) { String articleTitle = Jsoup.parse(originalArticle.optString(Article.ARTICLE_TITLE)).text(); articleTitle = Emotions.convert(articleTitle); final String articlePermalink = Latkes.getServePath() + originalArticle.optString(Article.ARTICLE_PERMALINK); final JSONObject timeline = new JSONObject(); timeline.put(Common.USER_ID, commenterId); timeline.put(Common.TYPE, Comment.COMMENT); String content = langPropsService.get("timelineCommentLabel"); if (fromClient) { // "<i class='ft-small'>by 88250</i>" String syncCommenterName = StringUtils.substringAfter(cc, "<i class=\"ft-small\">by "); syncCommenterName = StringUtils.substringBefore(syncCommenterName, "</i>"); if (UserRegisterValidation.invalidUserName(syncCommenterName)) { syncCommenterName = UserExt.ANONYMOUS_USER_NAME; } content = content.replace("{user}", syncCommenterName); } else { content = content.replace("{user}", "<a target='_blank' rel='nofollow' href='" + Latkes.getServePath() + "/member/" + commenterName + "'>" + commenterName + "</a>"); } content = content.replace("{article}", "<a target='_blank' rel='nofollow' href='" + articlePermalink + "'>" + articleTitle + "</a>") .replace("{comment}", cc.replaceAll("<p>", "").replaceAll("</p>", "")); content = Jsoup.clean(content, Whitelist.none().addAttributes("a", "href", "rel", "target")); timeline.put(Common.CONTENT, content); if (StringUtils.isNotBlank(content)) { timelineMgmtService.addTimeline(timeline); } } final String articleAuthorId = originalArticle.optString(Article.ARTICLE_AUTHOR_ID); final boolean commenterIsArticleAuthor = articleAuthorId.equals(commenterId); // 1. '@participants' Notification if (commentContent.contains("@participants ")) { final List<JSONObject> participants = articleQueryService.getArticleLatestParticipants( UserExt.USER_AVATAR_VIEW_MODE_C_ORIGINAL, articleId, Integer.MAX_VALUE); int count = participants.size(); if (count < 1) { return; } count = 0; for (final JSONObject participant : participants) { final String participantId = participant.optString(Keys.OBJECT_ID); if (participantId.equals(commenterId)) { continue; } count++; final JSONObject requestJSONObject = new JSONObject(); requestJSONObject.put(Notification.NOTIFICATION_USER_ID, participantId); requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, commentId); notificationMgmtService.addAtNotification(requestJSONObject); } final int sum = count * Pointtransfer.TRANSFER_SUM_C_AT_PARTICIPANTS; if (sum > 0) { pointtransferMgmtService.transfer(commenterId, Pointtransfer.ID_C_SYS, Pointtransfer.TRANSFER_TYPE_C_AT_PARTICIPANTS, sum, commentId, System.currentTimeMillis()); } return; } final Set<String> atUserNames = userQueryService.getUserNames(commentContent); atUserNames.remove(commenterName); final Set<String> watcherIds = new HashSet<>(); final JSONObject followerUsersResult = followQueryService.getArticleWatchers(UserExt.USER_AVATAR_VIEW_MODE_C_ORIGINAL, articleId, 1, Integer.MAX_VALUE); final List<JSONObject> watcherUsers = (List<JSONObject>) followerUsersResult.opt(Keys.RESULTS); for (final JSONObject watcherUser : watcherUsers) { final String watcherUserId = watcherUser.optString(Keys.OBJECT_ID); watcherIds.add(watcherUserId); } watcherIds.remove(articleAuthorId); if (commenterIsArticleAuthor && atUserNames.isEmpty() && watcherIds.isEmpty() && StringUtils.isBlank(originalCmtId)) { return; } // 2. 'Commented' Notification if (!commenterIsArticleAuthor) { final JSONObject requestJSONObject = new JSONObject(); requestJSONObject.put(Notification.NOTIFICATION_USER_ID, articleAuthorId); requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, commentId); notificationMgmtService.addCommentedNotification(requestJSONObject); } // 3. 'Reply' Notification final Set<String> repliedIds = new HashSet<>(); if (StringUtils.isNotBlank(originalCmtId)) { if (!articleAuthorId.equals(originalCmtAuthorId)) { final JSONObject requestJSONObject = new JSONObject(); requestJSONObject.put(Notification.NOTIFICATION_USER_ID, originalCmtAuthorId); requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, commentId); notificationMgmtService.addReplyNotification(requestJSONObject); repliedIds.add(originalCmtAuthorId); } } final String articleContent = originalArticle.optString(Article.ARTICLE_CONTENT); final Set<String> articleContentAtUserNames = userQueryService.getUserNames(articleContent); // 4. 'At' Notification final Set<String> atIds = new HashSet<>(); for (final String userName : atUserNames) { if (isDiscussion && !articleContentAtUserNames.contains(userName)) { continue; } final JSONObject user = userQueryService.getUserByName(userName); if (null == user) { LOGGER.log(Level.WARN, "Not found user by name [{0}]", userName); continue; } if (user.optString(Keys.OBJECT_ID).equals(articleAuthorId)) { continue; // Has notified in step 2 } final String userId = user.optString(Keys.OBJECT_ID); if (repliedIds.contains(userId)) { continue; } final JSONObject requestJSONObject = new JSONObject(); requestJSONObject.put(Notification.NOTIFICATION_USER_ID, userId); requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, commentId); notificationMgmtService.addAtNotification(requestJSONObject); atIds.add(userId); } // 5. 'following - article comment' Notification for (final String userId : watcherIds) { final JSONObject watcher = userRepository.get(userId); final String watcherName = watcher.optString(User.USER_NAME); if ((isDiscussion && !articleContentAtUserNames.contains(watcherName)) || commenterName.equals(watcherName) || repliedIds.contains(userId) || atIds.contains(userId)) { continue; } final JSONObject requestJSONObject = new JSONObject(); requestJSONObject.put(Notification.NOTIFICATION_USER_ID, userId); requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, commentId); notificationMgmtService.addFollowingArticleCommentNotification(requestJSONObject); } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Sends the comment notification failed", e); } } /** * Gets the event type {@linkplain EventTypes#ADD_COMMENT_TO_ARTICLE}. * * @return event type */ @Override public String getEventType() { return EventTypes.ADD_COMMENT_TO_ARTICLE; } }
package org.crygier.graphql; import graphql.Scalars; import graphql.schema.*; import org.crygier.graphql.annotation.SchemaDocumentation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import javax.persistence.metamodel.*; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class GraphQLSchemaBuilder { public static final String PAGINATION_REQUEST_PARAM_NAME = "paginationRequest"; private static final Logger log = LoggerFactory.getLogger(GraphQLSchemaBuilder.class); private EntityManager entityManager; public GraphQLSchemaBuilder(EntityManager entityManager) { this.entityManager = entityManager; } public GraphQLSchema getGraphQLSchema() { GraphQLSchema.Builder schemaBuilder = GraphQLSchema.newSchema(); schemaBuilder.query(getQueryType()); return schemaBuilder.build(); } private GraphQLObjectType getQueryType() { GraphQLObjectType.Builder queryType = GraphQLObjectType.newObject().name("QueryType_JPA").description("All encompassing schema for this JPA environment"); queryType.fields(entityManager.getMetamodel().getEntities().stream().map(this::getQueryFieldDefinition).collect(Collectors.toList())); queryType.fields(entityManager.getMetamodel().getEntities().stream().map(this::getQueryFieldPageableDefinition).collect(Collectors.toList())); return queryType.build(); } private GraphQLFieldDefinition getQueryFieldDefinition(EntityType<?> entityType) { return GraphQLFieldDefinition.newFieldDefinition() .name(entityType.getName()) .description(getSchemaDocumentation( entityType.getJavaType())) .type(new GraphQLList(getObjectType(entityType))) .dataFetcher(new JpaDataFetcher(entityManager, entityType)) .argument(entityType.getAttributes().stream().filter(this::isValidInput).map(this::getArgument).collect(Collectors.toList())) .build(); } private GraphQLFieldDefinition getQueryFieldPageableDefinition(EntityType<?> entityType) { GraphQLObjectType pageType = GraphQLObjectType.newObject() .name(entityType.getName() + "Connection") .description("'Connection' response wrapper object for " + entityType.getName() + ". When pagination or aggregation is requested, this object will be returned with metadata about the query.") .field(GraphQLFieldDefinition.newFieldDefinition().name("totalPages").description("Total number of pages calculated on the database for this pageSize.").type(JavaScalars.GraphQLLong).build()) .field(GraphQLFieldDefinition.newFieldDefinition().name("totalElements").description("Total number of results on the database for this query.").type(JavaScalars.GraphQLLong).build()) .field(GraphQLFieldDefinition.newFieldDefinition().name("content").description("The actual object results").type(new GraphQLList(getObjectType(entityType))).build()) .build(); return GraphQLFieldDefinition.newFieldDefinition() .name(entityType.getName() + "Connection") .description("'Connection' request wrapper object for " + entityType.getName() + ". Use this object in a query to request things like pagination or aggregation in an argument. Use the 'content' field to request actual fields ") .type(pageType) .dataFetcher(new ExtendedJpaDataFetcher(entityManager, entityType)) .argument(paginationArgument) .build(); } private GraphQLArgument getArgument(Attribute attribute) { GraphQLType type = getAttributeType(attribute); if (type instanceof GraphQLInputType) { return GraphQLArgument.newArgument() .name(attribute.getName()) .type((GraphQLInputType) type) .build(); } throw new IllegalArgumentException("Attribute " + attribute + " cannot be mapped as an Input Argument"); } private GraphQLObjectType getObjectType(EntityType<?> entityType) { return GraphQLObjectType.newObject() .name(entityType.getName()) .description(getSchemaDocumentation( entityType.getJavaType())) .fields(entityType.getAttributes().stream().map(this::getObjectField).collect(Collectors.toList())) .build(); } private GraphQLFieldDefinition getObjectField(Attribute attribute) { GraphQLType type = getAttributeType(attribute); if (type instanceof GraphQLOutputType) { List<GraphQLArgument> arguments = new ArrayList<>(); arguments.add(GraphQLArgument.newArgument().name("orderBy").type(orderByDirectionEnum).build()); // Always add the orderBy argument // Get the fields that can be queried on (i.e. Simple Types, no Sub-Objects) if (attribute instanceof SingularAttribute && attribute.getPersistentAttributeType() != Attribute.PersistentAttributeType.BASIC) { EntityType foreignType = (EntityType) ((SingularAttribute) attribute).getType(); Stream<Attribute> attributes = findBasicAttributes(foreignType.getAttributes()); attributes.forEach(it -> { arguments.add(GraphQLArgument.newArgument().name(it.getName()).type((GraphQLInputType) getAttributeType(it)).build()); }); } return GraphQLFieldDefinition.newFieldDefinition() .name(attribute.getName()) .description(getSchemaDocumentation(attribute.getJavaMember())) .type((GraphQLOutputType) type) .argument(arguments) .build(); } throw new IllegalArgumentException("Attribute " + attribute + " cannot be mapped as an Output Argument"); } private Stream<Attribute> findBasicAttributes(Collection<Attribute> attributes) { return attributes.stream().filter(it -> it.getPersistentAttributeType() == Attribute.PersistentAttributeType.BASIC); } private GraphQLType getAttributeType(Attribute attribute) { if (attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.BASIC) { if (String.class.isAssignableFrom(attribute.getJavaType())) return Scalars.GraphQLString; else if (Integer.class.isAssignableFrom(attribute.getJavaType()) || int.class.isAssignableFrom(attribute.getJavaType())) return Scalars.GraphQLInt; else if (Float.class.isAssignableFrom(attribute.getJavaType()) || float.class.isAssignableFrom(attribute.getJavaType()) || Double.class.isAssignableFrom(attribute.getJavaType()) || double.class.isAssignableFrom(attribute.getJavaType())) return Scalars.GraphQLFloat; else if (Long.class.isAssignableFrom(attribute.getJavaType()) || long.class.isAssignableFrom(attribute.getJavaType())) return Scalars.GraphQLLong; else if (Boolean.class.isAssignableFrom(attribute.getJavaType()) || boolean.class.isAssignableFrom(attribute.getJavaType())) return Scalars.GraphQLBoolean; else if (attribute.getJavaType().isEnum()) { return getTypeFromJavaType(attribute.getJavaType()); } } else if (attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.ONE_TO_MANY || attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.MANY_TO_MANY) { EntityType foreignType = (EntityType) ((PluralAttribute) attribute).getElementType(); return new GraphQLList(new GraphQLTypeReference(foreignType.getName())); } else if (attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.MANY_TO_ONE || attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.ONE_TO_ONE) { EntityType foreignType = (EntityType) ((SingularAttribute) attribute).getType(); return new GraphQLTypeReference(foreignType.getName()); } else if (attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.ELEMENT_COLLECTION) { Type foreignType = ((PluralAttribute) attribute).getElementType(); return new GraphQLList(getTypeFromJavaType(foreignType.getJavaType())); } throw new UnsupportedOperationException("Attribute could not be mapped to GraphQL: " + attribute); } private boolean isValidInput(Attribute attribute) { return attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.BASIC || attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.ELEMENT_COLLECTION; } private String getSchemaDocumentation(Member member) { if (member instanceof AnnotatedElement) { return getSchemaDocumentation((AnnotatedElement) member); } return null; } private String getSchemaDocumentation(AnnotatedElement annotatedElement) { if (annotatedElement != null) { SchemaDocumentation schemaDocumentation = annotatedElement.getAnnotation(SchemaDocumentation.class); return schemaDocumentation != null ? schemaDocumentation.value() : null; } return null; } private GraphQLType getTypeFromJavaType(Class clazz) { if (clazz.isEnum()) { GraphQLEnumType.Builder enumBuilder = GraphQLEnumType.newEnum().name(clazz.getSimpleName()); int ordinal = 0; for (Enum enumValue : ((Class<Enum>)clazz).getEnumConstants()) enumBuilder.value(enumValue.name(), ordinal++); GraphQLType answer = enumBuilder.build(); setIdentityCoercing(answer); return answer; } return null; } /** * A bit of a hack, since JPA will deserialize our Enum's for us...we don't want GraphQL doing it. * * @param type */ private void setIdentityCoercing(GraphQLType type) { try { Field coercing = type.getClass().getDeclaredField("coercing"); coercing.setAccessible(true); coercing.set(type, new IdentityCoercing()); } catch (Exception e) { log.error("Unable to set coercing for " + type, e); } } private static final GraphQLArgument paginationArgument = GraphQLArgument.newArgument() .name(PAGINATION_REQUEST_PARAM_NAME) .type(GraphQLInputObjectType.newInputObject() .name("PaginationObject") .description("Query object for Pagination Requests, specifying the requested page, and that page's size.\n\nNOTE: 'page' parameter is 1-indexed, NOT 0-indexed.\n\nExample: paginationRequest { page: 1, size: 20 }") .field(GraphQLInputObjectField.newInputObjectField().name("page").description("Which page should be returned, starting with 1 (1-indexed)").type(Scalars.GraphQLInt).build()) .field(GraphQLInputObjectField.newInputObjectField().name("size").description("How many results should this page contain").type(Scalars.GraphQLInt).build()) .build() ).build(); private static final GraphQLEnumType orderByDirectionEnum = GraphQLEnumType.newEnum() .name("OrderByDirection") .description("Describes the direction (Ascending / Descending) to sort a field.") .value("ASC", 0, "Ascending") .value("DESC", 1, "Descending") .build(); }
package org.dita.dost.reader; import static org.dita.dost.util.Constants.*; import static org.dita.dost.util.Configuration.*; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Stack; import java.util.Map.Entry; import org.apache.xerces.xni.grammars.XMLGrammarPool; import org.dita.dost.exception.DITAOTException; import org.dita.dost.exception.DITAOTXMLErrorHandler; import org.dita.dost.log.MessageBean; import org.dita.dost.log.MessageUtils; import org.dita.dost.module.GenMapAndTopicListModule.KeyDef; import org.dita.dost.reader.GenListModuleReader.Reference; import org.dita.dost.util.CatalogUtils; import org.dita.dost.util.DITAAttrUtils; import org.dita.dost.util.FileUtils; import org.dita.dost.util.FilterUtils; import org.dita.dost.util.OutputUtils; import org.dita.dost.util.StringUtils; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; /** * This class extends AbstractReader, used to parse relevant dita topics * and ditamap files for GenMapAndTopicListModule. * * <p><strong>Not thread-safe</strong>. Instances can be reused by calling * {@link #reset()} between calls to {@link #parse(File)}.</p> * * @version 1.0 2004-11-25 * * @author Wu, Zhi Qiang */ public final class GenListModuleReader extends AbstractXMLReader { /** XMLReader instance for parsing dita file */ private XMLReader reader = null; /** Filter utils */ private FilterUtils filterUtils; /** Output utilities */ private OutputUtils outputUtils; /** Basedir of the current parsing file */ private String currentDir = null; /** Flag for conref in parsing file */ private boolean hasConRef = false; /** Flag for href in parsing file */ private boolean hasHref = false; /** Flag for keyref in parsing file */ private boolean hasKeyRef = false; /** Flag for whether parsing file contains coderef */ private boolean hasCodeRef = false; /** Set of all the non-conref and non-copyto targets refered in current parsing file */ private final Set<Reference> nonConrefCopytoTargets; /** Set of conref targets refered in current parsing file */ private final Set<String> conrefTargets; /** Set of href nonConrefCopytoTargets refered in current parsing file */ private final Set<String> hrefTargets; /** Set of href targets with anchor appended */ private final Set<String> hrefTopicSet; /** Set of chunk targets */ private final Set<String> chunkTopicSet; /** Set of subject schema files */ private final Set<String> schemeSet; /** Set of subsidiary files */ private final Set<String> subsidiarySet; /** Set of sources of those copy-to that were ignored */ private final Set<String> ignoredCopytoSourceSet; /** Map of copy-to target to souce */ private final Map<String, String> copytoMap; /** Map of key definitions */ private final Map<String, KeyDef> keysDefMap; /** Map to store multi-level keyrefs */ private final Map<String, String>keysRefMap; /** Flag for conrefpush */ private boolean hasconaction = false; /** Flag used to mark if parsing entered into excluded element */ private boolean insideExcludedElement = false; /** Used to record the excluded level */ private int excludedLevel = 0; /** foreign/unknown nesting level */ private int foreignLevel = 0; /** chunk nesting level */ private int chunkLevel = 0; /** mark topics in reltables */ private int relTableLevel = 0; /** chunk to-navigation level */ private int chunkToNavLevel = 0; /** Topic group nesting level */ private int topicGroupLevel = 0; /** Flag used to mark if current file is still valid after filtering */ private boolean isValidInput = false; /** Contains the attribution specialization from props */ private String[][] props; /** Set of outer dita files */ private final Set<String> outDitaFilesSet; /** Absolute system path to input file parent directory */ private File rootDir = null; /** Absolute system path to file being processed */ private File currentFile=null; private File rootFilePath=null; private boolean setSystemid = true; /** Stack for @processing-role value */ private final Stack<String> processRoleStack; /** Depth inside a @processing-role parent */ private int processRoleLevel; /** Topics with processing role of "resource-only" */ private final Set<String> resourceOnlySet; /** Topics with processing role of "normal" */ private final Set<String> crossSet; private final Set<String> schemeRefSet; /** Subject scheme document root */ //private Document schemeRoot = null; /** Current processing node */ //private Element currentElement = null; /** Relationship graph between subject schema */ private Map<String, Set<String>> relationGraph = null; private List<ExportAnchor> resultList = new ArrayList<ExportAnchor>(); private ExportAnchor currentExportAnchor; /** Flag to show whether a file has <exportanchors> tag */ private boolean hasExport = false; /** For topic/dita files whether a </file> tag should be added */ private boolean shouldAppendEndTag = false; /** Store the href of topicref tag */ private String topicHref = ""; /** Topicmeta set for merge multiple exportanchors into one. * Each topicmeta/prolog can define many exportanchors */ private final Set<String> topicMetaSet; /** Refered topic id */ private String topicId = ""; /** Map to store plugin id */ private final Map<String, Set<String>> pluginMap = new HashMap<String, Set<String>>(); /** Transtype */ private String transtype; /** Map to store referenced branches. */ private final Map<String, List<String>> vaildBranches; /** Int to mark referenced nested elements. */ private int level; /** Topicref stack */ private final Stack<String> topicrefStack; /** Store the primary ditamap file name. */ private String primaryDitamap = ""; /** Get DITAAttrUtil */ private final DITAAttrUtils ditaAttrUtils = DITAAttrUtils.getInstance(); /** Store the external/peer keydefs */ private final Map<String, String> exKeysDefMap; /** File extension of source file. */ private String extName = null; /** * Constructor. */ public GenListModuleReader() { nonConrefCopytoTargets = new HashSet<Reference>(INT_64); hrefTargets = new HashSet<String>(INT_32); hrefTopicSet = new HashSet<String>(INT_32); chunkTopicSet = new HashSet<String>(INT_32); schemeSet = new HashSet<String>(INT_32); schemeRefSet = new HashSet<String>(INT_32); conrefTargets = new HashSet<String>(INT_32); copytoMap = new HashMap<String, String>(INT_16); subsidiarySet = new HashSet<String>(INT_16); ignoredCopytoSourceSet = new HashSet<String>(INT_16); outDitaFilesSet=new HashSet<String>(INT_64); keysDefMap = new HashMap<String, KeyDef>(); keysRefMap = new HashMap<String, String>(); exKeysDefMap = new HashMap<String, String>(); processRoleLevel = 0; processRoleStack = new Stack<String>(); resourceOnlySet = new HashSet<String>(INT_32); crossSet = new HashSet<String>(INT_32); //store the topicmeta element topicMetaSet = new HashSet<String>(INT_16); vaildBranches = new HashMap<String, List<String>>(INT_32); level = 0; topicrefStack = new Stack<String>(); //schemeRoot = null; //currentElement = null; props = null; try { reader = StringUtils.getXMLReader(); } catch (final SAXException e) { throw new RuntimeException("Unable to create XML parser: " + e.getMessage(), e); } reader.setContentHandler(this); try { reader.setProperty(LEXICAL_HANDLER_PROPERTY,this); } catch (final SAXNotRecognizedException e1) { logger.logException(e1); } catch (final SAXNotSupportedException e1) { logger.logException(e1); } } /** * Get transtype. * @return the transtype */ public String getTranstype() { return transtype; } /** * Set transtype. * @param transtype the transtype to set */ public void setTranstype(final String transtype) { this.transtype = transtype; } /** * Set temporary file extension. * @param extName file extension */ public void setExtName(final String extName) { this.extName = extName; } /** * @return the pluginMap */ public Map<String, Set<String>> getPluginMap() { return pluginMap; } /** * Get export anchors. * * @return list of export anchors */ public List<ExportAnchor> getExportAnchors() { return resultList; } /** * Set content filter. * * @param filterUtils filter utils */ public void setFilterUtils(final FilterUtils filterUtils) { this.filterUtils = filterUtils; } /** * Set output utilities. * @param outputUtils output utils */ public void setOutputUtils(final OutputUtils outputUtils) { this.outputUtils = outputUtils; } /** * Get out file set. * @return out file set */ public Set<String> getOutFilesSet(){ return outDitaFilesSet; } /** * @return the hrefTopicSet */ public Set<String> getHrefTopicSet() { return hrefTopicSet; } /** * @return the chunkTopicSet */ public Set<String> getChunkTopicSet() { return chunkTopicSet; } /** * Get scheme set. * @return scheme set */ public Set<String> getSchemeSet() { return this.schemeSet; } /** * Get scheme ref set. * @return scheme ref set */ public Set<String> getSchemeRefSet() { return this.schemeRefSet; } /** * List of files with "@processing-role=resource-only". * @return the resource-only set */ public Set<String> getResourceOnlySet() { resourceOnlySet.removeAll(crossSet); return resourceOnlySet; } /** * Get document root of the merged subject schema. * @return */ //public Document getSchemeRoot() { // return schemeRoot; /** * Get getRelationshipGrap. Keys are paths of normal map files and values * are paths of subject scheme maps. * * @return relationship grap */ public Map<String, Set<String>> getRelationshipGrap() { return this.relationGraph; } public String getPrimaryDitamap() { return primaryDitamap; } public void setPrimaryDitamap(final String primaryDitamap) { this.primaryDitamap = primaryDitamap; } /** * To see if the parsed file has conref inside. * * @return true if has conref and false otherwise */ public boolean hasConRef() { return hasConRef; } /** * To see if the parsed file has keyref inside. * * @return true if has keyref and false otherwise */ public boolean hasKeyRef(){ return hasKeyRef; } /** * To see if the parsed file has coderef inside. * * @return true if has coderef and false otherwise */ public boolean hasCodeRef(){ return hasCodeRef; } /** * To see if the parsed file has href inside. * * @return true if has href and false otherwise */ public boolean hasHref() { return hasHref; } /** * Get all targets except copy-to. * * @return set of target file path with option format after {@link org.dita.dost.util.Constants#STICK STICK} */ public Set<Reference> getNonCopytoResult() { final Set<Reference> nonCopytoSet = new HashSet<Reference>(INT_128); nonCopytoSet.addAll(nonConrefCopytoTargets); for (final String f: conrefTargets) { nonCopytoSet.add(new Reference(f)); } for (final String f: copytoMap.values()) { nonCopytoSet.add(new Reference(f)); } for (final String f: ignoredCopytoSourceSet) { nonCopytoSet.add(new Reference(f)); } for(final String filename : subsidiarySet){ //only activated on /generateout:3 & is out file. if(isOutFile(filename) && OutputUtils.getGeneratecopyouter() == OutputUtils.Generate.OLDSOLUTION){ nonCopytoSet.add(new Reference(filename)); } } //nonCopytoSet.addAll(subsidiarySet); return nonCopytoSet; } /** * Get the href target. * * @return Returns the hrefTargets. */ public Set<String> getHrefTargets() { return hrefTargets; } /** * Get conref targets. * * @return Returns the conrefTargets. */ public Set<String> getConrefTargets() { return conrefTargets; } /** * Get subsidiary targets. * * @return Returns the subsidiarySet. */ public Set<String> getSubsidiaryTargets() { return subsidiarySet; } /** * Get outditafileslist. * * @return Returns the outditafileslist. */ public Set<String> getOutDitaFilesSet(){ return outDitaFilesSet; } /** * Get non-conref and non-copyto targets. * * @return Returns the nonConrefCopytoTargets. */ public Set<String> getNonConrefCopytoTargets() { final Set<String> res = new HashSet<String>(nonConrefCopytoTargets.size()); for (final Reference r: nonConrefCopytoTargets) { res.add(r.filename); } return res; } /** * Returns the ignoredCopytoSourceSet. * * @return Returns the ignoredCopytoSourceSet. */ public Set<String> getIgnoredCopytoSourceSet() { return ignoredCopytoSourceSet; } /** * Get the copy-to map. * * @return copy-to map */ public Map<String, String> getCopytoMap() { return copytoMap; } /** * Get the Key definitions. * * @return Key definitions map */ public Map<String, KeyDef> getKeysDMap(){ return keysDefMap; } public Map<String, String> getExKeysDefMap() { return exKeysDefMap; } /** * Set the relative directory of current file. * * @param dir dir */ public void setCurrentDir(final String dir) { this.currentDir = dir; } /** * Check if the current file is valid after filtering. * * @return true if valid and false otherwise */ public boolean isValidInput() { return isValidInput; } /** * Check if the current file has conaction. * @return true if has conaction and false otherwise */ public boolean hasConaction(){ return hasconaction; } /** * Init xml reader used for pipeline parsing. * * @param ditaDir absolute path to DITA-OT directory * @param validate whether validate input file * @param rootFile absolute path to input file * @throws SAXException parsing exception * @throws IOException if getting canonical file path fails */ public void initXMLReader(final File ditaDir,final boolean validate,final File rootFile, final boolean arg_setSystemid) throws SAXException, IOException { //final DITAOTJavaLogger javaLogger=new DITAOTJavaLogger(); //to check whether the current parsing file's href value is out of inputmap.dir rootDir=rootFile.getParentFile().getCanonicalFile(); rootFilePath=rootFile.getCanonicalFile(); reader.setFeature(FEATURE_NAMESPACE_PREFIX, true); if(validate==true){ reader.setFeature(FEATURE_VALIDATION, true); try { reader.setFeature(FEATURE_VALIDATION_SCHEMA, true); } catch (final SAXNotRecognizedException e) { // Not Xerces, ignore exception } }else{ final String msg=MessageUtils.getInstance().getMessage("DOTJ037W").toString(); logger.logWarn(msg); } final XMLGrammarPool grammarPool = GrammarPoolManager.getGrammarPool(); setGrammarPool(reader, grammarPool); CatalogUtils.setDitaDir(ditaDir); setSystemid= arg_setSystemid; reader.setEntityResolver(CatalogUtils.getCatalogResolver()); } /** * * Reset the internal variables. */ public void reset() { hasKeyRef = false; hasConRef = false; hasHref = false; hasCodeRef = false; currentDir = null; insideExcludedElement = false; excludedLevel = 0; foreignLevel = 0; chunkLevel = 0; relTableLevel = 0; chunkToNavLevel = 0; topicGroupLevel = 0; isValidInput = false; hasconaction = false; nonConrefCopytoTargets.clear(); hrefTargets.clear(); hrefTopicSet.clear(); chunkTopicSet.clear(); conrefTargets.clear(); copytoMap.clear(); ignoredCopytoSourceSet.clear(); outDitaFilesSet.clear(); keysDefMap.clear(); keysRefMap.clear(); exKeysDefMap.clear(); schemeSet.clear(); schemeRefSet.clear(); //clear level level = 0; //clear stack topicrefStack.clear(); //@processing-role processRoleLevel = 0; processRoleStack.clear(); //reset utils ditaAttrUtils.reset(); /* * Don't clean up these sets, we need them through * the whole phase to determine a topic's processing-role. */ //resourceOnlySet.clear(); //crossSet.clear(); } /** * Parse input xml file. * * @param file file * @throws SAXException SAXException * @throws IOException IOException * @throws FileNotFoundException FileNotFoundException */ public void parse(final File file) throws FileNotFoundException, IOException, SAXException { currentFile=file.getAbsoluteFile(); reader.setErrorHandler(new DITAOTXMLErrorHandler(file.getName(), logger)); final InputSource is = new InputSource(new FileInputStream(file)); //Set the system ID if(setSystemid) { //is.setSystemId(URLUtil.correct(file).toString()); is.setSystemId(file.toURI().toURL().toString()); } reader.parse(is); } /** * Check if the current file is a ditamap with "@processing-role=resource-only". */ @Override public void startDocument() throws SAXException { final String href = FileUtils.getRelativePath(rootFilePath.getAbsolutePath(), currentFile.getAbsolutePath()); if (FileUtils.isDITAMapFile(currentFile.getName()) && resourceOnlySet.contains(href) && !crossSet.contains(href)) { processRoleLevel++; processRoleStack.push(ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY); } } @Override public void startElement(final String uri, final String localName, final String qName, final Attributes atts) throws SAXException { String domains = null; final Properties params = new Properties(); final String printValue = atts.getValue(ATTRIBUTE_NAME_PRINT); //increase element level for nested tags. ditaAttrUtils.increasePrintLevel(printValue); //Exclude the topic if it is needed. if(ditaAttrUtils.needExcludeForPrintAttri(transtype)){ return; } final String processingRole = atts.getValue(ATTRIBUTE_NAME_PROCESSING_ROLE); final String href = atts.getValue(ATTRIBUTE_NAME_HREF); final String scope = atts.getValue(ATTRIBUTE_NAME_SCOPE); if (processingRole != null) { processRoleStack.push(processingRole); processRoleLevel++; if (ATTR_SCOPE_VALUE_EXTERNAL.equals(scope)) { } else if (ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equals(processingRole)) { if (href != null) { resourceOnlySet.add(FileUtils.resolveFile(currentDir, href)); } } else if (ATTR_PROCESSING_ROLE_VALUE_NORMAL.equalsIgnoreCase(processingRole)) { if (href != null) { crossSet.add(FileUtils.resolveFile(currentDir, href)); } } } else if (processRoleLevel > 0) { processRoleLevel++; if (ATTR_SCOPE_VALUE_EXTERNAL.equals(scope)) { } else if (ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equalsIgnoreCase( processRoleStack.peek())) { if (href != null) { resourceOnlySet.add(FileUtils.resolveFile(currentDir, href)); } } else if (ATTR_PROCESSING_ROLE_VALUE_NORMAL.equalsIgnoreCase( processRoleStack.peek())) { if (href != null) { crossSet.add(FileUtils.resolveFile(currentDir, href)); } } } else { if (href != null) { crossSet.add(FileUtils.resolveFile(currentDir, href)); } } final String classValue = atts.getValue(ATTRIBUTE_NAME_CLASS); //has class attribute if(classValue!=null){ //when meets topic tag if(TOPIC_TOPIC.matches(classValue)){ topicId = atts.getValue(ATTRIBUTE_NAME_ID); //relpace place holder with first topic id //Get relative file name final String filename = FileUtils.getRelativePath( rootFilePath.getAbsolutePath(), currentFile.getAbsolutePath()); for (final ExportAnchor e: resultList) { if (e.topicids.contains(filename + QUESTION)) { e.topicids.add(topicId); e.topicids.remove(filename + QUESTION); } } } // WEK: As of 14 Dec 2009, transtype is sometimes null, not sure under what conditions. // System.out.println(" + [DEBUG] transtype=" + transtype); //get plugin id only transtype = eclipsehelp if(FileUtils.isDITAMapFile(currentFile.getName())&& rootFilePath.equals(currentFile)&& MAP_MAP.matches(classValue)&& INDEX_TYPE_ECLIPSEHELP.equals(transtype)){ String pluginId = atts.getValue(ATTRIBUTE_NAME_ID); if(pluginId == null){ pluginId = "org.sample.help.doc"; } final Set<String> set = StringUtils.restoreSet(pluginId); pluginMap.put("pluginId", set); } //merge multiple exportanchors into one //Each <topicref> can only have one <topicmeta>. //Each <topic> can only have one <prolog> //and <metadata> can have more than one exportanchors if (INDEX_TYPE_ECLIPSEHELP.equals(transtype)) { if (MAP_TOPICMETA.matches(classValue) || TOPIC_PROLOG.matches(classValue)) { topicMetaSet.add(qName); } // If the file has <exportanchors> tags only transtype = // eclipsehelp if (DELAY_D_EXPORTANCHORS.matches(classValue)) { hasExport = true; // If current file is a ditamap file if (FileUtils.isDITAMapFile(currentFile.getName())) { // if dita file's extension name is ".xml" String editedHref = ""; if (topicHref.endsWith(FILE_EXTENSION_XML)) { // change the extension to ".dita" for latter // compare editedHref = topicHref.replace( FILE_EXTENSION_XML, FILE_EXTENSION_DITA); } else { editedHref = topicHref; } // editedHref = editedHref.replace(File.separator, "/"); currentExportAnchor = new ExportAnchor(editedHref); // if <exportanchors> is defined in topicmeta(topicref), // there is only one topic id currentExportAnchor.topicids.add(topicId); // If current file is topic file } else if (FileUtils.isDITATopicFile(currentFile.getName())) { String filename = FileUtils.getRelativePath( rootFilePath.getAbsolutePath(), currentFile.getAbsolutePath()); // if dita file's extension name is ".xml" if (filename.endsWith(FILE_EXTENSION_XML)) { // change the extension to ".dita" for latter // compare filename = filename.replace( FILE_EXTENSION_XML, FILE_EXTENSION_DITA); } // filename = FileUtils.normalizeDirectory(currentDir, // filename); filename = FileUtils.separatorsToUnix(filename); currentExportAnchor = new ExportAnchor(filename); // if <exportanchors> is defined in metadata(topic), // there can be many topic ids currentExportAnchor.topicids.add(topicId); shouldAppendEndTag = true; } // meet <anchorkey> tag } else if (DELAY_D_ANCHORKEY.matches(classValue)) { // create keyref element in the StringBuffer // TODO in topic file is no keys final String keyref = atts .getValue(ATTRIBUTE_NAME_KEYREF); currentExportAnchor.keys.add(keyref); // meet <anchorid> tag } else if (DELAY_D_ANCHORID.matches(classValue)) { // create keyref element in the StringBuffer final String id = atts.getValue(ATTRIBUTE_NAME_ID); // If current file is a ditamap file // The id can only be element id within a topic if (FileUtils.isDITAMapFile(currentFile.getName())) { // only for dita format /* * if(!"".equals(topicHref)){ String absolutePathToFile * = FileUtils.resolveFile((new * File(rootFilePath)).getParent(),topicHref); //whether * the id is a topic id * if(FileUtils.isDITAFile(absolutePathToFile)){ found = * DelayConrefUtils * .getInstance().findTopicId(absolutePathToFile, id); } * //other format file }else{ found = false; } */ // id shouldn't be same as topic id in the case of duplicate insert if (!topicId.equals(id)) { currentExportAnchor.ids.add(id); } } else if (FileUtils.isDITATopicFile(currentFile.getName())) { // id shouldn't be same as topic id in the case of duplicate insert if (!topicId.equals(id)) { // topic id found currentExportAnchor.ids.add(id); } } } } } // Generate Scheme relationship graph if (classValue != null) { if (SUBJECTSCHEME_SUBJECTSCHEME.matches(classValue)) { if (this.relationGraph == null) { this.relationGraph = new LinkedHashMap<String, Set<String>>(); } //Make it easy to do the BFS later. Set<String> children = this.relationGraph.get("ROOT"); if (children == null || children.isEmpty()) { children = new LinkedHashSet<String>(); } children.add(this.currentFile.getAbsolutePath()); this.relationGraph.put("ROOT", children); schemeRefSet.add(FileUtils.getRelativePath(rootFilePath.getAbsolutePath(), currentFile.getAbsolutePath())); } else if (SUBJECTSCHEME_SCHEMEREF.matches(classValue)) { Set<String> children = this.relationGraph.get(this.currentFile.getAbsolutePath()); if (children == null) { children = new LinkedHashSet<String>(); this.relationGraph.put(currentFile.getAbsolutePath(), children); } if (href != null) { children.add(FileUtils.resolveFile(rootDir.getAbsolutePath(), href)); } } } if(foreignLevel > 0){ //if it is an element nested in foreign/unknown element //do not parse it foreignLevel ++; return; } else if(classValue != null && (TOPIC_FOREIGN.matches(classValue) || TOPIC_UNKNOWN.matches(classValue))){ foreignLevel ++; } if(chunkLevel > 0) { chunkLevel++; } else if(atts.getValue(ATTRIBUTE_NAME_CHUNK) != null) { chunkLevel++; } if(relTableLevel > 0) { relTableLevel ++; } else if(classValue != null && MAP_RELTABLE.matches(classValue)){ relTableLevel++; } if(chunkToNavLevel > 0) { chunkToNavLevel++; } else if(atts.getValue(ATTRIBUTE_NAME_CHUNK) != null && atts.getValue(ATTRIBUTE_NAME_CHUNK).indexOf("to-navigation") != -1){ chunkToNavLevel++; } if(topicGroupLevel > 0) { topicGroupLevel++; } else if (atts.getValue(ATTRIBUTE_NAME_CLASS) != null && atts.getValue(ATTRIBUTE_NAME_CLASS).contains(MAPGROUP_D_TOPICGROUP.matcher)) { topicGroupLevel++; } if(classValue==null && !ELEMENT_NAME_DITA.equals(localName)){ params.clear(); params.put("%1", localName); logger.logInfo(MessageUtils.getInstance().getMessage("DOTJ030I", params).toString()); } if (classValue != null && TOPIC_TOPIC.matches(classValue)){ domains = atts.getValue(ATTRIBUTE_NAME_DOMAINS); if(domains==null){ params.clear(); params.put("%1", localName); logger.logInfo(MessageUtils.getInstance().getMessage("DOTJ029I", params).toString()); } else { props = StringUtils.getExtProps(domains); } } if (insideExcludedElement) { ++excludedLevel; return; } // Ignore element that has been filtered out. if (filterUtils.needExclude(atts, props)) { insideExcludedElement = true; ++excludedLevel; return; } /* * For ditamap, set it to valid if element <map> or extended from * <map> was found, this kind of element's class attribute must * contains 'map/map'; * For topic files, set it to valid if element <title> or extended * from <title> was found, this kind of element's class attribute * must contains 'topic/title'. */ if (classValue != null) { if ((MAP_MAP.matches(classValue)) || (TOPIC_TITLE.matches(classValue))) { isValidInput = true; }else if (TOPIC_OBJECT.matches(classValue)){ parseAttribute(atts, ATTRIBUTE_NAME_DATA); } } //onlyTopicInMap is on. if(outputUtils.getOnlyTopicInMap() && this.canResolved()){ //topicref(only defined in ditamap file.) if(MAP_TOPICREF.matches(classValue)){ //get href attribute value. final String hrefValue = atts.getValue(ATTRIBUTE_NAME_HREF); //get conref attribute value. final String conrefValue = atts.getValue(ATTRIBUTE_NAME_CONREF); //has href attribute and refer to ditamap file. if(!StringUtils.isEmptyString(hrefValue)){ //exclude external resources final String attrScope = atts.getValue(ATTRIBUTE_NAME_SCOPE); if ("external".equalsIgnoreCase(attrScope) || "peer".equalsIgnoreCase(attrScope) || hrefValue.indexOf(COLON_DOUBLE_SLASH) != -1 || hrefValue.startsWith(SHARP)) { return; } //normalize href value. final File target=new File(hrefValue); //caculate relative path for href value. String fileName = null; if(target.isAbsolute()){ fileName = FileUtils.getRelativePath(rootFilePath.getAbsolutePath(),hrefValue); } fileName = FileUtils.normalizeDirectory(currentDir, hrefValue); //change '\' to '/' for comparsion. fileName = FileUtils.separatorsToUnix(fileName); final boolean canParse = parseBranch(atts, hrefValue, fileName); if(!canParse){ return; }else{ topicrefStack.push(localName); } }else if(!StringUtils.isEmptyString(conrefValue)){ //exclude external resources final String attrScope = atts.getValue(ATTRIBUTE_NAME_SCOPE); if ("external".equalsIgnoreCase(attrScope) || "peer".equalsIgnoreCase(attrScope) || conrefValue.indexOf(COLON_DOUBLE_SLASH) != -1 || conrefValue.startsWith(SHARP)) { return; } //normalize href value. final File target=new File(conrefValue); //caculate relative path for href value. String fileName = null; if(target.isAbsolute()){ fileName = FileUtils.getRelativePath(rootFilePath.getAbsolutePath(),conrefValue); } fileName = FileUtils.normalizeDirectory(currentDir, conrefValue); //change '\' to '/' for comparsion. fileName = FileUtils.separatorsToUnix(fileName); final boolean canParse = parseBranch(atts, conrefValue, fileName); if(!canParse){ return; }else{ topicrefStack.push(localName); } } } } parseAttribute(atts, ATTRIBUTE_NAME_CONREF); parseAttribute(atts, ATTRIBUTE_NAME_HREF); parseAttribute(atts, ATTRIBUTE_NAME_COPY_TO); parseAttribute(atts, ATTRIBUTE_NAME_IMG); parseAttribute(atts, ATTRIBUTE_NAME_CONACTION); parseAttribute(atts, ATTRIBUTE_NAME_KEYS); parseAttribute(atts, ATTRIBUTE_NAME_CONKEYREF); parseAttribute(atts, ATTRIBUTE_NAME_KEYREF); } @Override public void endElement(final String uri, final String localName, final String qName) throws SAXException { //subject scheme //if (currentElement != null && currentElement != schemeRoot.getDocumentElement()) { // currentElement = (Element)currentElement.getParentNode(); //@processing-role if (processRoleLevel > 0) { if (processRoleLevel == processRoleStack.size()) { processRoleStack.pop(); } processRoleLevel } if (foreignLevel > 0){ foreignLevel return; } if (chunkLevel > 0) { chunkLevel } if (relTableLevel > 0) { relTableLevel } if (chunkToNavLevel > 0) { chunkToNavLevel } if (topicGroupLevel > 0) { topicGroupLevel } if (insideExcludedElement) { // end of the excluded element, mark the flag as false if (excludedLevel == 1) { insideExcludedElement = false; } --excludedLevel; } //<exportanchors> over should write </file> tag if(topicMetaSet.contains(qName) && hasExport){ //If current file is a ditamap file if(FileUtils.isDITAMapFile(currentFile.getName())){ resultList.add(currentExportAnchor); currentExportAnchor = null; //If current file is topic file } hasExport = false; topicMetaSet.clear(); } if(!topicrefStack.isEmpty() && localName.equals(topicrefStack.peek())){ level topicrefStack.pop(); } //decrease element level. ditaAttrUtils.decreasePrintLevel(); } /** * Clean up. */ @Override public void endDocument() throws SAXException { if (processRoleLevel > 0) { processRoleLevel processRoleStack.pop(); } if(FileUtils.isDITATopicFile(currentFile.getName()) && shouldAppendEndTag){ resultList.add(currentExportAnchor); currentExportAnchor = null; //should reset shouldAppendEndTag = false; } checkMultiLevelKeys(keysDefMap, keysRefMap); } /** * Method for see whether a branch should be parsed. * @param atts {@link Attributes} * @param hrefValue {@link String} * @param fileName normalized file name(remove '#') * @return boolean */ private boolean parseBranch(final Attributes atts, final String hrefValue, final String fileName) { //current file is primary ditamap file. //parse every branch. final String currentFileRelative = FileUtils.getRelativePath( rootFilePath.getAbsolutePath(), currentFile.getAbsolutePath()); if(currentDir == null && currentFileRelative.equals(primaryDitamap)){ //add branches into map addReferredBranches(hrefValue, fileName); return true; }else{ //current file is a sub-ditamap one. //get branch's id final String id = atts.getValue(ATTRIBUTE_NAME_ID); //this branch is not referenced if(level == 0 && StringUtils.isEmptyString(id)){ //There is occassion that the whole ditamap should be parsed final boolean found = searchBrachesMap(id); if(found){ //Add this branch into map for parsing. addReferredBranches(hrefValue, fileName); //update level level++; return true; }else{ return false; } //this brach is a decendent of a referenced one }else if(level != 0){ //Add this branch into map for parsing. addReferredBranches(hrefValue, fileName); //update level level++; return true; //This branch has an id but is a new one }else if(!StringUtils.isEmptyString(id)){ //search branches map. final boolean found = searchBrachesMap(id); //branch is referenced if(found){ //Add this branch into map for parsing. addReferredBranches(hrefValue, fileName); //update level level ++; return true; }else{ //this branch is not referenced return false; } }else{ return false; } } } /** * Search braches map with branch id and current file name. * @param id String branch id. * @return boolean true if found and false otherwise. */ private boolean searchBrachesMap(final String id) { //caculate relative path for current file. final String currentFileRelative = FileUtils.getRelativePath( rootFilePath.getAbsolutePath(), currentFile.getAbsolutePath()); //seach the map with id & current file name. if(vaildBranches.containsKey(currentFileRelative)){ final List<String> branchIdList = vaildBranches.get(currentFileRelative); //the branch is referenced. if(branchIdList.contains(id)){ return true; }else if(branchIdList.size() == 0){ //the whole map is referenced return true; }else{ //the branch is not referred return false; } }else{ //current file is not refered return false; } } /** * Add branches into map. * @param hrefValue * @param fileName */ private void addReferredBranches(final String hrefValue, final String fileName) { String branchId = null; //href value has branch id. if(hrefValue.contains(SHARP)){ branchId = hrefValue.substring(hrefValue.lastIndexOf(SHARP) + 1); //The map contains the file name if(vaildBranches.containsKey(fileName)){ final List<String> branchIdList = vaildBranches.get(fileName); branchIdList.add(branchId); }else{ final List<String> branchIdList = new ArrayList<String>(); branchIdList.add(branchId); vaildBranches.put(fileName, branchIdList); } //href value has no branch id }else{ vaildBranches.put(fileName, new ArrayList<String>()); } } /** * Parse the input attributes for needed information. * * @param atts all attributes * @param attrName attributes to process */ private void parseAttribute(final Attributes atts, final String attrName) throws SAXException { String attrValue = atts.getValue(attrName); String filename = null; final String attrClass = atts.getValue(ATTRIBUTE_NAME_CLASS); final String attrScope = atts.getValue(ATTRIBUTE_NAME_SCOPE); final String attrFormat = atts.getValue(ATTRIBUTE_NAME_FORMAT); final String attrType = atts.getValue(ATTRIBUTE_NAME_TYPE); final String codebase = atts.getValue(ATTRIBUTE_NAME_CODEBASE); if (attrValue == null) { return; } // @conkeyref will be resolved to @conref in Debug&Fileter step if (ATTRIBUTE_NAME_CONREF.equals(attrName) || ATTRIBUTE_NAME_CONKEYREF.equals(attrName)) { hasConRef = true; } else if (ATTRIBUTE_NAME_HREF.equals(attrName)) { if(attrClass != null && PR_D_CODEREF.matches(attrClass) ){ //if current element is <coderef> or its specialization //set hasCodeRef to true hasCodeRef = true; }else{ hasHref = true; } } else if(ATTRIBUTE_NAME_KEYREF.equals(attrName)){ hasKeyRef = true; } // collect the key definitions if(ATTRIBUTE_NAME_KEYS.equals(attrName) && attrValue.length() != 0){ String target = atts.getValue(ATTRIBUTE_NAME_HREF); if (target != null && (attrFormat == null || attrFormat.equals(ATTR_FORMAT_VALUE_DITA)) && extName != null) { target = FileUtils.replaceExtension(target, extName); } final String keyRef = atts.getValue(ATTRIBUTE_NAME_KEYREF); final String copy_to = atts.getValue(ATTRIBUTE_NAME_COPY_TO); if (!StringUtils.isEmptyString(copy_to)) { target = copy_to; } //avoid NullPointException if(target == null){ target = ""; } //store the target final String temp = target; // Many keys can be defined in a single definition, like keys="a b c", a, b and c are seperated by blank. for(final String key: attrValue.split(" ")){ if (!isValidKeyName(key)) { logger.logError(MessageUtils.getInstance().getMessage("DOTJ055E", key).toString()); continue; } if(!keysDefMap.containsKey(key) && !key.equals("")){ if(target != null && target.length() != 0){ if(attrScope!=null && (attrScope.equals("external") || attrScope.equals("peer"))){ //store external or peer resources. exKeysDefMap.put(key, target); keysDefMap.put(key, new KeyDef(key, target, null)); }else{ String tail = ""; if(target.indexOf(SHARP) != -1){ tail = target.substring(target.indexOf(SHARP)); target = target.substring(0, target.indexOf(SHARP)); } if(new File(target).isAbsolute()) { target = FileUtils.getRelativePath(rootFilePath.getAbsolutePath(), target); } target = FileUtils.normalizeDirectory(currentDir, target); keysDefMap.put(key, new KeyDef(key, target + tail, null)); } }else if(!StringUtils.isEmptyString(keyRef)){ //store multi-level keys. keysRefMap.put(key, keyRef); }else{ // target is null or empty, it is useful in the future when consider the content of key definition keysDefMap.put(key, new KeyDef(key, null, null)); } }else{ final Properties prop = new Properties(); prop.setProperty("%1", key); prop.setProperty("%2", target); // DOTJ045W also exists, but is commented out of the messages file logger.logInfo(MessageUtils.getInstance().getMessage("DOTJ045I", prop).toString()); } //restore target target = temp; } } /* if (attrValue.startsWith(SHARP) || attrValue.indexOf(COLON_DOUBLE_SLASH) != -1){ return; } */ //external resource is filtered here. if ("external".equalsIgnoreCase(attrScope) || "peer".equalsIgnoreCase(attrScope) || attrValue.indexOf(COLON_DOUBLE_SLASH) != -1 || attrValue.startsWith(SHARP)) { return; } if(attrValue.startsWith("file:/") && attrValue.indexOf("file: attrValue = attrValue.substring("file:/".length()); //Unix like OS if(UNIX_SEPARATOR.equals(File.separator)){ attrValue = UNIX_SEPARATOR + attrValue; } } else if (attrValue.startsWith("file:") && !attrValue.startsWith("file:/")) { attrValue = attrValue.substring("file:".length()); } final File target=new File(attrValue); if(target.isAbsolute() && !ATTRIBUTE_NAME_DATA.equals(attrName)){ attrValue=FileUtils.getRelativePath(rootFilePath.getAbsolutePath(),attrValue); //for object tag bug:3052156 }else if(ATTRIBUTE_NAME_DATA.equals(attrName)){ if(!StringUtils.isEmptyString(codebase)){ filename = FileUtils.normalizeDirectory(codebase, attrValue); }else{ filename = FileUtils.normalizeDirectory(currentDir, attrValue); } }else{ //noraml process. filename = FileUtils.normalizeDirectory(currentDir, attrValue); } filename = toFile(filename); // XXX: At this point, filename should be a system path if (MAP_TOPICREF.matches(attrClass)) { if (ATTR_TYPE_VALUE_SUBJECT_SCHEME.equalsIgnoreCase(attrType)) { schemeSet.add(filename); } //only transtype = eclipsehelp if(INDEX_TYPE_ECLIPSEHELP.equals(transtype)){ //For only format of the href is dita topic if (attrFormat == null || ATTR_FORMAT_VALUE_DITA.equalsIgnoreCase(attrFormat)){ if(attrName.equals(ATTRIBUTE_NAME_HREF)){ topicHref = filename; topicHref = FileUtils.separatorsToUnix(topicHref); //attrValue has topicId if(attrValue.lastIndexOf(SHARP) != -1){ //get the topicId position final int position = attrValue.lastIndexOf(SHARP); topicId = attrValue.substring(position + 1); }else{ //get the first topicId(vaild href file) if(FileUtils.isDITAFile(topicHref)){ //topicId = MergeUtils.getInstance().getFirstTopicId(topicHref, (new File(rootFilePath)).getParent(), true); //to be unique topicId = topicHref + QUESTION; } } } }else{ topicHref = ""; topicId = ""; } } } //files referred by coderef won't effect the uplevels, code has already returned. if (("DITA-foreign".equals(attrType) && ATTRIBUTE_NAME_DATA.equals(attrName)) || attrClass!=null && PR_D_CODEREF.matches(attrClass)){ subsidiarySet.add(filename); return; } /* * Collect non-conref and non-copyto targets */ if (filename != null && FileUtils.isValidTarget(filename.toLowerCase()) && (StringUtils.isEmptyString(atts.getValue(ATTRIBUTE_NAME_COPY_TO)) || !FileUtils.isDITATopicFile(atts.getValue(ATTRIBUTE_NAME_COPY_TO).toLowerCase()) || (atts.getValue(ATTRIBUTE_NAME_CHUNK)!=null && atts.getValue(ATTRIBUTE_NAME_CHUNK).contains("to-content")) ) && !ATTRIBUTE_NAME_CONREF.equals(attrName) && !ATTRIBUTE_NAME_COPY_TO.equals(attrName) && (canResolved() || FileUtils.isSupportedImageFile(filename.toLowerCase()))) { nonConrefCopytoTargets.add(new Reference(filename, attrFormat)); //nonConrefCopytoTargets.add(filename); } //outside ditamap files couldn't cause warning messages, it is stopped here if (attrFormat != null && !ATTR_FORMAT_VALUE_DITA.equalsIgnoreCase(attrFormat)){ //The format of the href is not dita topic //The logic after this "if" clause is not related to files other than dita topic. //Therefore, we need to return here to filter out those files in other format. return; } /* * Collect only href target topic files for index extracting. */ if (ATTRIBUTE_NAME_HREF.equals(attrName) && FileUtils.isDITATopicFile(filename) && canResolved()) { hrefTargets.add(new File(filename).getPath()); toOutFile(new File(filename).getPath()); //use filename instead(It has already been resolved before-hand) bug:3058124 //String pathWithoutID = FileUtils.resolveFile(currentDir, attrValue); if (chunkLevel > 0 && chunkToNavLevel == 0 && topicGroupLevel == 0 && relTableLevel == 0) { chunkTopicSet.add(filename); } else { hrefTopicSet.add(filename); } } //add a warning message for outer files refered by @data /*if(ATTRIBUTE_NAME_DATA.equals(attrName)){ toOutFile(new File(filename).getPath()); }*/ /* * Collect only conref target topic files. */ if (ATTRIBUTE_NAME_CONREF.equals(attrName) && FileUtils.isDITAFile(filename)) { conrefTargets.add(filename); toOutFile(new File(filename).getPath()); } // Collect copy-to (target,source) into hash map if (ATTRIBUTE_NAME_COPY_TO.equals(attrName) && FileUtils.isDITATopicFile(filename)) { final String href = atts.getValue(ATTRIBUTE_NAME_HREF); final String value = toFile(FileUtils.normalizeDirectory(currentDir, href)); if (StringUtils.isEmptyString(href)) { final StringBuffer buff = new StringBuffer(); buff.append("[WARN]: Copy-to task [href=\"\" copy-to=\""); buff.append(filename); buff.append("\"] was ignored."); logger.logWarn(buff.toString()); } else if (copytoMap.get(filename) != null){ /*StringBuffer buff = new StringBuffer(); buff.append("Copy-to task [href=\""); buff.append(href); buff.append("\" copy-to=\""); buff.append(filename); buff.append("\"] which points to another copy-to target"); buff.append(" was ignored."); javaLogger.logWarn(buff.toString());*/ final Properties prop = new Properties(); prop.setProperty("%1", href); prop.setProperty("%2", filename); if(!value.equals(copytoMap.get(filename))) { logger.logWarn(MessageUtils.getInstance().getMessage("DOTX065W", prop).toString()); } ignoredCopytoSourceSet.add(href); } else if (!(atts.getValue(ATTRIBUTE_NAME_CHUNK) != null && atts.getValue(ATTRIBUTE_NAME_CHUNK).contains("to-content"))){ copytoMap.put(filename, value); } final String pathWithoutID = FileUtils.resolveFile(currentDir, toFile(attrValue)); if (chunkLevel > 0 && chunkToNavLevel == 0 && topicGroupLevel == 0) { chunkTopicSet.add(pathWithoutID); } else { hrefTopicSet.add(pathWithoutID); } } /* * Collect the conaction source topic file */ if(ATTRIBUTE_NAME_CONACTION.equals(attrName)){ if(attrValue.equals("mark")||attrValue.equals("pushreplace")){ hasconaction = true; } } } /** * Convert URI references to file paths. * * @param filename file reference * @return file path */ private String toFile(final String filename) { if (filename == null) { return null; } String f = filename; try{ f = URLDecoder.decode(filename, UTF8); }catch(final UnsupportedEncodingException e){ throw new RuntimeException(e); } if (processingMode == Mode.LAX) { f = f.replace(WINDOWS_SEPARATOR, File.separator); } f = f.replace(URI_SEPARATOR, File.separator); return f; } /** * Validate key name * @param key key name * @return {@code true} if key name is valid, otherwise {@code false} */ public static boolean isValidKeyName(final String key) { for (final char c: key.toCharArray()) { switch(c) { // disallowed characters case '{': case '}': case '[': case ']': case '/': case ' case '?': return false; // URI characters case '-': case '.': case '_': case '~': case ':': case '@': case '!': case '$': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case ';': case '=': break; default: if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))) { return false; } break; } } return true; } /** * Get multi-level keys list */ private List<String> getKeysList(final String key, final Map<String, String> keysRefMap) { final List<String> list = new ArrayList<String>(); //Iterate the map to look for multi-level keys final Iterator<Entry<String, String>> iter = keysRefMap.entrySet().iterator(); while (iter.hasNext()) { final Map.Entry<String, String> entry = iter.next(); //Multi-level key found if(entry.getValue().equals(key)){ //add key into the list final String entryKey = entry.getKey(); list.add(entryKey); //still have multi-level keys if(keysRefMap.containsValue(entryKey)){ //rescuive point final List<String> tempList = getKeysList(entryKey, keysRefMap); list.addAll(tempList); } } } return list; } /** * Update keysDefMap for multi-level keys */ private void checkMultiLevelKeys(final Map<String, KeyDef> keysDefMap, final Map<String, String> keysRefMap) { String key = null; KeyDef value = null; //tempMap storing values to avoid ConcurrentModificationException final Map<String, KeyDef> tempMap = new HashMap<String, KeyDef>(); final Iterator<Entry<String, KeyDef>> iter = keysDefMap.entrySet().iterator(); while (iter.hasNext()) { final Map.Entry<String, KeyDef> entry = iter.next(); key = entry.getKey(); value = entry.getValue(); //there is multi-level keys exist. if(keysRefMap.containsValue(key)){ //get multi-level keys final List<String> keysList = getKeysList(key, keysRefMap); for (final String multikey : keysList) { //update tempMap tempMap.put(multikey, value); } } } //update keysDefMap. keysDefMap.putAll(tempMap); } /** * Check if path walks up in parent directories * * @param toCheckPath path to check * @return {@code true} if path walks up, otherwise {@code false} */ private boolean isOutFile(final String toCheckPath) { if (!toCheckPath.startsWith("..")) { return false; } else { return true; } } /** * Check if {@link #currentFile} is a map * * @return {@code} true if file is map, otherwise {@code false} */ private boolean isMapFile() { final String current=FileUtils.normalize(currentFile.getAbsolutePath()); if(FileUtils.isDITAMapFile(current)) { return true; } else { return false; } } private boolean canResolved(){ if ((outputUtils.getOnlyTopicInMap() == false) || isMapFile() ) { return true; } else { return false; } } private void addToOutFilesSet(final String hrefedFile) { if (canResolved()) { outDitaFilesSet.add(hrefedFile); } } private void toOutFile(final String filename) throws SAXException { //the filename is a relative path from the dita input file final Properties prop=new Properties(); prop.put("%1", FileUtils.normalizeDirectory(rootDir.getAbsolutePath(), filename)); prop.put("%2", FileUtils.normalize(currentFile.getAbsolutePath())); if ((OutputUtils.getGeneratecopyouter() == OutputUtils.Generate.NOT_GENERATEOUTTER) || (OutputUtils.getGeneratecopyouter() == OutputUtils.Generate.GENERATEOUTTER)) { if (isOutFile(filename)) { if (outputUtils.getOutterControl() == OutputUtils.OutterControl.FAIL){ final MessageBean msgBean=MessageUtils.getInstance().getMessage("DOTJ035F", prop); throw new SAXParseException(null,null,new DITAOTException(msgBean,null,msgBean.toString())); } else if (outputUtils.getOutterControl() == OutputUtils.OutterControl.WARN){ final String message=MessageUtils.getInstance().getMessage("DOTJ036W",prop).toString(); logger.logWarn(message); } addToOutFilesSet(filename); } } } /** * File reference with path and optional format. */ public static class Reference { public final String filename; public final String format; public Reference(final String filename, final String format) { this.filename = filename; this.format = format; } public Reference(final String filename) { this(filename, null); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((filename == null) ? 0 : filename.hashCode()); result = prime * result + ((format == null) ? 0 : format.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Reference)) { return false; } Reference other = (Reference) obj; if (filename == null) { if (other.filename != null) { return false; } } else if (!filename.equals(other.filename)) { return false; } if (format == null) { if (other.format != null) { return false; } } else if (!format.equals(other.format)) { return false; } return true; } } public static class ExportAnchor { public final String file; public final Set<String> topicids = new HashSet<String>(); public final Set<String> keys = new HashSet<String>(); public final Set<String> ids = new HashSet<String>(); ExportAnchor(final String file) { this.file = file; } } }
package org.dita.dost.reader; import static org.dita.dost.util.Constants.*; import static org.dita.dost.util.Configuration.*; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Stack; import java.util.Map.Entry; import org.apache.xerces.xni.grammars.XMLGrammarPool; import org.dita.dost.exception.DITAOTException; import org.dita.dost.exception.DITAOTXMLErrorHandler; import org.dita.dost.log.MessageBean; import org.dita.dost.log.MessageUtils; import org.dita.dost.module.GenMapAndTopicListModule.KeyDef; import org.dita.dost.reader.GenListModuleReader.Reference; import org.dita.dost.util.CatalogUtils; import org.dita.dost.util.DITAAttrUtils; import org.dita.dost.util.FileUtils; import org.dita.dost.util.FilterUtils; import org.dita.dost.util.OutputUtils; import org.dita.dost.util.StringUtils; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; /** * This class extends AbstractReader, used to parse relevant dita topics * and ditamap files for GenMapAndTopicListModule. * * <p><strong>Not thread-safe</strong>. Instances can be reused by calling * {@link #reset()} between calls to {@link #parse(File)}.</p> * * @version 1.0 2004-11-25 * * @author Wu, Zhi Qiang */ public final class GenListModuleReader extends AbstractXMLReader { /** XMLReader instance for parsing dita file */ private XMLReader reader = null; /** Filter utils */ private FilterUtils filterUtils; /** Output utilities */ private OutputUtils outputUtils; /** Basedir of the current parsing file */ private String currentDir = null; /** Flag for conref in parsing file */ private boolean hasConRef = false; /** Flag for href in parsing file */ private boolean hasHref = false; /** Flag for keyref in parsing file */ private boolean hasKeyRef = false; /** Flag for whether parsing file contains coderef */ private boolean hasCodeRef = false; /** Set of all the non-conref and non-copyto targets refered in current parsing file */ private final Set<Reference> nonConrefCopytoTargets; /** Set of conref targets refered in current parsing file */ private final Set<String> conrefTargets; /** Set of href nonConrefCopytoTargets refered in current parsing file */ private final Set<String> hrefTargets; /** Set of href targets with anchor appended */ private final Set<String> hrefTopicSet; /** Set of chunk targets */ private final Set<String> chunkTopicSet; /** Set of subject schema files */ private final Set<String> schemeSet; /** Set of subsidiary files */ private final Set<String> subsidiarySet; /** Set of sources of those copy-to that were ignored */ private final Set<String> ignoredCopytoSourceSet; /** Map of copy-to target to souce */ private final Map<String, String> copytoMap; /** Map of key definitions */ private final Map<String, KeyDef> keysDefMap; /** Map to store multi-level keyrefs */ private final Map<String, String>keysRefMap; /** Flag for conrefpush */ private boolean hasconaction = false; /** Flag used to mark if parsing entered into excluded element */ private boolean insideExcludedElement = false; /** Used to record the excluded level */ private int excludedLevel = 0; /** foreign/unknown nesting level */ private int foreignLevel = 0; /** chunk nesting level */ private int chunkLevel = 0; /** mark topics in reltables */ private int relTableLevel = 0; /** chunk to-navigation level */ private int chunkToNavLevel = 0; /** Topic group nesting level */ private int topicGroupLevel = 0; /** Flag used to mark if current file is still valid after filtering */ private boolean isValidInput = false; /** Contains the attribution specialization from props */ private String[][] props; /** Set of outer dita files */ private final Set<String> outDitaFilesSet; /** Absolute system path to input file parent directory */ private File rootDir = null; /** Absolute system path to file being processed */ private File currentFile=null; private File rootFilePath=null; private boolean setSystemid = true; /** Stack for @processing-role value */ private final Stack<String> processRoleStack; /** Depth inside a @processing-role parent */ private int processRoleLevel; /** Topics with processing role of "resource-only" */ private final Set<String> resourceOnlySet; /** Topics with processing role of "normal" */ private final Set<String> crossSet; private final Set<String> schemeRefSet; /** Subject scheme document root */ //private Document schemeRoot = null; /** Current processing node */ //private Element currentElement = null; /** Relationship graph between subject schema */ private Map<String, Set<String>> relationGraph = null; private List<ExportAnchor> resultList = new ArrayList<ExportAnchor>(); private ExportAnchor currentExportAnchor; /** Flag to show whether a file has <exportanchors> tag */ private boolean hasExport = false; /** For topic/dita files whether a </file> tag should be added */ private boolean shouldAppendEndTag = false; /** Store the href of topicref tag */ private String topicHref = ""; /** Topicmeta set for merge multiple exportanchors into one. * Each topicmeta/prolog can define many exportanchors */ private final Set<String> topicMetaSet; /** Refered topic id */ private String topicId = ""; /** Map to store plugin id */ private final Map<String, Set<String>> pluginMap = new HashMap<String, Set<String>>(); /** Transtype */ private String transtype; /** Map to store referenced branches. */ private final Map<String, List<String>> vaildBranches; /** Int to mark referenced nested elements. */ private int level; /** Topicref stack */ private final Stack<String> topicrefStack; /** Store the primary ditamap file name. */ private String primaryDitamap = ""; /** Get DITAAttrUtil */ private final DITAAttrUtils ditaAttrUtils = DITAAttrUtils.getInstance(); /** Store the external/peer keydefs */ private final Map<String, String> exKeysDefMap; /** File extension of source file. */ private String extName = null; /** * Get transtype. * @return the transtype */ public String getTranstype() { return transtype; } /** * Set transtype. * @param transtype the transtype to set */ public void setTranstype(final String transtype) { this.transtype = transtype; } /** * Set temporary file extension. * @param extName file extension */ public void setExtName(final String extName) { this.extName = extName; } /** * @return the pluginMap */ public Map<String, Set<String>> getPluginMap() { return pluginMap; } /** * Get export anchors. * * @return list of export anchors */ public List<ExportAnchor> getExportAnchors() { return resultList; } /** * Constructor. */ public GenListModuleReader() { nonConrefCopytoTargets = new HashSet<Reference>(INT_64); hrefTargets = new HashSet<String>(INT_32); hrefTopicSet = new HashSet<String>(INT_32); chunkTopicSet = new HashSet<String>(INT_32); schemeSet = new HashSet<String>(INT_32); schemeRefSet = new HashSet<String>(INT_32); conrefTargets = new HashSet<String>(INT_32); copytoMap = new HashMap<String, String>(INT_16); subsidiarySet = new HashSet<String>(INT_16); ignoredCopytoSourceSet = new HashSet<String>(INT_16); outDitaFilesSet=new HashSet<String>(INT_64); keysDefMap = new HashMap<String, KeyDef>(); keysRefMap = new HashMap<String, String>(); exKeysDefMap = new HashMap<String, String>(); processRoleLevel = 0; processRoleStack = new Stack<String>(); resourceOnlySet = new HashSet<String>(INT_32); crossSet = new HashSet<String>(INT_32); //store the topicmeta element topicMetaSet = new HashSet<String>(INT_16); vaildBranches = new HashMap<String, List<String>>(INT_32); level = 0; topicrefStack = new Stack<String>(); //schemeRoot = null; //currentElement = null; props = null; try { reader = StringUtils.getXMLReader(); } catch (final SAXException e) { throw new RuntimeException("Unable to create XML parser: " + e.getMessage(), e); } reader.setContentHandler(this); try { reader.setProperty(LEXICAL_HANDLER_PROPERTY,this); } catch (final SAXNotRecognizedException e1) { logger.logException(e1); } catch (final SAXNotSupportedException e1) { logger.logException(e1); } } /** * Set content filter. * * @param filterUtils filter utils */ public void setFilterUtils(final FilterUtils filterUtils) { this.filterUtils = filterUtils; } /** * Set output utilities. * @param outputUtils output utils */ public void setOutputUtils(final OutputUtils outputUtils) { this.outputUtils = outputUtils; } /** * Init xml reader used for pipeline parsing. * * @param ditaDir absolute path to DITA-OT directory * @param validate whether validate input file * @param rootFile absolute path to input file * @throws SAXException parsing exception * @throws IOException if getting canonical file path fails */ public void initXMLReader(final File ditaDir,final boolean validate,final File rootFile, final boolean arg_setSystemid) throws SAXException, IOException { //final DITAOTJavaLogger javaLogger=new DITAOTJavaLogger(); //to check whether the current parsing file's href value is out of inputmap.dir rootDir=rootFile.getParentFile().getCanonicalFile(); rootFilePath=rootFile.getCanonicalFile(); reader.setFeature(FEATURE_NAMESPACE_PREFIX, true); if(validate==true){ reader.setFeature(FEATURE_VALIDATION, true); try { reader.setFeature(FEATURE_VALIDATION_SCHEMA, true); } catch (final SAXNotRecognizedException e) { // Not Xerces, ignore exception } }else{ final String msg=MessageUtils.getInstance().getMessage("DOTJ037W").toString(); logger.logWarn(msg); } final XMLGrammarPool grammarPool = GrammarPoolManager.getGrammarPool(); setGrammarPool(reader, grammarPool); CatalogUtils.setDitaDir(ditaDir); setSystemid= arg_setSystemid; reader.setEntityResolver(CatalogUtils.getCatalogResolver()); } /** * * Reset the internal variables. */ public void reset() { hasKeyRef = false; hasConRef = false; hasHref = false; hasCodeRef = false; currentDir = null; insideExcludedElement = false; excludedLevel = 0; foreignLevel = 0; chunkLevel = 0; relTableLevel = 0; chunkToNavLevel = 0; topicGroupLevel = 0; isValidInput = false; hasconaction = false; nonConrefCopytoTargets.clear(); hrefTargets.clear(); hrefTopicSet.clear(); chunkTopicSet.clear(); conrefTargets.clear(); copytoMap.clear(); ignoredCopytoSourceSet.clear(); outDitaFilesSet.clear(); keysDefMap.clear(); keysRefMap.clear(); exKeysDefMap.clear(); schemeSet.clear(); schemeRefSet.clear(); //clear level level = 0; //clear stack topicrefStack.clear(); //@processing-role processRoleLevel = 0; processRoleStack.clear(); //reset utils ditaAttrUtils.reset(); /* * Don't clean up these sets, we need them through * the whole phase to determine a topic's processing-role. */ //resourceOnlySet.clear(); //crossSet.clear(); } /** * To see if the parsed file has conref inside. * * @return true if has conref and false otherwise */ public boolean hasConRef() { return hasConRef; } /** * To see if the parsed file has keyref inside. * * @return true if has keyref and false otherwise */ public boolean hasKeyRef(){ return hasKeyRef; } /** * To see if the parsed file has coderef inside. * * @return true if has coderef and false otherwise */ public boolean hasCodeRef(){ return hasCodeRef; } /** * To see if the parsed file has href inside. * * @return true if has href and false otherwise */ public boolean hasHref() { return hasHref; } /** * Get all targets except copy-to. * * @return set of target file path with option format after {@link org.dita.dost.util.Constants#STICK STICK} */ public Set<Reference> getNonCopytoResult() { final Set<Reference> nonCopytoSet = new HashSet<Reference>(INT_128); nonCopytoSet.addAll(nonConrefCopytoTargets); for (final String f: conrefTargets) { nonCopytoSet.add(new Reference(f)); } for (final String f: copytoMap.values()) { nonCopytoSet.add(new Reference(f)); } for (final String f: ignoredCopytoSourceSet) { nonCopytoSet.add(new Reference(f)); } for(final String filename : subsidiarySet){ //only activated on /generateout:3 & is out file. if(isOutFile(filename) && OutputUtils.getGeneratecopyouter() == OutputUtils.Generate.OLDSOLUTION){ nonCopytoSet.add(new Reference(filename)); } } //nonCopytoSet.addAll(subsidiarySet); return nonCopytoSet; } /** * Get the href target. * * @return Returns the hrefTargets. */ public Set<String> getHrefTargets() { return hrefTargets; } /** * Get conref targets. * * @return Returns the conrefTargets. */ public Set<String> getConrefTargets() { return conrefTargets; } /** * Get subsidiary targets. * * @return Returns the subsidiarySet. */ public Set<String> getSubsidiaryTargets() { return subsidiarySet; } /** * Get outditafileslist. * * @return Returns the outditafileslist. */ public Set<String> getOutDitaFilesSet(){ return outDitaFilesSet; } /** * Get non-conref and non-copyto targets. * * @return Returns the nonConrefCopytoTargets. */ public Set<String> getNonConrefCopytoTargets() { final Set<String> res = new HashSet<String>(nonConrefCopytoTargets.size()); for (final Reference r: nonConrefCopytoTargets) { res.add(r.filename); } return res; } /** * Returns the ignoredCopytoSourceSet. * * @return Returns the ignoredCopytoSourceSet. */ public Set<String> getIgnoredCopytoSourceSet() { return ignoredCopytoSourceSet; } /** * Get the copy-to map. * * @return copy-to map */ public Map<String, String> getCopytoMap() { return copytoMap; } /** * Get the Key definitions. * * @return Key definitions map */ public Map<String, KeyDef> getKeysDMap(){ return keysDefMap; } public Map<String, String> getExKeysDefMap() { return exKeysDefMap; } /** * Set the relative directory of current file. * * @param dir dir */ public void setCurrentDir(final String dir) { this.currentDir = dir; } /** * Check if the current file is valid after filtering. * * @return true if valid and false otherwise */ public boolean isValidInput() { return isValidInput; } /** * Check if the current file has conaction. * @return true if has conaction and false otherwise */ public boolean hasConaction(){ return hasconaction; } /** * Parse input xml file. * * @param file file * @throws SAXException SAXException * @throws IOException IOException * @throws FileNotFoundException FileNotFoundException */ public void parse(final File file) throws FileNotFoundException, IOException, SAXException { currentFile=file.getAbsoluteFile(); reader.setErrorHandler(new DITAOTXMLErrorHandler(file.getName(), logger)); final InputSource is = new InputSource(new FileInputStream(file)); //Set the system ID if(setSystemid) { //is.setSystemId(URLUtil.correct(file).toString()); is.setSystemId(file.toURI().toURL().toString()); } reader.parse(is); } @Override public void startElement(final String uri, final String localName, final String qName, final Attributes atts) throws SAXException { String domains = null; final Properties params = new Properties(); final String printValue = atts.getValue(ATTRIBUTE_NAME_PRINT); //increase element level for nested tags. ditaAttrUtils.increasePrintLevel(printValue); //Exclude the topic if it is needed. if(ditaAttrUtils.needExcludeForPrintAttri(transtype)){ return; } final String processingRole = atts.getValue(ATTRIBUTE_NAME_PROCESSING_ROLE); final String href = atts.getValue(ATTRIBUTE_NAME_HREF); final String scope = atts.getValue(ATTRIBUTE_NAME_SCOPE); if (processingRole != null) { processRoleStack.push(processingRole); processRoleLevel++; if (ATTR_SCOPE_VALUE_EXTERNAL.equals(scope)) { } else if (ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equals(processingRole)) { if (href != null) { resourceOnlySet.add(FileUtils.resolveFile(currentDir, href)); } } else if (ATTR_PROCESSING_ROLE_VALUE_NORMAL.equalsIgnoreCase(processingRole)) { if (href != null) { crossSet.add(FileUtils.resolveFile(currentDir, href)); } } } else if (processRoleLevel > 0) { processRoleLevel++; if (ATTR_SCOPE_VALUE_EXTERNAL.equals(scope)) { } else if (ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equalsIgnoreCase( processRoleStack.peek())) { if (href != null) { resourceOnlySet.add(FileUtils.resolveFile(currentDir, href)); } } else if (ATTR_PROCESSING_ROLE_VALUE_NORMAL.equalsIgnoreCase( processRoleStack.peek())) { if (href != null) { crossSet.add(FileUtils.resolveFile(currentDir, href)); } } } else { if (href != null) { crossSet.add(FileUtils.resolveFile(currentDir, href)); } } final String classValue = atts.getValue(ATTRIBUTE_NAME_CLASS); //has class attribute if(classValue!=null){ //when meets topic tag if(TOPIC_TOPIC.matches(classValue)){ topicId = atts.getValue(ATTRIBUTE_NAME_ID); //relpace place holder with first topic id //Get relative file name final String filename = FileUtils.getRelativePath( rootFilePath.getAbsolutePath(), currentFile.getAbsolutePath()); for (final ExportAnchor e: resultList) { if (e.topicids.contains(filename + QUESTION)) { e.topicids.add(topicId); e.topicids.remove(filename + QUESTION); } } } // WEK: As of 14 Dec 2009, transtype is sometimes null, not sure under what conditions. // System.out.println(" + [DEBUG] transtype=" + transtype); //get plugin id only transtype = eclipsehelp if(FileUtils.isDITAMapFile(currentFile.getName())&& rootFilePath.equals(currentFile)&& MAP_MAP.matches(classValue)&& INDEX_TYPE_ECLIPSEHELP.equals(transtype)){ String pluginId = atts.getValue(ATTRIBUTE_NAME_ID); if(pluginId == null){ pluginId = "org.sample.help.doc"; } final Set<String> set = StringUtils.restoreSet(pluginId); pluginMap.put("pluginId", set); } //merge multiple exportanchors into one //Each <topicref> can only have one <topicmeta>. //Each <topic> can only have one <prolog> //and <metadata> can have more than one exportanchors if (INDEX_TYPE_ECLIPSEHELP.equals(transtype)) { if (MAP_TOPICMETA.matches(classValue) || TOPIC_PROLOG.matches(classValue)) { topicMetaSet.add(qName); } // If the file has <exportanchors> tags only transtype = // eclipsehelp if (DELAY_D_EXPORTANCHORS.matches(classValue)) { hasExport = true; // If current file is a ditamap file if (FileUtils.isDITAMapFile(currentFile.getName())) { // if dita file's extension name is ".xml" String editedHref = ""; if (topicHref.endsWith(FILE_EXTENSION_XML)) { // change the extension to ".dita" for latter // compare editedHref = topicHref.replace( FILE_EXTENSION_XML, FILE_EXTENSION_DITA); } else { editedHref = topicHref; } // editedHref = editedHref.replace(File.separator, "/"); currentExportAnchor = new ExportAnchor(editedHref); // if <exportanchors> is defined in topicmeta(topicref), // there is only one topic id currentExportAnchor.topicids.add(topicId); // If current file is topic file } else if (FileUtils.isDITATopicFile(currentFile.getName())) { String filename = FileUtils.getRelativePath( rootFilePath.getAbsolutePath(), currentFile.getAbsolutePath()); // if dita file's extension name is ".xml" if (filename.endsWith(FILE_EXTENSION_XML)) { // change the extension to ".dita" for latter // compare filename = filename.replace( FILE_EXTENSION_XML, FILE_EXTENSION_DITA); } // filename = FileUtils.normalizeDirectory(currentDir, // filename); filename = FileUtils.separatorsToUnix(filename); currentExportAnchor = new ExportAnchor(filename); // if <exportanchors> is defined in metadata(topic), // there can be many topic ids currentExportAnchor.topicids.add(topicId); shouldAppendEndTag = true; } // meet <anchorkey> tag } else if (DELAY_D_ANCHORKEY.matches(classValue)) { // create keyref element in the StringBuffer // TODO in topic file is no keys final String keyref = atts .getValue(ATTRIBUTE_NAME_KEYREF); currentExportAnchor.keys.add(keyref); // meet <anchorid> tag } else if (DELAY_D_ANCHORID.matches(classValue)) { // create keyref element in the StringBuffer final String id = atts.getValue(ATTRIBUTE_NAME_ID); // If current file is a ditamap file // The id can only be element id within a topic if (FileUtils.isDITAMapFile(currentFile.getName())) { // only for dita format /* * if(!"".equals(topicHref)){ String absolutePathToFile * = FileUtils.resolveFile((new * File(rootFilePath)).getParent(),topicHref); //whether * the id is a topic id * if(FileUtils.isDITAFile(absolutePathToFile)){ found = * DelayConrefUtils * .getInstance().findTopicId(absolutePathToFile, id); } * //other format file }else{ found = false; } */ // id shouldn't be same as topic id in the case of duplicate insert if (!topicId.equals(id)) { currentExportAnchor.ids.add(id); } } else if (FileUtils.isDITATopicFile(currentFile.getName())) { // id shouldn't be same as topic id in the case of duplicate insert if (!topicId.equals(id)) { // topic id found currentExportAnchor.ids.add(id); } } } } } // Generate Scheme relationship graph if (classValue != null) { if (SUBJECTSCHEME_SUBJECTSCHEME.matches(classValue)) { if (this.relationGraph == null) { this.relationGraph = new LinkedHashMap<String, Set<String>>(); } //Make it easy to do the BFS later. Set<String> children = this.relationGraph.get("ROOT"); if (children == null || children.isEmpty()) { children = new LinkedHashSet<String>(); } children.add(this.currentFile.getAbsolutePath()); this.relationGraph.put("ROOT", children); schemeRefSet.add(FileUtils.getRelativePath(rootFilePath.getAbsolutePath(), currentFile.getAbsolutePath())); } else if (SUBJECTSCHEME_SCHEMEREF.matches(classValue)) { Set<String> children = this.relationGraph.get(this.currentFile.getAbsolutePath()); if (children == null) { children = new LinkedHashSet<String>(); this.relationGraph.put(currentFile.getAbsolutePath(), children); } if (href != null) { children.add(FileUtils.resolveFile(rootDir.getAbsolutePath(), href)); } } } if(foreignLevel > 0){ //if it is an element nested in foreign/unknown element //do not parse it foreignLevel ++; return; } else if(classValue != null && (TOPIC_FOREIGN.matches(classValue) || TOPIC_UNKNOWN.matches(classValue))){ foreignLevel ++; } if(chunkLevel > 0) { chunkLevel++; } else if(atts.getValue(ATTRIBUTE_NAME_CHUNK) != null) { chunkLevel++; } if(relTableLevel > 0) { relTableLevel ++; } else if(classValue != null && MAP_RELTABLE.matches(classValue)){ relTableLevel++; } if(chunkToNavLevel > 0) { chunkToNavLevel++; } else if(atts.getValue(ATTRIBUTE_NAME_CHUNK) != null && atts.getValue(ATTRIBUTE_NAME_CHUNK).indexOf("to-navigation") != -1){ chunkToNavLevel++; } if(topicGroupLevel > 0) { topicGroupLevel++; } else if (atts.getValue(ATTRIBUTE_NAME_CLASS) != null && atts.getValue(ATTRIBUTE_NAME_CLASS).contains(MAPGROUP_D_TOPICGROUP.matcher)) { topicGroupLevel++; } if(classValue==null && !ELEMENT_NAME_DITA.equals(localName)){ params.clear(); params.put("%1", localName); logger.logInfo(MessageUtils.getInstance().getMessage("DOTJ030I", params).toString()); } if (classValue != null && TOPIC_TOPIC.matches(classValue)){ domains = atts.getValue(ATTRIBUTE_NAME_DOMAINS); if(domains==null){ params.clear(); params.put("%1", localName); logger.logInfo(MessageUtils.getInstance().getMessage("DOTJ029I", params).toString()); } else { props = StringUtils.getExtProps(domains); } } if (insideExcludedElement) { ++excludedLevel; return; } // Ignore element that has been filtered out. if (filterUtils.needExclude(atts, props)) { insideExcludedElement = true; ++excludedLevel; return; } /* * For ditamap, set it to valid if element <map> or extended from * <map> was found, this kind of element's class attribute must * contains 'map/map'; * For topic files, set it to valid if element <title> or extended * from <title> was found, this kind of element's class attribute * must contains 'topic/title'. */ if (classValue != null) { if ((MAP_MAP.matches(classValue)) || (TOPIC_TITLE.matches(classValue))) { isValidInput = true; }else if (TOPIC_OBJECT.matches(classValue)){ parseAttribute(atts, ATTRIBUTE_NAME_DATA); } } // onlyTopicInMap is on. topicref: if (outputUtils.getOnlyTopicInMap() && this.canResolved()) { // topicref(only defined in ditamap file.) if (MAP_TOPICREF.matches(classValue)) { //get href attribute value. final String hrefValue = atts.getValue(ATTRIBUTE_NAME_HREF); //get conref attribute value. final String conrefValue = atts.getValue(ATTRIBUTE_NAME_CONREF); //has href attribute and refer to ditamap file. if(!StringUtils.isEmptyString(hrefValue)){ //exclude external resources final String attrScope = atts.getValue(ATTRIBUTE_NAME_SCOPE); if ("external".equalsIgnoreCase(attrScope) || "peer".equalsIgnoreCase(attrScope) || hrefValue.indexOf(COLON_DOUBLE_SLASH) != -1 || hrefValue.startsWith(SHARP)) { break topicref; } //normalize href value. final File target=new File(hrefValue); //caculate relative path for href value. String fileName = null; if(target.isAbsolute()){ fileName = FileUtils.getRelativePath(rootFilePath.getAbsolutePath(),hrefValue); } fileName = FileUtils.normalizeDirectory(currentDir, hrefValue); //change '\' to '/' for comparsion. fileName = FileUtils.separatorsToUnix(fileName); final boolean canParse = parseBranch(atts, hrefValue, fileName); if (!canParse) { break topicref; } else { topicrefStack.push(localName); } }else if(!StringUtils.isEmptyString(conrefValue)){ //exclude external resources final String attrScope = atts.getValue(ATTRIBUTE_NAME_SCOPE); if ("external".equalsIgnoreCase(attrScope) || "peer".equalsIgnoreCase(attrScope) || conrefValue.indexOf(COLON_DOUBLE_SLASH) != -1 || conrefValue.startsWith(SHARP)) { break topicref; } //normalize href value. final File target=new File(conrefValue); //caculate relative path for href value. String fileName = null; if(target.isAbsolute()){ fileName = FileUtils.getRelativePath(rootFilePath.getAbsolutePath(),conrefValue); } fileName = FileUtils.normalizeDirectory(currentDir, conrefValue); //change '\' to '/' for comparsion. fileName = FileUtils.separatorsToUnix(fileName); final boolean canParse = parseBranch(atts, conrefValue, fileName); if (!canParse) { break topicref; } else { topicrefStack.push(localName); } } } } parseAttribute(atts, ATTRIBUTE_NAME_CONREF); parseAttribute(atts, ATTRIBUTE_NAME_HREF); parseAttribute(atts, ATTRIBUTE_NAME_COPY_TO); parseAttribute(atts, ATTRIBUTE_NAME_IMG); parseAttribute(atts, ATTRIBUTE_NAME_CONACTION); parseAttribute(atts, ATTRIBUTE_NAME_KEYS); parseAttribute(atts, ATTRIBUTE_NAME_CONKEYREF); parseAttribute(atts, ATTRIBUTE_NAME_KEYREF); } /** * Method for see whether a branch should be parsed. * @param atts {@link Attributes} * @param hrefValue {@link String} * @param fileName normalized file name(remove '#') * @return boolean */ private boolean parseBranch(final Attributes atts, final String hrefValue, final String fileName) { //current file is primary ditamap file. //parse every branch. final String currentFileRelative = FileUtils.getRelativePath( rootFilePath.getAbsolutePath(), currentFile.getAbsolutePath()); if(currentDir == null && currentFileRelative.equals(primaryDitamap)){ //add branches into map addReferredBranches(hrefValue, fileName); return true; }else{ //current file is a sub-ditamap one. //get branch's id final String id = atts.getValue(ATTRIBUTE_NAME_ID); //this branch is not referenced if(level == 0 && StringUtils.isEmptyString(id)){ //There is occassion that the whole ditamap should be parsed final boolean found = searchBrachesMap(id); if(found){ //Add this branch into map for parsing. addReferredBranches(hrefValue, fileName); //update level level++; return true; }else{ return false; } //this brach is a decendent of a referenced one }else if(level != 0){ //Add this branch into map for parsing. addReferredBranches(hrefValue, fileName); //update level level++; return true; //This branch has an id but is a new one }else if(!StringUtils.isEmptyString(id)){ //search branches map. final boolean found = searchBrachesMap(id); //branch is referenced if(found){ //Add this branch into map for parsing. addReferredBranches(hrefValue, fileName); //update level level ++; return true; }else{ //this branch is not referenced return false; } }else{ return false; } } } /** * Search braches map with branch id and current file name. * @param id String branch id. * @return boolean true if found and false otherwise. */ private boolean searchBrachesMap(final String id) { //caculate relative path for current file. final String currentFileRelative = FileUtils.getRelativePath( rootFilePath.getAbsolutePath(), currentFile.getAbsolutePath()); //seach the map with id & current file name. if(vaildBranches.containsKey(currentFileRelative)){ final List<String> branchIdList = vaildBranches.get(currentFileRelative); //the branch is referenced. if(branchIdList.contains(id)){ return true; }else if(branchIdList.size() == 0){ //the whole map is referenced return true; }else{ //the branch is not referred return false; } }else{ //current file is not refered return false; } } /** * Add branches into map. * @param hrefValue * @param fileName */ private void addReferredBranches(final String hrefValue, final String fileName) { String branchId = null; //href value has branch id. if(hrefValue.contains(SHARP)){ branchId = hrefValue.substring(hrefValue.lastIndexOf(SHARP) + 1); //The map contains the file name if(vaildBranches.containsKey(fileName)){ final List<String> branchIdList = vaildBranches.get(fileName); branchIdList.add(branchId); }else{ final List<String> branchIdList = new ArrayList<String>(); branchIdList.add(branchId); vaildBranches.put(fileName, branchIdList); } //href value has no branch id }else{ vaildBranches.put(fileName, new ArrayList<String>()); } } /** * Clean up. */ @Override public void endDocument() throws SAXException { if (processRoleLevel > 0) { processRoleLevel processRoleStack.pop(); } if(FileUtils.isDITATopicFile(currentFile.getName()) && shouldAppendEndTag){ resultList.add(currentExportAnchor); currentExportAnchor = null; //should reset shouldAppendEndTag = false; } checkMultiLevelKeys(keysDefMap, keysRefMap); } /** * Check if the current file is a ditamap with "@processing-role=resource-only". */ @Override public void startDocument() throws SAXException { final String href = FileUtils.getRelativePath(rootFilePath.getAbsolutePath(), currentFile.getAbsolutePath()); if (FileUtils.isDITAMapFile(currentFile.getName()) && resourceOnlySet.contains(href) && !crossSet.contains(href)) { processRoleLevel++; processRoleStack.push(ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY); } } @Override public void endElement(final String uri, final String localName, final String qName) throws SAXException { //subject scheme //if (currentElement != null && currentElement != schemeRoot.getDocumentElement()) { // currentElement = (Element)currentElement.getParentNode(); //@processing-role if (processRoleLevel > 0) { if (processRoleLevel == processRoleStack.size()) { processRoleStack.pop(); } processRoleLevel } if (foreignLevel > 0){ foreignLevel return; } if (chunkLevel > 0) { chunkLevel } if (relTableLevel > 0) { relTableLevel } if (chunkToNavLevel > 0) { chunkToNavLevel } if (topicGroupLevel > 0) { topicGroupLevel } if (insideExcludedElement) { // end of the excluded element, mark the flag as false if (excludedLevel == 1) { insideExcludedElement = false; } --excludedLevel; } //<exportanchors> over should write </file> tag if(topicMetaSet.contains(qName) && hasExport){ //If current file is a ditamap file if(FileUtils.isDITAMapFile(currentFile.getName())){ resultList.add(currentExportAnchor); currentExportAnchor = null; //If current file is topic file } hasExport = false; topicMetaSet.clear(); } if(!topicrefStack.isEmpty() && localName.equals(topicrefStack.peek())){ level topicrefStack.pop(); } //decrease element level. ditaAttrUtils.decreasePrintLevel(); } /** * Parse the input attributes for needed information. * * @param atts all attributes * @param attrName attributes to process */ private void parseAttribute(final Attributes atts, final String attrName) throws SAXException { String attrValue = atts.getValue(attrName); String filename = null; final String attrClass = atts.getValue(ATTRIBUTE_NAME_CLASS); final String attrScope = atts.getValue(ATTRIBUTE_NAME_SCOPE); final String attrFormat = atts.getValue(ATTRIBUTE_NAME_FORMAT); final String attrType = atts.getValue(ATTRIBUTE_NAME_TYPE); final String codebase = atts.getValue(ATTRIBUTE_NAME_CODEBASE); if (attrValue == null) { return; } // @conkeyref will be resolved to @conref in Debug&Fileter step if (ATTRIBUTE_NAME_CONREF.equals(attrName) || ATTRIBUTE_NAME_CONKEYREF.equals(attrName)) { hasConRef = true; } else if (ATTRIBUTE_NAME_HREF.equals(attrName)) { if(attrClass != null && PR_D_CODEREF.matches(attrClass) ){ //if current element is <coderef> or its specialization //set hasCodeRef to true hasCodeRef = true; }else{ hasHref = true; } } else if(ATTRIBUTE_NAME_KEYREF.equals(attrName)){ hasKeyRef = true; } // collect the key definitions if(ATTRIBUTE_NAME_KEYS.equals(attrName) && attrValue.length() != 0){ String target = atts.getValue(ATTRIBUTE_NAME_HREF); if (target != null && (attrFormat == null || attrFormat.equals(ATTR_FORMAT_VALUE_DITA)) && extName != null) { target = FileUtils.replaceExtension(target, extName); } final String keyRef = atts.getValue(ATTRIBUTE_NAME_KEYREF); final String copy_to = atts.getValue(ATTRIBUTE_NAME_COPY_TO); if (!StringUtils.isEmptyString(copy_to)) { target = copy_to; } //avoid NullPointException if(target == null){ target = ""; } //store the target final String temp = target; // Many keys can be defined in a single definition, like keys="a b c", a, b and c are seperated by blank. for(final String key: attrValue.split(" ")){ if (!isValidKeyName(key)) { logger.logError(MessageUtils.getInstance().getMessage("DOTJ055E", key).toString()); continue; } if(!keysDefMap.containsKey(key) && !key.equals("")){ if(target != null && target.length() != 0){ if(attrScope!=null && (attrScope.equals("external") || attrScope.equals("peer"))){ //store external or peer resources. exKeysDefMap.put(key, target); keysDefMap.put(key, new KeyDef(key, target, null)); }else{ String tail = ""; if(target.indexOf(SHARP) != -1){ tail = target.substring(target.indexOf(SHARP)); target = target.substring(0, target.indexOf(SHARP)); } if(new File(target).isAbsolute()) { target = FileUtils.getRelativePath(rootFilePath.getAbsolutePath(), target); } target = FileUtils.normalizeDirectory(currentDir, target); keysDefMap.put(key, new KeyDef(key, target + tail, null)); } }else if(!StringUtils.isEmptyString(keyRef)){ //store multi-level keys. keysRefMap.put(key, keyRef); }else{ // target is null or empty, it is useful in the future when consider the content of key definition keysDefMap.put(key, new KeyDef(key, null, null)); } }else{ final Properties prop = new Properties(); prop.setProperty("%1", key); prop.setProperty("%2", target); // DOTJ045W also exists, but is commented out of the messages file logger.logInfo(MessageUtils.getInstance().getMessage("DOTJ045I", prop).toString()); } //restore target target = temp; } } /* if (attrValue.startsWith(SHARP) || attrValue.indexOf(COLON_DOUBLE_SLASH) != -1){ return; } */ //external resource is filtered here. if ("external".equalsIgnoreCase(attrScope) || "peer".equalsIgnoreCase(attrScope) || attrValue.indexOf(COLON_DOUBLE_SLASH) != -1 || attrValue.startsWith(SHARP)) { return; } if(attrValue.startsWith("file:/") && attrValue.indexOf("file: attrValue = attrValue.substring("file:/".length()); //Unix like OS if(UNIX_SEPARATOR.equals(File.separator)){ attrValue = UNIX_SEPARATOR + attrValue; } } else if (attrValue.startsWith("file:") && !attrValue.startsWith("file:/")) { attrValue = attrValue.substring("file:".length()); } final File target=new File(attrValue); if(target.isAbsolute() && !ATTRIBUTE_NAME_DATA.equals(attrName)){ attrValue=FileUtils.getRelativePath(rootFilePath.getAbsolutePath(),attrValue); //for object tag bug:3052156 }else if(ATTRIBUTE_NAME_DATA.equals(attrName)){ if(!StringUtils.isEmptyString(codebase)){ filename = FileUtils.normalizeDirectory(codebase, attrValue); }else{ filename = FileUtils.normalizeDirectory(currentDir, attrValue); } }else{ //noraml process. filename = FileUtils.normalizeDirectory(currentDir, attrValue); } filename = toFile(filename); // XXX: At this point, filename should be a system path if (MAP_TOPICREF.matches(attrClass)) { if (ATTR_TYPE_VALUE_SUBJECT_SCHEME.equalsIgnoreCase(attrType)) { schemeSet.add(filename); } //only transtype = eclipsehelp if(INDEX_TYPE_ECLIPSEHELP.equals(transtype)){ //For only format of the href is dita topic if (attrFormat == null || ATTR_FORMAT_VALUE_DITA.equalsIgnoreCase(attrFormat)){ if(attrName.equals(ATTRIBUTE_NAME_HREF)){ topicHref = filename; topicHref = FileUtils.separatorsToUnix(topicHref); //attrValue has topicId if(attrValue.lastIndexOf(SHARP) != -1){ //get the topicId position final int position = attrValue.lastIndexOf(SHARP); topicId = attrValue.substring(position + 1); }else{ //get the first topicId(vaild href file) if(FileUtils.isDITAFile(topicHref)){ //topicId = MergeUtils.getInstance().getFirstTopicId(topicHref, (new File(rootFilePath)).getParent(), true); //to be unique topicId = topicHref + QUESTION; } } } }else{ topicHref = ""; topicId = ""; } } } //files referred by coderef won't effect the uplevels, code has already returned. if (("DITA-foreign".equals(attrType) && ATTRIBUTE_NAME_DATA.equals(attrName)) || attrClass!=null && PR_D_CODEREF.matches(attrClass)){ subsidiarySet.add(filename); return; } /* * Collect non-conref and non-copyto targets */ if (filename != null && FileUtils.isValidTarget(filename.toLowerCase()) && (StringUtils.isEmptyString(atts.getValue(ATTRIBUTE_NAME_COPY_TO)) || !FileUtils.isDITATopicFile(atts.getValue(ATTRIBUTE_NAME_COPY_TO).toLowerCase()) || (atts.getValue(ATTRIBUTE_NAME_CHUNK)!=null && atts.getValue(ATTRIBUTE_NAME_CHUNK).contains("to-content")) ) && !ATTRIBUTE_NAME_CONREF.equals(attrName) && !ATTRIBUTE_NAME_COPY_TO.equals(attrName) && (canResolved() || FileUtils.isSupportedImageFile(filename.toLowerCase()))) { nonConrefCopytoTargets.add(new Reference(filename, attrFormat)); //nonConrefCopytoTargets.add(filename); } //outside ditamap files couldn't cause warning messages, it is stopped here if (attrFormat != null && !ATTR_FORMAT_VALUE_DITA.equalsIgnoreCase(attrFormat)){ //The format of the href is not dita topic //The logic after this "if" clause is not related to files other than dita topic. //Therefore, we need to return here to filter out those files in other format. return; } /* * Collect only href target topic files for index extracting. */ if (ATTRIBUTE_NAME_HREF.equals(attrName) && FileUtils.isDITATopicFile(filename) && canResolved()) { hrefTargets.add(new File(filename).getPath()); toOutFile(new File(filename).getPath()); //use filename instead(It has already been resolved before-hand) bug:3058124 //String pathWithoutID = FileUtils.resolveFile(currentDir, attrValue); if (chunkLevel > 0 && chunkToNavLevel == 0 && topicGroupLevel == 0 && relTableLevel == 0) { chunkTopicSet.add(filename); } else { hrefTopicSet.add(filename); } } //add a warning message for outer files refered by @data /*if(ATTRIBUTE_NAME_DATA.equals(attrName)){ toOutFile(new File(filename).getPath()); }*/ /* * Collect only conref target topic files. */ if (ATTRIBUTE_NAME_CONREF.equals(attrName) && FileUtils.isDITAFile(filename)) { conrefTargets.add(filename); toOutFile(new File(filename).getPath()); } // Collect copy-to (target,source) into hash map if (ATTRIBUTE_NAME_COPY_TO.equals(attrName) && FileUtils.isDITATopicFile(filename)) { final String href = atts.getValue(ATTRIBUTE_NAME_HREF); final String value = toFile(FileUtils.normalizeDirectory(currentDir, href)); if (StringUtils.isEmptyString(href)) { final StringBuffer buff = new StringBuffer(); buff.append("[WARN]: Copy-to task [href=\"\" copy-to=\""); buff.append(filename); buff.append("\"] was ignored."); logger.logWarn(buff.toString()); } else if (copytoMap.get(filename) != null){ /*StringBuffer buff = new StringBuffer(); buff.append("Copy-to task [href=\""); buff.append(href); buff.append("\" copy-to=\""); buff.append(filename); buff.append("\"] which points to another copy-to target"); buff.append(" was ignored."); javaLogger.logWarn(buff.toString());*/ final Properties prop = new Properties(); prop.setProperty("%1", href); prop.setProperty("%2", filename); if(!value.equals(copytoMap.get(filename))) { logger.logWarn(MessageUtils.getInstance().getMessage("DOTX065W", prop).toString()); } ignoredCopytoSourceSet.add(href); } else if (!(atts.getValue(ATTRIBUTE_NAME_CHUNK) != null && atts.getValue(ATTRIBUTE_NAME_CHUNK).contains("to-content"))){ copytoMap.put(filename, value); } final String pathWithoutID = FileUtils.resolveFile(currentDir, toFile(attrValue)); if (chunkLevel > 0 && chunkToNavLevel == 0 && topicGroupLevel == 0) { chunkTopicSet.add(pathWithoutID); } else { hrefTopicSet.add(pathWithoutID); } } /* * Collect the conaction source topic file */ if(ATTRIBUTE_NAME_CONACTION.equals(attrName)){ if(attrValue.equals("mark")||attrValue.equals("pushreplace")){ hasconaction = true; } } } /** * Convert URI references to file paths. * * @param filename file reference * @return file path */ private String toFile(final String filename) { if (filename == null) { return null; } String f = filename; try{ f = URLDecoder.decode(filename, UTF8); }catch(final UnsupportedEncodingException e){ throw new RuntimeException(e); } if (processingMode == Mode.LAX) { f = f.replace(WINDOWS_SEPARATOR, File.separator); } f = f.replace(URI_SEPARATOR, File.separator); return f; } /** * Validate key name * @param key key name * @return {@code true} if key name is valid, otherwise {@code false} */ public static boolean isValidKeyName(final String key) { for (final char c: key.toCharArray()) { switch(c) { // disallowed characters case '{': case '}': case '[': case ']': case '/': case ' case '?': return false; // URI characters case '-': case '.': case '_': case '~': case ':': case '@': case '!': case '$': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case ';': case '=': break; default: if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))) { return false; } break; } } return true; } /** * Get multi-level keys list */ private List<String> getKeysList(final String key, final Map<String, String> keysRefMap) { final List<String> list = new ArrayList<String>(); //Iterate the map to look for multi-level keys final Iterator<Entry<String, String>> iter = keysRefMap.entrySet().iterator(); while (iter.hasNext()) { final Map.Entry<String, String> entry = iter.next(); //Multi-level key found if(entry.getValue().equals(key)){ //add key into the list final String entryKey = entry.getKey(); list.add(entryKey); //still have multi-level keys if(keysRefMap.containsValue(entryKey)){ //rescuive point final List<String> tempList = getKeysList(entryKey, keysRefMap); list.addAll(tempList); } } } return list; } /** * Update keysDefMap for multi-level keys */ private void checkMultiLevelKeys(final Map<String, KeyDef> keysDefMap, final Map<String, String> keysRefMap) { String key = null; KeyDef value = null; //tempMap storing values to avoid ConcurrentModificationException final Map<String, KeyDef> tempMap = new HashMap<String, KeyDef>(); final Iterator<Entry<String, KeyDef>> iter = keysDefMap.entrySet().iterator(); while (iter.hasNext()) { final Map.Entry<String, KeyDef> entry = iter.next(); key = entry.getKey(); value = entry.getValue(); //there is multi-level keys exist. if(keysRefMap.containsValue(key)){ //get multi-level keys final List<String> keysList = getKeysList(key, keysRefMap); for (final String multikey : keysList) { //update tempMap tempMap.put(multikey, value); } } } //update keysDefMap. keysDefMap.putAll(tempMap); } /** * Check if path walks up in parent directories * * @param toCheckPath path to check * @return {@code true} if path walks up, otherwise {@code false} */ private boolean isOutFile(final String toCheckPath) { if (!toCheckPath.startsWith("..")) { return false; } else { return true; } } /** * Check if {@link #currentFile} is a map * * @return {@code} true if file is map, otherwise {@code false} */ private boolean isMapFile() { final String current=FileUtils.normalize(currentFile.getAbsolutePath()); if(FileUtils.isDITAMapFile(current)) { return true; } else { return false; } } private boolean canResolved(){ if ((outputUtils.getOnlyTopicInMap() == false) || isMapFile() ) { return true; } else { return false; } } private void addToOutFilesSet(final String hrefedFile) { if (canResolved()) { outDitaFilesSet.add(hrefedFile); } } /* private Element createElement(String uri, String qName, Attributes atts) { if (schemeRoot != null) { Element element = schemeRoot.createElementNS(uri, qName); for (int i = 0; i < atts.getLength(); i++) { element.setAttribute(atts.getQName(i), atts.getValue(i)); } return element; } return null; } */ private void toOutFile(final String filename) throws SAXException { //the filename is a relative path from the dita input file final Properties prop=new Properties(); prop.put("%1", FileUtils.normalizeDirectory(rootDir.getAbsolutePath(), filename)); prop.put("%2", FileUtils.normalize(currentFile.getAbsolutePath())); if ((OutputUtils.getGeneratecopyouter() == OutputUtils.Generate.NOT_GENERATEOUTTER) || (OutputUtils.getGeneratecopyouter() == OutputUtils.Generate.GENERATEOUTTER)) { if (isOutFile(filename)) { if (outputUtils.getOutterControl() == OutputUtils.OutterControl.FAIL){ final MessageBean msgBean=MessageUtils.getInstance().getMessage("DOTJ035F", prop); throw new SAXParseException(null,null,new DITAOTException(msgBean,null,msgBean.toString())); } else if (outputUtils.getOutterControl() == OutputUtils.OutterControl.WARN){ final String message=MessageUtils.getInstance().getMessage("DOTJ036W",prop).toString(); logger.logWarn(message); } addToOutFilesSet(filename); } } } /** * Get out file set. * @return out file set */ public Set<String> getOutFilesSet(){ return outDitaFilesSet; } /** * @return the hrefTopicSet */ public Set<String> getHrefTopicSet() { return hrefTopicSet; } /** * @return the chunkTopicSet */ public Set<String> getChunkTopicSet() { return chunkTopicSet; } /** * Get scheme set. * @return scheme set */ public Set<String> getSchemeSet() { return this.schemeSet; } /** * Get scheme ref set. * @return scheme ref set */ public Set<String> getSchemeRefSet() { return this.schemeRefSet; } /** * List of files with "@processing-role=resource-only". * @return the resource-only set */ public Set<String> getResourceOnlySet() { resourceOnlySet.removeAll(crossSet); return resourceOnlySet; } /** * Get document root of the merged subject schema. * @return */ //public Document getSchemeRoot() { // return schemeRoot; /** * Get getRelationshipGrap. * @return relationship grap */ public Map<String, Set<String>> getRelationshipGrap() { return this.relationGraph; } public String getPrimaryDitamap() { return primaryDitamap; } public void setPrimaryDitamap(final String primaryDitamap) { this.primaryDitamap = primaryDitamap; } /** * File reference with path and optional format. */ public static class Reference { public final String filename; public final String format; public Reference(final String filename, final String format) { this.filename = filename; this.format = format; } public Reference(final String filename) { this(filename, null); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((filename == null) ? 0 : filename.hashCode()); result = prime * result + ((format == null) ? 0 : format.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Reference)) { return false; } Reference other = (Reference) obj; if (filename == null) { if (other.filename != null) { return false; } } else if (!filename.equals(other.filename)) { return false; } if (format == null) { if (other.format != null) { return false; } } else if (!format.equals(other.format)) { return false; } return true; } } public static class ExportAnchor { public final String file; public final Set<String> topicids = new HashSet<String>(); public final Set<String> keys = new HashSet<String>(); public final Set<String> ids = new HashSet<String>(); ExportAnchor(final String file) { this.file = file; } } }
package org.jmxtrans.embedded.config; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.Proxy; import java.net.URL; import java.util.StringTokenizer; import org.apache.commons.io.IOUtils; import org.jmxtrans.embedded.EmbeddedJmxTransException; import org.jmxtrans.embedded.util.json.PlaceholderEnabledJsonNodeFactory; import com.fasterxml.jackson.databind.ObjectMapper; /** * This is an etcd based KVStore implementation. The connection to etcd is estabilished and closed * every time a key is read. This is by design since we don't need to read a lot of keys and we do * it at relativly long interval times * * @author Simone Zorzetti */ public class EtcdKVStore implements KVStore { private static final String HTTP_ERR = "ERR"; private final ObjectMapper mapper; { mapper = new ObjectMapper(); mapper.setNodeFactory(new PlaceholderEnabledJsonNodeFactory()); } /** * Bean for a simplified etcd node */ public static class EtcdNode { private String key; private long createdIndex; private long modifiedIndex; private String value; // For TTL keys private String expiration; private Integer ttl; public EtcdNode() { super(); } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public long getCreatedIndex() { return createdIndex; } public void setCreatedIndex(long createdIndex) { this.createdIndex = createdIndex; } public long getModifiedIndex() { return modifiedIndex; } public void setModifiedIndex(long modifiedIndex) { this.modifiedIndex = modifiedIndex; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getExpiration() { return expiration; } public void setExpiration(String expiration) { this.expiration = expiration; } public Integer getTtl() { return ttl; } public void setTtl(Integer ttl) { this.ttl = ttl; } } /** * Bean for a simplified etcd answer (just for GET) */ public static class EtcdResult { // General values private String action; private EtcdNode node; // For errors private Integer errorCode; private String message; private String cause; private int errorIndex; public EtcdResult() { super(); } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public EtcdNode getNode() { return node; } public void setNode(EtcdNode node) { this.node = node; } public Integer getErrorCode() { return errorCode; } public void setErrorCode(Integer errorCode) { this.errorCode = errorCode; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getCause() { return cause; } public void setCause(String cause) { this.cause = cause; } public int getErrorIndex() { return errorIndex; } public void setErrorIndex(int errorIndex) { this.errorIndex = errorIndex; } } public EtcdKVStore() { super(); } /** * Get a key value from etcd. Returns the key value and the etcd modification index as version * * @param KeyURI URI of the key in the form etcd://ipaddr:port/path for an etcd cluster you can * use etcd://[ipaddr1:port1, ipaddr:port2,...]:/path * @return a KeyValue object * @throws EmbeddedJmxTransException * * @see org.jmxtrans.embedded.config.KVStore#getKeyValue(java.lang.String) */ public KeyValue getKeyValue(String KeyURI) throws EmbeddedJmxTransException { String etcdURI = KeyURI.substring(0, KeyURI.indexOf("/", 7)); String key = KeyURI.substring(KeyURI.indexOf("/", 7)); try { return getFromEtcd(makeEtcdBaseUris(etcdURI), key); } catch (Throwable t) { throw new EmbeddedJmxTransException("Exception reading etcd key '" + KeyURI + "': " + t.getMessage(), t); } } private URL[] makeEtcdBaseUris(String etcdURI) throws EmbeddedJmxTransException { String serverList = null; try { if (etcdURI.indexOf("[") > 0) { serverList = etcdURI.substring(etcdURI.indexOf("[") + 1, etcdURI.indexOf("]")); } else { serverList = etcdURI.substring(7, etcdURI.indexOf("/", 7)); } StringTokenizer st = new StringTokenizer(serverList, ","); URL[] result = new URL[st.countTokens()]; int k = 0; while (st.hasMoreTokens()) { result[k] = new URL("http://" + st.nextToken().trim()); k++; } return result; } catch (Exception e) { throw new EmbeddedJmxTransException("Exception buildind etcd server list from: '" + etcdURI + "': " + e.getMessage(), e); } } private KeyValue getFromEtcd(URL[] baseUris, String key) throws EmbeddedJmxTransException { String json = null; int k = -1; while (k < baseUris.length - 1) { k++; String httpResponse = httpGET(baseUris[k], key); if (httpResponse == null) { // key not found on etcd server; since it's a cluster no need to try another one return null; } if (!HTTP_ERR.equals(httpResponse)) { json = httpResponse; break; } } if (json == null) { // couldn't get the key from etcd return null; } EtcdResult res = null; try { res = mapper.readValue(json, EtcdResult.class); } catch (Exception e) { throw new EmbeddedJmxTransException("Exception parsing etcd response: '" + json + "': " + e.getMessage(), e); } if (res.errorCode == null) { return new KeyValue(res.node.value, Long.toString(res.node.modifiedIndex)); } else if (res.errorCode == 100) { // key not found return null; } else { throw new EmbeddedJmxTransException("Etcd error reading etcd key '" + key + "': " + res.errorCode); } } private String httpGET(URL base, String key) { InputStream is = null; HttpURLConnection conn = null; String json = null; try { URL url = new URL(base + "/v2/keys/" + key); conn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); conn.setRequestMethod("GET"); conn.setConnectTimeout(2000); conn.setReadTimeout(2000); conn.connect(); int respCode = conn.getResponseCode(); if (respCode == 404) { return null; } else if (respCode > 400) { return HTTP_ERR; } is = conn.getInputStream(); String contentEncoding = conn.getContentEncoding() != null ? conn.getContentEncoding() : "UTF-8"; json = IOUtils.toString(is, contentEncoding); } catch (MalformedURLException e) { json = HTTP_ERR; // nothing to do, try next server } catch (ProtocolException e) { // nothing to do, try next server json = HTTP_ERR; } catch (IOException e) { // nothing to do, try next server json = HTTP_ERR; } finally { if (is != null) { try { is.close(); } catch (IOException e) { // nothing to do, try next server } } if (conn != null) { conn.disconnect(); } } return json; } }
package org.junit.validator; import static java.util.Collections.singletonList; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.runners.model.Annotatable; import org.junit.runners.model.FrameworkField; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.TestClass; /** * An {@code AnnotationsValidator} validates all annotations of a test class, * including its annotated fields and methods. * * @since 4.12 */ public final class AnnotationsValidator implements TestClassValidator { private static final List<AnnotatableValidator<?>> VALIDATORS = Arrays.<AnnotatableValidator<?>>asList( new ClassValidator(), new MethodValidator(), new FieldValidator()); /** * Validate all annotations of the specified test class that are be * annotated with {@link ValidateWith}. * * @param testClass * the {@link TestClass} that is validated. * @return the errors found by the validator. */ public List<Exception> validateTestClass(TestClass testClass) { List<Exception> validationErrors= new ArrayList<Exception>(); for (AnnotatableValidator<?> validator : VALIDATORS) { List<Exception> additionalErrors= validator .validateTestClass(testClass); validationErrors.addAll(additionalErrors); } return validationErrors; } private static abstract class AnnotatableValidator<T extends Annotatable> { private static final AnnotationValidatorFactory ANNOTATION_VALIDATOR_FACTORY = new AnnotationValidatorFactory(); abstract Iterable<T> getAnnotatablesForTestClass(TestClass testClass); abstract List<Exception> validateAnnotatable( AnnotationValidator validator, T annotatable); public List<Exception> validateTestClass(TestClass testClass) { List<Exception> validationErrors= new ArrayList<Exception>(); for (T annotatable : getAnnotatablesForTestClass(testClass)) { List<Exception> additionalErrors= validateAnnotatable(annotatable); validationErrors.addAll(additionalErrors); } return validationErrors; } private List<Exception> validateAnnotatable(T annotatable) { List<Exception> validationErrors= new ArrayList<Exception>(); for (Annotation annotation : annotatable.getAnnotations()) { Class<? extends Annotation> annotationType = annotation .annotationType(); ValidateWith validateWith = annotationType .getAnnotation(ValidateWith.class); if (validateWith != null) { AnnotationValidator annotationValidator = ANNOTATION_VALIDATOR_FACTORY .createAnnotationValidator(validateWith); List<Exception> errors= validateAnnotatable( annotationValidator, annotatable); validationErrors.addAll(errors); } } return validationErrors; } } private static class ClassValidator extends AnnotatableValidator<TestClass> { @Override Iterable<TestClass> getAnnotatablesForTestClass(TestClass testClass) { return singletonList(testClass); } @Override List<Exception> validateAnnotatable( AnnotationValidator validator, TestClass testClass) { return validator.validateAnnotatedClass(testClass); } } private static class MethodValidator extends AnnotatableValidator<FrameworkMethod> { @Override Iterable<FrameworkMethod> getAnnotatablesForTestClass( TestClass testClass) { return testClass.getAnnotatedMethods(); } @Override List<Exception> validateAnnotatable( AnnotationValidator validator, FrameworkMethod method) { return validator.validateAnnotatedMethod(method); } } private static class FieldValidator extends AnnotatableValidator<FrameworkField> { @Override Iterable<FrameworkField> getAnnotatablesForTestClass(TestClass testClass) { return testClass.getAnnotatedFields(); } @Override List<Exception> validateAnnotatable( AnnotationValidator validator, FrameworkField field) { return validator.validateAnnotatedField(field); } } }
package org.littleshoot.proxy; import static org.jboss.netty.channel.Channels.pipeline; import java.net.InetSocketAddress; import java.nio.channels.ClosedChannelException; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.lang.StringUtils; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.channel.group.ChannelGroup; import org.jboss.netty.channel.socket.ClientSocketChannelFactory; import org.jboss.netty.handler.codec.http.HttpChunk; import org.jboss.netty.handler.codec.http.HttpChunkAggregator; import org.jboss.netty.handler.codec.http.HttpContentDecompressor; import org.jboss.netty.handler.codec.http.HttpMethod; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpResponseDecoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class for handling all HTTP requests from the browser to the proxy. * * Note this class only ever handles a single connection from the browser. * The browser can and will, however, send requests to multiple hosts using * that same connection, i.e. it will send a request to host B once a request * to host A has completed. */ public class HttpRequestHandler extends SimpleChannelUpstreamHandler implements RelayListener { private final static Logger log = LoggerFactory.getLogger(HttpRequestHandler.class); private volatile boolean readingChunks; private static volatile int totalBrowserToProxyConnections = 0; private volatile int browserToProxyConnections = 0; private final Map<String, ChannelFuture> endpointsToChannelFutures = new ConcurrentHashMap<String, ChannelFuture>(); private volatile int messagesReceived = 0; private volatile int numWebConnections = 0; private final ProxyAuthorizationManager authorizationManager; /** * Note, we *can* receive requests for multiple different sites from the * same connection from the browser, so the host and port most certainly * does change. * * Why do we need to store it? We need it to lookup the appropriate * external connection to send HTTP chunks to. */ private String hostAndPort; private final String chainProxyHostAndPort; private final ChannelGroup channelGroup; /** * {@link Map} of host name and port strings to filters to apply. */ private final Map<String, HttpFilter> filters; private final ClientSocketChannelFactory clientChannelFactory; private final ProxyCacheManager cacheManager; private final HttpRequestFilter requestFilter; /** * Creates a new class for handling HTTP requests with the specified * authentication manager. * * @param cacheManager The manager for the cache. * @param authorizationManager The class that handles any * proxy authentication requirements. * @param channelGroup The group of channels for keeping track of all * channels we've opened. * @param filters HTTP filtering rules. * @param clientChannelFactory The common channel factory for clients. * @param chainProxyHostAndPort upstream proxy server host and port or null * if none used. * @param requestFilter An optional filter for HTTP requests. */ public HttpRequestHandler(final ProxyCacheManager cacheManager, final ProxyAuthorizationManager authorizationManager, final ChannelGroup channelGroup, final Map<String, HttpFilter> filters, final ClientSocketChannelFactory clientChannelFactory, final String chainProxyHostAndPort, final HttpRequestFilter requestFilter) { this.cacheManager = cacheManager; this.authorizationManager = authorizationManager; this.channelGroup = channelGroup; this.filters = filters; this.clientChannelFactory = clientChannelFactory; this.chainProxyHostAndPort = chainProxyHostAndPort; this.requestFilter = requestFilter; } /** * Creates a new class for handling HTTP requests with the specified * authentication manager. * * @param cacheManager The manager for the cache. * @param authorizationManager The class that handles any * proxy authentication requirements. * @param channelGroup The group of channels for keeping track of all * channels we've opened. * @param filters HTTP filtering rules. * @param clientChannelFactory The common channel factory for clients. */ public HttpRequestHandler(final ProxyCacheManager cacheManager, final ProxyAuthorizationManager authorizationManager, final ChannelGroup channelGroup, final Map<String, HttpFilter> filters, final ClientSocketChannelFactory clientChannelFactory) { this(cacheManager, authorizationManager, channelGroup, filters, clientChannelFactory, null, null); } @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent me) { messagesReceived++; log.info("Received "+messagesReceived+" total messages"); if (!readingChunks) { processMessage(ctx, me); } else { processChunk(ctx, me); } } private void processChunk(final ChannelHandlerContext ctx, final MessageEvent me) { log.info("Processing chunk..."); final HttpChunk chunk = (HttpChunk) me.getMessage(); // Remember this will typically be a persistent connection, so we'll // get another request after we're read the last chunk. So we need to // reset it back to no longer read in chunk mode. if (chunk.isLast()) { this.readingChunks = false; } final ChannelFuture cf = endpointsToChannelFutures.get(hostAndPort); // We don't necessarily know the channel is connected yet!! This can // happen if the client sends a chunk directly after the initial // request. if (cf.getChannel().isConnected()) { cf.getChannel().write(chunk); } else { cf.addListener(new ChannelFutureListener() { public void operationComplete(final ChannelFuture future) throws Exception { cf.getChannel().write(chunk); } }); } } private void processMessage(final ChannelHandlerContext ctx, final MessageEvent me) { if (this.cacheManager.returnCacheHit((HttpRequest)me.getMessage(), me.getChannel())) { log.info("Found cache hit! Cache wrote the response."); return; } final HttpRequest request = (HttpRequest) me.getMessage(); log.info("Got request: {} on channel: "+me.getChannel(), request); if (!this.authorizationManager.handleProxyAuthorization(request, ctx)) { log.info("Not authorized!!"); return; } // Check if we are running in proxy chain mode and modify request // accordingly final HttpRequest httpRequestCopy = ProxyUtils.copyHttpRequest(request, this.chainProxyHostAndPort != null); if (this.requestFilter != null) { this.requestFilter.filter(httpRequestCopy); } if (this.chainProxyHostAndPort != null) { this.hostAndPort = this.chainProxyHostAndPort; } else { this.hostAndPort = ProxyUtils.parseHostAndPort(request); } final Channel inboundChannel = me.getChannel(); final class OnConnect { public ChannelFuture onConnect(final ChannelFuture cf) { if (httpRequestCopy.getMethod() != HttpMethod.CONNECT) { return cf.getChannel().write(httpRequestCopy); } else { writeConnectResponse(ctx, request, cf.getChannel()); return cf; } } } final OnConnect onConnect = new OnConnect(); // We synchronize to avoid creating duplicate connections to the // same host, which we shouldn't for a single connection from the // browser. Note the synchronization here is short-lived, however, // due to the asynchronous connection establishment. synchronized (endpointsToChannelFutures) { final ChannelFuture curFuture = endpointsToChannelFutures.get(hostAndPort); if (curFuture != null) { log.info("Using exising connection..."); if (curFuture.getChannel().isConnected()) { onConnect.onConnect(curFuture); } else { final ChannelFutureListener cfl = new ChannelFutureListener() { public void operationComplete(final ChannelFuture future) throws Exception { onConnect.onConnect(curFuture); } }; curFuture.addListener(cfl); } } else { log.info("Establishing new connection"); /* final ChannelFutureListener closedCfl = new ChannelFutureListener() { public void operationComplete(final ChannelFuture closed) throws Exception { endpointsToChannelFutures.remove(hostAndPort); } }; */ final ChannelFuture cf = newChannelFuture(httpRequestCopy, inboundChannel); endpointsToChannelFutures.put(hostAndPort, cf); cf.addListener(new ChannelFutureListener() { public void operationComplete(final ChannelFuture future) throws Exception { final Channel channel = future.getChannel(); channelGroup.add(channel); if (future.isSuccess()) { log.info("Connected successfully to: {}", channel); log.info("Writing message on channel..."); final ChannelFuture wf = onConnect.onConnect(cf); wf.addListener(new ChannelFutureListener() { public void operationComplete(final ChannelFuture wcf) throws Exception { log.info("Finished write: "+wcf+ " to: "+ httpRequestCopy.getMethod()+" "+ httpRequestCopy.getUri()); } }); } else { log.info("Could not connect to "+hostAndPort, future.getCause()); if (browserToProxyConnections == 1) { log.warn("Closing browser to proxy channel " + "after not connecting to: {}", hostAndPort); me.getChannel().close(); endpointsToChannelFutures.remove(hostAndPort); } } } }); } } if (request.isChunked()) { readingChunks = true; } } private void writeConnectResponse(final ChannelHandlerContext ctx, final HttpRequest httpRequest, final Channel outgoingChannel) { final int port = ProxyUtils.parsePort(httpRequest); final Channel browserToProxyChannel = ctx.getChannel(); // TODO: We should really only allow access on 443, but this breaks // what a lot of browsers do in practice. //if (port != 443) { if (port < 0) { log.warn("Connecting on port other than 443!!"); final String statusLine = "HTTP/1.1 502 Proxy Error\r\n"; ProxyUtils.writeResponse(browserToProxyChannel, statusLine, ProxyUtils.PROXY_ERROR_HEADERS); } else { browserToProxyChannel.setReadable(false); // We need to modify both the pipeline encoders and decoders for the // browser to proxy channel *and* the encoders and decoders for the // proxy to external site channel. ctx.getPipeline().remove("encoder"); ctx.getPipeline().remove("decoder"); ctx.getPipeline().remove("handler"); ctx.getPipeline().addLast("handler", new HttpConnectRelayingHandler(outgoingChannel, this.channelGroup)); final String statusLine = "HTTP/1.1 200 Connection established\r\n"; ProxyUtils.writeResponse(browserToProxyChannel, statusLine, ProxyUtils.CONNECT_OK_HEADERS); browserToProxyChannel.setReadable(true); } } private ChannelFuture newChannelFuture(final HttpRequest httpRequest, final Channel browserToProxyChannel) { this.numWebConnections++; final String host; final int port; if (hostAndPort.contains(":")) { host = StringUtils.substringBefore(hostAndPort, ":"); final String portString = StringUtils.substringAfter(hostAndPort, ":"); port = Integer.parseInt(portString); } else { host = hostAndPort; port = 80; } // Configure the client. final ClientBootstrap cb = new ClientBootstrap(clientChannelFactory); final ChannelPipelineFactory cpf; if (httpRequest.getMethod() == HttpMethod.CONNECT) { // In the case of CONNECT, we just want to relay all data in both // directions. We SHOULD make sure this is traffic on a reasonable // port, however, such as 80 or 443, to reduce security risks. cpf = new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { // Create a default pipeline implementation. final ChannelPipeline pipeline = pipeline(); pipeline.addLast("handler", new HttpConnectRelayingHandler(browserToProxyChannel, channelGroup)); return pipeline; } }; } else { cpf = newDefaultRelayPipeline(httpRequest, browserToProxyChannel); } // Set up the event pipeline factory. cb.setPipelineFactory(cpf); cb.setOption("connectTimeoutMillis", 40*1000); // Start the connection attempt. log.info("Starting new connection to: "+hostAndPort); final ChannelFuture future = cb.connect(new InetSocketAddress(host, port)); return future; } private ChannelPipelineFactory newDefaultRelayPipeline( final HttpRequest httpRequest, final Channel browserToProxyChannel) { return new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { // Create a default pipeline implementation. final ChannelPipeline pipeline = pipeline(); // We always include the request and response decoders // regardless of whether or not this is a URL we're // filtering responses for. The reason is that we need to // follow connection closing rules based on the response // headers and HTTP version. // We also importantly need to follow the cache directives // in the HTTP response. pipeline.addLast("decoder", new HttpResponseDecoder()); log.info("Querying for host and port: {}", hostAndPort); final boolean shouldFilter; final HttpFilter filter = filters.get(hostAndPort); if (filter == null) { log.info("Filter not found in: {}", filters); shouldFilter = false; } else { log.info("Using filter: {}", filter); shouldFilter = filter.shouldFilterResponses(httpRequest); } log.info("Filtering: "+shouldFilter); // We decompress and aggregate chunks for responses from // sites we're applying rules to. if (shouldFilter) { pipeline.addLast("inflater", new HttpContentDecompressor()); pipeline.addLast("aggregator", new HttpChunkAggregator(filter.getMaxResponseSize()));//2048576)); } // The trick here is we need to determine whether or not // to cache responses based on the full URI of the request. // This request encoder will only get the URI without the // host, so we just have to be aware of that and construct // the original. final HttpRelayingHandler handler; if (shouldFilter) { handler = new HttpRelayingHandler(browserToProxyChannel, channelGroup, filter, HttpRequestHandler.this, hostAndPort); } else { handler = new HttpRelayingHandler(browserToProxyChannel, channelGroup, HttpRequestHandler.this, hostAndPort); } final ProxyHttpRequestEncoder encoder = new ProxyHttpRequestEncoder(handler); pipeline.addLast("encoder", encoder); pipeline.addLast("handler", handler); return pipeline; } }; } @Override public void channelOpen(final ChannelHandlerContext ctx, final ChannelStateEvent cse) throws Exception { final Channel inboundChannel = cse.getChannel(); log.info("New channel opened: {}", inboundChannel); totalBrowserToProxyConnections++; browserToProxyConnections++; log.info("Now "+totalBrowserToProxyConnections+ " browser to proxy channels..."); log.info("Now this class has "+browserToProxyConnections+ " browser to proxy channels..."); // We need to keep track of the channel so we can close it at the end. this.channelGroup.add(inboundChannel); } @Override public void channelClosed(final ChannelHandlerContext ctx, final ChannelStateEvent cse) { log.warn("Channel closed: {}", cse.getChannel()); totalBrowserToProxyConnections browserToProxyConnections log.info("Now "+totalBrowserToProxyConnections+ " total browser to proxy channels..."); log.info("Now this class has "+browserToProxyConnections+ " browser to proxy channels..."); // The following should always be the case with // @ChannelPipelineCoverage("one") if (browserToProxyConnections == 0) { log.warn("Closing all proxy to web channels for this browser " + "to proxy connection!!!"); final Collection<ChannelFuture> futures = this.endpointsToChannelFutures.values(); for (final ChannelFuture future : futures) { final Channel ch = future.getChannel(); if (ch.isOpen()) { future.getChannel().close(); } } } } public void onRelayChannelClose(final ChannelHandlerContext ctx, final ChannelStateEvent e, final Channel browserToProxyChannel, final String key) { this.numWebConnections if (this.numWebConnections == 0) { log.info("Closing browser to proxy channel"); closeOnFlush(browserToProxyChannel); } else { log.info("Not closing browser to proxy channel. Still "+ this.numWebConnections+" connections..."); } this.endpointsToChannelFutures.remove(key); if (numWebConnections != this.endpointsToChannelFutures.size()) { log.error("Something's amiss. We have "+numWebConnections+" and "+ this.endpointsToChannelFutures.size()+" connections stored"); } else { log.info("WEB CONNECTIONS COUNTS IN SYNC"); } } @Override public void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent e) throws Exception { final Channel channel = e.getChannel(); final Throwable cause = e.getCause(); if (cause instanceof ClosedChannelException) { log.warn("Caught an exception on browser to proxy channel: "+ channel, cause); } else { log.info("Caught an exception on browser to proxy channel: "+ channel, cause); } if (channel.isOpen()) { closeOnFlush(channel); } } /** * Closes the specified channel after all queued write requests are flushed. */ private static void closeOnFlush(final Channel ch) { log.warn("Closing on flush: {}", ch); if (ch.isConnected()) { ch.write(ChannelBuffers.EMPTY_BUFFER).addListener( ChannelFutureListener.CLOSE); } } }
package org.neo4j.kernel.impl.osgi; import org.neo4j.helpers.Service; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; /** * OSGi bundle activator to start an OSGi servicewatcher for kernel extensions. * */ public final class OSGiActivator implements BundleActivator { /** * Called whenever the OSGi framework starts our bundle */ public void start( BundleContext bc ) throws Exception { System.out.println( "STARTING neo4j-kernel" ); // start the extension listener Service.osgiExtensionLoader = new OSGiExtensionLoader( bc ); } /** * Called whenever the OSGi framework stops our bundle */ public void stop( BundleContext bc ) throws Exception { System.out.println( "STOPPING neo4j-kernel" ); // no need to unregister our service - the OSGi framework handles it for } }
package com.badlogic.gdx.graphics.g2d; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.Array; public class DistanceFieldFont extends BitmapFont { private float distanceFieldSmoothing; public DistanceFieldFont (BitmapFontData data, Array<TextureRegion> pageRegions, boolean integer) { super(data, pageRegions, integer); } public DistanceFieldFont (BitmapFontData data, TextureRegion region, boolean integer) { super(data, region, integer); } public DistanceFieldFont (FileHandle fontFile, boolean flip) { super(fontFile, flip); } public DistanceFieldFont (FileHandle fontFile, FileHandle imageFile, boolean flip, boolean integer) { super(fontFile, imageFile, flip, integer); } public DistanceFieldFont (FileHandle fontFile, FileHandle imageFile, boolean flip) { super(fontFile, imageFile, flip); } public DistanceFieldFont (FileHandle fontFile, TextureRegion region, boolean flip) { super(fontFile, region, flip); } public DistanceFieldFont (FileHandle fontFile, TextureRegion region) { super(fontFile, region); } public DistanceFieldFont (FileHandle fontFile) { super(fontFile); } protected void load (BitmapFontData data) { super.load(data); // Distance field font rendering requires font texture to be filtered linear. final Array<TextureRegion> regions = getRegions(); for (TextureRegion region : regions) region.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear); } @Override public BitmapFontCache newFontCache () { return new DistanceFieldFontCache(this, integer); } /** @return The distance field smoothing factor for this font. */ public float getDistanceFieldSmoothing () { return distanceFieldSmoothing; } /** @param distanceFieldSmoothing Set the distance field smoothing factor for this font. SpriteBatch needs to have this shader * set for rendering distance field fonts. */ public void setDistanceFieldSmoothing (float distanceFieldSmoothing) { this.distanceFieldSmoothing = distanceFieldSmoothing; } static public ShaderProgram createDistanceFieldShader () { String vertexShader = "attribute vec4 " + ShaderProgram.POSITION_ATTRIBUTE + ";\n" + "attribute vec4 " + ShaderProgram.COLOR_ATTRIBUTE + ";\n" + "attribute vec2 " + ShaderProgram.TEXCOORD_ATTRIBUTE + "0;\n" + "uniform mat4 u_projTrans;\n" + "varying vec4 v_color;\n" + "varying vec2 v_texCoords;\n" + "\n" + "void main() {\n" + " v_color = " + ShaderProgram.COLOR_ATTRIBUTE + ";\n" + " v_color.a = v_color.a * (255.0/254.0);\n" + " v_texCoords = " + ShaderProgram.TEXCOORD_ATTRIBUTE + "0;\n" + " gl_Position = u_projTrans * " + ShaderProgram.POSITION_ATTRIBUTE + ";\n" + "}\n"; String fragmentShader = "#ifdef GL_ES\n" + " precision mediump float;\n" + " precision mediump int;\n" + "#endif\n" + "\n" + "uniform sampler2D u_texture;\n" + "uniform float u_smoothing;\n" + "varying vec4 v_color;\n" + "varying vec2 v_texCoords;\n" + "\n" + "void main() {\n" + " if (u_smoothing > 0.0) {\n" + " float smoothing = 0.25 / u_smoothing;\n" + " float distance = texture2D(u_texture, v_texCoords).a;\n" + " float alpha = smoothstep(0.5 - smoothing, 0.5 + smoothing, distance);\n" + " gl_FragColor = vec4(v_color.rgb, alpha * v_color.a);\n" + " } else {\n" + " gl_FragColor = v_color * texture2D(u_texture, v_texCoords);\n" + " }\n" + "}\n"; ShaderProgram shader = new ShaderProgram(vertexShader, fragmentShader); if (!shader.isCompiled()) throw new IllegalArgumentException("Error compiling distance field shader: " + shader.getLog()); return shader; } /** Provides a font cache that uses distance field shader for rendering fonts. Attention: breaks batching because uniform is * needed for smoothing factor, so a flush is performed before and after every font rendering. * @author Florian Falkner */ static private class DistanceFieldFontCache extends BitmapFontCache { public DistanceFieldFontCache (DistanceFieldFont font) { super(font, font.usesIntegerPositions()); } public DistanceFieldFontCache (DistanceFieldFont font, boolean integer) { super(font, integer); } private float getSmoothingFactor () { final DistanceFieldFont font = (DistanceFieldFont)super.getFont(); return font.getDistanceFieldSmoothing() * font.getScaleX(); } private void setSmoothingUniform (Batch spriteBatch, float smoothing) { spriteBatch.flush(); spriteBatch.getShader().setUniformf("u_smoothing", smoothing); } @Override public void draw (Batch spriteBatch) { setSmoothingUniform(spriteBatch, getSmoothingFactor()); super.draw(spriteBatch); setSmoothingUniform(spriteBatch, 0); } @Override public void draw (Batch spriteBatch, int start, int end) { setSmoothingUniform(spriteBatch, getSmoothingFactor()); super.draw(spriteBatch, start, end); setSmoothingUniform(spriteBatch, 0); } } }
package de.saumya.mojo.proxy; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TreeSet; import de.saumya.mojo.proxy.Controller.FileLocation.Type; import de.saumya.mojo.ruby.GemScriptingContainer; public class Controller { private static final String SHA1 = ".sha1"; private static final String RUBYGEMS_URL = "https://rubygems.org/gems"; private static final String RUBYGEMS_S3_URL = "http://s3.amazonaws.com/production.s3.rubygems.org/gems"; static final Map<String, Set<String>> BROKEN_GEMS = new HashMap<String, Set<String>>(); static { // activeresource-2.0.0 does not exist !!! Set<String> rails = new TreeSet<String>(); rails.add("2.0.0"); BROKEN_GEMS.put("rails", rails); // juby-openssl-0.7.6 can not open gem with jruby-1.6.8 Set<String> openssl = new TreeSet<String>(); openssl.add("0.7.6"); BROKEN_GEMS.put("jruby-openssl", openssl); } private final File localStorage; private final GemScriptingContainer script = new GemScriptingContainer(); public static class FileLocation { enum Type { XML_CONTENT, HTML_CONTENT, ASCII_FILE, XML_FILE, REDIRECT, NOT_FOUND , ASCII_CONTENT, REDIRECT_TO_DIRECTORY, TEMP_UNAVAILABLE } public FileLocation() { this(null, null, null, Type.REDIRECT_TO_DIRECTORY); } public FileLocation(String message) { this(null, null, message, Type.NOT_FOUND); } public FileLocation(String content, Type type) { this(null, null, content, type); } public FileLocation(File local, Type type) { this(local, null, null, type); } public FileLocation(URL remote) { this(null, remote, null, Type.REDIRECT); } private FileLocation(File localFile, URL remoteFile, String content, Type type) { this.content = content; this.remoteUrl = remoteFile; this.localFile = localFile; this.type = type; } final File localFile; final URL remoteUrl; final String content; final Type type; } private final Object createPom; // assume there will be only one instance of this class per servlet container private final Set<String> fileLocks = new HashSet<String>(); public Controller(File storage) throws IOException{ this.localStorage = storage; this.localStorage.mkdirs(); this.createPom = script.runScriptletFromClassloader("create_pom.rb"); } public FileLocation locate(String path) throws IOException{ // release/rubygems/name/version // release/rubygems/name/version/ // release/rubygems/name/version/name-version.gem // release/rubygems/name/version/name-version.gem.md5 // release/rubygems/name/version/name-version.pom // release/rubygems/name/version/name-version.pom.md5 // release/rubygems/name // release/rubygems/name/ // release/rubygems/name/maven-metadata.xml path = path.replaceAll("/+", "/"); if(path.endsWith("/")){ path += "index.html"; } String[] parts = path.split("/"); if(parts.length == 0){ // TODO make listing with two directories 'releases', 'prereleases' return new FileLocation("for maven", Type.ASCII_CONTENT); } else { boolean prereleases = parts[0].contains("pre"); if(parts.length > 1 && !"rubygems".equals(parts[1])){ return notFound("Only rubygems/ groupId is supported through this proxy."); } switch(parts.length){ case 1: case 2: // TODO make listing with one directory 'rubygems' return notFound("directory listing not implemented"); case 3: if("index.html".equals(parts[2])) { return notFound("directory listing not implemented"); } else { return new FileLocation(); } case 4: if("maven-metadata.xml".equals(parts[3])){ return metadata(parts[2], prereleases); } else if(("maven-metadata.xml" + SHA1).equals(parts[3])){ return metadataSha1(parts[2], prereleases); } else if("index.html".equals(parts[3])){ return versionListDirectory(parts[2], path, prereleases); } else { return notFound("not found"); } case 5: String filename = parts[4]; if("index.html".equals(filename)){ return directory(parts[2], parts[3], path); } if(filename.endsWith(".gem")){ // keep it backward compatible filename = filename.replace("-java.gem", ".gem"); File local = new File(localStorage, filename.replace(".gem", ".pom")); if(!local.exists()){ if (!createFiles(parts[2], parts[3])){ return new FileLocation(filename + " is being generated", Type.TEMP_UNAVAILABLE); } } String url = RUBYGEMS_S3_URL + "/" + filename.replace(".gem", "-java.gem"); if ( !exists( url ) ) { // there are gem which use "jruby" as platform instead of "java" // like therubyrhino-1.72 url = RUBYGEMS_S3_URL + "/" + filename.replace(".gem", "-jruby.gem"); if ( !exists( url ) ) { url = RUBYGEMS_S3_URL + "/" + filename; } } return new FileLocation( new URL( url ) ); } if(filename.endsWith(SHA1) || filename.endsWith(".pom")){ File local = new File(localStorage, filename); if(!local.exists()){ try { if (!createFiles(parts[2], parts[3])){ return new FileLocation(filename + " is being generated", Type.TEMP_UNAVAILABLE); } } catch (FileNotFoundException e) { return notFound("not found"); } } return new FileLocation(local, filename.endsWith(SHA1)? Type.ASCII_FILE: Type.XML_FILE); } return notFound("not found"); default: return notFound("Completely unhandleable request!"); } } } public boolean exists(String url){ try { HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("HEAD"); return con.getResponseCode() == HttpURLConnection.HTTP_OK; } catch (FileNotFoundException e) { //e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } } private FileLocation directory(String gemname, String version, String path) throws IOException { HtmlDirectoryBuilder builder = new HtmlDirectoryBuilder(); builder.buildHeader(path); String basename = gemname + "-" + version; String pomfile = basename + ".pom"; String gemfile = basename + ".gem"; builder.buildFileLink(pomfile); builder.buildFileLink(pomfile + SHA1); builder.buildFileLink(gemfile); builder.buildFileLink(gemfile + SHA1); builder.buildFooter(); return new FileLocation(builder.toHTML(), Type.HTML_CONTENT); } private boolean createFiles(String name, String version) throws IOException { String gemname = name + "-" + version; try { synchronized (fileLocks) { if (fileLocks.contains(gemname)) { return false; } else { fileLocks.add(gemname); } } File gemfile = new File(this.localStorage, gemname + ".gem"); File gemfileSha = new File(this.localStorage, gemname + ".gem" + SHA1); File pomfile = new File(this.localStorage, gemname + ".pom"); File pomfileSha = new File(this.localStorage, gemname + ".pom" + SHA1); if (!(gemfileSha.exists() && pomfile.exists() && pomfileSha.exists())) { try { downloadGemfile(gemfile, new URL(RUBYGEMS_URL + "/" + gemname + "-java.gem")); } catch (FileNotFoundException e) { // there are gem which use "jruby" as platform nstead of "java" // like therubyrhino-1.72 try { downloadGemfile(gemfile, new URL(RUBYGEMS_URL + "/" + gemname + "-jruby.gem")); } catch (FileNotFoundException ee) { downloadGemfile(gemfile, new URL(RUBYGEMS_URL + "/" + gemname + ".gem")); } } String pom = createPom(gemfile); writeUTF8(pomfile, pom); writeUTF8(pomfileSha, sha1(pom)); } // we do not keep the gemfile on disc gemfile.delete(); return true; } finally { synchronized (fileLocks) { fileLocks.remove(gemname); } } } private String createPom(File gemfile) { // protect the script container synchronized (script) { return script.callMethod(createPom, "create", gemfile.getAbsolutePath(), String.class); } } private void downloadGemfile(File gemfile, URL url) throws IOException { InputStream input = null; OutputStream output = null; MessageDigest sha = newSha1Digest(); try { input = new BufferedInputStream(url.openStream()); output = new BufferedOutputStream(new FileOutputStream(gemfile)); int b = input.read(); while(b != -1){ output.write(b); sha.update((byte) b); b = input.read(); } } finally { if( input != null){ input.close(); } if( output != null){ output.close(); writeSha(new File(gemfile.getAbsolutePath() + SHA1), sha); } } } private void writeSha(File file, MessageDigest sha) throws IOException { writeUTF8(file, toHex(sha.digest())); } private void writeUTF8(File file, String content) throws IOException { PrintWriter writer = null; try { writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF-8"))); writer.print(content); } finally { if(writer != null){ writer.close(); } } } private FileLocation versionListDirectory(String name, String path, boolean prereleases) throws IOException { HtmlDirectoryBuilder html = new HtmlDirectoryBuilder(); html.buildHeader(path); VersionDirectoryBuilder builder = new VersionDirectoryBuilder(name, prereleases, html, BROKEN_GEMS.get(name)); builder.build(); html.buildFileLink("maven-metadata.xml"); html.buildFileLink("maven-metadata.xml" + SHA1); html.buildFooter(); return new FileLocation(html.toHTML(), Type.HTML_CONTENT); } private FileLocation notFound(String message) { return new FileLocation(message); } private FileLocation metadata(String name, boolean prereleases) throws IOException { MavenMetadataBuilder builder = new MavenMetadataBuilder(name, prereleases, BROKEN_GEMS.get(name)); builder.build(); return new FileLocation(builder.toXML(), Type.XML_CONTENT); } private FileLocation metadataSha1(String name, boolean prereleases) throws IOException { MavenMetadataBuilder builder = new MavenMetadataBuilder(name, prereleases, BROKEN_GEMS.get(name)); builder.build(); return new FileLocation(sha1(builder.toXML()), Type.ASCII_CONTENT); } private String sha1(String text) { MessageDigest md = newSha1Digest(); try { md.update(text.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException("should not happen", e); } return toHex(md.digest()); } private MessageDigest newSha1Digest() { MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("error getting sha1 instance", e); } return md; } private String toHex(byte[] data) { StringBuilder buf = new StringBuilder();//data.length * 2); for (byte b: data) { if(b < 0){ buf.append(Integer.toHexString(256 + b)); } else if(b < 16) { buf.append('0').append(Integer.toHexString(b)); } else { buf.append(Integer.toHexString(b)); } } return buf.toString(); } }
package org.jetel.component; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.ByteBuffer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.data.DataRecord; import org.jetel.data.Defaults; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.XMLConfigurationException; import org.jetel.graph.InputPortDirect; import org.jetel.graph.Node; import org.jetel.graph.OutputPortDirect; import org.jetel.graph.TransformationGraph; import org.jetel.interpreter.ParseException; import org.jetel.interpreter.TransformLangExecutor; import org.jetel.interpreter.TransformLangParser; import org.jetel.interpreter.node.CLVFStartExpression; import org.jetel.util.ComponentXMLAttributes; import org.jetel.util.SynchronizeUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; /** * <h3>Extended Filter Component</h3> * * <!-- All records for which the filterExpression evaluates TRUE are copied from input port:0 onto output port:0. * rejected records are copied to port:1 (if connected) --> * * <table border="1"> * <th>Component:</th> * <tr><td><h4><i>Name:</i></h4></td> * <td>Filter</td></tr> * <tr><td><h4><i>Category:</i></h4></td> * <td></td></tr> * <tr><td><h4><i>Description:</i></h4></td> * <td>All records for which the filterExpression evaluates TRUE are copied from input port:0 onto output port:0. Rejected records * are copied onto output port:1 (if it is connected).</td></tr> * <tr><td><h4><i>Inputs:</i></h4></td> * <td>[0]- input records</td></tr> * <tr><td><h4><i>Outputs:</i></h4></td> * <td>[0] - accepted records<br> * [1] - (optional) rejected records </td></tr> * <tr><td><h4><i>Comment:</i></h4></td> * <td>It can filter on text, date, integer, numeric * fields with comparison <code>[&gt;, &lt;, ==, &lt;=, &gt;=, !=]</code><br> * Text fields/expressions can also be compared to a * Java regexp. using <tt>~=</tt> (tilda,equal sign) characters<br> * A filter can be made of different parts separated by a logical * operator AND, OR. You can as well use parenthesis to give precendence<br> * <b>Note:</b>Date format used for specifying date value is <tt>yyyy-MM-dd</tt> for * dates only and <tt>yyyy-MM-dd HH:mm:ss</tt> for date&time. These patterns correspond * to values specified in "defaultProperties" file.<br> * When referencing particular field, you have to precede field's name with * dollar [$] sign - e.g. $FirstName.<br> * To ease the burden of converting comparison operators to XML-compatible form, * each operator has its textual abbreviation - <tt>[.eq. .ne. .lt. .le. .gt. .ge.]</tt><br> * Built-in functions you can use in expressions: * <ul> * <li>today() * <li>uppercase( ..str expression.. ) * <li>lowercase( ..str expression.. ) * <li>substring( ..str expression.. , from, length) * <li>trim( .. str expression.. ) * <li>length( ..str expression.. ) * <li>isnull( &lt;field reference&gt; ) * <li>concat( ..str expression.., ..str expression.. , ...... ) * <li>dateadd( ..date expression.., ..amount.. , year|month|day|hour|minute|sec ) * <li>datediff( ..date expression.., ..date expression.. , year|month|day|hour|minute|sec ) * <li>nvl(&lt;field reference&gt;, ..expression.. ) * <li>replace(..str expression.., ..regex_pattern.., ..str expression.. ) * <li>num2str(..num expression.. ) * <li>str2num(..str expression.. ) * <li>iif ( ..condition expression .. , ..expression.. , ..expression.. ) * <li>print_err ( ..str expression.. ) * <li>date2str(..date expression..,..format str expression..) * <li>str2date(..str expression.., .. format str expression..) * </ul> * </td></tr> * </table> * <br> * <table border="1"> * <th>XML attributes:</th> * <tr><td><b>type</b></td><td>"EXT_FILTER"</td></tr> * <tr><td><b>id</b></td> * <td>component identification</td> * </tr> * <tr><td><b>filterExpression</b></td><td>Expression used for filtering records. <i>See above.</i></td></tr> * </table> * <i>Note: you can also put the expression inside the XML Node - see examples.</i> * <h4>Examples:</h4> * Want to filter on HireDate field. HireDate must be less than 31st of December 1993<br> * <pre>&lt;Node id="FILTEREMPL1" type="EXT_FILTER" filterExpression="$HireDate &amp;lt; &quot;1993-12-31&quot;"/&gt;</pre> * Want to filter on Name and Age fields. Name must start with 'A' char and Age must be greater than 25<br> * <pre>&lt;Node id="FILTEREMPL1" type="EXT_FILTER" filterExpression="$Name~=&quot;^A.*&quot; and $Age &amp;gt;25"/&gt;</pre> * <pre>&lt;Node id="FILTEREMPL1" type="EXT_FILTER"&gt; * $Name~="^A.*" and $Age.gt.25 *&lt;/Node&gt;</pre> * More complex example showing how to use various built-in functions.<br> * <pre>&lt;Node id="FILTEREMPL1" type="EXT_FILTER"&gt; * ( trim($CustomerName)~=".*Peter.*" or $DateSale==dateadd(today(),-1,month)) and $Age*2.lt.$Weight-10 *&lt;/Node&gt;</pre> * </pre> * Evaluating data fields with NULL values (have isNull() set) results in runtime error. To * circumvent such situation, use <code>isnull</code> and <code>nvl</code> functions.<br> * <pre>&lt;Node id="FILTEREMPL1" type="EXT_FILTER"&gt; * !isnull($CustomerName) && $CustomerName~=".*Peter.*" or nvl($DateSale,2001-1-1)>=$DateInvoice *&lt;/Node&gt;</pre> * </pre> * <br> * <b>Hint:</b> If you have combination of filtering expressions connected by AND operator, it * is wise to write first those which can be quickly evaluated - comparing integers, numbers, dates. * * @author dpavlis * @since Sep 01, 2004 * @see org.jetel.graph.TransformationGraph * @see org.jetel.graph.Node * @see org.jetel.graph.Edge */ public class ExtFilter extends org.jetel.graph.Node { private static final String XML_FILTEREXPRESSION_ATTRIBUTE = "filterExpression"; public final static String COMPONENT_TYPE="EXT_FILTER"; private final static int READ_FROM_PORT=0; private final static int WRITE_TO_PORT=0; private final static int REJECTED_PORT=1; private CLVFStartExpression recordFilter; private String filterExpression; static Log logger = LogFactory.getLog(ExtFilter.class); public ExtFilter(String id){ super(id); } /** * Main processing method for the Filter object * * @since July 23, 2002 */ public void run() { InputPortDirect inPort=getInputPortDirect(READ_FROM_PORT); OutputPortDirect outPort=getOutputPortDirect(WRITE_TO_PORT); OutputPortDirect rejectedPort=getOutputPortDirect(REJECTED_PORT); boolean isData=true; TransformLangExecutor executor=new TransformLangExecutor(); DataRecord record = new DataRecord(getInputPort(READ_FROM_PORT).getMetadata()); record.init(); ByteBuffer recordBuffer=ByteBuffer.allocateDirect(Defaults.Record.MAX_RECORD_SIZE); executor.setInputRecords(new DataRecord[] {record}); while(isData && runIt){ try{ recordBuffer.clear(); if (!inPort.readRecordDirect(recordBuffer)){ isData = false; break; } record.deserialize(recordBuffer); executor.visit(recordFilter,null); if (((Boolean)executor.getResult()).booleanValue()){ recordBuffer.rewind(); outPort.writeRecordDirect(recordBuffer); }else if (rejectedPort!=null){ recordBuffer.rewind(); rejectedPort.writeRecordDirect(recordBuffer); } }catch(IOException ex){ resultMsg=ex.getMessage(); resultCode=Node.RESULT_ERROR; closeAllOutputPorts(); return; }catch(ClassCastException ex){ resultMsg="Invalid filter expression - does not evaluate to TRUE/FALSE !"; resultCode=Node.RESULT_FATAL_ERROR; closeAllOutputPorts(); return; }catch(Exception ex){ resultMsg=ex.getClass().getName()+" : "+ ex.getMessage(); resultCode=Node.RESULT_FATAL_ERROR; return; } SynchronizeUtils.cloverYield(); } broadcastEOF(); if (runIt) resultMsg="OK"; else resultMsg="STOPPED"; resultCode=Node.RESULT_OK; } /** * Description of the Method * * @since July 23, 2002 */ public void init() throws ComponentNotReadyException { // test that we have at least one input port and one output if (inPorts.size()<1){ throw new ComponentNotReadyException("At least one input port has to be defined!"); }else if (outPorts.size()<1){ throw new ComponentNotReadyException("At least one output port has to be defined!"); } TransformLangParser parser=new TransformLangParser(getInputPort(READ_FROM_PORT).getMetadata(), new ByteArrayInputStream(filterExpression.getBytes())); if (parser!=null){ try { recordFilter = parser.StartExpression(); }catch (ParseException ex) { throw new ComponentNotReadyException("Parser error when parsing expression: "+ex.getMessage()); }catch (Exception e) { throw new ComponentNotReadyException("Error when parsing expression: "+e.getMessage()); } try{ recordFilter.init(); }catch (Exception e) { throw new ComponentNotReadyException("Error when initializing expression executor: "+e.getMessage()); } }else{ throw new ComponentNotReadyException("Can't create filter expression parser !"); } } /** * Description of the Method * * @return Description of the Returned Value * @since July 23, 2002 */ public void toXML(Element xmlElement) { super.toXML(xmlElement); Document doc = xmlElement.getOwnerDocument(); Element childElement = doc.createElement("attr"); childElement.setAttribute("name", XML_FILTEREXPRESSION_ATTRIBUTE); // join given SQL commands Text textElement = doc.createTextNode(filterExpression); childElement.appendChild(textElement); xmlElement.appendChild(childElement); } /** * Description of the Method * * @param nodeXML Description of Parameter * @return Description of the Returned Value * @since July 23, 2002 */ @Override public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException { ExtFilter filter; ComponentXMLAttributes xattribs=new ComponentXMLAttributes(xmlElement, graph); try{ filter = new ExtFilter(xattribs.getString(XML_ID_ATTRIBUTE)); if (xattribs.exists(XML_FILTEREXPRESSION_ATTRIBUTE)){ filter.setFilterExpression(xattribs.getString(XML_FILTEREXPRESSION_ATTRIBUTE)); }else{ filter.setFilterExpression(xattribs.getText(xmlElement)); } return filter; }catch(Exception ex){ throw new XMLConfigurationException(COMPONENT_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE," unknown ID ") + ":" + ex.getMessage(),ex); } } /** Description of the Method */ public boolean checkConfig() { return true; } /** * @param filterExpression The filterExpression to set. */ public void setFilterExpression(String filterExpression) { this.filterExpression = filterExpression; } public String getType(){ return COMPONENT_TYPE; } }
package org.tapestry.controller; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.tapestry.dao.AppointmentDao; import org.tapestry.dao.PatientDao; import org.tapestry.dao.SurveyResultDao; import org.tapestry.objects.Appointment; import org.tapestry.objects.Patient; import org.tapestry.objects.Report; import org.tapestry.objects.SurveyResult; import org.tapestry.report.AlertManager; import org.tapestry.report.AlertsInReport; import org.tapestry.report.ScoresInReport; import org.tapestry.surveys.ResultParser; import org.tapestry.report.CalculationManager; import org.yaml.snakeyaml.Yaml; import org.tapestry.myoscar.utils.*; import org.oscarehr.myoscar_server.ws.PersonTransfer3; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Document; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.Image; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Phrase; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; @Controller public class ReportController { protected static Logger logger = Logger.getLogger(AppointmentController.class); private ClassPathResource dbConfigFile; private Map<String, String> config; private Yaml yaml; private PatientDao patientDao; private AppointmentDao appointmentDao; private SurveyResultDao surveyResultDao; /** * Reads the file /WEB-INF/classes/db.yaml and gets the values contained therein */ @PostConstruct public void readDatabaseConfig(){ String DB = ""; String UN = ""; String PW = ""; try{ dbConfigFile = new ClassPathResource("tapestry.yaml"); yaml = new Yaml(); config = (Map<String, String>) yaml.load(dbConfigFile.getInputStream()); DB = config.get("url"); UN = config.get("username"); PW = config.get("password"); } catch (IOException e) { System.out.println("Error reading from config file"); System.out.println(e.toString()); } patientDao = new PatientDao(DB, UN, PW); appointmentDao = new AppointmentDao(DB, UN, PW); surveyResultDao = new SurveyResultDao(DB, UN, PW); } @RequestMapping(value="/view_report/{patientID}", method=RequestMethod.GET) public String viewReport(@PathVariable("patientID") int id, @RequestParam(value="appointmentId", required=true) int appointmentId, ModelMap model, HttpServletResponse response){ Patient patient = patientDao.getPatientByID(id); //call web service to get patient info from myoscar String userName = "carolchou.test"; try{ PersonTransfer3 personInMyoscar = ClientManager.getClientByUsername(userName); StringBuffer sb = new StringBuffer(); if (personInMyoscar.getStreetAddress1() != null) sb.append(personInMyoscar.getStreetAddress1()); String city = personInMyoscar.getCity(); if (city != null) { sb.append(", "); sb.append(city); patient.setCity(city); } if (personInMyoscar.getProvince() != null) { sb.append(", "); sb.append(personInMyoscar.getProvince()); } patient.setAddress(sb.toString()); if (personInMyoscar.getBirthDate() != null) { Calendar birthDay = personInMyoscar.getBirthDate(); patient.setBod(Utils.getDateByCalendar(birthDay)); } } catch (Exception e){ System.err.println("Have some problems when calling myoscar web service"); } Appointment appointment = appointmentDao.getAppointmentById(appointmentId); Report report = new Report(); ScoresInReport scores = new ScoresInReport(); report.setPatient(patient); //Plan and Key Observations String keyObservation = appointmentDao.getKeyObservationByAppointmentId(appointmentId); String plan = appointmentDao.getPlanByAppointmentId(appointmentId); appointment.setKeyObservation(keyObservation); appointment.setPlans(plan); report.setAppointment(appointment); List<SurveyResult> surveyResultList = surveyResultDao.getCompletedSurveysByPatientID(id); SurveyResult healthGoalsSurvey = new SurveyResult(); SurveyResult dailyLifeActivitySurvey = new SurveyResult(); SurveyResult nutritionSurvey = new SurveyResult(); SurveyResult rAPASurvey = new SurveyResult(); SurveyResult mobilitySurvey = new SurveyResult(); SurveyResult socialLifeSurvey = new SurveyResult(); SurveyResult generalHealthySurvey = new SurveyResult(); SurveyResult memorySurvey = new SurveyResult(); SurveyResult carePlanSurvey = new SurveyResult(); SurveyResult goals = new SurveyResult(); for(SurveyResult survey: surveyResultList){ String title = survey.getSurveyTitle(); if (title.equalsIgnoreCase("Goal Setting"))//Goal Setting survey healthGoalsSurvey = survey; if (title.equalsIgnoreCase("Daily Life Activities"))//Daily life activity survey dailyLifeActivitySurvey = survey; if (title.equalsIgnoreCase("Screen II"))//Nutrition nutritionSurvey = survey; if (title.equalsIgnoreCase("Rapid Assessment of Physical Activity"))//RAPA survey rAPASurvey = survey; if (title.equalsIgnoreCase("Mobility Survey"))//Mobility survey mobilitySurvey = survey; if (title.equalsIgnoreCase("Social Life")) //Social Life(Duke Index of Social Support) socialLifeSurvey = survey; if (title.equalsIgnoreCase("General Health")) //General Health(Edmonton Frail Scale) generalHealthySurvey = survey; if (title.equalsIgnoreCase("Memory")) //Memory Survey memorySurvey = survey; if (title.equalsIgnoreCase("Advance_Directives")) //Care Plan/Advanced_Directive survey carePlanSurvey = survey; if (title.equalsIgnoreCase("GAS")) goals = survey; } String xml; //Healthy Goals try{ xml = new String(healthGoalsSurvey.getResults(), "UTF-8"); } catch (Exception e) { xml = ""; } LinkedHashMap<String, String> mHealthGoalsSurvey = ResultParser.getResults(xml); List<String> qList = new ArrayList<String>(); List<String> questionTextList = new ArrayList<String>(); questionTextList = ResultParser.getSurveyQuestions(xml); //get answer list qList = getQuestionList(mHealthGoalsSurvey); Map<String, String> sMap = new TreeMap<String, String>(); sMap = getSurveyContentMap(questionTextList, qList); report.setHealthGoals(sMap); //Additional Information //Memory try{ xml = new String(memorySurvey.getResults(), "UTF-8"); } catch (Exception e) { xml = ""; } LinkedHashMap<String, String> mMemorySurvey = ResultParser.getResults(xml); qList = new ArrayList<String>(); questionTextList = new ArrayList<String>(); questionTextList = ResultParser.getSurveyQuestions(xml); //only keep the second and forth question text in the list if ((questionTextList != null) && (questionTextList.size() > 0)) { List<String> displayQuestionTextList = new ArrayList<String>(); displayQuestionTextList.add(removeObserverNotes(questionTextList.get(1))); displayQuestionTextList.add(removeObserverNotes(questionTextList.get(3))); displayQuestionTextList = removeRedundantFromQuestionText(displayQuestionTextList, "of 2"); //get answer list qList = getQuestionListForMemorySurvey(mMemorySurvey); sMap = new TreeMap<String, String>(); //Care Plan/Advanced_Directive try{ xml = new String(carePlanSurvey.getResults(), "UTF-8"); } catch (Exception e) { xml = ""; } LinkedHashMap<String, String> mCarePlanSurvey = ResultParser.getResults(xml); questionTextList = new ArrayList<String>(); questionTextList = ResultParser.getSurveyQuestions(xml); //take 3 question text from the list for (int i = 1; i <= 3; i++) displayQuestionTextList.add(removeObserverNotes(questionTextList.get(i))); displayQuestionTextList = removeRedundantFromQuestionText(displayQuestionTextList, "of 3"); //get answer list qList.addAll(getQuestionList(mCarePlanSurvey)); sMap = getSurveyContentMapForMemorySurvey(displayQuestionTextList, qList); report.setAdditionalInfos(sMap); } //Daily Life Activities try{ xml = new String(dailyLifeActivitySurvey.getResults(), "UTF-8"); } catch (Exception e) { xml = ""; } LinkedHashMap<String, String> mDailyLifeActivitySurvey = ResultParser.getResults(xml); questionTextList = new ArrayList<String>(); questionTextList = ResultParser.getSurveyQuestions(xml); qList = new ArrayList<String>(); qList = getQuestionList(mDailyLifeActivitySurvey); //last question in Daily life activity survey is about falling stuff List<String> lAlert = new ArrayList<String>(); String fallingQA = qList.get(qList.size() -1); if (fallingQA.startsWith("yes")||fallingQA.startsWith("Yes")) lAlert.add(AlertsInReport.DAILY_ACTIVITY_ALERT); sMap = new TreeMap<String, String>(); sMap = getSurveyContentMap(questionTextList, qList); report.setDailyActivities(sMap); //General Healthy Alert try{ xml = new String(generalHealthySurvey.getResults(), "UTF-8"); } catch (Exception e) { xml = ""; } LinkedHashMap<String, String> mGeneralHealthySurvey = ResultParser.getResults(xml); qList = new ArrayList<String>(); //get answer list qList = getQuestionList(mGeneralHealthySurvey); //get score info for Summary of tapestry tools if ("1".equals(qList.get(0))) scores.setClockDrawingTest("No errors"); else if ("2".equals(qList.get(0))) scores.setClockDrawingTest("Minor spacing errors"); else if ("3".equals(qList.get(0))) scores.setClockDrawingTest("Other errors"); else scores.setClockDrawingTest("Not done"); if ("1".equals(qList.get(10))) scores.setTimeUpGoTest("1 (0-10s)"); else if ("2".equals(qList.get(10))) scores.setTimeUpGoTest("2 (11-20s)"); else if ("3".equals(qList.get(10))) scores.setTimeUpGoTest("3 (More than 20s)"); else if ("4".equals(qList.get(10))) scores.setTimeUpGoTest("4 (Patient required assistance)"); else scores.setTimeUpGoTest("5 (Patient is unwilling)"); int generalHealthyScore = CalculationManager.getScoreByQuestionsList(qList); lAlert = AlertManager.getGeneralHealthyAlerts(generalHealthyScore, lAlert); if (generalHealthyScore < 5) scores.setEdmontonFrailScale(String.valueOf(generalHealthyScore) + " (Robust)"); else if (generalHealthyScore < 7) scores.setEdmontonFrailScale(String.valueOf(generalHealthyScore) + " (Apparently Vulnerable)"); else scores.setEdmontonFrailScale(String.valueOf(generalHealthyScore) + " (Frail)"); //Social Life Alert try{ xml = new String(socialLifeSurvey.getResults(), "UTF-8"); } catch (Exception e) { xml = ""; } LinkedHashMap<String, String> mSocialLifeSurvey = ResultParser.getResults(xml); qList = new ArrayList<String>(); //get answer list qList = getQuestionList(mSocialLifeSurvey); int socialLifeScore = CalculationManager.getScoreByQuestionsList(qList); lAlert = AlertManager.getSocialLifeAlerts(socialLifeScore, lAlert); //summary tools for social supports int satisfactionScore = CalculationManager.getScoreByQuestionsList(qList.subList(0, 6)); scores.setSocialSatisfication(satisfactionScore); int networkScore = CalculationManager.getScoreByQuestionsList(qList.subList(6, 10)); scores.setSocialNetwork(networkScore); //Nutrition Alerts try{ xml = new String(nutritionSurvey.getResults(), "UTF-8"); } catch (Exception e) { xml = ""; } LinkedHashMap<String, String> mNutritionSurvey = ResultParser.getResults(xml); qList = new ArrayList<String>(); //get answer list qList = getQuestionList(mNutritionSurvey); //get scores for nutrition survey based on answer list int nutritionScore = CalculationManager.getScoreByQuestionsList(qList); scores.setNutritionScreen(nutritionScore); //high nutrition risk alert Map<String, String> nAlert = new TreeMap<String, String>(); lAlert = AlertManager.getNutritionAlerts(nutritionScore, lAlert, qList); //set alerts in report bean if (nAlert != null && nAlert.size()>0) report.setAlerts(lAlert); else report.setAlerts(null); //RAPA Alert try{ xml = new String(rAPASurvey.getResults(), "UTF-8"); } catch (Exception e) { xml = ""; } LinkedHashMap<String, String> mRAPASurvey = ResultParser.getResults(xml); qList = new ArrayList<String>(); //get answer list qList = getQuestionList(mRAPASurvey); int rAPAScore = CalculationManager.getScoreForRAPA(qList); if (rAPAScore < 6) lAlert.add(AlertsInReport.PHYSICAL_ACTIVITY_ALERT); scores.setPhysicalActivity(rAPAScore); //Mobility Alerts try{ xml = new String(mobilitySurvey.getResults(), "UTF-8"); } catch (Exception e) { xml = ""; } LinkedHashMap<String, String> mMobilitySurvey = ResultParser.getResults(xml); Map<String, String> qMap = getQuestionMap(mMobilitySurvey); lAlert = AlertManager.getMobilityAlerts(qMap, lAlert); //summary tools for Mobility for (int i = 0; i < lAlert.size(); i++) { if (lAlert.get(i).contains("2.0")) scores.setMobilityWalking2(lAlert.get(i)); if (lAlert.get(i).contains("0.5")) scores.setMobilityWalkingHalf(lAlert.get(i)); if (lAlert.get(i).contains("climbing")) scores.setMobilityClimbing(lAlert.get(i)); } String noLimitation = "No Limitation"; if (Utils.isNullOrEmpty(scores.getMobilityWalking2())) scores.setMobilityWalking2(noLimitation); if (Utils.isNullOrEmpty(scores.getMobilityWalkingHalf())) scores.setMobilityWalkingHalf(noLimitation); if (Utils.isNullOrEmpty(scores.getMobilityClimbing())) scores.setMobilityClimbing(noLimitation); report.setScores(scores); model.addAttribute("scores", scores); report.setAlerts(lAlert); //end of alert try{ xml = new String(goals.getResults(), "UTF-8"); } catch (Exception e) { xml = ""; } LinkedHashMap<String, String> mGoals = ResultParser.getResults(xml); questionTextList = ResultParser.getSurveyQuestions(xml); //get answer list qList = getQuestionList(mGoals); for (int i =0; i<qList.size(); i++) System.out.println("Goals is === " + i + " " + qList.get(i)); // sMap = new TreeMap<String, String>(); // sMap = getSurveyContentMap(questionTextList, qList); // report.setHealthGoals(sMap); //get volunteer information String volunteer = appointment.getVolunteer(); String partner = appointment.getPartner(); String comments = appointment.getComments(); Map<String, String> vMap = new TreeMap<String, String>(); if (!Utils.isNullOrEmpty(volunteer)) vMap.put(" 1", volunteer); else vMap.put(" 1", ""); if (!Utils.isNullOrEmpty(partner)) vMap.put(" 2", partner); else vMap.put(" 2", ""); if (!Utils.isNullOrEmpty(comments)) vMap.put(" V", comments); else vMap.put(" V", " "); report.setVolunteerInformations(vMap); model.addAttribute("report", report); // return "/admin/view_report"; buildPDF(report, response); return null; } private void buildPDF(Report report, HttpServletResponse response){ String orignalFileName="reportTest.pdf"; try { Document document = new Document(); response.setHeader("Content-Disposition", "outline;filename=\"" +orignalFileName+ "\""); PdfWriter.getInstance(document, response.getOutputStream()); document.open(); Image imageFhs = Image.getInstance("webapps/tapestry/resources/images/fhs.png"); imageFhs.scalePercent(25f); imageFhs.setAbsolutePosition(450, PageSize.A4.getHeight() - imageFhs.getScaledHeight()); document.add(imageFhs); Image imageLogo = Image.getInstance("webapps/tapestry/resources/images/logo.png"); imageLogo.scalePercent(25f); imageLogo.setAbsolutePosition(0, PageSize.A4.getHeight() - imageFhs.getScaledHeight()); document.add(imageLogo); Image imageDegroote = Image.getInstance("webapps/tapestry/resources/images/degroote.png"); imageDegroote.scalePercent(25f); imageDegroote.setAbsolutePosition(200, PageSize.A4.getHeight() - imageFhs.getScaledHeight()); document.add(imageDegroote); document.add(new Phrase(" ")); document.add(new Phrase(" ")); document.add(new Phrase(" ")); //tapestry report //Font setup //white font Font wbLargeFont = new Font(Font.FontFamily.HELVETICA , 20, Font.BOLD); wbLargeFont.setColor(BaseColor.WHITE); Font wMediumFont = new Font(Font.FontFamily.HELVETICA , 16, Font.BOLD); wMediumFont.setColor(BaseColor.WHITE); //red font Font rbFont = new Font(Font.FontFamily.HELVETICA, 20, Font.BOLD); rbFont.setColor(BaseColor.RED); Font rmFont = new Font(Font.FontFamily.HELVETICA, 16); rmFont.setColor(BaseColor.RED); Font rFont = new Font(Font.FontFamily.HELVETICA, 20); rFont.setColor(BaseColor.RED); Font rMediumFont = new Font(Font.FontFamily.HELVETICA, 12); rMediumFont.setColor(BaseColor.RED); Font rSmallFont = new Font(Font.FontFamily.HELVETICA, 8); rSmallFont.setColor(BaseColor.RED); //green font Font gbMediumFont = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD); gbMediumFont.setColor(BaseColor.GREEN); Font gbSmallFont = new Font(Font.FontFamily.HELVETICA, 9, Font.BOLD); gbSmallFont.setColor(BaseColor.GREEN); //black font Font sFont = new Font(Font.FontFamily.HELVETICA, 9); Font sbFont = new Font(Font.FontFamily.HELVETICA, 9, Font.BOLD); Font mFont = new Font(Font.FontFamily.HELVETICA, 12); Font bMediumFont = new Font(Font.FontFamily.HELVETICA , 16, Font.BOLD); Font iSmallFont = new Font(Font.FontFamily.HELVETICA , 9, Font.ITALIC ); Font ibMediumFont = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLDITALIC); Font bmFont = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD); Font blFont = new Font(Font.FontFamily.HELVETICA, 20, Font.BOLD); //Patient info PdfPTable table = new PdfPTable(2); table.setWidthPercentage(100); float[] columWidths = {1f, 2f}; table.setWidths(columWidths); PdfPCell cell; String patientName = report.getPatient().getFirstName() + " " + report.getPatient().getLastName(); cell = new PdfPCell(new Phrase(patientName, sbFont)); cell.setBorderWidthTop(1f); cell.setBorderWidthLeft(1f); cell.setBorderWidthBottom(0); cell.setBorderWidthRight(0); table.addCell(cell); cell = new PdfPCell(new Phrase("Address: 11 hunter Street S, Hamilton, On" + report.getPatient().getAddress(), sbFont)); cell.setBorderWidthTop(1f); cell.setBorderWidthRight(1f); cell.setBorderWidthLeft(0); cell.setBorderWidthBottom(0); table.addCell(cell); cell = new PdfPCell(new Phrase("MRP: David Chan", sbFont)); cell.setBorderWidthLeft(1f); cell.setBorderWidthTop(0); cell.setBorderWidthBottom(0); cell.setBorderWidthRight(0); table.addCell(cell); cell = new PdfPCell( new Phrase("Date of visit: " + report.getAppointment().getDate(), sbFont)); cell.setBorderWidthRight(1f); cell.setBorderWidthTop(0); cell.setBorderWidthLeft(0); cell.setBorderWidthBottom(0); table.addCell(cell); cell = new PdfPCell(new Phrase("Time: " + report.getAppointment().getTime(), sbFont)); cell.setBorderWidthLeft(1f); cell.setBorderWidthBottom(1f); cell.setBorderWidthTop(0); cell.setBorderWidthRight(0); table.addCell(cell); cell = new PdfPCell(new Phrase("Visit: " + report.getAppointment().getStrType(), sbFont)); cell.setBorderWidthRight(1f); cell.setBorderWidthBottom(1f); cell.setBorderWidthTop(0); cell.setBorderWidthLeft(0); table.addCell(cell); document.add(table); //Patient Info table = new PdfPTable(1); table.setWidthPercentage(100); cell = new PdfPCell(new Phrase("TAPESTRY REPORT: --- (0000-00-00)", blFont)); cell.setBorder(0); table.addCell(cell); cell = new PdfPCell(new Phrase("PATIENT GOAL(S)", wbLargeFont)); cell.setBackgroundColor(BaseColor.BLACK); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); table.addCell(cell); String[] goals = {"health food","low blood pressure", "walking 2 km a day", "swim once a week", "loose 5 lb in 2 months"}; for (int i=0; i<5; i++){ cell = new PdfPCell(new Phrase(goals[i])); table.addCell(cell); } document.add(table); //alert table = new PdfPTable(1); table.setWidthPercentage(100); Phrase comb = new Phrase(); comb.add(new Phrase(" ALERT :", rbFont)); comb.add(new Phrase(" Consider Case Review wirh IP-TEAM", wbLargeFont)); cell.addElement(comb); cell.setBackgroundColor(BaseColor.BLACK); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); table.addCell(cell); List<String> alerts = report.getAlerts(); for (int i =0; i<alerts.size(); i++){ cell = new PdfPCell(new Phrase(alerts.get(i).toString(), rmFont)); table.addCell(cell); } document.add(table); document.add(new Phrase(" ")); //Key observation table = new PdfPTable(1); table.setWidthPercentage(100); cell = new PdfPCell(new Phrase("KEY OBSERVATIONS by Volunteer", wbLargeFont)); cell.setBackgroundColor(BaseColor.BLACK); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); table.addCell(cell); cell = new PdfPCell(new Phrase(report.getAppointment().getKeyObservation())); table.addCell(cell); document.add(table); document.add(new Phrase(" ")); //Plan table = new PdfPTable(2); table.setWidthPercentage(100); cell = new PdfPCell(new Phrase("PLAN", wbLargeFont)); cell.setBackgroundColor(BaseColor.BLACK); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setColspan(2); table.addCell(cell); List<String> pList = new ArrayList<String>(); if (!Utils.isNullOrEmpty(report.getAppointment().getPlans())) pList = Arrays.asList(report.getAppointment().getPlans().split(",")); Map<String, String> pMap = new TreeMap<String, String>(); for (int i = 1; i<= pList.size(); i++){ pMap.put(String.valueOf(i), pList.get(i-1)); } for (Map.Entry<String, String> entry : pMap.entrySet()) { cell = new PdfPCell(new Phrase(entry.getKey())); table.addCell(cell); cell = new PdfPCell(new Phrase(entry.getValue())); table.addCell(cell); } float[] cWidths = {1f, 18f}; table.setWidths(cWidths); document.add(table); //Additional Information table = new PdfPTable(2); table.setWidthPercentage(100); cell = new PdfPCell(new Phrase("ADDITIONAL INFORMATION", wbLargeFont)); cell.setBackgroundColor(BaseColor.BLACK); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setColspan(2); table.addCell(cell); for (Map.Entry<String, String> entry : report.getAdditionalInfos().entrySet()) { if ("YES".equalsIgnoreCase(entry.getValue())){ cell = new PdfPCell(new Phrase(entry.getKey(), rMediumFont)); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPaddingBottom(5); table.addCell(cell); cell = new PdfPCell(new Phrase(entry.getValue(), rMediumFont)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPaddingBottom(5); table.addCell(cell); } else{ cell = new PdfPCell(new Phrase(entry.getKey(), mFont)); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPaddingBottom(5); table.addCell(cell); cell = new PdfPCell(new Phrase(entry.getValue(), mFont)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setPaddingBottom(5); table.addCell(cell); } } float[] aWidths = {24f, 3f}; table.setWidths(aWidths); document.add(table); document.add(new Phrase(" ")); //Summary of Tapestry tools table = new PdfPTable(3); table.setWidthPercentage(100); table.setWidths(new float[]{1.2f, 2f, 2f}); cell = new PdfPCell(new Phrase("Summary of TAPESTRY Tools", wbLargeFont)); cell.setBackgroundColor(BaseColor.GRAY); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setFixedHeight(28f); cell.setColspan(3); table.addCell(cell); cell = new PdfPCell(new Phrase("DOMAIN", wMediumFont)); cell.setBackgroundColor(BaseColor.BLACK); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setFixedHeight(28f); table.addCell(cell); cell = new PdfPCell(new Phrase("SCORE", wMediumFont)); cell.setBackgroundColor(BaseColor.BLACK); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setFixedHeight(28f); table.addCell(cell); cell = new PdfPCell(new Phrase("DESCRIPTION", wMediumFont)); cell.setBackgroundColor(BaseColor.BLACK); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setFixedHeight(28f); table.addCell(cell); cell = new PdfPCell(new Phrase("Functional Status", mFont)); cell.setBackgroundColor(BaseColor.LIGHT_GRAY); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setMinimumHeight(45f); table.addCell(cell); StringBuffer sb = new StringBuffer(); sb.append("Clock drawing test: "); sb.append(report.getScores().getClockDrawingTest()); sb.append("\n"); sb.append("Timed up-and-go test score = "); sb.append(report.getScores().getTimeUpGoTest()); sb.append("\n"); sb.append("Edmonton Frail Scale sore = "); sb.append(report.getScores().getEdmontonFrailScale()); sb.append("\n"); cell = new PdfPCell(new Phrase(sb.toString(), iSmallFont)); cell.setBackgroundColor(BaseColor.LIGHT_GRAY); cell.setNoWrap(false); table.addCell(cell); sb = new StringBuffer(); sb.append("Edmonton Frail Scale (Score Key):"); sb.append("\n"); sb.append("Robust: 0-4"); sb.append("\n"); sb.append("Apparently Vulnerable: 5-6"); sb.append("\n"); sb.append("Frail: 7-17"); sb.append("\n"); cell = new PdfPCell(new Phrase(sb.toString(), sFont)); cell.setBackgroundColor(BaseColor.LIGHT_GRAY); cell.setNoWrap(false); table.addCell(cell); cell = new PdfPCell(new Phrase("Nutritional Status", mFont)); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setMinimumHeight(35f); table.addCell(cell); sb = new StringBuffer(); sb.append("Screen II score : "); sb.append(report.getScores().getNutritionScreen()); sb.append("\n"); sb.append("\n"); sb.append("\n"); cell = new PdfPCell(new Phrase(sb.toString(), iSmallFont)); cell.setNoWrap(false); table.addCell(cell); sb = new StringBuffer(); sb.append("Screen II Nutrition Screening Tool:"); sb.append("\n"); sb.append("Max Score = 64"); sb.append("\n"); sb.append("High Risk < 50"); sb.append("\n"); cell = new PdfPCell(new Phrase(sb.toString(), sFont)); cell.setNoWrap(false); table.addCell(cell); cell = new PdfPCell(new Phrase("Social Support", mFont)); cell.setBackgroundColor(BaseColor.LIGHT_GRAY); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setMinimumHeight(55f); table.addCell(cell); sb = new StringBuffer(); sb.append("Satisfaction score = "); sb.append(report.getScores().getSocialSatisfication()); sb.append("\n"); sb.append("Network score = "); sb.append(report.getScores().getSocialNetwork()); sb.append("\n"); sb.append("\n"); cell = new PdfPCell(new Phrase(sb.toString(), iSmallFont)); cell.setBackgroundColor(BaseColor.LIGHT_GRAY); cell.setNoWrap(false); table.addCell(cell); sb = new StringBuffer(); sb.append("Satisfaction score range: 6-18"); sb.append("\n"); sb.append("Score < 10 risk cut off"); sb.append("\n"); sb.append("Perceived satisfaction with behavioural or"); sb.append("\n"); sb.append("emotional support obtained from this network"); sb.append("\n"); sb.append("Network score range : 4-12"); sb.append("\n"); sb.append("Size and structure of social network"); sb.append("\n"); cell = new PdfPCell(new Phrase(sb.toString(), sFont)); cell.setNoWrap(false); cell.setBackgroundColor(BaseColor.LIGHT_GRAY); table.addCell(cell); ////Mobility PdfPTable nest_table1 = new PdfPTable(1); cell = new PdfPCell(new Phrase("Mobility ", mFont)); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setBorderWidthLeft(0); cell.setBorderWidthBottom(1f); cell.setBorderWidthTop(0); cell.setBorderWidthRight(0); nest_table1.addCell(cell); cell = new PdfPCell(new Phrase("Walking 2.0 km ", sFont)); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setBorder(0); nest_table1.addCell(cell); cell = new PdfPCell(new Phrase("Walking 0.5 km ", sFont)); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setBorderWidthTop(1f); cell.setBorderWidthLeft(0); cell.setBorderWidthBottom(0); cell.setBorderWidthRight(0); nest_table1.addCell(cell); cell = new PdfPCell(new Phrase("Climbing Stairs ", sFont)); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setBorderWidthTop(1f); cell.setBorderWidthLeft(0); cell.setBorderWidthBottom(0); cell.setBorderWidthRight(0); nest_table1.addCell(cell); PdfPTable nest_table2 = new PdfPTable(1); cell = new PdfPCell(new Phrase(" ", mFont)); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setBorderWidthLeft(0); cell.setBorderWidthBottom(1f); cell.setBorderWidthTop(0); cell.setBorderWidthRight(0); nest_table2.addCell(cell); cell = new PdfPCell(new Phrase(report.getScores().getMobilityWalking2(), iSmallFont)); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setBorder(0); nest_table2.addCell(cell); cell = new PdfPCell(new Phrase(report.getScores().getMobilityWalkingHalf(), iSmallFont)); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setBorderWidthTop(1f); cell.setBorderWidthLeft(0); cell.setBorderWidthBottom(0); cell.setBorderWidthRight(0); nest_table2.addCell(cell); cell = new PdfPCell(new Phrase(report.getScores().getMobilityClimbing(), iSmallFont)); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setBorderWidthTop(1f); cell.setBorderWidthLeft(0); cell.setBorderWidthBottom(0); cell.setBorderWidthRight(0); nest_table2.addCell(cell); table.addCell(nest_table1); table.addCell(nest_table2); sb = new StringBuffer(); sb.append("MANTY:"); sb.append("\n"); sb.append("No Limitation"); sb.append("\n"); sb.append("Preclinical Limitation"); sb.append("\n"); sb.append("Minor Manifest Limitation"); sb.append("\n"); sb.append("Major Manifest Limitation"); sb.append("\n"); sb.append("\n"); cell = new PdfPCell(new Phrase(sb.toString(), mFont)); cell.setNoWrap(false); table.addCell(cell); ////RAPA cell = new PdfPCell(new Phrase("Physical Activity", mFont)); cell.setBackgroundColor(BaseColor.LIGHT_GRAY); cell.setVerticalAlignment(Element.ALIGN_TOP); cell.setMinimumHeight(45f); table.addCell(cell); sb = new StringBuffer(); sb.append("Score = "); sb.append(report.getScores().getPhysicalActivity()); sb.append("\n"); sb.append("\n"); sb.append("\n"); cell = new PdfPCell(new Phrase(sb.toString(), iSmallFont)); cell.setBackgroundColor(BaseColor.LIGHT_GRAY); cell.setNoWrap(false); table.addCell(cell); sb = new StringBuffer(); sb.append("Rapid Assessment of Physical Activity(RAPA)"); sb.append("\n"); sb.append("Score range : 1-7"); sb.append("\n"); sb.append("Score < 6 Suboptimal Activity(Aerobic)"); sb.append("\n"); sb.append("\n"); cell = new PdfPCell(new Phrase(sb.toString(), sFont)); cell.setNoWrap(false); cell.setBackgroundColor(BaseColor.LIGHT_GRAY); table.addCell(cell); document.add(table); document.add(new Phrase(" ")); //Tapestry Questions table = new PdfPTable(2); table.setWidthPercentage(100); cell = new PdfPCell(new Phrase("TAPESTRY QUESTIONS", bMediumFont)); cell.setBackgroundColor(BaseColor.LIGHT_GRAY); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setColspan(2); table.addCell(cell); for (Map.Entry<String, String> entry : report.getDailyActivities().entrySet()) { cell = new PdfPCell(new Phrase(entry.getKey(), sFont)); table.addCell(cell); cell = new PdfPCell(new Phrase(entry.getValue(), sFont)); table.addCell(cell); } table.setWidths(cWidths); document.add(table); //Volunteer Information table = new PdfPTable(2); table.setWidthPercentage(100); cell = new PdfPCell(new Phrase("VOLUNTEER INFORMATION & NOTES", gbMediumFont)); cell.setBackgroundColor(BaseColor.LIGHT_GRAY); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setColspan(2); table.addCell(cell); cell = new PdfPCell(new Phrase("1", bmFont)); table.addCell(cell); cell = new PdfPCell(new Phrase(report.getAppointment().getVolunteer(), ibMediumFont)); table.addCell(cell); cell = new PdfPCell(new Phrase("2", bmFont)); table.addCell(cell); cell = new PdfPCell(new Phrase(report.getAppointment().getPartner(), ibMediumFont)); table.addCell(cell); cell = new PdfPCell(new Phrase("V", gbMediumFont)); table.addCell(cell); cell = new PdfPCell(new Phrase(report.getAppointment().getComments(), gbMediumFont)); cell.setPaddingBottom(10); table.addCell(cell); table.setWidths(cWidths); document.add(table); document.close(); } catch (Exception e) { e.printStackTrace(); } } private Map<String, String> getSurveyContentMap(List<String> questionTextList, List<String> questionAnswerList){ Map<String, String> content; if (questionTextList != null && questionTextList.size() > 0) {//remove the first element which is description about whole survey questionTextList.remove(0); if (questionAnswerList != null && questionAnswerList.size() > 0) {//remove the first element which is empty or "-" if ("-".equals(questionAnswerList.get(0))) questionAnswerList.remove(0); content = new TreeMap<String, String>(); StringBuffer sb; for (int i = 0; i < questionAnswerList.size(); i++){ sb = new StringBuffer(); // sb.append(questionTextList.get(i)); sb.append(removeObserverNotes(questionTextList.get(i).toString())); // sb.append("<br/><br/>"); //html view sb.append("\n\n");// for PDF format sb.append(questionAnswerList.get(i)); content.put(String.valueOf(i + 1), sb.toString()); } return content; } else { System.out.println("All answers in Goal Setting survey are empty!"); return null; } } else { System.out.println("Bad thing happens, no question text found for this Goal Setting survey!"); return null; } } private String removeObserverNotes(String questionText) { //remove /observernotes/ from question text int index = questionText.indexOf("/observernote/"); if (index > 0) questionText = questionText.substring(0, index); return questionText; } private Map<String, String> getSurveyContentMapForMemorySurvey(List<String> questionTextList, List<String> questionAnswerList){ Map<String, String> displayContent = new TreeMap<String, String>(); int size = questionTextList.size(); Object answer; String questionText; if (questionAnswerList.size() == size) { for (int i = 0; i < size; i++) { questionText = questionTextList.get(i).toString(); //remove /observernotes/ from question text removeObserverNotes(questionText); answer = questionAnswerList.get(i); if ((answer != null) && (answer.toString().equals("1"))) displayContent.put(questionText, "YES"); else displayContent.put(questionText, "NO"); } return displayContent; } else System.out.println("Bad thing happens"); return null; } private List<String> removeRedundantFromQuestionText(List<String> list, String redundantStr){ String str; int index; for (int i = 0 ; i < list.size(); i ++) { str = list.get(i).toString(); index = str.indexOf(redundantStr); if (index > 0) { str = str.substring(index + 4); list.set(i, str); } } return list; } //remove observer notes from answer private List<String> getQuestionList(LinkedHashMap<String, String> questionMap) { List<String> qList = new ArrayList<String>(); String question; for (Map.Entry<String, String> entry : questionMap.entrySet()) { String key = entry.getKey(); if (!key.equalsIgnoreCase("title") && !key.equalsIgnoreCase("date") && !key.equalsIgnoreCase("surveyId")) { Object value = entry.getValue(); question = value.toString(); question = removeObserverNotes(question); if (!question.equals("-")) qList.add(question); } } return qList; } private List<String> getQuestionListForMemorySurvey(LinkedHashMap<String, String> questionMap){ List<String> qList = new ArrayList<String>(); String question; for (Map.Entry<String, String> entry : questionMap.entrySet()) { String key = entry.getKey(); if ((key.equalsIgnoreCase("YM1"))||(key.equalsIgnoreCase("YM2"))) { Object value = entry.getValue(); question = value.toString(); //remove observer notes question = removeObserverNotes(question); qList.add(question); } } return qList; } //remove observer notes and other not related to question/answer private Map<String, String> getQuestionMap(LinkedHashMap<String, String> questions){ Map<String, String> qMap = new LinkedHashMap<String, String>(); String question; for (Map.Entry<String, String> entry : questions.entrySet()) { String key = entry.getKey(); if (!key.equalsIgnoreCase("title") && !key.equalsIgnoreCase("date") && !key.equalsIgnoreCase("surveyId")) { Object value = entry.getValue(); question = value.toString(); question = removeObserverNotes(question); if (!question.equals("-")) qMap.put(key, question); } } return qMap; } }
package org.jetel.component; import java.io.File; import java.io.IOException; import org.jetel.data.DataRecord; import org.jetel.data.formatter.XLSDataFormatter; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.XMLConfigurationException; import org.jetel.graph.InputPort; import org.jetel.graph.Node; import org.jetel.graph.TransformationGraph; import org.jetel.util.ComponentXMLAttributes; import org.jetel.util.SynchronizeUtils; import org.w3c.dom.Element; public class XLSWriter extends Node { private static final String XML_FILEURL_ATTRIBUTE = "fileURL"; private static final String XML_SAVENAMES_ATTRIBUTE = "saveNames"; private static final String XML_SHEETNAME_ATTRIBUTE = "sheetName"; private static final String XML_SHEETNUMBER_ATTRIBUTE = "sheetNumber"; private static final String XML_APPEND_ATTRIBUTE = "append"; private static final String XML_FIRSTDATAROW_ATTRIBUTE = "firstDataRow"; private static final String XML_FIRSTCOLUMN_ATTRIBUTE = "firstColumn"; private static final String XML_NAMESROW_ATTRIBUTE = "namesRow"; public final static String COMPONENT_TYPE = "XLS_WRITER"; private final static int READ_FROM_PORT = 0; private String fileURL; private XLSDataFormatter formatter; /** * Constructor * * @param id * @param fileURL output file * @param saveNames indicates if save metadata names * @param append indicates if new data are appended or rewrite old data */ public XLSWriter(String id,String fileURL, boolean saveNames, boolean append){ super(id); this.fileURL = fileURL; formatter = new XLSDataFormatter(saveNames,append); } /* (non-Javadoc) * @see org.jetel.graph.Node#getType() */ @Override public String getType() { return COMPONENT_TYPE; } /* (non-Javadoc) * @see org.jetel.graph.Node#run() */ @Override public void run() { InputPort inPort = getInputPort(READ_FROM_PORT); DataRecord record = new DataRecord(inPort.getMetadata()); record.init(); while (record != null && runIt) { try { record = inPort.readRecord(record); if (record != null) { formatter.write(record); } } catch (IOException ex) { resultMsg=ex.getMessage(); resultCode=Node.RESULT_ERROR; closeAllOutputPorts(); return; } catch (Exception ex) { resultMsg=ex.getClass().getName()+" : "+ ex.getMessage(); resultCode=Node.RESULT_FATAL_ERROR; return; } SynchronizeUtils.cloverYield(); } formatter.close(); if (runIt) resultMsg="OK"; else resultMsg="STOPPED"; resultCode=Node.RESULT_OK; } /* (non-Javadoc) * @see org.jetel.graph.GraphElement#checkConfig() */ @Override public boolean checkConfig() { return true; } /* (non-Javadoc) * @see org.jetel.graph.GraphElement#init() */ @Override public void init() throws ComponentNotReadyException { File out = new File(fileURL); try { if (!out.exists()){ out.createNewFile(); } formatter.open(out,getInputPort(READ_FROM_PORT).getMetadata()); }catch(IOException ex){ throw new ComponentNotReadyException(ex); } } public static Node fromXML(TransformationGraph graph, Element nodeXML) throws XMLConfigurationException { ComponentXMLAttributes xattribs = new ComponentXMLAttributes(nodeXML, graph); XLSWriter xlsWriter; try{ xlsWriter = new XLSWriter(xattribs.getString(XML_ID_ATTRIBUTE), xattribs.getString(XML_FILEURL_ATTRIBUTE), xattribs.getBoolean(XML_SAVENAMES_ATTRIBUTE,false), xattribs.getBoolean(XML_APPEND_ATTRIBUTE,false)); if (xattribs.exists(XML_SHEETNAME_ATTRIBUTE)){ xlsWriter.setSheetName(xattribs.getString(XML_SHEETNAME_ATTRIBUTE)); } else if (xattribs.exists(XML_SHEETNUMBER_ATTRIBUTE)){ xlsWriter.setSheetNumber(xattribs.getInteger(XML_SHEETNUMBER_ATTRIBUTE)); } xlsWriter.setFirstColumn(xattribs.getString(XML_FIRSTCOLUMN_ATTRIBUTE,"A")); xlsWriter.setFirstRow(xattribs.getInteger(XML_FIRSTDATAROW_ATTRIBUTE,1)); xlsWriter.setNamesRow(xattribs.getInteger(XML_NAMESROW_ATTRIBUTE,0)); return xlsWriter; } catch (Exception ex) { throw new XMLConfigurationException(COMPONENT_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE," unknown ID ") + ":" + ex.getMessage(),ex); } } /** * Description of the Method * * @return Description of the Returned Value * @since May 21, 2002 */ public void toXML(org.w3c.dom.Element xmlElement) { super.toXML(xmlElement); xmlElement.setAttribute(XML_FILEURL_ATTRIBUTE,this.fileURL); xmlElement.setAttribute(XML_APPEND_ATTRIBUTE, String.valueOf(formatter.isAppend())); xmlElement.setAttribute(XML_FIRSTCOLUMN_ATTRIBUTE,String.valueOf(formatter.getFirstColumn())); xmlElement.setAttribute(XML_FIRSTDATAROW_ATTRIBUTE, String.valueOf(formatter.getFirstRow()+1)); xmlElement.setAttribute(XML_NAMESROW_ATTRIBUTE, String.valueOf(formatter.getNamesRow()+1)); if (formatter.getSheetName() != null) {//TODO can't we obtain it from parser? xmlElement.setAttribute(XML_SHEETNAME_ATTRIBUTE,formatter.getSheetName()); } xmlElement.setAttribute(XML_SAVENAMES_ATTRIBUTE,String.valueOf(formatter.isSaveNames())); } private void setSheetName(String sheetName) { formatter.setSheetName(sheetName); } private void setSheetNumber(int sheetNumber) { formatter.setSheetNumber(sheetNumber); } private void setFirstColumn(String firstColumn){ formatter.setFirstColumn(firstColumn); } private void setFirstRow(int firstRow){ formatter.setFirstRow(firstRow-1); } private void setNamesRow(int namesRow){ formatter.setNamesRow(namesRow-1); } }
package org.zalando.nakadi.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class NakadiSettings { private final int maxTopicPartitionCount; private final int defaultTopicPartitionCount; private final int defaultTopicReplicaFactor; private final long defaultTopicRetentionMs; private final long defaultTopicRotationMs; private final long defaultCommitTimeoutSeconds; private final long kafkaPollTimeoutMs; private final long kafkaSendTimeoutMs; @Autowired public NakadiSettings(@Value("${nakadi.topic.max.partitionNum}") final int maxTopicPartitionCount, @Value("${nakadi.topic.default.partitionNum}") final int defaultTopicPartitionCount, @Value("${nakadi.topic.default.replicaFactor}") final int defaultTopicReplicaFactor, @Value("${nakadi.topic.default.retentionMs}") final long defaultTopicRetentionMs, @Value("${nakadi.topic.default.rotationMs}") final long defaultTopicRotationMs, @Value("${nakadi.stream.default.commitTimeout}") final long defaultCommitTimeoutSeconds, @Value("${nakadi.kafka.poll.timeoutMs}") final long kafkaPollTimeoutMs, @Value("${nakadi.kafka.send.timeoutMs}") final long kafkaSendTimeoutMs) { this.maxTopicPartitionCount = maxTopicPartitionCount; this.defaultTopicPartitionCount = defaultTopicPartitionCount; this.defaultTopicReplicaFactor = defaultTopicReplicaFactor; this.defaultTopicRetentionMs = defaultTopicRetentionMs; this.defaultTopicRotationMs = defaultTopicRotationMs; this.defaultCommitTimeoutSeconds = defaultCommitTimeoutSeconds; this.kafkaPollTimeoutMs = kafkaPollTimeoutMs; this.kafkaSendTimeoutMs = kafkaSendTimeoutMs; } public int getDefaultTopicPartitionCount() { return defaultTopicPartitionCount; } public int getMaxTopicPartitionCount() { return maxTopicPartitionCount; } public int getDefaultTopicReplicaFactor() { return defaultTopicReplicaFactor; } public long getDefaultTopicRetentionMs() { return defaultTopicRetentionMs; } public long getDefaultTopicRotationMs() { return defaultTopicRotationMs; } public long getDefaultCommitTimeoutSeconds() { return defaultCommitTimeoutSeconds; } public long getKafkaPollTimeoutMs() { return kafkaPollTimeoutMs; } public long getKafkaSendTimeoutMs() { return kafkaSendTimeoutMs; } }
package org.jbehave.core.embedder; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.jbehave.core.model.Meta; import org.jbehave.core.model.Meta.Property; import java.util.HashSet; import java.util.Properties; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * <p> * Allows filtering on meta info. * </p> * * <p> * Filters are represented as a sequence of any name-value properties (separated * by a space), prefixed by "+" for inclusion and "-" for exclusion. E.g.: * * <pre> * new Filter(&quot;+author Mauro -theme smoke testing +map *API -skip&quot;) * </pre> * * </p> */ public class MetaFilter { public static final MetaFilter EMPTY = new MetaFilter(); private final Properties include = new Properties(); private final Properties exclude = new Properties(); private final String filterAsString; private final EmbedderMonitor monitor; public MetaFilter() { this(""); } public MetaFilter(String filterAsString) { this(filterAsString, new PrintStreamEmbedderMonitor()); } public MetaFilter(String filterAsString, EmbedderMonitor monitor) { this.filterAsString = filterAsString.replace('_', ' '); this.monitor = monitor; parse(include, "+"); parse(exclude, "-"); } private void parse(Properties properties, String prefix) { properties.clear(); for (String found : found(prefix)) { Property property = new Property(StringUtils.removeStartIgnoreCase(found, prefix)); properties.setProperty(property.getName(), property.getValue()); } } private Set<String> found(String prefix) { Matcher matcher = findAllPrefixed(prefix).matcher(filterAsString); Set<String> found = new HashSet<String>(); while (matcher.find()) { found.add(matcher.group().trim()); } return found; } private Pattern findAllPrefixed(String prefix) { return Pattern.compile("(\\" + prefix + "(\\w|\\s|\\*)*)", Pattern.DOTALL); } public boolean allow(Meta meta) { boolean allowed; if (!include.isEmpty() && exclude.isEmpty()) { allowed = match(include, meta); } else if (include.isEmpty() && !exclude.isEmpty()) { allowed = !match(exclude, meta); } else if (!include.isEmpty() && !exclude.isEmpty()) { allowed = match(merge(include, exclude), meta) && !match(exclude, meta); } else { allowed = true; } if (!allowed) { monitor.metaNotAllowed(meta, this); } return allowed; } private Properties merge(Properties include, Properties exclude) { Set<Object> in = new HashSet<Object>(include.keySet()); in.addAll(exclude.keySet()); Properties merged = new Properties(); for (Object key : in) { if (include.containsKey(key)) { merged.put(key, include.get(key)); } else if (exclude.containsKey(key)) { merged.put(key, exclude.get(key)); } } return merged; } private boolean match(Properties properties, Meta meta) { for (Object key : properties.keySet()) { String property = (String) properties.get(key); for (String metaName : meta.getPropertyNames()) { if (key.equals(metaName)) { String value = meta.getProperty(metaName); if (StringUtils.isBlank(value)) { return true; } else if (property.contains("*")) { return value.matches(property.replace("*", ".*")); } return properties.get(key).equals(value); } } } return false; } public Properties include() { return include; } public Properties exclude() { return exclude; } public String asString() { return filterAsString; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } }
package org.bdgp.MMSlide.Modules; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.swing.JPanel; import org.bdgp.MMSlide.Logger; import org.bdgp.MMSlide.WorkflowRunner; import org.bdgp.MMSlide.DB.Config; import org.bdgp.MMSlide.DB.Task; import org.bdgp.MMSlide.DB.Task.Status; import org.bdgp.MMSlide.Modules.Interfaces.Configuration; import org.bdgp.MMSlide.Modules.Interfaces.Module; import static org.bdgp.MMSlide.Util.map; public class Start implements Module { @Override public Status run(WorkflowRunner workflow, Task task, Map<String,Config> config, Logger logger) { return Status.SUCCESS; } @Override public String getTitle() { return this.getClass().getName(); } @Override public String getDescription() { return this.getClass().getName(); } @Override public Configuration configure() { return new Configuration() { @Override public List<Config> retrieve() { return new ArrayList<Config>(); } @Override public JPanel display() { return new JPanel(); }}; } @Override public void createTaskRecords(WorkflowRunner workflow, String moduleId) { Task task = new Task(moduleId, workflow.getInstance().getStorageLocation(), Status.NEW); workflow.getTaskStatus().insert(task); task.update(workflow.getTaskStatus()); } @Override public Map<String, Integer> getResources() { return map("cpu",1); } }
package com.google.devtools.moe.client; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.io.Files; import com.google.common.io.Resources; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * A {@link FileSystem} using the real local filesystem via operations in {@link File}. * * @author dbentley@google.com (Daniel Bentley) */ public class SystemFileSystem implements FileSystem { private final Map<File, Lifetime> tempDirLifetimes = Maps.newHashMap(); @Override public File getTemporaryDirectory(String prefix) { return getTemporaryDirectory(prefix, Lifetimes.currentTask()); } @Override public File getTemporaryDirectory(String prefix, Lifetime lifetime) { File tempDir; try { tempDir = File.createTempFile("moe_" + prefix, ""); tempDir.delete(); } catch (IOException e) { throw new MoeProblem("could not create temp file: " + e.getMessage()); } tempDirLifetimes.put(tempDir, lifetime); return tempDir; } @Override public void cleanUpTempDirs() throws IOException { Iterator<Entry<File, Lifetime>> tempDirIterator = tempDirLifetimes.entrySet().iterator(); while (tempDirIterator.hasNext()) { Entry<File, Lifetime> entry = tempDirIterator.next(); if (entry.getValue().shouldCleanUp()) { deleteRecursively(entry.getKey()); tempDirIterator.remove(); AppContext.RUN.ui.debug("Deleted temp dir: " + entry.getKey()); } } } @Override public void setLifetime(File path, Lifetime lifetime) { Preconditions.checkState( tempDirLifetimes.containsKey(path), "Trying to set the Lifetime for an unknown path: %s", path); tempDirLifetimes.put(path, lifetime); } /** * Find files under a path. */ @Override public Set<File> findFiles(File path) { Set<File> result = Sets.newHashSet(); findFilesRecursiveHelper(path, result); return result; } void findFilesRecursiveHelper(File f, Set<File> result) { if (f.exists() && f.isFile()) { result.add(f); return; } for (File subFile : f.listFiles()) { findFilesRecursiveHelper(subFile, result); } } @Override public File[] listFiles(File path) { return path.listFiles(); } @Override public boolean exists(File f) { return f.exists(); } @Override public String getName(File f) { return f.getName(); } @Override public boolean isFile(File f) { return f.isFile(); } @Override public boolean isDirectory(File f) { return f.isDirectory(); } @Override public boolean isExecutable(File f) { return exists(f) && f.canExecute(); } @Override public boolean isReadable(File f) { return exists(f) && f.canRead(); } @Override public void setExecutable(File f) { f.setExecutable(true, false); } @Override public void setNonExecutable(File f) { f.setExecutable(false, false); } @Override public void makeDirsForFile(File f) throws IOException { Files.createParentDirs(f); } @Override public void makeDirs(File f) throws IOException { Files.createParentDirs(new File(f, "foo")); } @Override public void copyFile(File src, File dest) throws IOException { Files.copy(src, dest); dest.setExecutable(src.canExecute(), false); } @Override public void write(String contents, File f) throws IOException { Files.write(contents, f, Charsets.UTF_8); } @Override public void deleteRecursively(File file) throws IOException { Files.deleteRecursively(file); } @Override public File getResourceAsFile(String resource) throws IOException { String name = (new File(resource)).getName(); if (name.isEmpty()) { throw new IOException("Invalid resource name: " + resource); } File extractedFile = new File( getTemporaryDirectory("resource_extraction_", Lifetimes.moeExecution()), name); makeDirsForFile(extractedFile); OutputStream os = Files.asByteSink(extractedFile).openStream(); Resources.copy( SystemFileSystem.class.getResource(resource), os); os.close(); return extractedFile; } @Override public String fileToString(File f) throws IOException { return Files.toString(f, Charsets.UTF_8); } }
package ru.r2cloud.jradio.blocks; import ru.r2cloud.jradio.crc.Crc16Ccitt; public class HdlcTransmitter { private static final int CRC16_LEN_BYTES = 2; private static final int BITS_IN_BYTE = 8; private static final int BIT_STUFFING_PESSIMISTIC_EXCESS_MULTIPLIER = 2; private static final int FRAMING_BITS_LEN = 8; private final int prepend; private final int append; private byte[] bitsToSend; private int bitsToSendLength; private int successiveOnes; public HdlcTransmitter() { this(0, 0); } public HdlcTransmitter(int prepend, int append) { this.prepend = prepend; this.append = append; } public byte[] encode(byte[] messageToSend) { bitsToSendLength = 0; int crc16 = Crc16Ccitt.calculateReverse(messageToSend); int requiredBitsToSendLength = prepend * BITS_IN_BYTE + append * BITS_IN_BYTE + (messageToSend.length + CRC16_LEN_BYTES) * BITS_IN_BYTE * BIT_STUFFING_PESSIMISTIC_EXCESS_MULTIPLIER + 2 * FRAMING_BITS_LEN; // init new buffer only if previous was smaller if (bitsToSend == null || requiredBitsToSendLength > bitsToSend.length) { bitsToSend = new byte[requiredBitsToSendLength]; } for (int i = 0; i < prepend; i++) { appendNonStuffed(0x7E); } appendNonStuffed(0x7E); for (int i = 0; i < messageToSend.length; i++) { appendStuffed(messageToSend[i] & 0xFF); } appendStuffed(crc16 & 0xFF); appendStuffed((crc16 >> 8) & 0xFF); appendNonStuffed(0x7E); for (int i = 0; i < append; i++) { appendNonStuffed(0x7E); } byte[] result = new byte[bitsToSendLength]; System.arraycopy(bitsToSend, 0, result, 0, result.length); return result; } private void appendStuffed(int curByte) { for (int i = 0; i < BITS_IN_BYTE; i++) { byte curBit = (byte) ((curByte >> i) & 0x1); if (curBit == 1) { successiveOnes++; } else { successiveOnes = 0; } bitsToSend[bitsToSendLength] = curBit; bitsToSendLength++; if (successiveOnes == 5) { bitsToSend[bitsToSendLength] = 0; bitsToSendLength++; successiveOnes = 0; } } } private void appendNonStuffed(int curByte) { for (int i = 0; i < BITS_IN_BYTE; i++) { bitsToSend[bitsToSendLength] = (byte) ((curByte >> i) & 0x1); bitsToSendLength++; } } }
package org.jlib.container; import java.util.Collection; import org.jlib.core.traverser.RemoveTraverser; /** * <p> * Container that supports addition and removal of Items. * </p> * <p> * Note: In jlib, {@code null} is not a value. Hence, {@link Container * Containers} may <em>not</em> contain null items * </p> * * @param <Item> * type of items held in the {@link Container} * * @author Igor Akkerman */ public interface RemoveContainer<Item> extends Container<Item> { public void remove(final Item item) throws IllegalArgumentException; /** * Removes all Items of this {@link RemoveContainer}. */ public void removeAll(); /** * Removes all Items contained by the specified {@link Container} from this * {@link RemoveContainer}. * * @param items * {@link Container} containing the Items to remove */ public void removeAll(final Container<? extends Item> items); /** * Removes all Items contained by the specified {@link Collection} from this * {@link RemoveContainer}. * * @param items * {@link Collection} containing the Items to remove */ public void removeAll(final Collection<? extends Item> items); /** * Removes all Items provided by the specified {@link Iterable} from this * {@link AddContainer}. * * @param items * {@link Iterable} providing the Items to remove */ public void removeAll(final Iterable<? extends Item> items); /** * Removes all specified Items from this {@link RemoveContainer}. * * @param items * vararg list of Items to remove */ public void removeAll(@SuppressWarnings({ "unchecked", /* "varargs" */}) final Item... items); /** * Removes all Items from this {@link RemoveContainer} <i>except</i> the * Items contained by the specified {@link Container}. * * @param items * {@link Container} containing the Items to retain */ public void retainAll(final Container<? extends Item> items); /** * Removes all Items from this {@link RemoveContainer} <i>except</i> the * Items contained by the specified {@link Collection}. * * @param items * {@link Collection} containing the Items to retain */ public void retainAll(final Collection<? extends Item> items); /** * Removes all Items from this {@link RemoveContainer} <i>except</i> the * specified Items. * * @param items * vararg list of Items to retain */ public void retainAll(@SuppressWarnings({ "unchecked", /* "varargs" */}) final Item... items); /** * Creates a new {@link RemoveTraverser} over this {@link RemoveContainer}. * * @return newly created {@link RemoveTraverser} */ @Override public RemoveTraverser<Item> createTraverser(); }
package org.lichess.compression.game; import java.util.ArrayList; import org.lichess.compression.BitReader; import org.lichess.compression.BitWriter; import org.lichess.compression.VarIntEncoder; public class Encoder { static byte[] encode(String pgnMoves[]) { BitWriter writer = new BitWriter(); Board board = new Board(); ArrayList<Move> legals = new ArrayList<Move>(255); VarIntEncoder.writeUnsigned(pgnMoves.length, writer); for (String pgnMove: pgnMoves) { board.legalMoves(legals); legals.sort(new MoveComparator()); for (int code = 0; code < legals.size(); code++) { Move legal = legals.get(code); // TODO: Optimize SAN parsing if (san(legal, legals).equals(pgnMove.replace("+", "").replace(" Huffman.write(code, writer); board.play(legal); } } } return writer.toArray(); } public static ArrayList<String> decode(byte input[]) { BitReader reader = new BitReader(input); int length = VarIntEncoder.readUnsigned(reader); ArrayList<String> output = new ArrayList<String>(length); Board board = new Board(); ArrayList<Move> legals = new ArrayList<Move>(255); for (int i = 0; i < length + 1; i++) { board.legalMoves(legals); if (i > 0) { if (board.isCheck()) output.set(i - 1, legals.get(i - 1) + (legals.isEmpty() ? " } if (i < length) { legals.sort(new MoveComparator()); Move move = legals.get(Huffman.read(reader)); output.add(san(move, legals)); board.play(move); } } return output; } private static String san(Move move, ArrayList<Move> legals) { StringBuilder builder; switch (move.type) { case Move.NORMAL: builder = new StringBuilder(6); builder.append(move.role.symbol); if (move.role != Role.PAWN) { boolean file = false, rank = false; long others = 0; for (Move other: legals) { if (other.role == move.role && other.to == move.to && other.from != move.from) { others |= 1L << other.from; } } if (others != 0) { if ((others & Bitboard.RANKS[Square.rank(move.from)]) != 0) file = true; if ((others & Bitboard.FILES[Square.file(move.from)]) != 0) rank = true; else file = true; } if (file) builder.append((char) (Square.file(move.from) + 'a')); if (rank) builder.append((char) (Square.rank(move.from) + '1')); } else if (move.capture) { builder.append((char) (Square.file(move.from) + 'a')); } if (move.capture) builder.append('x'); builder.append((char) (Square.file(move.to) + 'a')); builder.append((char) (Square.rank(move.to) + '1')); if (move.promotion != null) { builder.append('='); builder.append(move.promotion.symbol); } return builder.toString(); case Move.EN_PASSANT: builder = new StringBuilder(4); builder.append((char) (Square.file(move.from) + 'a')); builder.append('x'); builder.append((char) (Square.file(move.to) + 'a')); builder.append((char) (Square.rank(move.to) + '1')); return builder.toString(); case Move.CASTLING: return move.from < move.to ? "O-O" : "O-O-O"; } return " } }
package priceHistory; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import database.ConnectionPool; import database.PoolableConnection; import database.sqlite.Procs; import javafx.collections.ObservableList; import priceHistory.dataFeed.DataFeedTO; import priceHistory.dataFeed.yahooFinance.YahooDataRequest; import utility.DateUtility; public enum PriceHistoryService { INSTANCE; private ConcurrentHashMap<String, Boolean> priceHistoryDataRequestCache = new ConcurrentHashMap<String, Boolean>(20,0.75f,2); /** * used to return 2 objects from searchPriceHistory(). Find a nicer way of doing it. */ private class Pair{ public List<DataFeedTO> priceHistory; public Date mostRecentDate; Pair( List<DataFeedTO> p_priceHistory, Date p_mostRecentDate ) { priceHistory = p_priceHistory; mostRecentDate = p_mostRecentDate; } } public List<DataFeedTO> getPriceChartData( String p_ticker, Date p_beginDate, Date p_endDate ) { List<DataFeedTO> l_priceHistory = new ArrayList<DataFeedTO>(); Date l_mostRecentDate; Date l_todayDate = DateUtility.getTodayDate(); Pair hack = searchPriceHistoryHack( p_ticker, p_beginDate, p_endDate ); l_priceHistory = hack.priceHistory; l_mostRecentDate = hack.mostRecentDate; if ( l_mostRecentDate.before(l_todayDate) && !(priceHistoryDataRequestCache.containsKey("insertPrice"+p_ticker+DateUtility.parseDateToString(p_endDate))) ) { YahooDataRequest l_rr = new YahooDataRequest( p_ticker, l_mostRecentDate ); List<DataFeedTO> l_missingHistory = l_rr.getPriceHistory(); insertPriceHistory( p_ticker, l_missingHistory ); l_priceHistory.addAll( l_missingHistory ); priceHistoryDataRequestCache.putIfAbsent( "insertPrice"+p_ticker+DateUtility.parseDateToString(p_endDate), true ); } return l_priceHistory; } /** * Currently using a Pair to return the priceHistory plus mostRecentDate. The date is used to determine whether * a dataRequest should be sent to retrieve up to date price information. * <p> Don't want to iterate over the priceHistory twice just to get the date. */ private Pair searchPriceHistoryHack( String p_ticker, Date p_beginDate, Date p_endDate ) { List<DataFeedTO> l_priceHistory = new ArrayList<DataFeedTO>(400); Date l_mostRecentDate = new Date(0); ConnectionPool pool = new ConnectionPool(1,1); PoolableConnection poolableConnection = null; try { poolableConnection = pool.requestConnection(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if ( poolableConnection != null ) { try { PreparedStatement preparedStatement = poolableConnection.prepareStatement(Procs.S_PRICEHISTORY); preparedStatement.setString( 1, p_ticker ); preparedStatement.setString( 2, DateUtility.parseDateToString(p_beginDate) ); preparedStatement.setString( 3, DateUtility.parseDateToString(p_endDate) ); ResultSet results = preparedStatement.executeQuery(); while ( results.next() ) { DataFeedTO dataTO = new DataFeedTO(); dataTO.setTicker( results.getString("TICKER") ); dataTO.setDate( results.getString("DATE") ); dataTO.setOpenPrice( results.getBigDecimal("OPENPRICE") ); dataTO.setHighPrice( results.getBigDecimal("HIGHPRICE") ); dataTO.setLowPrice( results.getBigDecimal("LOWPRICE") ); dataTO.setClosePrice( results.getBigDecimal("CLOSEPRICE") ); dataTO.setVolume( results.getInt("VOLUME") ); l_priceHistory.add( dataTO ); Date l_thisDate = DateUtility.parseStringToDate( results.getString("DATE") ); if ( l_thisDate.after(l_mostRecentDate) ) { l_mostRecentDate = l_thisDate; } } } catch ( SQLException e ) { throw new RuntimeException(); } } return new Pair( l_priceHistory, l_mostRecentDate ); } private void insertPriceHistory( String p_ticker, List<DataFeedTO> p_priceHistory ) { if ( p_priceHistory.isEmpty() ) { return; } ConnectionPool pool = new ConnectionPool(1,1); PoolableConnection poolableConnection = null; try { poolableConnection = pool.requestConnection(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if ( poolableConnection != null ) { try { poolableConnection.setAutoCommit(false); PreparedStatement preparedStatement = poolableConnection.prepareStatement( Procs.I_PRICEHISTORY ); for ( DataFeedTO dataTO : p_priceHistory ) { preparedStatement.setString(1, p_ticker ); preparedStatement.setString(2, dataTO.getDate() ); preparedStatement.setBigDecimal(3, dataTO.getOpenPrice()); preparedStatement.setBigDecimal(4, dataTO.getHighPrice()); preparedStatement.setBigDecimal(5, dataTO.getLowPrice()); preparedStatement.setBigDecimal(6, dataTO.getClosePrice()); preparedStatement.setInt(7, dataTO.getVolume()); preparedStatement.addBatch(); } int[] results = preparedStatement.executeBatch(); poolableConnection.commit(); } catch (SQLException e) { poolableConnection.silentRollback(); } } } }
package seedu.oneline.logic.commands; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; import seedu.oneline.commons.core.EventsCenter; import seedu.oneline.commons.events.storage.StorageLocationChangedEvent; public class SaveCommand extends Command { public static final String COMMAND_WORD = "save"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Sets the folder to be used for storage\n" + "Parameters: FOLDERPATH\n" + "Example: " + COMMAND_WORD + " C:/Users/Bob/Desktop/"; public static final String MESSAGE_SET_STORAGE_SUCCESS = "Storage location succesfully set to %1$s."; public static final String MESSAGE_SET_STORAGE_FAILURE_PATH_INVALID = "Cannot set storage location to \"%1$s\", path is invalid!"; public static final String MESSAGE_SET_STORAGE_FAILURE_NOT_DIRECTORY = "Cannot set storage location to \"%1$s\", this is not a directory!"; public static final String MESSAGE_SET_STORAGE_FAILURE_CANNOT_READ = "Cannot set storage location to \"%1$s\", cannot read from here!"; public static final String MESSAGE_SET_STORAGE_FAILURE_CANNOT_WRITE = "Cannot set storage location to \"%1$s\", cannot write to here!"; String storageLocation; public SaveCommand(String storageLocation) { this.storageLocation = storageLocation.trim(); } @Override public CommandResult execute() { Optional<Path> path = getValidPath(storageLocation); if (!path.isPresent()) { indicateAttemptToExecuteIncorrectCommand(); return new CommandResult(String.format(MESSAGE_SET_STORAGE_FAILURE_PATH_INVALID, storageLocation)); } else { Path actualPath = path.get(); if (!isDirectory(actualPath)) { return new CommandResult(String.format(MESSAGE_SET_STORAGE_FAILURE_NOT_DIRECTORY, actualPath.toAbsolutePath())); } else if (!isReadable(actualPath)) { return new CommandResult(String.format(MESSAGE_SET_STORAGE_FAILURE_CANNOT_READ, actualPath.toAbsolutePath())); } else if (!isWritable(actualPath)) { return new CommandResult(String.format(MESSAGE_SET_STORAGE_FAILURE_CANNOT_WRITE, actualPath.toAbsolutePath())); } } Path actualPath = path.get(); EventsCenter.getInstance().post(new StorageLocationChangedEvent(storageLocation)); return new CommandResult(String.format(MESSAGE_SET_STORAGE_SUCCESS, actualPath.toAbsolutePath())); } private Optional<Path> getValidPath(String folderpath) { if (folderpath == null || folderpath.isEmpty()) { return Optional.empty(); } try { Path path = Paths.get(folderpath); return Optional.of(path); } catch (InvalidPathException ipe) { return Optional.empty(); } catch (SecurityException sece) { return Optional.empty(); } } private boolean isDirectory(Path path) { return Files.isDirectory(path); } private boolean isWritable(Path path) { return Files.isWritable(path); } private boolean isReadable(Path path) { return Files.isReadable(path); } }
package org.infradead.libopenconnect; import java.util.ArrayList; import java.util.HashMap; public abstract class LibOpenConnect { /* constants */ public static final int OC_FORM_OPT_TEXT = 1; public static final int OC_FORM_OPT_PASSWORD = 2; public static final int OC_FORM_OPT_SELECT = 3; public static final int OC_FORM_OPT_HIDDEN = 4; public static final int OC_FORM_OPT_TOKEN = 5; public static final int OC_FORM_OPT_IGNORE = 0x0001; public static final int OC_FORM_OPT_NUMERIC = 0x0002; public static final int OC_TOKEN_MODE_NONE = 0; public static final int OC_TOKEN_MODE_STOKEN = 1; public static final int OC_TOKEN_MODE_TOTP = 2; public static final int OC_TOKEN_MODE_HOTP = 3; public static final int OC_FORM_RESULT_ERR = -1; public static final int OC_FORM_RESULT_OK = 0; public static final int OC_FORM_RESULT_CANCELLED = 1; public static final int OC_FORM_RESULT_NEWGROUP = 2; public static final int PRG_ERR = 0; public static final int PRG_INFO = 1; public static final int PRG_DEBUG = 2; public static final int PRG_TRACE = 3; public static final int RECONNECT_INTERVAL_MIN = 10; public static final int RECONNECT_INTERVAL_MAX = 100; /* required callbacks */ public abstract int onProcessAuthForm(AuthForm authForm); public abstract void onProgress(int level, String msg); /* optional callbacks */ public int onValidatePeerCert(String msg) { return 0; } public int onWriteNewConfig(byte[] buf) { return 0; } public void onProtectSocket(int fd) { } public void onStatsUpdate(VPNStats stats) { } public int onTokenLock() { return 0; } public int onTokenUnlock(String newToken) { return 0; } /* create/destroy library instances */ public LibOpenConnect() { libctx = init("OpenConnect VPN Agent (Java)"); } public synchronized void destroy() { if (libctx != 0) { free(); libctx = 0; } } /* async requests (safe to call from any thread) */ public void cancel() { synchronized (asyncLock) { if (!canceled) { doCancel(); canceled = true; } } } public boolean isCanceled() { synchronized (asyncLock) { return canceled; } } public native void pause(); public native void requestStats(); public native void setLogLevel(int level); /* control operations */ public synchronized native int parseURL(String url); public synchronized native int obtainCookie(); public synchronized native void clearCookie(); public synchronized native void resetSSL(); public synchronized native int makeCSTPConnection(); public synchronized native int setupTunDevice(String vpncScript, String IFName); public synchronized native int setupTunScript(String tunScript); public synchronized native int setupTunFD(int tunFD); public synchronized native int setupDTLS(int attemptPeriod); public synchronized native int mainloop(int reconnectTimeout, int reconnectInterval); /* connection settings */ public synchronized native int passphraseFromFSID(); public synchronized native void setCertExpiryWarning(int seconds); public synchronized native void setDPD(int minSeconds); public synchronized native int setProxyAuth(String methods); public synchronized native int setHTTPProxy(String proxy); public synchronized native void setXMLSHA1(String hash); public synchronized native void setHostname(String hostname); public synchronized native void setUrlpath(String urlpath); public synchronized native void setCAFile(String caFile); public synchronized native void setReportedOS(String os); public synchronized native void setMobileInfo(String mobilePlatformVersion, String mobileDeviceType, String mobileDeviceUniqueID); public synchronized native int setTokenMode(int tokenMode, String tokenString); public synchronized native void setCSDWrapper(String wrapper, String TMPDIR, String PATH); public synchronized native void setXMLPost(boolean isEnabled); public synchronized native void setClientCert(String cert, String sslKey); public synchronized native void setServerCertSHA1(String hash); public synchronized native void setReqMTU(int mtu); public synchronized native void setPFS(boolean isEnabled); /* connection info */ public synchronized native String getHostname(); public synchronized native String getUrlpath(); public synchronized native int getPort(); public synchronized native String getCookie(); public synchronized native String getIFName(); public synchronized native IPInfo getIPInfo(); /* certificate info */ public synchronized native String getCertSHA1(); public synchronized native String getCertDetails(); public synchronized native byte[] getCertDER(); /* library info */ public static native String getVersion(); public static native boolean hasPKCS11Support(); public static native boolean hasTSSBlobSupport(); public static native boolean hasStokenSupport(); public static native boolean hasOATHSupport(); /* public data structures */ public static class FormOpt { public int type; public String name; public String label; public long flags; public ArrayList<FormChoice> choices = new ArrayList<FormChoice>(); public String value; public Object userData; /* FormOpt internals (called from JNI) */ void addChoice(FormChoice fc) { this.choices.add(fc); } }; public static class FormChoice { public String name; public String label; public String authType; public String overrideName; public String overrideLabel; public Object userData; }; public static class AuthForm { public String banner; public String message; public String error; public String authID; public String method; public String action; public ArrayList<FormOpt> opts = new ArrayList<FormOpt>(); public FormOpt authgroupOpt; public int authgroupSelection; public Object userData; /* AuthForm internals (called from JNI) */ FormOpt addOpt(boolean isAuthgroup) { FormOpt fo = new FormOpt(); opts.add(fo); if (isAuthgroup) { authgroupOpt = fo; } return fo; } String getOptValue(String name) { for (FormOpt fo : opts) { if (fo.name.equals(name)) { return fo.value; } } return null; } } public static class IPInfo { public String addr; public String netmask; public String addr6; public String netmask6; public ArrayList<String> DNS = new ArrayList<String>(); public ArrayList<String> NBNS = new ArrayList<String>(); public String domain; public String proxyPac; public int MTU; public ArrayList<String> splitDNS = new ArrayList<String>(); public ArrayList<String> splitIncludes = new ArrayList<String>(); public ArrayList<String> splitExcludes = new ArrayList<String>(); public HashMap<String,String> CSTPOptions = new HashMap<String,String>(); public HashMap<String,String> DTLSOptions = new HashMap<String,String>(); public Object userData; /* IPInfo internals (called from JNI) */ void addDNS(String arg) { DNS.add(arg); } void addNBNS(String arg) { NBNS.add(arg); } void addSplitDNS(String arg) { splitDNS.add(arg); } void addSplitInclude(String arg) { splitIncludes.add(arg); } void addSplitExclude(String arg) { splitExcludes.add(arg); } void addCSTPOption(String key, String value) { CSTPOptions.put(key, value); } void addDTLSOption(String key, String value) { DTLSOptions.put(key, value); } } public static class VPNStats { public long txPkts; public long txBytes; public long rxPkts; public long rxBytes; public Object userData; }; /* Optional storage for caller's data */ public Object userData; /* LibOpenConnect internals */ long libctx; boolean canceled = false; Object asyncLock = new Object(); static synchronized native void globalInit(); static { globalInit(); } synchronized native long init(String useragent); synchronized native void free(); native void doCancel(); }
package arcs.android; import android.content.Context; import android.graphics.Bitmap; import android.os.Handler; import android.os.Looper; import android.os.Trace; import android.util.Log; import android.view.View; import android.webkit.JavascriptInterface; import android.webkit.ServiceWorkerClient; import android.webkit.ServiceWorkerController; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import androidx.webkit.WebViewAssetLoader; import androidx.webkit.WebViewAssetLoader.AssetsPathHandler; import androidx.webkit.WebViewAssetLoader.ResourcesPathHandler; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import javax.inject.Provider; import javax.inject.Singleton; import arcs.api.Constants; import arcs.api.PecPortManager; import arcs.api.PortableJson; import arcs.api.PortableJsonParser; import arcs.api.RuntimeSettings; import arcs.api.UiBroker; /** * Android WebView based environment for Arcs runtime. */ @Singleton final class AndroidArcsEnvironment { private static final String TAG = "Arcs"; interface ReadyListener { void onReady(List<PortableJson> recipes); } private static final Logger logger = Logger.getLogger(AndroidArcsEnvironment.class.getName()); private static final String ASSETS_PREFIX = "https://$assets/"; // Uses relative path to support multiple protocols i.e. file, https and etc. private static final String APK_ASSETS_URL_PREFIX = "./"; private static final String ROOT_MANIFEST_FILENAME = "Root.arcs"; private static final String FIELD_MESSAGE = "message"; private static final String MESSAGE_READY = "ready"; private static final String MESSAGE_CONTEXT = "context"; private static final String FIELD_READY_RECIPES = "recipes"; private static final String MESSAGE_DATA = "data"; private static final String MESSAGE_OUTPUT = "output"; private static final String MESSAGE_PEC = "pec"; private static final String FIELD_DATA = "data"; private static final String FIELD_PEC_ID = "id"; private static final String FIELD_SESSION_ID = "sessionId"; private final PortableJsonParser jsonParser; private final PecPortManager pecPortManager; private final UiBroker uiBroker; // Fetches the up-to-date properties on every get(). private final Provider<RuntimeSettings> runtimeSettings; private final List<ReadyListener> readyListeners = new ArrayList<>(); private final Handler uiThreadHandler = new Handler(Looper.getMainLooper()); private WebView webView; AndroidArcsEnvironment( PortableJsonParser portableJsonParser, PecPortManager pecPortManager, UiBroker uiBroker, Provider<RuntimeSettings> runtimeSettings) { this.jsonParser = portableJsonParser; this.pecPortManager = pecPortManager; this.uiBroker = uiBroker; this.runtimeSettings = runtimeSettings; } void addReadyListener(ReadyListener listener) { readyListeners.add(listener); } void init(Context context) { WebView.setWebContentsDebuggingEnabled(true); webView = new WebView(context); webView.setVisibility(View.GONE); webView.getSettings().setAppCacheEnabled(false); webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); webView.clearCache(true); WebSettings arcsSettings = webView.getSettings(); arcsSettings.setDatabaseEnabled(true); arcsSettings.setGeolocationEnabled(true); arcsSettings.setJavaScriptEnabled(true); arcsSettings.setDomStorageEnabled(true); arcsSettings.setSafeBrowsingEnabled(false); // These two are needed for file:// URLs to work and load subresources arcsSettings.setAllowFileAccessFromFileURLs(true); // needed to allow WebWorkers to work in FileURLs. arcsSettings.setAllowUniversalAccessFromFileURLs(true); // As trampolines to map https protocol to file protocol. // file:///android_asset/foo final WebViewAssetLoader assetLoader = new WebViewAssetLoader.Builder() .addPathHandler("/assets/", new AssetsPathHandler(context)) .addPathHandler("/res/", new ResourcesPathHandler(context)) .build(); webView.setWebViewClient(new WebViewClient() { @Override public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { // For the renderer main thread to intercept the urls. return assetLoader.shouldInterceptRequest(request.getUrl()); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { Trace.beginAsyncSection("AndroidArcsEnvironment::init::loadUrl", 0); } @Override public void onPageFinished(WebView view, String url) { Trace.endAsyncSection("AndroidArcsEnvironment::init::loadUrl", 0); } }); ServiceWorkerController.getInstance() .setServiceWorkerClient(new ServiceWorkerClient() { @Override public WebResourceResponse shouldInterceptRequest(WebResourceRequest request) { // For the service worker thread to intercept the urls. return assetLoader.shouldInterceptRequest(request.getUrl()); } }); webView.addJavascriptInterface(this, "DeviceClient"); webView.addJavascriptInterface(new ArcsSystemTrace(), "SystemTraceApis"); RuntimeSettings settings = runtimeSettings.get(); // If using any of the host shells, i.e. pipe-shells at the host: // adding the following attribute to allow HTTP connection(s) at // <application> in service/AndroidManifest.xml: // android:usesCleartextTraffic="true" String url = settings.shellUrl(); url += "log=" + settings.logLevel(); if (settings.enableArcsExplorer()) { url += "&explore-proxy=" + settings.devServerPort(); } if (settings.useCacheManager()) { url += "&use-cache"; } url += "&systrace=" + settings.systemTraceChannel(); Log.i("Arcs", "runtime url: " + url); webView.loadUrl(url); } void destroy() { if (webView != null) { webView.destroy(); } readyListeners.clear(); } void sendMessageToArcs(String msg) { String escapedEnvelope = msg.replace("\\\"", "\\\\\"") .replace("'", "\\'"); String script = String.format("ShellApi.receive('%s');", escapedEnvelope); if (webView != null) { // evaluateJavascript runs asynchronously by default // and must be used from the UI thread uiThreadHandler.post( () -> webView.evaluateJavascript(script, (String unused) -> {})); } else { Log.e("Arcs", "webView is null"); } } @JavascriptInterface public void receive(String json) { uiThreadHandler.post(() -> { PortableJson content = jsonParser.parse(json); String message = content.getString(FIELD_MESSAGE); switch (message) { case MESSAGE_READY: configureShell(); break; case MESSAGE_CONTEXT: fireReadyEvent(content.getArray(FIELD_READY_RECIPES).asObjectArray()); break; case MESSAGE_DATA: logger.warning("logger: Received deprecated 'data' message"); break; case MESSAGE_PEC: deliverPecMessage(content.getObject(FIELD_DATA)); break; case MESSAGE_OUTPUT: if (!uiBroker.render(content.getObject(FIELD_DATA))) { logger.warning( "Skipped rendering content for " + jsonParser.stringify(content.getObject("data"))); } break; default: throw new AssertionError("Received unsupported message: " + message); } }); } private void deliverPecMessage(PortableJson message) { String pecId = message.getString(FIELD_PEC_ID); String sessionId = message.hasKey(FIELD_SESSION_ID) ? message.getString(FIELD_SESSION_ID) : null; pecPortManager.deliverPecMessage(pecId, sessionId, message); } private void fireReadyEvent(List<PortableJson> recipes) { readyListeners.forEach(listener -> listener.onReady(recipes)); } private void configureShell() { RuntimeSettings settings = runtimeSettings.get(); PortableJson urlMap = jsonParser.emptyObject() // For fetching bundled javascript. .put("https://$build/", ""); if (settings.loadAssetsFromWorkstation()) { // Fetch generated root manifest from the APK assets directory. urlMap.put( ASSETS_PREFIX + ROOT_MANIFEST_FILENAME, APK_ASSETS_URL_PREFIX + ROOT_MANIFEST_FILENAME); // Fetch remaining assets from the workstation redirecting requests // for .wasm modules to the build directory. urlMap.put(ASSETS_PREFIX, jsonParser.emptyObject() .put("root", "http://localhost:" + settings.devServerPort() + "/") .put("buildDir", "bazel-bin/") .put("buildOutputRegex", "(\\\\.wasm)|(\\\\.root\\\\.arcs)$")); } else { // Fetch all assets from the APK assets directory. urlMap.put(ASSETS_PREFIX, APK_ASSETS_URL_PREFIX); } sendMessageToArcs(jsonParser.stringify(jsonParser .emptyObject() .put(Constants.MESSAGE_FIELD, Constants.CONFIGURE_MESSAGE) .put("config", jsonParser.emptyObject() .put("rootPath", ".") .put("storage", "volatile: .put("manifest", "import '" + ASSETS_PREFIX + ROOT_MANIFEST_FILENAME + "'") .put("urlMap", urlMap)))); } }
package team.creative.ambientsounds; import java.util.Arrays; import java.util.Random; import net.minecraft.client.resources.sounds.Sound; import net.minecraft.client.resources.sounds.SoundInstance; import net.minecraft.client.resources.sounds.TickableSoundInstance; import net.minecraft.client.sounds.SoundManager; import net.minecraft.client.sounds.WeighedSoundEvents; import net.minecraft.resources.ResourceLocation; import net.minecraft.sounds.SoundSource; import net.minecraft.util.Mth; import net.minecraft.util.RandomSource; import team.creative.ambientsounds.env.AmbientEnvironment; import team.creative.creativecore.common.config.api.CreativeConfig; public class AmbientSound extends AmbientCondition { private static final Random RANDOM = new Random(); @CreativeConfig.DecimalRange(min = 0, max = 1) public transient double volumeSetting = 1; public String name; public transient String fullName; public ResourceLocation[] files; public double[] chances; public transient SoundStream stream1; public transient SoundStream stream2; protected transient boolean active; protected transient float aimedVolume; protected transient float currentVolume; protected transient float aimedPitch; protected transient int transition; protected transient int transitionTime; protected transient int pauseTimer = -1; protected transient AmbientSoundProperties currentPropertries; protected transient AmbientEngine engine; @Override public void init(AmbientEngine engine) { if (files == null || files.length == 0) throw new RuntimeException("Invalid sound " + name + " which does not contain any sound file"); this.engine = engine; if (chances == null) { chances = new double[files.length]; Arrays.fill(chances, 1D / files.length); } else if (chances.length != files.length) { double[] newChances = new double[files.length]; for (int i = 0; i < newChances.length; i++) { if (chances.length > i) newChances[i] = chances[i]; else newChances[i] = 1D / files.length; } this.chances = newChances; } } protected int getRandomFile() { if (files.length == 1) return 0; return RANDOM.nextInt(files.length); } protected int getRandomFileExcept(int i) { if (files.length == 2) return i == 0 ? 1 : 0; int index = RANDOM.nextInt(files.length - 1); if (index >= i) index++; return index; } public boolean fastTick(AmbientEnvironment env) { if (currentVolume < aimedVolume) currentVolume += Math.min(currentPropertries.getFadeInVolume(engine), aimedVolume - currentVolume); else if (currentVolume > aimedVolume) currentVolume -= Math.min(currentPropertries.getFadeOutVolume(engine), currentVolume - aimedVolume); if (isPlaying()) { if (inTransition()) { // Two files are played stream1.volume = Math.max(0, Math.min(stream1.volume, getCombinedVolume(env) * (1D - (double) transition / transitionTime))); stream2.volume = Math.min(getCombinedVolume(env), getCombinedVolume(env) * ((double) transition / transitionTime)); if (transition >= transitionTime) { engine.soundEngine.stop(stream1); stream1 = stream2; stream2 = null; } transition++; } else { // Only one file is played at the moment if (stream1.duration == -1 && currentPropertries.length != null) stream1.duration = (int) currentPropertries.length.randomValue(); else if (stream1.duration > 0 && currentPropertries.length == null) stream1.duration = -1; stream1.volume = getCombinedVolume(env); if (currentPropertries.length != null) { // If the sound has a length if (currentPropertries.pause == null && files.length > 1) { // Continuous transition if (stream1.remaining() <= 0) { transition = 0; stream2 = play(getRandomFileExcept(stream1.index), env, 0); transitionTime = currentPropertries.transition != null ? currentPropertries.transition : 60; } } else { int fadeOutTime = (int) Math.ceil(aimedVolume / currentPropertries.getFadeOutVolume(engine)); if (stream1.remaining() <= 0) { // Exceeded length engine.soundEngine.stop(stream1); stream1 = null; pauseTimer = -1; } else if (fadeOutTime > stream1.remaining()) // about to exceed length -> fade out stream1.volume = getCombinedVolume(env) * stream1.remaining() / fadeOutTime; } } } if (stream1 != null) { if (stream1.pitch < aimedPitch) stream1.pitch += Math.min(currentPropertries.getFadeInPitch(engine), aimedPitch - stream1.pitch); else if (stream1.pitch > aimedPitch) stream1.pitch -= Math.min(currentPropertries.getFadeOutPitch(engine), stream1.pitch - aimedPitch); stream1.ticksPlayed++; } if (stream2 != null) { if (stream2.pitch < aimedPitch) stream2.pitch += Math.min(currentPropertries.getFadeInPitch(engine), aimedPitch - stream2.pitch); else if (stream2.pitch > aimedPitch) stream2.pitch -= Math.min(currentPropertries.getFadeOutPitch(engine), stream2.pitch - aimedPitch); stream2.ticksPlayed++; } } else { if (stream2 != null) { engine.soundEngine.stop(stream2); stream2 = null; } if (pauseTimer == -1) if (currentPropertries.pause != null) pauseTimer = (int) currentPropertries.pause.randomValue(); if (pauseTimer <= 0) stream1 = play(getRandomFile(), env); else pauseTimer } return aimedVolume > 0 || currentVolume > 0; } @Override public AmbientSelection value(AmbientEnvironment env) { if (volumeSetting == 0) return null; return super.value(env); } public boolean tick(AmbientEnvironment env, AmbientSelection selection) { if (selection != null) { AmbientSelection soundSelection = value(env); if (soundSelection != null) { AmbientSelection last = selection.getLast(); last.subSelection = soundSelection; aimedVolume = (float) selection.getEntireVolume(); currentPropertries = selection.getProperties(); last.subSelection = null; aimedPitch = Mth.clamp(currentPropertries.getPitch(env), 0.5F, 2.0F); } else aimedVolume = 0; } else aimedVolume = 0; return aimedVolume > 0 || currentVolume > 0; } protected SoundStream play(int index, AmbientEnvironment env) { SoundStream stream = new SoundStream(index, env); stream.pitch = aimedPitch; if (currentPropertries.length != null) stream.duration = (int) currentPropertries.length.randomValue(); engine.soundEngine.play(stream); return stream; } protected SoundStream play(int index, AmbientEnvironment env, double volume) { SoundStream stream = new SoundStream(index, env); stream.pitch = aimedPitch; if (currentPropertries.length != null) stream.duration = (int) currentPropertries.length.randomValue(); stream.volume = volume; engine.soundEngine.play(stream); return stream; } public boolean isPlaying() { return stream1 != null; } public boolean inTransition() { return stream1 != null && stream2 != null; } public boolean isActive() { return active; } public void activate() { active = true; } public void deactivate() { active = false; if (stream1 != null) { engine.soundEngine.stop(stream1); stream1 = null; } if (stream2 != null) { engine.soundEngine.stop(stream2); stream2 = null; } } public void onSoundFinished() { if (stream1 != null && stream1.finished) { stream1 = null; pauseTimer = -1; } else stream2 = null; } public boolean loop() { return currentPropertries.length != null || (currentPropertries.pause == null && files.length == 1); } public double getCombinedVolume(AmbientEnvironment env) { return currentVolume * volumeSetting * env.dimension.volumeSetting * AmbientSounds.CONFIG.volume; } public class SoundStream implements TickableSoundInstance { private static final RandomSource rand = RandomSource.create(); public final int index; public final ResourceLocation location; public float generatedVoume; public WeighedSoundEvents soundeventaccessor; public double volume; public double pitch; public int duration = -1; public int ticksPlayed = 0; private boolean finished = false; private boolean playedOnce; public final SoundSource category; public SoundStream(int index, AmbientEnvironment env) { this.index = index; this.location = AmbientSound.this.files[index]; this.volume = AmbientSound.this.getCombinedVolume(env); this.category = getSoundSource(currentPropertries.category); this.generatedVoume = (float) volume; } public boolean loop() { return AmbientSound.this.loop(); } public int remaining() { return duration - ticksPlayed; } public double mute() { return AmbientSound.this.currentPropertries.mute * volume; } public void onStart() { this.finished = false; playedOnce = false; } public void onFinished() { this.finished = true; AmbientSound.this.onSoundFinished(); } public boolean hasPlayedOnce() { return playedOnce; } public void setPlayedOnce() { playedOnce = true; } public boolean hasFinished() { return finished; } @Override public String toString() { return "l:" + location + ",v:" + (Math.round(volume * 100D) / 100D) + ",i:" + index + ",p:" + pitch + ",t:" + ticksPlayed + ",d:" + duration; } @Override public boolean isLooping() { return loop(); } @Override public WeighedSoundEvents resolve(SoundManager sndHandler) { soundeventaccessor = sndHandler.getSoundEvent(location); return soundeventaccessor; } @Override public SoundInstance.Attenuation getAttenuation() { return SoundInstance.Attenuation.NONE; } @Override public SoundSource getSource() { return category; } @Override public float getPitch() { return (float) pitch; } @Override public int getDelay() { return 0; } @Override public Sound getSound() { return soundeventaccessor.getSound(rand); } @Override public ResourceLocation getLocation() { return location; } @Override public float getVolume() { return generatedVoume; } @Override public double getX() { return 0; } @Override public double getY() { return 0; } @Override public double getZ() { return 0; } @Override public boolean isStopped() { return false; } @Override public void tick() { } @Override public boolean isRelative() { return true; } } @Override public String toString() { StringBuilder builder = new StringBuilder(name); if (stream1 != null) builder.append("[" + stream1 + "]"); if (stream2 != null) builder.append("[" + stream2 + "]"); if (inTransition()) builder.append("t: " + transition + "/" + transitionTime); return builder.toString(); } public static SoundSource getSoundSource(String name) { if (AmbientSounds.CONFIG.useSoundMasterSource) return SoundSource.MASTER; if (name == null) return SoundSource.AMBIENT; for (int i = 0; i < SoundSource.values().length; i++) if (SoundSource.values()[i].getName().equals(name)) return SoundSource.values()[i]; return SoundSource.AMBIENT; } }
package music_thing; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.TextField; import javafx.stage.Stage; import org.controlsfx.control.Rating; /** * FXML Controller class * * @author joshuakaplan */ public class EditTrackController implements Initializable { @FXML private TextField editName; @FXML private TextField editArtist; @FXML private TextField editComposer; @FXML private TextField editGenre; @FXML private TextField editAlbum; @FXML private Rating editRating; private Track track; private Stage dialogStage; private boolean okClicked = false; /** * Sets the stage of this dialog. * @param dialogStage */ public void setDialogStage(Stage dialogStage) { this.dialogStage = dialogStage; } /** * Returns true if the user clicked OK, false otherwise. * @return */ public boolean isOkClicked() { return okClicked; } /** * Called when the user clicks ok. */ @FXML private void handleOk() { track.setName(editName.getText()); track.setArtist(editArtist.getText()); track.setComposer(editComposer.getText()); track.setAlbum(editAlbum.getText()); track.setGenre(editGenre.getText()); track.setRating(editRating.getRating()); okClicked = true; dialogStage.close(); } /** * Called when the user clicks cancel. */ @FXML private void handleCancel() { dialogStage.close(); } public void setTrack(Track track){ this.track=track; editName.setText(track.getName()); editArtist.setText(track.getArtist()); editComposer.setText(track.getComposer()); editGenre.setText(track.getGenre()); editAlbum.setText(track.getAlbum()); editRating.setRating(track.getRating()); } /** * Initializes the controller class. * @param url * @param rb */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO } }
package us.crast.mondochest.dialogue; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import mondocommand.ChatMagic; import org.apache.commons.lang.StringUtils; import org.bukkit.conversations.ConversationAbandonedEvent; import org.bukkit.conversations.ConversationAbandonedListener; import org.bukkit.conversations.ConversationContext; import org.bukkit.conversations.ConversationFactory; import org.bukkit.conversations.ConversationPrefix; import org.bukkit.conversations.Prompt; import org.bukkit.conversations.RegexPrompt; import org.bukkit.entity.Player; import us.crast.chatmagic.BasicMessage; import us.crast.chatmagic.MessageWithStatus; import us.crast.chatmagic.MondoMessage; import us.crast.chatmagic.Status; import us.crast.datastructures.DefaultDict; import us.crast.datastructures.builders.ListBuilder; import us.crast.mondochest.BankSet; import us.crast.mondochest.MondoChest; import us.crast.mondochest.MondoConfig; import us.crast.mondochest.MondoConstants; import us.crast.mondochest.MondoListener; import us.crast.mondochest.persist.BankManager; import us.crast.utils.CollectionUtil; public final class AccessConvo implements ConversationAbandonedListener { private ConversationFactory conversationFactory; private MondoListener listener; private BankManager bankManager; public AccessConvo(MondoChest plugin, MondoListener listener) { this.bankManager = plugin.getBankManager(); this.listener = listener; this.conversationFactory = new ConversationFactory(plugin) .withModality(false) .withPrefix(new ConvoPrefix()) .withFirstPrompt(new AccessPrompt()) .withTimeout(60) .withEscapeSequence("/quit") .addConversationAbandonedListener(this); } public void begin(Player player) throws MondoMessage { player.sendMessage(listAccess(player, 1).render(false)); conversationFactory.buildConversation(player).begin(); } @Override public void conversationAbandoned(ConversationAbandonedEvent e) { if (!e.gracefulExit()) { e.getContext().getForWhom().sendRawMessage(BasicMessage.render(Status.ERROR, "Access conversation ended")); } else { e.getContext().getForWhom().sendRawMessage(BasicMessage.render(Status.INFO, "Bye!")); } } public MessageWithStatus listAccess(Player player, int page) throws MondoMessage { if (!MondoConfig.ACL_ENABLED) { throw new MondoMessage(MondoConstants.ACL_ENABLED_MESSAGE, Status.ERROR); } BankSet bank = listener.getLastClickedBank(player, true); if (bank.getAcl().isEmpty()) { return new BasicMessage("Allowed Users: EVERYONE", Status.SUCCESS); } else { DefaultDict<String, List<String>> byRole = new DefaultDict<String, List<String>>(new ListBuilder<String>()); for (Map.Entry<String, String> entry : CollectionUtil.sortedDictEntries(bank.stringAcl())) { byRole.ensure(entry.getValue()).add( ChatMagic.colorize("{NOUN}%s{GOLD}", entry.getKey()) ); } List<String> lines = new ArrayList<String>(); for (Map.Entry<String, List<String>> e : byRole.entrySet()) { lines.add(ChatMagic.colorize(" {VERB}%s: %s", e.getKey(), StringUtils.join(e.getValue(), ", "))); } String allowed = StringUtils.join(lines, "\n"); return new BasicMessage( String.format("Allowed Users:\n%s", allowed), Status.SUCCESS ); } } public MessageWithStatus addAccess(Player player, String target, String role) throws MondoMessage { BankSet bank = listener.getLastClickedBank(player, true); if (bank.addAccess(target, role)) { bankManager.markChanged(bank, true); return new BasicMessage(Status.SUCCESS, "Added {NOUN}%s {GREEN}with role {GRAY}%s", target, role); } else { return new BasicMessage(Status.ERROR, "Role {VERB}%s {ERROR}doesn't exist", role); } } public MessageWithStatus removeAccess(Player player, String target) throws MondoMessage { BankSet bank = listener.getLastClickedBank(player, true); if (bank.removeAccess(target)) { bankManager.markChanged(bank, true); return new BasicMessage(Status.SUCCESS, "Removed user %s", target); }else { return new BasicMessage(Status.ERROR, "WOT"); } } final class AccessPrompt extends RegexPrompt { public AccessPrompt() { super(Pattern.compile("^/?\\w+( .*)?")); } @Override public String getPromptText(ConversationContext ctx) { Object response = ctx.getSessionData("next_response"); if (response != null && response instanceof MessageWithStatus) { ctx.setSessionData("next_response", null); return ((MessageWithStatus) response).render(false); } else { return ChatMagic.colorize("{USAGE}Commands: {AQUA}list{GOLD}, {AQUA}add{GOLD}, {AQUA}remove{GOLD}, {AQUA}quit"); } } @Override protected Prompt acceptValidatedInput(ConversationContext ctx, String input) { String[] parts = input.split(" ", 3); Player player = (Player) ctx.getForWhom(); MessageWithStatus response = null; String cmd = parts[0].toLowerCase(); if (cmd.startsWith("/")) cmd = cmd.substring(1); try { if (cmd.equals("list")) { int page = (parts.length == 2)? Integer.parseInt(parts[1]) : 1; response = listAccess(player, page); } else if (cmd.equals("add")) { if (parts.length >= 2) { String role = (parts.length == 3)? parts[2] : "user"; response = addAccess(player, parts[1], role); } else { response = new BasicMessage("Usage: add <name> [<role>]", Status.USAGE); } } else if (cmd.equals("remove")) { if (parts.length == 2) { response = removeAccess(player, parts[1]); } else { response = new BasicMessage("Usage: remove <name>", Status.USAGE); } } else if (cmd.equals("quit")) { return null; } } catch (MondoMessage m) { response = m; } if (response != null) { ctx.setSessionData("next_response", response); } return this; } } public void shutdown() { listener = null; conversationFactory = null; } public class ConvoPrefix implements ConversationPrefix { @Override public String getPrefix(ConversationContext arg0) { return ChatMagic.colorize("{GOLD}access{RED}> {RESET}"); } } }
package wanion.unidict.integration; import cofh.core.inventory.ComparableItemStack; import cofh.thermalexpansion.util.managers.machine.*; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; import wanion.lib.common.Util; import javax.annotation.Nonnull; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import java.util.Map; final class TEIntegration extends AbstractIntegrationThread { TEIntegration() { super("Thermal Expansion"); } @Override public String call() { try { fixCompactorRecipes(); fixRefineryRecipes(); fixInductionSmelterRecipes(); fixRedstoneFurnaceRecipes(); fixPulverizerRecipes(); } catch (Exception e) { logger.error(threadName + e); } return threadName + "The world seems to be more thermally involved."; } private void fixCompactorRecipes() { final List<Map<ComparableItemStack, CompactorManager.CompactorRecipe>> compactorRecipeMapList = new ArrayList<>(); compactorRecipeMapList.add(Util.getField(CompactorManager.class, "recipeMapAll", null, Map.class)); compactorRecipeMapList.add(Util.getField(CompactorManager.class, "recipeMapPlate", null, Map.class)); compactorRecipeMapList.add(Util.getField(CompactorManager.class, "recipeMapCoin", null, Map.class)); compactorRecipeMapList.add(Util.getField(CompactorManager.class, "recipeMapGear", null, Map.class)); compactorRecipeMapList.forEach(this::fixCompactorRecipe); } private void fixCompactorRecipe(final Map<ComparableItemStack, CompactorManager.CompactorRecipe> compactorRecipeMap) { if (compactorRecipeMap == null) return; Constructor<CompactorManager.CompactorRecipe> recipeCompactorConstructor = null; try { recipeCompactorConstructor = CompactorManager.CompactorRecipe.class.getDeclaredConstructor(ItemStack.class, ItemStack.class, int.class); recipeCompactorConstructor.setAccessible(true); } catch (NoSuchMethodException e) { e.printStackTrace(); } if (recipeCompactorConstructor == null) return; for (final ComparableItemStack recipeMapKey : compactorRecipeMap.keySet()) { final CompactorManager.CompactorRecipe recipeCompactor = compactorRecipeMap.get(recipeMapKey); final ItemStack correctOutput = resourceHandler.getMainItemStack(recipeCompactor.getOutput()); if (correctOutput == recipeCompactor.getOutput()) continue; try { compactorRecipeMap.put(recipeMapKey, recipeCompactorConstructor.newInstance(recipeCompactor.getInput(), correctOutput, recipeCompactor.getEnergy())); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } } private void fixInductionSmelterRecipes() { final Map<List<ComparableItemStack>, SmelterManager.SmelterRecipe> recipeMap = Util.getField(SmelterManager.class, "recipeMap", null, Map.class); if (recipeMap == null) return; Constructor<SmelterManager.SmelterRecipe> smelterRecipeConstructor = null; try { smelterRecipeConstructor = SmelterManager.SmelterRecipe.class.getDeclaredConstructor(ItemStack.class, ItemStack.class, ItemStack.class, ItemStack.class, int.class, int.class); smelterRecipeConstructor.setAccessible(true); } catch (NoSuchMethodException e) { e.printStackTrace(); } if (smelterRecipeConstructor == null) return; for (final List<ComparableItemStack> recipeMapKey : recipeMap.keySet()) { final SmelterManager.SmelterRecipe smelterRecipe = recipeMap.get(recipeMapKey); final ItemStack correctOutput = resourceHandler.getMainItemStack(smelterRecipe.getPrimaryOutput()); final ItemStack correctSecondaryOutput = resourceHandler.getMainItemStack(smelterRecipe.getSecondaryOutput()); if (correctOutput == smelterRecipe.getPrimaryOutput() && correctSecondaryOutput == smelterRecipe.getSecondaryOutput()) continue; try { recipeMap.put(recipeMapKey, smelterRecipeConstructor.newInstance(smelterRecipe.getPrimaryInput(), smelterRecipe.getSecondaryInput(), correctOutput, correctSecondaryOutput, smelterRecipe.getSecondaryOutputChance(), smelterRecipe.getEnergy())); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } } private void fixRefineryRecipes() { final Int2ObjectOpenHashMap<RefineryManager.RefineryRecipe> recipeMap = Util.getField(RefineryManager.class, "recipeMap", null, Int2ObjectOpenHashMap.class); if (recipeMap == null) return; Constructor<RefineryManager.RefineryRecipe> refineryRecipeConstructor = null; try { refineryRecipeConstructor = RefineryManager.RefineryRecipe.class.getDeclaredConstructor(FluidStack.class, FluidStack.class, ItemStack.class, int.class, int.class); refineryRecipeConstructor.setAccessible(true); } catch (NoSuchMethodException e) { e.printStackTrace(); } if (refineryRecipeConstructor == null) return; for (final int recipeMapKey : recipeMap.keySet()) { final RefineryManager.RefineryRecipe refineryRecipe = recipeMap.get(recipeMapKey); final ItemStack correctOutput = resourceHandler.getMainItemStack(refineryRecipe.getOutputItem()); if (correctOutput == refineryRecipe.getOutputItem()) continue; try { recipeMap.put(recipeMapKey, refineryRecipeConstructor.newInstance(refineryRecipe.getInput(), refineryRecipe.getOutputFluid(), correctOutput, refineryRecipe.getEnergy(), refineryRecipe.getChance())); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } } private void fixRedstoneFurnaceRecipes() { final Map<ComparableItemStack, FurnaceManager.FurnaceRecipe> recipeMap = Util.getField(FurnaceManager.class, "recipeMap", null, Map.class); if (recipeMap == null) return; Constructor<FurnaceManager.FurnaceRecipe> redstoneFurnaceRecipeConstructor = null; try { redstoneFurnaceRecipeConstructor = FurnaceManager.FurnaceRecipe.class.getDeclaredConstructor(ItemStack.class, ItemStack.class, int.class); redstoneFurnaceRecipeConstructor.setAccessible(true); } catch (NoSuchMethodException e) { e.printStackTrace(); } if (redstoneFurnaceRecipeConstructor == null) return; for (final ComparableItemStack recipeMapKey : recipeMap.keySet()) { final FurnaceManager.FurnaceRecipe redstoneFurnaceRecipe = recipeMap.get(recipeMapKey); final ItemStack correctOutput = resourceHandler.getMainItemStack(redstoneFurnaceRecipe.getOutput()); if (correctOutput == redstoneFurnaceRecipe.getOutput()) continue; try { recipeMap.put(recipeMapKey, redstoneFurnaceRecipeConstructor.newInstance(redstoneFurnaceRecipe.getInput(), correctOutput, redstoneFurnaceRecipe.getEnergy())); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } } private void fixPulverizerRecipes() { final Map<ComparableItemStack, PulverizerManager.PulverizerRecipe> recipeMap = Util.getField(PulverizerManager.class, "recipeMap", null, Map.class); if (recipeMap == null) return; Constructor<PulverizerManager.PulverizerRecipe> pulverizerRecipeConstructor = null; try { pulverizerRecipeConstructor = PulverizerManager.PulverizerRecipe.class.getDeclaredConstructor(ItemStack.class, ItemStack.class, ItemStack.class, int.class, int.class); pulverizerRecipeConstructor.setAccessible(true); } catch (NoSuchMethodException e) { e.printStackTrace(); } if (pulverizerRecipeConstructor == null) return; for (final ComparableItemStack recipeMapKey : recipeMap.keySet()) { final PulverizerManager.PulverizerRecipe pulverizerRecipe = recipeMap.get(recipeMapKey); final ItemStack correctOutput = resourceHandler.getMainItemStack(pulverizerRecipe.getPrimaryOutput()); final ItemStack correctSecondaryOutput = resourceHandler.getMainItemStack(pulverizerRecipe.getSecondaryOutput()); if (correctOutput == pulverizerRecipe.getPrimaryOutput() && correctSecondaryOutput == pulverizerRecipe.getSecondaryOutput()) continue; try { recipeMap.put(recipeMapKey, pulverizerRecipeConstructor.newInstance(pulverizerRecipe.getInput(), correctOutput, correctSecondaryOutput, pulverizerRecipe.getSecondaryOutputChance(), pulverizerRecipe.getEnergy())); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } } }
package org.deidentifier.arx.algorithm; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.PriorityQueue; import java.util.Stack; import org.deidentifier.arx.criteria.KAnonymity; import org.deidentifier.arx.framework.check.INodeChecker; import org.deidentifier.arx.framework.check.history.History; import org.deidentifier.arx.framework.check.history.History.PruningStrategy; import org.deidentifier.arx.framework.lattice.Lattice; import org.deidentifier.arx.framework.lattice.Node; /** * This class provides a reference implementation of the ARX algorithm. * * @author Prasser, Kohlmayer */ public class FLASHAlgorithm extends AbstractAlgorithm { /** Potential traverse types */ private static enum TraverseType { FIRST_PHASE_ONLY, FIRST_AND_SECOND_PHASE, SECOND_PHASE_ONLY } /** The stack. */ private final Stack<Node> stack; /** The heap. */ private final PriorityQueue<Node> pqueue; /** The current path. */ private final ArrayList<Node> path; /** Are the pointers for a node with id 'index' already sorted?. */ private final boolean[] sorted; /** The strategy. */ private final FLASHStrategy strategy; /** Traverse type of 2PF */ private TraverseType traverseType; /** The history*/ private History history; /** * Creates a new instance of the ARX algorithm. * * @param lattice * The lattice * @param history * The history * @param checker * The checker * @param strategy * The strategy */ public FLASHAlgorithm(final Lattice lattice, final INodeChecker checker, final FLASHStrategy strategy) { this(lattice, checker, strategy, false); } /** * Creates a new instance of the ARX algorithm. * * @param lattice * The lattice * @param history * The history * @param checker * The checker * @param strategy * The strategy * @param secondPhaseOnly * Force the algorithm to only perform the second phase */ public FLASHAlgorithm(final Lattice lattice, final INodeChecker checker, final FLASHStrategy strategy, final boolean secondPhaseOnly) { super(lattice, checker); this.strategy = strategy; pqueue = new PriorityQueue<Node>(11, strategy); sorted = new boolean[lattice.getSize()]; path = new ArrayList<Node>(); stack = new Stack<Node>(); this.history = checker.getHistory(); if (secondPhaseOnly){ this.traverseType = TraverseType.SECOND_PHASE_ONLY; history.setPruningStrategy(PruningStrategy.CHECKED); } else { // NOTE: If we assume practical monotonicity then we assume // monotonicity for both criterion AND metric! // NOTE: We assume monotonicity for criterion with 0% suppression if ((checker.getConfiguration().getAbsoluteMaxOutliers() == 0) || (checker.getConfiguration().isCriterionMonotonic() && checker.getMetric() .isMonotonic()) || (checker.getConfiguration().isPracticalMonotonicity())) { traverseType = TraverseType.FIRST_PHASE_ONLY; history.setPruningStrategy(PruningStrategy.ANONYMOUS); } else { if (checker.getConfiguration().getMinimalGroupSize() != Integer.MAX_VALUE) { traverseType = TraverseType.FIRST_AND_SECOND_PHASE; history.setPruningStrategy(PruningStrategy.K_ANONYMOUS); } else { traverseType = TraverseType.SECOND_PHASE_ONLY; history.setPruningStrategy(PruningStrategy.CHECKED); } } } } /** * Check a node during the first phase * * @param node */ protected void checkNode1(final Node node) { checker.check(node); switch (traverseType) { case FIRST_PHASE_ONLY: lattice.tagAnonymous(node, node.isAnonymous()); break; case FIRST_AND_SECOND_PHASE: lattice.tagKAnonymous(node, node.isKAnonymous()); lattice.triggerTagged(); break; default: throw new RuntimeException("This method must not be called when only executing the 2nd phase!"); } } /** * Check a node during the second phase * * @param node */ protected void checkNode2(final Node node) { if (!node.isChecked()) { // TODO: Rethink var1 & var2 final boolean var1 = !checker.getMetric().isMonotonic() && checker.getConfiguration() .isCriterionMonotonic(); final boolean var2 = !checker.getMetric().isMonotonic() && !checker.getConfiguration() .isCriterionMonotonic() && checker.getConfiguration() .isPracticalMonotonicity(); // NOTE: Might return non-anonymous result as optimum, when // 1. the criterion is not monotonic, and // 2. practical monotonicity is assumed, and // 3. the metric is non-monotonic BUT independent. // -> Such a metric does currently not exist if (checker.getMetric().isIndependent() && (var1 || var2)) { checker.getMetric().evaluate(node, null); } else { checker.check(node); } } // In case metric is monotone it can be tagged if the node is anonymous if (checker.getMetric().isMonotonic() && node.isAnonymous()) { lattice.tagAnonymous(node, node.isAnonymous()); } else { node.setTagged(); lattice.untaggedCount[node.getLevel()] lattice.triggerTagged(); } } /** * Checks a path binary. * * @param path * The path */ private final Node checkPathBinary(final List<Node> path) { int low = 0; int high = path.size() - 1; Node lastAnonymousNode = null; while (low <= high) { final int mid = (low + high) >>> 1; final Node node = path.get(mid); if (!node.isTagged()) { checkNode1(node); if (!isNodeAnonymous(node)) { // put only non-anonymous nodes in // pqueue, as potetnially a // snaphsot is avaliable for (final Node up : node.getSuccessors()) { if (!up.isTagged()) { // only unknown nodes are // nesessary pqueue.add(up); } } } } if (isNodeAnonymous(node)) { lastAnonymousNode = node; high = mid - 1; } else { low = mid + 1; } } return lastAnonymousNode; } /** * Checks a path sequentially. * * @param path * The path */ private final void checkPathExhaustive(final List<Node> path) { for (final Node node : path) { if (!node.isTagged()) { checkNode2(node); // Put all untagged nodes on the stack for (final Node up : node.getSuccessors()) { if (!up.isTagged()) { stack.push(up); } } } } } /** * Greedy find path. * * @param current * The current * @return the list */ private final List<Node> findPath(Node current) { path.clear(); path.add(current); boolean found = true; while (found) { found = false; this.sort(current); for (final Node candidate : current.getSuccessors()) { if (!candidate.isTagged()) { current = candidate; path.add(candidate); found = true; break; } } } return path; } /** * Is the node anonymous according to the first run of the algorithm * * @param node * @param traverseType * @return */ private boolean isNodeAnonymous(final Node node) { // SECOND_PHASE_ONLY not needed, as isNodeAnonymous is only used during the first phase switch (traverseType) { case FIRST_PHASE_ONLY: return node.isAnonymous(); case FIRST_AND_SECOND_PHASE: return node.isKAnonymous(); default: throw new RuntimeException("Not implemented!"); } } /** * Sorts a level. * * @param level * The level * @return the node[] */ private final Node[] sort(final int level) { final Node[] result = new Node[lattice.getUntaggedCount(level)]; if (result.length == 0) { return result; } int index = 0; final Node[] nlevel = lattice.getLevels()[level]; for (final Node n : nlevel) { if (!n.isTagged()) { result[index++] = n; } } this.sort(result); return result; } /** * Sorts upwards pointers of a node. * * @param current * The current */ private final void sort(final Node current) { if (!sorted[current.id]) { this.sort(current.getSuccessors()); sorted[current.id] = true; } } /** * Sorts a node array. * * @param array * The array */ protected final void sort(final Node[] array) { Arrays.sort(array, strategy); } /* * (non-Javadoc) * * @see org.deidentifier.ARX.algorithm.AbstractAlgorithm#traverse() */ @Override public void traverse() { pqueue.clear(); stack.clear(); // check first node for (final Node[] level : lattice.getLevels()) { if (level.length != 0) { if (level.length == 1) { checker.check(level[0]); break; } else { throw new RuntimeException("Multiple bottom nodes!"); } } } // For each node final int length = lattice.getLevels().length; for (int i = 0; i < length; i++) { Node[] level; level = this.sort(i); for (final Node node : level) { if (!node.isTagged()) { pqueue.add(node); while (!pqueue.isEmpty()) { Node head = pqueue.poll(); // if anonymity is unknown if (!head.isTagged()) { // If first phase is needed if (traverseType == TraverseType.FIRST_PHASE_ONLY || traverseType == TraverseType.FIRST_AND_SECOND_PHASE) { findPath(head); head = checkPathBinary(path); } // if second phase needed, process path if (head != null && (traverseType == TraverseType.FIRST_AND_SECOND_PHASE || traverseType == TraverseType.SECOND_PHASE_ONLY)) { // Change strategy final PruningStrategy pruning = history.getPruningStrategy(); history.setPruningStrategy(PruningStrategy.CHECKED); // Untag all nodes above first anonymous node if they have // already been tagged in first phase. // They will all be tagged again in the second phase if (traverseType == TraverseType.FIRST_AND_SECOND_PHASE) { lattice.doUnTagUpwards(head); } stack.push(head); while (!stack.isEmpty()) { final Node start = stack.pop(); if (!start.isTagged()) { findPath(start); checkPathExhaustive(path); } } // Switch back to previous strategy history.setPruningStrategy(pruning); } } } } } } } }
package com.kaviju.accesscontrol.model; import java.util.*; import org.apache.log4j.Logger; import com.webobjects.appserver.*; import com.webobjects.eocontrol.*; import com.webobjects.foundation.NSArray; @SuppressWarnings("serial") public abstract class KAUserProfile extends com.kaviju.accesscontrol.model.base._KAUserProfile { @SuppressWarnings("unused") private static Logger log = Logger.getLogger(KAUserProfile.class); private Set<String> allEffectiveRoles; @SuppressWarnings("unchecked") public <U extends KAUser> U user(Class<U> userClass) { return (U) user(); } @Override public void awakeFromInsertion(EOEditingContext editingContext) { super.awakeFromInsertion(editingContext); setIsDefaultProfile(false); } public String profileCode() { if (profile() != null) { return profile().code(); } return null; } @Override public void clearProperties() { super.clearProperties(); clearAllEffectivesRoles(); } public boolean hasRole(String roleCode) { return allEffectiveRoles().contains(roleCode); } public boolean hasAtLeastOneOfTheseRoles(String ...roleCodes) { return hasAtLeastOneOfTheseRoles(Arrays.asList(roleCodes)); } public boolean hasAtLeastOneOfTheseRoles(Collection<String> rolesCodes) { for (String roleCode : rolesCodes) { if (hasRole(roleCode)) { return true; } } return false; } public boolean hasAllTheseRoles(Collection<String> requiredRoleCodes) { for (String roleCode : requiredRoleCodes) { if ( !hasRole(roleCode)) { return false; } } return true; } public synchronized Set<String> allEffectiveRoles() { if (allEffectiveRoles == null) { HashSet<String> allRoles = new HashSet<>(); if (profile() != null) { allRoles.addAll(KARole.CODE.arrayValueInObject(profile().mandatoryRoles())); } allRoles.addAll(KAUserProfileRole.ROLE.dot(KARole.CODE).arrayValueInObject(roles())); allEffectiveRoles = Collections.unmodifiableSet(allRoles); } return allEffectiveRoles; } @Override public void setProfile(KAProfile value) { deleteAllRolesRelationships(); if (value != null) { for (KARole role : value.mandatoryRoles()) { addRole(role); } } super.setProfile(value); clearAllEffectivesRoles(); } public void addRole(KARole role) { KAUserProfileRole newUserProfileRole = createRolesRelationship(); newUserProfileRole.setRole(role); clearAllEffectivesRoles(); } public void removeRole(KARole role) { for (KAUserProfileRole userProfileRole : roles().immutableClone()) { if (userProfileRole.role().equals(role)) { deleteRolesRelationship(userProfileRole); } } clearAllEffectivesRoles(); } private synchronized void clearAllEffectivesRoles() { allEffectiveRoles = null; } public void setProfileWithCode(String profileCode) { KAProfile profile = KAProfile.profileWithCode(editingContext(), profileCode); setProfile(profile); } public NSArray<String> itemCodesForRole(String roleCode) { KAUserProfileRole foundUserProfileRole = userProfileRoleWithCode(roleCode); if (foundUserProfileRole != null) { return foundUserProfileRole.itemCodes(); } return new NSArray<String>(); } public <T extends EOEnterpriseObject> NSArray<T> itemsAsObjectsForRole(Class<T> entityClass, String roleCode) { KAUserProfileRole foundUserProfileRole = userProfileRoleWithCode(roleCode); if (foundUserProfileRole != null) { return foundUserProfileRole.itemsAsObjects(entityClass); } return new NSArray<T>(); } public NSArray<KAAccessListItem> listItemsForRole(KARole role) { return userProfileRoleWithCode(role.code()).listItems(); } public void addItemForRole(KAAccessListItem item, KARole role) { userProfileRoleWithCode(role.code()).addToListItems(item); } public void removeItemForRole(KAAccessListItem item, KARole role) { userProfileRoleWithCode(role.code()).removeFromListItems(item); } private KAUserProfileRole userProfileRoleWithCode(String roleCode) { for (KAUserProfileRole userProfileRole : roles()) { if (userProfileRole.role().code().equals(roleCode)) { return userProfileRole; } } return null; } public WOComponent createHomePage(WOContext context) { return user().createHomePageForUserProfile(context, this); } }
package authentication.web; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.UUID; import javax.mail.MessagingException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.codehaus.jackson.map.ObjectMapper; import util.EmailSender; import util.HttpUtils; import util.RandomStringGenerator; import accounts.FrameworkUserManager; import accounts.UserProfile; import authentication.FrameworkConfiguration; /** * Servlet provides some authentication functions: login, logout, register new user, restore password, change password. * * For some types of errors it sends error code and description in response. * In these cases response has json format: {code : ERROR_CODE, message : ERROR_DESCRIPTION}. * * Error codes: * 1 - user already exists (during user registration, user with the same name or e-mail already exists) * 2 - incorrect old password (change password) * 3 - user doesn't exists (in restore password) */ public class AuthenticationServlet extends HttpServlet { private static final long serialVersionUID = 1L; private FrameworkUserManager frameworkUserManager; @Override public void init(ServletConfig config) throws ServletException { super.init(config); try { frameworkUserManager = FrameworkConfiguration.getInstance(getServletContext()) .getFrameworkUserManager(); } catch (FileNotFoundException e) { throw new ServletException(e); } catch (Exception e) { throw new ServletException(e); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String mode = request.getParameter("mode"); PrintWriter out = response.getWriter(); if ("login".equals(mode)) { String username = request.getParameter("username"); String password = request.getParameter("password"); // check username and password boolean correctCredentials = false; try { correctCredentials = frameworkUserManager.checkPassword(username, password); } catch (Exception e) { e.printStackTrace(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); return; } if (!correctCredentials) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } // create and save session token String token = UUID.randomUUID().toString(); try { frameworkUserManager.saveSessionToken(username, token); } catch (Exception e) { e.printStackTrace(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); return; } // get user profile UserProfile userProfile; try { userProfile = frameworkUserManager.getUserProfile(username); // send request with session token and user profile response.addCookie(new Cookie("token", token)); ObjectMapper objectMapper = new ObjectMapper(); String responseStr = objectMapper.writeValueAsString(userProfile); out.print(responseStr); } catch (Exception e) { e.printStackTrace(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); return; } } else if ("logout".equals(mode)) { String username = request.getParameter("username"); // remove user session tokens try { frameworkUserManager.removeAllSessionTokens(username); // remove session token from cookies Cookie tokenCookie = new Cookie("token", ""); tokenCookie.setMaxAge(0); } catch (Exception e) { e.printStackTrace(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } } else if ("create".equals(mode)) { String username = request.getParameter("username"); String email = request.getParameter("email"); //check if user already exists boolean userExists = false; try { userExists = frameworkUserManager.checkUserExists(username, email); } catch (Exception e) { e.printStackTrace(); } if (userExists) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); out.print("{\"code\" : \"1\", \"message\" : \"User already exists\"}"); return; } // create user String password = new RandomStringGenerator().generateBasic(6); try { frameworkUserManager.createUser(username, password, email); EmailSender emailSender = FrameworkConfiguration.getInstance(getServletContext()) .getDefaultEmailSender(); emailSender.send(email, "ACC registration", "Your login: " + username + ", password: " + password); String responseStr = "{\"message\" : \"Your password will be sent to your e-mail address " + email + " \"}"; response.getWriter().print(responseStr); } catch (MessagingException e) { e.printStackTrace(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (Exception e) { e.printStackTrace(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } } else if ("changePassword".equals(mode)) { String username = request.getParameter("username"); String oldPassword = request.getParameter("oldPassword"); String newPassword = request.getParameter("newPassword"); // check token String token = HttpUtils.getCookieValue(request, "token"); boolean valid; try { valid = frameworkUserManager.checkToken(username, token); if (!valid) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "invalid token " + token + " for user " + username); } else { //check old password boolean isCorrect = frameworkUserManager.checkPassword(username, oldPassword); if (!isCorrect) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); out.print("{\"code\" : \"2\", \"message\" : \"Incorrect old password\"}"); return; } // change password frameworkUserManager.changePassword(username, oldPassword, newPassword); // send new password to user UserProfile userProfile = frameworkUserManager.getUserProfile(username); if (userProfile == null) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "User profile " + username + " not found"); return; } EmailSender emailSender = FrameworkConfiguration.getInstance(getServletContext()).getDefaultEmailSender(); emailSender.send(userProfile.getEmail(), "ACC change password", "Your password for the Linked Data Information Workbench account " + username + " was changed."); String responseStr = "{\"message\" : \"Your password was changed\"}"; response.getWriter().print(responseStr); } } catch (Exception e) { e.printStackTrace(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } } else if ("restorePassword".equals(mode)) { String username = request.getParameter("username"); // get user profile UserProfile userProfile; try { userProfile = frameworkUserManager.getUserProfile(username); if (userProfile == null) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); out.print("{\"code\" : \"3\", \"message\" : \"User doesn't exists\"}"); return; } // change password String password = new RandomStringGenerator().generateBasic(6); frameworkUserManager.setPassword(username, password); // send new password to user EmailSender emailSender = FrameworkConfiguration.getInstance(getServletContext()) .getDefaultEmailSender(); emailSender.send(userProfile.getEmail(), "ACC restore password", "Your login: " + username + ", password: " + password); String responseStr = "{\"message\" : \"New password will be sent to your e-mail address " + userProfile.getEmail() + " \"}"; response.getWriter().print(responseStr); } catch (MessagingException e) { e.printStackTrace(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (Exception e) { e.printStackTrace(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } } else if ("getUsers".equals(mode)) { Collection<UserProfile> profiles; try { profiles = frameworkUserManager.getAllUsersProfiles(); } catch (Exception e) { e.printStackTrace(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); return; } Collection<String> accounts = new ArrayList<String>(); for (UserProfile p : profiles) accounts.add(p.getAccountURI()); String responseStr = new ObjectMapper().writeValueAsString(accounts); response.getWriter().print(responseStr); } else { // throw new ServletException("Unexpected mode: " + mode); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unexpected mode: " + mode); } } }
package com.googlecode.jslint4java; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import static org.junit.matchers.JUnitMatchers.*; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; /** * @author dom */ public class JSLintTest { private static final String EXPECTED_SEMICOLON = "Expected ';' and instead saw '(end)'."; private JSLint lint = null; // Check that the issues list matches zero or more reasons. private void assertIssues(List<Issue> issues, String... reasons) { assertThat(issues, is(notNullValue())); String msg = "Actual issues: " + issues; assertThat(msg, issues.size(), is(reasons.length)); for (int i = 0; i < reasons.length; i++) { assertThat(issues.get(i).getReason(), is(reasons[i])); } } // small helper function. private JSLintResult lint(Reader reader) throws IOException { return lint.lint("-", reader); } // small helper function. private JSLintResult lint(String source) { return lint.lint("-", source); } @Before public void setUp() throws IOException { lint = new JSLintBuilder().fromDefault(); } @Test public void testAccurateColumnNumbers() { List<Issue> issues = lint("var foo = 1").getIssues(); // ....................... 123456789012 assertIssues(issues, EXPECTED_SEMICOLON); assertThat(issues.get(0).getCharacter(), is(12)); } @Test public void testAccurateLineNumbers() { List<Issue> issues = lint("var foo = 1").getIssues(); assertIssues(issues, EXPECTED_SEMICOLON); assertThat(issues.get(0).getLine(), is(1)); } /** * See what information we can return about a single function. * @throws Exception */ @Test public void testDataFunctions() throws Exception { JSLintResult result = lint("var z = 5;function foo(x) {var y = x+z;return y;}"); assertIssues(result.getIssues()); List<JSFunction> functions = result.getFunctions(); assertThat(functions.size(), is(1)); JSFunction f1 = functions.get(0); assertThat(f1.getName(), is("foo")); assertThat(f1.getLine(), is(1)); assertThat(f1.getParams().size(), is(1)); assertThat(f1.getParams().get(0), is("x")); // TODO: how to test getClosure()? assertThat(f1.getVars().size(), is(1)); assertThat(f1.getVars().get(0), is("y")); // TODO: test getException() // TODO: test getOuter() // TODO: test getUnused() assertThat(f1.getGlobal().size(), is(1)); assertThat(f1.getGlobal().get(0), is("z")); // TODO: test getLabel() } @Test public void testDataGlobals() throws Exception { JSLintResult result = lint("var foo = 12;"); assertTrue(result.getIssues().isEmpty()); assertThat(result.getGlobals(), hasItem("foo")); } @Test public void testDataImplieds() throws Exception { JSLintResult result = lint("foo();"); assertIssues(result.getIssues()); List<JSIdentifier> implieds = result.getImplieds(); assertThat(implieds.size(), is(1)); assertThat(implieds.get(0).getName(), is("foo")); assertThat(implieds.get(0).getLine(), is(1)); } @Test public void testDataJsonness() throws Exception { JSLintResult result = lint("{\"a\":100}"); assertIssues(result.getIssues()); assertTrue(result.isJson()); } @Test public void testDataMembers() throws Exception { JSLintResult result = lint("var obj = {\"a\":1, \"b\": 42, 3: \"c\"};"); assertIssues(result.getIssues()); Map<String, Integer> members = result.getMember(); assertThat(members.size(), is(3)); // It's a count of how many times we've seen each member. assertThat(members.get("a"), is(1)); assertThat(members.get("b"), is(1)); assertThat(members.get("3"), is(0)); // Nope, I've no idea why it's zero either. } @Test public void testDataUnused() throws Exception { JSLintResult result = lint("function f() {var foo = 2;}"); assertIssues(result.getIssues()); List<JSIdentifier> unused = result.getUnused(); assertThat(unused.size(), is(1)); assertThat(unused.get(0).getName(), is("foo")); assertThat(unused.get(0).getLine(), is(1)); } @Test public void testDataUrls() throws Exception { JSLintResult result = lint("<html><body><a href='http://example.com'>e.g.</a>" + "</body></html>"); assertIssues(result.getIssues()); List<String> urls = result.getUrls(); assertThat(urls.size(), is(1)); assertThat(urls.get(0), is("http://example.com")); } @Test public void testEmptySource() throws Exception { assertIssues(lint("").getIssues()); } @Test public void testGetEdition() throws Exception { String edition = lint.getEdition(); assertThat(edition, is(notNullValue())); String dateRe = "^\\d\\d\\d\\d-\\d\\d-\\d\\d$"; assertTrue(edition + " matches " + dateRe, edition.matches(dateRe)); } // Issue 16. @Test public void testGlobalName() throws Exception { String src = "/*global name: true */\nname = \"fred\";"; assertIssues(lint(src).getIssues()); } @Test public void testLintReader() throws Exception { Reader reader = new StringReader("var foo = 1"); List<Issue> issues = lint(reader).getIssues(); assertIssues(issues, EXPECTED_SEMICOLON); } @Test public void testMaxErr() throws Exception { lint.addOption(Option.WHITE); lint.addOption(Option.UNDEF); lint.addOption(Option.MAXERR, "2"); // Just some nasty thing I threw together. :) JSLintResult result = lint("if (foo=42) {\n println(\"bother\")\n}\n"); assertIssues(result.getIssues(), "'foo' is not defined.", "Missing space between 'foo' and '='.", "Too many errors. (25% scanned)."); } @Test public void testMaxLen() { lint.addOption(Option.MAXLEN, "1"); JSLintResult result = lint("var foo = 42;"); assertIssues(result.getIssues(), "Line too long."); } @Test public void testNoProblems() throws IOException { List<Issue> problems = lint("var foo = 1;").getIssues(); assertIssues(problems); } @Test public void testNullSource() throws Exception { List<Issue> issues = lint((String) null).getIssues(); assertIssues(issues); } @Test public void testOneProblem() throws IOException { // There is a missing semicolon here. List<Issue> problems = lint("var foo = 1").getIssues(); assertIssues(problems, EXPECTED_SEMICOLON); } /** * We're testing this so that we know arrays get passed into JavaScript * correctly. */ @Test public void testPredefOption() throws Exception { lint.addOption(Option.PREDEF, "foo,bar"); lint.addOption(Option.UNDEF); List<Issue> issues = lint("foo(bar(42));").getIssues(); assertIssues(issues); } @Test public void testReportErrorsOnly() throws Exception { String html = lint.report("var foo = 42", true); assertThat(html, containsString("<div id=errors")); assertThat(html, containsString(EXPECTED_SEMICOLON)); } @Test public void testReportFull() throws Exception { String html = lint.report("var foo = 42;"); assertThat(html, containsString("<div>")); } @Test public void testReportInResult() throws Exception { String html = lint("var foo = 42").getReport(); assertThat(html, containsString("<div id=errors")); assertThat(html, containsString(EXPECTED_SEMICOLON)); assertThat(html, containsString("<div>")); } @Test public void testResetOptions() throws Exception { String eval_js = "eval('1');"; lint.addOption(Option.EVIL); lint.resetOptions(); List<Issue> issues = lint(eval_js).getIssues(); assertIssues(issues, "eval is evil."); } @Test public void testSetOption() throws Exception { String eval_js = "eval('1');"; // should be disallowed by default. List<Issue> issues = lint(eval_js).getIssues(); assertIssues(issues, "eval is evil."); // Now should be a problem. lint.addOption(Option.EVIL); issues = lint(eval_js).getIssues(); assertIssues(issues); } @Test public void testSetOptionWithArgument() throws Exception { // This should only pass when indent=2. String js = "var x = 0;\nif (!x) {\n x = 1;\n}"; lint.addOption(Option.WHITE); lint.addOption(Option.INDENT, "2"); List<Issue> issues = lint(js).getIssues(); assertIssues(issues); } @Test public void testUnableToContinue() throws Exception { // This isn't the originally reported problem, but it tickles the // "can't continue" message. List<Issue> issues = lint("\"").getIssues(); assertIssues(issues, "Unclosed string.", "Stopping. (100% scanned)."); } }
package de.hfu.studiportal.data; import java.io.Serializable; import android.content.Context; import de.hfu.funfpunktnull.R; public class Exam implements Serializable { public enum Kind { PL, VL, P, G, KO, UNDEFINED } public enum State { AN, BE, NB, EN, UNDEFINED } public enum Note { GR, K, SA, U, VF, UNDEFINED } private static final long serialVersionUID = -4473350889205404637L; private int id; private String examNo; private String name = "-"; private String bonus = "-"; private String malus = "-"; private String ects = "-"; private String sws = "-"; private String semester = "-"; private String kind = "-"; private String tryCount = "-"; private String grade = "-"; private String state = "-"; private String comment = "-"; private String resignation = "-"; private String note = "-"; public Exam(String examNo) { this.setExamNo(examNo); } public boolean isResignated() { try { return this.getResignation().equals("1"); } catch(Exception e) { return false; } } public Kind getKindEnum() { try { return Kind.valueOf(this.getKind()); } catch(Exception e) { return Kind.UNDEFINED; } } public State getStateEnum() { try { return State.valueOf(this.getState()); } catch(Exception e) { return State.UNDEFINED; } } public String getStateName(Context c) { switch(this.getStateEnum()) { case BE: return this.getStringResource(c, R.string.text_be); case AN: return this.getStringResource(c, R.string.text_an); case NB: return this.getStringResource(c, R.string.text_nb); case EN: return this.getStringResource(c, R.string.text_en); case UNDEFINED: return "Undefined"; } return null; } private String getStringResource(Context c, int id) { return c.getResources().getString(id); } public Note getNoteEnum() { try { return Note.valueOf(this.getNote()); } catch(Exception e) { return Note.UNDEFINED; } } public String getNoteName(Context c) { switch(this.getNoteEnum()) { case GR: return this.getStringResource(c, R.string.text_gr); case U: return this.getStringResource(c, R.string.text_u); case VF: return this.getStringResource(c, R.string.text_vf); case K: return this.getStringResource(c, R.string.text_k); case SA: return this.getStringResource(c, R.string.text_sa); case UNDEFINED: return "Undefined"; } return null; } public int getId() { return id; } public String getExamNo() { return examNo; } public String getName() { return name; } public String getBonus() { return bonus; } public String getECTS() { return ects; } public String getSWS() { return sws; } public String getMalus() { return malus; } public String getSemester() { return semester; } public String getKind() { return kind; } public String getTryCount() { return tryCount; } public String getGrade() { return grade; } public String getState() { return state; } public String getComment() { return comment; } public String getResignation() { return resignation; } public String getNote() { return note; } public Exam setExamNo(String examNo) { this.examNo = examNo.replaceAll(" +", " "); this.id = examNo.hashCode(); return this; } public Exam setName(String name) { this.name = name; return this; } public Exam setBonus(String bonus) { this.bonus = bonus; return this; } public Exam setMalus(String malus) { this.malus = malus; return this; } public Exam setECTS(String ects) { this.ects = ects; return this; } public Exam setSWS(String sws) { this.sws = sws; return this; } public Exam setSemester(String semester) { this.semester = semester; this.id = (examNo + this.semester).hashCode(); return this; } public Exam setKind(String kind) { this.kind = kind; return this; } public Exam setTryCount(String tryCount) { this.tryCount = tryCount; return this; } public Exam setGrade(String grade) { this.grade = grade; return this; } public Exam setState(String state) { this.state = state; return this; } public Exam setComment(String comment) { this.comment = comment; return this; } public Exam setResignation(String resignation) { this.resignation = resignation; return this; } public Exam setNote(String note) { this.note = note; return this; } }
package cat.nyaa.nyaautils.repair; import cat.nyaa.nyaautils.NyaaUtils; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.Repairable; import org.librazy.nyaautils_lang_checker.LangKey; import org.librazy.nyaautils_lang_checker.LangKeyType; public class RepairInstance { @LangKey(type = LangKeyType.SUFFIX) public enum RepairStat { UNREPAIRABLE, UNREPAIRABLE_REPAIRED, UNREPAIRABLE_UNBREAKABLE, UNREPAIRABLE_RLE,// RepairLimitExceeded UNREPAIRABLE_LOWRECOVER, REPAIRABLE; } public RepairStat stat = RepairStat.UNREPAIRABLE; public Material repairMaterial; public int expConsumption; public int durRecovered; public int repairLimit; public RepairInstance(ItemStack item, RepairConfig config, NyaaUtils plugin) { if (item == null || item.getType() == Material.AIR) return; RepairConfig.RepairConfigItem cfg = config.getRepairConfig(item.getType()); if (cfg == null) return; if (!(item.getItemMeta() instanceof Repairable)) return; if (item.hasItemMeta() && item.getItemMeta().hasLore()) { if (!plugin.cfg.globalLoreBlacklist.canRepair(item.getItemMeta().getLore())) { stat = RepairStat.UNREPAIRABLE; return; } } stat = RepairStat.REPAIRABLE; if (item.getItemMeta().isUnbreakable()) { stat = RepairStat.UNREPAIRABLE_UNBREAKABLE; } Repairable repairableMeta = (Repairable) item.getItemMeta(); repairLimit = cfg.repairLimit; if (repairLimit > 0 && repairableMeta.getRepairCost() >= repairLimit) { stat = RepairStat.UNREPAIRABLE_RLE; } Material toolMaterial = item.getType(); repairMaterial = cfg.material; int currentDurability = item.getDurability(); if (currentDurability <= 0) { stat = RepairStat.UNREPAIRABLE_REPAIRED; } int enchLevel = 0; for (Enchantment ench : Enchantment.values()) { enchLevel += Math.max(item.getEnchantmentLevel(ench), 0); } int fullDurability = toolMaterial.getMaxDurability(); durRecovered = (int) Math.floor((double) fullDurability / ((double) cfg.fullRepairCost + (double) enchLevel * cfg.enchantCostPerLv)); expConsumption = (int) Math.floor(cfg.expCost + cfg.enchantCostPerLv * enchLevel); if (durRecovered <= 0) { stat = RepairStat.UNREPAIRABLE_LOWRECOVER; } } }