answer
stringlengths
17
10.2M
// V e r s i o n s // // <editor-fold defaultstate="collapsed" desc="hdr"> // This program is free software: you can redistribute it and/or modify it under the terms of the // </editor-fold> package org.audiveris.omr.sheet; import com.jgoodies.forms.builder.PanelBuilder; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import org.audiveris.omr.OMR; import org.audiveris.omr.WellKnowns; import org.audiveris.omr.constant.Constant; import org.audiveris.omr.constant.ConstantSet; import org.audiveris.omr.step.Step; import org.audiveris.omr.ui.field.LComboBox; import org.audiveris.omr.ui.field.LLabel; import org.audiveris.omr.ui.util.BrowserLinkListener; import org.audiveris.omr.ui.util.Panel; import org.audiveris.omr.ui.util.UIUtil; import org.audiveris.omr.util.LabeledEnum; import org.audiveris.omr.util.Version; import org.audiveris.omr.util.Version.UpgradeVersion; import org.jdesktop.application.Application; import org.jdesktop.application.ResourceMap; import org.kohsuke.github.GHOrganization; import org.kohsuke.github.GHRelease; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.awt.Color; import java.awt.Insets; import java.awt.event.ActionEvent; import java.io.IOException; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JEditorPane; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextPane; public abstract class Versions { private static final Constants constants = new Constants(); private static final Logger logger = LoggerFactory.getLogger(Versions.class); /** GitHub organization name. */ public static final String AUDIVERIS_ORGANIZATION_NAME = WellKnowns.TOOL_NAME; /** GitHub repository name. */ public static final String AUDIVERIS_REPOSITORY_NAME = WellKnowns.TOOL_ID; /** Version of current Audiveris software. */ public static final Version CURRENT_SOFTWARE = new Version(WellKnowns.TOOL_REF); /** * Version focused on better precision in inter geometry. * <ul> * <li>Migration from Point to Point2D for many inter segments (horizontal or vertical). * <li>Barline and Bracket now include staff line height. * <li>Related BarConnector and BracketConnector are shortened accordingly. * <li>Stem now uses thickness and vertical median line in lieu of top/bottom points. * <li>Ledger now uses thickness and horizontal median line. * </ul> */ public static final UpgradeVersion INTER_GEOMETRY = new UpgradeVersion("5.2.1"); /** * New handling of rest chords interleaved between beamed head chords. */ public static final UpgradeVersion INTERLEAVED_RESTS = new UpgradeVersion("5.2.3") { @Override public boolean upgradeNeeded (SheetStub stub) { if (stub.getVersion().compareTo(this) >= 0) { return false; } // Interleaved rests are built and used starting at RHYTHMS step final Step latestStep = stub.getLatestStep(); return (latestStep != null) && latestStep.compareTo(Step.RHYTHMS) >= 0; } }; // NOTA: Add here below any new version for which some upgrade is necessary. /** * Sequence of upgrade versions to check. * NOTA: This sequence must be manually updated when a new upgrade version is added above. */ public static final List<UpgradeVersion> UPGRADE_VERSIONS = Arrays.asList( INTER_GEOMETRY, INTERLEAVED_RESTS); /** Resource injection. Lazily populated on GUI. */ private static ResourceMap resources; /** Localized values of Frequency enum type. Lazily populated on GUI. */ private static LabeledEnum<Frequency>[] localeFrequencies; /** How to format dates. */ private static final DateFormat DATE_FORMAT = new SimpleDateFormat("dd-MMM-yyyy", Locale.US); // CheckResult // public enum CheckResult { COMPATIBLE, BOOK_TOO_OLD, PROGRAM_TOO_OLD; } // Frequency // /** Frequency for polling project site. */ private static enum Frequency { Always, Daily, Weekly, Monthly, Yearly, Never; } /** No instance needed for this functional class. */ private Versions () { } // check // /** * Check a provided (".omr" file) version against current software version. * * @param version version to check * @return check result */ public static CheckResult check (Version version) { if (version.major < CURRENT_SOFTWARE.major) { // Non compatible, reprocess from binary? return CheckResult.BOOK_TOO_OLD; } if (version.major > CURRENT_SOFTWARE.major) { // Non compatible, use more recent program return CheckResult.PROGRAM_TOO_OLD; } if (version.minor > CURRENT_SOFTWARE.minor) { // Non compatible, use more recent program return CheckResult.PROGRAM_TOO_OLD; } // Compatible (though book file may be upgraded automatically) return CheckResult.COMPATIBLE; } // getUpgrades // /** * Report the sequence of upgrade versions to apply on the provided sheet version. * * @param sheetVersion current version of sheet * @return sequence of upgrades to perform, perhaps empty but never null */ public static List<Version> getUpgrades (Version sheetVersion) { List<Version> list = null; for (Version v : UPGRADE_VERSIONS) { if (sheetVersion.compareTo(v) < 0) { if (list == null) { list = new ArrayList<>(); } list.add(v); } } return (list == null) ? Collections.emptyList() : list; } // getLatestRelease // /** * Retrieve the latest release available on Audiveris project site. * * @return the latest release, or null if something went wrong */ public static GHRelease getLatestRelease () { try { GitHub github = GitHub.connectAnonymously(); GHOrganization organization = github.getOrganization(AUDIVERIS_ORGANIZATION_NAME); logger.debug("{}", organization); GHRepository repository = organization.getRepository(AUDIVERIS_REPOSITORY_NAME); logger.debug("{}", repository); if (repository == null) { logger.warn("Unknown repository: {}", AUDIVERIS_REPOSITORY_NAME); return null; } GHRelease latestRelease = repository.getLatestRelease(); logger.debug("Latest release: {}", latestRelease); // Remember the date this poll was made Calendar now = new GregorianCalendar(); constants.lastReleaseCheckDate.setValue(now.getTime()); return latestRelease; } catch (IOException ex) { logger.warn("Could not connect to Audiveris project.\n{}", ex.toString()); if (ex.getCause() != null) { logger.warn("Cause: {}", ex.getCause().toString()); } return null; } } // considerPolling // /** * Check whether poll time has come and, if so, do poll the project site. */ public static void considerPolling () { if (isTimeToPoll()) { poll(false /* manual */); } else { logger.debug("Versions. Not yet time to poll"); } } // poll // /** * Poll the GitHub site for a new Audiveris release. * * @param manual true for a user manual poll, false for an automatic poll */ public static void poll (boolean manual) { final GHRelease latest = getLatestRelease(); final Version latestVersion = new Version(latest.getTagName().trim()); if (Versions.CURRENT_SOFTWARE.compareTo(latestVersion) < 0) { logger.info("A new software release is available: {}", latestVersion); if (OMR.gui == null) { logger.info("See {}", latest.getHtmlUrl()); } else { // Explicitly tell the user that check result is positive AbstractPanel panel = new PositivePanel(latest); getResources().injectComponents(panel); JOptionPane.showMessageDialog( OMR.gui.getFrame(), panel, panel.getTitle(), JOptionPane.INFORMATION_MESSAGE); } } else { logger.info("Software version is up-to-date"); if ((OMR.gui != null) && manual) { // Explicitly tell the user that check result is negative AbstractPanel panel = new NegativePanel(latest); getResources().injectComponents(panel); JOptionPane.showMessageDialog( OMR.gui.getFrame(), panel, panel.getTitle(), JOptionPane.INFORMATION_MESSAGE); } } } // getNextPollDate // /** * Report the next date when project site is to be polled. * * @return next poll date */ private static Calendar getNextPollDate () { Calendar next = new GregorianCalendar(); next.setTime(constants.lastReleaseCheckDate.getValue()); final Frequency frequency = constants.releaseCheckFrequency.getValue(); switch (frequency) { case Always: break; case Daily: next.add(Calendar.DAY_OF_MONTH, 1); break; case Weekly: next.add(Calendar.WEEK_OF_MONTH, 1); break; case Monthly: next.add(Calendar.MONTH, 1); break; case Yearly: next.add(Calendar.YEAR, 1); break; case Never: next = null; } logger.info("Versions. Poll frequency: {}, next poll on: {}", frequency, (next != null) ? DATE_FORMAT.format(next.getTime()) : null); return next; } // getLocaleFrequencies // private static LabeledEnum<Frequency>[] getLocaleFrequencies () { if (localeFrequencies == null) { localeFrequencies = LabeledEnum.values( Frequency.values(), getResources(), Frequency.class); } return localeFrequencies; } // getResources // private static ResourceMap getResources () { if (resources == null) { resources = Application.getInstance().getContext().getResourceMap(Versions.class); } return resources; } // isTimeToPoll // /** * Report whether the time has come to poll project site for a new release. * * @return true if so */ private static boolean isTimeToPoll () { Calendar now = new GregorianCalendar(); Calendar next = getNextPollDate(); if (next == null) { return false; } return now.compareTo(next) > 0; } // AbstractPanel // /** * Common part between Negative and Positive panels. */ private abstract static class AbstractPanel extends Panel { protected final String title; protected LLabel status = new LLabel(JLabel.LEFT); protected LLabel tag = new LLabel(JLabel.LEFT); protected LComboBox<LabeledEnum<Frequency>> polling = new LComboBox<>(getLocaleFrequencies()); /** The JGoodies/Form layout to be used by all subclasses. */ protected final FormLayout layout = new FormLayout(getColumnsSpec(), getRowsSpec()); /** The JGoodies/Form builder to be used by all subclasses. */ protected final PanelBuilder builder; /** Handling of entered / selected values. */ private final Action paramAction; AbstractPanel (String title, GHRelease release) { this.title = title; status.setName("status"); tag.setName("tag"); polling.setName("polling"); paramAction = new ParamAction(); builder = new PanelBuilder(layout, this); defineLayout(); tag.setText(release.getTagName()); Frequency f = constants.releaseCheckFrequency.getValue(); polling.setSelectedItem(LabeledEnum.valueOf(f, getLocaleFrequencies())); } String getTitle () { return title; } protected String getColumnsSpec () { return "right:pref, 5dlu, pref, 5dlu"; } protected String getRowsSpec () { return "pref, 3dlu,pref, 3dlu,pref"; } private void defineLayout () { final CellConstraints cst = new CellConstraints(); // Status int r = 1; builder.add(status.getLabel(), cst.xy(1, r)); builder.add(status.getField(), cst.xyw(3, r, 3)); // Tag r += 2; builder.add(tag.getLabel(), cst.xy(1, r)); builder.add(tag.getField(), cst.xyw(3, r, 3)); // Polling r += 2; builder.add(polling.getLabel(), cst.xy(1, r)); builder.add(polling.getField(), cst.xyw(3, r, 1)); polling.addActionListener(paramAction); setInsets(10, 10, 10, 10); setOpaque(true); setBackground(Color.WHITE); } private class ParamAction extends AbstractAction { /** * Method run when user presses Return/Enter in one of the parameter fields * * @param e the triggering event */ @Override public void actionPerformed (ActionEvent e) { if (polling.getField() == e.getSource()) { final Frequency newFrequency = polling.getSelectedItem().value; constants.releaseCheckFrequency.setValue(newFrequency); } } } } // Constants // private static class Constants extends ConstantSet { private final Constant.Enum<Frequency> releaseCheckFrequency = new Constant.Enum<>( Frequency.class, Frequency.Weekly, "Frequency of release check"); private final Constant.Date lastReleaseCheckDate = new Constant.Date( "1-Jan-2000", "Date when last release check was made"); } // NegativePanel // private static class NegativePanel extends AbstractPanel { NegativePanel (GHRelease release) { super(getResources().getString("Negative.title"), release); setName("PollingNegativeDialog"); tag.setVisible(false); // Status status.setText(getResources().getString("Negative.msg")); } @Override protected String getColumnsSpec () { return super.getColumnsSpec() + ", 75dlu"; } } // PositivePanel // private static class PositivePanel extends AbstractPanel { private final LLabel published = new LLabel(null, null, JLabel.LEFT); private final JLabel urlLabel = new JLabel(); private final JEditorPane urlField = new JEditorPane(); private final LLabel releaseTitle = new LLabel(JLabel.LEFT); private final JLabel contentLabel = new JLabel(); private final JTextPane contentField = new JTextPane(); PositivePanel (GHRelease release) { super(getResources().getString("Positive.title"), release); setName("PollingPositiveDialog"); // Status status.setText(getResources().getString("Positive.msg")); defineLayout(); // Published published.setName("published"); DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.LONG); published.setText(dateFormat.format(release.getPublished_at())); // Url final URL url = release.getHtmlUrl(); urlLabel.setName("urlLabel"); urlField.setName("urlField"); urlField.addHyperlinkListener(new BrowserLinkListener()); urlField.setContentType("text/html"); urlField.setEditable(false); urlField.setBackground(Color.WHITE); urlField.setText(UIUtil.htmlLink(url.toString())); // Release Title releaseTitle.setName("releaseTitle"); releaseTitle.setText(release.getName()); // Content contentLabel.setName("contentLabel"); contentField.setName("contentField"); contentField.setBackground(Color.WHITE); contentField.setEditable(false); contentField.setMargin(new Insets(5, 5, 5, 5)); contentField.setText(release.getBody().trim()); } @Override protected String getColumnsSpec () { return super.getColumnsSpec() + ", 250dlu"; } @Override protected String getRowsSpec () { return super.getRowsSpec() + ", 3dlu,pref, 3dlu,pref, 3dlu,pref, 3dlu,pref"; } private void defineLayout () { final CellConstraints cst = new CellConstraints(); // Published int r = 7; builder.add(published.getLabel(), cst.xy(1, r)); builder.add(published.getField(), cst.xyw(3, r, 3)); // Url r += 2; builder.add(urlLabel, cst.xy(1, r)); builder.add(urlField, cst.xyw(3, r, 3)); // Title r += 2; builder.add(releaseTitle.getLabel(), cst.xy(1, r)); builder.add(releaseTitle.getField(), cst.xyw(3, r, 3)); // Content r += 2; builder.add(contentLabel, cst.xy(1, r)); builder.add(contentField, cst.xyw(3, r, 3)); } } }
package base; public class TextNote extends Note { String content; public TextNote(String title) { super(title); } public TextNote(String title, String content) { this(title); this.content = content; } @Override boolean matchKeyword(String keyword) { return getTitle().toLowerCase().contains(keyword.toLowerCase()) || content.toLowerCase().contains(keyword.toLowerCase()); } }
package learn; //import gcm2sbml.parser.GCMFile; import lhpn2sbml.parser.LHPNFile; import parser.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import java.util.prefs.Preferences; import javax.swing.*; //import org.sbml.libsbml.*; import biomodelsim.*; /** * This class creates a GUI for the Learn program. It implements the * ActionListener class. This allows the GUI to perform actions when menu items * and buttons are selected. * * @author Curtis Madsen */ public class LearnLHPN extends JPanel implements ActionListener, Runnable, ItemListener { // added ItemListener SB private static final long serialVersionUID = -5806315070287184299L; private JButton save, run, viewLhpn, saveLhpn, viewLog; // the run button private JComboBox debug; // debug combo box private JTextField iteration, backgroundField, propertyG; // private JTextField windowRising, windowSize; private JComboBox numBins; private JCheckBox basicFBP; private ArrayList<ArrayList<Component>> variables; private JPanel variablesPanel; //, basicOpt, advancedOpt; private JRadioButton user, auto, range, points; private JButton suggest; private String directory, lrnFile; private JLabel numBinsLabel; private Log log; private String separator; private BioSim biosim; private String learnFile, lhpnFile; private boolean change, fail; private ArrayList<String> variablesList; private boolean firstRead, generate, execute; private ArrayList<Variable> reqdVarsL; private ArrayList<Integer> reqdVarIndices; private ArrayList<ArrayList<Double>> data; private ArrayList<String> varNames; private int[][] bins; private ArrayList<ArrayList<Double>> divisionsL; private Double[][] rates; private Double[] duration; private int dmvcCnt = 0; private int pathLength ; //= 7 ;// intFixed 25 pd 7 integrator 15; private int rateSampling ; //= -1 ; //intFixed 250; 20; //-1; private boolean placeRates = true; private LHPNFile g; private Integer numPlaces = 0; private Integer numTransitions = 0; HashMap<String, Properties> placeInfo; HashMap<String, Properties> transitionInfo; HashMap<String, Properties> cvgInfo; /* * public enum PType { RATE, DMVC, PROP, ASGN, TRACE } */ private Double minDelayVal = 10.0; private Double minRateVal = 10.0; private Double minDivisionVal = 10.0; // private String decPercent; // private boolean limitExists; private Double delayScaleFactor = 1.0; private Double varScaleFactor = 1.0; BufferedWriter out; File logFile; // Threshold parameters private double epsilon ;//= 0.1; // What is the +/- epsilon where signals are considered to be equivalent private int runLength ; //= 15; // the number of time points that a value must persist to be considered constant private double runTime ; // = 5e-12; // 10e-6 for intFixed; 5e-6 for integrator. 5e-12 for pd;// the amount of time that must pass to be considered constant when using absoluteTime private boolean absoluteTime ; // = true; // true for intfixed //false; true for pd; false for integrator// when False time points are used to determine DMVC and when true absolutime time is used to determine DMVC private double percent ; // = 0.8; // a decimal value representing the percent of the total trace that must be constant to qualify to become a DMVC var private JTextField epsilonG; private JTextField percentG; private JCheckBox absTimeG; private JTextField pathLengthG; private JTextField rateSamplingG; private JTextField runTimeG; private JTextField runLengthG; private boolean suggestIsSource = false; // private int[] numValuesL;// the number of constant values for each variable...-1 indicates that the variable isn't considered a DMVC variable // private double vaRateUpdateInterval = 1e-6;// how often the rate is added // to the continuous variable in the Verilog-A model output // Pattern lParenR = Pattern.compile("\\(+"); //SB // Pattern absoluteTimeR = Pattern.compile(".absoluteTime"); //SB // Pattern falseR = Pattern.compile("false",Pattern.CASE_INSENSITIVE); //pass the I flag to be case insensitive /** * This is the constructor for the Learn class. It initializes all the input * fields, puts them on panels, adds the panels to the frame, and then * displays the frame. */ public LearnLHPN(String directory, Log log, BioSim biosim) { if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } this.biosim = biosim; this.log = log; this.directory = directory; String[] getFilename = directory.split(separator); lrnFile = getFilename[getFilename.length - 1] + ".lrn"; // binFile = getFilename[getFilename.length - 1] + ".bins"; // newBinFile = getFilename[getFilename.length - 1] + "_NEW" + ".bins"; lhpnFile = getFilename[getFilename.length - 1] + ".lpn"; Preferences biosimrc = Preferences.userRoot(); // Sets up the encodings area JPanel radioPanel = new JPanel(new BorderLayout()); JPanel selection1 = new JPanel(); JPanel selection2 = new JPanel(); JPanel selection = new JPanel(new BorderLayout()); /* * spacing = new JRadioButton("Equal Spacing Of Bins"); data = new * JRadioButton("Equal Data Per Bins"); */ range = new JRadioButton("Minimize Range of Rates"); points = new JRadioButton("Equalize Points Per Bin"); user = new JRadioButton("Use User Generated Levels"); auto = new JRadioButton("Use Auto Generated Levels"); suggest = new JButton("Suggest Levels"); ButtonGroup select = new ButtonGroup(); select.add(auto); select.add(user); ButtonGroup select2 = new ButtonGroup(); select2.add(range); select2.add(points); // if (biosimrc.get("biosim.learn.autolevels", "").equals("Auto")) { // auto.setSelected(true); // else { // user.setSelected(true); user.addActionListener(this); range.addActionListener(this); auto.addActionListener(this); suggest.addActionListener(this); // if (biosimrc.get("biosim.learn.equaldata", "").equals("Equal Data Per // Bins")) { // data.setSelected(true); // else { range.setSelected(true); points.addActionListener(this); selection1.add(points); selection1.add(range); selection2.add(auto); selection2.add(user); selection2.add(suggest); auto.setSelected(true); selection.add(selection1, "North"); selection.add(selection2, "Center"); suggest.setEnabled(false); JPanel encodingPanel = new JPanel(new BorderLayout()); variablesPanel = new JPanel(); JPanel sP = new JPanel(); ((FlowLayout) sP.getLayout()).setAlignment(FlowLayout.LEFT); sP.add(variablesPanel); JLabel encodingsLabel = new JLabel("Variable Levels:"); JScrollPane scroll2 = new JScrollPane(); scroll2.setMinimumSize(new Dimension(260, 200)); scroll2.setPreferredSize(new Dimension(276, 132)); scroll2.setViewportView(sP); radioPanel.add(selection, "North"); radioPanel.add(encodingPanel, "Center"); encodingPanel.add(encodingsLabel, "North"); encodingPanel.add(scroll2, "Center"); // Sets up initial network and experiments text fields // JPanel initNet = new JPanel(); // JLabel initNetLabel = new JLabel("Background Knowledge Network:"); // browseInit = new JButton("Browse"); // browseInit.addActionListener(this); // initNetwork = new JTextField(39); // initNet.add(initNetLabel); // initNet.add(initNetwork); // initNet.add(browseInit); // Sets up the thresholds area JPanel thresholdPanel2 = new JPanel(new GridLayout(8, 2)); JPanel thresholdPanel1 = new JPanel(new GridLayout(4, 2)); JLabel backgroundLabel = new JLabel("Model File:"); backgroundField = new JTextField(lhpnFile); backgroundField.setEditable(false); thresholdPanel1.add(backgroundLabel); thresholdPanel1.add(backgroundField); JLabel iterationLabel = new JLabel("Iterations of Optimization Algorithm"); iteration = new JTextField("10"); thresholdPanel1.add(iterationLabel); thresholdPanel1.add(iteration); JLabel rateLabel = new JLabel("Rate calculation parameters"); JLabel epsilonLabel = new JLabel("Epsilon"); epsilonG = new JTextField("0.1"); JLabel pathLengthLabel = new JLabel("Minimum Pathlength");//("Pathlength"); pathLengthG = new JTextField("15"); JLabel rateSamplingLabel = new JLabel("Window Size");//("Rate Sampling"); rateSamplingG = new JTextField("-1"); JLabel dmvcLabel = new JLabel("DMVC determination parameters"); JLabel absTimeLabel = new JLabel("Absolute Time"); absTimeG = new JCheckBox(); absTimeG.setSelected(true); absTimeG.addItemListener(this); JLabel percentLabel = new JLabel("Percent"); percentG = new JTextField("0.8"); JLabel runTimeLabel = new JLabel("Dmvc Run Time"); runTimeG = new JTextField("5e-6"); JLabel runLengthLabel = new JLabel("DMVC Run Length"); runLengthG = new JTextField("15"); runLengthG.setEnabled(false); epsilonG.addActionListener(this); pathLengthG.addActionListener(this); rateSamplingG.addActionListener(this); percentG.addActionListener(this); runTimeG.addActionListener(this); runLengthG.addActionListener(this); JPanel newPanel = new JPanel(); JPanel jPanel1 = new JPanel(); JPanel jPanel2 = new JPanel(); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(epsilonLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 104, Short.MAX_VALUE) .addComponent(epsilonG, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(rateSamplingLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(129, 129, 129) .addComponent(rateSamplingG, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(pathLengthLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE) .addGap(68, 68, 68) .addComponent(pathLengthG, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(60, 60, 60) .addComponent(rateLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {epsilonG, pathLengthG, rateSamplingG}); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(rateLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(51, 51, 51) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(epsilonLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(epsilonG, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(rateSamplingLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(rateSamplingG, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pathLengthLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(pathLengthG, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(35, 35, 35)) ); jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {epsilonG, epsilonLabel, pathLengthG, pathLengthLabel, rateSamplingG, rateSamplingLabel}); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(140, Short.MAX_VALUE) .addComponent(dmvcLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(85, 85, 85)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(83, 83, 83) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(percentLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(percentG, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(absTimeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(31, 31, 31) .addComponent(absTimeG) .addGap(30, 30, 30)))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGap(73, 73, 73) .addComponent(runTimeLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(runTimeG, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(73, Short.MAX_VALUE) .addComponent(runLengthLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(runLengthG, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {percentG, runLengthG, runTimeG}); jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {absTimeLabel, percentLabel, runLengthLabel, runTimeLabel}); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGap(53, 53, 53) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(dmvcLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(34, 34, 34) .addComponent(absTimeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(absTimeG)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(percentLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(percentG, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(runTimeLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(runTimeG, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(runLengthLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(runLengthG, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(63, 63, 63)) ); jPanel2Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {absTimeLabel, percentG, percentLabel, runLengthG, runLengthLabel, runTimeG, runTimeLabel}); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(newPanel); newPanel.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(72, 72, 72) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 256, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(157, 157, 157)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 298, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(56, 56, 56) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); divisionsL = new ArrayList<ArrayList<Double>>(); reqdVarsL = new ArrayList<Variable>(); /* * JLabel activationLabel = new JLabel("Ratio For Activation (Ta):"); * thresholdPanel2.add(activationLabel); activation = new * JTextField(biosimrc.get("biosim.learn.ta", "")); // * activation.addActionListener(this); thresholdPanel2.add(activation); * JLabel repressionLabel = new JLabel("Ratio For Repression (Tr):"); * thresholdPanel2.add(repressionLabel); repression = new * JTextField(biosimrc.get("biosim.learn.tr", "")); // * repression.addActionListener(this); thresholdPanel2.add(repression); * JLabel influenceLevelLabel = new JLabel("Merge Influence Vectors * Delta (Tm):"); thresholdPanel2.add(influenceLevelLabel); * influenceLevel = new JTextField(biosimrc.get("biosim.learn.tm", "")); // * influenceLevel.addActionListener(this); * thresholdPanel2.add(influenceLevel); JLabel letNThroughLabel = new * JLabel("Minimum Number Of Initial Vectors (Tn): "); * thresholdPanel1.add(letNThroughLabel); letNThrough = new * JTextField(biosimrc.get("biosim.learn.tn", "")); // * letNThrough.addActionListener(this); * thresholdPanel1.add(letNThrough); JLabel maxVectorSizeLabel = new * JLabel("Maximum Influence Vector Size (Tj):"); * thresholdPanel1.add(maxVectorSizeLabel); maxVectorSize = new * JTextField(biosimrc.get("biosim.learn.tj", "")); // * maxVectorSize.addActionListener(this); * thresholdPanel1.add(maxVectorSize); JLabel parentLabel = new * JLabel("Score For Empty Influence Vector (Ti):"); * thresholdPanel1.add(parentLabel); parent = new * JTextField(biosimrc.get("biosim.learn.ti", "")); * parent.addActionListener(this); thresholdPanel1.add(parent); JLabel * relaxIPDeltaLabel = new JLabel("Relax Thresholds Delta (Tt):"); * thresholdPanel2.add(relaxIPDeltaLabel); relaxIPDelta = new * JTextField(biosimrc.get("biosim.learn.tt", "")); // * relaxIPDelta.addActionListener(this); * thresholdPanel2.add(relaxIPDelta); */ numBinsLabel = new JLabel("Number of Bins:"); String[] bins = { "2", "3", "4", "5", "6", "7", "8", "9" }; numBins = new JComboBox(bins); numBins.setSelectedItem(biosimrc.get("biosim.learn.bins", "")); numBins.addActionListener(this); numBins.setActionCommand("text"); thresholdPanel1.add(numBinsLabel); thresholdPanel1.add(numBins); JLabel propertyLabel = new JLabel("Property to be Verified"); propertyG = new JTextField(""); thresholdPanel1.add(propertyLabel); thresholdPanel1.add(propertyG); JPanel thresholdPanelHold1 = new JPanel(); thresholdPanelHold1.add(thresholdPanel1); JLabel debugLabel = new JLabel("Debug Level:"); String[] options = new String[4]; options[0] = "0"; options[1] = "1"; options[2] = "2"; options[3] = "3"; debug = new JComboBox(options); // debug.setSelectedItem(biosimrc.get("biosim.learn.debug", "")); debug.addActionListener(this); thresholdPanel2.add(debugLabel); thresholdPanel2.add(debug); // succ = new JRadioButton("Successors"); // pred = new JRadioButton("Predecessors"); // both = new JRadioButton("Both"); // if (biosimrc.get("biosim.learn.succpred", "").equals("Successors")) { // succ.setSelected(true); // else if (biosimrc.get("biosim.learn.succpred", // "").equals("Predecessors")) { // pred.setSelected(true); // else { // both.setSelected(true); // succ.addActionListener(this); // pred.addActionListener(this); // both.addActionListener(this); basicFBP = new JCheckBox("Basic FindBaseProb"); // if (biosimrc.get("biosim.learn.findbaseprob", "").equals("True")) { // basicFBP.setSelected(true); // else { basicFBP.setSelected(false); basicFBP.addActionListener(this); // ButtonGroup succOrPred = new ButtonGroup(); // succOrPred.add(succ); // succOrPred.add(pred); // succOrPred.add(both); JPanel three = new JPanel(); // three.add(succ); // three.add(pred); // three.add(both); ((FlowLayout) three.getLayout()).setAlignment(FlowLayout.LEFT); thresholdPanel2.add(three); thresholdPanel2.add(new JPanel()); thresholdPanel2.add(basicFBP); thresholdPanel2.add(new JPanel()); // JPanel thresholdPanelHold2 = new JPanel(); // thresholdPanelHold2.add(thresholdPanel2); /* * JLabel windowRisingLabel = new JLabel("Window Rising Amount:"); * windowRising = new JTextField("1"); * thresholdPanel2.add(windowRisingLabel); * thresholdPanel2.add(windowRising); JLabel windowSizeLabel = new * JLabel("Window Size:"); windowSize = new JTextField("1"); * thresholdPanel2.add(windowSizeLabel); * thresholdPanel2.add(windowSize); harshenBoundsOnTie = new * JCheckBox("Harshen Bounds On Tie"); * harshenBoundsOnTie.setSelected(true); donotInvertSortOrder = new * JCheckBox("Do Not Invert Sort Order"); * donotInvertSortOrder.setSelected(true); seedParents = new * JCheckBox("Parents Should Be Ranked By Score"); * seedParents.setSelected(true); mustNotWinMajority = new * JCheckBox("Must Not Win Majority"); * mustNotWinMajority.setSelected(true); donotTossSingleRatioParents = * new JCheckBox("Single Ratio Parents Should Be Kept"); * donotTossChangedInfluenceSingleParents = new JCheckBox( "Parents That * Change Influence Should Not Be Tossed"); * thresholdPanel2.add(harshenBoundsOnTie); * thresholdPanel2.add(donotInvertSortOrder); * thresholdPanel2.add(seedParents); * thresholdPanel2.add(mustNotWinMajority); * thresholdPanel2.add(donotTossSingleRatioParents); * thresholdPanel2.add(donotTossChangedInfluenceSingleParents); */ // load parameters // reading lrnFile twice. On the first read, only learnFile (the initial lpn) is processed // in the gap b/w these reads, reqdVarsL is created based on the learnFile Properties load = new Properties(); learnFile = ""; try { FileInputStream in = new FileInputStream(new File(directory + separator + lrnFile)); load.load(in); in.close(); if (load.containsKey("learn.file")) { String[] getProp = load.getProperty("learn.file").split( separator); learnFile = directory.substring(0, directory.length() - getFilename[getFilename.length - 1].length()) + separator + getProp[getProp.length - 1]; backgroundField.setText(getProp[getProp.length - 1]); } } catch (Exception e) { JOptionPane.showMessageDialog(biosim.frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } variablesList = new ArrayList<String>(); LHPNFile lhpn = new LHPNFile(log); // log.addText(learnFile); lhpn.load(learnFile); HashMap<String, Properties> variablesMap = lhpn.getVariables(); for (String s : variablesMap.keySet()) { variablesList.add(s); reqdVarsL.add(new Variable(s)); divisionsL.add(new ArrayList<Double>()); } // System.out.println(variablesList); try { FileInputStream in = new FileInputStream(new File(directory + separator + lrnFile)); load.load(in); in.close(); if (load.containsKey("learn.iter")) { iteration.setText(load.getProperty("learn.iter")); } if (load.containsKey("learn.bins")) { numBins.setSelectedItem(load.getProperty("learn.bins")); } if (load.containsKey("learn.prop")) { propertyG.setText(load.getProperty("learn.prop")); } if (load.containsKey("learn.equal")) { if (load.getProperty("learn.equal").equals("range")) { range.setSelected(true); } else { points.setSelected(true); } } if (load.containsKey("learn.use")) { if (load.getProperty("learn.use").equals("auto")) { auto.setSelected(true); } else if (load.getProperty("learn.use").equals("user")) { user.setSelected(true); } } if (load.containsKey("learn.epsilon")){ epsilonG.setText(load.getProperty("learn.epsilon")); } if (load.containsKey("learn.rateSampling")){ rateSamplingG.setText(load.getProperty("learn.rateSampling")); } if (load.containsKey("learn.pathLength")){ pathLengthG.setText(load.getProperty("learn.pathLength")); } if (load.containsKey("learn.percent")){ percentG.setText(load.getProperty("learn.percent")); } if (load.containsKey("learn.absTime")){ absTimeG.setSelected(Boolean.parseBoolean(load.getProperty("learn.absTime"))); } if (load.containsKey("learn.runTime")){ runTimeG.setText(load.getProperty("learn.runTime")); } if (load.containsKey("learn.runLength")){ runLengthG.setText(load.getProperty("learn.runLength")); } int j = 0; //levels(); while (load.containsKey("learn.bins"+j)){ String s = load.getProperty("learn.bins" + j); String[] savedBins = s.split("\\s"); //divisionsL.add(new ArrayList<Double>()); //variablesList.add(savedBins[0]); // ((JComboBox)(((JPanel)variablesPanel.getComponent(j+1)).getComponent(2))).setSelectedItem(savedBins[1]); for (int i = 2; i < savedBins.length ; i++){ // ((JTextField)(((JPanel)variablesPanel.getComponent(j+1)).getComponent(i+1))).setText(savedBins[i]); divisionsL.get(j).add(Double.parseDouble(savedBins[i])); } j++; } if (load.containsKey("learn.inputs")){ String s = load.getProperty("learn.inputs"); String[] savedInputs = s.split("\\s"); for (String st1 : savedInputs){ reqdVarsL.get(Integer.parseInt(st1)).setInput(true); } } } catch (Exception e) { JOptionPane.showMessageDialog(biosim.frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } try { FileWriter write = new FileWriter(new File(directory + separator + "background.g")); BufferedReader input = new BufferedReader(new FileReader(new File(learnFile))); String line = null; while ((line = input.readLine()) != null) { write.write(line + "\n"); } write.close(); input.close(); } catch (Exception e) { JOptionPane.showMessageDialog(biosim.frame(), "Unable to create background file!", "Error Writing Background", JOptionPane.ERROR_MESSAGE); } // sortSpecies(); JPanel runHolder = new JPanel(); autogen(false); if (auto.isSelected()) { auto.doClick(); } else { user.doClick(); } // Creates the run button run = new JButton("Save and Learn"); runHolder.add(run); run.addActionListener(this); run.setMnemonic(KeyEvent.VK_L); // Creates the run button save = new JButton("Save Parameters"); runHolder.add(save); save.addActionListener(this); save.setMnemonic(KeyEvent.VK_S); // Creates the view circuit button viewLhpn = new JButton("View Circuit"); runHolder.add(viewLhpn); viewLhpn.addActionListener(this); viewLhpn.setMnemonic(KeyEvent.VK_V); // Creates the save circuit button saveLhpn = new JButton("Save Circuit"); runHolder.add(saveLhpn); saveLhpn.addActionListener(this); saveLhpn.setMnemonic(KeyEvent.VK_C); // Creates the view circuit button viewLog = new JButton("View Run Log"); runHolder.add(viewLog); viewLog.addActionListener(this); viewLog.setMnemonic(KeyEvent.VK_R); if (!(new File(directory + separator + lhpnFile).exists())) { viewLhpn.setEnabled(false); saveLhpn.setEnabled(false); } if (!(new File(directory + separator + "run.log").exists())) { viewLog.setEnabled(false); } // Creates the main panel this.setLayout(new BorderLayout()); JPanel middlePanel = new JPanel(new BorderLayout()); JPanel firstTab = new JPanel(new BorderLayout()); JPanel firstTab1 = new JPanel(new BorderLayout()); JPanel secondTab = new JPanel(new BorderLayout()); // SB uncommented middlePanel.add(radioPanel, "Center"); // firstTab1.add(initNet, "North"); firstTab1.add(thresholdPanelHold1, "Center"); firstTab.add(firstTab1, "North"); JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, middlePanel, null); splitPane.setDividerSize(0); // secondTab.add(thresholdPanelHold2, "North"); // JPanel binsFileHoldPanel = new JPanel(); // binsFileHoldPanel.add(binsFilePanel); //binsFileHoldPanel.setMinimumSize(new Dimension(10000,16000)); //binsFileHoldPanel.setPreferredSize(getPreferredSize()); //secondTab.add(binsFileHoldPanel, "Center"); secondTab.add(newPanel,"Center"); firstTab.add(splitPane, "Center"); JTabbedPane tab = new JTabbedPane(); tab.addTab("Basic Options", firstTab); tab.addTab("Advanced Options", secondTab); this.add(tab, "Center"); //this.addTab("Basic", (JComponent)firstTab); //this.addTab("Advanced", (JComponent)firstTab); // this.add(runHolder, "South"); firstRead = true; // if (user.isSelected()) { // auto.doClick(); // user.doClick(); // else { // user.doClick(); // auto.doClick(); firstRead = false; change = false; } /** * This method performs different functions depending on what menu items or * buttons are selected. */ public void actionPerformed(ActionEvent e) { /* * if (e.getActionCommand().contains("box")) { int num = * Integer.parseInt(e.getActionCommand().substring(3)) - 1; if * (!((JCheckBox) this.species.get(num).get(0)).isSelected()) { * ((JComboBox) this.species.get(num).get(2)).setSelectedItem("0"); * editText(num); speciesPanel.revalidate(); speciesPanel.repaint(); for * (int i = 1; i < this.species.get(num).size(); i++) { * this.species.get(num).get(i).setEnabled(false); } } else { * this.species.get(num).get(1).setEnabled(true); if (user.isSelected()) { * for (int i = 2; i < this.species.get(num).size(); i++) { * this.species.get(num).get(i).setEnabled(true); } } } } else */ change = true; if (e.getActionCommand().contains("text")) { // int num = Integer.parseInt(e.getActionCommand().substring(4)) - if (variables != null && user.isSelected()) { // action source is any of the variables' combobox for (int i = 0; i < variables.size(); i++) { editText(i); int combox_selected = Integer.parseInt((String) ((JComboBox) variables.get(i).get(2)).getSelectedItem()); if (divisionsL.get(i).size() >= combox_selected){ for (int j = divisionsL.get(i).size() - 1; j >= (combox_selected-1) ; j divisionsL.get(i).remove(j); //combox_selected); } } } } else if ( auto.isSelected()) { // variables != null // action source is numBins on top int combox_selected = Integer.parseInt((String) numBins.getSelectedItem()); for (int i = 0; i < variablesList.size(); i++) { editText(i); //editText not required?? if (divisionsL.get(i).size() >= combox_selected){ for (int j = divisionsL.get(i).size() - 1; j >= (combox_selected-1) ; j divisionsL.get(i).remove(j); //combox_selected); } } } } variablesPanel.revalidate(); variablesPanel.repaint(); int j = 0; for (Component c : variablesPanel.getComponents()) { if (j == 0){ // recheck .. SB j++; continue; } if (reqdVarsL.get(j-1).isInput()){ //tempPorts.get(j-1)){ ((JCheckBox)((JPanel) c).getComponent(1)).setSelected(true); } j++; } biosim.setGlassPane(true); } else if (e.getSource() == numBins || e.getSource() == debug) { biosim.setGlassPane(true); } else if (e.getActionCommand().contains("dmv")) { int num = Integer.parseInt(e.getActionCommand().substring(3)) - 1; editText(num); } else if (e.getActionCommand().contains("input")) { int num = Integer.parseInt(e.getActionCommand().substring(5)); reqdVarsL.get(num).setInput(!reqdVarsL.get(num).isInput()); } else if (e.getSource() == user) { if (!firstRead) { try { for (int i = 0; i < variables.size(); i++) { if (divisionsL.get(i).size() == 0){ // This condition added later.. This ensures that when you switch from auto to user, the options of auto are written to the textboxes. SB.. rechk for (int j = 3; j < variables.get(i).size(); j++) { // changed 2 to 3 SB if (((JTextField) variables.get(i).get(j)).getText().trim().equals("")) { //divisionsL.get(i).set(j-3,null); /* if (divisionsL.get(i).size() < (j-3)){ divisionsL.get(i).set(j-3,null); } else{ divisionsL.get(i).add(null); } */ } else { //divisionsL.get(i).set(j-3,Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim())); if (divisionsL.get(i).size() <= (j-3)){ divisionsL.get(i).add(Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim())); } else{ divisionsL.get(i).set(j-3,Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim())); } } } } // write.write("\n"); } // write.close(); } catch (Exception e1) { System.out.println("exception in ActionPerformed:user"); } } numBinsLabel.setEnabled(false); numBins.setEnabled(false); suggest.setEnabled(true); // levelsBin(); variablesPanel.revalidate(); variablesPanel.repaint(); levels(); // To be added later? if the scaled divisions are not supposed to be shown after auto to user switching, then should have something like divsB4scaling which should be passed as a parameter to levels() } else if (e.getSource() == auto) { numBinsLabel.setEnabled(true); numBins.setEnabled(true); suggest.setEnabled(false); //int j = 0; // recheck .. SB for (Component c : variablesPanel.getComponents()) { for (int i = 2; i < ((JPanel) c).getComponentCount(); i++) { // changed 1 to 2 SB ((JPanel) c).getComponent(i).setEnabled(false); } /* if (j == 0){ // recheck .. SB j++; // SB continue; // SB } //SB ((JCheckBox)((JPanel) c).getComponent(1)).addActionListener(this); // SB ((JCheckBox)((JPanel) c).getComponent(1)).setActionCommand("input" + j); // SB */ } } else if (e.getSource() == suggest) { suggestIsSource = true; autogen(false); variablesPanel.revalidate(); variablesPanel.repaint(); int j = 0; for (Component c : variablesPanel.getComponents()) { if (j == 0){ // recheck .. SB j++; continue; } if (reqdVarsL.get(j-1).isInput()){ //tempPorts.get(j-1)){ ((JCheckBox)((JPanel) c).getComponent(1)).setSelected(true); } //if (tempPorts.get(j-1)){ // ((JCheckBox)((JPanel) c).getComponent(1)).setSelected(true); // SB j++; } } // if the browse initial network button is clicked // else if (e.getSource() == browseInit) { // Buttons.browse(this, new File(initNetwork.getText().trim()), // initNetwork, // JFileChooser.FILES_ONLY, "Open"); // if the run button is selected else if (e.getSource() == run) { if (!auto.isSelected()){ save(); learn(); } else{ learn(); } } else if (e.getSource() == save) { save(); } else if (e.getSource() == viewLhpn) { viewLhpn(); } else if (e.getSource() == viewLog) { viewLog(); } else if (e.getSource() == saveLhpn) { saveLhpn(); } } public void itemStateChanged(ItemEvent e) { Object source = e.getItemSelectable(); if (source == absTimeG) { absoluteTime = !absoluteTime; if (e.getStateChange() == ItemEvent.DESELECTED){ absTimeG.setSelected(false); runTimeG.setEnabled(false); runLengthG.setEnabled(true); } else{ absTimeG.setSelected(true); runTimeG.setEnabled(true); runLengthG.setEnabled(false); } } } private void autogen(boolean readfile) { try { if (!readfile) { // FileWriter write = new FileWriter(new File(directory + separator + binFile)); // FileWriter writeNew = new FileWriter(new File(directory + separator + newBinFile)); // write.write("time 0\n"); // boolean flag = false; // for (int i = 0; i < variables.size(); i++) { // if (((JCheckBox) variables.get(i).get(1)).isSelected()) { // if (!flag) { // write.write(".dmvc "); // writeNew.write(".dmvc "); // flag = true; // write.write(((JTextField) // variables.get(i).get(0)).getText().trim() + " "); // writeNew.write(((JTextField) // variables.get(i).get(0)).getText().trim() // if (flag) { // write.write("\n"); // writeNew.write("\n"); for (int i = 0; i < variables.size(); i++) { // if (!((JCheckBox) variables.get(i).get(1)).isSelected()) // if (((JTextField) variables.get(i).get(0)).getText().trim().equals("")) { // write.write("?"); // writeNew.write("?"); // } else { // write.write(((JTextField) variables.get(i).get(0)).getText().trim()); // writeNew.write(((JTextField) variables.get(i).get(0)).getText().trim()); // write.write(" " + ((JComboBox) // variables.get(i).get(1)).getSelectedItem()); for (int j = 3; j < variables.get(i).size(); j++) { // changed 2 to 3 SB if (((JTextField) variables.get(i).get(j)).getText().trim().equals("")) { // write.write(" ?"); // writeNew.write(" ?"); // divisionsL.get(i).set(j-3,null); } else { // write.write(" " + ((JTextField) variables.get(i).get(j)).getText().trim()); // writeNew.write(" " + ((JTextField) variables.get(i).get(j)).getText().trim()); // divisionsL.get(i).set(j-3,Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim())); if (divisionsL.get(i).size() <= (j-3)){ divisionsL.get(i).add(Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim())); } else{ divisionsL.get(i).set(j-3,Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim())); } } } // write.write("\n"); // writeNew.write("\n"); } // write.close(); // writeNew.close(); // Integer numThresh = // Integer.parseInt(numBins.getSelectedItem().toString()) - 1; // Thread myThread = new Thread(this); generate = true; execute = false; new Thread(this).start(); } } catch (Exception e1) { // e1.printStackTrace(); levels(); } } private void levels() { // based on the current data, create/update the variablesPanel??? /* ArrayList<String> str = null; try { Scanner f = new Scanner(new File(directory + separator + binFile)); // log.addText(directory + separator + binFile); str = new ArrayList<String>(); str.add(f.nextLine()); while (f.hasNextLine()) { str.add(f.nextLine()); } f.close(); // System.out.println("here " + str.toString()); } catch (Exception e1) { } */ if (!directory.equals("")) { if (true) { // System.out.println(str.toString()); variablesPanel.removeAll(); this.variables = new ArrayList<ArrayList<Component>>(); variablesPanel.setLayout(new GridLayout( variablesList.size() + 1, 1)); int max = 0; if (!divisionsL.isEmpty()){ for (int i = 0; i < divisionsL.size(); i++){ max = Math.max(max, divisionsL.get(i).size()+2); } } JPanel label = new JPanel(new GridLayout()); // label.add(new JLabel("Use")); label.add(new JLabel("Variables")); // label.add(new JLabel("DMV")); label.add(new JLabel("Input")); label.add(new JLabel("Number Of Bins")); for (int i = 0; i < max - 2; i++) { label.add(new JLabel("Level " + (i + 1))); } variablesPanel.add(label); int j = 0; for (String s : variablesList) { j++; JPanel sp = new JPanel(new GridLayout()); ArrayList<Component> specs = new ArrayList<Component>(); // JCheckBox check = new JCheckBox(); // check.setSelected(true); // specs.add(check); specs.add(new JTextField(s)); String[] options = { "2", "3", "4", "5", "6", "7", "8", "9" }; // String[] options = { "3", "4", "5", "6", "7", "8", "9" }; JComboBox combo = new JComboBox(options); // String[] dmvOptions = { "", "Yes", "No" }; // JComboBox dmv = new JComboBox(dmvOptions); JCheckBox dmv = new JCheckBox(); JCheckBox input = new JCheckBox(); // dmv.setSelectedIndex(0); dmv.addActionListener(this); input.addActionListener(this); dmv.setActionCommand("dmv" + j); input.setActionCommand("input" + (j-1)); // SB j-1 or j ?????? combo.setSelectedItem(numBins.getSelectedItem()); // specs.add(dmv); specs.add(input); specs.add(combo); ((JTextField) specs.get(0)).setEditable(false); // sp.add(specs.get(0)); // ((JCheckBox) specs.get(0)).addActionListener(this); // ((JCheckBox) specs.get(0)).setActionCommand("box" + j); sp.add(specs.get(0)); sp.add(specs.get(1)); sp.add(specs.get(2)); // Uncommented SB if (reqdVarsL.get(j-1).isInput()){ ((JCheckBox) specs.get(1)).setSelected(true); } else{ ((JCheckBox) specs.get(1)).setSelected(false); } ((JComboBox) specs.get(2)).addActionListener(this); // changed 1 to 2 SB ((JComboBox) specs.get(2)).setActionCommand("text" + j);// changed 1 to 2 SB this.variables.add(specs); if (!divisionsL.isEmpty()) { boolean found = false; ArrayList<Double> div = divisionsL.get(j-1); // log.addText(s + " here " + st); // String[] getString = st.split(" "); // log.addText(getString[0] + s); /*if (getString[0].trim().equals(".dmvc")) { for (int i = 1; i < getString.length; i++) { if (getString[i].equals(s)) { // log.addText(s); // ((JCheckBox) specs.get(1)).setSelected(true); } } } else if (getString[0].trim().equals(s)) {*/ found = true; // if (getString.length >= 1) { if (div.size() >= 0){ //((JComboBox) specs.get(2)).setSelectedItem("div.size()+1");// Treats div.size() as string & doesn't work.. changed 1 to 2 SB ((JComboBox) specs.get(2)).setSelectedItem(String.valueOf(div.size()+1));// changed 1 to 2 SB for (int i = 0; i < (Integer.parseInt((String) ((JComboBox) specs.get(2)).getSelectedItem()) - 1); i++) {// changed 1 to 2 SB if (div.isEmpty() || div.size() < i) { specs.add(new JTextField("")); } else { // log.addText(getString[i+1]); specs.add(new JTextField(div.get(i).toString())); } // if (((JCheckBox) specs.get(1)).isSelected()) { // log.addText("here"); // ((JTextField) specs.get(i + 2)).setEditable(false); sp.add(specs.get(i + 3)); // changed 2 to 3 SB } for (int i = Integer.parseInt((String) ((JComboBox) specs.get(2)).getSelectedItem()) - 1; i < max - 2; i++) {// changed 1 to 2 SB sp.add(new JLabel()); } } if (!found) { for (int i = 0; i < Integer.parseInt((String) ((JComboBox) specs.get(2)).getSelectedItem()) - 1; i++) {// changed 1 to 2 SB specs.add(new JTextField("")); sp.add(specs.get(i + 2));// changed 1 to 2 SB } for (int i = Integer.parseInt((String) ((JComboBox) specs.get(2)).getSelectedItem()) - 1; i < max - 2; i++) {// changed 1 to 2 SB sp.add(new JLabel()); } } } else { for (int i = 0; i < Integer.parseInt((String) ((JComboBox) specs.get(2)).getSelectedItem()) - 1; i++) {// changed 1 to 2 SB specs.add(new JTextField("")); sp.add(specs.get(i + 2));// changed 1 to 2 SB } } variablesPanel.add(sp); } } } editText(0); } private void editText(int num) { try { ArrayList<Component> specs = variables.get(num); Component[] panels = variablesPanel.getComponents(); int boxes = Integer.parseInt((String) ((JComboBox) specs.get(2)).getSelectedItem()); //changed 1 to 2 SB if ((specs.size() - 3) < boxes) { // changed 2 to 3 SB for (int i = 0; i < boxes - 1; i++) { try { specs.get(i + 3); // changed 2 to 3 SB } catch (Exception e1) { JTextField temp = new JTextField(""); ((JPanel) panels[num + 1]).add(temp); specs.add(temp); } } } else { try { if (boxes > 0) { while (true) { specs.remove(boxes + 2); // changed 1 to 2 SB ((JPanel) panels[num + 1]).remove(boxes + 2); // changed 1 to 2 SB } } else if (boxes == 0) { while (true) { specs.remove(3); // changed 2 to 3 SB ((JPanel) panels[num + 1]).remove(3); // changed 2 to 3 SB } } } catch (Exception e1) { } } int max = 0; for (int i = 0; i < this.variables.size(); i++) { max = Math.max(max, variables.get(i).size()); } if (((JPanel) panels[0]).getComponentCount() < max) { for (int i = 0; i < max - 3; i++) { //changed 2 to 3 SB try { ((JPanel) panels[0]).getComponent(i + 3); //changed 2 to 3 SB } catch (Exception e) { ((JPanel) panels[0]).add(new JLabel("Level " + (i + 1))); } } } else { try { while (true) { ((JPanel) panels[0]).remove(max); } } catch (Exception e) { } } for (int i = 1; i < panels.length; i++) { JPanel sp = (JPanel) panels[i]; for (int j = sp.getComponentCount() - 1; j >= 3; j--) {//changed 2 to 3 SB if (sp.getComponent(j) instanceof JLabel) { sp.remove(j); } } if (max > sp.getComponentCount()) { for (int j = sp.getComponentCount(); j < max; j++) { sp.add(new JLabel()); } } else { for (int j = sp.getComponentCount() - 2; j >= max; j--) {//changed 2 to 3 SB .. not sure?? sp.remove(j); } } } } catch (Exception e) { } } public void saveLhpn() { try { if (true) {// (new File(directory + separator + // "method.gcm").exists()) { String copy = JOptionPane.showInputDialog(biosim.frame(), "Enter Circuit Name:", "Save Circuit", JOptionPane.PLAIN_MESSAGE); if (copy != null) { copy = copy.trim(); } else { return; } if (!copy.equals("")) { if (copy.length() > 1) { if (!copy.substring(copy.length() - 2).equals(".lpn")) { copy += ".lpn"; } } else { copy += ".lpn"; } } biosim.saveLhpn(copy, directory + separator + lhpnFile); } else { JOptionPane.showMessageDialog(biosim.frame(), "No circuit has been generated yet.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(biosim.frame(), "Unable to save circuit.", "Error", JOptionPane.ERROR_MESSAGE); } } public void viewLhpn() { try { File work = new File(directory); if (new File(directory + separator + lhpnFile).exists()) { String dotFile = lhpnFile.replace(".lpn", ".dot"); File dot = new File(directory + separator + dotFile); dot.delete(); log.addText("Executing:\n" + "atacs -cPllodpl " + lhpnFile); Runtime exec = Runtime.getRuntime(); Process load = exec.exec("atacs -cPllodpl " + lhpnFile, null, work); load.waitFor(); if (dot.exists()) { viewLhpn.setEnabled(true); String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { command = "gnome-open " + dotFile; log.addText("gnome-open " + directory + separator + dotFile + "\n"); } else { command = "open " + dotFile; log.addText("open " + directory + separator + dotFile + "\n"); } exec.exec(command, null, work); } else { File log = new File(directory + separator + "atacs.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(biosim.frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } else { JOptionPane.showMessageDialog(biosim.frame(), "No circuit has been generated yet.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(biosim.frame(), "Unable to view circuit.", "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(biosim.frame(), scrolls, "Run Log", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(biosim.frame(), "No run log exists.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(biosim.frame(), "Unable to view run log.", "Error", JOptionPane.ERROR_MESSAGE); } } public void save() { try { Properties prop = new Properties(); FileInputStream in = new FileInputStream(new File(directory + separator + lrnFile)); prop.load(in); in.close(); prop.setProperty("learn.file", learnFile); prop.setProperty("learn.iter", this.iteration.getText().trim()); prop.setProperty("learn.bins", (String) this.numBins.getSelectedItem()); prop.setProperty("learn.prop", (String) this.propertyG.getText().trim()); if (range.isSelected()) { prop.setProperty("learn.equal", "range"); } else { prop.setProperty("learn.equal", "points"); } if (auto.isSelected()) { prop.setProperty("learn.use", "auto"); int k = 0; // added later .. so that the exact divisions are stored to file when auto is selected. & not the divisions in the textboxes int inputCount = 0; String ip = null; int numOfBins = Integer.parseInt(this.numBins.getSelectedItem().toString()); //int numThresholds = numOfBins -1; for (Component c : variablesPanel.getComponents()) { if (k == 0){ k++; continue; } String s = ((JTextField)((JPanel)c).getComponent(0)).getText().trim() + " " + numOfBins; if ((divisionsL != null) && (divisionsL.size() != 0)){ for (int i = 0; i < (numOfBins -1); i++){ if ((divisionsL.get(k-1)!= null) && (divisionsL.get(k-1).size() > i)){ s += " "; s += divisionsL.get(k-1).get(i); } } } prop.setProperty("learn.bins"+ (k-1), s); if (((JCheckBox)((JPanel)c).getComponent(1)).isSelected()){ if (inputCount == 0){ inputCount++; ip = String.valueOf(k-1);//((JTextField)((JPanel)c).getComponent(0)).getText().trim(); } else{ ip = ip + " " + String.valueOf(k-1); } } k++; } if (inputCount != 0){ prop.setProperty("learn.inputs", ip); } } else { prop.setProperty("learn.use", "user"); int k = 0; int inputCount = 0; String ip = null; for (Component c : variablesPanel.getComponents()) { if (k == 0){ k++; continue; } String s = ((JTextField)((JPanel)c).getComponent(0)).getText().trim() + " " + (String)((JComboBox)((JPanel)c).getComponent(2)).getSelectedItem(); int numOfBins = Integer.parseInt((String)((JComboBox)((JPanel)c).getComponent(2)).getSelectedItem())-1; for (int i = 0; i < numOfBins; i++){ s += " "; s += ((JTextField)(((JPanel)c).getComponent(i+3))).getText().trim(); } prop.setProperty("learn.bins"+ (k-1), s); if (((JCheckBox)((JPanel)c).getComponent(1)).isSelected()){ if (inputCount == 0){ inputCount++; ip = String.valueOf(k-1);//((JTextField)((JPanel)c).getComponent(0)).getText().trim(); } else{ ip = ip + " " + String.valueOf(k-1); } } k++; } if (inputCount != 0){ prop.setProperty("learn.inputs", ip); } } prop.setProperty("learn.epsilon", this.epsilonG.getText().trim()); prop.setProperty("learn.pathLength", this.pathLengthG.getText().trim()); prop.setProperty("learn.rateSampling", this.rateSamplingG.getText().trim()); prop.setProperty("learn.percent", this.percentG.getText().trim()); prop.setProperty("learn.absTime",String.valueOf(this.absTimeG.isSelected())); prop.setProperty("learn.runTime",this.runTimeG.getText().trim()); prop.setProperty("learn.runLength",this.runLengthG.getText().trim()); log.addText("Saving learn parameters to file:\n" + directory + separator + lrnFile + "\n"); FileOutputStream out = new FileOutputStream(new File(directory + separator + lrnFile)); prop.store(out, learnFile); out.close(); // log.addText("Creating levels file:\n" + directory + separator + // binFile + "\n"); // String command = "autogenT.py -b" + binFile + " -t" // + numBins.getSelectedItem().toString() + " -i" + // iteration.getText(); // if (range.isSelected()) { // command = command + " -cr"; // File work = new File(directory); // Runtime.getRuntime().exec(command, null, work); change = false; } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(biosim.frame(), "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } } public void reload(String newname) { // try { // Properties prop = new Properties(); // FileInputStream in = new FileInputStream(new File(directory + // separator + lrnFile)); // prop.load(in); // in.close(); // prop.setProperty("learn.file", newname); // prop.setProperty("learn.iter", this.iteration.getText().trim()); // prop.setProperty("learn.bins", (String) // this.numBins.getSelectedItem()); // if (range.isSelected()) { // prop.setProperty("learn.equal", "range"); // else { // prop.setProperty("learn.equal", "points"); // if (auto.isSelected()) { // prop.setProperty("learn.use", "auto"); // else { // prop.setProperty("learn.use", "user"); // log.addText("Saving learn parameters to file:\n" + directory + // separator + lrnFile // FileOutputStream out = new FileOutputStream(new File(directory + // separator + lrnFile)); // prop.store(out, learnFile); // out.close(); // catch (Exception e1) { // //e1.printStackTrace(); // JOptionPane.showMessageDialog(biosim.frame(), "Unable to save // parameter file!", // "Error Saving File", JOptionPane.ERROR_MESSAGE); backgroundField.setText(newname); } public void learn() { try { if (auto.isSelected()) { for (int i = 0; i < variables.size(); i++) { for (int j = 3; j < variables.get(i).size(); j++) { if (((JTextField) variables.get(i).get(j)).getText().trim().equals("")) { } else { if (divisionsL.get(i).size() <= (j-3)){ divisionsL.get(i).add(Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim())); } else{ divisionsL.get(i).set(j-3,Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim())); } } } } generate = true; } else { for (int i = 0; i < variables.size(); i++) { for (int j = 3; j < variables.get(i).size(); j++) { // changed 2 to 3 SB if (((JTextField) variables.get(i).get(j)).getText().trim().equals("")) { } else { if (divisionsL.get(i).size() <= (j-3)){ divisionsL.get(i).add(Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim())); } else{ divisionsL.get(i).set(j-3,Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim())); } } } } generate = false; } execute = true; new Thread(this).start(); } catch (Exception e) { System.out.println("Some problem"); } } public void run() { new File(directory + separator + lhpnFile).delete(); fail = false; try { File work = new File(directory); final JFrame running = new JFrame("Progress"); final JButton cancel = new JButton("Cancel"); 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); // progress.setStringPainted(true); // progress.setString(""); progress.setValue(0); text.add(label); progBar.add(progress); button.add(cancel); all.add(text, "North"); all.add(progBar, "Center"); all.add(button, "South"); 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)); FileWriter out = new FileWriter(new File(directory + separator + "run.log")); if (generate) { log.addText("Running:"); log.addText("autoGenT()"); //divisionsL = autoGenT(divisionsL); divisionsL = autoGenT(); /* String makeBin = "autogenT.py -b" + newBinFile + " -i" + iteration.getText(); if (range.isSelected()) { makeBin = makeBin + " -cr"; } log.addText(makeBin); // log.addText("Creating levels file:\n" + directory + separator // + binFile + "\n"); final Process bins = Runtime.getRuntime().exec(makeBin, null, work); cancel.setActionCommand("Cancel"); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { bins.destroy(); running.setCursor(null); running.dispose(); } }); biosim.getExitButton().setActionCommand("Exit program"); biosim.getExitButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { bins.destroy(); running.setCursor(null); running.dispose(); } }); try { String output = ""; InputStream reb = bins.getInputStream(); InputStreamReader isr = new InputStreamReader(reb); BufferedReader br = new BufferedReader(isr); int count = 0; while ((output = br.readLine()) != null) { if (output.matches("\\d+/\\d+")) { // log.addText(output); count += 500; progress.setValue(count); } else if (output.contains("ERROR")) { fail = true; } out.write(output); out.write("\n"); } br.close(); isr.close(); reb.close(); if (!execute || fail) { out.close(); } viewLog.setEnabled(true); } catch (Exception e) { } int exitValue = bins.waitFor(); if (exitValue == 143) { JOptionPane.showMessageDialog(biosim.frame(), "Learning was" + " canceled by the user.", "Canceled Learning", JOptionPane.ERROR_MESSAGE); } FileOutputStream outBins = new FileOutputStream(new File(directory + separator + binFile)); FileInputStream inBins = new FileInputStream(new File(directory + separator + newBinFile)); int read = inBins.read(); while (read != -1) { outBins.write(read); read = inBins.read(); } inBins.close(); outBins.close(); if (!execute) { levels(); } */ if (!execute) { levels(); } else{ //added later.. for saving the autogenerated thresholds into learn file after generating thresholds & before running data2lhpn save(); } } if (execute && !fail) { File lhpn = new File(lhpnFile); lhpn.delete(); // String command = "data2lhpn.py -b" + binFile + " -l" + // lhpnFile; String command = "dataToLHPN()"; log.addText("Running:\n" + command + "\n"); dataToLHPN(); // log.addText("Executing:\n" + command + " " + directory + // File work = new File(directory); // final Process run = Runtime.getRuntime().exec(command, // null,work); // cancel.setActionCommand("Cancel"); // cancel.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // run.destroy(); // running.setCursor(null); // running.dispose(); // biosim.getExitButton().setActionCommand("Exit program"); // biosim.getExitButton().addActionListener(new ActionListener() // public void actionPerformed(ActionEvent e) { // run.destroy(); // running.setCursor(null); // running.dispose(); // try { // String output = ""; // InputStream reb = run.getInputStream(); // InputStreamReader isr = new InputStreamReader(reb); // BufferedReader br = new BufferedReader(isr); // while ((output = br.readLine()) != null) { // if (output.contains("ERROR")) { // fail = true; // out.write(output); // out.write("\n"); // br.close(); // isr.close(); // reb.close(); // out.close(); // viewLog.setEnabled(true); // catch (Exception e) { // int exitValue = run.waitFor(); // if (exitValue == 143) { // JOptionPane.showMessageDialog(biosim.frame(), "Learning was" // + "canceled by the user.", "Canceled Learning", // JOptionPane.ERROR_MESSAGE); viewLog.setEnabled(true); if (new File(directory + separator + lhpnFile).exists()) { viewLhpn(); } else { fail = true; } } running.setCursor(null); running.dispose(); if (fail) { viewLog(); } } catch (Exception e1) { e1.printStackTrace(); } } public boolean hasChanged() { return change; } public boolean isComboSelected() { if (debug.isFocusOwner() || numBins.isFocusOwner()) { return true; } if (variables == null) { return false; } for (int i = 0; i < variables.size(); i++) { if (((JComboBox) variables.get(i).get(2)).isFocusOwner()) { // changed 1 to 2 SB return true; } } return false; } public boolean getViewLhpnEnabled() { return viewLhpn.isEnabled(); } public boolean getSaveLhpnEnabled() { return saveLhpn.isEnabled(); } public boolean getViewLogEnabled() { return viewLog.isEnabled(); } public void updateSpecies(String newLearnFile) { learnFile = newLearnFile; variablesList = new ArrayList<String>(); * learnFile); Set<String> ids = lhpn.getVariables().keySet(); /*try { * FileWriter write = new FileWriter( new File(directory + separator + * "background.g")); write.write("digraph G {\n"); for (String s : ids) { * variablesList.add(s); write.write("s" + s + " * [shape=ellipse,color=black,label=\"" + (s) + "\"" + "];\n"); } * write.write("}\n"); write.close(); } catch (Exception e) { * JOptionPane.showMessageDialog(biosim.frame(), "Unable to create * background file!", "Error Writing Background", * JOptionPane.ERROR_MESSAGE); } } else { */ LHPNFile lhpn = new LHPNFile(); lhpn.load(learnFile); HashMap<String, Properties> speciesMap = lhpn.getVariables(); for (String s : speciesMap.keySet()) { variablesList.add(s); } /* * try { FileWriter write = new FileWriter( new File(directory + * separator + "background.gcm")); BufferedReader input = new * BufferedReader(new FileReader(new File(learnFile))); String line = * null; while ((line = input.readLine()) != null) { write.write(line + * "\n"); } write.close(); input.close(); } catch (Exception e) { * JOptionPane.showMessageDialog(biosim.frame(), "Unable to create * background file!", "Error Writing Background", * JOptionPane.ERROR_MESSAGE); } */ sortVariables(); if (user.isSelected()) { auto.doClick(); user.doClick(); } else { user.doClick(); auto.doClick(); } levels(); } private void sortVariables() { int i, j; String index; for (i = 1; i < variablesList.size(); i++) { index = variablesList.get(i); j = i; while ((j > 0) && variablesList.get(j - 1).compareToIgnoreCase(index) > 0) { variablesList.set(j, variablesList.get(j - 1)); j = j - 1; } variablesList.set(j, index); } } public void setDirectory(String directory) { this.directory = directory; String[] getFilename = directory.split(separator); lrnFile = getFilename[getFilename.length - 1] + ".lrn"; } /** * This method generates an LHPN model from the simulation traces provided * in the learn view. The generated LHPN is stored in an object of type * lhpn2sbml.parser.LHPNfile . It is then saved in *.lpn file using the * save() method of the above class. * * Rev. 1 - Scott Little (data2lhpn.py) * Rev. 2 - Satish Batchu ( dataToLHPN() ) */ public void dataToLHPN() { try { /* Initializations added on Aug 12,2009. These initializations ensure that place,transition * numbers start from 0 everytime we click play button on LEMA though compiled only once. */ dmvcCnt = 0; numPlaces = 0; numTransitions = 0; delayScaleFactor = 1.0; varScaleFactor = 1.0; /* end Initializations */ logFile = new File(directory + separator + "tmp.log"); logFile.createNewFile(); out = new BufferedWriter(new FileWriter(logFile)); TSDParser tsd = new TSDParser(directory + separator + "run-1.tsd", biosim, false); varNames = tsd.getSpecies(); String[] learnDir = lrnFile.split("\\."); File cvgFile = new File(directory + separator + learnDir[0] + ".cvg"); cvgFile.createNewFile(); BufferedWriter coverage = new BufferedWriter(new FileWriter(cvgFile)); //FileOutputStream coverage = new FileOutputStream(cvgFile); // Check whether all the tsd files are following the same variables // & order vars = varNames.toArray(new String[varNames.size()]); int i = 1; // divisionsL = parseBinFile(); // reqdVarsL.get(1).setInput(true); // // reqdVarsL.get(4).setInput(true); // for pd // reqdVarsL.get(5).setInput(true); // for pd String failProp = ""; String enFailAnd = ""; String enFail = ""; // Graph g = new Graph(reqdVarsL.toArray(new // Variable[reqdVarsL.size()]),failProp); // Add logic to deal with failprop and related places/transitions g = new LHPNFile(); // The generated lhpn is stored in this object placeInfo = new HashMap<String, Properties>(); transitionInfo = new HashMap<String, Properties>(); cvgInfo = new HashMap<String, Properties>(); /*if (new File(directory + separator + "learn" + ".prop").exists()){ BufferedReader prop = new BufferedReader(new FileReader(directory + separator + "learn" + ".prop")); failProp = prop.readLine(); failProp = failProp.replace("\n", ""); */ if (!(propertyG.getText()).equals("")){ //BufferedReader prop = new BufferedReader(new FileReader(directory + separator + "learn" + ".prop")); failProp = propertyG.getText().trim(); failProp = "~(" + failProp + ")"; Properties p0 = new Properties(); placeInfo.put("failProp", p0); p0.setProperty("placeNum", numPlaces.toString()); p0.setProperty("type", "PROP"); p0.setProperty("initiallyMarked", "true"); g.addPlace("p" + numPlaces, true); numPlaces++; Properties p1 = new Properties(); transitionInfo.put("failProp", p1); p1.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addControlFlow("p" + placeInfo.get("failProp").getProperty("placeNum"), "t" + transitionInfo.get("failProp").getProperty("transitionNum")); numTransitions++; enFailAnd = "&~fail"; enFail = "~fail"; } epsilon = Double.parseDouble(epsilonG.getText().trim()); rateSampling = Integer.parseInt(rateSamplingG.getText().trim()); pathLength = Integer.parseInt(pathLengthG.getText().trim()); percent = Double.parseDouble(percentG.getText().trim()); runLength = Integer.parseInt(runLengthG.getText().trim()); runTime = Double.parseDouble(runTimeG.getText().trim()); while (new File(directory + separator + "run-" + i + ".tsd").exists()) { Properties cProp = new Properties(); cvgInfo.put(String.valueOf(i), cProp); cProp.setProperty("places", String.valueOf(0)); cProp.setProperty("transitions", String.valueOf(0)); cProp.setProperty("rates", String.valueOf(0)); cProp.setProperty("delays", String.valueOf(0)); tsd = new TSDParser(directory + separator + "run-" + i + ".tsd", biosim,false); data = tsd.getData(); genBinsRates(divisionsL); // changes made here.. data being used was global before. //genBinsRates("run-" + i + ".tsd", divisionsL); detectDMV(); updateGraph(bins, rates, cProp); //cProp.store(coverage, "run-" + String.valueOf(i) + ".tsd"); coverage.write("run-" + String.valueOf(i) + ".tsd\t"); coverage.write("places : " + cProp.getProperty("places")); coverage.write("\ttransitions : " + cProp.getProperty("transitions") + "\n"); i++; } coverage.close(); for (String st1 : g.getTransitionList()) { out.write("\nTransition is " + st1); String binEncoding = getPlaceInfoIndex(g.getPreset(st1)[0]); out.write(" Incoming place " + g.getPreset(st1)[0] + " Bin encoding is " + binEncoding); if (g.getPostset(st1).length != 0){ binEncoding = getPlaceInfoIndex(g.getPostset(st1)[0]); out.write(" Outgoing place " + g.getPostset(st1)[0] + " Bin encoding is " + binEncoding); } } out.write("\nTotal no of transitions : " + numTransitions); out.write("\nTotal no of places : " + numPlaces); out.write("\nPlaces are : "); for (String st3 : g.getPlaceList()) { out.write(st3 + " "); } out.write("\n"); for (String t : g.getTransitionList()) { for (String p : g.getPreset(t)) { out.write(p + " " + t + "\n"); } for (String p : g.getPostset(t)) { out.write(t + " " + p + "\n"); } } Properties initCond = new Properties(); for (Variable v : reqdVarsL) { if (v.isDmvc()) { g.addInteger(v.getName(), v.getInitValue()); } else { initCond.put("value", v.getInitValue()); initCond.put("rate", v.getInitValue()); g.addVar(v.getName(), initCond); } } g.addOutput("fail", "false"); normalize(); for (String t : g.getTransitionList()) { // Transition t = g.get_valT(sortedTrans.get(j)); if ((g.getPreset(t) != null) && (g.getPostset(t) != null) && (placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE")) && (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))) { // g.getPreset(t).length != 0 && g.getPostset(t).length != 0 ?? ArrayList<Integer> diffL = diff(getPlaceInfoIndex(g.getPreset(t)[0]), getPlaceInfoIndex(g.getPostset(t)[0])); String condStr = ""; String[] binIncoming = getPlaceInfoIndex(g.getPreset(t)[0]).split(""); String[] binOutgoing = getPlaceInfoIndex(g.getPostset(t)[0]).split(""); for (int k : diffL) { if (Integer.parseInt(binIncoming[k + 1]) < Integer.parseInt(binOutgoing[k + 1])) { double val = divisionsL.get(k).get(Integer.parseInt(binIncoming[k + 1])).doubleValue(); condStr += "(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.floor(val) + ")"; } else { double val = divisionsL.get(k).get(Integer.parseInt(binOutgoing[k + 1])).doubleValue(); condStr += "~(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.ceil(val) + ")"; } if (diffL.get(diffL.size() - 1) != k) { condStr += "&"; } // Enablings Till above.. Below one is dmvc // delay,assignment. Whenever a transition's incoming // and outgoing places differ in dmvc vars, then the // transition before this transition gets the assignment // of this dmvc value with delay equal to that of the in // b/w place's duration range. This has to be changed // after taking the causal relation input if ((reqdVarsL.get(k).isDmvc()) && (!reqdVarsL.get(k).isInput())) { // require // few more changes here.should // check for those variables that are constant over // these regions and make them as causal????? thesis String pPrev = g.getPreset(t)[0]; for (String tPrev : g.getPreset(pPrev)) { out.write("\n<" + tPrev + "= " + "{" + placeInfo.get(getPlaceInfoIndex(pPrev)).getProperty("dMin") + "," + placeInfo.get(getPlaceInfoIndex(pPrev)).getProperty("dMax") + "}" + "[" + reqdVarsL.get(k).getName() + ":=[" + placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty(reqdVarsL.get(k).getName() + "_vMin") + "," + placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty(reqdVarsL.get(k).getName() + "_vMax") + "]>"); g.changeDelay(tPrev, "[" + (int) Double.parseDouble(placeInfo.get(getPlaceInfoIndex(pPrev)).getProperty("dMin")) + "," + (int) Double.parseDouble(placeInfo.get(getPlaceInfoIndex(pPrev)).getProperty("dMax")) + "]"); g.addIntAssign(tPrev,reqdVarsL.get(k).getName(),"[" + (int) Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty(reqdVarsL.get(k).getName() + "_vMin"))) + ","+ (int) Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty(reqdVarsL.get(k).getName() + "_vMax"))) + "]"); } } } condStr += enFailAnd; g.addEnabling(t, condStr); } else if ((g.getPreset(t) != null) && (g.getPostset(t) != null) && (placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("DMVC")) && (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("DMVC"))) { // Dealing with graphs obtained from DMVC INPUT variables // NO ENABLINGS for these transitions String nextPlace = g.getPostset(t)[0]; g.changeDelay(t, "[" + (int) Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty("dMin")) + "," + (int) Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty("dMax")) + "]"); g.addIntAssign(t, placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("DMVCVariable"), "[" + (int) Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("DMVCValue"))) + "," + (int) Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("DMVCValue"))) + "]"); g.addEnabling(t, enFail); } else if ((g.getPreset(t) != null) && (placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("PROP"))){ g.addEnabling(t, failProp); g.addBoolAssign(t, "fail", "true"); // fail would be the variable name //g.addProperty(failProp); } // if ((t.getIncomingP() != null) && // (t.getIncomingP().isPropP())){ // t.setEnabling(t.getIncomingP().getProperty()); // if ((t.getIncomingP() != null) && (t.getOutgoingP() != null) // && (t.getIncomingP().isDmvcP()) && // (t.getOutgoingP().isDmvcP())){ // out.write("\n<t"+t.getTransitionNum() + "= " + "{" + // t.getMinDelay() + "," + t.getMaxDelay() + "}" + "["+ // reqdVarsL.get(t.getOutgoingP().getDmvcVar()).getName()+ ":= " // + t.getOutgoingP().getDmvcVal() + "]>"); } out.write("\n#@.rate_assignments {"); if (placeRates) { for (String st1 : g.getPlaceList()) { String p = getPlaceInfoIndex(st1); if (placeInfo.get(p).getProperty("type").equalsIgnoreCase( "RATE")) { for (String t : g.getPreset(st1)) { for (int k = 0; k < reqdVarsL.size(); k++) { if (!reqdVarsL.get(k).isDmvc()) { out.write("<" + t + "=[" + reqdVarsL.get(k).getName() + ":=[" + getMinRate(p, reqdVarsL.get(k).getName()) + "," + getMaxRate(p, reqdVarsL.get(k).getName()) + "]]>"); g.addRateAssign(t, reqdVarsL.get(k).getName(), "[" + getMinRate(p, reqdVarsL.get(k).getName()) + "," + getMaxRate(p, reqdVarsL.get(k).getName()) + "]"); } } } out.write("\n"); } } } /* * ADD TRANSITION BASED RATE GENERATION LOGIC HERE else{ * //Transition based rate generation for (String st: sortedTrans){ * Transition t = g.get_valT(st); if ((t.getOutgoingP() != null) && * (t.getIncomingP() != null)){ ArrayList<Integer> diffL = * t.getOutgoingP().diff(t.getIncomingP().getBinEncoding()); for * (int k:diffL){ if (t.getIncomingP().isRateP()){ out.write("<t" + * t.getTransitionNum() + "=[" + reqdVarsL.get(k).getName() + ":=[" + * t.minRate(k) + "," + t.maxRate(k) + "]]>\n"); } } } } } */ /* * if (g.isFailProp()){ out.write("#@.boolean_assignments {\n"); for * (String st:sortedPlaces){ Place p = g.get_valP(st); if * (p.isPropP()){ for (Transition t:p.getOutgoing()){ out.write("<t" + * t.getTransitionNum() + "=[fail:=TRUE]>"); } } } out.write("\n"); } */out.close(); g.save(directory + separator + lhpnFile); writeVHDLAMSFile(lhpnFile.split("\\.")[0]+".vhd"); } catch (IOException e) { System.out.println("LPN file couldn't be created/written "); } } /* public ArrayList<ArrayList<Double>> parseBinFile() { reqdVarsL = new ArrayList<Variable>(); ArrayList<String> linesBinFileL = null; int h = 0; //ArrayList<ArrayList<Double>> divisionsL = new ArrayList<ArrayList<Double>>(); try { Scanner f1 = new Scanner(new File(directory + separator + binFile)); // log.addText(directory + separator + binFile); linesBinFileL = new ArrayList<String>(); linesBinFileL.add(f1.nextLine()); while (f1.hasNextLine()) { linesBinFileL.add(f1.nextLine()); } out.write("Required variables and their levels are :"); for (String st : linesBinFileL) { divisionsL.add(new ArrayList<Double>()); String[] wordsBinFileL = st.split("\\s"); for (int i = 0; i < wordsBinFileL.length; i++) { if (i == 0) { reqdVarsL.add(new Variable(wordsBinFileL[i])); out.write("\n" + reqdVarsL.get(reqdVarsL.size() - 1).getName()); } else { divisionsL.get(h).add(Double.parseDouble(wordsBinFileL[i])); } } out.write(" " + divisionsL.get(h)); h++; // max = Math.max(max, wordsBinFileL.length + 1); } f1.close(); } catch (Exception e1) { } return divisionsL; } */ public void genBinsRates(ArrayList<ArrayList<Double>> divisionsL) { // genBins // public void genBinsRates(String datFile,ArrayList<ArrayList<Double>> divisionsL) { // genBins // TSDParser tsd = new TSDParser(directory + separator + datFile, biosim,false); // genBins // data = tsd.getData(); reqdVarIndices = new ArrayList<Integer>(); bins = new int[reqdVarsL.size()][data.get(0).size()]; for (int i = 0; i < reqdVarsL.size(); i++) { // System.out.println("Divisions " + divisionsL.get(i)); for (int j = 1; j < varNames.size(); j++) { if (reqdVarsL.get(i).getName().equalsIgnoreCase(varNames.get(j))) { // System.out.println(reqdVarsL.get(i) + " matched "+ // varNames.get(j) + " i = " + i + " j = " + j); reqdVarIndices.add(j); for (int k = 0; k < data.get(j).size(); k++) { // System.out.print(data.get(j).get(k) + " "); for (int l = 0; l < divisionsL.get(i).size(); l++) { if (data.get(j).get(k) <= divisionsL.get(i).get(l)) { bins[i][k] = l; break; } else { bins[i][k] = l + 1; // indices of bins not same // as that of the variable. // i here. not j; if j // wanted, then size of bins // array should be varNames // not reqdVars } } } // System.out.print(" "); } } } /* * System.out.println("array bins is :"); for (int i = 0; i < * reqdVarsL.size(); i++) { System.out.print(reqdVarsL.get(i).getName() + " * "); for (int k = 0; k < data.get(0).size(); k++) { * System.out.print(bins[i][k] + " "); } System.out.print("\n"); } */ // genRates rates = new Double[reqdVarsL.size()][data.get(0).size()]; duration = new Double[data.get(0).size()]; int mark, k; // indices of rates not same as that of the variable. if // wanted, then size of rates array should be varNames // not reqdVars if (placeRates) { if (rateSampling == -1) { // replacing inf with -1 since int mark = 0; for (int i = 0; i < data.get(0).size(); i++) { if (i < mark) { continue; } while ((mark < data.get(0).size()) && (compareBins(i, mark))) { mark++; } if ((data.get(0).get(mark - 1) != data.get(0).get(i)) && ((mark - i) >= pathLength)) { for (int j = 0; j < reqdVarsL.size(); j++) { k = reqdVarIndices.get(j); rates[j][i] = ((data.get(k).get(mark - 1) - data.get(k).get(i)) / (data.get(0).get(mark - 1) - data.get(0).get(i))); } duration[i] = data.get(0).get(mark - 1) - data.get(0).get(i); } } } else { boolean calcRate; boolean prevFail = true; int binStartPoint = 0, binEndPoint = 0; for (int i = 0; i < (data.get(0).size() - rateSampling); i++) { calcRate = true; for (int l = 0; l < rateSampling; l++) { if (!compareBins(i, i + l)) { if (!prevFail){ binEndPoint = i -2 + rateSampling; duration[binStartPoint] = data.get(0).get(binEndPoint) - data.get(0).get(binStartPoint); } calcRate = false; prevFail = true; break; } } if (calcRate && (data.get(0).get(i + rateSampling) != data.get(0).get(i))) { for (int j = 0; j < reqdVarsL.size(); j++) { k = reqdVarIndices.get(j); rates[j][i] = ((data.get(k).get(i + rateSampling) - data.get(k).get(i)) / (data.get(0).get(i + rateSampling) - data.get(0).get(i))); } if (prevFail){ binStartPoint = i; } prevFail = false; } } if (!prevFail){ // for the last genuine rate-calculating region of the trace; this may not be required if the trace is incomplete.trace data may not necessarily end at a region endpt duration[binStartPoint] = data.get(0).get(data.get(0).size()-1) - data.get(0).get(binStartPoint); } } } /* * ADD LATER: duration[i] SHOULD BE ADDED TO THE NEXT 2 IF/ELSE * BRANCHES(Transition based rate calc) ALSO */ else { // Transition based rate calculation if (rateSampling == -1) { // replacing inf with -1 since int for (int j = 0; j < reqdVarsL.size(); j++) { mark = 0; k = reqdVarIndices.get(j); for (int i = 0; i < data.get(0).size(); i++) { if (i < mark) { continue; } while ((mark < data.get(0).size()) && (bins[k][i] == bins[k][mark])) { mark++; } if ((data.get(0).get(mark - 1) != data.get(0).get(i))) { rates[j][i] = ((data.get(k).get(mark - 1) - data.get(k).get(i)) / (data.get(0).get(mark - 1) - data.get(0).get(i))); } } } } else { boolean calcRate; for (int i = 0; i < (data.get(0).size() - rateSampling); i++) { for (int j = 0; j < reqdVarsL.size(); j++) { calcRate = true; k = reqdVarIndices.get(j); for (int l = 0; l < rateSampling; l++) { if (bins[k][i] != bins[k][i + l]) { calcRate = false; break; } } if (calcRate && (data.get(0).get(i + rateSampling) != data.get(0).get(i))) { rates[j][i] = ((data.get(k).get(i + rateSampling) - data.get(k).get(i)) / (data.get(0).get(i + rateSampling) - data.get(0).get(i))); } } } } } try { for (int i = 0; i < (data.get(0).size()); i++) { for (int j = 0; j < reqdVarsL.size(); j++) { k = reqdVarIndices.get(j); out.write(data.get(k).get(i) + " ");// + bins[j][i] + " " + // rates[j][i] + " "); } for (int j = 0; j < reqdVarsL.size(); j++) { out.write(bins[j][i] + " "); } for (int j = 0; j < reqdVarsL.size(); j++) { out.write(rates[j][i] + " "); } out.write(duration[i] + " "); out.write("\n"); } } catch (IOException e) { System.out .println("Log file couldn't be opened for writing rates and bins "); } } public boolean compareBins(int j, int mark) { for (int i = 0; i < reqdVarsL.size(); i++) { if (bins[i][j] != bins[i][mark]) { return false; } else { continue; } } return true; } public void updateRateInfo(int[][] bins, Double[][] rates, Properties cvgProp) { String prevPlaceKey = ""; // "" or " " ; rechk String key = ""; // boolean addNewPlace; // ArrayList<String> ratePlaces = new ArrayList<String>(); // ratePlaces can include non-input dmv places. // boolean newRate = false; Properties p0, p1 = null; for (int i = 0; i < (data.get(0).size() - 1); i++) { if (rates[0][i] != null) { // check if indices are ok. 0???? or 1??? prevPlaceKey = key; key = ""; for (int j = 0; j < reqdVarsL.size(); j++) { key += bins[j][i]; } if (placeInfo.containsKey(key)) { p0 = placeInfo.get(key); } else { p0 = new Properties(); placeInfo.put(key, p0); p0.setProperty("placeNum", numPlaces.toString()); p0.setProperty("type", "RATE"); p0.setProperty("initiallyMarked", "false"); g.addPlace("p" + numPlaces, false); numPlaces++; cvgProp.setProperty("places", String.valueOf(Integer.parseInt(cvgProp.getProperty("places"))+1)); } if (duration[i] != null){ addDuration(p0, duration[i]); } for (int j = 0; j < reqdVarsL.size(); j++) { // rechk if (reqdVarsL.get(j).isDmvc() && reqdVarsL.get(j).isInput()) { // continue; if (reqdVarsL.get(j).isDmvc()) { // && !reqdVarsL.get(j).isInput()){ for (int k = 0; k < reqdVarsL.get(j).getRuns().getAvgVals().length; k++) { if ((reqdVarsL.get(j).getRuns().getStartPoint(k) <= i) && (reqdVarsL.get(j).getRuns().getEndPoint(k) >= i)) { addValue(p0,reqdVarsL.get(j).getName(),reqdVarsL.get(j).getRuns().getAvgVals()[k]);// data.get(reqdVarIndices.get(j)).get(i)); break; } if (reqdVarsL.get(j).getRuns().getStartPoint(k) >= i) { addValue(p0,reqdVarsL.get(j).getName(),reqdVarsL.get(j).getRuns().getAvgVals()[k]);// data.get(reqdVarIndices.get(j)).get(i)); break; } // WRONG addValue(p0, reqdVarsL.get(j).getName(), data.get(reqdVarIndices.get(j)).get(i)); } continue; } addRate(p0, reqdVarsL.get(j).getName(), rates[j][i]); // newR, oldR, dmvc etc. left } if (!prevPlaceKey.equalsIgnoreCase(key)) { if (transitionInfo.containsKey(prevPlaceKey + key)) { // instead of tuple p1 = transitionInfo.get(prevPlaceKey + key); } else if (prevPlaceKey != "") { // transition = new Transition(reqdVarsL.size(),place,prevPlace); p1 = new Properties(); transitionInfo.put(prevPlaceKey + key, p1); p1.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addControlFlow("p" + placeInfo.get(prevPlaceKey).getProperty("placeNum"), "t" + transitionInfo.get(prevPlaceKey + key).getProperty("transitionNum")); g.addControlFlow("t" + transitionInfo.get(prevPlaceKey + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); numTransitions++; cvgProp.setProperty("transitions", String.valueOf(Integer.parseInt(cvgProp.getProperty("transitions"))+1)); // transition.setCore(true); } } if (p1 != null) { for (int j = 0; j < reqdVarsL.size(); j++) { if (reqdVarsL.get(j).isDmvc() && reqdVarsL.get(j).isInput()) { continue; } if (reqdVarsL.get(j).isDmvc()) { continue; } addRate(p1, reqdVarsL.get(j).getName(), rates[j][i]); } } } } } public void updateTimeInfo(int[][] bins, Properties cvgProp) { String prevPlace = null; String currPlace = null; Properties p3 = null; //ArrayList<String> dmvcPlaceL = new ArrayList<String>(); // only dmvc inputs boolean exists; // int dmvcCnt = 0; making this global .. rechk String[] places; try { for (int i = 0; i < reqdVarsL.size(); i++) { if (reqdVarsL.get(i).isDmvc() && reqdVarsL.get(i).isInput()) { out.write(reqdVarsL.get(i).getName() + " is a dmvc input variable \n"); // dmvcCnt = 0; in case of multiple tsd files, this may be a problem. may create a new distinct place with an existing key.?? prevPlace = null; currPlace = null; p3 = null; Properties p2 = null; String k; DMVCrun runs = reqdVarsL.get(i).getRuns(); Double[] avgVals = runs.getAvgVals(); out.write("variable " + reqdVarsL.get(i).getName() + " Number of runs = " + avgVals.length + "Avg Values are : " + avgVals + "\n"); for (int j = 0; j < avgVals.length; j++) { // this gives number of runs/startpoints/endpoints exists = false; places = g.getPlaceList(); if (places.length > 1) { for (String st : places) { k = getPlaceInfoIndex(st); if (placeInfo.get(k).getProperty("type").equalsIgnoreCase("DMVC")) { if ((Math.abs(Double.parseDouble(placeInfo.get(k).getProperty("DMVCValue")) - avgVals[j]) < epsilon) && (placeInfo.get(k).getProperty("DMVCVariable").equalsIgnoreCase(reqdVarsL.get(i).getName()))) { out.write("Place with key " + k + "already exists. so adding dmvcTime to it\n"); addDmvcTime(placeInfo.get(k), reqdVarsL.get(i).getName(), calcDelay(runs.getStartPoint(j), runs.getEndPoint(j))); exists = true; prevPlace = currPlace; currPlace = getPlaceInfoIndex(st); p2 = placeInfo.get(currPlace); //next few lines commented to remove multiple dmv input places of same variable from being marked initially. /* if (j == 0) { // adding the place corresponding to the first dmv run to initial marking. placeInfo.get(k).setProperty("initiallyMarked", "true"); g.changeInitialMarking("p" + placeInfo.get(k).getProperty("placeNum"),true); } */ // break ; here? } } } } if (!exists) { prevPlace = currPlace; currPlace = "d_" + i + "_" + dmvcCnt; p2 = new Properties(); p2.setProperty("placeNum", numPlaces.toString()); p2.setProperty("type", "DMVC"); p2.setProperty("DMVCVariable", reqdVarsL.get(i).getName()); p2.setProperty("DMVCValue", avgVals[j].toString()); p2.setProperty("initiallyMarked", "false"); addDmvcTime(p2, reqdVarsL.get(i).getName(),calcDelay(runs.getStartPoint(j), runs.getEndPoint(j))); placeInfo.put("d_" + i + "_" + dmvcCnt, p2); g.addPlace("p" + numPlaces, false); if (j == 0) { // adding the place corresponding to the first dmv run to initial marking p2.setProperty("initiallyMarked", "true"); g.changeInitialMarking("p" + p2.getProperty("placeNum"), true); } numPlaces++; out.write("Created new place with key " + "d_" + i + "_" + dmvcCnt + "\n"); dmvcCnt++; //dmvcPlaceL.add(currPlace); cvgProp.setProperty("places", String.valueOf(Integer.parseInt(cvgProp.getProperty("places"))+1)); } Double d = calcDelay(runs.getStartPoint(j), runs.getEndPoint(j));// data.get(0).get(runs.getEndPoint(j)) - data.get(0).get(runs.getStartPoint(j)); // data.get(0).get(reqdVarsL.get(prevPlace.getDmvcVar()).getRuns().getEndPoint(j-1)); addDuration(p2, d); // addDelay out.write("Delay in place p"+ p2.getProperty("placeNum")+ " after updating " + d + " is ["+ p2.getProperty("dMin") + ","+ p2.getProperty("dMax") + "]\n"); if (prevPlace != null) { if (transitionInfo.containsKey(prevPlace + currPlace)) { p3 = transitionInfo.get(prevPlace + currPlace); } else { p3 = new Properties(); transitionInfo.put(prevPlace + currPlace, p3); p3.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addControlFlow("p"+ placeInfo.get(prevPlace).getProperty("placeNum"), "t"+ transitionInfo.get(prevPlace + currPlace).getProperty("transitionNum")); g.addControlFlow("t"+ transitionInfo.get(prevPlace+ currPlace).getProperty("transitionNum"),"p"+ placeInfo.get(currPlace).getProperty("placeNum")); numTransitions++; cvgProp.setProperty("transitions", String.valueOf(Integer.parseInt(cvgProp.getProperty("transitions"))+1)); } } } } else if (reqdVarsL.get(i).isDmvc()) { // non-input dmvc } } } catch (IOException e) { System.out .println("Log file couldn't be opened for writing rates and bins "); } } public void updateGraph(int[][] bins, Double[][] rates, Properties cvgProp) { updateRateInfo(bins, rates, cvgProp); updateTimeInfo(bins,cvgProp); int initMark = 0; int k; String key; for (int i = 0; i < reqdVarsL.size(); i++) { for (int j = 0; j < data.get(0).size(); j++) { if (rates[i][j] != null) { k = reqdVarIndices.get(i); // addInitValues(data.get(k).get(j), i); // k or i think ?? // addInitRates(rates[i][j], i);// k or i think?? reqdVarsL.get(i).addInitValues(data.get(k).get(j)); reqdVarsL.get(i).addInitRates(rates[i][j]); initMark = j; break; } } key = ""; for (int l = 0; l < reqdVarsL.size(); l++) { key = key + bins[l][initMark]; } if (placeInfo.get(key).getProperty("initiallyMarked").equalsIgnoreCase("false")) { placeInfo.get(key).setProperty("initiallyMarked", "true"); g.changeInitialMarking("p" + placeInfo.get(key).getProperty("placeNum"), true); } } } public void detectDMV() { int startPoint, endPoint, mark, numPoints; double absTime; for (int i = 0; i < reqdVarsL.size(); i++) { absTime = 0; mark = 0; DMVCrun runs = reqdVarsL.get(i).getRuns(); runs.clearAll(); // flush all the runs from previous dat file. for (int j = 0; j < data.get(0).size(); j++) { if (j < mark) // not reqd?? continue; if (Math.abs(data.get(reqdVarIndices.get(i)).get(j) - data.get(reqdVarIndices.get(i)).get(j + 1)) <= epsilon) { startPoint = j; runs.addValue(data.get(reqdVarIndices.get(i)).get(j)); // chk carefully reqdVarIndices.get(i) while (((j + 1) < data.get(0).size()) && (Math.abs(data.get(reqdVarIndices.get(i)).get(startPoint) - data.get(reqdVarIndices.get(i)).get(j + 1)) <= epsilon)) { runs.addValue(data.get(reqdVarIndices.get(i)).get(j + 1)); // chk carefully // reqdVarIndices.get(i) j++; } endPoint = j; if (!absoluteTime) { if (((endPoint - startPoint) + 1) >= runLength) { runs.addStartPoint(startPoint); runs.addEndPoint(endPoint); } else { runs.removeValue(); } } else { if (calcDelay(startPoint, endPoint) >= runTime) { runs.addStartPoint(startPoint); runs.addEndPoint(endPoint); absTime += calcDelay(startPoint, endPoint); } else { runs.removeValue(); } } mark = endPoint; } } try { if (!absoluteTime) { numPoints = runs.getNumPoints(); if ((numPoints / (double) data.get(0).size()) < percent) { runs.clearAll(); reqdVarsL.get(i).setDmvc(false); out.write(reqdVarsL.get(i).getName() + " is not a dmvc \n"); } else { reqdVarsL.get(i).setDmvc(true); out .write(reqdVarsL.get(i).getName() + " is a dmvc \n"); } } else { if ((absTime / (data.get(0).get(data.get(0).size() - 1) - data .get(0).get(0))) < percent) { runs.clearAll(); reqdVarsL.get(i).setDmvc(false); out.write(reqdVarsL.get(i).getName() + " is not a dmvc \n"); } else { reqdVarsL.get(i).setDmvc(true); out .write(reqdVarsL.get(i).getName() + " is a dmvc \n"); } } } catch (IOException e) { System.out .println("Log file couldn't be opened for writing rates and bins "); } } } public double calcDelay(int i, int j) { return (data.get(0).get(j) - data.get(0).get(i)); // should add some next run logic later..? } public void addValue(Properties p, String name, Double v) { // latest // change.. // above one // working fine // if this // doesn't Double vMin; Double vMax; if ((p.getProperty(name + "_vMin") == null) && (p.getProperty(name + "_vMax") == null)) { p.setProperty(name + "_vMin", v.toString()); p.setProperty(name + "_vMax", v.toString()); return; } else { vMin = Double.parseDouble(p.getProperty(name + "_vMin")); vMax = Double.parseDouble(p.getProperty(name + "_vMax")); if (v < vMin) { vMin = v; } else if (v > vMax) { vMax = v; } } p.setProperty(name + "_vMin", vMin.toString()); p.setProperty(name + "_vMax", vMax.toString()); } public void addRate(Properties p, String name, Double r) { // latest // change.. above one working fine if this doesn't Double rMin; Double rMax; if ((p.getProperty(name + "_rMin") == null) && (p.getProperty(name + "_rMax") == null)) { p.setProperty(name + "_rMin", r.toString()); p.setProperty(name + "_rMax", r.toString()); return; } else { rMin = Double.parseDouble(p.getProperty(name + "_rMin")); rMax = Double.parseDouble(p.getProperty(name + "_rMax")); if (r < rMin) { rMin = r; } else if (r > rMax) { rMax = r; } } p.setProperty(name + "_rMin", rMin.toString()); p.setProperty(name + "_rMax", rMax.toString()); } public void addDmvcTime(Properties p, String name, Double t) { if (p.getProperty("dmvcTime_" + name) == null) { p.setProperty("dmvcTime_" + name, t.toString()); } else { // Double d = Double.parseDouble(p.getProperty("dmvcTime_" + name)); // d = d + t; // p.setProperty("dmvcTime_" + name, d.toString()); p.setProperty("dmvcTime_" + name, p.getProperty("dmvcTime_" + name) + " " + t.toString()); } } public void normalize() { Double minDelay = getMinDelay(); Double maxDelay = getMaxDelay(); Double scaleFactor = 1.0; try { out.write("minimum delay is " + minDelay + " before scaling time.\n"); if ((minDelay != null) && (minDelay != 0)) { for (int i = 0; i < 18; i++) { if (scaleFactor > (minDelayVal / minDelay)) { break; } scaleFactor *= 10.0; } if ((maxDelay != null) && ((int) (maxDelay * scaleFactor) > Integer.MAX_VALUE)) { System.out.println("Delay Scaling has caused an overflow"); } out.write("minimum delay value is " + scaleFactor * minDelay + "after scaling by " + scaleFactor + "\n"); delayScaleFactor = scaleFactor; scaleDelay(); } scaleFactor = 1.0; Double minRate = getMinRate(); // minRate should return minimum by // magnitude alone?? or even by sign.. Double maxRate = getMaxRate(); out.write("minimum rate is " + minRate + " before scaling the variable.\n"); if ((minRate != null) && (minRate != 0)) { for (int i = 0; i < 14; i++) { if (scaleFactor > Math.abs(minRateVal / minRate)) { break; } scaleFactor *= 10.0; } for (int i = 0; i < 14; i++) { if ((maxRate != null) && (Math.abs((int) (maxRate * scaleFactor)) < Integer.MAX_VALUE)) { break; } scaleFactor /= 10.0; } if ((maxRate != null) && (Math.abs((int) (maxRate * scaleFactor)) > Integer.MAX_VALUE)) { System.out.println("Rate Scaling has caused an overflow"); } out.write("minimum rate is " + minRate * scaleFactor + " after scaling by " + scaleFactor + "\n"); varScaleFactor = scaleFactor; scaleVariable(scaleFactor); } Double minDivision = getMinDiv(); Double maxDivision = getMaxDiv(); out.write("minimum division is " + minDivision + " before scaling for division.\n"); scaleFactor = 1.0; if ((minDivision != null) && (minDivision != 0)) { for (int i = 0; i < 14; i++) { if (Math.abs(scaleFactor * minDivision) > minDivisionVal) { break; } scaleFactor *= 10; } if ((maxDivision != null) && (Math.abs((int) (maxDivision * scaleFactor)) > Integer.MAX_VALUE)) { System.out.println("Division Scaling has caused an overflow"); } out.write("minimum division is " + minDivision * scaleFactor + " after scaling by " + scaleFactor + "\n"); varScaleFactor *= scaleFactor; scaleVariable(scaleFactor); } } catch (IOException e) { System.out.println("LPN file couldn't be created/written "); } return; } public void scaleVariable(Double scaleFactor) { for (String place : placeInfo.keySet()) { if (place != "failProp"){ Properties p = placeInfo.get(place); if (p.getProperty("type").equals("DMVC")) { p.setProperty("DMVCValue", Double.toString(Double.parseDouble(p.getProperty("DMVCValue"))* scaleFactor)); } else { for (Variable v : reqdVarsL) { if (!v.isDmvc()) { // p.setProperty(v.getName() + // "_rMin",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName() // + "_rMin"))/delayScaleFactor))); // p.setProperty(v.getName() + // "_rMax",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName() // + "_rMax"))/delayScaleFactor))); p.setProperty(v.getName() + "_rMin", Double .toString(Double.parseDouble(p.getProperty(v.getName() + "_rMin"))* scaleFactor)); p.setProperty(v.getName() + "_rMax", Double .toString(Double.parseDouble(p.getProperty(v.getName() + "_rMax"))* scaleFactor)); } else { // p.setProperty(v.getName() + // "_rMin",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName() // + "_rMin"))/delayScaleFactor))); // p.setProperty(v.getName() + // "_rMax",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName() // + "_rMax"))/delayScaleFactor))); if (!v.isInput()) { p.setProperty(v.getName() + "_vMin", Double .toString(Double.parseDouble(p.getProperty(v.getName() + "_vMin"))* scaleFactor)); p.setProperty(v.getName() + "_vMax", Double .toString(Double.parseDouble(p.getProperty(v.getName() + "_vMax")) * scaleFactor)); } } } } } } int i = 0; for (Variable v : reqdVarsL) { v.scaleInitByVar(scaleFactor); for (int j = 0; j < divisionsL.get(i).size(); j++) { divisionsL.get(i).set(j,divisionsL.get(i).get(j) * scaleFactor); } i++; } } public void scaleDelay() { for (String place : placeInfo.keySet()) { if (place != "failProp"){ Properties p = placeInfo.get(place); if (p.getProperty("type").equals("DMVC")) { String[] times = null; String name = p.getProperty("DMVCVariable"); String s = p.getProperty("dmvcTime_" + name); String newS = null; if (s != null) { times = s.split(" "); for (int i = 0; i < times.length; i++) { if (newS == null) { // newS = Integer.toString((int)(Double.parseDouble(times[i])*delayScaleFactor)); newS = Double.toString(Double.parseDouble(times[i]) * delayScaleFactor); } else { // newS = newS + Integer.toString((int)(Double.parseDouble(times[i])*delayScaleFactor)); newS = newS + Double.toString(Double .parseDouble(times[i]) * delayScaleFactor); } } p.setProperty("dmvcTime_" + name, newS); } p.setProperty("dMin", Double.toString(Double.parseDouble(p .getProperty("dMin")) * delayScaleFactor)); p.setProperty("dMax", Double.toString(Double.parseDouble(p .getProperty("dMax")) * delayScaleFactor)); } else{ // p.setProperty("dMin",Integer.toString((int)(Double.parseDouble(p.getProperty("dMin"))*delayScaleFactor))); // p.setProperty("dMax",Integer.toString((int)(Double.parseDouble(p.getProperty("dMax"))*delayScaleFactor))); p.setProperty("dMin", Double.toString(Double.parseDouble(p .getProperty("dMin")) * delayScaleFactor)); p.setProperty("dMax", Double.toString(Double.parseDouble(p .getProperty("dMax")) * delayScaleFactor)); for (Variable v : reqdVarsL) { if (!v.isDmvc()) { // p.setProperty(v.getName() + // "_rMin",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName() // + "_rMin"))/delayScaleFactor))); // p.setProperty(v.getName() + // "_rMax",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName() // + "_rMax"))/delayScaleFactor))); p.setProperty(v.getName() + "_rMin", Double .toString(Double.parseDouble(p.getProperty(v .getName() + "_rMin")) / delayScaleFactor)); p.setProperty(v.getName() + "_rMax", Double .toString(Double.parseDouble(p.getProperty(v .getName() + "_rMax")) / delayScaleFactor)); } } } } } for (Variable v : reqdVarsL) { // if (!v.isDmvc()){ this if maynot be required.. rates do exist for dmvc ones as well.. since calculated before detectDMV v.scaleInitByDelay(delayScaleFactor); } // SEE IF RATES IN TRANSITIONS HAVE TO BE ADJUSTED HERE } public Double getMinDiv() { Double minDiv = divisionsL.get(0).get(0); for (int i = 0; i < divisionsL.size(); i++) { for (int j = 0; j < divisionsL.get(i).size(); j++) { if (divisionsL.get(i).get(j) < minDiv) { minDiv = divisionsL.get(i).get(j); } } } return minDiv; } public Double getMaxDiv() { Double maxDiv = divisionsL.get(0).get(0); for (int i = 0; i < divisionsL.size(); i++) { for (int j = 0; j < divisionsL.get(i).size(); j++) { if (divisionsL.get(i).get(j) > maxDiv) { maxDiv = divisionsL.get(i).get(j); } } } return maxDiv; } public Double getMinRate() { // minimum of entire lpn Double minRate = null; for (String place : placeInfo.keySet()) { Properties p = placeInfo.get(place); if (p.getProperty("type").equals("RATE")) { for (Variable v : reqdVarsL) { if ((minRate == null) && (p.getProperty(v.getName() + "_rMin") != null) && (Double.parseDouble(p.getProperty(v.getName() + "_rMin")) != 0.0)) { minRate = Double.parseDouble(p.getProperty(v.getName() + "_rMin")); } else if ((p.getProperty(v.getName() + "_rMin") != null) && (Double.parseDouble(p.getProperty(v.getName() + "_rMin")) < minRate) && (Double.parseDouble(p.getProperty(v.getName() + "_rMin")) != 0.0)) { minRate = Double.parseDouble(p.getProperty(v.getName() + "_rMin")); } } } } return minRate; } public Double getMaxRate() { Double maxRate = null; for (String place : placeInfo.keySet()) { Properties p = placeInfo.get(place); if (p.getProperty("type").equals("RATE")) { for (Variable v : reqdVarsL) { if ((maxRate == null) && (p.getProperty(v.getName() + "_rMax") != null) && (Double.parseDouble(p.getProperty(v.getName() + "_rMax")) != 0.0)) { maxRate = Double.parseDouble(p.getProperty(v.getName() + "_rMax")); } else if ((p.getProperty(v.getName() + "_rMax") != null) && (Double.parseDouble(p.getProperty(v.getName() + "_rMax")) > maxRate) && (Double.parseDouble(p.getProperty(v.getName() + "_rMax")) != 0.0)) { maxRate = Double.parseDouble(p.getProperty(v.getName() + "_rMax")); } } } } return maxRate; } public Double getMinDelay() { Double minDelay = null; for (String place : placeInfo.keySet()) { Properties p = placeInfo.get(place); if (p.getProperty("type").equals("DMVC")) { if ((minDelay == null) && (getMinDmvcTime(p) != null) && (getMinDmvcTime(p) != 0)) { minDelay = getMinDmvcTime(p); } else if ((getMinDmvcTime(p) != null) && (getMinDmvcTime(p) != 0) && (getMinDmvcTime(p) < minDelay)) { minDelay = getMinDmvcTime(p); } } else { if ((minDelay == null) && (p.getProperty("dMin") != null) && (Double.parseDouble(p.getProperty("dMin")) != 0)) { minDelay = Double.parseDouble(p.getProperty("dMin")); } else if ((p.getProperty("dMin") != null) && (Double.parseDouble(p.getProperty("dMin")) != 0) && (Double.parseDouble(p.getProperty("dMin")) < minDelay)) { minDelay = Double.parseDouble(p.getProperty("dMin")); } } } return minDelay; } public Double getMaxDelay() { Double maxDelay = null; for (String place : placeInfo.keySet()) { Properties p = placeInfo.get(place); if (p.getProperty("type").equals("DMVC")) { if ((maxDelay == null) && (getMaxDmvcTime(p) != null) && (getMaxDmvcTime(p) != 0)) { maxDelay = getMaxDmvcTime(p); } else if ((getMaxDmvcTime(p) != null) && (getMaxDmvcTime(p) != 0) && (getMaxDmvcTime(p) > maxDelay)) { maxDelay = getMaxDmvcTime(p); } } else { if ((maxDelay == null) && (p.getProperty("dMax") != null) && (Double.parseDouble(p.getProperty("dMax")) != 0)) { maxDelay = Double.parseDouble(p.getProperty("dMax")); } else if ((p.getProperty("dMax") != null) && (Double.parseDouble(p.getProperty("dMax")) != 0) && (Double.parseDouble(p.getProperty("dMax")) > maxDelay)) { maxDelay = Double.parseDouble(p.getProperty("dMax")); } } } return maxDelay; } public Double getMinDmvcTime(Properties p) { String[] times = null; String name = p.getProperty("DMVCVariable"); String s = p.getProperty("dmvcTime_" + name); if (s != null) { times = s.split(" "); Double min = Double.parseDouble(times[0]); for (int i = 0; i < times.length; i++) { if (Double.parseDouble(times[i]) < min) { min = Double.parseDouble(times[i]); } } return min; } else { return null; } } public Double getMaxDmvcTime(Properties p) { String[] times = null; String name = p.getProperty("DMVCVariable"); String s = p.getProperty("dmvcTime_" + name); if (s != null) { times = s.split(" "); Double max = Double.parseDouble(times[0]); for (int i = 0; i < times.length; i++) { if (Double.parseDouble(times[i]) > max) { max = Double.parseDouble(times[i]); } } return max; } else { return null; } } public void addDuration(Properties p, Double d) { Double dMin; Double dMax; // d = d*(10^6); if ((p.getProperty("dMin") == null) && (p.getProperty("dMax") == null)) { // p.setProperty("dMin", Integer.toString((int)(Math.floor(d)))); // p.setProperty("dMax", Integer.toString((int)(Math.floor(d)))); p.setProperty("dMin", d.toString()); p.setProperty("dMax", d.toString()); return; } else { dMin = Double.parseDouble(p.getProperty("dMin")); dMax = Double.parseDouble(p.getProperty("dMax")); if (d < dMin) { dMin = d; } else if (d > dMax) { dMax = d; } } p.setProperty("dMin", dMin.toString()); p.setProperty("dMax", dMax.toString()); // p.setProperty("dMin", Integer.toString((int)(Math.floor(dMin)))); // p.setProperty("dMax", Integer.toString((int)(Math.ceil(dMax)))); } public String getPlaceInfoIndex(String s) { String index = null; for (String st2 : placeInfo.keySet()) { if (("p" + placeInfo.get(st2).getProperty("placeNum")) .equalsIgnoreCase(s)) { index = st2; break; } } return index; } public ArrayList<Integer> diff(String pre_bin, String post_bin) { ArrayList<Integer> diffL = new ArrayList<Integer>(); // String p_bin[] = p.getBinEncoding(); String[] preset_encoding = pre_bin.split(""); String[] postset_encoding = post_bin.split(""); for (int j = 1; j < preset_encoding.length; j++) { // to account for "" // being created in the array if (Integer.parseInt(preset_encoding[j]) != Integer .parseInt(postset_encoding[j])) { diffL.add(j - 1);// to account for "" being created in the // array } } return (diffL); } public int getMinRate(String place, String name) { Properties p = placeInfo.get(place); return ((int) Math.floor(Double.parseDouble(p.getProperty(name + "_rMin")))); // return(rMin[i]); } public int getMaxRate(String place, String name) { Properties p = placeInfo.get(place); return ((int) Math.floor(Double.parseDouble(p.getProperty(name + "_rMax")))); // return(rMin[i]); } public Double[][] getDataExtrema(ArrayList<ArrayList<Double>> data){ Double[][] extrema = new Double[reqdVarsL.size()][2]; for (int i=0; i<reqdVarsL.size(); i++){ //Object obj = Collections.min(data.get(reqdVarIndices.get(i))); Object obj = Collections.min(data.get(i+1)); extrema[i][0] = Double.parseDouble(obj.toString()); //obj = Collections.max(data.get(reqdVarIndices.get(i))); obj = Collections.max(data.get(i+1)); extrema[i][1] = Double.parseDouble(obj.toString()); } return extrema; } //public ArrayList<ArrayList<Double>> initDivisions(Double[][] extrema, ArrayList<ArrayList<Double>> divisions ){ public ArrayList<ArrayList<Double>> initDivisions(Double[][] extrema){ int numThresholds = Integer.parseInt(numBins.getSelectedItem().toString()) - 1; double interval; ArrayList<ArrayList<Double>> divisions = new ArrayList<ArrayList<Double>>(); for (int i = 0; i < reqdVarsL.size(); i++){ divisions.add(new ArrayList<Double>()); if (!suggestIsSource){ // could use user.isselected instead of this. //numThresholds = Integer.parseInt(numBins.getSelectedItem().toString()) - 1; } else{ numThresholds = Integer.parseInt((String)((JComboBox)((JPanel)variablesPanel.getComponent(i+1)).getComponent(2)).getSelectedItem())-1; } interval = (Math.abs(extrema[i][1] - extrema[i][0]))/(numThresholds + 1); for (int j = 0; j< numThresholds; j++){ //if ((divisions.get(i).size() == 0) || (divisions.get(i).get(j) == null)){ // divisions.get(i).set(j,extrema[i][0] + interval*j); if (divisions.get(i).size() <= j){ divisions.get(i).add(extrema[i][0] + interval*(j+1)); } else{ divisions.get(i).set(j,extrema[i][0] + interval*(j+1)); } } } suggestIsSource = false; return divisions; } /** * This method generates thresholds for the variables in the learn view. * If auto generate option is selected, then the number of thresholds for * all the variables is same as the number selected in the number of bins. * If user generation option is selected & suggest button is pressed, then * the number of thresholds for each variable is equal to the number selected * in the combobox against that variable in the variablesPanel. * * Rev. 1 - Scott Little (autogenT.py) * Rev. 2 - Satish Batchu ( autogenT() ) -- Aug 12, 2009 */ //public ArrayList<ArrayList<Double>> autoGenT(ArrayList<ArrayList<Double>> divisions ){ public ArrayList<ArrayList<Double>> autoGenT(){ //int iterations = Integer.parseInt(iteration.getText()); ArrayList<ArrayList<Double>> fullData = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> singleFileData = new ArrayList<ArrayList<Double>>(); //ArrayList<String> allVars; int i = 1; while (new File(directory + separator + "run-" + i + ".tsd").exists()) { TSDParser tsd = new TSDParser(directory + separator + "run-" + i +".tsd",biosim, false); singleFileData = tsd.getData(); varNames = tsd.getSpecies(); if (i == 1){ fullData.add(new ArrayList<Double>()); } (fullData.get(0)).addAll(singleFileData.get(0)); for (int k = 0; k < reqdVarsL.size(); k++){ for (int j = 0; j< singleFileData.size(); j++){ if (reqdVarsL.get(k).getName().equalsIgnoreCase(varNames.get(j))) { if (i == 1){ fullData.add(new ArrayList<Double>()); } (fullData.get(k+1)).addAll(singleFileData.get(j)); break; } } } i++; } Double[][] extrema = getDataExtrema(fullData); //divisions = initDivisions(extrema,divisions); ArrayList<ArrayList<Double>> divisions = initDivisions(extrema); divisions = greedyOpt(divisions,fullData,extrema); return divisions; } public ArrayList<ArrayList<Double>> greedyOpt(ArrayList<ArrayList<Double>> divisions,ArrayList<ArrayList<Double>> fullData, Double[][] extrema){ ArrayList<ArrayList<Double>> newDivs = new ArrayList<ArrayList<Double>>(); // = divisions; // initialization rechk?? ArrayList<Integer> res = new ArrayList<Integer>(); int updateVar = 0; Double bestCost =0.0,newCost; Double distance = 0.0; boolean pointsSelected = false; int numMoves = 0; int iterations = Integer.parseInt(iteration.getText()); if (points.isSelected()){ pointsSelected = true; bestCost = pointDistCost(fullData, divisions,res,updateVar); } else if (range.isSelected()){ pointsSelected = false; bestCost = rateRangeCost(fullData, divisions); } while (numMoves < iterations){ for (int i = 0; i < divisions.size(); i++){ for (int j = 0; j < divisions.get(i).size(); j++){ if (j == 0){ if (divisions.get(i).get(j) != null){ distance = Math.abs(divisions.get(i).get(j) - extrema[i][0])/2; } else{// will else case ever occur??? distance = Math.abs(divisions.get(i).get(j) - divisions.get(i).get(j-1))/2; } } else{ distance = Math.abs(divisions.get(i).get(j) - divisions.get(i).get(j-1))/2; } // deep copy //newDivs = divisions; newDivs = new ArrayList<ArrayList<Double>>(); for (ArrayList<Double> o1 : divisions){ ArrayList<Double> tempDiv = new ArrayList<Double>(); for (Double o2 : o1){ tempDiv.add( o2.doubleValue()); // clone() not working here } newDivs.add(tempDiv); } newDivs.get(i).set(j,newDivs.get(i).get(j)-distance); if (pointsSelected){ newCost = pointDistCost(fullData,newDivs,res,i+1); } else{ newCost = rateRangeCost(fullData, newDivs); } numMoves++; if (numMoves % 500 == 0){ System.out.println("Iteration "+ numMoves + "/" + iterations); } if (newCost < bestCost){ bestCost = newCost; divisions = new ArrayList<ArrayList<Double>>(); for (ArrayList<Double> o1 : newDivs){ ArrayList<Double> tempDiv = new ArrayList<Double>(); for (Double o2 : o1){ tempDiv.add( o2.doubleValue()); // clone() not working here } divisions.add(tempDiv); } // divisions = newDivs; deep copy ????? } else{ if (j == (divisions.get(i).size() - 1)){ distance = Math.abs(extrema[i][1] - divisions.get(i).get(j))/2; } else{ distance = Math.abs(divisions.get(i).get(j+1) - divisions.get(i).get(j))/2; } // deep copy //newDivs = divisions; newDivs = new ArrayList<ArrayList<Double>>(); for (ArrayList<Double> o1 : divisions){ ArrayList<Double> tempDiv = new ArrayList<Double>(); for (Double o2 : o1){ tempDiv.add( o2.doubleValue()); // clone() not working here } newDivs.add(tempDiv); } newDivs.get(i).set(j,newDivs.get(i).get(j)+distance); if (pointsSelected){ newCost = pointDistCost(fullData,newDivs,res,i+1); } else{ newCost = rateRangeCost(fullData, newDivs); } numMoves++; if (numMoves % 500 == 0){ System.out.println("Iteration "+ numMoves + "/" + iterations); } if (newCost < bestCost){ bestCost = newCost; divisions = new ArrayList<ArrayList<Double>>(); for (ArrayList<Double> o1 : newDivs){ ArrayList<Double> tempDiv = new ArrayList<Double>(); for (Double o2 : o1){ tempDiv.add( o2.doubleValue()); // clone() not working here } divisions.add(tempDiv); } // divisions = newDivs; deep copy ????? } if (numMoves > iterations){ return divisions; } } } } } return divisions; } public Double rateRangeCost(ArrayList<ArrayList<Double>> fullData, ArrayList<ArrayList<Double>> divisions){ Double total = 0.0; Double[] minMaxR = {null,null}; //genBinsRates(datFile, divisions); Double[][] rates = genBinsRatesForAutogen(fullData, divisions); for (int i = 0; i < divisions.size(); i++){ minMaxR = getMinMaxRates(rates[i]); total += Math.abs(minMaxR[1] - minMaxR[0]); } return total; } public Double pointDistCost(ArrayList<ArrayList<Double>> fullData,ArrayList<ArrayList<Double>> divisions, ArrayList<Integer> res, int updateVar ){ Double total = 0.0; int pts = 0; if (updateVar == 0){ for (int i = 0; i < divisions.size() + 1; i++){ res.add(0); } for (int i = 0; i < divisions.size(); i++){ pts = pointDistCostVar(fullData.get(i+1),divisions.get(i)); total += pts; res.set(i,pts); } } else if (updateVar > 0){ // res is kind of being passed by reference. it gets altered outside too. res.set(updateVar-1, pointDistCostVar(fullData.get(updateVar),divisions.get(updateVar-1))); for (Integer i : res){ total += i; } /*for (int i = 0; i < res.size(); i++){ if ((updateVar - 1) != i){ total += res.get(i); } else{ total += pointDistCostVar(fullData.get(updateVar),divisions.get(updateVar-1)) } } */ } else{ for (int i = 0; i < divisions.size(); i++){ total += pointDistCostVar(fullData.get(i+1),divisions.get(i)); } } return total; } public int pointDistCostVar(ArrayList<Double> dat,ArrayList<Double> div){ int optPointsPerBin = dat.size()/(div.size()+1); boolean top = false; ArrayList<Integer> pointsPerBin = new ArrayList<Integer>(); for (int i =0; i < (div.size() +1); i++){ pointsPerBin.add(0); } for (int i = 0; i <dat.size() ; i++){ top = true; for (int j =0; j < div.size(); j++){ if (dat.get(i) <= div.get(j)){ pointsPerBin.set(j, pointsPerBin.get(j)+1); top = false; break; } } if (top){ pointsPerBin.set(div.size(), pointsPerBin.get(div.size()) + 1); } } int score = 0; for (Integer pts : pointsPerBin){ score += Math.abs(pts - optPointsPerBin ); } return score; } public Double[] getMinMaxRates(Double[] rateList){ ArrayList<Double> cmpL = new ArrayList<Double>(); Double[] minMax = {null,null};// new Double[2]; for (Double r : rateList){ if (r != null){ cmpL.add(r); } } if (cmpL.size() > 0){ Object obj = Collections.min(cmpL); minMax[0] = Double.parseDouble(obj.toString()); obj = Collections.max(cmpL); minMax[1] = Double.parseDouble(obj.toString()); } return minMax; } public Double[][] genBinsRatesForAutogen(ArrayList<ArrayList<Double>> data,ArrayList<ArrayList<Double>> divisionsL) { // genBins // public void genBinsRates(String datFile,ArrayList<ArrayList<Double>> divisionsL) { // genBins // TSDParser tsd = new TSDParser(directory + separator + datFile, biosim,false); // genBins // data = tsd.getData(); rateSampling = Integer.parseInt(rateSamplingG.getText().trim()); pathLength = Integer.parseInt(pathLengthG.getText().trim()); // ArrayList<Integer> reqdVarIndices = new ArrayList<Integer>(); int[][] bins = new int[reqdVarsL.size()][data.get(0).size()]; for (int i = 0; i < reqdVarsL.size(); i++) { // for (int j = 1; j < varNames.size(); j++) { // if (reqdVarsL.get(i).getName().equalsIgnoreCase(varNames.get(j))) { // System.out.println(reqdVarsL.get(i) + " matched "+ // varNames.get(j) + " i = " + i + " j = " + j); // reqdVarIndices.add(j); for (int k = 0; k < data.get(i+1).size(); k++) { for (int l = 0; l < divisionsL.get(i).size(); l++) { if (data.get(i+1).get(k) <= divisionsL.get(i).get(l)) { bins[i][k] = l; break; } else { bins[i][k] = l + 1; // indices of bins not same as that of the variable. i here. not j; if j // wanted, then size of bins array should be varNames not reqdVars } } } } /* * System.out.println("array bins is :"); for (int i = 0; i < * reqdVarsL.size(); i++) { System.out.print(reqdVarsL.get(i).getName() + " * "); for (int k = 0; k < data.get(0).size(); k++) { * System.out.print(bins[i][k] + " "); } System.out.print("\n"); } */ // genRates Double[][] rates = new Double[reqdVarsL.size()][data.get(0).size()]; Double[] duration = new Double[data.get(0).size()]; int mark ; //, k; // indices of rates not same as that of the variable. if // wanted, then size of rates array should be varNames not reqdVars if (placeRates) { if (rateSampling == -1) { // replacing inf with -1 since int mark = 0; for (int i = 0; i < data.get(0).size(); i++) { if (i < mark) { continue; } while ((mark < data.get(0).size()) && (compareBins(i, mark,bins))) { mark++; } if ((data.get(0).get(mark - 1) != data.get(0).get(i)) && ((mark - i) >= pathLength)) { for (int j = 0; j < reqdVarsL.size(); j++) { //k = reqdVarIndices.get(j); rates[j][i] = ((data.get(j+1).get(mark - 1) - data.get(j+1).get(i)) / (data.get(0).get(mark - 1) - data.get(0).get(i))); } duration[i] = data.get(0).get(mark - 1) - data.get(0).get(i); } } } else { boolean calcRate; boolean prevFail = true; int binStartPoint = 0, binEndPoint = 0; for (int i = 0; i < (data.get(0).size() - rateSampling); i++) { calcRate = true; for (int l = 0; l < rateSampling; l++) { if (!compareBins(i, i + l,bins)) { if (!prevFail){ binEndPoint = i -2 + rateSampling; duration[binStartPoint] = data.get(0).get(binEndPoint) - data.get(0).get(binStartPoint); } calcRate = false; prevFail = true; break; } } if (calcRate && (data.get(0).get(i + rateSampling) != data.get(0).get(i))) { for (int j = 0; j < reqdVarsL.size(); j++) { //k = reqdVarIndices.get(j); rates[j][i] = ((data.get(j+1).get(i + rateSampling) - data.get(j+1).get(i)) / (data.get(0).get(i + rateSampling) - data.get(0).get(i))); } if (prevFail){ binStartPoint = i; } prevFail = false; } } if (!prevFail){ // for the last genuine rate-calculating region of the trace; this may not be required if the trace is incomplete.trace data may not necessarily end at a region endpt duration[binStartPoint] = data.get(0).get(data.get(0).size()-1) - data.get(0).get(binStartPoint); } } } /* * ADD LATER: duration[i] SHOULD BE ADDED TO THE NEXT 2 IF/ELSE * BRANCHES(Transition based rate calc) ALSO */ else { // Transition based rate calculation if (rateSampling == -1) { // replacing inf with -1 since int for (int j = 0; j < reqdVarsL.size(); j++) { mark = 0; //k = reqdVarIndices.get(j); for (int i = 0; i < data.get(0).size(); i++) { if (i < mark) { continue; } while ((mark < data.get(0).size()) && (bins[j][i] == bins[j][mark])) { mark++; } if ((data.get(0).get(mark - 1) != data.get(0).get(i))) { rates[j][i] = ((data.get(j+1).get(mark - 1) - data.get(j+1).get(i)) / (data.get(0).get(mark - 1) - data.get(0).get(i))); } } } } else { boolean calcRate; for (int i = 0; i < (data.get(0).size() - rateSampling); i++) { for (int j = 0; j < reqdVarsL.size(); j++) { calcRate = true; //k = reqdVarIndices.get(j); for (int l = 0; l < rateSampling; l++) { if (bins[j][i] != bins[j][i + l]) { calcRate = false; break; } } if (calcRate && (data.get(0).get(i + rateSampling) != data.get(0).get(i))) { rates[j][i] = ((data.get(j+1).get(i + rateSampling) - data.get(j+1).get(i)) / (data.get(0).get(i + rateSampling) - data.get(0).get(i))); } } } } } try { logFile = new File(directory + separator + "tmp.log"); logFile.createNewFile(); out = new BufferedWriter(new FileWriter(logFile)); for (int i = 0; i < (data.get(0).size()); i++) { for (int j = 0; j < reqdVarsL.size(); j++) { //k = reqdVarIndices.get(j); out.write(data.get(j+1).get(i) + " ");// + bins[j][i] + " " + // rates[j][i] + " "); } for (int j = 0; j < reqdVarsL.size(); j++) { out.write(bins[j][i] + " "); } for (int j = 0; j < reqdVarsL.size(); j++) { out.write(rates[j][i] + " "); } out.write(duration[i] + " "); out.write("\n"); } out.close(); } catch (IOException e) { System.out.println("Log file couldn't be opened for writing rates and bins "); } return rates; } public boolean compareBins(int j, int mark,int[][] bins) { for (int i = 0; i < reqdVarsL.size(); i++) { if (bins[i][j] != bins[i][mark]) { return false; } else { continue; } } return true; } public void writeVHDLAMSFile(String vhdFile){ try{ ArrayList<String> ratePlaces = new ArrayList<String>(); ArrayList<String> dmvcPlaces = new ArrayList<String>(); File VHDLFile = new File(directory + separator + vhdFile); VHDLFile.createNewFile(); BufferedWriter vhdlAms = new BufferedWriter(new FileWriter(VHDLFile)); vhdlAms.write("library IEEE;\n"); vhdlAms.write("use IEEE.std_logic_1164.all;\n"); vhdlAms.write("use work.handshake.all;\n"); vhdlAms.write("use work.nondeterminism.all;\n\n"); vhdlAms.write("entity amsDesign is\n"); vhdlAms.write("end amsDesign;\n\n"); vhdlAms.write("architecture "+vhdFile.split("\\.")[0]+" of amsDesign is\n"); for (Variable v : reqdVarsL){ vhdlAms.write("\tquantity "+v.getName()+":real;\n"); } vhdlAms.write("\nbegin\n"); for (Variable v : reqdVarsL){ // taking the lower value from the initial value range. Ok? vhdlAms.write("\tbreak "+v.getName()+" => "+((((v.getInitValue()).split("\\,"))[0]).split("\\["))[1]+".0;\n"); } vhdlAms.write("\n"); for (Variable v : reqdVarsL){ if (v.isDmvc()){ vhdlAms.write("\t"+v.getName()+"'dot == 0.0;\n"); } } vhdlAms.write("\n"); for (String st1 : g.getPlaceList()){ String p = getPlaceInfoIndex(st1); if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) { ratePlaces.add(st1); // w.r.t g here } if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("DMVC")) { dmvcPlaces.add(p); // w.r.t placeInfo here } } /*for (String st:dmvcPlaces){ System.out.println("p" + placeInfo.get(st).getProperty("placeNum") + "," +placeInfo.get(st).getProperty("DMVCVariable")); }*/ /* Collections.sort(dmvcPlaces,new Comparator<String>(){ public int compare(String a, String b){ String v1 = placeInfo.get(a).getProperty("DMVCVariable"); String v2 = placeInfo.get(b).getProperty("DMVCVariable"); if (reqdVarsL.indexOf(v1) < reqdVarsL.indexOf(v2)){ return -1; } else if (reqdVarsL.indexOf(v1) == reqdVarsL.indexOf(v2)){ return 0; } else{ return 1; } } });*/ Collections.sort(dmvcPlaces,new Comparator<String>(){ public int compare(String a, String b){ if (Integer.parseInt(a.split("_")[1]) < Integer.parseInt(b.split("_")[1])){ return -1; } else if (Integer.parseInt(a.split("_")[1]) == Integer.parseInt(b.split("_")[1])){ return 0; } else{ return 1; } } }); Collections.sort(ratePlaces,new Comparator<String>(){ public int compare(String a, String b){ String v1 = placeInfo.get(getPlaceInfoIndex(a)).getProperty("placeNum"); String v2 = placeInfo.get(getPlaceInfoIndex(b)).getProperty("placeNum"); if (Integer.parseInt(v1) < Integer.parseInt(v2)){ return -1; } else if (Integer.parseInt(v1) == Integer.parseInt(v2)){ return 0; } else{ return 1; } } }); // sending the initial place to the end of the list. since if statements begin with preset of each place ratePlaces.add(ratePlaces.get(0)); ratePlaces.remove(0); /*System.out.println("after sorting:"); for (String st:dmvcPlaces){ System.out.println("p" + placeInfo.get(st).getProperty("placeNum") + "," +placeInfo.get(st).getProperty("DMVCVariable")); }*/ ArrayList<ArrayList<String>> dmvcVarPlaces = new ArrayList<ArrayList<String>>(); for (Variable v: reqdVarsL){ dmvcVarPlaces.add(new ArrayList<String>()); } for (String st:dmvcPlaces){ dmvcVarPlaces.get(Integer.parseInt(st.split("_")[1])).add(st); } ArrayList<ArrayList<String>> ifL = new ArrayList<ArrayList<String>>(); ArrayList<ArrayList<String>> ifRateL = new ArrayList<ArrayList<String>>(); for (Variable v: reqdVarsL){ ifL.add(new ArrayList<String>()); ifRateL.add(new ArrayList<String>()); } String[] tL; for (String p : ratePlaces){ tL = g.getPreset(p); for (String t : tL){ if ((g.getPreset(t).length != 0) && (g.getPostset(t).length != 0) && (placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE")) && (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))) { ArrayList<Integer> diffL = diff(getPlaceInfoIndex(g.getPreset(t)[0]), getPlaceInfoIndex(g.getPostset(t)[0])); String ifStr = ""; String[] binIncoming = getPlaceInfoIndex(g.getPreset(t)[0]).split(""); String[] binOutgoing = getPlaceInfoIndex(g.getPostset(t)[0]).split(""); boolean above; double val; for (int k : diffL) { if (Integer.parseInt(binIncoming[k + 1]) < Integer.parseInt(binOutgoing[k + 1])) { val = divisionsL.get(k).get(Integer.parseInt(binIncoming[k + 1])).doubleValue(); above = true; } else { val = divisionsL.get(k).get(Integer.parseInt(binOutgoing[k + 1])).doubleValue(); above = false; } if (above) { ifStr = reqdVarsL.get(k).getName()+"'above("+val+")"; } else{ ifStr = "not "+ reqdVarsL.get(k).getName()+"'above("+val+")"; } for (int j = 0; j<reqdVarsL.size(); j++){ String rateStr = ""; if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){ //if (!(reqdVarsL.get(j).isInput() && reqdVarsL.get(j).isDmvc())){ rateStr = reqdVarsL.get(j).getName() + "'dot == span(" + getMinRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0,"+getMaxRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0)"; ifL.get(j).add(ifStr); ifRateL.get(j).add(rateStr); } } } } } } for (int i = 0; i<reqdVarsL.size(); i++){ for (int j = 0; j<ifL.get(i).size(); j++){ if (j==0){ vhdlAms.write("\tif "+ifL.get(i).get(j)+" use\n"); } else{ vhdlAms.write("\telsif "+ifL.get(i).get(j)+" use\n"); } vhdlAms.write("\t\t"+ ifRateL.get(i).get(j)+";\n"); } if (ifL.get(i).size() != 0){ vhdlAms.write("\tend use;\n\n"); } } // vhdlAms.write("\tprocess\n"); // vhdlAms.write("\tbegin\n"); for (int i = 0; i < dmvcVarPlaces.size(); i++){ if (dmvcVarPlaces.get(i).size() != 0){ vhdlAms.write("\tprocess\n"); vhdlAms.write("\tbegin\n"); for (String p : dmvcVarPlaces.get(i)){ vhdlAms.write("\t\twait for delay("+placeInfo.get(p).getProperty("dMax")+","+placeInfo.get(p).getProperty("dMin") +");\n"); // recheck above line.. truncating double to int.. becomes 0 in most unscaled cases?/ vhdlAms.write("\t\tbreak "+reqdVarsL.get(i).getName()+ " => "+ placeInfo.get(p).getProperty("DMVCValue") + ";\n"); } vhdlAms.write("\tend process;\n\n"); } } // vhdlAms.write("\tend process;\n\n"); vhdlAms.write("end "+vhdFile.split("\\.")[0]+";\n"); vhdlAms.close(); } catch(IOException e){ } } //T[] aux = (T[])a.clone(); } /* * public String cleanRow (String row){ String rowNS,rowTS = null; try{ rowNS = * lParenR.matcher(row).replaceAll(""); rowTS = * rParenR.matcher(rowNS).replaceAll(""); return rowTS; } * catch(PatternSyntaxException pse){ System.out.format("There is a problem with * the regular expression!%n"); System.out.format("The pattern in question is: * %s%n",pse.getPattern()); System.out.format("The description is: * %s%n",pse.getDescription()); System.out.format("The message is: * %s%n",pse.getMessage()); System.out.format("The index is: * %s%n",pse.getIndex()); System.exit(0); return rowTS; } } */
package client; import java.util.LinkedList; import bank.Bank; public class Client { int asset; String name; Bank bank; String accountNumber; public Client(String Name){ name = Name; accountNumber = "0"; } public void setAccountNumber(String Num){ accountNumber = Num; } public String getAccountNumber(){ return accountNumber; } public void openAccount(){ accountNumber = bank.openAccount(name); } public void closeAccount(){ asset += bank.closeAccount(accountNumber); } public void deposit(int money){ if(money < asset){ System.out.println(" ."); return; } asset -= money; bank.deposit(accountNumber, money); } public void withdraw(int money){ if(bank.withdraw(accountNumber, money)){ asset += money; } } public int getBalance(){ return bank.getBalance(accountNumber); } public void transfer(int money, String accountNumber){ bank.transfer(this.accountNumber, accountNumber, money); } public void loan(int money){ // money : bank.loan(accountNumber, money); } public void repayOnAccount(int money){ bank.repayOnAccount(accountNumber, money); } public void repay(int money){ bank.repay(accountNumber, money); } public void selectBank(Bank banks){ bank = banks; } public String getName(){ return name; } public int getAsset(){ return asset; } public LinkedList<String> getStateList(){ return bank.getStateList(accountNumber); } public int getDebt(){ return bank.getDebt(accountNumber); } public void timeLeap(){ bank.timeLeapYear(); } }
package com.bowlingx.cordova.webview; import org.apache.cordova.engine.SystemWebView; import android.view.ActionMode; import android.view.Menu; import android.view.View; import android.view.MenuInflater; public class HidePopoverCapableWebView extends SystemWebView { public HidePopoverCapableWebView setPopoverEnabled(boolean popoverEnabled) { isPopoverEnabled = popoverEnabled; return this; } private boolean isPopoverEnabled = false; @Override public ActionMode startActionMode(ActionMode.Callback callback, int type) { if(!this.isPopoverEnabled) { return this.dummyActionMode(); } else { return super.startActionMode(callback, type); } } @Override public ActionMode startActionMode(ActionMode.Callback callback) { return this.dummyActionMode(); if(!this.isPopoverEnabled) { return this.dummyActionMode(); } else { return super.startActionMode(callback); } } public ActionMode dummyActionMode() { return new ActionMode() { @Override public void setTitle(CharSequence title) { } @Override public void setTitle(int resId) { } @Override public void setSubtitle(CharSequence subtitle) { } @Override public void setSubtitle(int resId) { } @Override public void setCustomView(View view) { } @Override public void invalidate() { } @Override public void finish() { } @Override public Menu getMenu() { return null; } @Override public CharSequence getTitle() { return null; } @Override public CharSequence getSubtitle() { return null; } @Override public View getCustomView() { return null; } @Override public MenuInflater getMenuInflater() { return null; } }; } }
package com.yang.eto1.CordovaPlugin.TransparentWebViewServicePlugin; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.red_folder.phonegap.plugin.backgroundservice.BackgroundService; import android.annotation.TargetApi; import android.view.WindowManager; import android.graphics.PixelFormat; import android.view.Gravity; import android.widget.LinearLayout; import android.webkit.WebView; import android.webkit.WebViewClient; import android.webkit.WebSettings; import android.webkit.JavascriptInterface; import android.os.Build; import android.os.IBinder; import android.support.v4.app.NotificationCompat; import android.app.PendingIntent; import android.app.NotificationManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.ApplicationInfo; import android.media.RingtoneManager; import android.util.Log; public class TransparentWebViewService extends BackgroundService { private static final String TAG = "TransparentWebViewService"; private WebView wv; private boolean isActivityBound = false; private JSONObject currentMsg; private static int messageId = 0; @Override public void onCreate(){ super.onCreate(); WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE); WindowManager.LayoutParams params = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_PHONE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT); params.gravity = Gravity.TOP | Gravity.LEFT; params.x = 0; params.y = 0; params.width = 0; params.height = 0; wv = new WebView(this); wv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)); final WebSettings settings = wv.getSettings(); settings.setJavaScriptEnabled(true); settings.setDomStorageEnabled(true); //ApplicationInfo appInfo = this.getApplicationContext().getApplicationInfo(); if (/*(appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0 &&*/ android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { enableRemoteDebugging(); } if ((Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1)) { Log.e(TAG, "Disabled addJavascriptInterface() bridge since Android version is old."); return; } SystemExposedJsApi exposedJsApi = new SystemExposedJsApi(); wv.addJavascriptInterface(exposedJsApi, "simpleCordova"); wv.setWebViewClient(new WebViewClient() { public void onPageFinished (WebView view, String url){ Log.i(TAG, "background webview page load finished"); try{ currentMsg = new JSONObject("{type: \"PageFinished\"}"); }catch(JSONException e){ Log.e(TAG, "construct PageFinished msg error"); return; } runOnce(); } }); wv.loadUrl("file:///android_asset/www/background.html"); windowManager.addView(wv, params); Log.i(TAG, "service onCreate() finished, webview is started"); } @TargetApi(Build.VERSION_CODES.KITKAT) private void enableRemoteDebugging() { try { wv.setWebContentsDebuggingEnabled(true); } catch (IllegalArgumentException e) { Log.d(TAG, "You have one job! To turn on Remote Web Debugging! YOU HAVE FAILED! "); e.printStackTrace(); } } private void showNotification(String title, String text){ NotificationCompat.Builder builder = new NotificationCompat.Builder(this); Intent notifyIntent = new Intent(); ComponentName mainActivityComponent = findMainActivityComponentName(this); notifyIntent.setComponent(mainActivityComponent); // Sets the Activity to start in a new task notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent notifyPendingIntent = PendingIntent.getActivity( this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT ); builder.setContentIntent(notifyPendingIntent); builder.setAutoCancel(true); builder.setSmallIcon(this.getResources().getIdentifier("icon", "drawable", mainActivityComponent.getPackageName())); builder.setContentTitle(title); builder.setContentText(text); builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); builder.setVibrate(new long[]{0, 3000}); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(messageId, builder.build()); messageId++; } private static ComponentName findMainActivityComponentName(Context context) { PackageManager pm = context.getPackageManager(); PackageInfo packageInfo = null; try { packageInfo = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES); } catch (PackageManager.NameNotFoundException e) { throw new RuntimeException("No package info for " + context.getPackageName(), e); } for (ActivityInfo activityInfo : packageInfo.activities) { if ((activityInfo.flags & ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS) == 0) { return new ComponentName(packageInfo.packageName, activityInfo.name); } } throw new RuntimeException("Could not find main activity"); } @Override public IBinder onBind(Intent intent) { isActivityBound = true; Log.i(TAG, "main activity bound to service"); return super.onBind(intent); } @Override public boolean onUnbind(Intent intent){ isActivityBound = false; Log.i(TAG, "main activity unbound to service"); return super.onUnbind(intent); } class SystemExposedJsApi { @JavascriptInterface public void showNotification(String title, String text){ Log.i(TAG, "no activity, just service, so show notification, sender is "+title+", text is "+text); TransparentWebViewService.this.showNotification(title, text); } @JavascriptInterface public boolean isActivityBound(){ return TransparentWebViewService.this.isActivityBound; } @JavascriptInterface public void onMessage(JSONObject msg){ TransparentWebViewService.this.currentMsg = msg; TransparentWebViewService.this.runOnce(); } } private void webviewLoadUrlInMainThread(final String url){ wv.post(new Runnable(){ @Override public void run() { wv.loadUrl(url); } }); } @Override protected JSONObject doWork() { return currentMsg; } @Override protected JSONObject getConfig() { return null; } @Override protected void setConfig(JSONObject config) { String type; try{ type = config.getString("type"); Log.i(TAG, "got msg from main activity, type is "+type); }catch(JSONException e){ Log.e(TAG, "msg from main activity error, no type field"); return; } if(type.equals("LoginInfo")){ String username; String password; String role; try{ username = config.getString("username"); password = config.getString("password"); role = config.getString("role"); Log.i(TAG, "got login msg from main activity, username is "+username+", password is "+password+", role is "+role); }catch(JSONException e){ Log.e(TAG, "LoginInfo msg from main activity error"); return; } //webviewLoadUrlInMainThread("javascript:Auth.login(\""+username+"\", \""+password+"\", \""+role+"\", loginCallback);localStorage.loginInfo = JSON.stringify({username: \""+username+"\", password: \""+password+"\", role: \""+role+"\"});"); webviewLoadUrlInMainThread("javascript:myEvents.emit(\"login\", \""+username+"\", \""+password+"\", \""+role+"\");"); }else if(type.equals("Subscribe")){ String topic; try{ topic = config.getString("topic"); Log.i(TAG, "got subscribe msg from main activity, topic is "+topic); }catch(JSONException e){ Log.e(TAG, "Subscribe msg from main activity error"); return; } webviewLoadUrlInMainThread("javascript:MqttClient.subscribe(\""+topic+"\");"); }else if(type.equals("Publish")){ String topic, msg; try{ topic = config.getString("topic"); msg = config.getString("message"); Log.i(TAG, "got publish msg from main activity, topic is "+topic+", msg is "+msg); }catch(JSONException e){ Log.e(TAG, "publish msg from main activity error"); return; } webviewLoadUrlInMainThread("javascript:MqttClient.publish(\""+topic+"\", \""+msg+"\");"); }else{ Log.w(TAG, "got msg from main activity, but type is unknown"); } } @Override protected JSONObject initialiseLatestResult() { return null; } }
package authoring_environment; import gamedata.gamecomponents.Patch; import gamedata.gamecomponents.Piece; import java.util.HashMap; import java.util.Map; import authoring.concretefeatures.TerrainEntry; import authoring.concretefeatures.UnitEntry; import authoring.data.PatchTypeData; import authoring.data.PieceTypeData; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.Separator; import javafx.scene.control.SingleSelectionModel; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; /** * @author VOOGirls Generation * * GUI components for the library displayed on the left side of the * game authoring environment, which contains all instantiated units * and terrain. From here, the user can open the Unit/TerrainEditors * to edit the units and terrain, as well as select them for * placement on the grid. */ public class LibraryView extends TabPane { private final int HEIGHT = 300; private final int WIDTH = 580; private final String UNITS = "Units"; private final String TERRAIN = "Terrain"; private final String DELETE = "Delete"; private final String EDIT = "Edit"; private final String GLOBAL = "Global Commands"; private final String PIECES = "Piece Templates"; private final String PATCHES = "Patch Templates"; private PieceTypeData myPieces; private PatchTypeData myPatches; private SandyGrid myGrid; private Map<String, VBox> myLibraryMap; private Map<String, Tab> myTabMap; private SingleSelectionModel<Tab> mySelection; private Piece currentUnit; private Patch currentTerrain; private boolean doNothing; private boolean reset; private boolean edit; private int unitID; private String terrainName; /** * LibraryView constructor. Initializes two tabs - one for units, * one for terrain. Units and terrain are added dynamically to * their respective tabs as they are created in the UnitCreator * and TerrainCreator. */ public LibraryView (PieceTypeData pieceData, PatchTypeData patchData) { mySelection = this.getSelectionModel(); this.setPrefSize(HEIGHT, WIDTH); myPieces = pieceData; myPatches = patchData; doNothing = true; reset = true; edit = false; unitID = 0; terrainName = ""; Tab unitTab = new Tab(UNITS); unitTab.setClosable(false); ScrollPane unitContent = new ScrollPane(); VBox unitLibrary = new VBox(); unitLibrary.setPadding(UIspecs.allPadding); unitLibrary.setSpacing(5); Button unitDelete = new Button(DELETE); Button unitEdit = new Button(EDIT); unitDelete.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle (ActionEvent e) { doNothing = false; reset = true; edit = false; } }); unitEdit.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle (ActionEvent e) { doNothing = false; reset = false; edit = true; } }); HBox unitGlobal = new HBox(unitEdit, unitDelete); unitGlobal.setPadding(UIspecs.allPadding); unitGlobal.setSpacing(5); unitLibrary.getChildren().addAll(new Label(GLOBAL), unitGlobal, new Separator(), new Label(PIECES)); unitContent.setContent(unitLibrary); unitTab.setContent(unitContent); Tab terrainTab = new Tab(TERRAIN); terrainTab.setClosable(false); ScrollPane terrainContent = new ScrollPane(); VBox terrainLibrary = new VBox(); terrainLibrary.setPadding(UIspecs.allPadding); terrainLibrary.setSpacing(5); Button terrainDelete = new Button(DELETE); Button terrainEdit = new Button(EDIT); terrainDelete.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle (ActionEvent e) { doNothing = false; reset = true; edit = false; } }); terrainEdit.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle (ActionEvent e) { doNothing = false; reset = false; edit = true; } }); HBox terrainGlobal = new HBox(terrainEdit, terrainDelete); terrainGlobal.setPadding(UIspecs.allPadding); terrainGlobal.setSpacing(5); terrainLibrary.getChildren().addAll(new Label(GLOBAL), terrainGlobal, new Separator(), new Label(PATCHES)); terrainContent.setContent(terrainLibrary); terrainTab.setContent(terrainContent); this.getTabs().addAll(unitTab, terrainTab); this.setOnKeyPressed(new EventHandler<KeyEvent>() { @Override public void handle (KeyEvent e) { if (e.getCode() == KeyCode.ESCAPE) { doNothing = true; } } }); myLibraryMap = new HashMap<String, VBox>(); myLibraryMap.put(UNITS, unitLibrary); myLibraryMap.put(TERRAIN, terrainLibrary); myTabMap = new HashMap<String, Tab>(); myTabMap.put(UNITS, unitTab); myTabMap.put(TERRAIN, terrainTab); } public void associateGrid (SandyGrid grid) { System.out.println(grid); myGrid = grid; setGridActionEvents(); } public int getUnitID () { unitID += 1; return unitID; } public String getTerrainName () { return terrainName; } public void selectUnit (Piece unit) { currentUnit = unit; doNothing = false; reset = false; edit = false; } public void selectTerrain (Patch terrain) { currentTerrain = terrain; doNothing = false; reset = false; edit = false; } private void setGridActionEvents () { myGrid.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle (MouseEvent event) { handleAction(event); } }); myGrid.setOnMouseDragged(new EventHandler<MouseEvent>() { @Override public void handle (MouseEvent event) { handleAction(event); } }); } protected void handleAction (MouseEvent event) { SandyTile tile = myGrid.findTile(event); if (doNothing || tile == null) { return; } if (mySelection.isSelected(0)) { if (currentUnit != null) { Piece unit = new Piece(currentUnit); if (reset) { myGrid.removeUnit(tile, unit); } else if (edit) { myGrid.editUnit(tile, unit); } else { myGrid.addUnit(tile, unit); } } } else { if (currentTerrain != null) { Patch terrain = new Patch(currentTerrain); if (reset) { myGrid.removeTerrain(tile, terrain); } else if (edit) { myGrid.editTerrain(tile, terrain); } else { myGrid.addTerrain(tile, terrain); } } } } public void addPiece (UnitEntry unit) { mySelection.select(myTabMap.get(UNITS)); myLibraryMap.get(UNITS).getChildren().add(unit); myPieces.add(unit.getUnit()); } public void addPatch (TerrainEntry terrain) { mySelection.select(myTabMap.get(TERRAIN)); myLibraryMap.get(TERRAIN).getChildren().add(terrain); myPatches.add(terrain.getTerrain()); } public void removePiece (UnitEntry unit) { myLibraryMap.get(UNITS).getChildren().remove(unit); myGrid.removePieces(unit.getUnit()); myPieces.remove(unit.getUnit()); doNothing = true; } public void removePatch (TerrainEntry terrain) { myLibraryMap.get(TERRAIN).getChildren().remove(terrain); myGrid.removePatches(terrain.getTerrain()); myPatches.remove(terrain.getTerrain()); doNothing = true; } }
package br.ufrn.imd.netfrix.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.sun.rowset.CachedRowSetImpl; import br.ufrn.imd.netfrix.model.User; public class DataBase { //Declare JDBC Driver private static final String JDBC_DRIVER = "org.postgresql.Driver"; private static String url = "jdbc:postgresql://localhost/netfrix"; private static String user = "postgres"; private static String password = "postgres"; //Connection private static Connection conn = null; //Connect to DB public static void dbConnect() throws SQLException, ClassNotFoundException { //Setting Oracle JDBC Driver try { Class.forName(JDBC_DRIVER); } catch (ClassNotFoundException e) { System.out.println("Where is your Oracle JDBC Driver?"); e.printStackTrace(); throw e; } System.out.println("Oracle JDBC Driver Registered!"); //Establish the Oracle Connection using Connection String try { conn = DriverManager.getConnection(url, user, password); } catch (SQLException e) { System.out.println("Connection Failed! Check output console" + e); e.printStackTrace(); throw e; } } //Close Connection public static void dbDisconnect() throws SQLException { try { if (conn != null && !conn.isClosed()) { conn.close(); } } catch (Exception e){ throw e; } } //DB Execute Query Operation public static ResultSet dbExecuteQuery(String queryStmt) throws SQLException, ClassNotFoundException { //Declare statement, resultSet and CachedResultSet as null Statement stmt = null; ResultSet resultSet = null; CachedRowSetImpl crs = null; try { //Connect to DB (Establish Oracle Connection) dbConnect(); System.out.println("Select statement: " + queryStmt + "\n"); //Create statement stmt = conn.createStatement(); //Execute select (query) operation resultSet = stmt.executeQuery(queryStmt); //CachedRowSet Implementation //In order to prevent "java.sql.SQLRecoverableException: Closed Connection: next" error //We are using CachedRowSet crs = new CachedRowSetImpl(); crs.populate(resultSet); } catch (SQLException e) { System.out.println("Problem occurred at executeQuery operation : " + e); throw e; } finally { if (resultSet != null) { //Close resultSet resultSet.close(); } if (stmt != null) { //Close Statement stmt.close(); } //Close connection dbDisconnect(); } //Return CachedRowSet return crs; } //DB Execute Update (For Update/Insert/Delete) Operation public static void dbExecuteUpdate(String sqlStmt) throws SQLException, ClassNotFoundException { //Declare statement as null Statement stmt = null; try { //Connect to DB (Establish Oracle Connection) dbConnect(); //Create Statement stmt = conn.createStatement(); //Run executeUpdate operation with given sql statement stmt.executeUpdate(sqlStmt); } catch (SQLException e) { System.out.println("Problem occurred at executeUpdate operation : " + e); throw e; } finally { if (stmt != null) { //Close statement stmt.close(); } //Close connection dbDisconnect(); } } }
package br.mg.com.classe; import java.util.Date; import br.mg.com.enumeration.Sexo; public abstract class Pessoa { private String nome; private String nomeQuadrante; private String nomeCracha; private Long estadoCivil; private Date dataNascimento; private Date dataCasamento; private Sexo sexo; public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getNomeQuadrante() { return nomeQuadrante; } public void setNomeQuadrante(String nomeQuadrante) { this.nomeQuadrante = nomeQuadrante; } public String getNomeCracha() { return nomeCracha; } public void setNomeCracha(String nomeCracha) { this.nomeCracha = nomeCracha; } public Long getEstadoCivil() { return estadoCivil; } public void setEstadoCivil(Long estadoCivil) { this.estadoCivil = estadoCivil; } public Date getDataNascimento() { return dataNascimento; } public void setDataNascimento(Date dataNascimento) { this.dataNascimento = dataNascimento; } public Date getDataCasamento() { return dataCasamento; } public void setDataCasamento(Date dataCasamento) { this.dataCasamento = dataCasamento; } public Sexo getSexo() { return sexo; } public void setSexo(Sexo sexo) { this.sexo = sexo; } }
package de.unituebingen.ub.ubtools.solrmarcMixin; import org.marc4j.marc.ControlField; import org.marc4j.marc.DataField; import org.marc4j.marc.Record; import org.marc4j.marc.Subfield; import org.marc4j.marc.VariableField; import org.solrmarc.index.SolrIndexer; import org.solrmarc.index.SolrIndexerMixin; import org.solrmarc.tools.Utils; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TuelibMixin extends SolrIndexerMixin { private final static Logger logger = Logger.getLogger(TuelibMixin.class.getName()); /** * Returns either a Set<String> of parent (URL + colon + material type). URLs are taken from 856$u and material * types from 856$3, 856$z or 856$x. For missing type subfields the text "Unbekanntes Material" will be used. * Furthermore 024$2 will be checked for "doi". If we find this we generate a URL with a DOI resolver from the * DOI in 024$a and set the "material type" to "DOI Link". * * @param record the record * @return A, possibly empty, Set<String> containing the URL/material-type pairs. */ private final static String UNKNOWN_MATERIAL_TYPE = "Unbekanntes Material"; private final static Pattern EXTRACTION_PATTERN = Pattern.compile("^\\([^)]+\\)(.+)$"); // TODO: This should be in a translation mapping file private final static HashMap<String, String> isil_to_department_map = new HashMap<String, String>() { { this.put("Unknown", "Unknown"); this.put("DE-21", "Universit\u00E4tsbibliothek T\u00FCbingen"); this.put("DE-21-1", "Universit\u00E4t T\u00FCbingen, Klinik f\u00FCr Psychatrie und Psychologie"); this.put("DE-21-3", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Toxikologie und Pharmakologie"); this.put("DE-21-4", "Universit\u00E4t T\u00FCbingen, Universit\u00E4ts-Augenklinik"); this.put("DE-21-10", "Universit\u00E4tsbibliothek T\u00FCbingen, Bereichsbibliothek Geowissenschaften"); this.put("DE-21-11", "Universit\u00E4tsbibliothek T\u00FCbingen, Bereichsbibliothek Schloss Nord"); this.put("DE-21-14", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Ur- und Fr\u00FChgeschichte und Arch\u00E4ologie des Mittelalters, Abteilung j\u00FCngere Urgeschichte und Fr\u00FChgeschichte + Abteilung f\u00FCr Arch\u00E4ologie des Mittelalters"); this.put("DE-21-17", "Universit\u00E4t T\u00FCbingen, Geographisches Institut"); this.put("DE-21-18", "Universit\u00E4t T\u00FCbingen, Universit\u00E4ts-Hautklinik"); this.put("DE-21-19", "Universit\u00E4t T\u00FCbingen, Wirtschaftswissenschaftliches Seminar"); this.put("DE-21-20", "Universit\u00E4t T\u00FCbingen, Frauenklinik"); this.put("DE-21-21", "Universit\u00E4t T\u00FCbingen, Universit\u00E4ts-Hals-Nasen-Ohrenklinik, Bibliothek"); this.put("DE-21-22", "Universit\u00E4t T\u00FCbingen, Kunsthistorisches Institut"); this.put("DE-21-23", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Pathologie"); this.put("DE-21-24", "Universit\u00E4t T\u00FCbingen, Juristisches Seminar"); this.put("DE-21-25", "Universit\u00E4t T\u00FCbingen, Musikwissenschaftliches Institut"); this.put("DE-21-26", "Universit\u00E4t T\u00FCbingen, Anatomisches Institut"); this.put("DE-21-27", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Anthropologie und Humangenetik"); this.put("DE-21-28", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Astronomie und Astrophysik, Abteilung Astronomie"); this.put("DE-21-31", "Universit\u00E4t T\u00FCbingen, Evangelisch-theologische Fakult\u00E4t"); this.put("DE-21-32a", "Universit\u00E4t T\u00FCbingen, Historisches Seminar, Abteilung f\u00FCr Alte Geschichte"); this.put("DE-21-32b", "Universit\u00E4t T\u00FCbingen, Historisches Seminar, Abteilung f\u00FCr Mittelalterliche Geschichte"); this.put("DE-21-32c", "Universit\u00E4t T\u00FCbingen, Historisches Seminar, Abteilung f\u00FCr Neuere Geschichte"); this.put("DE-21-34", "Universit\u00E4t T\u00FCbingen, Asien-Orient-Institut, Abteilung f\u00FCr Indologie und Vergleichende Religionswissenschaft"); this.put("DE-21-35", "Universit\u00E4t T\u00FCbingen, Katholisch-theologische Fakult\u00E4t"); this.put("DE-21-39", "Universit\u00E4t T\u00FCbingen, Fachbibliothek Mathematik und Physik / Bereich Mathematik"); this.put("DE-21-37", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Sportwissenschaft"); this.put("DE-21-42", "Universit\u00E4t T\u00FCbingen, Asien-Orient-Institut, Abteilung f\u00FCr Orient- uns Islamwissenschaft"); this.put("DE-21-43", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Erziehungswissenschaft"); this.put("DE-21-45", "Universit\u00E4t T\u00FCbingen, Philologisches Seminar"); this.put("DE-21-46", "Universit\u00E4t T\u00FCbingen, Philosophisches Seminar"); this.put("DE-21-50", "Universit\u00E4t T\u00FCbingen, Physiologisches Institut"); this.put("DE-21-51", "Universit\u00E4t T\u00FCbingen, Psychologisches Institut"); this.put("DE-21-52", "Universit\u00E4t T\u00FCbingen, Ludwig-Uhland-Institut f\u00FCr Empirische Kulturwissenschaft"); this.put("DE-21-53", "Universit\u00E4t T\u00FCbingen, Asien-Orient-Institut, Abteilung f\u00FCr Ethnologie"); this.put("DE-21-54", "Universit\u00E4t T\u00FCbingen, Universit\u00E4tsklinik f\u00FCr Zahn-, Mund- und Kieferheilkunde"); this.put("DE-21-58", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Politikwissenschaft"); this.put("DE-21-62", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Osteurop\u00E4ische Geschichte und Landeskunde"); this.put("DE-21-63", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Tropenmedizin"); this.put("DE-21-64", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Geschichtliche Landeskunde und Historische Hilfswissenschaften"); this.put("DE-21-65", "Universit\u00E4t T\u00FCbingen, Universit\u00E4ts-Apotheke"); this.put("DE-21-74", "Universit\u00E4t T\u00FCbingen, Zentrum f\u00FCr Informations-Technologie"); this.put("DE-21-78", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Medizinische Biometrie"); this.put("DE-21-81", "Universit\u00E4t T\u00FCbingen, Inst. f. Astronomie und Astrophysik/Abt. Geschichte der Naturwiss."); this.put("DE-21-85", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Soziologie"); this.put("DE-21-86", "Universit\u00E4t T\u00FCbingen, Zentrum f\u00FCr Datenverarbeitung"); this.put("DE-21-89", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Arbeits- und Sozialmedizin"); this.put("DE-21-92", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Gerichtliche Medizin"); this.put("DE-21-93", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Ethik und Geschichte der Medizin"); this.put("DE-21-95", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Hirnforschung"); this.put("DE-21-98", "Universit\u00E4t T\u00FCbingen, Fachbibliothek Mathematik und Physik / Bereich Physik"); this.put("DE-21-99", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Ur- und Fr\u00FChgeschichte und Arch\u00E4ologie des Mittelalters, Abteilung f\u00FCr \u00E4ltere Urgeschichteund Quart\u00E4r\u00F6kologie"); this.put("DE-21-106", "Universit\u00E4t T\u00FCbingen, Seminar f\u00FCr Zeitgeschichte"); this.put("DE-21-108", "Universit\u00E4t T\u00FCbingen, Fakult\u00E4tsbibliothek Neuphilologie"); this.put("DE-21-109", "Universit\u00E4t T\u00FCbingen, Asien-Orient-Institut, Abteilung f\u00FCr Sinologie und Koreanistik"); this.put("DE-21-110", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Kriminologie"); this.put("DE-21-112", "Universit\u00E4t T\u00FCbingen, Fakult\u00E4t f\u00FCr Biologie, Bibliothek"); this.put("DE-21-116", "Universit\u00E4t T\u00FCbingen, Zentrum f\u00FCr Molekularbiologie der Pflanzen, Forschungsgruppe Pflanzenbiochemie"); this.put("DE-21-117", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Medizinische Informationsverarbeitung"); this.put("DE-21-118", "Universit\u00E4t T\u00FCbingen, Universit\u00E4ts-Archiv"); this.put("DE-21-119", "Universit\u00E4t T\u00FCbingen, Wilhelm-Schickard-Institut f\u00FCr Informatik"); this.put("DE-21-120", "Universit\u00E4t T\u00FCbingen, Asien-Orient-Institut, Abteilung f\u00FCr Japanologie"); this.put("DE-21-121", "Universit\u00E4t T\u00FCbingen, Internationales Zentrum f\u00FCr Ethik in den Wissenschaften"); this.put("DE-21-123", "Universit\u00E4t T\u00FCbingen, Medizinbibliothek"); this.put("DE-21-124", "Universit\u00E4t T\u00FCbingen, Institut f. Medizinische Virologie und Epidemiologie d. Viruskrankheiten"); this.put("DE-21-126", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Medizinische Mikrobiologie und Hygiene"); this.put("DE-21-203", "Universit\u00E4t T\u00FCbingen, Sammlung Werner Schweikert - Archiv der Weltliteratur"); this.put("DE-21-205", "Universit\u00E4t T\u00FCbingen, Zentrum f\u00FCr Islamische Theologie"); this.put("DE-Frei85", "Freiburg MPI Ausl\u00E4nd.Recht, Max-Planck-Institut f\u00FCr ausl\u00E4ndisches und internationales Strafrecht"); } }; private final static Pattern PAGE_RANGE_PATTERN1 = Pattern.compile("\\s*(\\d+)\\s*-\\s*(\\d+)$"); private final static Pattern PAGE_RANGE_PATTERN2 = Pattern.compile("\\s*\\[(\\d+)\\]\\s*-\\s*(\\d+)$"); private final static Pattern PAGE_RANGE_PATTERN3 = Pattern.compile("\\s*(\\d+)\\s*ff"); private final static Pattern YEAR_PATTERN = Pattern.compile("(\\d\\d\\d\\d)"); private final static Pattern VOLUME_PATTERN = Pattern.compile("^\\s*(\\d+)$"); // Map used by getPhysicalType(). private static final Map<String, String> phys_code_to_full_name_map; static { Map<String, String> tempMap = new HashMap<>(); tempMap.put("arbtrans", "Transparency"); tempMap.put("blindendr", "Braille"); tempMap.put("bray", "Blu-ray Disc"); tempMap.put("cdda", "CD"); tempMap.put("ckop", "Microfiche"); tempMap.put("cofz", "Online Resource"); tempMap.put("crom", "CD-ROM"); tempMap.put("dias", "Slides"); tempMap.put("disk", "Diskette"); tempMap.put("druck", "Printed Material"); tempMap.put("dvda", "Audio DVD"); tempMap.put("dvdr", "DVD-ROM"); tempMap.put("dvdv", "Video DVD"); tempMap.put("gegenst", "Physical Object"); tempMap.put("handschr", "Longhand Text"); tempMap.put("kunstbl", "Artistic Works on Paper"); tempMap.put("lkop", "Mircofilm"); tempMap.put("medi", "Multiple Media Types"); tempMap.put("scha", "Record"); tempMap.put("skop", "Microform"); tempMap.put("sobildtt", "Audiovisual Carriers"); tempMap.put("soerd", "Carriers of Other Electronic Data"); tempMap.put("sott", "Carriers of Other Audiodata"); tempMap.put("tonbd", "Audiotape"); tempMap.put("tonks", "Audiocasette"); tempMap.put("vika", "Videocasette"); phys_code_to_full_name_map = Collections.unmodifiableMap(tempMap); } private Set<String> isils_cache = null; private Set<String> reviews_cache = null; private Set<String> reviewedRecords_cache = null; @Override public void perRecordInit(final Record record) { reviews_cache = reviewedRecords_cache = isils_cache = null; } /** * Determine Record Title * * @param record the record * @return String nicely formatted title */ public String getTitle(final Record record) { final DataField title = (DataField) record.getVariableField("245"); if (title == null) return null; final String title_a = (title.getSubfield('a') == null) ? null : title.getSubfield('a').getData(); final String title_b = (title.getSubfield('b') == null) ? null : title.getSubfield('b').getData(); if (title_a == null && title_b == null) return null; final StringBuilder complete_title = new StringBuilder(); if (title_a == null) complete_title.append(Utils.cleanData(title_b)); else if (title_b == null) complete_title.append(Utils.cleanData(title_a)); else { // Neither title_a nor title_b are null. complete_title.append(Utils.cleanData(title_a)); complete_title.append(" : "); complete_title.append(Utils.cleanData(title_b)); } final String title_n = (title.getSubfield('n') == null) ? null : title.getSubfield('n').getData(); if (title_n != null) { complete_title.append(' '); complete_title.append(Utils.cleanData(title_n)); } return complete_title.toString(); } /** * Determine Record Title Subfield * * @param record the record * @param subfield_code * @return String nicely formatted title subfield */ public String getTitleSubfield(final Record record, final String subfield_code) { final DataField title = (DataField) record.getVariableField("245"); if (title == null) return null; final Subfield subfield = title.getSubfield(subfield_code.charAt(0)); if (subfield == null) return null; final String subfield_data = subfield.getData(); if (subfield_data == null) return null; return Utils.cleanData(subfield_data); } /** * get the local subjects from LOK-tagged fields and get subjects from 936k and 689a subfields * <p/> * LOK = Field * |0 689 = Subfield * |a Imperialismus = Subfield with local subject * * @param record the record * @return Set of local subjects */ public Set<String> getAllTopics(final Record record) { final Set<String> topics = SolrIndexer.getAllSubfields(record, "600:610:611:630:650:653:656:689a:936a", " "); for (final VariableField variableField : record.getVariableFields("LOK")) { final DataField lokfield = (DataField) variableField; final Subfield subfield0 = lokfield.getSubfield('0'); if (subfield0 == null || !subfield0.getData().equals("689 ")) { continue; } final Subfield subfieldA = lokfield.getSubfield('a'); if (subfieldA == null || subfieldA.getData().length() <= 1) { continue; } topics.add(subfieldA.getData()); } return topics; } /** * Hole das Sachschlagwort aus 689|a (wenn 689|d != z oder f) * * @param record the record * @return Set "topic_facet" */ public Set<String> getFacetTopics(final Record record) { final Set<String> result = SolrIndexer.getAllSubfields(record, "600x:610x:611x:630x:648x:650a:650x:651x:655x", " "); String topic_string; // Check 689 subfield a and d final List<VariableField> fields = record.getVariableFields("689"); if (fields != null) { DataField dataField; for (final VariableField variableField : fields) { dataField = (DataField) variableField; final Subfield subfieldD = dataField.getSubfield('d'); if (subfieldD == null) { continue; } topic_string = subfieldD.getData().toLowerCase(); if (topic_string.equals("f") || topic_string.equals("z")) { continue; } final Subfield subfieldA = dataField.getSubfield('a'); if (subfieldA != null) { result.add(subfieldA.getData()); } } } return result; } /** * Finds the first subfield which is nonempty. * * @param dataField the data field * @param subfieldIDs the subfield identifiers to search for * @return a nonempty subfield or null */ private Subfield getFirstNonEmptySubfield(final DataField dataField, final char... subfieldIDs) { for (final char subfieldID : subfieldIDs) { for (final Subfield subfield : dataField.getSubfields(subfieldID)) { if (subfield != null && subfield.getData() != null && !subfield.getData().isEmpty()) { return subfield; } } } return null; } public Set<String> getUrlsAndMaterialTypes(final Record record) { final Set<String> nonUnknownMaterialTypeURLs = new HashSet<String>(); final Map<String, Set<String>> materialTypeToURLsMap = new TreeMap<String, Set<String>>(); final Set<String> urls_and_material_types = new LinkedHashSet<>(); for (final VariableField variableField : record.getVariableFields("856")) { final DataField field = (DataField) variableField; final Subfield materialTypeSubfield = getFirstNonEmptySubfield(field, '3', 'z', 'y', 'x'); final String materialType = (materialTypeSubfield == null) ? UNKNOWN_MATERIAL_TYPE : materialTypeSubfield.getData(); // Extract all links from u-subfields and resolve URNs: for (final Subfield subfield_u : field.getSubfields('u')) { Set<String> URLs = materialTypeToURLsMap.get(materialType); if (URLs == null) { URLs = new HashSet<String>(); materialTypeToURLsMap.put(materialType, URLs); } final String rawLink = subfield_u.getData(); final String link; if (rawLink.startsWith("urn:")) link = "https://nbn-resolving.org/" + rawLink; else if (rawLink.startsWith("http://nbn-resolving.de")) link = "https://nbn-resolving.org/" + rawLink.substring(23); // Replace HTTP w/ HTTPS. else if (rawLink.startsWith("http://nbn-resolving.org")) link = "https://nbn-resolving.org/" + rawLink.substring(24); // Replace HTTP w/ HTTPS. else link = rawLink; URLs.add(link); if (!materialType.equals(UNKNOWN_MATERIAL_TYPE)) { nonUnknownMaterialTypeURLs.add(link); } } } // Remove duplicates while favouring SWB and, if not present, DNB links: for (final String material_type : materialTypeToURLsMap.keySet()) { if (material_type.equals(UNKNOWN_MATERIAL_TYPE)) { for (final String url : materialTypeToURLsMap.get(material_type)) { if (!nonUnknownMaterialTypeURLs.contains(url)) { urls_and_material_types.add(url + ":" + UNKNOWN_MATERIAL_TYPE); } } } else { // Locate SWB and DNB URLs, if present: String preferredURL = null; for (final String url : materialTypeToURLsMap.get(material_type)) { if (url.startsWith("http://swbplus.bsz-bw.de")) { preferredURL = url; break; } else if (url.startsWith("http://d-nb.info")) preferredURL = url; } if (preferredURL != null) urls_and_material_types.add(preferredURL + ":" + material_type); else { // Add the kitchen sink. for (final String url : materialTypeToURLsMap.get(material_type)) urls_and_material_types.add(url + ":" + material_type); } } } // Handle DOI's: for (final VariableField variableField : record.getVariableFields("024")) { final DataField field = (DataField) variableField; final Subfield subfield_2 = field.getSubfield('2'); if (subfield_2 != null && subfield_2.getData().equals("doi")) { final Subfield subfield_a = field.getSubfield('a'); if (subfield_a != null) { final String url = "https://doi.org/" + subfield_a.getData(); urls_and_material_types.add(url + ":DOI"); } } } return urls_and_material_types; } /** * Returns either a Set<String> of parent (ID + colon + parent title). Only IDs w/o titles will not be returned, * instead a warning will be emitted on stderr. * * @param record the record * @return A, possibly empty, Set<String> containing the ID/title pairs. */ public Set<String> getContainerIdsWithTitles(final Record record) { final Set<String> containerIdsAndTitles = new TreeSet<>(); for (final String tag : new String[]{"800", "810", "830", "773"}) { for (final VariableField variableField : record.getVariableFields(tag)) { final DataField field = (DataField) variableField; final Subfield titleSubfield = getFirstNonEmptySubfield(field, 't', 'a'); final Subfield volumeSubfield = field.getSubfield('v'); final Subfield idSubfield = field.getSubfield('w'); if (titleSubfield == null || idSubfield == null) continue; final Matcher matcher = EXTRACTION_PATTERN.matcher(idSubfield.getData()); if (!matcher.matches()) continue; final String parentId = matcher.group(1); containerIdsAndTitles.add(parentId + (char) 0x1F + titleSubfield.getData() + (char) 0x1F + (volumeSubfield == null ? "" : volumeSubfield.getData())); } } return containerIdsAndTitles; } private void collectReviewsAndReviewedRecords(final Record record) { if (reviews_cache != null && reviewedRecords_cache != null) { return; } reviews_cache = new TreeSet<>(); reviewedRecords_cache = new TreeSet<>(); for (final VariableField variableField : record.getVariableFields("787")) { final DataField field = (DataField) variableField; final Subfield reviewTypeSubfield = getFirstNonEmptySubfield(field, 'i'); final Subfield reviewerSubfield = getFirstNonEmptySubfield(field, 'a'); final Subfield titleSubfield = getFirstNonEmptySubfield(field, 't'); final Subfield idSubfield = field.getSubfield('w'); if (reviewerSubfield == null || titleSubfield == null || idSubfield == null || reviewTypeSubfield == null) continue; final Matcher matcher = EXTRACTION_PATTERN.matcher(idSubfield.getData()); if (!matcher.matches()) continue; final String parentId = matcher.group(1); if (reviewTypeSubfield.getData().equals("Rezension")) { reviews_cache.add(parentId + (char) 0x1F + reviewerSubfield.getData() + (char) 0x1F + titleSubfield.getData()); } else if (reviewTypeSubfield.getData().equals("Rezension von")) { reviewedRecords_cache.add(parentId + (char) 0x1F + reviewerSubfield.getData() + (char) 0x1F + titleSubfield.getData()); } } } public Set<String> getReviews(final Record record) { collectReviewsAndReviewedRecords(record); return reviews_cache; } public Set<String> getReviewedRecords(final Record record) { collectReviewsAndReviewedRecords(record); return reviewedRecords_cache; } /** * @param record the record * @param fieldnums * @return */ public Set<String> getSuperMP(final Record record, final String fieldnums) { final Set<String> retval = new LinkedHashSet<>(); final HashMap<String, String> resvalues = new HashMap<>(); final HashMap<String, Integer> resscores = new HashMap<>(); String value; String id; Integer score; Integer cscore; String fnum; String fsfc; final String[] fields = fieldnums.split(":"); for (final String field : fields) { fnum = field.replaceAll("[a-z]+$", ""); fsfc = field.replaceAll("^[0-9]+", ""); final List<VariableField> fs = record.getVariableFields(fnum); if (fs == null) { continue; } for (final VariableField variableField : fs) { final DataField dataField = (DataField) variableField; final Subfield subfieldW = dataField.getSubfield('w'); if (subfieldW == null) { continue; } final Subfield fsubany = dataField.getSubfield(fsfc.charAt(0)); if (fsubany == null) { continue; } value = fsubany.getData().trim(); id = subfieldW.getData().replaceAll("^\\([^\\)]+\\)", ""); // Count number of commas in "value": score = value.length() - value.replace(",", "").length(); if (resvalues.containsKey(id)) { cscore = resscores.get(id); if (cscore > score) { continue; } } resvalues.put(id, value); resscores.put(id, score); } } for (final String key : resvalues.keySet()) { value = "(" + key + ")" + resvalues.get(key); retval.add(value); } return retval; } /** * get the ISILs from LOK-tagged fields * <p/> * Typical LOK-Section below a Marc21 - Title-Set of a record: * LOK |0 000 xxxxxnu a22 zn 4500 * LOK |0 001 000001376 * LOK |0 003 DE-576 * LOK |0 004 000000140 * LOK |0 005 20020725000000 * LOK |0 008 020725||||||||||||||||ger||||||| * LOK |0 014 |a 000001368 |b DE-576 * LOK |0 541 |e 76.6176 * LOK |0 852 |a DE-Sp3 * LOK |0 852 1 |c B IV 529 |9 00 * <p/> * LOK = Field * |0 852 = Subfield * |a DE-Sp3 = Subfield with ISIL * * @param record the record * @return Set of isils */ public Set<String> getIsils(final Record record) { if (isils_cache != null) { return isils_cache; } final Set<String> isils = new LinkedHashSet<>(); final List<VariableField> fields = record.getVariableFields("LOK"); if (fields != null) { for (final VariableField variableField : fields) { final DataField lokfield = (DataField) variableField; final Subfield subfield0 = lokfield.getSubfield('0'); if (subfield0 == null || !subfield0.getData().startsWith("852")) { continue; } final Subfield subfieldA = lokfield.getSubfield('a'); if (subfieldA != null) { isils.add(subfieldA.getData()); } } } if (isils.isEmpty()) { // Nothing worked! isils.add("Unknown"); } this.isils_cache = isils; return isils; } /** * @param record the record * @return */ public String isAvailableInTuebingen(final Record record) { return Boolean.toString(!record.getVariableFields("SIG").isEmpty()); } /** * get the collections from LOK-tagged fields * <p/> * Typical LOK-Section below a Marc21 - Title-Set of a record: * LOK |0 000 xxxxxnu a22 zn 4500 * LOK |0 001 000001376 * LOK |0 003 DE-576 * LOK |0 004 000000140 * LOK |0 005 20020725000000 * LOK |0 008 020725||||||||||||||||ger||||||| * LOK |0 014 |a 000001368 |b DE-576 * LOK |0 541 |e 76.6176 * LOK |0 852 |a DE-Sp3 * LOK |0 852 1 |c B IV 529 |9 00 * <p/> * LOK = Field * |0 852 = Subfield * |a DE-Sp3 = Subfield with ISIL * * @param record the record * @return Set of collections */ public Set<String> getCollections(final Record record) { final Set<String> isils = getIsils(record); final Set<String> collections = new HashSet<>(); for (final String isil : isils) { final String collection = isil_to_department_map.get(isil); if (collection != null) { collections.add(collection); } else { throw new IllegalArgumentException("Unknown ISIL: " + isil); } } if (collections.isEmpty()) collections.add("Unknown"); return collections; } /** * @param record the record */ public String getInstitution(final Record record) { final Set<String> collections = getCollections(record); return collections.iterator().next(); } /** * @param record the record */ public String getBSZIndexedDate(final Record record) { for (final VariableField variableField : record.getVariableFields("LOK")) { final DataField lokfield = (DataField) variableField; final List<Subfield> subfields = lokfield.getSubfields(); final Iterator<Subfield> subfieldsIter = subfields.iterator(); while (subfieldsIter.hasNext()) { Subfield subfield = subfieldsIter.next(); char formatCode = subfield.getCode(); String dataString = subfield.getData(); if (formatCode != '0' || !dataString.startsWith("938") || !subfieldsIter.hasNext()) { continue; } subfield = subfieldsIter.next(); formatCode = subfield.getCode(); if (formatCode != 'a') { continue; } dataString = subfield.getData(); if (dataString.length() != 4) { continue; } final String sub_year_text = dataString.substring(0, 2); final int sub_year = Integer.parseInt("20" + sub_year_text); final int current_year = Calendar.getInstance().get(Calendar.YEAR); final String year; if (sub_year > current_year) { // It is from the last century year = "19" + sub_year_text; } else { year = "20" + sub_year_text; } final String month = dataString.substring(2, 4); return year + "-" + month + "-01T11:00:00:000Z"; } } return null; } /** * @param record the record */ public String getPageRange(final Record record) { final String field_value = SolrIndexer.getFirstFieldVal(record, "936h"); if (field_value == null) return null; final Matcher matcher1 = PAGE_RANGE_PATTERN1.matcher(field_value); if (matcher1.matches()) return matcher1.group(1) + "-" + matcher1.group(2); final Matcher matcher2 = PAGE_RANGE_PATTERN2.matcher(field_value); if (matcher2.matches()) return matcher2.group(1) + "-" + matcher2.group(2); final Matcher matcher3 = PAGE_RANGE_PATTERN3.matcher(field_value); if (matcher3.matches()) return matcher3.group(1) + "-"; return null; } /** * @param record the record */ public String getContainerYear(final Record record) { final String field_value = SolrIndexer.getFirstFieldVal(record, "936j"); if (field_value == null) return null; final Matcher matcher = YEAR_PATTERN.matcher(field_value); return matcher.matches() ? matcher.group(1) : null; } /** * @param record the record */ public String getContainerVolume(final Record record) { final String field_value = SolrIndexer.getFirstFieldVal(record, "936d"); if (field_value == null) return null; final Matcher matcher = VOLUME_PATTERN.matcher(field_value); return matcher.matches() ? matcher.group(1) : null; } /** * @param record the record */ public Set<String> getPhysicalType(final Record record) { final Set<String> results = new TreeSet<>(); for (final DataField data_field : record.getDataFields()) { if (!data_field.getTag().equals("935")) continue; final List<Subfield> physical_code_subfields = data_field.getSubfields('b'); for (final Subfield physical_code_subfield : physical_code_subfields) { final String physical_code = physical_code_subfield.getData(); if (phys_code_to_full_name_map.containsKey(physical_code)) results.add(phys_code_to_full_name_map.get(physical_code)); else System.err.println("in TuelibMixin.getPhysicalType: can't map \"" + physical_code + "\"!"); } } return results; } /** * param record the record */ public Set<String> getAuthor2AndRole(final Record record) { final Set<String> results = new TreeSet<>(); for (final DataField data_field : record.getDataFields()) { if (!data_field.getTag().equals("700")) continue; // Fixme: Query other author2 fields final String author2 = (data_field.getSubfield('a') != null) ? data_field.getSubfield('a').getData() : ""; final String author2role = (data_field.getSubfield('e') != null) ? data_field.getSubfield('e').getData() : ""; final StringBuilder author2AndRole = new StringBuilder(); if (author2 != "" && author2role != "") { author2AndRole.append(author2); author2AndRole.append("$"); author2AndRole.append(author2role); results.add(author2AndRole.toString()); } } return results; } public Set<String> getValuesOrUnassigned(final Record record, final String fieldSpecs) { final Set<String> values = SolrIndexer.getFieldList(record, fieldSpecs); if (values.isEmpty()) { values.add("[Unassigned]"); } return values; } public String getFirstValueOrUnassigned(final Record record, final String fieldSpecs) { final Set<String> values = SolrIndexer.getFieldList(record, fieldSpecs); if (values.isEmpty()) { values.add("[Unassigned]"); } return values.iterator().next(); } /** * Get all available dates from the record. * * @param record MARC record * @return set of dates */ public Set<String> getDates(final Record record) { final Set<String> dates = new LinkedHashSet<>(); final List<VariableField> list534 = record.getVariableFields("534"); for (final VariableField vf : list534) { final DataField df = (DataField) vf; final List<Subfield> currentDates = df.getSubfields('c'); for (final Subfield sf : currentDates) { final String currentDateStr = Utils.cleanDate(sf.getData()); dates.add(currentDateStr); } } if (!dates.isEmpty()) { return dates; } final List<VariableField> list260 = record.getVariableFields("260"); for (final VariableField vf : list260) { final DataField df = (DataField) vf; final List<Subfield> currentDates = df.getSubfields('c'); for (final Subfield sf : currentDates) { final String currentDateStr = Utils.cleanDate(sf.getData()); dates.add(currentDateStr); } } // Now track down relevant RDA-style 264c dates; we only care about // publication dates are present). final Set<String> pubDates = new LinkedHashSet<>(); final Set<String> copyDates = new LinkedHashSet<>(); final List<VariableField> list264 = record.getVariableFields("264"); for (final VariableField vf : list264) { final DataField df = (DataField) vf; final List<Subfield> currentDates = df.getSubfields('c'); for (final Subfield sf : currentDates) { final String currentDateStr = Utils.cleanDate(sf.getData()); final char ind2 = df.getIndicator2(); switch (ind2) { case '1': pubDates.add(currentDateStr); break; case '4': copyDates.add(currentDateStr); break; } } } if (!pubDates.isEmpty()) { dates.addAll(pubDates); } else if (!copyDates.isEmpty()) { dates.addAll(copyDates); } return dates; } /** * Get the earliest publication date from the record. * * Fix for NullPointerException! * * @param record MARC record * @return earliest date */ public String getFirstDate(final Record record) { String result = null; final Set<String> dates = getDates(record); for (final String current : dates) { if (result == null || current != null && Integer.parseInt(current) < Integer.parseInt(result)) { result = current; } } return result; } public String isSuperiorWork(final Record record) { return Boolean.toString(record.getVariableField("SPR") != null); } private static String currentYear = null; /** @return the last two digits of the current year. */ private static String getCurrentYear() { if (currentYear == null) { final DateFormat df = new SimpleDateFormat("yy"); currentYear = df.format(Calendar.getInstance().getTime()); } return currentYear; } /** @brief Extracts the date (YYMMDD) that the record was created from a part of the 008 field. */ public String getRecordingDate(final Record record) { final ControlField _008_field = (ControlField)record.getVariableField("008"); final String fieldContents = _008_field.getData(); final StringBuilder iso8601_date = new StringBuilder(10); iso8601_date.append(fieldContents.substring(0, 2).compareTo(getCurrentYear()) > 0 ? "19" :"20"); iso8601_date.append(fieldContents.substring(0, 2)); iso8601_date.append('-'); iso8601_date.append(fieldContents.substring(2, 4)); iso8601_date.append('-'); iso8601_date.append(fieldContents.substring(4, 6)); iso8601_date.append("T00:00:00Z"); return iso8601_date.toString(); } }
package rxjava2; import io.reactivex.Observable; class Changex { private final int id; public Changex(int id) { this.id = id; } public Eventx two(Changex c) { return new Eventx(c); } } class Eventx { private final Changex changex; public Eventx(Changex c) { this.changex = c; } } class ComplexScanWith { public static void main(String[] args) { } public void work() { Observable.just(new Changex(10)) .scanWith(this::one, Eventx::two) .subscribe(); } public Eventx one() { Changex c = new Changex(21); return new Eventx(c); } }
package de.unituebingen.ub.ubtools.solrmarcMixin; import org.marc4j.marc.ControlField; import org.marc4j.marc.DataField; import org.marc4j.marc.Record; import org.marc4j.marc.Subfield; import org.marc4j.marc.VariableField; import org.solrmarc.index.SolrIndexer; import org.solrmarc.index.SolrIndexerMixin; import org.solrmarc.tools.Utils; import java.util.*; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TuelibMixin extends SolrIndexerMixin { private final static Logger logger = Logger.getLogger(TuelibMixin.class.getName()); /** * Returns either a Set<String> of parent (URL + colon + material type). URLs are taken from 856$u and material * types from 856$3, 856$z or 856$x. For missing type subfields the text "Unbekanntes Material" will be used. * Furthermore 024$2 will be checked for "doi". If we find this we generate a URL with a DOI resolver from the * DOI in 024$a and set the "material type" to "DOI Link". * * @param record the record * @return A, possibly empty, Set<String> containing the URL/material-type pairs. */ private final static String UNKNOWN_MATERIAL_TYPE = "Unbekanntes Material"; private final static Pattern EXTRACTION_PATTERN = Pattern.compile("^\\([^)]+\\)(.+)$"); // TODO: This should be in a translation mapping file private final static HashMap<String, String> isil_to_department_map = new HashMap<String, String>() { { this.put("Unknown", "Unknown"); this.put("DE-21", "Universit\u00E4tsbibliothek T\u00FCbingen"); this.put("DE-21-1", "Universit\u00E4t T\u00FCbingen, Klinik f\u00FCr Psychatrie und Psychologie"); this.put("DE-21-3", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Toxikologie und Pharmakologie"); this.put("DE-21-4", "Universit\u00E4t T\u00FCbingen, Universit\u00E4ts-Augenklinik"); this.put("DE-21-10", "Universit\u00E4tsbibliothek T\u00FCbingen, Bereichsbibliothek Geowissenschaften"); this.put("DE-21-11", "Universit\u00E4tsbibliothek T\u00FCbingen, Bereichsbibliothek Schloss Nord"); this.put("DE-21-14", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Ur- und Fr\u00FChgeschichte und Arch\u00E4ologie des Mittelalters, Abteilung j\u00FCngere Urgeschichte und Fr\u00FChgeschichte + Abteilung f\u00FCr Arch\u00E4ologie des Mittelalters"); this.put("DE-21-17", "Universit\u00E4t T\u00FCbingen, Geographisches Institut"); this.put("DE-21-18", "Universit\u00E4t T\u00FCbingen, Universit\u00E4ts-Hautklinik"); this.put("DE-21-19", "Universit\u00E4t T\u00FCbingen, Wirtschaftswissenschaftliches Seminar"); this.put("DE-21-20", "Universit\u00E4t T\u00FCbingen, Frauenklinik"); this.put("DE-21-21", "Universit\u00E4t T\u00FCbingen, Universit\u00E4ts-Hals-Nasen-Ohrenklinik, Bibliothek"); this.put("DE-21-22", "Universit\u00E4t T\u00FCbingen, Kunsthistorisches Institut"); this.put("DE-21-23", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Pathologie"); this.put("DE-21-24", "Universit\u00E4t T\u00FCbingen, Juristisches Seminar"); this.put("DE-21-25", "Universit\u00E4t T\u00FCbingen, Musikwissenschaftliches Institut"); this.put("DE-21-26", "Universit\u00E4t T\u00FCbingen, Anatomisches Institut"); this.put("DE-21-27", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Anthropologie und Humangenetik"); this.put("DE-21-28", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Astronomie und Astrophysik, Abteilung Astronomie"); this.put("DE-21-31", "Universit\u00E4t T\u00FCbingen, Evangelisch-theologische Fakult\u00E4t"); this.put("DE-21-32a", "Universit\u00E4t T\u00FCbingen, Historisches Seminar, Abteilung f\u00FCr Alte Geschichte"); this.put("DE-21-32b", "Universit\u00E4t T\u00FCbingen, Historisches Seminar, Abteilung f\u00FCr Mittelalterliche Geschichte"); this.put("DE-21-32c", "Universit\u00E4t T\u00FCbingen, Historisches Seminar, Abteilung f\u00FCr Neuere Geschichte"); this.put("DE-21-34", "Universit\u00E4t T\u00FCbingen, Asien-Orient-Institut, Abteilung f\u00FCr Indologie und Vergleichende Religionswissenschaft"); this.put("DE-21-35", "Universit\u00E4t T\u00FCbingen, Katholisch-theologische Fakult\u00E4t"); this.put("DE-21-39", "Universit\u00E4t T\u00FCbingen, Fachbibliothek Mathematik und Physik / Bereich Mathematik"); this.put("DE-21-37", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Sportwissenschaft"); this.put("DE-21-42", "Universit\u00E4t T\u00FCbingen, Asien-Orient-Institut, Abteilung f\u00FCr Orient- uns Islamwissenschaft"); this.put("DE-21-43", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Erziehungswissenschaft"); this.put("DE-21-45", "Universit\u00E4t T\u00FCbingen, Philologisches Seminar"); this.put("DE-21-46", "Universit\u00E4t T\u00FCbingen, Philosophisches Seminar"); this.put("DE-21-50", "Universit\u00E4t T\u00FCbingen, Physiologisches Institut"); this.put("DE-21-51", "Universit\u00E4t T\u00FCbingen, Psychologisches Institut"); this.put("DE-21-52", "Universit\u00E4t T\u00FCbingen, Ludwig-Uhland-Institut f\u00FCr Empirische Kulturwissenschaft"); this.put("DE-21-53", "Universit\u00E4t T\u00FCbingen, Asien-Orient-Institut, Abteilung f\u00FCr Ethnologie"); this.put("DE-21-54", "Universit\u00E4t T\u00FCbingen, Universit\u00E4tsklinik f\u00FCr Zahn-, Mund- und Kieferheilkunde"); this.put("DE-21-58", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Politikwissenschaft"); this.put("DE-21-62", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Osteurop\u00E4ische Geschichte und Landeskunde"); this.put("DE-21-63", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Tropenmedizin"); this.put("DE-21-64", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Geschichtliche Landeskunde und Historische Hilfswissenschaften"); this.put("DE-21-65", "Universit\u00E4t T\u00FCbingen, Universit\u00E4ts-Apotheke"); this.put("DE-21-74", "Universit\u00E4t T\u00FCbingen, Zentrum f\u00FCr Informations-Technologie"); this.put("DE-21-78", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Medizinische Biometrie"); this.put("DE-21-81", "Universit\u00E4t T\u00FCbingen, Inst. f. Astronomie und Astrophysik/Abt. Geschichte der Naturwiss."); this.put("DE-21-85", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Soziologie"); this.put("DE-21-86", "Universit\u00E4t T\u00FCbingen, Zentrum f\u00FCr Datenverarbeitung"); this.put("DE-21-89", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Arbeits- und Sozialmedizin"); this.put("DE-21-92", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Gerichtliche Medizin"); this.put("DE-21-93", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Ethik und Geschichte der Medizin"); this.put("DE-21-95", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Hirnforschung"); this.put("DE-21-98", "Universit\u00E4t T\u00FCbingen, Fachbibliothek Mathematik und Physik / Bereich Physik"); this.put("DE-21-99", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Ur- und Fr\u00FChgeschichte und Arch\u00E4ologie des Mittelalters, Abteilung f\u00FCr \u00E4ltere Urgeschichteund Quart\u00E4r\u00F6kologie"); this.put("DE-21-106", "Universit\u00E4t T\u00FCbingen, Seminar f\u00FCr Zeitgeschichte"); this.put("DE-21-108", "Universit\u00E4t T\u00FCbingen, Fakult\u00E4tsbibliothek Neuphilologie"); this.put("DE-21-109", "Universit\u00E4t T\u00FCbingen, Asien-Orient-Institut, Abteilung f\u00FCr Sinologie und Koreanistik"); this.put("DE-21-110", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Kriminologie"); this.put("DE-21-112", "Universit\u00E4t T\u00FCbingen, Fakult\u00E4t f\u00FCr Biologie, Bibliothek"); this.put("DE-21-116", "Universit\u00E4t T\u00FCbingen, Zentrum f\u00FCr Molekularbiologie der Pflanzen, Forschungsgruppe Pflanzenbiochemie"); this.put("DE-21-117", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Medizinische Informationsverarbeitung"); this.put("DE-21-118", "Universit\u00E4t T\u00FCbingen, Universit\u00E4ts-Archiv"); this.put("DE-21-119", "Universit\u00E4t T\u00FCbingen, Wilhelm-Schickard-Institut f\u00FCr Informatik"); this.put("DE-21-120", "Universit\u00E4t T\u00FCbingen, Asien-Orient-Institut, Abteilung f\u00FCr Japanologie"); this.put("DE-21-121", "Universit\u00E4t T\u00FCbingen, Internationales Zentrum f\u00FCr Ethik in den Wissenschaften"); this.put("DE-21-123", "Universit\u00E4t T\u00FCbingen, Medizinbibliothek"); this.put("DE-21-124", "Universit\u00E4t T\u00FCbingen, Institut f. Medizinische Virologie und Epidemiologie d. Viruskrankheiten"); this.put("DE-21-126", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Medizinische Mikrobiologie und Hygiene"); this.put("DE-21-203", "Universit\u00E4t T\u00FCbingen, Sammlung Werner Schweikert - Archiv der Weltliteratur"); this.put("DE-21-205", "Universit\u00E4t T\u00FCbingen, Zentrum f\u00FCr Islamische Theologie"); this.put("DE-Frei85", "Freiburg MPI Ausl\u00E4nd.Recht, Max-Planck-Institut f\u00FCr ausl\u00E4ndisches und internationales Strafrecht"); } }; private final static Pattern PAGE_RANGE_PATTERN1 = Pattern.compile("\\s*(\\d+)\\s*-\\s*(\\d+)$"); private final static Pattern PAGE_RANGE_PATTERN2 = Pattern.compile("\\s*\\[(\\d+)\\]\\s*-\\s*(\\d+)$"); private final static Pattern PAGE_RANGE_PATTERN3 = Pattern.compile("\\s*(\\d+)\\s*ff"); private final static Pattern YEAR_PATTERN = Pattern.compile("(\\d\\d\\d\\d)"); private final static Pattern VOLUME_PATTERN = Pattern.compile("^\\s*(\\d+)$"); // Map used by getPhysicalType(). private static final Map<String, String> phys_code_to_full_name_map; static { Map<String, String> tempMap = new HashMap<>(); tempMap.put("arbtrans", "Transparency"); tempMap.put("blindendr", "Braille"); tempMap.put("bray", "Blu-ray Disc"); tempMap.put("cdda", "CD"); tempMap.put("ckop", "Microfiche"); tempMap.put("cofz", "Online Resource"); tempMap.put("crom", "CD-ROM"); tempMap.put("dias", "Slides"); tempMap.put("disk", "Diskette"); tempMap.put("druck", "Printed Material"); tempMap.put("dvda", "Audio DVD"); tempMap.put("dvdr", "DVD-ROM"); tempMap.put("dvdv", "Video DVD"); tempMap.put("gegenst", "Physical Object"); tempMap.put("handschr", "Longhand Text"); tempMap.put("kunstbl", "Artistic Works on Paper"); tempMap.put("lkop", "Mircofilm"); tempMap.put("medi", "Multiple Media Types"); tempMap.put("scha", "Record"); tempMap.put("skop", "Microform"); tempMap.put("sobildtt", "Audiovisual Carriers"); tempMap.put("soerd", "Carriers of Other Electronic Data"); tempMap.put("sott", "Carriers of Other Audiodata"); tempMap.put("tonbd", "Audiotape"); tempMap.put("tonks", "Audiocasette"); tempMap.put("vika", "Videocasette"); phys_code_to_full_name_map = Collections.unmodifiableMap(tempMap); } private Set<String> isils_cache = null; private Set<String> reviews_cache = null; private Set<String> reviewedRecords_cache = null; @Override public void perRecordInit(final Record record) { reviews_cache = reviewedRecords_cache = isils_cache = null; } /** * Determine Record Title * * @param record the record * @return String nicely formatted title */ public String getTitle(final Record record) { final DataField title = (DataField) record.getVariableField("245"); if (title == null) return null; final String title_a = (title.getSubfield('a') == null) ? null : title.getSubfield('a').getData(); final String title_b = (title.getSubfield('b') == null) ? null : title.getSubfield('b').getData(); if (title_a == null && title_b == null) return null; final StringBuilder complete_title = new StringBuilder(); if (title_a == null) complete_title.append(Utils.cleanData(title_b)); else if (title_b == null) complete_title.append(Utils.cleanData(title_a)); else { // Neither title_a nor title_b are null. complete_title.append(Utils.cleanData(title_a)); complete_title.append(" : "); complete_title.append(Utils.cleanData(title_b)); } final String title_n = (title.getSubfield('n') == null) ? null : title.getSubfield('n').getData(); if (title_n != null) { complete_title.append(' '); complete_title.append(Utils.cleanData(title_n)); } return complete_title.toString(); } /** * Determine Record Title Subfield * * @param record the record * @param subfield_code * @return String nicely formatted title subfield */ public String getTitleSubfield(final Record record, final String subfield_code) { final DataField title = (DataField) record.getVariableField("245"); if (title == null) return null; final Subfield subfield = title.getSubfield(subfield_code.charAt(0)); if (subfield == null) return null; final String subfield_data = subfield.getData(); if (subfield_data == null) return null; return Utils.cleanData(subfield_data); } /** * get the local subjects from LOK-tagged fields and get subjects from 936k and 689a subfields * <p/> * LOK = Field * |0 689 = Subfield * |a Imperialismus = Subfield with local subject * * @param record the record * @return Set of local subjects */ public Set<String> getAllTopics(final Record record) { final Set<String> topics = SolrIndexer.getAllSubfields(record, "600:610:611:630:650:653:656:689a:936a", " "); for (final VariableField variableField : record.getVariableFields("LOK")) { final DataField lokfield = (DataField) variableField; final Subfield subfield0 = lokfield.getSubfield('0'); if (subfield0 == null || !subfield0.getData().equals("689 ")) { continue; } final Subfield subfieldA = lokfield.getSubfield('a'); if (subfieldA == null || subfieldA.getData().length() <= 1) { continue; } topics.add(subfieldA.getData()); } return topics; } /** * Hole das Sachschlagwort aus 689|a (wenn 689|d != z oder f) * * @param record the record * @return Set "topic_facet" */ public Set<String> getFacetTopics(final Record record) { final Set<String> result = SolrIndexer.getAllSubfields(record, "600x:610x:611x:630x:648x:650a:650x:651x:655x", " "); String topic_string; // Check 689 subfield a and d final List<VariableField> fields = record.getVariableFields("689"); if (fields != null) { DataField dataField; for (final VariableField variableField : fields) { dataField = (DataField) variableField; final Subfield subfieldD = dataField.getSubfield('d'); if (subfieldD == null) { continue; } topic_string = subfieldD.getData().toLowerCase(); if (topic_string.equals("f") || topic_string.equals("z")) { continue; } final Subfield subfieldA = dataField.getSubfield('a'); if (subfieldA != null) { result.add(subfieldA.getData()); } } } return result; } /** * Finds the first subfield which is nonempty. * * @param dataField the data field * @param subfieldIDs the subfield identifiers to search for * @return a nonempty subfield or null */ private Subfield getFirstNonEmptySubfield(final DataField dataField, final char... subfieldIDs) { for (final char subfieldID : subfieldIDs) { for (final Subfield subfield : dataField.getSubfields(subfieldID)) { if (subfield != null && subfield.getData() != null && !subfield.getData().isEmpty()) { return subfield; } } } return null; } public Set<String> getUrlsAndMaterialTypes(final Record record) { final Set<String> nonUnknownMaterialTypeURLs = new HashSet<String>(); final Map<String, Set<String>> materialTypeToURLsMap = new TreeMap<String, Set<String>>(); final Set<String> urls_and_material_types = new LinkedHashSet<>(); for (final VariableField variableField : record.getVariableFields("856")) { final DataField field = (DataField) variableField; final Subfield materialTypeSubfield = getFirstNonEmptySubfield(field, '3', 'z', 'y', 'x'); final String materialType = (materialTypeSubfield == null) ? UNKNOWN_MATERIAL_TYPE : materialTypeSubfield.getData(); // Extract all links from u-subfields and resolve URNs: for (final Subfield subfield_u : field.getSubfields('u')) { Set<String> URLs = materialTypeToURLsMap.get(materialType); if (URLs == null) { URLs = new HashSet<String>(); materialTypeToURLsMap.put(materialType, URLs); } final String rawLink = subfield_u.getData(); final String link; if (rawLink.startsWith("urn:")) link = "https://nbn-resolving.org/" + rawLink; else if (rawLink.startsWith("http://nbn-resolving.de")) link = "https://nbn-resolving.org/" + rawLink.substring(23); // Replace HTTP w/ HTTPS. else if (rawLink.startsWith("http://nbn-resolving.org")) link = "https://nbn-resolving.org/" + rawLink.substring(24); // Replace HTTP w/ HTTPS. else link = rawLink; URLs.add(link); if (!materialType.equals(UNKNOWN_MATERIAL_TYPE)) { nonUnknownMaterialTypeURLs.add(link); } } } // Remove duplicates while favouring SWB and, if not present, DNB links: for (final String material_type : materialTypeToURLsMap.keySet()) { if (material_type.equals(UNKNOWN_MATERIAL_TYPE)) { for (final String url : materialTypeToURLsMap.get(material_type)) { if (!nonUnknownMaterialTypeURLs.contains(url)) { urls_and_material_types.add(url + ":" + UNKNOWN_MATERIAL_TYPE); } } } else { // Locate SWB and DNB URLs, if present: String preferredURL = null; for (final String url : materialTypeToURLsMap.get(material_type)) { if (url.startsWith("http://swbplus.bsz-bw.de")) { preferredURL = url; break; } else if (url.startsWith("http://d-nb.info")) preferredURL = url; } if (preferredURL != null) urls_and_material_types.add(preferredURL + ":" + material_type); else { // Add the kitchen sink. for (final String url : materialTypeToURLsMap.get(material_type)) urls_and_material_types.add(url + ":" + material_type); } } } // Handle DOI's: for (final VariableField variableField : record.getVariableFields("024")) { final DataField field = (DataField) variableField; final Subfield subfield_2 = field.getSubfield('2'); if (subfield_2 != null && subfield_2.getData().equals("doi")) { final Subfield subfield_a = field.getSubfield('a'); if (subfield_a != null) { final String url = "https://doi.org/" + subfield_a.getData(); urls_and_material_types.add(url + ":DOI"); } } } return urls_and_material_types; } /** * Returns either a Set<String> of parent (ID + colon + parent title). Only IDs w/o titles will not be returned, * instead a warning will be emitted on stderr. * * @param record the record * @return A, possibly empty, Set<String> containing the ID/title pairs. */ public Set<String> getContainerIdsWithTitles(final Record record) { final Set<String> containerIdsAndTitles = new TreeSet<>(); for (final String tag : new String[]{"800", "810", "830", "773"}) { for (final VariableField variableField : record.getVariableFields(tag)) { final DataField field = (DataField) variableField; final Subfield titleSubfield = getFirstNonEmptySubfield(field, 't', 'a'); final Subfield volumeSubfield = field.getSubfield('v'); final Subfield idSubfield = field.getSubfield('w'); if (titleSubfield == null || idSubfield == null) continue; final Matcher matcher = EXTRACTION_PATTERN.matcher(idSubfield.getData()); if (!matcher.matches()) continue; final String parentId = matcher.group(1); containerIdsAndTitles.add(parentId + (char) 0x1F + titleSubfield.getData() + (char) 0x1F + (volumeSubfield == null ? "" : volumeSubfield.getData())); } } return containerIdsAndTitles; } private void collectReviewsAndReviewedRecords(final Record record) { if (reviews_cache != null && reviewedRecords_cache != null) { return; } reviews_cache = new TreeSet<>(); reviewedRecords_cache = new TreeSet<>(); for (final VariableField variableField : record.getVariableFields("787")) { final DataField field = (DataField) variableField; final Subfield reviewTypeSubfield = getFirstNonEmptySubfield(field, 'i'); final Subfield reviewerSubfield = getFirstNonEmptySubfield(field, 'a'); final Subfield titleSubfield = getFirstNonEmptySubfield(field, 't'); final Subfield idSubfield = field.getSubfield('w'); if (reviewerSubfield == null || titleSubfield == null || idSubfield == null || reviewTypeSubfield == null) continue; final Matcher matcher = EXTRACTION_PATTERN.matcher(idSubfield.getData()); if (!matcher.matches()) continue; final String parentId = matcher.group(1); if (reviewTypeSubfield.getData().equals("Rezension")) { reviews_cache.add(parentId + (char) 0x1F + reviewerSubfield.getData() + (char) 0x1F + titleSubfield.getData()); } else if (reviewTypeSubfield.getData().equals("Rezension von")) { reviewedRecords_cache.add(parentId + (char) 0x1F + reviewerSubfield.getData() + (char) 0x1F + titleSubfield.getData()); } } } public Set<String> getReviews(final Record record) { collectReviewsAndReviewedRecords(record); return reviews_cache; } public Set<String> getReviewedRecords(final Record record) { collectReviewsAndReviewedRecords(record); return reviewedRecords_cache; } /** * @param record the record * @param fieldnums * @return */ public Set<String> getSuperMP(final Record record, final String fieldnums) { final Set<String> retval = new LinkedHashSet<>(); final HashMap<String, String> resvalues = new HashMap<>(); final HashMap<String, Integer> resscores = new HashMap<>(); String value; String id; Integer score; Integer cscore; String fnum; String fsfc; final String[] fields = fieldnums.split(":"); for (final String field : fields) { fnum = field.replaceAll("[a-z]+$", ""); fsfc = field.replaceAll("^[0-9]+", ""); final List<VariableField> fs = record.getVariableFields(fnum); if (fs == null) { continue; } for (final VariableField variableField : fs) { final DataField dataField = (DataField) variableField; final Subfield subfieldW = dataField.getSubfield('w'); if (subfieldW == null) { continue; } final Subfield fsubany = dataField.getSubfield(fsfc.charAt(0)); if (fsubany == null) { continue; } value = fsubany.getData().trim(); id = subfieldW.getData().replaceAll("^\\([^\\)]+\\)", ""); // Count number of commas in "value": score = value.length() - value.replace(",", "").length(); if (resvalues.containsKey(id)) { cscore = resscores.get(id); if (cscore > score) { continue; } } resvalues.put(id, value); resscores.put(id, score); } } for (final String key : resvalues.keySet()) { value = "(" + key + ")" + resvalues.get(key); retval.add(value); } return retval; } /** * get the ISILs from LOK-tagged fields * <p/> * Typical LOK-Section below a Marc21 - Title-Set of a record: * LOK |0 000 xxxxxnu a22 zn 4500 * LOK |0 001 000001376 * LOK |0 003 DE-576 * LOK |0 004 000000140 * LOK |0 005 20020725000000 * LOK |0 008 020725||||||||||||||||ger||||||| * LOK |0 014 |a 000001368 |b DE-576 * LOK |0 541 |e 76.6176 * LOK |0 852 |a DE-Sp3 * LOK |0 852 1 |c B IV 529 |9 00 * <p/> * LOK = Field * |0 852 = Subfield * |a DE-Sp3 = Subfield with ISIL * * @param record the record * @return Set of isils */ public Set<String> getIsils(final Record record) { if (isils_cache != null) { return isils_cache; } final Set<String> isils = new LinkedHashSet<>(); final List<VariableField> fields = record.getVariableFields("LOK"); if (fields != null) { for (final VariableField variableField : fields) { final DataField lokfield = (DataField) variableField; final Subfield subfield0 = lokfield.getSubfield('0'); if (subfield0 == null || !subfield0.getData().startsWith("852")) { continue; } final Subfield subfieldA = lokfield.getSubfield('a'); if (subfieldA != null) { isils.add(subfieldA.getData()); } } } if (isils.isEmpty()) { // Nothing worked! isils.add("Unknown"); } this.isils_cache = isils; return isils; } /** * @param record the record * @return */ public String isAvailableInTuebingen(final Record record) { return Boolean.toString(!record.getVariableFields("SIG").isEmpty()); } /** * get the collections from LOK-tagged fields * <p/> * Typical LOK-Section below a Marc21 - Title-Set of a record: * LOK |0 000 xxxxxnu a22 zn 4500 * LOK |0 001 000001376 * LOK |0 003 DE-576 * LOK |0 004 000000140 * LOK |0 005 20020725000000 * LOK |0 008 020725||||||||||||||||ger||||||| * LOK |0 014 |a 000001368 |b DE-576 * LOK |0 541 |e 76.6176 * LOK |0 852 |a DE-Sp3 * LOK |0 852 1 |c B IV 529 |9 00 * <p/> * LOK = Field * |0 852 = Subfield * |a DE-Sp3 = Subfield with ISIL * * @param record the record * @return Set of collections */ public Set<String> getCollections(final Record record) { final Set<String> isils = getIsils(record); final Set<String> collections = new HashSet<>(); for (final String isil : isils) { final String collection = isil_to_department_map.get(isil); if (collection != null) { collections.add(collection); } else { throw new IllegalArgumentException("Unknown ISIL: " + isil); } } if (collections.isEmpty()) collections.add("Unknown"); return collections; } /** * @param record the record */ public String getInstitution(final Record record) { final Set<String> collections = getCollections(record); return collections.iterator().next(); } /** * @param record the record */ public String getBSZIndexedDate(final Record record) { for (final VariableField variableField : record.getVariableFields("LOK")) { final DataField lokfield = (DataField) variableField; final List<Subfield> subfields = lokfield.getSubfields(); final Iterator<Subfield> subfieldsIter = subfields.iterator(); while (subfieldsIter.hasNext()) { Subfield subfield = subfieldsIter.next(); char formatCode = subfield.getCode(); String dataString = subfield.getData(); if (formatCode != '0' || !dataString.startsWith("938") || !subfieldsIter.hasNext()) { continue; } subfield = subfieldsIter.next(); formatCode = subfield.getCode(); if (formatCode != 'a') { continue; } dataString = subfield.getData(); if (dataString.length() != 4) { continue; } final String sub_year_text = dataString.substring(0, 2); final int sub_year = Integer.parseInt("20" + sub_year_text); final int current_year = Calendar.getInstance().get(Calendar.YEAR); final String year; if (sub_year > current_year) { // It is from the last century year = "19" + sub_year_text; } else { year = "20" + sub_year_text; } final String month = dataString.substring(2, 4); return year + "-" + month + "-01T11:00:00:000Z"; } } return null; } /** * @param record the record */ public String getPageRange(final Record record) { final String field_value = SolrIndexer.getFirstFieldVal(record, "936h"); if (field_value == null) return null; final Matcher matcher1 = PAGE_RANGE_PATTERN1.matcher(field_value); if (matcher1.matches()) return matcher1.group(1) + "-" + matcher1.group(2); final Matcher matcher2 = PAGE_RANGE_PATTERN2.matcher(field_value); if (matcher2.matches()) return matcher2.group(1) + "-" + matcher2.group(2); final Matcher matcher3 = PAGE_RANGE_PATTERN3.matcher(field_value); if (matcher3.matches()) return matcher3.group(1) + "-"; return null; } /** * @param record the record */ public String getContainerYear(final Record record) { final String field_value = SolrIndexer.getFirstFieldVal(record, "936j"); if (field_value == null) return null; final Matcher matcher = YEAR_PATTERN.matcher(field_value); return matcher.matches() ? matcher.group(1) : null; } /** * @param record the record */ public String getContainerVolume(final Record record) { final String field_value = SolrIndexer.getFirstFieldVal(record, "936d"); if (field_value == null) return null; final Matcher matcher = VOLUME_PATTERN.matcher(field_value); return matcher.matches() ? matcher.group(1) : null; } /** * @param record the record */ public Set<String> getPhysicalType(final Record record) { final Set<String> results = new TreeSet<>(); for (final DataField data_field : record.getDataFields()) { if (!data_field.getTag().equals("935")) continue; final List<Subfield> physical_code_subfields = data_field.getSubfields('b'); for (final Subfield physical_code_subfield : physical_code_subfields) { final String physical_code = physical_code_subfield.getData(); if (phys_code_to_full_name_map.containsKey(physical_code)) results.add(phys_code_to_full_name_map.get(physical_code)); else System.err.println("in TuelibMixin.getPhysicalType: can't map \"" + physical_code + "\"!"); } } return results; } /** * param record the record */ public Set<String> getAuthor2AndRole(final Record record) { final Set<String> results = new TreeSet<>(); for (final DataField data_field : record.getDataFields()) { if (!data_field.getTag().equals("700")) continue; // Fixme: Query other author2 fields final String author2 = (data_field.getSubfield('a') != null) ? data_field.getSubfield('a').getData() : ""; final String author2role = (data_field.getSubfield('e') != null) ? data_field.getSubfield('e').getData() : ""; final StringBuilder author2AndRole = new StringBuilder(); if (author2 != "" && author2role != "") { author2AndRole.append(author2); author2AndRole.append("$"); author2AndRole.append(author2role); results.add(author2AndRole.toString()); } } return results; } public Set<String> getValuesOrUnassigned(final Record record, final String fieldSpecs) { final Set<String> values = SolrIndexer.getFieldList(record, fieldSpecs); if (values.isEmpty()) { values.add("[Unassigned]"); } return values; } public String getFirstValueOrUnassigned(final Record record, final String fieldSpecs) { final Set<String> values = SolrIndexer.getFieldList(record, fieldSpecs); if (values.isEmpty()) { values.add("[Unassigned]"); } return values.iterator().next(); } /** * Get all available dates from the record. * * @param record MARC record * @return set of dates */ public Set<String> getDates(final Record record) { final Set<String> dates = new LinkedHashSet<>(); final List<VariableField> list534 = record.getVariableFields("534"); for (final VariableField vf : list534) { final DataField df = (DataField) vf; final List<Subfield> currentDates = df.getSubfields('c'); for (final Subfield sf : currentDates) { final String currentDateStr = Utils.cleanDate(sf.getData()); dates.add(currentDateStr); } } if (!dates.isEmpty()) { return dates; } final List<VariableField> list260 = record.getVariableFields("260"); for (final VariableField vf : list260) { final DataField df = (DataField) vf; final List<Subfield> currentDates = df.getSubfields('c'); for (final Subfield sf : currentDates) { final String currentDateStr = Utils.cleanDate(sf.getData()); dates.add(currentDateStr); } } // Now track down relevant RDA-style 264c dates; we only care about // publication dates are present). final Set<String> pubDates = new LinkedHashSet<>(); final Set<String> copyDates = new LinkedHashSet<>(); final List<VariableField> list264 = record.getVariableFields("264"); for (final VariableField vf : list264) { final DataField df = (DataField) vf; final List<Subfield> currentDates = df.getSubfields('c'); for (final Subfield sf : currentDates) { final String currentDateStr = Utils.cleanDate(sf.getData()); final char ind2 = df.getIndicator2(); switch (ind2) { case '1': pubDates.add(currentDateStr); break; case '4': copyDates.add(currentDateStr); break; } } } if (!pubDates.isEmpty()) { dates.addAll(pubDates); } else if (!copyDates.isEmpty()) { dates.addAll(copyDates); } return dates; } /** * Get the earliest publication date from the record. * * Fix for NullPointerException! * * @param record MARC record * @return earliest date */ public String getFirstDate(final Record record) { String result = null; final Set<String> dates = getDates(record); for (final String current : dates) { if (result == null || current != null && Integer.parseInt(current) < Integer.parseInt(result)) { result = current; } } return result; } public String isSuperiorWork(final Record record) { return Boolean.toString(record.getVariableField("SPR") != null); } /** @brief Extracts the date (YYMMDD) that the record was created from a part of the 008 field. */ public String getRecordingDate(final Record record) { final ControlField _008_field = (ControlField)record.getVariableField("008"); return _008_field.getData().substring(0, 6); } }
package de.unituebingen.ub.ubtools.solrmarcMixin; import org.marc4j.marc.DataField; import org.marc4j.marc.Record; import org.marc4j.marc.Subfield; import org.marc4j.marc.VariableField; import org.solrmarc.index.SolrIndexer; import org.solrmarc.index.SolrIndexerMixin; import org.solrmarc.tools.Utils; import java.util.*; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TuelibMixin extends SolrIndexerMixin { private final static Logger logger = Logger.getLogger(TuelibMixin.class.getName()); private Set<String> isils_cache = null; @Override public void perRecordInit(final Record record) { isils_cache = null; } /** * Determine Record Title * * @param record the record * @return String nicely formatted title */ public String getTitle(final Record record) { final DataField title = (DataField) record.getVariableField("245"); if (title == null) return null; final String title_a = (title.getSubfield('a') == null) ? null : title.getSubfield('a').getData(); final String title_b = (title.getSubfield('b') == null) ? null : title.getSubfield('b').getData(); if (title_a == null && title_b == null) return null; StringBuilder complete_title = new StringBuilder(); if (title_a == null) complete_title.append(Utils.cleanData(title_b)); else if (title_b == null) complete_title.append(Utils.cleanData(title_a)); else { // Neither title_a nor title_b are null. complete_title.append(Utils.cleanData(title_a)); complete_title.append(' '); complete_title.append(Utils.cleanData(title_b)); } final String title_c = (title.getSubfield('c') == null) ? null : title.getSubfield('c').getData(); if (title_c != null) { complete_title.append(' '); complete_title.append(Utils.cleanData(title_c)); } final String title_n = (title.getSubfield('n') == null) ? null : title.getSubfield('n').getData(); if (title_n != null) { complete_title.append(' '); complete_title.append(Utils.cleanData(title_n)); } return complete_title.toString(); } /** * Determine Record Title Subfield * * @param record the record * @param subfield_code * @return String nicely formatted title subfield */ public String getTitleSubfield(final Record record, final String subfield_code) { final DataField title = (DataField) record.getVariableField("245"); if (title == null) return null; final Subfield subfield = title.getSubfield(subfield_code.charAt(0)); if (subfield == null) return null; final String subfield_data = subfield.getData(); if (subfield_data == null) return null; return Utils.cleanData(subfield_data); } /** * get the local subjects from LOK-tagged fields and get subjects from 936k and 689a subfields * <p/> * LOK = Field * |0 689 = Subfield * |a Imperialismus = Subfield with local subject * * @param record the record * @return Set of local subjects */ public Set<String> getAllTopics(final Record record) { final Set<String> topics = SolrIndexer.getAllSubfields(record, "600:610:611:630:650:653:656:689a:936a", " "); for (final VariableField variableField : record.getVariableFields("LOK")) { final DataField lokfield = (DataField) variableField; final Subfield subfield0 = lokfield.getSubfield('0'); if (subfield0 == null || !subfield0.getData().equals("689")) { continue; } final Subfield subfieldA = lokfield.getSubfield('a'); if (subfieldA == null || subfieldA.getData().length() <= 1) { continue; } topics.add(subfieldA.getData()); } return topics; } /** * Hole das Sachschlagwort aus 689|a (wenn 689|d != z oder f) * * @param record the record * @return Set "topic_facet" */ public Set<String> getFacetTopics(final Record record) { final Set<String> result = SolrIndexer.getAllSubfields(record, "600x:610x:611x:630x:648x:650a:650x:651x:655x", " "); String topic_string; // Check 689 subfield a and d final List<VariableField> fields = record.getVariableFields("689"); if (fields != null) { DataField dataField; for (final VariableField variableField : fields) { dataField = (DataField) variableField; final Subfield subfieldD = dataField.getSubfield('d'); if (subfieldD == null) { continue; } topic_string = subfieldD.getData().toLowerCase(); if (topic_string.equals("f") || topic_string.equals("z")) { continue; } final Subfield subfieldA = dataField.getSubfield('a'); if (subfieldA != null) { result.add(subfieldA.getData()); } } } return result; } /** * Returns either a Set<String> of parent (URL + colon + material type). URLs are taken from 856$u and material * types from 856$3, 856$z or 856$x. For missing type subfields the text "Unbekanntes Material" will be used. * Furthermore 024$2 will be checked for "doi". If we find this we generate a URL with a DOI resolver from the * DOI in 024$a and set the "material type" to "DOI Link". * * @param record the record * @return A, possibly empty, Set<String> containing the URL/material-type pairs. */ public Set<String> getUrlsAndMaterialTypes(final Record record) { final Set<String> urls_and_material_types = new LinkedHashSet<>(); for (final VariableField variableField : record.getVariableFields("856")) { final DataField field = (DataField) variableField; final Subfield subfield_3 = field.getSubfield('3'); final String material_type; if (subfield_3 != null) material_type = subfield_3.getData(); else { final Subfield subfield_z = field.getSubfield('z'); if (subfield_z != null) material_type = subfield_z.getData(); else { final Subfield subfield_x = field.getSubfield('x'); material_type = (subfield_x == null) ? "Unbekanntes Material" : subfield_x.getData(); } } for (final Subfield subfield_u : field.getSubfields('u')) urls_and_material_types.add(subfield_u.getData() + ":" + material_type); } // Handle DOI's: for (final VariableField variableField : record.getVariableFields("024")) { final DataField field = (DataField) variableField; final Subfield subfield_2 = field.getSubfield('2'); if (subfield_2 != null && subfield_2.getData().equals("doi")) { final Subfield subfield_a = field.getSubfield('a'); if (subfield_a != null) { final String url = "https://doi.org/" + subfield_a.getData(); urls_and_material_types.add(url + ":DOI"); } } } return urls_and_material_types; } private final static Pattern EXTRACTION_PATTERN = Pattern.compile("^\\([^)]+\\)(\\.+)$"); /** * Returns either a Set<String> of parent (ID + colon + parent title). Only IDs w/o titles will not be returned, * instead a warning will be emitted on stderr. * * @param record the record * @param fields_and_subfields fields_and_subfields, a colon-separated "list" of field tags where each * tag must be followed by two subfield codes e.g. "800aw:810aw:830aw". * The first subfield code for each tag must indicate the "title" subfield * and the second subfield code the ID subfield. * @param optionalFieldExtractionRegex * @return A, possibly empty, Set<String> containing the ID/title pairs. */ public Set<String> getContainerIdsWithTitles(final Record record) { final Set<String> containerIdsAndTitles = new TreeSet<String>(); for (final String tag : new String[] { "800", "810", "830", "773" }) { for (final VariableField variableField : record.getVariableFields(tag)) { final DataField field = (DataField) variableField; final Subfield titleSubfield = field.getSubfield('t'); final Subfield volumeSubfield = field.getSubfield('v'); final Subfield idSubfield = field.getSubfield('w'); if (titleSubfield == null || idSubfield == null) continue; final Matcher matcher = EXTRACTION_PATTERN.matcher(idSubfield.getData()); if (!matcher.matches()) continue; final String parentId = matcher.group(1); containerIdsAndTitles.add(parentId + "\u001F" + titleSubfield.getData() + "\u001F" + (volumeSubfield == null ? "" : volumeSubfield.getData())); } } return containerIdsAndTitles; } /** * Returns either a Set<String> of parent (ID + colon + child title). * * @param record the record * @param fieldsAndSubfields fieldsAndSubfields, a colon-separated "list" of field tags where each * tag must be followed by two subfield codes e.g. "800aw:810aw:830aw". * The first subfield code for each tag must indicate the "title" subfield * and the second subfield code the ID subfield. * @return A, possibly empty, Set<String> containing the ID/title pairs. */ public Set<String> getContaineeIdsWithTitles(final Record record, final String fieldsAndSubfields) { final String[] fieldsAndSubfieldsArray = fieldsAndSubfields.split(":"); if (fieldsAndSubfieldsArray.length == 0) { throw new IllegalArgumentException("Missing fields and subfields to select!"); } final Set<String> containerIdsAndTitles = new LinkedHashSet<>(); for (final String fieldAndSubfield : fieldsAndSubfieldsArray) { final char idSubfieldCode = fieldAndSubfield.charAt(3); final char titleSubfieldCode = fieldAndSubfield.charAt(4); final String tag = fieldAndSubfield.substring(0, 3); for (final VariableField variableField : record.getVariableFields(tag)) { final DataField dataField = (DataField) variableField; final Subfield idSubfield = dataField.getSubfield(idSubfieldCode); final Subfield titleSubfield = dataField.getSubfield(titleSubfieldCode); if (idSubfield == null || titleSubfield == null) { if (idSubfield != null || titleSubfield != null) { logger.fine("Weird, either title or ID is missing!"); } continue; } containerIdsAndTitles.add(idSubfield.getData() + ":" + titleSubfield.getData()); } } return containerIdsAndTitles; } /** * @param record the record * @param fieldnums * @return */ public Set<String> getSuperMP(final Record record, final String fieldnums) { final Set<String> retval = new LinkedHashSet<>(); final HashMap<String, String> resvalues = new HashMap<>(); final HashMap<String, Integer> resscores = new HashMap<>(); String value; String id; Integer score; Integer cscore; String fnum; String fsfc; final String[] fields = fieldnums.split(":"); for (final String field : fields) { fnum = field.replaceAll("[a-z]+$", ""); fsfc = field.replaceAll("^[0-9]+", ""); final List<VariableField> fs = record.getVariableFields(fnum); if (fs == null) { continue; } for (final VariableField variableField : fs) { final DataField dataField = (DataField) variableField; final Subfield subfieldW = dataField.getSubfield('w'); if (subfieldW == null) { continue; } final Subfield fsubany = dataField.getSubfield(fsfc.charAt(0)); if (fsubany == null) { continue; } value = fsubany.getData().trim(); id = subfieldW.getData().replaceAll("^\\([^\\)]+\\)", ""); // Count number of commas in "value": score = value.length() - value.replace(",", "").length(); if (resvalues.containsKey(id)) { cscore = resscores.get(id); if (cscore > score) { continue; } } resvalues.put(id, value); resscores.put(id, score); } } for (final String key : resvalues.keySet()) { value = "(" + key + ")" + resvalues.get(key); retval.add(value); } return retval; } /** * get the ISILs from LOK-tagged fields * <p/> * Typical LOK-Section below a Marc21 - Title-Set of a record: * LOK |0 000 xxxxxnu a22 zn 4500 * LOK |0 001 000001376 * LOK |0 003 DE-576 * LOK |0 004 000000140 * LOK |0 005 20020725000000 * LOK |0 008 020725||||||||||||||||ger||||||| * LOK |0 014 |a 000001368 |b DE-576 * LOK |0 541 |e 76.6176 * LOK |0 852 |a DE-Sp3 * LOK |0 852 1 |c B IV 529 |9 00 * <p/> * LOK = Field * |0 852 = Subfield * |a DE-Sp3 = Subfield with ISIL * * @param record the record * @return Set of isils */ public Set<String> getIsils(final Record record) { if (isils_cache != null) { return isils_cache; } final Set<String> isils = new LinkedHashSet<>(); final List<VariableField> fields = record.getVariableFields("LOK"); if (fields != null) { for (final VariableField variableField : fields) { final DataField lokfield = (DataField) variableField; final Subfield subfield0 = lokfield.getSubfield('0'); if (subfield0 == null || !subfield0.getData().startsWith("852")) { continue; } final Subfield subfieldA = lokfield.getSubfield('a'); if (subfieldA != null) { isils.add(subfieldA.getData()); } } } if (isils.isEmpty()) { // Nothing worked! isils.add("Unknown"); } this.isils_cache = isils; return isils; } /** * @param record the record * @return */ public String isAvailableInTuebingen(final Record record) { final Set<String> isils = getIsils(record); if (isils.contains("DE-21") || isils.contains("DE-21-110")) { return Boolean.toString(true); } return Boolean.toString(!record.getVariableFields("SIG").isEmpty()); } // TODO: This should be in a translation mapping file private final static HashMap<String, String> isil_to_department_map = new HashMap<String, String>() { { this.put("Unknown", "Unknown"); this.put("DE-21", "Universit\u00E4tsbibliothek T\u00FCbingen"); this.put("DE-21-1", "Universit\u00E4t T\u00FCbingen, Klinik f\u00FCr Psychatrie und Psychologie"); this.put("DE-21-3", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Toxikologie und Pharmakologie"); this.put("DE-21-4", "Universit\u00E4t T\u00FCbingen, Universit\u00E4ts-Augenklinik"); this.put("DE-21-10", "Universit\u00E4tsbibliothek T\u00FCbingen, Bereichsbibliothek Geowissenschaften"); this.put("DE-21-11", "Universit\u00E4tsbibliothek T\u00FCbingen, Bereichsbibliothek Schloss Nord"); this.put("DE-21-14", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Ur- und Fr\u00FChgeschichte und Arch\u00E4ologie des Mittelalters, Abteilung j\u00FCngere Urgeschichte und Fr\u00FChgeschichte + Abteilung f\u00FCr Arch\u00E4ologie des Mittelalters"); this.put("DE-21-17", "Universit\u00E4t T\u00FCbingen, Geographisches Institut"); this.put("DE-21-18", "Universit\u00E4t T\u00FCbingen, Universit\u00E4ts-Hautklinik"); this.put("DE-21-19", "Universit\u00E4t T\u00FCbingen, Wirtschaftswissenschaftliches Seminar"); this.put("DE-21-20", "Universit\u00E4t T\u00FCbingen, Frauenklinik"); this.put("DE-21-21", "Universit\u00E4t T\u00FCbingen, Universit\u00E4ts-Hals-Nasen-Ohrenklinik, Bibliothek"); this.put("DE-21-22", "Universit\u00E4t T\u00FCbingen, Kunsthistorisches Institut"); this.put("DE-21-23", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Pathologie"); this.put("DE-21-24", "Universit\u00E4t T\u00FCbingen, Juristisches Seminar"); this.put("DE-21-25", "Universit\u00E4t T\u00FCbingen, Musikwissenschaftliches Institut"); this.put("DE-21-26", "Universit\u00E4t T\u00FCbingen, Anatomisches Institut"); this.put("DE-21-27", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Anthropologie und Humangenetik"); this.put("DE-21-28", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Astronomie und Astrophysik, Abteilung Astronomie"); this.put("DE-21-31", "Universit\u00E4t T\u00FCbingen, Evangelisch-theologische Fakult\u00E4t"); this.put("DE-21-32a", "Universit\u00E4t T\u00FCbingen, Historisches Seminar, Abteilung f\u00FCr Alte Geschichte"); this.put("DE-21-32b", "Universit\u00E4t T\u00FCbingen, Historisches Seminar, Abteilung f\u00FCr Mittelalterliche Geschichte"); this.put("DE-21-32c", "Universit\u00E4t T\u00FCbingen, Historisches Seminar, Abteilung f\u00FCr Neuere Geschichte"); this.put("DE-21-34", "Universit\u00E4t T\u00FCbingen, Asien-Orient-Institut, Abteilung f\u00FCr Indologie und Vergleichende Religionswissenschaft"); this.put("DE-21-35", "Universit\u00E4t T\u00FCbingen, Katholisch-theologische Fakult\u00E4t"); this.put("DE-21-39", "Universit\u00E4t T\u00FCbingen, Fachbibliothek Mathematik und Physik / Bereich Mathematik"); this.put("DE-21-37", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Sportwissenschaft"); this.put("DE-21-42", "Universit\u00E4t T\u00FCbingen, Asien-Orient-Institut, Abteilung f\u00FCr Orient- uns Islamwissenschaft"); this.put("DE-21-43", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Erziehungswissenschaft"); this.put("DE-21-45", "Universit\u00E4t T\u00FCbingen, Philologisches Seminar"); this.put("DE-21-46", "Universit\u00E4t T\u00FCbingen, Philosophisches Seminar"); this.put("DE-21-50", "Universit\u00E4t T\u00FCbingen, Physiologisches Institut"); this.put("DE-21-51", "Universit\u00E4t T\u00FCbingen, Psychologisches Institut"); this.put("DE-21-52", "Universit\u00E4t T\u00FCbingen, Ludwig-Uhland-Institut f\u00FCr Empirische Kulturwissenschaft"); this.put("DE-21-53", "Universit\u00E4t T\u00FCbingen, Asien-Orient-Institut, Abteilung f\u00FCr Ethnologie"); this.put("DE-21-54", "Universit\u00E4t T\u00FCbingen, Universit\u00E4tsklinik f\u00FCr Zahn-, Mund- und Kieferheilkunde"); this.put("DE-21-58", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Politikwissenschaft"); this.put("DE-21-62", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Osteurop\u00E4ische Geschichte und Landeskunde"); this.put("DE-21-63", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Tropenmedizin"); this.put("DE-21-64", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Geschichtliche Landeskunde und Historische Hilfswissenschaften"); this.put("DE-21-65", "Universit\u00E4t T\u00FCbingen, Universit\u00E4ts-Apotheke"); this.put("DE-21-74", "Universit\u00E4t T\u00FCbingen, Zentrum f\u00FCr Informations-Technologie"); this.put("DE-21-78", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Medizinische Biometrie"); this.put("DE-21-81", "Universit\u00E4t T\u00FCbingen, Inst. f. Astronomie und Astrophysik/Abt. Geschichte der Naturwiss."); this.put("DE-21-85", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Soziologie"); this.put("DE-21-86", "Universit\u00E4t T\u00FCbingen, Zentrum f\u00FCr Datenverarbeitung"); this.put("DE-21-89", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Arbeits- und Sozialmedizin"); this.put("DE-21-92", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Gerichtliche Medizin"); this.put("DE-21-93", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Ethik und Geschichte der Medizin"); this.put("DE-21-95", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Hirnforschung"); this.put("DE-21-98", "Universit\u00E4t T\u00FCbingen, Fachbibliothek Mathematik und Physik / Bereich Physik"); this.put("DE-21-99", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Ur- und Fr\u00FChgeschichte und Arch\u00E4ologie des Mittelalters, Abteilung f\u00FCr \u00E4ltere Urgeschichteund Quart\u00E4r\u00F6kologie"); this.put("DE-21-106", "Universit\u00E4t T\u00FCbingen, Seminar f\u00FCr Zeitgeschichte"); this.put("DE-21-108", "Universit\u00E4t T\u00FCbingen, Fakult\u00E4tsbibliothek Neuphilologie"); this.put("DE-21-109", "Universit\u00E4t T\u00FCbingen, Asien-Orient-Institut, Abteilung f\u00FCr Sinologie und Koreanistik"); this.put("DE-21-110", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Kriminologie"); this.put("DE-21-112", "Universit\u00E4t T\u00FCbingen, Fakult\u00E4t f\u00FCr Biologie, Bibliothek"); this.put("DE-21-116", "Universit\u00E4t T\u00FCbingen, Zentrum f\u00FCr Molekularbiologie der Pflanzen, Forschungsgruppe Pflanzenbiochemie"); this.put("DE-21-117", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Medizinische Informationsverarbeitung"); this.put("DE-21-118", "Universit\u00E4t T\u00FCbingen, Universit\u00E4ts-Archiv"); this.put("DE-21-119", "Universit\u00E4t T\u00FCbingen, Wilhelm-Schickard-Institut f\u00FCr Informatik"); this.put("DE-21-120", "Universit\u00E4t T\u00FCbingen, Asien-Orient-Institut, Abteilung f\u00FCr Japanologie"); this.put("DE-21-121", "Universit\u00E4t T\u00FCbingen, Internationales Zentrum f\u00FCr Ethik in den Wissenschaften"); this.put("DE-21-123", "Universit\u00E4t T\u00FCbingen, Medizinbibliothek"); this.put("DE-21-124", "Universit\u00E4t T\u00FCbingen, Institut f. Medizinische Virologie und Epidemiologie d. Viruskrankheiten"); this.put("DE-21-126", "Universit\u00E4t T\u00FCbingen, Institut f\u00FCr Medizinische Mikrobiologie und Hygiene"); this.put("DE-21-203", "Universit\u00E4t T\u00FCbingen, Sammlung Werner Schweikert - Archiv der Weltliteratur"); this.put("DE-21-205", "Universit\u00E4t T\u00FCbingen, Zentrum f\u00FCr Islamische Theologie"); } }; /** * get the collections from LOK-tagged fields * <p/> * Typical LOK-Section below a Marc21 - Title-Set of a record: * LOK |0 000 xxxxxnu a22 zn 4500 * LOK |0 001 000001376 * LOK |0 003 DE-576 * LOK |0 004 000000140 * LOK |0 005 20020725000000 * LOK |0 008 020725||||||||||||||||ger||||||| * LOK |0 014 |a 000001368 |b DE-576 * LOK |0 541 |e 76.6176 * LOK |0 852 |a DE-Sp3 * LOK |0 852 1 |c B IV 529 |9 00 * <p/> * LOK = Field * |0 852 = Subfield * |a DE-Sp3 = Subfield with ISIL * * @param record the record * @return Set of collections */ public Set getCollections(final Record record) { final Set<String> isils = getIsils(record); final Set<String> collections = new HashSet<>(); for (final String isil : isils) { final String collection = isil_to_department_map.get(isil); if (collection != null) { collections.add(collection); } else { throw new IllegalArgumentException("Unknown ISIL: " + isil); } } if (collections.isEmpty()) collections.add("Unknown"); return collections; } /** * @param record the record */ public String getInstitution(final Record record) { final Set collections = getCollections(record); return (String) collections.iterator().next(); } /** * @param record the record */ public String getBSZIndexedDate(final Record record) { for (final VariableField variableField : record.getVariableFields("LOK")) { final DataField lokfield = (DataField) variableField; final List<Subfield> subfields = lokfield.getSubfields(); final Iterator<Subfield> subfieldsIter = subfields.iterator(); while (subfieldsIter.hasNext()) { Subfield subfield = subfieldsIter.next(); char formatCode = subfield.getCode(); String dataString = subfield.getData(); if (formatCode != '0' || !dataString.startsWith("938") || !subfieldsIter.hasNext()) { continue; } subfield = subfieldsIter.next(); formatCode = subfield.getCode(); if (formatCode != 'a') { continue; } dataString = subfield.getData(); if (dataString.length() != 4) { continue; } final String sub_year_text = dataString.substring(0, 2); final int sub_year = Integer.parseInt("20" + sub_year_text); final int current_year = Calendar.getInstance().get(Calendar.YEAR); final String year; if (sub_year > current_year) { // It is from the last century year = "19" + sub_year_text; } else { year = "20" + sub_year_text; } final String month = dataString.substring(2, 4); return year + "-" + month + "-01T11:00:00:000Z"; } } return null; } private final static Pattern PAGE_RANGE_PATTERN1 = Pattern.compile("\\s*(\\d+)\\s*-\\s*(\\d+)$"); private final static Pattern PAGE_RANGE_PATTERN2 = Pattern.compile("\\s*\\[(\\d+)\\]\\s*-\\s*(\\d+)$"); private final static Pattern PAGE_RANGE_PATTERN3 = Pattern.compile("\\s*(\\d+)\\s*ff"); private final static Pattern YEAR_PATTERN = Pattern.compile("(\\d\\d\\d\\d)"); private final static Pattern VOLUME_PATTERN = Pattern.compile("^\\s*(\\d+)$"); /** * @param record the record */ public String getPageRange(final Record record) { final String field_value = SolrIndexer.getFirstFieldVal(record, "936h"); if (field_value == null) return null; final Matcher matcher1 = PAGE_RANGE_PATTERN1.matcher(field_value); if (matcher1.matches()) return matcher1.group(1) + "-" + matcher1.group(2); final Matcher matcher2 = PAGE_RANGE_PATTERN2.matcher(field_value); if (matcher2.matches()) return matcher2.group(1) + "-" + matcher2.group(2); final Matcher matcher3 = PAGE_RANGE_PATTERN3.matcher(field_value); if (matcher3.matches()) return matcher3.group(1) + "-"; return null; } /** * @param record the record */ public String getContainerYear(final Record record) { final String field_value = SolrIndexer.getFirstFieldVal(record, "936j"); if (field_value == null) return null; final Matcher matcher = YEAR_PATTERN.matcher(field_value); return matcher.matches() ? matcher.group(1) : null; } /** * @param record the record */ public String getContainerVolume(final Record record) { final String field_value = SolrIndexer.getFirstFieldVal(record, "936d"); if (field_value == null) return null; final Matcher matcher = VOLUME_PATTERN.matcher(field_value); return matcher.matches() ? matcher.group(1) : null; } }
package com.perm.kate.api; import java.io.Serializable; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; //Fields are optional. Should be null if not populated public class User implements Serializable { private static final long serialVersionUID = 1L; public long uid; public String first_name; public String last_name; public String nickname; public Integer sex=null; public Boolean online=null; public Boolean online_mobile=null; public String birthdate; //bdate public String photo;//photo_50 public String photo_big;//photo_200_orig public String photo_200; public String photo_medium_rec; public String photo_400_orig; public Integer city=null; public Integer country=null; public Integer timezone=null; public String lists; public String domain; public Integer rate=null; public Integer university=null; //if education public String university_name; //if education public Integer faculty=null; //if education public String faculty_name; //if education public Integer graduation=null; //if education public Boolean has_mobile=null; public String home_phone; public String mobile_phone; public String status; public Integer relation; public String friends_list_ids = null; public long last_seen; public int albums_count; public int videos_count; public int audios_count; public int notes_count; public int friends_count; public int user_photos_count; public int user_videos_count; public int followers_count; //public int subscriptions_count; //public int online_friends_count; public String phone;//for getByPhones public int groups_count; //relation_partner public Long relation_partner_id; public String relation_partner_first_name; public String relation_partner_last_name; //new connections fields public String twitter; public String facebook; public String facebook_name; public String skype; public String livejounal; //new additional fields public String interests; public String movies; public String tv; public String books; public String games; public String about; public static User parse(JSONObject o) throws JSONException { User u = new User(); u.uid = Long.parseLong(o.getString("id")); if(!o.isNull("first_name")) u.first_name = Api.unescape(o.getString("first_name")); if(!o.isNull("last_name")) u.last_name = Api.unescape(o.getString("last_name")); if(!o.isNull("nickname")) u.nickname = Api.unescape(o.optString("nickname")); if(!o.isNull("screen_name")) u.domain = o.optString("screen_name"); if(!o.isNull("online")) u.online = o.optInt("online")==1; if(!o.isNull("online_mobile")) u.online_mobile = o.optInt("online_mobile")==1; else //if it's not there it means false u.online_mobile=false; if(!o.isNull("sex")) u.sex = Integer.parseInt(o.optString("sex")); if(!o.isNull("bdate")) u.birthdate = o.optString("bdate"); try{ u.city = Integer.parseInt(o.optString("city")); }catch(NumberFormatException ex){} try{ u.country = Integer.parseInt(o.optString("country")); }catch(NumberFormatException ex){} if(!o.isNull("timezone")) u.timezone = o.optInt("timezone"); if(!o.isNull("photo_50")) u.photo = o.optString("photo_50"); if(!o.isNull("photo_100")) u.photo_medium_rec = o.optString("photo_100"); if(!o.isNull("photo_200_orig")) u.photo_big = o.optString("photo_200_orig"); if(!o.isNull("photo_200")) u.photo_200 = o.optString("photo_200"); if(!o.isNull("photo_400_orig")) u.photo_400_orig = o.optString("photo_400_orig"); if(!o.isNull("has_mobile")) u.has_mobile = o.optInt("has_mobile")==1; if(!o.isNull("home_phone")) u.home_phone = o.optString("home_phone"); if(!o.isNull("mobile_phone")) u.mobile_phone = o.optString("mobile_phone"); if(!o.isNull("rate")) u.rate = Integer.parseInt(o.optString("rate")); try{ u.faculty = Integer.parseInt(o.optString("faculty")); }catch(NumberFormatException ex){} if(!o.isNull("faculty_name")) u.faculty_name = o.optString("faculty_name"); try{ u.university = Integer.parseInt(o.optString("university")); }catch(NumberFormatException ex){} if(!o.isNull("university_name")) u.university_name = o.optString("university_name"); try{ u.graduation = Integer.parseInt(o.optString("graduation")); }catch(NumberFormatException ex){} if(!o.isNull("activity")) u.status = Api.unescape(o.optString("activity")); if(!o.isNull("relation")) u.relation = o.optInt("relation"); if (!o.isNull("lists")) { JSONArray array = o.optJSONArray("lists"); if (array != null) { String ids = ""; for (int i=0; i<array.length()-1;++i) ids += array.getString(i) + ","; ids += array.getString(array.length()-1); u.friends_list_ids = ids; } } if(!o.isNull("last_seen")) { JSONObject object = o.optJSONObject("last_seen"); if (object != null) u.last_seen = object.optLong("time"); } if(!o.isNull("counters")) { JSONObject object = o.optJSONObject("counters"); if (object != null) { u.albums_count = object.optInt("albums"); u.videos_count = object.optInt("videos"); u.audios_count = object.optInt("audios"); u.notes_count = object.optInt("notes"); u.friends_count = object.optInt("friends"); u.user_photos_count = object.optInt("user_photos"); u.user_videos_count = object.optInt("user_videos"); //u.online_friends_count = object.optInt("online_friends"); u.followers_count = object.optInt("followers"); //u.subscriptions_count = object.optInt("subscriptions"); u.groups_count = object.optInt("groups"); } } if(!o.isNull("relation_partner")) { JSONObject object = o.optJSONObject("relation_partner"); if (object != null) { u.relation_partner_id = object.optLong("id"); u.relation_partner_first_name = object.optString("first_name"); u.relation_partner_last_name = object.optString("last_name"); } } if(!o.isNull("twitter")) u.twitter = o.optString("twitter"); if(!o.isNull("facebook")) u.facebook = o.optString("facebook"); if(!o.isNull("facebook_name")) u.facebook_name = o.optString("facebook_name"); if(!o.isNull("skype")) u.skype = o.optString("skype"); if(!o.isNull("livejounal")) u.livejounal = o.optString("livejounal"); if(!o.isNull("interests")) u.interests = o.optString("interests"); if(!o.isNull("movies")) u.movies = o.optString("movies"); if(!o.isNull("tv")) u.tv = o.optString("tv"); if(!o.isNull("books")) u.books = o.optString("books"); if(!o.isNull("games")) u.games = o.optString("games"); if(!o.isNull("about")) u.about = o.optString("about"); return u; } public static User parseFromNews(JSONObject jprofile) throws JSONException { User m = new User(); m.uid = jprofile.getLong("id"); m.first_name = Api.unescape(jprofile.optString("first_name")); m.last_name = Api.unescape(jprofile.optString("last_name")); m.photo = jprofile.optString("photo"); if(jprofile.has("photo_50")) m.photo = jprofile.optString("photo_50"); m.photo_medium_rec = jprofile.optString("photo_medium_rec"); if(jprofile.has("photo_100")) m.photo_medium_rec = jprofile.optString("photo_100"); try{ m.sex = Integer.parseInt(jprofile.optString("sex")); }catch(NumberFormatException ex){ ex.printStackTrace(); } if(!jprofile.isNull("online")) m.online = jprofile.optInt("online")==1; return m; } public static User parseFromGetByPhones(JSONObject o) throws JSONException { User u = new User(); u.uid = o.getLong("id"); u.first_name = Api.unescape(o.optString("first_name")); u.last_name = Api.unescape(o.optString("last_name")); u.phone = o.optString("phone"); return u; } public static ArrayList<User> parseUsers(JSONArray array) throws JSONException { return parseUsers(array, false); } public static ArrayList<User> parseUsers(JSONArray array, boolean from_notifications) throws JSONException { ArrayList<User> users=new ArrayList<User>(); //it may be null if no users returned //no users may be returned if we request users that are already removed if(array==null) return users; int category_count=array.length(); for(int i=0; i<category_count; ++i){ JSONObject o = (JSONObject)array.get(i); User u; if(from_notifications) u = User.parseFromNotifications(o); else u = User.parse(o); users.add(u); } return users; } public static ArrayList<User> parseUsersForGetByPhones(JSONArray array) throws JSONException { ArrayList<User> users=new ArrayList<User>(); //it may be null if no users returned //no users may be returned if we request users that are already removed if(array==null) return users; int category_count=array.length(); for(int i=0; i<category_count; ++i){ if(array.get(i)==null || ((array.get(i) instanceof JSONObject)==false)) continue; JSONObject o = (JSONObject)array.get(i); User u = User.parseFromGetByPhones(o); users.add(u); } return users; } public static User parseFromFave(JSONObject jprofile) throws JSONException { User m = new User(); m.uid = Long.parseLong(jprofile.getString("id")); m.first_name = Api.unescape(jprofile.optString("first_name")); m.last_name = Api.unescape(jprofile.optString("last_name")); m.photo_medium_rec = jprofile.optString("photo_100"); if(!jprofile.isNull("online")) m.online = jprofile.optInt("online")==1; if(!jprofile.isNull("online_mobile")) m.online_mobile = jprofile.optInt("online_mobile")==1; else //if it's not there it means false m.online_mobile=false; return m; } public static User parseFromNotifications(JSONObject jprofile) throws JSONException { User m = new User(); m.uid = jprofile.getLong("id"); m.first_name = Api.unescape(jprofile.optString("first_name")); m.last_name = Api.unescape(jprofile.optString("last_name")); m.photo_medium_rec = jprofile.optString("photo_medium_rec"); if(jprofile.has("photo_100")) m.photo_medium_rec = jprofile.optString("photo_100"); m.photo = jprofile.optString("photo"); if(jprofile.has("photo_50")) m.photo = jprofile.optString("photo_50"); return m; } }
package sophena.io; import java.nio.file.Files; import java.nio.file.Path; import java.util.Objects; import java.util.UUID; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sophena.Tests; import sophena.db.daos.ProductDao; import sophena.db.daos.ProjectDao; import sophena.io.datapack.DataPack; import sophena.io.datapack.Export; import sophena.io.datapack.Import; import sophena.model.Product; import sophena.model.ProductEntry; import sophena.model.Project; /** * Test the import and export of shared and private project products. */ public class ProductsPackTest { private Logger log = LoggerFactory.getLogger(getClass()); private ProjectDao projectDao = new ProjectDao(Tests.getDb()); private ProductDao productDao = new ProductDao(Tests.getDb()); private Project project; @Before public void setUp() throws Exception { project = createModel(); } @After public void tearDown() throws Exception { if (project != null) { projectDao.delete(project); } } /** * Creates the test model: a project with references to a shared product and * a project private product. */ private Project createModel() { // shared product Product shared = new Product(); shared.id = UUID.randomUUID().toString(); shared.name = "Shared product"; productDao.insert(shared); // project Project project = new Project(); project.id = UUID.randomUUID().toString(); project.name = "Project"; // own product Product own = new Product(); own.id = UUID.randomUUID().toString(); own.name = "Own product"; own.projectId = project.id; project.ownProducts.add(own); // product entries ProductEntry sharedEntry = new ProductEntry(); sharedEntry.id = UUID.randomUUID().toString(); sharedEntry.product = shared; sharedEntry.count = 24; project.productEntries.add(sharedEntry); ProductEntry ownEntry = new ProductEntry(); ownEntry.id = UUID.randomUUID().toString(); ownEntry.product = own; ownEntry.count = 42; project.productEntries.add(ownEntry); return projectDao.insert(project); } @Test public void testModel() { testModel(project); } @Test public void testClone() { Project clone = project.clone(); projectDao.insert(clone); testModel(clone); Assert.assertNotEquals(project.ownProducts.get(0), clone.ownProducts.get(0)); projectDao.delete(clone); } @Test public void testPackIO() throws Exception { Path path = Files.createTempFile("test_products_pack_", ".sophena"); Files.delete(path); try (DataPack pack = new DataPack(path.toFile())) { log.trace("Created data package: {}", path); Export export = new Export(pack); export.write(project); } projectDao.delete(project); Assert.assertNull(projectDao.get(project.id)); Assert.assertNull(productDao.get(project.ownProducts.get(0).id)); Import packImport = new Import(path.toFile(), Tests.getDb()); packImport.run(); project = projectDao.get(project.id); testModel(project); } private void testModel(Project project) { Assert.assertEquals(1, project.ownProducts.size()); Product own = project.ownProducts.get(0); Assert.assertEquals("Own product", own.name); Assert.assertEquals(2, project.productEntries.size()); for (ProductEntry entry : project.productEntries) { if (Objects.equals(own, entry.product)) { Assert.assertEquals(42, entry.count, 1e-15); } else { Assert.assertEquals("Shared product", entry.product.name); Assert.assertEquals(24, entry.count, 1e-15); } } } }
package com.intellij.openapi.roots.ui.configuration; import com.intellij.Patches; import com.intellij.ide.util.BrowseFilesListener; import com.intellij.ide.util.JavaUtil; import com.intellij.ide.util.projectWizard.ToolbarPanel; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.module.Module; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.util.ProgressWindow; import com.intellij.openapi.progress.util.SmoothProgressAdapter; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ContentEntry; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.roots.ModuleRootModel; import com.intellij.openapi.roots.ui.componentsList.components.ScrollablePanel; import com.intellij.openapi.roots.ui.componentsList.layout.VerticalStackLayout; import com.intellij.openapi.roots.ui.configuration.actions.ModulesConfigurationAction; import com.intellij.openapi.ui.Splitter; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.ex.VirtualFileManagerAdapter; import com.intellij.openapi.vfs.ex.VirtualFileManagerEx; import com.intellij.ui.FieldPanel; import com.intellij.ui.InsertPathAction; import com.intellij.ui.ScrollPaneFactory; import com.intellij.util.concurrency.SwingWorker; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.event.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class ContentEntriesEditor extends ModuleElementsEditor { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.roots.ui.configuration.ContentEntriesEditor"); public static final String NAME = "Paths"; public static final Icon ICON = IconLoader.getIcon("/modules/paths.png"); private static final Color BACKGROUND_COLOR = UIManager.getColor("List.background"); private static final Icon ADD_CONTENT_ENTRY_ICON = IconLoader.getIcon("/modules/addContentEntry.png"); private ContentEntryTreeEditor myRootTreeEditor; private MyContentEntryEditorListener myContentEntryEditorListener; private JPanel myEditorsPanel; private final Map<ContentEntry, ContentEntryEditor> myEntryToEditorMap = new HashMap<ContentEntry, ContentEntryEditor>(); private ContentEntry mySelectedEntry; private FieldPanel myOutputPathPanel; private FieldPanel myTestsOutputPathPanel; private VirtualFile myLastSelectedDir = null; private JRadioButton myRbRelativePaths; private JCheckBox myCbExcludeOutput; private VirtualFileManagerAdapter myVFMListener; private final String myModuleName; private final ModulesProvider myModulesProvider; public ContentEntriesEditor(Project project, String moduleName, ModifiableRootModel model, ModulesProvider modulesProvider) { super(project, model); myModuleName = moduleName; myModulesProvider = modulesProvider; myVFMListener = new VirtualFileManagerAdapter() { public void afterRefreshFinish(boolean asynchonous) { for (Iterator<ContentEntry> it = myEntryToEditorMap.keySet().iterator(); it.hasNext();) { final ContentEntryEditor editor = myEntryToEditorMap.get(it.next()); if (editor != null) { editor.update(); } } } }; ((VirtualFileManagerEx)VirtualFileManager.getInstance()).addVirtualFileManagerListener(myVFMListener); } public String getHelpTopic() { return "project.paths.paths"; } public String getDisplayName() { return NAME; } public Icon getIcon() { return ICON; } public void disposeUIResources() { ((VirtualFileManagerEx)VirtualFileManager.getInstance()).removeVirtualFileManagerListener(myVFMListener); if (myRootTreeEditor != null) { myRootTreeEditor.setContentEntryEditor(null); } super.disposeUIResources(); } public boolean isModified() { if (super.isModified()) { return true; } final Module selfModule = getMyModule(); return selfModule == null || myRbRelativePaths == null ? false : selfModule.isSavePathsRelative() != myRbRelativePaths.isSelected(); } public JPanel createComponentImpl() { final Project project = getMyModule().getProject(); myContentEntryEditorListener = new MyContentEntryEditorListener(); final JPanel mainPanel = new JPanel(new BorderLayout()); mainPanel.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6)); JComponent outputPathsBlock = createOutputPathsBlock(); outputPathsBlock.setBorder(BorderFactory.createEmptyBorder(0, 0, 12, 0)); mainPanel.add(outputPathsBlock, BorderLayout.NORTH); final JPanel entriesPanel = new JPanel(new BorderLayout()); final DefaultActionGroup group = new DefaultActionGroup(); group.add(new AddContentEntryAction()); myEditorsPanel = new ScrollablePanel(new VerticalStackLayout()); myEditorsPanel.setBackground(BACKGROUND_COLOR); JScrollPane myScrollPane = ScrollPaneFactory.createScrollPane(myEditorsPanel); entriesPanel.add(new ToolbarPanel(myScrollPane, group), BorderLayout.CENTER); final Splitter splitter = new Splitter(false); splitter.setHonorComponentsMinimumSize(true); mainPanel.add(splitter, BorderLayout.CENTER); final JPanel editorsPanel = new JPanel(new GridBagLayout()); splitter.setFirstComponent(editorsPanel); editorsPanel.add(entriesPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); myRootTreeEditor = new ContentEntryTreeEditor(project); final JComponent treeEditorComponent = myRootTreeEditor.createComponent(); splitter.setSecondComponent(treeEditorComponent); final JPanel rbPanel = new JPanel(new GridBagLayout()); rbPanel.setBorder(BorderFactory.createEmptyBorder(6, 0, 0, 6)); myRbRelativePaths = new JRadioButton("Use relative path"); final JRadioButton rbAbsolutePaths = new JRadioButton("Use absolute path"); ButtonGroup buttonGroup = new ButtonGroup(); buttonGroup.add(myRbRelativePaths); buttonGroup.add(rbAbsolutePaths); rbPanel.add(new JLabel("For files outside module file directory:"), new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); rbPanel.add(rbAbsolutePaths, new GridBagConstraints(1, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); rbPanel.add(myRbRelativePaths, new GridBagConstraints(2, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); if (getMyModule().isSavePathsRelative()) { myRbRelativePaths.setSelected(true); } else { rbAbsolutePaths.setSelected(true); } mainPanel.add(rbPanel, BorderLayout.SOUTH); final ContentEntry[] contentEntries = myModel.getContentEntries(); if (contentEntries.length > 0) { for (int idx = 0; idx < contentEntries.length; idx++) { final ContentEntry contentEntry = contentEntries[idx]; addContentEntryPanel(contentEntry); } selectContentEntry(contentEntries[0]); } return mainPanel; } private Module getMyModule() { return myModulesProvider.getModule(myModuleName); } private JComponent createOutputPathsBlock() { myOutputPathPanel = createOutputPathPanel("Select Output Path", new CommitPathRunnable() { public void saveUrl(String url) { myModel.setCompilerOutputPath(url); } }); myTestsOutputPathPanel = createOutputPathPanel("Select Test Output Path", new CommitPathRunnable() { public void saveUrl(String url) { myModel.setCompilerOutputPathForTests(url); } }); myCbExcludeOutput = new JCheckBox("Exclude output paths", myModel.isExcludeOutput()); myCbExcludeOutput.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { myModel.setExcludeOutput(e.getStateChange() == ItemEvent.SELECTED); if (myRootTreeEditor != null) { myRootTreeEditor.update(); } } }); final JPanel outputPathsPanel = new JPanel(new GridBagLayout()); outputPathsPanel.add(new JLabel("Output path:"), new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(6, 0, 0, 4), 0, 0)); outputPathsPanel.add(myOutputPathPanel, new GridBagConstraints(1, GridBagConstraints.RELATIVE, 2, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(6, 4, 0, 0), 0, 0)); outputPathsPanel.add(new JLabel("Test output path:"), new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(6, 0, 0, 4), 0, 0)); outputPathsPanel.add(myTestsOutputPathPanel, new GridBagConstraints(1, GridBagConstraints.RELATIVE, 2, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(6, 4, 0, 0), 0, 0)); outputPathsPanel.add(myCbExcludeOutput, new GridBagConstraints(1, GridBagConstraints.RELATIVE, 2, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(6, 0, 0, 0), 0, 0)); // fill with data final VirtualFile compilerOutputPath = myModel.getCompilerOutputPath(); if (compilerOutputPath != null) { myOutputPathPanel.setText(compilerOutputPath.getPath().replace('/', File.separatorChar)); } else { final String compilerOutputUrl = myModel.getCompilerOutputPathUrl(); if (compilerOutputUrl != null) { myOutputPathPanel.setText(VirtualFileManager.extractPath(compilerOutputUrl).replace('/', File.separatorChar)); } } final VirtualFile testsOutputPath = myModel.getCompilerOutputPathForTests(); if (testsOutputPath != null) { myTestsOutputPathPanel.setText(testsOutputPath.getPath().replace('/', File.separatorChar)); } else { final String testsOutputUrl = myModel.getCompilerOutputPathForTestsUrl(); if (testsOutputUrl != null) { myTestsOutputPathPanel.setText(VirtualFileManager.extractPath(testsOutputUrl).replace('/', File.separatorChar)); } } return outputPathsPanel; } private static interface CommitPathRunnable { void saveUrl(String url); } private FieldPanel createOutputPathPanel(final String title, final CommitPathRunnable commitPathRunnable) { final JTextField textField = new JTextField(); final FileChooserDescriptor outputPathsChooserDescriptor = new FileChooserDescriptor(false, true, false, false, false, false); outputPathsChooserDescriptor.setHideIgnored(false); InsertPathAction.addTo(textField, outputPathsChooserDescriptor); final Runnable commitRunnable = new Runnable() { public void run() { if (!myModel.isWritable()) { return; } final String path = textField.getText().trim(); if (path.length() == 0) { commitPathRunnable.saveUrl(null); } else { // should set only absolute paths String canonicalPath; try { canonicalPath = new File(path).getCanonicalPath(); } catch (IOException e) { canonicalPath = path; } commitPathRunnable.saveUrl(VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, canonicalPath.replace(File.separatorChar, '/'))); } if (myRootTreeEditor != null) { myRootTreeEditor.update(); // need this in order to update appearance of excluded output paths if they are under content root } } }; textField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent e) { commitRunnable.run(); } }); final FieldPanel fieldPanel = new FieldPanel(textField, null, null, new BrowseFilesListener(textField, title, "", outputPathsChooserDescriptor) { public void actionPerformed(ActionEvent e) { super.actionPerformed(e); commitRunnable.run(); } }, null); return fieldPanel; } private void addContentEntryPanel(final ContentEntry contentEntry) { final ContentEntryEditor contentEntryEditor = new ContentEntryEditor(contentEntry, myModel); contentEntryEditor.addContentEntryEditorListener(myContentEntryEditorListener); myEntryToEditorMap.put(contentEntry, contentEntryEditor); Border border = BorderFactory.createEmptyBorder(2, 2, 0, 2); final JComponent component = contentEntryEditor.getComponent(); final Border componentBorder = component.getBorder(); if (componentBorder != null) { border = BorderFactory.createCompoundBorder(border, componentBorder); } component.setBorder(border); myEditorsPanel.add(component); } private void selectContentEntry(ContentEntry contentEntry) { if (mySelectedEntry != null && mySelectedEntry.equals(contentEntry)) { return; } try { if (mySelectedEntry != null) { ContentEntryEditor editor = myEntryToEditorMap.get(mySelectedEntry); if (editor != null) { editor.setSelected(false); } } if (contentEntry != null) { ContentEntryEditor editor = myEntryToEditorMap.get(contentEntry); if (editor != null) { editor.setSelected(true); final JComponent component = editor.getComponent(); final JComponent scroller = (JComponent)component.getParent(); SwingUtilities.invokeLater(new Runnable() { public void run() { scroller.scrollRectToVisible(component.getBounds()); } }); myRootTreeEditor.setContentEntryEditor(editor); myRootTreeEditor.requestFocus(); } } } finally { mySelectedEntry = contentEntry; } } private ContentEntry getNextContentEntry(ContentEntry contentEntry) { return getAdjacentContentEntry(contentEntry, 1); } /* private ContentEntry getPreviousContentEntry(ContentEntry contentEntry) { return getAdjacentContentEntry(contentEntry, -1); } */ private ContentEntry getAdjacentContentEntry(ContentEntry contentEntry, int delta) { final ContentEntry[] contentEntries = myModel.getContentEntries(); for (int idx = 0; idx < contentEntries.length; idx++) { ContentEntry entry = contentEntries[idx]; if (contentEntry.equals(entry)) { int nextEntryIndex = (idx + delta) % contentEntries.length; if (nextEntryIndex < 0) { nextEntryIndex += contentEntries.length; } return nextEntryIndex == idx ? null : contentEntries[nextEntryIndex]; } } return null; } private void addContentEntries(final VirtualFile[] files) { java.util.List<ContentEntry> contentEntries = new ArrayList<ContentEntry>(); for (int idx = 0; idx < files.length; idx++) { final VirtualFile file = files[idx]; if (isAlreadyAdded(file)) { continue; } final ContentEntry contentEntry = myModel.addContentEntry(file); contentEntries.add(contentEntry); } if (contentEntries.size() > 0) { final ContentEntry[] contentEntriesArray = contentEntries.toArray(new ContentEntry[contentEntries.size()]); addSourceRoots(myProject, contentEntriesArray, new Runnable() { public void run() { for (int idx = 0; idx < contentEntriesArray.length; idx++) { addContentEntryPanel(contentEntriesArray[idx]); } myEditorsPanel.revalidate(); myEditorsPanel.repaint(); selectContentEntry(contentEntriesArray[contentEntriesArray.length - 1]); } }); } } private boolean isAlreadyAdded(VirtualFile file) { final VirtualFile[] contentRoots = myModel.getContentRoots(); for (int idx = 0; idx < contentRoots.length; idx++) { VirtualFile contentRoot = contentRoots[idx]; if (contentRoot.equals(file)) { return true; } } return false; } public void saveData() { getMyModule().setSavePathsRelative(myRbRelativePaths.isSelected()); } private static void addSourceRoots(final Project project, final ContentEntry[] contentEntries, final Runnable finishRunnable) { final HashMap<ContentEntry, java.util.List<Pair<File, String>>> entryToRootMap = new HashMap<ContentEntry, java.util.List<Pair<File, String>>>(); final Map<File, ContentEntry> fileToEntryMap = new HashMap<File, ContentEntry>(); for (int idx = 0; idx < contentEntries.length; idx++) { final ContentEntry contentEntry = contentEntries[idx]; entryToRootMap.put(contentEntry, null); fileToEntryMap.put(VfsUtil.virtualToIoFile(contentEntry.getFile()), contentEntry); } final ProgressWindow progressWindow = new ProgressWindow(true, project); final ProgressIndicator progressIndicator = Patches.MAC_HIDE_QUIT_HACK ? progressWindow : (ProgressIndicator)new SmoothProgressAdapter(progressWindow, project); final Runnable searchRunnable = new Runnable() { public void run() { final Runnable process = new Runnable() { public void run() { for (Iterator it = fileToEntryMap.keySet().iterator(); it.hasNext();) { final File entryFile = (File)it.next(); progressIndicator.setText("Searching for source roots in " + entryFile.getPath()); final java.util.List<Pair<File, String>> roots = JavaUtil.suggestRoots(entryFile); entryToRootMap.put(fileToEntryMap.get(entryFile), roots); } } }; progressWindow.setTitle("Adding Source Roots"); ProgressManager.getInstance().runProcess(process, progressIndicator); } }; final Runnable addSourcesRunnable = new Runnable() { public void run() { for (int idx = 0; idx < contentEntries.length; idx++) { final ContentEntry contentEntry = contentEntries[idx]; final java.util.List<Pair<File, String>> suggestedRoots = entryToRootMap.get(contentEntry); if (suggestedRoots != null) { for (int j = 0; j < suggestedRoots.size(); j++) { final Pair<File, String> suggestedRoot = suggestedRoots.get(j); final VirtualFile sourceRoot = LocalFileSystem.getInstance().findFileByIoFile(suggestedRoot.first); if (sourceRoot != null && VfsUtil.isAncestor(contentEntry.getFile(), sourceRoot, false)) { contentEntry.addSourceFolder(sourceRoot, false, suggestedRoot.getSecond()); } } } } if (finishRunnable != null) { finishRunnable.run(); } } }; new SwingWorker() { public Object construct() { searchRunnable.run(); return null; } public void finished() { addSourcesRunnable.run(); } }.start(); } private final class MyContentEntryEditorListener extends ContentEntryEditorListenerAdapter { public void editingStarted(ContentEntryEditor editor) { selectContentEntry(editor.getContentEntry()); } public void beforeEntryDeleted(ContentEntryEditor editor) { final ContentEntry entry = editor.getContentEntry(); if (mySelectedEntry != null && mySelectedEntry.equals(entry)) { myRootTreeEditor.setContentEntryEditor(null); } final ContentEntry nextContentEntry = getNextContentEntry(entry); removeContentEntryPanel(entry); selectContentEntry(nextContentEntry); editor.removeContentEntryEditorListener(this); } public void folderIncluded(ContentEntryEditor editor, VirtualFile file) { if (editor.isCompilerOutput(file)) { myCbExcludeOutput.setSelected(false); } } public void folderExcluded(ContentEntryEditor editor, VirtualFile file) { if (editor.isCompilerOutput(file)) { myCbExcludeOutput.setSelected(true); } } public void navigationRequested(ContentEntryEditor editor, VirtualFile file) { if (mySelectedEntry != null && mySelectedEntry.equals(editor.getContentEntry())) { myRootTreeEditor.requestFocus(); myRootTreeEditor.select(file); } else { selectContentEntry(editor.getContentEntry()); myRootTreeEditor.requestFocus(); myRootTreeEditor.select(file); } } private void removeContentEntryPanel(final ContentEntry contentEntry) { ContentEntryEditor editor = myEntryToEditorMap.get(contentEntry); if (editor != null) { myEditorsPanel.remove(editor.getComponent()); myEntryToEditorMap.remove(contentEntry); myEditorsPanel.revalidate(); myEditorsPanel.repaint(); } } } private class AddContentEntryAction extends ModulesConfigurationAction { private final FileChooserDescriptor myDescriptor; public AddContentEntryAction() { super("Add Content Root", "Add content root to the module", ADD_CONTENT_ENTRY_ICON); myDescriptor = new FileChooserDescriptor(false, true, true, false, true, true) { public void validateSelectedFiles(VirtualFile[] files) throws Exception { validateContentEntriesCandidates(files); } }; myDescriptor.setTitle("Select content root directory"); myDescriptor.setDescription("Content root is a directory containing all files related to this module"); } public void actionPerformed(AnActionEvent e) { VirtualFile[] files = FileChooser.chooseFiles(myProject, myDescriptor, myLastSelectedDir); if (files.length > 0) { myLastSelectedDir = files[0]; addContentEntries(files); } } private void validateContentEntriesCandidates(VirtualFile[] files) throws Exception { for (int i = 0; i < files.length; i++) { final VirtualFile file = files[i]; // check for collisions with already existing entries for (Iterator<ContentEntry> it = myEntryToEditorMap.keySet().iterator(); it.hasNext();) { final ContentEntry contentEntry = it.next(); final VirtualFile contentEntryFile = contentEntry.getFile(); if (contentEntryFile == null) { continue; // skip invalid entry } if (contentEntryFile.equals(file)) { throw new Exception("Content root \"" + file.getPresentableUrl() + "\" already exists"); } if (VfsUtil.isAncestor(contentEntryFile, file, true)) { // intersection not allowed throw new Exception( "Content root being added \"" + file.getPresentableUrl() + "\"\nis located below existing content root \"" + contentEntryFile.getPresentableUrl() + "\".\nContent entries should not intersect."); } if (VfsUtil.isAncestor(file, contentEntryFile, true)) { // intersection not allowed throw new Exception( "Content root being added \"" + file.getPresentableUrl() + "\"\ndominates existing content root \"" + contentEntryFile.getPresentableUrl() + "\".\nContent entries should not intersect."); } } // check if the same root is configured for another module final Module[] modules = myModulesProvider.getModules(); for (int j = 0; j < modules.length; j++) { final Module module = modules[j]; if (myModuleName.equals(module.getName())) { continue; } ModuleRootModel rootModel = myModulesProvider.getRootModel(module); LOG.assertTrue(rootModel != null); final VirtualFile[] moduleContentRoots = rootModel.getContentRoots(); for (int k = 0; k < moduleContentRoots.length; k++) { VirtualFile moduleContentRoot = moduleContentRoots[k]; if (file.equals(moduleContentRoot)) { throw new Exception( "Content root \"" + file.getPresentableUrl() + "\" already defined for module \"" + module.getName() + "\".\nTwo modules in a project cannot share the same content root."); } } } } } } }
package com.yahoo.squidb.processor.writers; import com.yahoo.aptutils.model.CoreTypes; import com.yahoo.aptutils.model.DeclaredTypeName; import com.yahoo.aptutils.model.GenericName; import com.yahoo.aptutils.model.TypeName; import com.yahoo.aptutils.utils.AptUtils; import com.yahoo.aptutils.writer.JavaFileWriter; import com.yahoo.aptutils.writer.JavaFileWriter.Type; import com.yahoo.aptutils.writer.expressions.Expressions; import com.yahoo.aptutils.writer.parameters.MethodDeclarationParameters; import com.yahoo.aptutils.writer.parameters.TypeDeclarationParameters; import com.yahoo.squidb.processor.TypeConstants; import com.yahoo.squidb.processor.data.ModelSpec; import com.yahoo.squidb.processor.plugins.PluginBundle; import com.yahoo.squidb.processor.plugins.PluginEnvironment; import com.yahoo.squidb.processor.plugins.defaults.properties.generators.PropertyGenerator; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.annotation.processing.Filer; import javax.lang.model.element.Modifier; import javax.tools.JavaFileObject; public abstract class ModelFileWriter<T extends ModelSpec<?>> { protected final AptUtils utils; protected final PluginEnvironment pluginEnv; protected final T modelSpec; protected JavaFileWriter writer; public static final String PROPERTIES_ARRAY_NAME = "PROPERTIES"; protected static final String DEFAULT_VALUES_NAME = "defaultValues"; private static final MethodDeclarationParameters GET_CREATOR_PARAMS; private static final MethodDeclarationParameters GET_DEFAULT_VALUES_PARAMS; static { List<TypeName> extend = new ArrayList<TypeName>(); extend.add(TypeConstants.ABSTRACT_MODEL); GenericName returnGeneric = new GenericName(GenericName.WILDCARD_CHAR, extend, null); DeclaredTypeName returnType = TypeConstants.CREATOR.clone(); returnType.setTypeArgs(Collections.singletonList(returnGeneric)); GET_CREATOR_PARAMS = new MethodDeclarationParameters() .setMethodName("getCreator") .setModifiers(Modifier.PROTECTED) .setReturnType(returnType); GET_DEFAULT_VALUES_PARAMS = new MethodDeclarationParameters() .setMethodName("getDefaultValues") .setModifiers(Modifier.PUBLIC) .setReturnType(TypeConstants.CONTENT_VALUES); } public ModelFileWriter(T modelSpec, PluginEnvironment pluginEnv, AptUtils utils) { this.modelSpec = modelSpec; this.pluginEnv = pluginEnv; this.utils = utils; } public final void writeJava(Filer filer) throws IOException { initFileWriter(filer); writeJavaFile(); writer.close(); } private void initFileWriter(Filer filer) throws IOException { if (this.writer == null) { JavaFileObject jfo = filer.createSourceFile(modelSpec.getGeneratedClassName().toString(), modelSpec.getModelSpecElement()); Writer writer = jfo.openWriter(); this.writer = new JavaFileWriter(writer); } else { throw new IllegalStateException("JavaFileWriter already initialized"); } } private void writeJavaFile() throws IOException { PluginBundle plugins = modelSpec.getPluginBundle(); emitPackage(); emitImports(); beginClassDeclaration(); plugins.beforeEmitSchema(writer); emitPropertiesArray(); emitModelSpecificFields(); emitPropertyDeclarations(); emitDefaultValues(); plugins.afterEmitSchema(writer); plugins.emitConstructors(writer); plugins.beforeEmitMethods(writer); emitGettersAndSetters(); plugins.emitMethods(writer); plugins.afterEmitMethods(writer); emitCreator(); emitModelSpecificHelpers(); plugins.emitAdditionalJava(writer); writer.finishTypeDefinition(); } private void emitPackage() throws IOException { writer.writePackage(modelSpec.getGeneratedClassName().getPackageName()); } private void emitImports() throws IOException { Set<DeclaredTypeName> imports = new HashSet<DeclaredTypeName>(); modelSpec.addRequiredImports(imports); writer.writeImports(imports); writer.registerOtherKnownNames(TypeConstants.CREATOR, TypeConstants.MODEL_CREATOR, TypeConstants.TABLE_MAPPING_VISITORS, modelSpec.getModelSpecName()); } private void beginClassDeclaration() throws IOException { writer.writeComment("Generated code -- do not modify!"); writer.writeString("/** This class was generated from the model spec at {@link " + modelSpec.getModelSpecName() + "} */\n"); if (modelSpec.getModelSpecElement().getAnnotation(Deprecated.class) != null) { writer.writeAnnotation(CoreTypes.DEPRECATED); } TypeDeclarationParameters params = new TypeDeclarationParameters() .setName(modelSpec.getGeneratedClassName()) .setSuperclass(modelSpec.getModelSuperclass()) .setInterfaces(accumulateInterfacesFromPlugins()) .setKind(Type.CLASS) .setModifiers(Modifier.PUBLIC); writer.beginTypeDefinition(params); } private List<DeclaredTypeName> accumulateInterfacesFromPlugins() { Set<DeclaredTypeName> interfaces = new LinkedHashSet<DeclaredTypeName>(); modelSpec.getPluginBundle().addInterfacesToImplement(interfaces); return Arrays.asList(interfaces.toArray(new DeclaredTypeName[interfaces.size()])); } protected void emitPropertiesArray() throws IOException { writer.writeComment("--- allocate properties array"); writer.writeFieldDeclaration(TypeConstants.PROPERTY_ARRAY, PROPERTIES_ARRAY_NAME, Expressions.arrayAllocation(TypeConstants.PROPERTY, 1, getPropertiesArrayLength()), TypeConstants.PUBLIC_STATIC_FINAL); writer.writeNewline(); } protected int getPropertiesArrayLength() { return modelSpec.getPropertyGenerators().size(); } protected void emitModelSpecificFields() throws IOException { // Subclasses can override } private void emitPropertyDeclarations() throws IOException { writer.writeComment("--- property declarations"); emitAllProperties(); emitPropertyArrayInitialization(); writer.writeNewline(); } protected abstract void emitAllProperties() throws IOException; protected void emitPropertyArrayInitialization() throws IOException { writer.beginInitializerBlock(true, true); writePropertiesInitializationBlock(); writer.finishInitializerBlock(false, true); } protected abstract void writePropertiesInitializationBlock() throws IOException; protected void emitDefaultValues() throws IOException { writer.writeComment("--- default values"); writer.writeFieldDeclaration(TypeConstants.CONTENT_VALUES, DEFAULT_VALUES_NAME, Expressions.callConstructor(TypeConstants.CONTENT_VALUES), Modifier.PROTECTED, Modifier.STATIC, Modifier.FINAL); if (pluginEnv.hasOption(PluginEnvironment.OPTIONS_DISABLE_DEFAULT_CONTENT_VALUES)) { writer.writeComment("--- property defaults disabled by plugin flag"); } else { writer.beginInitializerBlock(true, true) .writeComment("--- put property defaults"); emitDefaultValuesInitializationBlock(); writer.finishInitializerBlock(false, true).writeNewline(); } writer.writeAnnotation(CoreTypes.OVERRIDE) .beginMethodDefinition(GET_DEFAULT_VALUES_PARAMS) .writeStringStatement("return " + DEFAULT_VALUES_NAME) .finishMethodDefinition(); } protected abstract void emitDefaultValuesInitializationBlock() throws IOException; protected void emitGettersAndSetters() throws IOException { if (pluginEnv.hasOption(PluginEnvironment.OPTIONS_DISABLE_DEFAULT_GETTERS_AND_SETTERS)) { writer.writeComment("--- getters and setters disabled by plugin flag"); } else { writer.writeComment("--- getters and setters"); for (PropertyGenerator generator : modelSpec.getPropertyGenerators()) { emitGetter(writer, generator); emitSetter(writer, generator); } } } private void emitGetter(JavaFileWriter writer, PropertyGenerator generator) throws IOException { generator.beforeEmitGetter(writer); generator.emitGetter(writer); generator.afterEmitGetter(writer); } private void emitSetter(JavaFileWriter writer, PropertyGenerator generator) throws IOException { generator.beforeEmitSetter(writer); generator.emitSetter(writer); generator.afterEmitSetter(writer); } private void emitCreator() throws IOException { writer.writeComment("--- parcelable helpers"); List<DeclaredTypeName> genericList = Collections.singletonList(modelSpec.getGeneratedClassName()); DeclaredTypeName creatorType = TypeConstants.CREATOR.clone(); DeclaredTypeName modelCreatorType = TypeConstants.MODEL_CREATOR.clone(); creatorType.setTypeArgs(genericList); modelCreatorType.setTypeArgs(genericList); writer.writeFieldDeclaration(creatorType, "CREATOR", Expressions.callConstructor(modelCreatorType, Expressions.classObject(modelSpec.getGeneratedClassName())), TypeConstants.PUBLIC_STATIC_FINAL) .writeNewline(); writer.writeAnnotation(CoreTypes.OVERRIDE) .beginMethodDefinition(GET_CREATOR_PARAMS) .writeStringStatement("return CREATOR") .finishMethodDefinition(); } protected void emitModelSpecificHelpers() throws IOException { // Subclasses can override } }
package org.objectweb.proactive.examples.components.userguide; import java.util.HashMap; import java.util.Map; import org.objectweb.fractal.adl.Factory; import org.objectweb.fractal.api.Component; import org.objectweb.fractal.api.control.LifeCycleController; import org.objectweb.fractal.api.factory.GenericFactory; import org.objectweb.fractal.api.type.ComponentType; import org.objectweb.fractal.api.type.InterfaceType; import org.objectweb.fractal.api.type.TypeFactory; import org.objectweb.fractal.util.Fractal; import org.objectweb.proactive.ActiveObjectCreationException; import org.objectweb.proactive.api.PAActiveObject; import org.objectweb.proactive.api.PADeployment; import org.objectweb.proactive.core.ProActiveException; import org.objectweb.proactive.core.component.Constants; import org.objectweb.proactive.core.component.ContentDescription; import org.objectweb.proactive.core.component.ControllerDescription; import org.objectweb.proactive.core.component.factory.ProActiveGenericFactory; import org.objectweb.proactive.core.descriptor.data.ProActiveDescriptor; import org.objectweb.proactive.core.descriptor.data.VirtualNode; import org.objectweb.proactive.core.node.Node; import org.objectweb.proactive.core.node.NodeException; import org.objectweb.proactive.examples.components.userguide.primitive.ComputeItf; import org.objectweb.proactive.examples.components.userguide.primitive.One; import org.objectweb.proactive.examples.components.userguide.primitive.PrimitiveComputer; import org.objectweb.proactive.examples.components.userguide.primitive.PrimitiveMaster; //TODO replace false and true by TypeFactory.SERVER ... public class Main { public static void main(String[] args) { //System.out.println("Launch and deploy a simple AO:"); // Main.launchAndDeployAO(); // System.out.println("Launch primitive component example"); // Main.launchFirstPrimitive(); //System.out.println("Launch component assembly example"); // Main.launchWithoutADL(); System.out.println("Launch and deploy component assembly example"); Main.launchAndDeployWithoutADL(); // System.out.println("Launch component assembly example with ADL"); // Main.launchOneWithADL(); // System.out.println( // "Launch and deploy component assembly example with ADL"); // Main.launchAndDeployWithADL(); //System.err.println("The END..."); //System.exit(0); } private static void launchAndDeployAO() { ProActiveDescriptor pad = null; try { pad = PADeployment.getProactiveDescriptor(Main.class.getResource("deploymentDescriptor.xml") .getPath()); } catch (ProActiveException e) { e.printStackTrace(); } VirtualNode vn = pad.getVirtualNode("primitive-node"); System.out.println("Main.launchAndDeployAO() activate"); vn.activate(); A a = null; try { System.out.println("Main.launchAndDeployAO() new Active"); a = (A) PAActiveObject.newActive("org.objectweb.proactive.examples.components.userguide.A", new Object[0], vn.getNode()); } catch (ActiveObjectCreationException e) { e.printStackTrace(); } catch (NodeException e) { e.printStackTrace(); } System.out.println("Main.launchAndDeployAO() creation OK"); System.err.println("Random : " + a.random()); PAActiveObject.terminateActiveObject(a, false); try { pad.killall(false); } catch (ProActiveException e) { e.printStackTrace(); } } private static void launchFirstPrimitive() { try { Component boot = Fractal.getBootstrapComponent(); TypeFactory typeFact = Fractal.getTypeFactory(boot); GenericFactory genericFact = Fractal.getGenericFactory(boot); Component primitiveComputer = null; // type of PrimitiveComputer component ComponentType computerType = typeFact.createFcType(new InterfaceType[] { typeFact.createFcItfType("compute-itf", ComputeItf.class.getName(), TypeFactory.SERVER, TypeFactory.MANDATORY, TypeFactory.SINGLE), typeFact.createFcItfType("on", One.class.getName(), TypeFactory.SERVER, TypeFactory.MANDATORY, TypeFactory.SINGLE) }); // component creation primitiveComputer = genericFact.newFcInstance(computerType, new ControllerDescription("root", Constants.PRIMITIVE), new ContentDescription(PrimitiveComputer.class.getName())); // start PrimitiveComputer component Fractal.getLifeCycleController(primitiveComputer).startFc(); ((LifeCycleController) primitiveComputer.getFcInterface("lifecycle-controller")).startFc(); // get the compute-itf interface ComputeItf itf = ((ComputeItf) primitiveComputer.getFcInterface("compute-itf")); One itf2 = ((One) primitiveComputer.getFcInterface("on")); System.err.println("itf2 class: " + itf2.getClass()); ; // call component itf.doNothing(); int result = itf.compute(5); String result2 = itf2.helloWorld("Me"); System.out.println("Result of computation whith 5 is: " + result); //display 10 System.out.println("Result2 of hello is: " + result2); //display 10 } catch (Exception e) { e.printStackTrace(); } } private static void launchWithoutADL() { try { Component boot = Fractal.getBootstrapComponent(); TypeFactory typeFact = Fractal.getTypeFactory(boot); GenericFactory genericFact = Fractal.getGenericFactory(boot); // component types: PrimitiveComputer, PrimitiveMaster, CompositeWrapper ComponentType computerType = typeFact.createFcType(new InterfaceType[] { typeFact .createFcItfType("compute-itf", ComputeItf.class.getName(), TypeFactory.SERVER, TypeFactory.MANDATORY, TypeFactory.SINGLE) }); ComponentType masterType = typeFact.createFcType(new InterfaceType[] { typeFact.createFcItfType("run", Runnable.class.getName(), TypeFactory.SERVER, TypeFactory.MANDATORY, TypeFactory.SINGLE), typeFact.createFcItfType("compute-itf", ComputeItf.class.getName(), TypeFactory.CLIENT, TypeFactory.MANDATORY, TypeFactory.SINGLE) }); ComponentType wrapperType = typeFact.createFcType(new InterfaceType[] { typeFact.createFcItfType( "run", Runnable.class.getName(), TypeFactory.SERVER, TypeFactory.MANDATORY, TypeFactory.SINGLE) }); // components creation Component primitiveComputer = genericFact.newFcInstance(computerType, new ControllerDescription( "PrimitiveComputer", Constants.PRIMITIVE), new ContentDescription(PrimitiveComputer.class .getName())); Component primitiveMaster = genericFact.newFcInstance(masterType, new ControllerDescription( "PrimitiveMaster", Constants.PRIMITIVE), new ContentDescription(PrimitiveMaster.class .getName())); Component compositeWrapper = genericFact.newFcInstance(wrapperType, new ControllerDescription( "CompositeWrapper", Constants.COMPOSITE), null); // component assembling Fractal.getContentController(compositeWrapper).addFcSubComponent(primitiveComputer); Fractal.getContentController(compositeWrapper).addFcSubComponent(primitiveMaster); primitiveMaster.getFcInterface("run"); Fractal.getBindingController(compositeWrapper).bindFc("run", primitiveMaster.getFcInterface("run")); Fractal.getBindingController(primitiveMaster).bindFc("compute-itf", primitiveComputer.getFcInterface("compute-itf")); // start CompositeWrapper component Fractal.getLifeCycleController(compositeWrapper).startFc(); // get the run interface Runnable itf = ((Runnable) compositeWrapper.getFcInterface("run")); // call component itf.run(); } catch (Exception e) { e.printStackTrace(); } } private static void launchAndDeployWithoutADL() { try { Component boot = Fractal.getBootstrapComponent(); TypeFactory typeFact = Fractal.getTypeFactory(boot); ProActiveGenericFactory genericFact = (ProActiveGenericFactory) Fractal.getGenericFactory(boot); ProActiveDescriptor deploymentDescriptor = PADeployment.getProactiveDescriptor(Main.class .getResource("deploymentDescriptor.xml").getPath()); //context.put("deployment-descriptor", deploymentDescriptor); deploymentDescriptor.activateMappings(); VirtualNode vnode = deploymentDescriptor.getVirtualNode("primitive-node"); vnode.activate(); Node node1 = vnode.getNode(); // Node[] nodes = vnode.getNodes(); // component types: PrimitiveComputer, PrimitiveMaster, CompositeWrapper ComponentType computerType = typeFact.createFcType(new InterfaceType[] { typeFact .createFcItfType("compute-itf", ComputeItf.class.getName(), TypeFactory.SERVER, TypeFactory.MANDATORY, TypeFactory.SINGLE) }); ComponentType masterType = typeFact.createFcType(new InterfaceType[] { typeFact.createFcItfType("run", Runnable.class.getName(), TypeFactory.SERVER, TypeFactory.MANDATORY, TypeFactory.SINGLE), typeFact.createFcItfType("compute-itf", ComputeItf.class.getName(), TypeFactory.CLIENT, TypeFactory.MANDATORY, TypeFactory.SINGLE) }); ComponentType wrapperType = typeFact.createFcType(new InterfaceType[] { typeFact.createFcItfType( "run", Runnable.class.getName(), TypeFactory.SERVER, TypeFactory.MANDATORY, TypeFactory.SINGLE) }); // components creation Component primitiveComputer = genericFact.newFcInstance(computerType, new ControllerDescription( "PrimitiveComputer", Constants.PRIMITIVE), new ContentDescription(PrimitiveComputer.class .getName()), node1); Component primitiveMaster = genericFact.newFcInstance(masterType, new ControllerDescription( "PrimitiveMaster", Constants.PRIMITIVE), new ContentDescription(PrimitiveMaster.class .getName())); Component compositeWrapper = genericFact.newFcInstance(wrapperType, new ControllerDescription( "CompositeWrapper", Constants.COMPOSITE), null); // component assembling Fractal.getContentController(compositeWrapper).addFcSubComponent(primitiveComputer); Fractal.getContentController(compositeWrapper).addFcSubComponent(primitiveMaster); primitiveMaster.getFcInterface("run"); Fractal.getBindingController(compositeWrapper).bindFc("run", primitiveMaster.getFcInterface("run")); Fractal.getBindingController(primitiveMaster).bindFc("compute-itf", primitiveComputer.getFcInterface("compute-itf")); // start CompositeWrapper component Fractal.getLifeCycleController(compositeWrapper).startFc(); // get the run interface Runnable itf = ((Runnable) compositeWrapper.getFcInterface("run")); // call component while (true) { Thread.sleep(1000); itf.run(); } } catch (Exception e) { e.printStackTrace(); } } private static void launchWithADL() { try { Factory f = org.objectweb.proactive.core.component.adl.FactoryFactory.getFactory(); Map<String, Object> context = new HashMap<String, Object>(); // component creation Component compositeWrapper = (Component) f.newComponent( "org.objectweb.proactive.examples.components.userguide.adl.CompositeWrapper", context); // start PrimitiveComputer component Fractal.getLifeCycleController(compositeWrapper).startFc(); // get the run interface Runnable itf = ((Runnable) compositeWrapper.getFcInterface("run")); // call component itf.run(); } catch (Exception e) { e.printStackTrace(); } } private static void launchOneWithADL() { try { Factory f = org.objectweb.proactive.core.component.adl.FactoryFactory.getFactory(); Map<String, Object> context = new HashMap<String, Object>(); // component creation Component compositeWrapper = (Component) f.newComponent( "org.objectweb.proactive.examples.components.userguide.adl.PrimitiveComputer", context); // start PrimitiveComputer component Fractal.getLifeCycleController(compositeWrapper).startFc(); // get the run interface ComputeItf itf = ((ComputeItf) compositeWrapper.getFcInterface("compute-itf")); One itf2 = ((One) compositeWrapper.getFcInterface("on")); // call component System.out.println("Result compute: " + itf2.helloWorld("sss")); System.out.println("Result compute: " + itf.compute(2)); } catch (Exception e) { e.printStackTrace(); } } private static void launchAndDeployWithADL() { try { // get the component Factory allowing component creation from ADL Factory f = org.objectweb.proactive.core.component.adl.FactoryFactory.getFactory(); Map<String, Object> context = new HashMap<String, Object>(); // retrieve the deployment descriptor ProActiveDescriptor deploymentDescriptor = PADeployment.getProactiveDescriptor(Main.class .getResource("deploymentDescriptor.xml").getPath()); context.put("deployment-descriptor", deploymentDescriptor); deploymentDescriptor.activateMappings(); // System.out.println("sleep"); // Thread.sleep(10000); // System.out.println("wake up"); // component creation Component compositeWrapper = (Component) f.newComponent( "org.objectweb.proactive.examples.components.userguide.adl.CompositeWrapper", context); System.out.println("certion OK"); // start PrimitiveComputer component Fractal.getLifeCycleController(compositeWrapper).startFc(); System.out.println("start OK"); // get the compute-itf interface Runnable itf = ((Runnable) compositeWrapper.getFcInterface("run")); // call component itf.run(); System.out.println("call OK"); Thread.sleep(1000); // wait for the end of execution // and kill JVM created with the deployment descriptor deploymentDescriptor.killall(false); } catch (Exception e) { e.printStackTrace(); } } }
package experimentalcode.erich.histogram; import java.util.HashMap; import java.util.List; import de.lmu.ifi.dbs.elki.algorithm.AbstractAlgorithm; import de.lmu.ifi.dbs.elki.algorithm.Algorithm; import de.lmu.ifi.dbs.elki.data.DatabaseObject; import de.lmu.ifi.dbs.elki.database.AssociationID; import de.lmu.ifi.dbs.elki.database.Database; import de.lmu.ifi.dbs.elki.result.AnnotationFromHashMap; import de.lmu.ifi.dbs.elki.result.AnnotationResult; import de.lmu.ifi.dbs.elki.result.MultiResult; import de.lmu.ifi.dbs.elki.result.Result; import de.lmu.ifi.dbs.elki.result.ResultUtil; import de.lmu.ifi.dbs.elki.utilities.Description; import de.lmu.ifi.dbs.elki.utilities.optionhandling.ClassParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID; import de.lmu.ifi.dbs.elki.utilities.optionhandling.ParameterException; import de.lmu.ifi.dbs.elki.utilities.optionhandling.Parameterizable; public class NormalizeOutlierScoreMetaAlgorithm<O extends DatabaseObject> extends AbstractAlgorithm<O, Result> { /** * Association ID for scaled values */ public static final AssociationID<Double> SCALED_SCORE = AssociationID.getOrCreateAssociationID("SCALED_SCORE", Double.class); /** * OptionID for {@link #SCALING_PARAM} */ public static final OptionID SCALING_ID = OptionID.getOrCreateOptionID("comphist.scaling", "Class to use as scaling function."); /** * Parameter to specify the algorithm to be applied, must extend * {@link de.lmu.ifi.dbs.elki.algorithm.Algorithm}. * <p> * Key: {@code -algorithm} * </p> */ private final ClassParameter<Algorithm<O, Result>> ALGORITHM_PARAM = new ClassParameter<Algorithm<O, Result>>(OptionID.ALGORITHM, Algorithm.class); /** * Parameter to specify a scaling function to use. * <p> * Key: {@code -comphist.scaling} * </p> */ private final ClassParameter<OutlierScalingFunction> SCALING_PARAM = new ClassParameter<OutlierScalingFunction>(SCALING_ID, OutlierScalingFunction.class, IdentityScaling.class.getName()); /** * Holds the algorithm to run. */ private Algorithm<O, Result> algorithm; /** * Stores the result object. */ private MultiResult result; /** * Scaling function to use */ private OutlierScalingFunction scaling; public NormalizeOutlierScoreMetaAlgorithm() { addOption(ALGORITHM_PARAM); addOption(SCALING_PARAM); } @Override protected Result runInTime(Database<O> database) throws IllegalStateException { Result innerresult = algorithm.run(database); AnnotationResult<Double> ann = getAnnotationResult(database, innerresult); scaling.prepare(database, innerresult, ann); HashMap<Integer, Double> scaledscores = new HashMap<Integer, Double>(database.size()); for(Integer id : database) { double val = ann.getValueFor(id); val = scaling.getScaled(val); scaledscores.put(id, val); } if (innerresult instanceof MultiResult) { result = (MultiResult) innerresult; } else { result = new MultiResult(); result.addResult(innerresult); } result.prependResult(new AnnotationFromHashMap<Double>(SCALED_SCORE, scaledscores)); return result; } /** * Find an AnnotationResult that contains Doubles. * * @param database Database context * @param result Result object * @return Iterator to work with */ @SuppressWarnings("unchecked") private AnnotationResult<Double> getAnnotationResult(Database<O> database, Result result) { List<AnnotationResult<?>> annotations = ResultUtil.getAnnotationResults(result); for(AnnotationResult<?> ann : annotations) { if(Double.class.isAssignableFrom(ann.getAssociationID().getType())) { return (AnnotationResult<Double>) ann; } } throw new IllegalStateException("Comparison algorithm expected at least one Annotation<Double> result, got " + annotations.size() + " annotation results."); } @Override public Description getDescription() { // TODO Auto-generated method stub return null; } @Override public MultiResult getResult() { return result; } @Override public List<String> setParameters(List<String> args) throws ParameterException { List<String> remainingParameters = super.setParameters(args); // algorithm algorithm = ALGORITHM_PARAM.instantiateClass(); addParameterizable(algorithm); remainingParameters = algorithm.setParameters(remainingParameters); // scaling function scaling = SCALING_PARAM.instantiateClass(); if (scaling instanceof Parameterizable) { Parameterizable param = (Parameterizable) scaling; addParameterizable(param); remainingParameters = param.setParameters(remainingParameters); } return remainingParameters; } }
package org.xins.client; import org.xins.common.MandatoryArgumentChecker; import org.xins.common.collections.PropertyReader; import org.xins.common.service.TargetDescriptor; /** * Exception that indicates that a result code was returned by the API call. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>) * * @since XINS 1.0.0 */ public class UnsuccessfulXINSCallException extends XINSCallException implements XINSCallResultData { // NOTE: Since XINS 1.1.0, this class is no longer final. However, all // methods still are. // NOTE: Since XINS 1.2.0, this class implements the XINSCallResultData // interface. // Class fields // Class functions private static final String determineDetail(XINSCallResultData result, String detail) throws IllegalArgumentException { // Argument cannot be null MandatoryArgumentChecker.check("result", result); // Result must be unsuccessful String errorCode = result.getErrorCode(); if (errorCode == null) { throw new IllegalArgumentException("result.getErrorCode() == null"); } if (detail == null || detail.length() < 1) { return "Error code \"" + errorCode + "\"."; } else { return "Error code \"" + errorCode + "\": " + detail; } } // Constructors UnsuccessfulXINSCallException(XINSCallRequest request, TargetDescriptor target, long duration, XINSCallResultData resultData, String detail) throws IllegalArgumentException { super("Unsuccessful XINS call result", request, target, duration, determineDetail(resultData, detail), null); // Check additional precondition MandatoryArgumentChecker.check("resultData", resultData); // TODO: Check all mandatory arguments at once // Result object must be unsuccessful String errorCode = resultData.getErrorCode(); if (errorCode == null) { throw new IllegalArgumentException("resultData.getErrorCode() == null"); } // Store details _result = resultData; } // Fields /** * The result data. The value of this field cannot be <code>null</code>. */ private final XINSCallResultData _result; // Methods /** * Returns the error code. * * @return * the error code, never <code>null</code>. */ public final String getErrorCode() { return _result.getErrorCode(); } /** * Gets all returned parameters. * * @return * a {@link PropertyReader} containing all parameters, or * <code>null</code> if there are none. */ public final PropertyReader getParameters() { return _result.getParameters(); } public final String getParameter(String name) throws IllegalArgumentException { PropertyReader p = getParameters(); if (p == null) { return null; } else { return p.get(name); } } /** * Returns the optional extra data. * * @return * the extra data as a {@link DataElement}, can be <code>null</code>; */ public final DataElement getDataElement() { return _result.getDataElement(); } }
package org.helioviewer.jhv.data.container.cache; import java.awt.Color; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.Set; import java.util.TreeMap; import org.helioviewer.jhv.data.container.util.DateUtil; import org.helioviewer.jhv.data.datatype.event.JHVEvent; import org.helioviewer.jhv.data.datatype.event.JHVEventParameter; import org.helioviewer.jhv.data.datatype.event.JHVEventRelation; import org.helioviewer.jhv.data.datatype.event.JHVEventRelationShipRule; import org.helioviewer.jhv.data.datatype.event.JHVEventType; import org.helioviewer.jhv.data.datatype.event.JHVRelatedOn; public class JHVEventCache { /** singleton instance of JHVevent cache */ private static JHVEventCache instance; /** The events received for a certain date */ private final Map<Date, Map<Date, List<JHVEvent>>> events; /** A set with IDs */ private final Set<String> eventIDs; private final Map<String, JHVEvent> allEvents; private final Map<String, List<JHVEvent>> missingEventsInEventRelations; private final Map<Color, Set<String>> idsPerColor; private final List<JHVEvent> eventsWithRelationRules; private final Set<JHVEventType> activeEventTypes; /** * private default constructor */ private JHVEventCache() { events = new HashMap<Date, Map<Date, List<JHVEvent>>>(); eventIDs = new HashSet<String>(); allEvents = new HashMap<String, JHVEvent>(); missingEventsInEventRelations = new HashMap<String, List<JHVEvent>>(); idsPerColor = new HashMap<Color, Set<String>>(); eventsWithRelationRules = new ArrayList<JHVEvent>(); activeEventTypes = new HashSet<JHVEventType>(); } /** * Gets the singleton instance of the JHV event cache. * * @return singleton instance of the cache. */ public static JHVEventCache getSingletonInstance() { if (instance == null) { instance = new JHVEventCache(); } return instance; } /** * Add the JHV event to the cache * * @param event * the event to add */ public void add(JHVEvent event) { activeEventTypes.add(event.getJHVEventType()); if (!eventIDs.contains(event.getUniqueID())) { allEvents.put(event.getUniqueID(), event); Date startDate = DateUtil.getCurrentDate(event.getStartDate()); Date endDate = DateUtil.getNextDate(event.getEndDate()); addToList(startDate, endDate, event); eventIDs.add(event.getUniqueID()); checkAndFixRelationShip(event); } else { JHVEvent savedEvent = allEvents.get(event.getUniqueID()); savedEvent.merge(event); } } /** * Gets the events containing the given date. * * @param date * The date in which the event should have happened * @return the list of events happened on the given date */ public Map<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>> get(Date date) { Map<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>> eventsResult = new HashMap<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>>(); if (!activeEventTypes.isEmpty()) { Calendar reference = Calendar.getInstance(); reference.setTime(date); for (Date sDate : events.keySet()) { Calendar tempS = Calendar.getInstance(); tempS.setTime(sDate); if (tempS.compareTo(reference) <= 0) { Map<Date, List<JHVEvent>> eventOnEndTime = events.get(sDate); for (Date eDate : eventOnEndTime.keySet()) { Calendar tempE = Calendar.getInstance(); tempE.setTime(eDate); if (tempE.compareTo(reference) >= 0) { addEventsToResult(eventsResult, eventOnEndTime.get(eDate)); } } } } } return eventsResult; } /** * Gets the events containing on of the dates in the list of date. * * @param dates * list of dates for which events are requested * @return the list of events that are available for the dates */ public Map<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>> get(List<Date> dates) { Map<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>> eventsResult = new HashMap<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>>(); if (!activeEventTypes.isEmpty()) { for (Date date : dates) { eventsResult = mergeMaps(eventsResult, get(date)); } } return eventsResult; } /** * Gets the events that are available within the interval. * * @param startDate * start date of the interval * @param endDate * end date of the interval * @return the list of events that are available in the interval */ public Map<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>> get(Date startDate, Date endDate) { Map<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>> eventsResult = new HashMap<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>>(); if (!activeEventTypes.isEmpty()) { Calendar intervalS = Calendar.getInstance(); intervalS.setTime(startDate); Calendar intervalE = Calendar.getInstance(); intervalE.setTime(endDate); for (Date sDate : events.keySet()) { Calendar tempS = Calendar.getInstance(); tempS.setTime(sDate); // event starts after interval start but before interval end if (intervalS.compareTo(tempS) <= 0 && intervalE.compareTo(tempS) >= 0) { for (List<JHVEvent> tempEvent : events.get(sDate).values()) { addEventsToResult(eventsResult, tempEvent); } } // event start before interval start and end after interval // start Map<Date, List<JHVEvent>> endDatesEvents = events.get(sDate); for (Date eDate : endDatesEvents.keySet()) { Calendar tempE = Calendar.getInstance(); tempE.setTime(eDate); if (intervalS.compareTo(tempS) >= 0 && intervalS.compareTo(tempE) <= 0) { addEventsToResult(eventsResult, endDatesEvents.get(eDate)); } } } } return eventsResult; } /** * Removes all the events of the given event type from the event cache. * * @param eventType * the event type to remove */ public void removeEventType(JHVEventType eventType) { activeEventTypes.remove(eventType); /* * for (Map<Date, List<JHVEvent>> endDateEvents : events.values()) { for * (List<JHVEvent> eventList : endDateEvents.values()) { List<JHVEvent> * deleteList = new ArrayList<JHVEvent>(); for (JHVEvent event : * eventList) { if (event.getJHVEventType().equals(eventType)) { * deleteList.add(event); eventIDs.remove(event.getUniqueID()); * allEvents.remove(event.getUniqueID()); * missingEventsInEventRelations.remove(event.getUniqueID()); * eventsWithRelationRules.remove(event); for (JHVEventRelation relation * : event.getEventRelationShip().getRelatedEventsByRule().values()) { * if (relation.getTheEvent() != null) { * relation.getTheEvent().getEventRelationShip * ().getRelatedEventsByRule().remove(event.getUniqueID()); } } } } * eventList.removeAll(deleteList); } } */ } private void checkAndFixRelationShip(JHVEvent event) { checkRelationColor(event); checkMissingRelations(event); checkAndFixNextRelatedEvents(event); checkAndFixPrecedingRelatedEvents(event); checkAndFixRelatedEventsByRule(event); executeRelationshipRules(event); } private void executeRelationshipRules(JHVEvent event) { List<JHVEventRelationShipRule> rules = event.getEventRelationShip().getRelationshipRules(); for (JHVEventRelationShipRule rule : rules) { // Go over the rules for (JHVEvent candidate : eventsWithRelationRules) { // Check new candidate if (candidate.getJHVEventType().getEventType().toLowerCase().equals(rule.getRelatedWith().getEventType().toLowerCase())) { // Candidate has the correct event type int foundCorrespondinParameters = 0; for (JHVRelatedOn relatedOn : rule.getRelatedOn()) { // Check all the related on parameters for (JHVEventParameter p : candidate.getAllEventParameters()) { // Loop over candidate parameters if (relatedOn.getRelatedOnWith().getParameterName().toLowerCase().equals(p.getParameterName().toLowerCase())) { // Candidate has the related on parameter for (JHVEventParameter eventP : event.getAllEventParameters()) { // Loop over the event parameter to find the // value of the related on parameter if (eventP.getParameterName().toLowerCase().equals(relatedOn.getRelatedOnWith().getParameterName().toLowerCase())) { // Parameter found in the event if (eventP.getParameterValue() != null && p.getParameterValue() != null && eventP.getParameterValue().equals(p.getParameterValue())) { // at least one of the related on // parameters found foundCorrespondinParameters++; } } else { // parameter not found in the event skip // rule. } } } } } if (foundCorrespondinParameters == rule.getRelatedOn().size()) { event.getEventRelationShip().getRelatedEventsByRule().put(candidate.getUniqueID(), new JHVEventRelation(candidate.getUniqueID(), candidate)); candidate.getEventRelationShip().getRelatedEventsByRule().put(event.getUniqueID(), new JHVEventRelation(event.getUniqueID(), event)); } } } } eventsWithRelationRules.add(event); } private void checkRelationColor(JHVEvent event) { if (event.getEventRelationShip().getRelationshipColor() == null) { event.getEventRelationShip().setRelationshipColor(JHVCacheColors.getNextColor()); } if (idsPerColor.containsKey(event.getEventRelationShip().getRelationshipColor())) { // Color of event is already used check if the event is in the // list // of events that can use the color Set<String> ids = idsPerColor.get(event.getEventRelationShip().getRelationshipColor()); if (ids.contains(event.getUniqueID())) { // The event is in the list of events, add the following and // preceding event ids to the list and give them the correct // color addRelatedEvents(event, new HashSet<String>()); } else { // The event is not in the list check if one of the // following or // preceding events is in the list if (checkFollowingAndPrecedingEvents(event)) { addRelatedEvents(event, new HashSet<String>()); } else { Color c = JHVCacheColors.getNextColor(); event.getEventRelationShip().setRelationshipColor(c); ids = new HashSet<String>(); ids.add(event.getUniqueID()); idsPerColor.put(event.getEventRelationShip().getRelationshipColor(), ids); addRelatedEvents(event, new HashSet<String>()); } } } else { // Color not present add the color and add all the preceding and // following event unique identifiers. Check the color of them. HashSet<String> ids = new HashSet<String>(); ids.add(event.getUniqueID()); JHVCacheColors.setColorUsed(event.getEventRelationShip().getRelationshipColor()); idsPerColor.put(event.getEventRelationShip().getRelationshipColor(), ids); addRelatedEvents(event, new HashSet<String>()); } } private void addRelatedEvents(JHVEvent event, Set<String> handledEvents) { if (!handledEvents.contains(event.getUniqueID())) { handledEvents.add(event.getUniqueID()); for (JHVEventRelation relation : event.getEventRelationShip().getNextEvents().values()) { if (relation.getTheEvent() != null) { relation.getTheEvent().getEventRelationShip().setRelationshipColor(event.getEventRelationShip().getRelationshipColor()); idsPerColor.get(event.getEventRelationShip().getRelationshipColor()).add(relation.getTheEvent().getUniqueID()); addRelatedEvents(event, handledEvents); } } for (JHVEventRelation relation : event.getEventRelationShip().getPrecedingEvents().values()) { if (relation.getTheEvent() != null) { relation.getTheEvent().getEventRelationShip().setRelationshipColor(event.getEventRelationShip().getRelationshipColor()); idsPerColor.get(event.getEventRelationShip().getRelationshipColor()).add(relation.getTheEvent().getUniqueID()); addRelatedEvents(event, handledEvents); } } } } private boolean checkFollowingAndPrecedingEvents(JHVEvent event) { if (checkPrecedingEvents(event, event.getEventRelationShip().getPrecedingEvents())) { return true; } else { return checkFollowingEvent(event, event.getEventRelationShip().getNextEvents()); } } private boolean checkPrecedingEvents(JHVEvent event, Map<String, JHVEventRelation> precedingEvents) { for (String key : precedingEvents.keySet()) { if (idsPerColor.get(event.getEventRelationShip().getRelationshipColor()).contains(key)) { return true; } else { if (precedingEvents.get(key).getTheEvent() != null) { return checkFollowingEvent(event, precedingEvents.get(key).getTheEvent().getEventRelationShip().getPrecedingEvents()); } } } return false; } private boolean checkFollowingEvent(JHVEvent event, Map<String, JHVEventRelation> nextEvents) { for (String key : nextEvents.keySet()) { if (idsPerColor.get(event.getEventRelationShip().getRelationshipColor()).contains(key)) { return true; } else { if (nextEvents.get(key).getTheEvent() != null) { return checkFollowingEvent(event, nextEvents.get(key).getTheEvent().getEventRelationShip().getNextEvents()); } } } return false; } private void checkMissingRelations(JHVEvent event) { if (missingEventsInEventRelations.containsKey(event.getUniqueID())) { List<JHVEvent> listOfRelatedEvents = missingEventsInEventRelations.get(event.getUniqueID()); for (JHVEvent relatedEvent : listOfRelatedEvents) { if (relatedEvent.getEventRelationShip().getNextEvents().containsKey(event.getUniqueID())) { JHVEventRelation relation = relatedEvent.getEventRelationShip().getNextEvents().get(event.getUniqueID()); relation.setTheEvent(event); event.getEventRelationShip().setRelationshipColor(relatedEvent.getColor()); } if (relatedEvent.getEventRelationShip().getPrecedingEvents().containsKey(event.getUniqueID())) { JHVEventRelation relation = relatedEvent.getEventRelationShip().getPrecedingEvents().get(event.getUniqueID()); relation.setTheEvent(event); relatedEvent.getEventRelationShip().setRelationshipColor(event.getEventRelationShip().getRelationshipColor()); } /* * if * (relatedEvent.getEventRelationShip().getRelationshipRules() * .containsKey(event.getUniqueID())) { JHVEventRelation * relation = * relatedEvent.getEventRelationShip().getRelatedEventsByRule * ().get(event.getUniqueID()); relation.setTheEvent(event); } */ } missingEventsInEventRelations.remove(event.getUniqueID()); } } private void checkAndFixNextRelatedEvents(JHVEvent event) { for (JHVEventRelation er : event.getEventRelationShip().getNextEvents().values()) { if (er.getTheEvent() == null) { if (allEvents.containsKey(er.getUniqueIdentifier())) { er.setTheEvent(allEvents.get(er.getUniqueIdentifier())); er.getTheEvent().getEventRelationShip().setRelationshipColor(event.getEventRelationShip().getRelationshipColor()); } else { List<JHVEvent> missingRelations = new ArrayList<JHVEvent>(); if (missingEventsInEventRelations.containsKey(er.getUniqueIdentifier())) { missingRelations = missingEventsInEventRelations.get(er.getUniqueIdentifier()); } missingRelations.add(event); missingEventsInEventRelations.put(er.getUniqueIdentifier(), missingRelations); } } } } private void checkAndFixPrecedingRelatedEvents(JHVEvent event) { for (JHVEventRelation er : event.getEventRelationShip().getPrecedingEvents().values()) { if (er.getTheEvent() == null) { if (allEvents.containsKey(er.getUniqueIdentifier())) { JHVEvent relatedEvent = allEvents.get(er.getUniqueIdentifier()); er.setTheEvent(relatedEvent); event.getEventRelationShip().setRelationshipColor(relatedEvent.getEventRelationShip().getRelationshipColor()); } else { List<JHVEvent> missingRelations = new ArrayList<JHVEvent>(); if (missingEventsInEventRelations.containsKey(er.getUniqueIdentifier())) { missingRelations = missingEventsInEventRelations.get(er.getUniqueIdentifier()); } missingRelations.add(event); missingEventsInEventRelations.put(er.getUniqueIdentifier(), missingRelations); } } } } private void checkAndFixRelatedEventsByRule(JHVEvent event) { for (JHVEventRelation er : event.getEventRelationShip().getRelatedEventsByRule().values()) { if (er.getTheEvent() == null) { if (allEvents.containsKey(er.getUniqueIdentifier())) { JHVEvent relatedEvent = allEvents.get(er.getUniqueIdentifier()); er.setTheEvent(relatedEvent); } else { List<JHVEvent> missingRelations = new ArrayList<JHVEvent>(); if (missingEventsInEventRelations.containsKey(er.getUniqueIdentifier())) { missingRelations = missingEventsInEventRelations.get(er.getUniqueIdentifier()); } missingRelations.add(event); missingEventsInEventRelations.put(er.getUniqueIdentifier(), missingRelations); } } } } /** * Adds the event with cache date start date and end date to the event * cache. * * @param startDate * the cache start date of the event * @param endDate * the cache end date of the event * @param event * the event to add */ private void addToList(Date startDate, Date endDate, JHVEvent event) { Map<Date, List<JHVEvent>> eventsOnStartDate = new HashMap<Date, List<JHVEvent>>(); List<JHVEvent> eventsOnStartEndDate = new ArrayList<JHVEvent>(); if (events.containsKey(startDate)) { eventsOnStartDate = events.get(startDate); if (eventsOnStartDate.containsKey(endDate)) { eventsOnStartEndDate = eventsOnStartDate.get(endDate); } } eventsOnStartEndDate.add(event); eventsOnStartDate.put(endDate, eventsOnStartEndDate); events.put(startDate, eventsOnStartDate); } /** * Adds a list of events to the given result. * * @param eventsResult * the result to which the data should be added * @param tempEvents * the events that should be added */ private void addEventsToResult(Map<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>> eventsResult, List<JHVEvent> tempEvents) { for (JHVEvent event : tempEvents) { if (activeEventTypes.contains(event.getJHVEventType())) { NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>> datesPerType = new TreeMap<Date, NavigableMap<Date, List<JHVEvent>>>(); NavigableMap<Date, List<JHVEvent>> endDatesPerStartDate = new TreeMap<Date, List<JHVEvent>>(); List<JHVEvent> events = new ArrayList<JHVEvent>(); if (eventsResult.containsKey(event.getJHVEventType().getEventType())) { datesPerType = eventsResult.get(event.getJHVEventType().getEventType()); if (datesPerType.containsKey(event.getStartDate())) { endDatesPerStartDate = datesPerType.get(event.getStartDate()); if (endDatesPerStartDate.containsKey(event.getEndDate())) { events = endDatesPerStartDate.get(event.getEndDate()); } } } events.add(event); endDatesPerStartDate.put(event.getEndDate(), events); datesPerType.put(event.getStartDate(), endDatesPerStartDate); eventsResult.put(event.getJHVEventType().getEventType(), datesPerType); } } } private Map<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>> mergeMaps(Map<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>> eventsResult, Map<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>> map) { for (String eventType : map.keySet()) { if (eventsResult.containsKey(eventType)) { NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>> datesPerTypeMap = map.get(eventType); NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>> datesPerTypeResult = eventsResult.get(eventType); for (Date sDate : datesPerTypeMap.keySet()) { if (datesPerTypeResult.containsKey(sDate)) { NavigableMap<Date, List<JHVEvent>> endDatesPerStartDateMap = datesPerTypeMap.get(sDate); NavigableMap<Date, List<JHVEvent>> endDatesPerStartDateResult = datesPerTypeResult.get(sDate); for (Date eDate : endDatesPerStartDateMap.keySet()) { if (endDatesPerStartDateResult.containsKey(eDate)) { endDatesPerStartDateResult.get(eDate).addAll(endDatesPerStartDateMap.get(eDate)); } else { endDatesPerStartDateResult.put(eDate, endDatesPerStartDateMap.get(eDate)); } } } else { datesPerTypeResult.put(sDate, datesPerTypeMap.get(sDate)); } } } else { eventsResult.put(eventType, map.get(eventType)); } } return eventsResult; } }
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ package processing.app; import cc.arduino.packages.BoardPort; import cc.arduino.packages.MonitorFactory; import cc.arduino.packages.Uploader; import cc.arduino.packages.uploaders.SerialUploader; import cc.arduino.view.GoToLineNumber; import cc.arduino.view.StubMenuListener; import cc.arduino.view.findreplace.FindReplace; import cc.arduino.CompilerProgressListener; import com.jcraft.jsch.JSchException; import jssc.SerialPortException; import processing.app.debug.RunnerException; import processing.app.forms.PasswordAuthorizationDialog; import processing.app.helpers.DocumentTextChangeListener; import processing.app.helpers.Keys; import processing.app.helpers.OSUtils; import processing.app.helpers.PreferencesMapException; import processing.app.helpers.StringReplacer; import processing.app.legacy.PApplet; import processing.app.syntax.PdeKeywords; import processing.app.syntax.SketchTextArea; import processing.app.tools.MenuScroller; import processing.app.tools.Tool; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.BadLocationException; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.*; import java.awt.print.PageFormat; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.io.IOException; import java.net.ConnectException; import java.net.URL; import java.net.URLClassLoader; import java.util.*; import java.util.List; import java.util.function.Predicate; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.ArrayList; import static processing.app.I18n.tr; import static processing.app.Theme.scale; /** * Main editor panel for the Processing Development Environment. */ @SuppressWarnings("serial") public class Editor extends JFrame implements RunnerListener { public static final int MAX_TIME_AWAITING_FOR_RESUMING_SERIAL_MONITOR = 10000; final Platform platform; private JMenu recentSketchesMenu; private JMenu programmersMenu; private final Box upper; private ArrayList<EditorTab> tabs = new ArrayList<>(); private int currentTabIndex = -1; private static class ShouldSaveIfModified implements Predicate<SketchController> { @Override public boolean test(SketchController controller) { return PreferencesData.getBoolean("editor.save_on_verify") && controller.getSketch().isModified() && !controller.isReadOnly( BaseNoGui.librariesIndexer .getInstalledLibraries(), BaseNoGui.getExamplesPath()); } } private static class ShouldSaveReadOnly implements Predicate<SketchController> { @Override public boolean test(SketchController sketch) { return sketch.isReadOnly(BaseNoGui.librariesIndexer.getInstalledLibraries(), BaseNoGui.getExamplesPath()); } } private final static List<String> BOARD_PROTOCOLS_ORDER = Arrays.asList("serial", "network"); private final static List<String> BOARD_PROTOCOLS_ORDER_TRANSLATIONS = Arrays.asList(tr("Serial ports"), tr("Network ports")); final Base base; // otherwise, if the window is resized with the message label // set to blank, it's preferredSize() will be fukered private static final String EMPTY = " " + " " + " "; /** Command on Mac OS X, Ctrl on Windows and Linux */ private static final int SHORTCUT_KEY_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); /** Command-W on Mac OS X, Ctrl-W on Windows and Linux */ static final KeyStroke WINDOW_CLOSE_KEYSTROKE = KeyStroke.getKeyStroke('W', SHORTCUT_KEY_MASK); /** Command-Option on Mac OS X, Ctrl-Alt on Windows and Linux */ static final int SHORTCUT_ALT_KEY_MASK = ActionEvent.ALT_MASK | Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); /** * true if this file has not yet been given a name by the user */ boolean untitled; private PageFormat pageFormat; // file, sketch, and tools menus for re-inserting items private JMenu fileMenu; private JMenu toolsMenu; private int numTools = 0; public boolean avoidMultipleOperations = false; private final EditorToolbar toolbar; // these menus are shared so that they needn't be rebuilt for all windows // each time a sketch is created, renamed, or moved. static JMenu toolbarMenu; static JMenu sketchbookMenu; static JMenu examplesMenu; static JMenu importMenu; private static JMenu portMenu; static volatile AbstractMonitor serialMonitor; static AbstractMonitor serialPlotter; final EditorHeader header; EditorStatus status; EditorConsole console; private JSplitPane splitPane; // currently opened program SketchController sketchController; Sketch sketch; EditorLineStatus lineStatus; //JEditorPane editorPane; /** Contains all EditorTabs, of which only one will be visible */ private JPanel codePanel; //Runner runtime; private JMenuItem saveMenuItem; private JMenuItem saveAsMenuItem; //boolean presenting; private boolean uploading; // undo fellers private JMenuItem undoItem; private JMenuItem redoItem; private FindReplace find; Runnable runHandler; Runnable presentHandler; private Runnable runAndSaveHandler; private Runnable presentAndSaveHandler; Runnable exportHandler; private Runnable exportAppHandler; private Runnable timeoutUploadHandler; public Editor(Base ibase, File file, int[] storedLocation, int[] defaultLocation, Platform platform) throws Exception { super("Arduino"); this.base = ibase; this.platform = platform; Base.setIcon(this); // Install default actions for Run, Present, etc. resetHandlers(); // add listener to handle window close box hit event addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { base.handleClose(Editor.this); } }); // don't close the window when clicked, the app will take care // of that via the handleQuitInternal() methods setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // When bringing a window to front, let the Base know addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent e) { base.handleActivated(Editor.this); } // added for 1.0.5 public void windowDeactivated(WindowEvent e) { fileMenu.remove(sketchbookMenu); fileMenu.remove(examplesMenu); List<Component> toolsMenuItemsToRemove = new LinkedList<>(); for (Component menuItem : toolsMenu.getMenuComponents()) { if (menuItem instanceof JComponent) { Object removeOnWindowDeactivation = ((JComponent) menuItem).getClientProperty("removeOnWindowDeactivation"); if (removeOnWindowDeactivation != null && Boolean.valueOf(removeOnWindowDeactivation.toString())) { toolsMenuItemsToRemove.add(menuItem); } } } for (Component menuItem : toolsMenuItemsToRemove) { toolsMenu.remove(menuItem); } toolsMenu.remove(portMenu); } }); //PdeKeywords keywords = new PdeKeywords(); //sketchbook = new Sketchbook(this); buildMenuBar(); // For rev 0120, placing things inside a JPanel Container contentPain = getContentPane(); contentPain.setLayout(new BorderLayout()); JPanel pane = new JPanel(); pane.setLayout(new BorderLayout()); contentPain.add(pane, BorderLayout.CENTER); Box box = Box.createVerticalBox(); upper = Box.createVerticalBox(); if (toolbarMenu == null) { toolbarMenu = new JMenu(); base.rebuildToolbarMenu(toolbarMenu); } toolbar = new EditorToolbar(this, toolbarMenu); upper.add(toolbar); header = new EditorHeader(this); upper.add(header); // assemble console panel, consisting of status area and the console itself JPanel consolePanel = new JPanel(); consolePanel.setLayout(new BorderLayout()); status = new EditorStatus(this); consolePanel.add(status, BorderLayout.NORTH); console = new EditorConsole(); console.setName("console"); // windows puts an ugly border on this guy console.setBorder(null); consolePanel.add(console, BorderLayout.CENTER); lineStatus = new EditorLineStatus(); consolePanel.add(lineStatus, BorderLayout.SOUTH); codePanel = new JPanel(new BorderLayout()); upper.add(codePanel); splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upper, consolePanel); // repaint child panes while resizing splitPane.setContinuousLayout(true); // if window increases in size, give all of increase to // the textarea in the uppper pane splitPane.setResizeWeight(1D); // to fix ugliness.. normally macosx java 1.3 puts an // ugly white border around this object, so turn it off. splitPane.setBorder(null); // By default, the split pane binds Ctrl-Tab and Ctrl-Shift-Tab for changing // focus. Since we do not use that, but want to use these shortcuts for // switching tabs, remove the bindings from the split pane. This allows the // events to bubble up and be handled by the EditorHeader. Keys.killBinding(splitPane, Keys.ctrl(KeyEvent.VK_TAB)); Keys.killBinding(splitPane, Keys.ctrlShift(KeyEvent.VK_TAB)); splitPane.setDividerSize(scale(splitPane.getDividerSize())); // the following changed from 600, 400 for netbooks splitPane.setMinimumSize(scale(new Dimension(600, 100))); box.add(splitPane); // hopefully these are no longer needed w/ swing // (har har har.. that was wishful thinking) // listener = new EditorListener(this, textarea); pane.add(box); pane.setTransferHandler(new FileDropHandler()); // Set the minimum size for the editor window setMinimumSize(scale(new Dimension( PreferencesData.getInteger("editor.window.width.min"), PreferencesData.getInteger("editor.window.height.min")))); // Bring back the general options for the editor applyPreferences(); // Finish preparing Editor (formerly found in Base) pack(); // Set the window bounds and the divider location before setting it visible setPlacement(storedLocation, defaultLocation); // Open the document that was passed in boolean loaded = handleOpenInternal(file); if (!loaded) sketchController = null; } /** * Handles files dragged & dropped from the desktop and into the editor * window. Dragging files into the editor window is the same as using * "Sketch &rarr; Add File" for each file. */ private class FileDropHandler extends TransferHandler { public boolean canImport(JComponent dest, DataFlavor[] flavors) { return true; } @SuppressWarnings("unchecked") public boolean importData(JComponent src, Transferable transferable) { int successful = 0; try { DataFlavor uriListFlavor = new DataFlavor("text/uri-list;class=java.lang.String"); if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { List<File> list = (List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor); for (File file : list) { if (sketchController.addFile(file)) { successful++; } } } else if (transferable.isDataFlavorSupported(uriListFlavor)) { // Some platforms (Mac OS X and Linux, when this began) preferred // this method of moving files. String data = (String)transferable.getTransferData(uriListFlavor); String[] pieces = PApplet.splitTokens(data, "\r\n"); for (String piece : pieces) { if (piece.startsWith("#")) continue; String path = null; if (piece.startsWith("file: path = piece.substring(7); } else if (piece.startsWith("file:/")) { path = piece.substring(5); } if (sketchController.addFile(new File(path))) { successful++; } } } } catch (Exception e) { e.printStackTrace(); return false; } if (successful == 0) { statusError(tr("No files were added to the sketch.")); } else if (successful == 1) { statusNotice(tr("One file added to the sketch.")); } else { statusNotice( I18n.format(tr("{0} files added to the sketch."), successful)); } return true; } } private void setPlacement(int[] storedLocation, int[] defaultLocation) { if (storedLocation.length > 5 && storedLocation[5] != 0) { setExtendedState(storedLocation[5]); setPlacement(defaultLocation); } else { setPlacement(storedLocation); } } private void setPlacement(int[] location) { setBounds(location[0], location[1], location[2], location[3]); if (location[4] != 0) { splitPane.setDividerLocation(location[4]); } } protected int[] getPlacement() { int[] location = new int[6]; // Get the dimensions of the Frame Rectangle bounds = getBounds(); location[0] = bounds.x; location[1] = bounds.y; location[2] = bounds.width; location[3] = bounds.height; // Get the current placement of the divider location[4] = splitPane.getDividerLocation(); location[5] = getExtendedState() & MAXIMIZED_BOTH; return location; } /** * Read and apply new values from the preferences, either because * the app is just starting up, or the user just finished messing * with things in the Preferences window. */ public void applyPreferences() { boolean external = PreferencesData.getBoolean("editor.external"); saveMenuItem.setEnabled(!external); saveAsMenuItem.setEnabled(!external); for (EditorTab tab: tabs) tab.applyPreferences(); } private void buildMenuBar() { JMenuBar menubar = new JMenuBar(); final JMenu fileMenu = buildFileMenu(); fileMenu.addMenuListener(new StubMenuListener() { @Override public void menuSelected(MenuEvent e) { List<Component> components = Arrays.asList(fileMenu.getComponents()); if (!components.contains(sketchbookMenu)) { fileMenu.insert(sketchbookMenu, 3); } if (!components.contains(sketchbookMenu)) { fileMenu.insert(examplesMenu, 4); } fileMenu.revalidate(); validate(); } }); menubar.add(fileMenu); menubar.add(buildEditMenu()); final JMenu sketchMenu = new JMenu(tr("Sketch")); sketchMenu.setMnemonic(KeyEvent.VK_S); sketchMenu.addMenuListener(new StubMenuListener() { @Override public void menuSelected(MenuEvent e) { buildSketchMenu(sketchMenu); sketchMenu.revalidate(); validate(); } }); buildSketchMenu(sketchMenu); menubar.add(sketchMenu); final JMenu toolsMenu = buildToolsMenu(); toolsMenu.addMenuListener(new StubMenuListener() { @Override public void menuSelected(MenuEvent e) { List<Component> components = Arrays.asList(toolsMenu.getComponents()); int offset = 0; for (JMenu menu : base.getBoardsCustomMenus()) { if (!components.contains(menu)) { toolsMenu.insert(menu, numTools + offset); offset++; } } if (!components.contains(portMenu)) { toolsMenu.insert(portMenu, numTools + offset); } programmersMenu.removeAll(); base.getProgrammerMenus().forEach(programmersMenu::add); toolsMenu.revalidate(); validate(); } }); menubar.add(toolsMenu); menubar.add(buildHelpMenu()); setJMenuBar(menubar); } private JMenu buildFileMenu() { JMenuItem item; fileMenu = new JMenu(tr("File")); fileMenu.setMnemonic(KeyEvent.VK_F); item = newJMenuItem(tr("New"), 'N'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { base.handleNew(); } catch (Exception e1) { e1.printStackTrace(); } } }); fileMenu.add(item); item = Editor.newJMenuItem(tr("Open..."), 'O'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { base.handleOpenPrompt(); } catch (Exception e1) { e1.printStackTrace(); } } }); fileMenu.add(item); base.rebuildRecentSketchesMenuItems(); recentSketchesMenu = new JMenu(tr("Open Recent")); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { rebuildRecentSketchesMenu(); } }); fileMenu.add(recentSketchesMenu); if (sketchbookMenu == null) { sketchbookMenu = new JMenu(tr("Sketchbook")); MenuScroller.setScrollerFor(sketchbookMenu); base.rebuildSketchbookMenu(sketchbookMenu); } fileMenu.add(sketchbookMenu); if (examplesMenu == null) { examplesMenu = new JMenu(tr("Examples")); MenuScroller.setScrollerFor(examplesMenu); base.rebuildExamplesMenu(examplesMenu); } fileMenu.add(examplesMenu); item = Editor.newJMenuItem(tr("Close"), 'W'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleClose(Editor.this); } }); fileMenu.add(item); saveMenuItem = newJMenuItem(tr("Save"), 'S'); saveMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSave(false); } }); fileMenu.add(saveMenuItem); saveAsMenuItem = newJMenuItemShift(tr("Save As..."), 'S'); saveAsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSaveAs(); } }); fileMenu.add(saveAsMenuItem); fileMenu.addSeparator(); item = newJMenuItemShift(tr("Page Setup"), 'P'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePageSetup(); } }); fileMenu.add(item); item = newJMenuItem(tr("Print"), 'P'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePrint(); } }); fileMenu.add(item); // macosx already has its own preferences and quit menu if (!OSUtils.isMacOS()) { fileMenu.addSeparator(); item = newJMenuItem(tr("Preferences"), ','); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handlePrefs(); } }); fileMenu.add(item); fileMenu.addSeparator(); item = newJMenuItem(tr("Quit"), 'Q'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleQuit(); } }); fileMenu.add(item); } return fileMenu; } public void rebuildRecentSketchesMenu() { recentSketchesMenu.removeAll(); for (JMenuItem recentSketchMenuItem : base.getRecentSketchesMenuItems()) { recentSketchesMenu.add(recentSketchMenuItem); } } private void buildSketchMenu(JMenu sketchMenu) { sketchMenu.removeAll(); JMenuItem item = newJMenuItem(tr("Verify/Compile"), 'R'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleRun(false, Editor.this.presentHandler, Editor.this.runHandler); } }); sketchMenu.add(item); item = newJMenuItem(tr("Upload"), 'U'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleExport(false); } }); sketchMenu.add(item); item = newJMenuItemShift(tr("Upload Using Programmer"), 'U'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleExport(true); } }); sketchMenu.add(item); item = newJMenuItemAlt(tr("Export compiled Binary"), 'S'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (new ShouldSaveReadOnly().test(sketchController) && !handleSave(true)) { System.out.println(tr("Export canceled, changes must first be saved.")); return; } handleRun(false, new ShouldSaveReadOnly(), Editor.this.presentAndSaveHandler, Editor.this.runAndSaveHandler); } }); sketchMenu.add(item); // item = new JMenuItem("Stop"); // item.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // handleStop(); // sketchMenu.add(item); sketchMenu.addSeparator(); item = newJMenuItem(tr("Show Sketch Folder"), 'K'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openFolder(sketch.getFolder()); } }); sketchMenu.add(item); item.setEnabled(Base.openFolderAvailable()); if (importMenu == null) { importMenu = new JMenu(tr("Include Library")); MenuScroller.setScrollerFor(importMenu); base.rebuildImportMenu(importMenu); } sketchMenu.add(importMenu); item = new JMenuItem(tr("Add File...")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sketchController.handleAddFile(); } }); sketchMenu.add(item); } private JMenu buildToolsMenu() { toolsMenu = new JMenu(tr("Tools")); toolsMenu.setMnemonic(KeyEvent.VK_T); addInternalTools(toolsMenu); JMenuItem item = newJMenuItemShift(tr("Serial Monitor"), 'M'); item.addActionListener(e -> handleSerial()); toolsMenu.add(item); item = newJMenuItemShift(tr("Serial Plotter"), 'L'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePlotter(); } }); toolsMenu.add(item); addTools(toolsMenu, BaseNoGui.getToolsFolder()); File sketchbookTools = new File(BaseNoGui.getSketchbookFolder(), "tools"); addTools(toolsMenu, sketchbookTools); toolsMenu.addSeparator(); numTools = toolsMenu.getItemCount(); // XXX: DAM: these should probably be implemented using the Tools plugin // API, if possible (i.e. if it supports custom actions, etc.) base.getBoardsCustomMenus().stream().forEach(toolsMenu::add); if (portMenu == null) portMenu = new JMenu(tr("Port")); populatePortMenu(); toolsMenu.add(portMenu); MenuScroller.setScrollerFor(portMenu); item = new JMenuItem(tr("Get Board Info")); item.addActionListener(e -> handleBoardInfo()); toolsMenu.add(item); toolsMenu.addSeparator(); base.rebuildProgrammerMenu(); programmersMenu = new JMenu(tr("Programmer")); base.getProgrammerMenus().stream().forEach(programmersMenu::add); toolsMenu.add(programmersMenu); item = new JMenuItem(tr("Burn Bootloader")); item.addActionListener(e -> handleBurnBootloader()); toolsMenu.add(item); toolsMenu.addMenuListener(new StubMenuListener() { public void menuSelected(MenuEvent e) { //System.out.println("Tools menu selected."); populatePortMenu(); for (Component c : toolsMenu.getMenuComponents()) { if ((c instanceof JMenu) && c.isVisible()) { JMenu menu = (JMenu)c; String name = menu.getText(); if (name == null) continue; String basename = name; int index = name.indexOf(':'); if (index > 0) basename = name.substring(0, index); String sel = null; int count = menu.getItemCount(); for (int i=0; i < count; i++) { JMenuItem item = menu.getItem(i); if (item != null && item.isSelected()) { sel = item.getText(); if (sel != null) break; } } if (sel == null) { if (!name.equals(basename)) menu.setText(basename); } else { if (sel.length() > 50) sel = sel.substring(0, 50) + "..."; String newname = basename + ": \"" + sel + "\""; if (!name.equals(newname)) menu.setText(newname); } } } } }); return toolsMenu; } private void addTools(JMenu menu, File sourceFolder) { if (sourceFolder == null) return; Map<String, JMenuItem> toolItems = new HashMap<>(); File[] folders = sourceFolder.listFiles(new FileFilter() { public boolean accept(File folder) { if (folder.isDirectory()) { //System.out.println("checking " + folder); File subfolder = new File(folder, "tool"); return subfolder.exists(); } return false; } }); if (folders == null || folders.length == 0) { return; } for (File folder : folders) { File toolDirectory = new File(folder, "tool"); try { // add dir to classpath for .classes //urlList.add(toolDirectory.toURL()); // add .jar files to classpath File[] archives = toolDirectory.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return (name.toLowerCase().endsWith(".jar") || name.toLowerCase().endsWith(".zip")); } }); URL[] urlList = new URL[archives.length]; for (int j = 0; j < urlList.length; j++) { urlList[j] = archives[j].toURI().toURL(); } URLClassLoader loader = new URLClassLoader(urlList); String className = null; for (File archive : archives) { className = findClassInZipFile(folder.getName(), archive); if (className != null) break; } // If no class name found, just move on. if (className == null) continue; Class<?> toolClass = Class.forName(className, true, loader); final Tool tool = (Tool) toolClass.newInstance(); tool.init(Editor.this); String title = tool.getMenuTitle(); JMenuItem item = new JMenuItem(title); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(tool); //new Thread(tool).start(); } }); //menu.add(item); toolItems.put(title, item); } catch (Exception e) { e.printStackTrace(); } } ArrayList<String> toolList = new ArrayList<>(toolItems.keySet()); if (toolList.size() == 0) return; menu.addSeparator(); Collections.sort(toolList); for (String title : toolList) { menu.add(toolItems.get(title)); } } private String findClassInZipFile(String base, File file) { // Class file to search for String classFileName = "/" + base + ".class"; ZipFile zipFile = null; try { zipFile = new ZipFile(file); Enumeration<?> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (!entry.isDirectory()) { String name = entry.getName(); //System.out.println("entry: " + name); if (name.endsWith(classFileName)) { //int slash = name.lastIndexOf('/'); //String packageName = (slash == -1) ? "" : name.substring(0, slash); // Remove .class and convert slashes to periods. return name.substring(0, name.length() - 6).replace('/', '.'); } } } } catch (IOException e) { //System.err.println("Ignoring " + filename + " (" + e.getMessage() + ")"); e.printStackTrace(); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { // noop } } } return null; } public void updateKeywords(PdeKeywords keywords) { for (EditorTab tab : tabs) tab.updateKeywords(keywords); } JMenuItem createToolMenuItem(String className) { try { Class<?> toolClass = Class.forName(className); final Tool tool = (Tool) toolClass.newInstance(); JMenuItem item = new JMenuItem(tool.getMenuTitle()); tool.init(Editor.this); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(tool); } }); return item; } catch (Exception e) { e.printStackTrace(); return null; } } private void addInternalTools(JMenu menu) { JMenuItem item; item = createToolMenuItem("cc.arduino.packages.formatter.AStyle"); if (item == null) { throw new NullPointerException("Tool cc.arduino.packages.formatter.AStyle unavailable"); } item.setName("menuToolsAutoFormat"); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); item.setAccelerator(KeyStroke.getKeyStroke('T', modifiers)); menu.add(item); //menu.add(createToolMenuItem("processing.app.tools.CreateFont")); //menu.add(createToolMenuItem("processing.app.tools.ColorSelector")); menu.add(createToolMenuItem("processing.app.tools.Archiver")); menu.add(createToolMenuItem("processing.app.tools.FixEncoding")); } class SerialMenuListener implements ActionListener { private final String serialPort; public SerialMenuListener(String serialPort) { this.serialPort = serialPort; } public void actionPerformed(ActionEvent e) { selectSerialPort(serialPort); base.onBoardOrPortChange(); } } private void selectSerialPort(String name) { if(portMenu == null) { System.out.println(tr("serialMenu is null")); return; } if (name == null) { System.out.println(tr("name is null")); return; } JCheckBoxMenuItem selection = null; for (int i = 0; i < portMenu.getItemCount(); i++) { JMenuItem menuItem = portMenu.getItem(i); if (!(menuItem instanceof JCheckBoxMenuItem)) { continue; } JCheckBoxMenuItem checkBoxMenuItem = ((JCheckBoxMenuItem) menuItem); checkBoxMenuItem.setState(false); if (name.equals(checkBoxMenuItem.getText())) selection = checkBoxMenuItem; } if (selection != null) selection.setState(true); //System.out.println(item.getLabel()); BaseNoGui.selectSerialPort(name); if (serialMonitor != null) { try { serialMonitor.close(); serialMonitor.setVisible(false); } catch (Exception e) { // ignore } } if (serialPlotter != null) { try { serialPlotter.close(); serialPlotter.setVisible(false); } catch (Exception e) { // ignore } } onBoardOrPortChange(); base.onBoardOrPortChange(); //System.out.println("set to " + get("serial.port")); } private void populatePortMenu() { portMenu.removeAll(); String selectedPort = PreferencesData.get("serial.port"); List<BoardPort> ports = Base.getDiscoveryManager().discovery(); ports = platform.filterPorts(ports, PreferencesData.getBoolean("serial.ports.showall")); Collections.sort(ports, new Comparator<BoardPort>() { @Override public int compare(BoardPort o1, BoardPort o2) { return BOARD_PROTOCOLS_ORDER.indexOf(o1.getProtocol()) - BOARD_PROTOCOLS_ORDER.indexOf(o2.getProtocol()); } }); String lastProtocol = null; String lastProtocolTranslated; for (BoardPort port : ports) { if (lastProtocol == null || !port.getProtocol().equals(lastProtocol)) { if (lastProtocol != null) { portMenu.addSeparator(); } lastProtocol = port.getProtocol(); if (BOARD_PROTOCOLS_ORDER.indexOf(port.getProtocol()) != -1) { lastProtocolTranslated = BOARD_PROTOCOLS_ORDER_TRANSLATIONS.get(BOARD_PROTOCOLS_ORDER.indexOf(port.getProtocol())); } else { lastProtocolTranslated = port.getProtocol(); } JMenuItem lastProtocolMenuItem = new JMenuItem(tr(lastProtocolTranslated)); lastProtocolMenuItem.setEnabled(false); portMenu.add(lastProtocolMenuItem); } String address = port.getAddress(); String label = port.getLabel(); JCheckBoxMenuItem item = new JCheckBoxMenuItem(label, address.equals(selectedPort)); item.addActionListener(new SerialMenuListener(address)); portMenu.add(item); } portMenu.setEnabled(portMenu.getMenuComponentCount() > 0); } private JMenu buildHelpMenu() { // To deal with a Mac OS X 10.5 bug, add an extra space after the name // so that the OS doesn't try to insert its slow help menu. JMenu menu = new JMenu(tr("Help")); menu.setMnemonic(KeyEvent.VK_H); JMenuItem item; item = new JMenuItem(tr("Getting Started")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showArduinoGettingStarted(); } }); menu.add(item); item = new JMenuItem(tr("Environment")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showEnvironment(); } }); menu.add(item); item = new JMenuItem(tr("Troubleshooting")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showTroubleshooting(); } }); menu.add(item); item = new JMenuItem(tr("Reference")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference(); } }); menu.add(item); menu.addSeparator(); item = new JMenuItem(tr("Galileo Help")); item.setEnabled(false); menu.add(item); item = new JMenuItem(tr("Getting Started")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference("reference/Galileo_help_files", "ArduinoIDE_guide_galileo"); } }); menu.add(item); item = new JMenuItem(tr("Troubleshooting")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference("reference/Galileo_help_files", "Guide_Troubleshooting_Galileo"); } }); menu.add(item); menu.addSeparator(); item = new JMenuItem(tr("Edison Help")); item.setEnabled(false); menu.add(item); item = new JMenuItem(tr("Getting Started")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference("reference/Edison_help_files", "ArduinoIDE_guide_edison"); } }); menu.add(item); item = new JMenuItem(tr("Troubleshooting")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference("reference/Edison_help_files", "Guide_Troubleshooting_Edison"); } }); menu.add(item); menu.addSeparator(); item = newJMenuItemShift(tr("Find in Reference"), 'F'); item.addActionListener(this::handleFindReference); menu.add(item); item = new JMenuItem(tr("Frequently Asked Questions")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showFAQ(); } }); menu.add(item); item = new JMenuItem(tr("Visit Arduino.cc")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL(tr("http: } }); menu.add(item); // macosx already has its own about menu if (!OSUtils.isMacOS()) { menu.addSeparator(); item = new JMenuItem(tr("About Arduino")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleAbout(); } }); menu.add(item); } return menu; } private JMenu buildEditMenu() { JMenu menu = new JMenu(tr("Edit")); menu.setName("menuEdit"); menu.setMnemonic(KeyEvent.VK_E); undoItem = newJMenuItem(tr("Undo"), 'Z'); undoItem.setName("menuEditUndo"); undoItem.addActionListener(e -> getCurrentTab().handleUndo()); menu.add(undoItem); if (!OSUtils.isMacOS()) { redoItem = newJMenuItem(tr("Redo"), 'Y'); } else { redoItem = newJMenuItemShift(tr("Redo"), 'Z'); } redoItem.setName("menuEditRedo"); redoItem.addActionListener(e -> getCurrentTab().handleRedo()); menu.add(redoItem); menu.addSeparator(); JMenuItem cutItem = newJMenuItem(tr("Cut"), 'X'); cutItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getCurrentTab().handleCut(); } }); menu.add(cutItem); JMenuItem copyItem = newJMenuItem(tr("Copy"), 'C'); copyItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getCurrentTab().getTextArea().copy(); } }); menu.add(copyItem); JMenuItem copyForumItem = newJMenuItemShift(tr("Copy for Forum"), 'C'); copyForumItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getCurrentTab().handleDiscourseCopy(); } }); menu.add(copyForumItem); JMenuItem copyHTMLItem = newJMenuItemAlt(tr("Copy as HTML"), 'C'); copyHTMLItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getCurrentTab().handleHTMLCopy(); } }); menu.add(copyHTMLItem); JMenuItem pasteItem = newJMenuItem(tr("Paste"), 'V'); pasteItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getCurrentTab().handlePaste(); } }); menu.add(pasteItem); JMenuItem selectAllItem = newJMenuItem(tr("Select All"), 'A'); selectAllItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getCurrentTab().handleSelectAll(); } }); menu.add(selectAllItem); JMenuItem gotoLine = newJMenuItem(tr("Go to line..."), 'L'); gotoLine.addActionListener(e -> { GoToLineNumber goToLineNumber = new GoToLineNumber(Editor.this); goToLineNumber.setLocationRelativeTo(Editor.this); goToLineNumber.setVisible(true); }); menu.add(gotoLine); menu.addSeparator(); JMenuItem commentItem = newJMenuItem(tr("Comment/Uncomment"), PreferencesData.get("editor.keys.shortcut_comment", "/").charAt(0)); commentItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getCurrentTab().handleCommentUncomment(); } }); menu.add(commentItem); JMenuItem increaseIndentItem = new JMenuItem(tr("Increase Indent")); increaseIndentItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0)); increaseIndentItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getCurrentTab().handleIndentOutdent(true); } }); menu.add(increaseIndentItem); JMenuItem decreseIndentItem = new JMenuItem(tr("Decrease Indent")); decreseIndentItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK)); decreseIndentItem.setName("menuDecreaseIndent"); decreseIndentItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getCurrentTab().handleIndentOutdent(false); } }); menu.add(decreseIndentItem); menu.addSeparator(); JMenuItem findItem = newJMenuItem(tr("Find..."), 'F'); findItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find == null) { find = new FindReplace(Editor.this, Base.FIND_DIALOG_STATE); } if (!OSUtils.isMacOS()) { find.setFindText(getCurrentTab().getSelectedText()); } find.setLocationRelativeTo(Editor.this); find.setVisible(true); } }); menu.add(findItem); JMenuItem findNextItem = newJMenuItem(tr("Find Next"), 'G'); findNextItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find != null) { find.findNext(); } } }); menu.add(findNextItem); JMenuItem findPreviousItem = newJMenuItemShift(tr("Find Previous"), 'G'); findPreviousItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find != null) { find.findPrevious(); } } }); menu.add(findPreviousItem); if (OSUtils.isMacOS()) { JMenuItem useSelectionForFindItem = newJMenuItem(tr("Use Selection For Find"), 'E'); useSelectionForFindItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find == null) { find = new FindReplace(Editor.this, Base.FIND_DIALOG_STATE); } find.setFindText(getCurrentTab().getSelectedText()); } }); menu.add(useSelectionForFindItem); } menu.addMenuListener(new MenuListener() { @Override public void menuSelected(MenuEvent e) { boolean enabled = getCurrentTab().getSelectedText() != null; cutItem.setEnabled(enabled); copyItem.setEnabled(enabled); } @Override public void menuDeselected(MenuEvent e) {} @Override public void menuCanceled(MenuEvent e) {} }); return menu; } /** * A software engineer, somewhere, needs to have his abstraction * taken away. In some countries they jail or beat people for writing * the sort of API that would require a five line helper function * just to set the command key for a menu item. */ static public JMenuItem newJMenuItem(String title, int what) { JMenuItem menuItem = new JMenuItem(title); menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_KEY_MASK)); return menuItem; } /** * Like newJMenuItem() but adds shift as a modifier for the key command. */ static public JMenuItem newJMenuItemShift(String title, int what) { JMenuItem menuItem = new JMenuItem(title); menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_KEY_MASK | ActionEvent.SHIFT_MASK)); return menuItem; } /** * Same as newJMenuItem(), but adds the ALT (on Linux and Windows) * or OPTION (on Mac OS X) key as a modifier. */ private static JMenuItem newJMenuItemAlt(String title, int what) { JMenuItem menuItem = new JMenuItem(title); menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_ALT_KEY_MASK)); return menuItem; } protected void updateUndoRedoState() { SketchTextArea textArea = getCurrentTab().getTextArea(); undoItem.setEnabled(textArea.canUndo()); redoItem.setEnabled(textArea.canRedo()); } // these will be done in a more generic way soon, more like: // setHandler("action name", Runnable); // but for the time being, working out the kinks of how many things to // abstract from the editor in this fashion. private void resetHandlers() { runHandler = new BuildHandler(); presentHandler = new BuildHandler(true); runAndSaveHandler = new BuildHandler(false, true); presentAndSaveHandler = new BuildHandler(true, true); exportHandler = new DefaultExportHandler(); exportAppHandler = new DefaultExportAppHandler(); timeoutUploadHandler = new TimeoutUploadHandler(); } /** * Gets the current sketch controller. */ public SketchController getSketchController() { return sketchController; } /** * Gets the current sketch. */ public Sketch getSketch() { return sketch; } /** * Gets the currently displaying tab. */ public EditorTab getCurrentTab() { return tabs.get(currentTabIndex); } /** * Gets the index of the currently displaying tab. */ public int getCurrentTabIndex() { return currentTabIndex; } /** * Returns an (unmodifiable) list of currently opened tabs. */ public List<EditorTab> getTabs() { return Collections.unmodifiableList(tabs); } /** * Change the currently displayed tab. * Note that the GUI might not update immediately, since this needs * to run in the Event dispatch thread. * @param index The index of the tab to select */ public void selectTab(final int index) { currentTabIndex = index; updateUndoRedoState(); updateTitle(); header.rebuild(); getCurrentTab().activated(); // This must be run in the GUI thread SwingUtilities.invokeLater(() -> { codePanel.removeAll(); codePanel.add(tabs.get(index), BorderLayout.CENTER); tabs.get(index).requestFocusInWindow(); // get the caret blinking // For some reason, these are needed. Revalidate says it should be // automatically called when components are added or removed, but without // it, the component switched to is not displayed. repaint() is needed to // clear the entire text area of any previous text. codePanel.revalidate(); codePanel.repaint(); }); } public void selectNextTab() { selectTab((currentTabIndex + 1) % tabs.size()); } public void selectPrevTab() { selectTab((currentTabIndex - 1 + tabs.size()) % tabs.size()); } public EditorTab findTab(final SketchFile file) { return tabs.get(findTabIndex(file)); } /** * Finds the index of the tab showing the given file. Matches the file against * EditorTab.getSketchFile() using ==. * * @returns The index of the tab for the given file, or -1 if no such tab was * found. */ public int findTabIndex(final SketchFile file) { for (int i = 0; i < tabs.size(); ++i) { if (tabs.get(i).getSketchFile() == file) return i; } return -1; } /** * Finds the index of the tab showing the given file. Matches the file against * EditorTab.getSketchFile().getFile() using equals. * * @returns The index of the tab for the given file, or -1 if no such tab was * found. */ public int findTabIndex(final File file) { for (int i = 0; i < tabs.size(); ++i) { if (tabs.get(i).getSketchFile().getFile().equals(file)) return i; } return -1; } /** * Create tabs for each of the current sketch's files, removing any existing * tabs. */ public void createTabs() { tabs.clear(); currentTabIndex = -1; tabs.ensureCapacity(sketch.getCodeCount()); for (SketchFile file : sketch.getFiles()) { try { addTab(file, null); } catch(IOException e) { // TODO: Improve / move error handling System.err.println(e); } } selectTab(0); } /** * Reorders tabs as per current sketch's files order */ public void reorderTabs() { Collections.sort(tabs, (x, y) -> Sketch.CODE_DOCS_COMPARATOR.compare(x.getSketchFile(), y.getSketchFile())); } /** * Add a new tab. * * @param file * The file to show in the tab. * @param contents * The contents to show in the tab, or null to load the contents from * the given file. * @throws IOException */ protected void addTab(SketchFile file, String contents) throws IOException { EditorTab tab = new EditorTab(this, file, contents); tab.getTextArea().getDocument() .addDocumentListener(new DocumentTextChangeListener( () -> updateUndoRedoState())); tabs.add(tab); reorderTabs(); } protected void removeTab(SketchFile file) throws IOException { int index = findTabIndex(file); tabs.remove(index); } void handleFindReference(ActionEvent e) { String text = getCurrentTab().getCurrentKeyword(); String referenceFile = base.getPdeKeywords().getReference(text); if (referenceFile == null) { statusNotice(I18n.format(tr("No reference available for \"{0}\""), text)); } else { if (referenceFile.startsWith("Serial_")) { Base.showReference("Serial/" + referenceFile.substring("Serial_".length())); } else { Base.showReference("Reference/" + referenceFile); } } } /** * Implements Sketch &rarr; Run. * @param verbose Set true to run with verbose output. * @param verboseHandler * @param nonVerboseHandler */ public void handleRun(final boolean verbose, Runnable verboseHandler, Runnable nonVerboseHandler) { handleRun(verbose, new ShouldSaveIfModified(), verboseHandler, nonVerboseHandler); } private void handleRun(final boolean verbose, Predicate<SketchController> shouldSavePredicate, Runnable verboseHandler, Runnable nonVerboseHandler) { if (shouldSavePredicate.test(sketchController)) { handleSave(true); } toolbar.activateRun(); status.progress(tr("Compiling sketch...")); // do this to advance/clear the terminal window / dos prompt / etc for (int i = 0; i < 10; i++) System.out.println(); // clear the console on each run, unless the user doesn't want to if (PreferencesData.getBoolean("console.auto_clear")) { console.clear(); } // Cannot use invokeLater() here, otherwise it gets // placed on the event thread and causes a hang--bad idea all around. new Thread(verbose ? verboseHandler : nonVerboseHandler).start(); } class BuildHandler implements Runnable { private final boolean verbose; private final boolean saveHex; public BuildHandler() { this(false); } public BuildHandler(boolean verbose) { this(verbose, false); } public BuildHandler(boolean verbose, boolean saveHex) { this.verbose = verbose; this.saveHex = saveHex; } @Override public void run() { try { removeAllLineHighlights(); sketchController.build(verbose, saveHex); statusNotice(tr("Done compiling.")); } catch (PreferencesMapException e) { statusError(I18n.format( tr("Error while compiling: missing '{0}' configuration parameter"), e.getMessage())); } catch (Exception e) { status.unprogress(); statusError(e); } status.unprogress(); toolbar.deactivateRun(); avoidMultipleOperations = false; } } public void removeAllLineHighlights() { for (EditorTab tab : tabs) tab.getTextArea().removeAllLineHighlights(); } public void addLineHighlight(int line) throws BadLocationException { getCurrentTab().getTextArea().addLineHighlight(line, new Color(1, 0, 0, 0.2f)); getCurrentTab().getTextArea().setCaretPosition(getCurrentTab().getTextArea().getLineStartOffset(line)); } /** * Implements Sketch &rarr; Stop, or pressing Stop on the toolbar. */ private void handleStop() { // called by menu or buttons // toolbar.activate(EditorToolbar.STOP); toolbar.deactivateRun(); // toolbar.deactivate(EditorToolbar.STOP); // focus the PDE again after quitting presentation mode [toxi 030903] toFront(); } /** * Check if the sketch is modified and ask user to save changes. * @return false if canceling the close/quit operation */ protected boolean checkModified() { if (!sketch.isModified()) return true; // As of Processing 1.0.10, this always happens immediately. toFront(); String prompt = I18n.format(tr("Save changes to \"{0}\"? "), sketch.getName()); if (!OSUtils.isMacOS()) { int result = JOptionPane.showConfirmDialog(this, prompt, tr("Close"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); switch (result) { case JOptionPane.YES_OPTION: return handleSave(true); case JOptionPane.NO_OPTION: return true; // ok to continue case JOptionPane.CANCEL_OPTION: case JOptionPane.CLOSED_OPTION: // Escape key pressed return false; default: throw new IllegalStateException(); } } else { // This code is disabled unless Java 1.5 is being used on Mac OS X // because of a Java bug that prevents the initial value of the // dialog from being set properly (at least on my MacBook Pro). // The bug causes the "Don't Save" option to be the highlighted, // blinking, default. This sucks. But I'll tell you what doesn't // suck--workarounds for the Mac and Apple's snobby attitude about it! // I think it's nifty that they treat their developers like dirt. JOptionPane pane = new JOptionPane(tr("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>Do you want to save changes to this sketch<BR>" + " before closing?</b>" + "<p>If you don't save, your changes will be lost."), JOptionPane.QUESTION_MESSAGE); String[] options = new String[] { tr("Save"), tr("Cancel"), tr("Don't Save") }; pane.setOptions(options); // highlight the safest option ala apple hig pane.setInitialValue(options[0]); JDialog dialog = pane.createDialog(this, null); dialog.setVisible(true); Object result = pane.getValue(); if (result == options[0]) { // save (and close/quit) return handleSave(true); } else { return result == options[2]; } } } /** * Second stage of open, occurs after having checked to see if the * modifications (if any) to the previous sketch need to be saved. */ protected boolean handleOpenInternal(File sketchFile) { // check to make sure that this .pde file is // in a folder of the same name String fileName = sketchFile.getName(); File file = Sketch.checkSketchFile(sketchFile); if (file == null) { if (!fileName.endsWith(".ino") && !fileName.endsWith(".pde")) { Base.showWarning(tr("Bad file selected"), tr("Arduino can only open its own sketches\n" + "and other files ending in .ino or .pde"), null); return false; } else { String properParent = fileName.substring(0, fileName.length() - 4); Object[] options = {tr("OK"), tr("Cancel")}; String prompt = I18n.format(tr("The file \"{0}\" needs to be inside\n" + "a sketch folder named \"{1}\".\n" + "Create this folder, move the file, and continue?"), fileName, properParent); int result = JOptionPane.showOptionDialog(this, prompt, tr("Moving"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result != JOptionPane.YES_OPTION) { return false; } // create properly named folder File properFolder = new File(sketchFile.getParent(), properParent); if (properFolder.exists()) { Base.showWarning(tr("Error"), I18n.format(tr("A folder named \"{0}\" already exists. " + "Can't open sketch."), properParent), null); return false; } if (!properFolder.mkdirs()) { //throw new IOException("Couldn't create sketch folder"); Base.showWarning(tr("Error"), tr("Could not create the sketch folder."), null); return false; } // copy the sketch inside File properPdeFile = new File(properFolder, sketchFile.getName()); try { Base.copyFile(sketchFile, properPdeFile); } catch (IOException e) { Base.showWarning(tr("Error"), tr("Could not copy to a proper location."), e); return false; } // remove the original file, so user doesn't get confused sketchFile.delete(); // update with the new path file = properPdeFile; } } try { sketch = new Sketch(file); } catch (IOException e) { Base.showWarning(tr("Error"), tr("Could not create the sketch."), e); return false; } sketchController = new SketchController(this, sketch); createTabs(); // Disable untitled setting from previous document, if any untitled = false; // opening was successful return true; } private void updateTitle() { if (sketchController == null) { return; } SketchFile current = getCurrentTab().getSketchFile(); String customFormat = PreferencesData.get("editor.custom_title_format"); if (customFormat != null && !customFormat.trim().isEmpty()) { Map<String, String> titleMap = new HashMap<String, String>(); titleMap.put("file", current.getFileName()); String path = sketch.getFolder().getAbsolutePath(); titleMap.put("folder", path); titleMap.put("path", path); titleMap.put("project", sketch.getName()); titleMap.put("version", BaseNoGui.VERSION_NAME_LONG); setTitle(StringReplacer.replaceFromMapping(customFormat, titleMap)); } else { if (current.isPrimary()) { setTitle(I18n.format(tr("{0} | Arduino {1}"), sketch.getName(), BaseNoGui.VERSION_NAME_LONG)); } else { setTitle(I18n.format(tr("{0} - {1} | Arduino {2}"), sketch.getName(), current.getFileName(), BaseNoGui.VERSION_NAME_LONG)); } } } public boolean handleSave(boolean immediately) { //stopRunner(); handleStop(); // 0136 removeAllLineHighlights(); if (untitled) { return handleSaveAs(); // need to get the name, user might also cancel here } else if (immediately) { return handleSave2(); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { handleSave2(); } }); } return true; } private boolean handleSave2() { toolbar.activateSave(); statusNotice(tr("Saving...")); boolean saved = false; try { boolean wasReadOnly = sketchController.isReadOnly(BaseNoGui.librariesIndexer.getInstalledLibraries(), BaseNoGui.getExamplesPath()); String previousMainFilePath = sketch.getMainFilePath(); saved = sketchController.save(); if (saved) { statusNotice(tr("Done Saving.")); if (wasReadOnly) { base.removeRecentSketchPath(previousMainFilePath); } base.storeRecentSketches(sketchController); base.rebuildRecentSketchesMenuItems(); } else { statusEmpty(); } // rebuild sketch menu in case a save-as was forced // Disabling this for 0125, instead rebuild the menu inside // the Save As method of the Sketch object, since that's the // only one who knows whether something was renamed. //sketchbook.rebuildMenus(); //sketchbook.rebuildMenusAsync(); } catch (Exception e) { // show the error as a message in the window statusError(e); // zero out the current action, // so that checkModified2 will just do nothing //checkModifiedMode = 0; // this is used when another operation calls a save } //toolbar.clear(); toolbar.deactivateSave(); return saved; } public boolean handleSaveAs() { //stopRunner(); // formerly from 0135 handleStop(); toolbar.activateSave(); //SwingUtilities.invokeLater(new Runnable() { //public void run() { statusNotice(tr("Saving...")); try { if (sketchController.saveAs()) { base.storeRecentSketches(sketchController); base.rebuildRecentSketchesMenuItems(); statusNotice(tr("Done Saving.")); // Disabling this for 0125, instead rebuild the menu inside // the Save As method of the Sketch object, since that's the // only one who knows whether something was renamed. //sketchbook.rebuildMenusAsync(); } else { statusNotice(tr("Save Canceled.")); return false; } } catch (Exception e) { // show the error as a message in the window statusError(e); } finally { // make sure the toolbar button deactivates toolbar.deactivateSave(); // Update editor window title in case of "Save as..." updateTitle(); header.rebuild(); } return true; } private boolean serialPrompt() { int count = portMenu.getItemCount(); Object[] names = new Object[count]; for (int i = 0; i < count; i++) { names[i] = portMenu.getItem(i).getText(); } String result = (String) JOptionPane.showInputDialog(this, I18n.format( tr("Serial port {0} not found.\n" + "Retry the upload with another serial port?"), PreferencesData.get("serial.port") ), "Serial port not found", JOptionPane.PLAIN_MESSAGE, null, names, 0); if (result == null) return false; selectSerialPort(result); base.onBoardOrPortChange(); return true; } /** * Called by Sketch &rarr; Export. * Handles calling the export() function on sketch, and * queues all the gui status stuff that comes along with it. * <p/> * Made synchronized to (hopefully) avoid problems of people * hitting export twice, quickly, and horking things up. */ /** * Handles calling the export() function on sketch, and * queues all the gui status stuff that comes along with it. * * Made synchronized to (hopefully) avoid problems of people * hitting export twice, quickly, and horking things up. */ synchronized public void handleExport(final boolean usingProgrammer) { if (PreferencesData.getBoolean("editor.save_on_verify")) { if (sketch.isModified() && !sketchController.isReadOnly( BaseNoGui.librariesIndexer .getInstalledLibraries(), BaseNoGui.getExamplesPath())) { handleSave(true); } } toolbar.activateExport(); console.clear(); status.progress(tr("Uploading to I/O Board...")); avoidMultipleOperations = true; new Thread(timeoutUploadHandler).start(); new Thread(usingProgrammer ? exportAppHandler : exportHandler).start(); } // DAM: in Arduino, this is upload class DefaultExportHandler implements Runnable { public void run() { try { removeAllLineHighlights(); if (serialMonitor != null) { serialMonitor.suspend(); } if (serialPlotter != null) { serialPlotter.suspend(); } uploading = true; boolean success = sketchController.exportApplet(false); if (success) { statusNotice(tr("Done uploading.")); } } catch (SerialNotFoundException e) { if (portMenu.getItemCount() == 0) statusError(e); else if (serialPrompt()) run(); else statusNotice(tr("Upload canceled.")); } catch (PreferencesMapException e) { statusError(I18n.format( tr("Error while uploading: missing '{0}' configuration parameter"), e.getMessage())); } catch (RunnerException e) { //statusError("Error during upload."); //e.printStackTrace(); status.unprogress(); statusError(e); } catch (Exception e) { e.printStackTrace(); } finally { populatePortMenu(); avoidMultipleOperations = false; } status.unprogress(); uploading = false; //toolbar.clear(); toolbar.deactivateExport(); resumeOrCloseSerialMonitor(); resumeOrCloseSerialPlotter(); base.onBoardOrPortChange(); } } private void resumeOrCloseSerialMonitor() { // Return the serial monitor window to its initial state if (serialMonitor != null) { BoardPort boardPort = BaseNoGui.getDiscoveryManager().find(PreferencesData.get("serial.port")); long sleptFor = 0; while (boardPort == null && sleptFor < MAX_TIME_AWAITING_FOR_RESUMING_SERIAL_MONITOR) { try { Thread.sleep(100); sleptFor += 100; boardPort = BaseNoGui.getDiscoveryManager().find(PreferencesData.get("serial.port")); } catch (InterruptedException e) { // noop } } try { if (serialMonitor != null) { serialMonitor.resume(boardPort); if (boardPort == null) { serialMonitor.close(); handleSerial(); } else { serialMonitor.resume(boardPort); } } } catch (Exception e) { statusError(e); } } } private void resumeOrCloseSerialPlotter() { // Return the serial plotter window to its initial state if (serialPlotter != null) { BoardPort boardPort = BaseNoGui.getDiscoveryManager().find(PreferencesData.get("serial.port")); try { if (serialPlotter != null) serialPlotter.resume(boardPort); if (boardPort == null) { serialPlotter.close(); handlePlotter(); } else { serialPlotter.resume(boardPort); } } catch (Exception e) { statusError(e); } } } // DAM: in Arduino, this is upload (with verbose output) class DefaultExportAppHandler implements Runnable { public void run() { try { if (serialMonitor != null) { serialMonitor.suspend(); } if (serialPlotter != null) { serialPlotter.suspend(); } uploading = true; boolean success = sketchController.exportApplet(true); if (success) { statusNotice(tr("Done uploading.")); } } catch (SerialNotFoundException e) { if (portMenu.getItemCount() == 0) statusError(e); else if (serialPrompt()) run(); else statusNotice(tr("Upload canceled.")); } catch (PreferencesMapException e) { statusError(I18n.format( tr("Error while uploading: missing '{0}' configuration parameter"), e.getMessage())); } catch (RunnerException e) { //statusError("Error during upload."); //e.printStackTrace(); status.unprogress(); statusError(e); } catch (Exception e) { e.printStackTrace(); } finally { avoidMultipleOperations = false; populatePortMenu(); } status.unprogress(); uploading = false; //toolbar.clear(); toolbar.deactivateExport(); resumeOrCloseSerialMonitor(); resumeOrCloseSerialPlotter(); base.onBoardOrPortChange(); } } class TimeoutUploadHandler implements Runnable { public void run() { try { //10 seconds, than reactivate upload functionality and let the programmer pid being killed Thread.sleep(1000 * 10); if (uploading) { avoidMultipleOperations = false; } } catch (InterruptedException e) { // noop } } } public void handleSerial() { if(serialPlotter != null) { if(serialPlotter.isClosed()) { serialPlotter = null; } else { statusError(tr("Serial monitor not available while plotter is open")); return; } } if (serialMonitor != null) { // The serial monitor already exists if (serialMonitor.isClosed()) { serialMonitor.dispose(); // If it's closed, clear the refrence to the existing // monitor and create a new one serialMonitor = null; } else { // If it's not closed, give it the focus try { serialMonitor.toFront(); serialMonitor.requestFocus(); return; } catch (Exception e) { // noop } } } BoardPort port = Base.getDiscoveryManager().find(PreferencesData.get("serial.port")); if (port == null) { statusError(I18n.format(tr("Board at {0} is not available"), PreferencesData.get("serial.port"))); return; } serialMonitor = new MonitorFactory().newMonitor(port); if (serialMonitor == null) { String board = port.getPrefs().get("board"); String boardName = BaseNoGui.getPlatform().resolveDeviceByBoardID(BaseNoGui.packages, board); statusError(I18n.format(tr("Serial monitor is not supported on network ports such as {0} for the {1} in this release"), PreferencesData.get("serial.port"), boardName)); return; } Base.setIcon(serialMonitor); // If currently uploading, disable the monitor (it will be later // enabled when done uploading) if (uploading || avoidMultipleOperations) { try { serialMonitor.suspend(); } catch (Exception e) { statusError(e); } } boolean success = false; do { if (serialMonitor.requiresAuthorization() && !PreferencesData.has(serialMonitor.getAuthorizationKey())) { PasswordAuthorizationDialog dialog = new PasswordAuthorizationDialog(this, tr("Type board password to access its console")); dialog.setLocationRelativeTo(this); dialog.setVisible(true); if (dialog.isCancelled()) { statusNotice(tr("Unable to open serial monitor")); return; } PreferencesData.set(serialMonitor.getAuthorizationKey(), dialog.getPassword()); } try { serialMonitor.setVisible(true); if (!avoidMultipleOperations) { serialMonitor.open(); } success = true; } catch (ConnectException e) { statusError(tr("Unable to connect: is the sketch using the bridge?")); } catch (JSchException e) { statusError(tr("Unable to connect: wrong password?")); } catch (SerialException e) { String errorMessage = e.getMessage(); if (e.getCause() != null && e.getCause() instanceof SerialPortException) { errorMessage += " (" + ((SerialPortException) e.getCause()).getExceptionType() + ")"; } statusError(errorMessage); try { serialMonitor.close(); } catch (Exception e1) { // noop } } catch (Exception e) { statusError(e); } finally { if (serialMonitor.requiresAuthorization() && !success) { PreferencesData.remove(serialMonitor.getAuthorizationKey()); } } } while (serialMonitor.requiresAuthorization() && !success); } public void handlePlotter() { if(serialMonitor != null) { if(serialMonitor.isClosed()) { serialMonitor = null; } else { statusError(tr("Plotter not available while serial monitor is open")); return; } } if (serialPlotter != null) { // The serial plotter already exists if (serialPlotter.isClosed()) { // If it's closed, clear the refrence to the existing // plotter and create a new one serialPlotter = null; } else { // If it's not closed, give it the focus try { serialPlotter.toFront(); serialPlotter.requestFocus(); return; } catch (Exception e) { // noop } } } BoardPort port = Base.getDiscoveryManager().find(PreferencesData.get("serial.port")); if (port == null) { statusError(I18n.format(tr("Board at {0} is not available"), PreferencesData.get("serial.port"))); return; } serialPlotter = new SerialPlotter(port); Base.setIcon(serialPlotter); // If currently uploading, disable the plotter (it will be later // enabled when done uploading) if (uploading) { try { serialPlotter.suspend(); } catch (Exception e) { statusError(e); } } boolean success = false; do { if (serialPlotter.requiresAuthorization() && !PreferencesData.has(serialPlotter.getAuthorizationKey())) { PasswordAuthorizationDialog dialog = new PasswordAuthorizationDialog(this, tr("Type board password to access its console")); dialog.setLocationRelativeTo(this); dialog.setVisible(true); if (dialog.isCancelled()) { statusNotice(tr("Unable to open serial plotter")); return; } PreferencesData.set(serialPlotter.getAuthorizationKey(), dialog.getPassword()); } try { serialPlotter.open(); serialPlotter.setVisible(true); success = true; } catch (ConnectException e) { statusError(tr("Unable to connect: is the sketch using the bridge?")); } catch (JSchException e) { statusError(tr("Unable to connect: wrong password?")); } catch (SerialException e) { String errorMessage = e.getMessage(); if (e.getCause() != null && e.getCause() instanceof SerialPortException) { errorMessage += " (" + ((SerialPortException) e.getCause()).getExceptionType() + ")"; } statusError(errorMessage); } catch (Exception e) { statusError(e); } finally { if (serialPlotter.requiresAuthorization() && !success) { PreferencesData.remove(serialPlotter.getAuthorizationKey()); } } } while (serialPlotter.requiresAuthorization() && !success); } private void handleBurnBootloader() { console.clear(); statusNotice(tr("Burning bootloader to I/O Board (this may take a minute)...")); new Thread(() -> { try { Uploader uploader = new SerialUploader(); if (uploader.burnBootloader()) { SwingUtilities.invokeLater(() -> statusNotice(tr("Done burning bootloader."))); } else { SwingUtilities.invokeLater(() -> statusError(tr("Error while burning bootloader."))); // error message will already be visible } } catch (PreferencesMapException e) { SwingUtilities.invokeLater(() -> { statusError(I18n.format( tr("Error while burning bootloader: missing '{0}' configuration parameter"), e.getMessage())); }); } catch (RunnerException e) { SwingUtilities.invokeLater(() -> statusError(e.getMessage())); } catch (Exception e) { SwingUtilities.invokeLater(() -> statusError(tr("Error while burning bootloader."))); e.printStackTrace(); } }).start(); } private void handleBoardInfo() { console.clear(); String selectedPort = PreferencesData.get("serial.port"); List<BoardPort> ports = Base.getDiscoveryManager().discovery(); String label = ""; String vid = ""; String pid = ""; String iserial = ""; String protocol = ""; boolean found = false; for (BoardPort port : ports) { if (port.getAddress().equals(selectedPort)) { label = port.getBoardName(); vid = port.getVID(); pid = port.getPID(); iserial = port.getISerial(); protocol = port.getProtocol(); found = true; break; } } if (!found) { statusNotice(tr("Please select a port to obtain board info")); return; } if (protocol.equals("network")) { statusNotice(tr("Network port, can't obtain info")); return; } if (vid == null || vid.equals("") || vid.equals("0000")) { statusNotice(tr("Native serial port, can't obtain info")); return; } if (iserial == null || iserial.equals("")) { iserial = tr("Upload any sketch to obtain it"); } if (label == null) { label = tr("Unknown board"); } String infos = I18n.format("BN: {0}\nVID: {1}\nPID: {2}\nSN: {3}", label, vid, pid, iserial); JTextArea textArea = new JTextArea(infos); JOptionPane.showMessageDialog(this, textArea, tr("Board Info"), JOptionPane.PLAIN_MESSAGE); } /** * Handler for File &rarr; Page Setup. */ private void handlePageSetup() { PrinterJob printerJob = PrinterJob.getPrinterJob(); if (pageFormat == null) { pageFormat = printerJob.defaultPage(); } pageFormat = printerJob.pageDialog(pageFormat); } /** * Handler for File &rarr; Print. */ private void handlePrint() { statusNotice(tr("Printing...")); //printerJob = null; PrinterJob printerJob = PrinterJob.getPrinterJob(); if (pageFormat != null) { //System.out.println("setting page format " + pageFormat); printerJob.setPrintable(getCurrentTab().getTextArea(), pageFormat); } else { printerJob.setPrintable(getCurrentTab().getTextArea()); } // set the name of the job to the code name printerJob.setJobName(getCurrentTab().getSketchFile().getPrettyName()); if (printerJob.printDialog()) { try { printerJob.print(); statusNotice(tr("Done printing.")); } catch (PrinterException pe) { statusError(tr("Error while printing.")); pe.printStackTrace(); } } else { statusNotice(tr("Printing canceled.")); } //printerJob = null; // clear this out? } /** * Show an error int the status bar. */ public void statusError(String what) { System.err.println(what); status.error(what); //new Exception("deactivating RUN").printStackTrace(); toolbar.deactivateRun(); } /** * Show an exception in the editor status bar. */ public void statusError(Exception e) { e.printStackTrace(); // if (e == null) { // System.err.println("Editor.statusError() was passed a null exception."); // return; if (e instanceof RunnerException) { RunnerException re = (RunnerException) e; if (re.hasCodeFile()) { selectTab(findTabIndex(re.getCodeFile())); } if (re.hasCodeLine()) { int line = re.getCodeLine(); // subtract one from the end so that the \n ain't included if (line >= getCurrentTab().getTextArea().getLineCount()) { // The error is at the end of this current chunk of code, // so the last line needs to be selected. line = getCurrentTab().getTextArea().getLineCount() - 1; if (getCurrentTab().getLineText(line).length() == 0) { // The last line may be zero length, meaning nothing to select. // If so, back up one more line. line } } if (line < 0 || line >= getCurrentTab().getTextArea().getLineCount()) { System.err.println(I18n.format(tr("Bad error line: {0}"), line)); } else { try { addLineHighlight(line); } catch (BadLocationException e1) { e1.printStackTrace(); } } } } // Since this will catch all Exception types, spend some time figuring // out which kind and try to give a better error message to the user. String mess = e.getMessage(); if (mess != null) { String javaLang = "java.lang."; if (mess.indexOf(javaLang) == 0) { mess = mess.substring(javaLang.length()); } String rxString = "RuntimeException: "; if (mess.indexOf(rxString) == 0) { mess = mess.substring(rxString.length()); } statusError(mess); } // e.printStackTrace(); } /** * Show a notice message in the editor status bar. */ public void statusNotice(String msg) { status.notice(msg); } /** * Clear the status area. */ private void statusEmpty() { statusNotice(EMPTY); } protected void onBoardOrPortChange() { Map<String, String> boardPreferences = BaseNoGui.getBoardPreferences(); if (boardPreferences != null) lineStatus.setBoardName(boardPreferences.get("name")); else lineStatus.setBoardName("-"); lineStatus.setSerialPort(PreferencesData.get("serial.port")); lineStatus.repaint(); } public void addCompilerProgressListener(CompilerProgressListener listener){ this.status.addCompilerProgressListener(listener); } }
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ package processing.app; import processing.app.debug.*; import processing.app.syntax.*; import processing.app.tools.*; import processing.core.*; import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.*; import java.awt.print.*; import java.io.*; import java.net.*; import java.util.*; import java.util.zip.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; import javax.swing.undo.*; import org.apache.log4j.BasicConfigurator; //import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.Logger; import org.apache.log4j.Level; import gnu.io.*; /** * Main editor panel for the Processing Development Environment. */ public class Editor extends JFrame implements RunnerListener { static Logger logger = Logger.getLogger(Base.class.getName()); Base base; // otherwise, if the window is resized with the message label // set to blank, it's preferredSize() will be fukered static protected final String EMPTY = " " + " " + " "; /** Command on Mac OS X, Ctrl on Windows and Linux */ static final int SHORTCUT_KEY_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); /** Command-W on Mac OS X, Ctrl-W on Windows and Linux */ static final KeyStroke WINDOW_CLOSE_KEYSTROKE = KeyStroke.getKeyStroke('W', SHORTCUT_KEY_MASK); /** Command-Option on Mac OS X, Ctrl-Alt on Windows and Linux */ static final int SHORTCUT_ALT_KEY_MASK = ActionEvent.ALT_MASK | Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); /** * true if this file has not yet been given a name by the user */ boolean untitled; PageFormat pageFormat; PrinterJob printerJob; // file, sketch, and tools menus for re-inserting items JMenu fileMenu; JMenu sketchMenu; JMenu toolsMenu; int numTools = 0; EditorToolbar toolbar; // these menus are shared so that they needn't be rebuilt for all windows // each time a sketch is created, renamed, or moved. static JMenu toolbarMenu; static JMenu sketchbookMenu; static JMenu examplesMenu; static JMenu importMenu; // these menus are shared so that the board and serial port selections // are the same for all windows (since the board and serial port that are // actually used are determined by the preferences, which are shared) static JMenu boardsMenu; static JMenu serialMenu; static SerialMenuListener serialMenuListener; static SerialMonitor serialMonitor; EditorHeader header; EditorStatus status; EditorConsole console; JSplitPane splitPane; JPanel consolePanel; JLabel lineNumberComponent; // currently opened program Sketch sketch; EditorLineStatus lineStatus; JEditorPane editorPane; JEditTextArea textarea; EditorListener listener; // runtime information and window placement Point sketchWindowLocation; //Runner runtime; JMenuItem exportAppItem; JMenuItem saveMenuItem; JMenuItem saveAsMenuItem; boolean running; //boolean presenting; boolean uploading; // undo fellers JMenuItem undoItem, redoItem; protected UndoAction undoAction; protected RedoAction redoAction; UndoManager undo; // used internally, and only briefly CompoundEdit compoundEdit; FindReplace find; Runnable runHandler; Runnable presentHandler; Runnable stopHandler; Runnable exportHandler; Runnable exportAppHandler; public Editor(Base ibase, String path, int[] location) { super("mpide"); this.base = ibase; Base.setIcon(this); // Install default actions for Run, Present, etc. resetHandlers(); // add listener to handle window close box hit event addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { base.handleClose(Editor.this); } }); // don't close the window when clicked, the app will take care // of that via the handleQuitInternal() methods setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // When bringing a window to front, let the Base know addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent e) { // System.err.println("activate"); // not coming through base.handleActivated(Editor.this); // re-add the sub-menus that are shared by all windows fileMenu.insert(sketchbookMenu, 2); fileMenu.insert(examplesMenu, 3); sketchMenu.insert(importMenu, 4); toolsMenu.insert(boardsMenu, numTools); toolsMenu.insert(serialMenu, numTools + 1); } // added for 1.0.5 public void windowDeactivated(WindowEvent e) { // System.err.println("deactivate"); // not coming through fileMenu.remove(sketchbookMenu); fileMenu.remove(examplesMenu); sketchMenu.remove(importMenu); toolsMenu.remove(boardsMenu); toolsMenu.remove(serialMenu); } }); //PdeKeywords keywords = new PdeKeywords(); //sketchbook = new Sketchbook(this); if (serialMonitor == null) serialMonitor = new SerialMonitor(Preferences.get("serial.port")); buildMenuBar(); // For rev 0120, placing things inside a JPanel Container contentPain = getContentPane(); contentPain.setLayout(new BorderLayout()); JPanel pain = new JPanel(); pain.setLayout(new BorderLayout()); contentPain.add(pain, BorderLayout.CENTER); Box box = Box.createVerticalBox(); Box upper = Box.createVerticalBox(); if (toolbarMenu == null) { toolbarMenu = new JMenu(); base.rebuildToolbarMenu(toolbarMenu); } toolbar = new EditorToolbar(this, toolbarMenu); upper.add(toolbar); header = new EditorHeader(this); upper.add(header); textarea = new JEditTextArea(new PdeTextAreaDefaults()); textarea.setRightClickPopup(new TextAreaPopup()); textarea.setHorizontalOffset(6); // assemble console panel, consisting of status area and the console itself consolePanel = new JPanel(); consolePanel.setLayout(new BorderLayout()); status = new EditorStatus(this); consolePanel.add(status, BorderLayout.NORTH); console = new EditorConsole(this); // windows puts an ugly border on this guy console.setBorder(null); consolePanel.add(console, BorderLayout.CENTER); lineStatus = new EditorLineStatus(textarea); consolePanel.add(lineStatus, BorderLayout.SOUTH); upper.add(textarea); splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upper, consolePanel); splitPane.setOneTouchExpandable(true); // repaint child panes while resizing splitPane.setContinuousLayout(true); // if window increases in size, give all of increase to // the textarea in the uppper pane splitPane.setResizeWeight(1D); // to fix ugliness.. normally macosx java 1.3 puts an // ugly white border around this object, so turn it off. splitPane.setBorder(null); // the default size on windows is too small and kinda ugly int dividerSize = Preferences.getInteger("editor.divider.size"); if (dividerSize != 0) { splitPane.setDividerSize(dividerSize); } splitPane.setMinimumSize(new Dimension(600, 400)); box.add(splitPane); // hopefully these are no longer needed w/ swing // (har har har.. that was wishful thinking) listener = new EditorListener(this, textarea); pain.add(box); // get shift down/up events so we can show the alt version of toolbar buttons textarea.addKeyListener(toolbar); pain.setTransferHandler(new FileDropHandler()); // System.out.println("t1"); // Finish preparing Editor (formerly found in Base) pack(); // System.out.println("t2"); // Set the window bounds and the divider location before setting it visible setPlacement(location); // If the window is resized too small this will resize it again to the // minimums. Adapted by Chris Lonnen from comments here: final int minW = Preferences.getInteger("editor.window.width.min"); final int minH = Preferences.getInteger("editor.window.height.min"); addComponentListener(new java.awt.event.ComponentAdapter() { public void componentResized(ComponentEvent event) { setSize((getWidth() < minW) ? minW : getWidth(), (getHeight() < minH) ? minH : getHeight()); } }); // System.out.println("t3"); // Bring back the general options for the editor applyPreferences(); // System.out.println("t4"); // Open the document that was passed in boolean loaded = handleOpenInternal(path); if (!loaded) sketch = null; // System.out.println("t5"); // All set, now show the window //setVisible(true); } /** * Handles files dragged & dropped from the desktop and into the editor * window. Dragging files into the editor window is the same as using * "Sketch &rarr; Add File" for each file. */ class FileDropHandler extends TransferHandler { public boolean canImport(JComponent dest, DataFlavor[] flavors) { return true; } @SuppressWarnings("unchecked") public boolean importData(JComponent src, Transferable transferable) { int successful = 0; try { DataFlavor uriListFlavor = new DataFlavor("text/uri-list;class=java.lang.String"); if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { java.util.List list = (java.util.List) transferable.getTransferData(DataFlavor.javaFileListFlavor); for (int i = 0; i < list.size(); i++) { File file = (File) list.get(i); if (sketch.addFile(file)) { successful++; } } } else if (transferable.isDataFlavorSupported(uriListFlavor)) { // Some platforms (Mac OS X and Linux, when this began) preferred // this method of moving files. String data = (String)transferable.getTransferData(uriListFlavor); String[] pieces = PApplet.splitTokens(data, "\r\n"); for (int i = 0; i < pieces.length; i++) { if (pieces[i].startsWith("#")) continue; String path = null; if (pieces[i].startsWith("file: path = pieces[i].substring(7); } else if (pieces[i].startsWith("file:/")) { path = pieces[i].substring(5); } if (sketch.addFile(new File(path))) { successful++; } } } } catch (Exception e) { e.printStackTrace(); return false; } if (successful == 0) { statusError("No files were added to the sketch."); } else if (successful == 1) { statusNotice("One file added to the sketch."); } else { statusNotice(successful + " files added to the sketch."); } return true; } } protected void setPlacement(int[] location) { setBounds(location[0], location[1], location[2], location[3]); if (location[4] != 0) { splitPane.setDividerLocation(location[4]); } } protected int[] getPlacement() { int[] location = new int[5]; // Get the dimensions of the Frame Rectangle bounds = getBounds(); location[0] = bounds.x; location[1] = bounds.y; location[2] = bounds.width; location[3] = bounds.height; // Get the current placement of the divider location[4] = splitPane.getDividerLocation(); return location; } /** * Hack for #@#)$(* Mac OS X 10.2. * <p/> * This appears to only be required on OS X 10.2, and is not * even being called on later versions of OS X or Windows. */ // public Dimension getMinimumSize() { // //System.out.println("getting minimum size"); // return new Dimension(500, 550); /** * Read and apply new values from the preferences, either because * the app is just starting up, or the user just finished messing * with things in the Preferences window. */ protected void applyPreferences() { // apply the setting for 'use external editor' boolean external = Preferences.getBoolean("editor.external"); textarea.setEditable(!external); saveMenuItem.setEnabled(!external); saveAsMenuItem.setEnabled(!external); TextAreaPainter painter = textarea.getPainter(); if (external) { // disable line highlight and turn off the caret when disabling Color color = Theme.getColor("editor.external.bgcolor"); painter.setBackground(color); painter.setLineHighlightEnabled(false); textarea.setCaretVisible(false); } else { Color color = Theme.getColor("editor.bgcolor"); painter.setBackground(color); boolean highlight = Preferences.getBoolean("editor.linehighlight"); painter.setLineHighlightEnabled(highlight); textarea.setCaretVisible(true); } // apply changes to the font size for the editor //TextAreaPainter painter = textarea.getPainter(); painter.setFont(Preferences.getFont("editor.font")); //Font font = painter.getFont(); //textarea.getPainter().setFont(new Font("Courier", Font.PLAIN, 36)); // in case tab expansion stuff has changed listener.applyPreferences(); // in case moved to a new location // For 0125, changing to async version (to be implemented later) //sketchbook.rebuildMenus(); // For 0126, moved into Base, which will notify all editors. //base.rebuildMenusAsync(); } protected void buildMenuBar() { JMenuBar menubar = new JMenuBar(); menubar = new JMenuBar(); menubar.add(buildFileMenu()); menubar.add(buildEditMenu()); menubar.add(buildSketchMenu()); menubar.add(buildToolsMenu()); menubar.add(buildHelpMenu()); setJMenuBar(menubar); } protected JMenu buildFileMenu() { JMenuItem item; fileMenu = new JMenu("File"); item = newJMenuItem("New", 'N'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleNew(); } }); fileMenu.add(item); item = Editor.newJMenuItem("Open...", 'O'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleOpenPrompt(); } }); fileMenu.add(item); if (sketchbookMenu == null) { sketchbookMenu = new JMenu("Sketchbook"); base.rebuildSketchbookMenu(sketchbookMenu); } fileMenu.add(sketchbookMenu); if (examplesMenu == null) { examplesMenu = new JMenu("Examples"); base.rebuildExamplesMenu(examplesMenu); } fileMenu.add(examplesMenu); item = Editor.newJMenuItem("Close", 'W'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleClose(Editor.this); } }); fileMenu.add(item); saveMenuItem = newJMenuItem("Save", 'S'); saveMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSave(false); } }); fileMenu.add(saveMenuItem); saveAsMenuItem = newJMenuItemShift("Save As...", 'S'); saveAsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSaveAs(); } }); fileMenu.add(saveAsMenuItem); item = newJMenuItem("Upload to I/O Board", 'U'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleExport(false); } }); fileMenu.add(item); // item = newJMenuItemShift("Upload to I/O Board (verbose)", 'U'); // item.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // handleExport(true); // fileMenu.add(item); fileMenu.addSeparator(); item = newJMenuItemShift("Page Setup", 'P'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePageSetup(); } }); fileMenu.add(item); item = newJMenuItem("Print", 'P'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePrint(); } }); fileMenu.add(item); // macosx already has its own preferences and quit menu if (!Base.isMacOS()) { fileMenu.addSeparator(); item = newJMenuItem("Preferences", ','); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handlePrefs(); } }); fileMenu.add(item); fileMenu.addSeparator(); item = newJMenuItem("Quit", 'Q'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleQuit(); } }); fileMenu.add(item); } return fileMenu; } protected JMenu buildSketchMenu() { JMenuItem item; sketchMenu = new JMenu("Sketch"); item = newJMenuItem("Verify / Compile", 'R'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleRun(false); } }); sketchMenu.add(item); // item = newJMenuItemShift("Verify / Compile (verbose)", 'R'); // item.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // handleRun(true); // sketchMenu.add(item); item = new JMenuItem("Stop"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleStop(); } }); sketchMenu.add(item); sketchMenu.addSeparator(); if (importMenu == null) { importMenu = new JMenu("Import Library..."); base.rebuildImportMenu(importMenu); } sketchMenu.add(importMenu); item = newJMenuItem("Show Sketch Folder", 'K'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openFolder(sketch.getFolder()); } }); sketchMenu.add(item); item.setEnabled(Base.openFolderAvailable()); item = new JMenuItem("Add File..."); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sketch.handleAddFile(); } }); sketchMenu.add(item); return sketchMenu; } protected JMenu buildToolsMenu() { toolsMenu = new JMenu("Tools"); JMenu menu = toolsMenu; JMenuItem item; addInternalTools(menu); item = newJMenuItemShift("Serial Monitor", 'M'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSerial(); } }); menu.add(item); addTools(menu, Base.getToolsFolder()); File sketchbookTools = new File(Base.getSketchbookFolder(), "tools"); addTools(menu, sketchbookTools); menu.addSeparator(); numTools = menu.getItemCount(); // XXX: DAM: these should probably be implemented using the Tools plugin // API, if possible (i.e. if it supports custom actions, etc.) if (boardsMenu == null) { boardsMenu = new JMenu("Board"); base.rebuildBoardsMenu(boardsMenu); //Debug: rebuild imports importMenu.removeAll(); base.rebuildImportMenu(importMenu); } menu.add(boardsMenu); if (serialMenuListener == null) serialMenuListener = new SerialMenuListener(); if (serialMenu == null) serialMenu = new JMenu("Serial Port"); populateSerialMenu(); menu.add(serialMenu); menu.addSeparator(); JMenu bootloaderMenu = new JMenu("Burn Bootloader"); base.rebuildBurnBootloaderMenu(bootloaderMenu); menu.add(bootloaderMenu); menu.addMenuListener(new MenuListener() { public void menuCanceled(MenuEvent e) {} public void menuDeselected(MenuEvent e) {} public void menuSelected(MenuEvent e) { //System.out.println("Tools menu selected."); populateSerialMenu(); } }); return menu; } protected void addTools(JMenu menu, File sourceFolder) { HashMap<String, JMenuItem> toolItems = new HashMap<String, JMenuItem>(); File[] folders = sourceFolder.listFiles(new FileFilter() { public boolean accept(File folder) { if (folder.isDirectory()) { //System.out.println("checking " + folder); File subfolder = new File(folder, "tool"); return subfolder.exists(); } return false; } }); if (folders == null || folders.length == 0) { return; } for (int i = 0; i < folders.length; i++) { File toolDirectory = new File(folders[i], "tool"); try { // add dir to classpath for .classes //urlList.add(toolDirectory.toURL()); // add .jar files to classpath File[] archives = toolDirectory.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return (name.toLowerCase().endsWith(".jar") || name.toLowerCase().endsWith(".zip")); } }); URL[] urlList = new URL[archives.length]; for (int j = 0; j < urlList.length; j++) { urlList[j] = archives[j].toURI().toURL(); } URLClassLoader loader = new URLClassLoader(urlList); String className = null; for (int j = 0; j < archives.length; j++) { className = findClassInZipFile(folders[i].getName(), archives[j]); if (className != null) break; } // If no class name found, just move on. if (className == null) continue; Class<?> toolClass = Class.forName(className, true, loader); final Tool tool = (Tool) toolClass.newInstance(); tool.init(Editor.this); String title = tool.getMenuTitle(); JMenuItem item = new JMenuItem(title); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(tool); //new Thread(tool).start(); } }); //menu.add(item); toolItems.put(title, item); } catch (Exception e) { e.printStackTrace(); } } ArrayList<String> toolList = new ArrayList<String>(toolItems.keySet()); if (toolList.size() == 0) return; menu.addSeparator(); Collections.sort(toolList); for (String title : toolList) { menu.add((JMenuItem) toolItems.get(title)); } } protected String findClassInZipFile(String base, File file) { // Class file to search for String classFileName = "/" + base + ".class"; try { ZipFile zipFile = new ZipFile(file); Enumeration<?> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (!entry.isDirectory()) { String name = entry.getName(); //System.out.println("entry: " + name); if (name.endsWith(classFileName)) { //int slash = name.lastIndexOf('/'); //String packageName = (slash == -1) ? "" : name.substring(0, slash); // Remove .class and convert slashes to periods. return name.substring(0, name.length() - 6).replace('/', '.'); } } } } catch (IOException e) { //System.err.println("Ignoring " + filename + " (" + e.getMessage() + ")"); e.printStackTrace(); } return null; } protected JMenuItem createToolMenuItem(String className) { try { Class<?> toolClass = Class.forName(className); final Tool tool = (Tool) toolClass.newInstance(); JMenuItem item = new JMenuItem(tool.getMenuTitle()); tool.init(Editor.this); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(tool); } }); return item; } catch (Exception e) { e.printStackTrace(); return null; } } protected JMenu addInternalTools(JMenu menu) { JMenuItem item; item = createToolMenuItem("processing.app.tools.AutoFormat"); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); item.setAccelerator(KeyStroke.getKeyStroke('T', modifiers)); menu.add(item); //menu.add(createToolMenuItem("processing.app.tools.CreateFont")); //menu.add(createToolMenuItem("processing.app.tools.ColorSelector")); menu.add(createToolMenuItem("processing.app.tools.Archiver")); menu.add(createToolMenuItem("processing.app.tools.FixEncoding")); // // These are temporary entries while Android mode is being worked out. // // The mode will not be in the tools menu, and won't involve a cmd-key // if (!Base.RELEASE) { // item = createToolMenuItem("processing.app.tools.android.AndroidTool"); // item.setAccelerator(KeyStroke.getKeyStroke('D', modifiers)); // menu.add(item); // menu.add(createToolMenuItem("processing.app.tools.android.Reset")); return menu; } class SerialMenuListener implements ActionListener { //public SerialMenuListener() { } public void actionPerformed(ActionEvent e) { selectSerialPort(((JCheckBoxMenuItem)e.getSource()).getText()); } /* public void actionPerformed(ActionEvent e) { System.out.println(e.getSource()); String name = e.getActionCommand(); PdeBase.properties.put("serial.port", name); System.out.println("set to " + get("serial.port")); //editor.skOpen(path + File.separator + name, name); // need to push "serial.port" into PdeBase.properties } */ } protected void selectSerialPort(String name) { if(serialMenu == null) { System.out.println("serialMenu is null"); return; } if (name == null) { System.out.println("name is null"); return; } JCheckBoxMenuItem selection = null; for (int i = 0; i < serialMenu.getItemCount(); i++) { JCheckBoxMenuItem item = ((JCheckBoxMenuItem)serialMenu.getItem(i)); if (item == null) { System.out.println("name is null"); continue; } item.setState(false); if (name.equals(item.getText())) selection = item; } if (selection != null) selection.setState(true); //System.out.println(item.getLabel()); Preferences.set("serial.port", name); serialMonitor.closeSerialPort(); serialMonitor.setVisible(false); serialMonitor = new SerialMonitor(Preferences.get("serial.port")); //System.out.println("set to " + get("serial.port")); } protected void populateSerialMenu() { // getting list of ports JMenuItem rbMenuItem; //System.out.println("Clearing serial port menu."); serialMenu.removeAll(); boolean empty = true; try { for (Enumeration enumeration = CommPortIdentifier.getPortIdentifiers(); enumeration.hasMoreElements();) { CommPortIdentifier commportidentifier = (CommPortIdentifier)enumeration.nextElement(); //System.out.println("Found communication port: " + commportidentifier); if (commportidentifier.getPortType() == CommPortIdentifier.PORT_SERIAL) { //System.out.println("Adding port to serial port menu: " + commportidentifier); String curr_port = commportidentifier.getName(); rbMenuItem = new JCheckBoxMenuItem(curr_port, curr_port.equals(Preferences.get("serial.port"))); rbMenuItem.addActionListener(serialMenuListener); //serialGroup.add(rbMenuItem); serialMenu.add(rbMenuItem); empty = false; } } if (!empty) { //System.out.println("enabling the serialMenu"); serialMenu.setEnabled(true); } } catch (Exception exception) { System.out.println("error retrieving port list"); exception.printStackTrace(); } if (serialMenu.getItemCount() == 0) { serialMenu.setEnabled(false); } //serialMenu.addSeparator(); //serialMenu.add(item); } protected JMenu buildHelpMenu() { // To deal with a Mac OS X 10.5 bug, add an extra space after the name // so that the OS doesn't try to insert its slow help menu. JMenu menu = new JMenu("Help "); JMenuItem item; item = new JMenuItem("Getting Started"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showGettingStarted(); } }); menu.add(item); item = new JMenuItem("Environment"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showEnvironment(); } }); menu.add(item); item = new JMenuItem("Troubleshooting"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showTroubleshooting(); } }); menu.add(item); item = new JMenuItem("Reference"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference(); } }); menu.add(item); item = newJMenuItemShift("Find in Reference", 'F'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (textarea.isSelectionActive()) { handleFindReference(); } } }); menu.add(item); item = new JMenuItem("Frequently Asked Questions"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showFAQ(); } }); menu.add(item); item = new JMenuItem("Visit Arduino.cc"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL("http://arduino.cc/"); } }); menu.add(item); item = new JMenuItem("Visit ChipKit.cc"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL("http://chipkit.cc/"); } }); menu.add(item); // macosx already has its own about menu if (!Base.isMacOS()) { menu.addSeparator(); item = new JMenuItem("About Arduino"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleAbout(); } }); menu.add(item); } return menu; } protected JMenu buildEditMenu() { JMenu menu = new JMenu("Edit"); JMenuItem item; undoItem = newJMenuItem("Undo", 'Z'); undoItem.addActionListener(undoAction = new UndoAction()); menu.add(undoItem); redoItem = newJMenuItem("Redo", 'Y'); redoItem.addActionListener(redoAction = new RedoAction()); menu.add(redoItem); menu.addSeparator(); // TODO "cut" and "copy" should really only be enabled // if some text is currently selected item = newJMenuItem("Cut", 'X'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCut(); } }); menu.add(item); item = newJMenuItem("Copy", 'C'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.copy(); } }); menu.add(item); item = newJMenuItemShift("Copy for Forum", 'C'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // SwingUtilities.invokeLater(new Runnable() { // public void run() { new DiscourseFormat(Editor.this, false).show(); } }); menu.add(item); item = newJMenuItemAlt("Copy as HTML", 'C'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // SwingUtilities.invokeLater(new Runnable() { // public void run() { new DiscourseFormat(Editor.this, true).show(); } }); menu.add(item); item = newJMenuItem("Paste", 'V'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.paste(); sketch.setModified(true); } }); menu.add(item); item = newJMenuItem("Select All", 'A'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.selectAll(); } }); menu.add(item); menu.addSeparator(); item = newJMenuItem("Comment/Uncomment", '/'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCommentUncomment(); } }); menu.add(item); item = newJMenuItem("Increase Indent", ']'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleIndentOutdent(true); } }); menu.add(item); item = newJMenuItem("Decrease Indent", '['); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleIndentOutdent(false); } }); menu.add(item); menu.addSeparator(); item = newJMenuItem("Find...", 'F'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find == null) { find = new FindReplace(Editor.this); } //new FindReplace(Editor.this).show(); find.setVisible(true); //find.setVisible(true); } }); menu.add(item); // TODO find next should only be enabled after a // search has actually taken place item = newJMenuItem("Find Next", 'G'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find != null) { //find.find(true); //FindReplace find = new FindReplace(Editor.this); //.show(); find.find(true); } } }); menu.add(item); return menu; } /** * A software engineer, somewhere, needs to have his abstraction * taken away. In some countries they jail or beat people for writing * the sort of API that would require a five line helper function * just to set the command key for a menu item. */ static public JMenuItem newJMenuItem(String title, int what) { JMenuItem menuItem = new JMenuItem(title); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers)); return menuItem; } /** * Like newJMenuItem() but adds shift as a modifier for the key command. */ static public JMenuItem newJMenuItemShift(String title, int what) { JMenuItem menuItem = new JMenuItem(title); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); modifiers |= ActionEvent.SHIFT_MASK; menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers)); return menuItem; } /** * Same as newJMenuItem(), but adds the ALT (on Linux and Windows) * or OPTION (on Mac OS X) key as a modifier. */ static public JMenuItem newJMenuItemAlt(String title, int what) { JMenuItem menuItem = new JMenuItem(title); //int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); //menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers)); menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_ALT_KEY_MASK)); return menuItem; } class UndoAction extends AbstractAction { public UndoAction() { super("Undo"); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { try { undo.undo(); } catch (CannotUndoException ex) { //System.out.println("Unable to undo: " + ex); //ex.printStackTrace(); } updateUndoState(); redoAction.updateRedoState(); } protected void updateUndoState() { if (undo.canUndo()) { this.setEnabled(true); undoItem.setEnabled(true); undoItem.setText(undo.getUndoPresentationName()); putValue(Action.NAME, undo.getUndoPresentationName()); if (sketch != null) { sketch.setModified(true); // 0107 } } else { this.setEnabled(false); undoItem.setEnabled(false); undoItem.setText("Undo"); putValue(Action.NAME, "Undo"); if (sketch != null) { sketch.setModified(false); // 0107 } } } } class RedoAction extends AbstractAction { public RedoAction() { super("Redo"); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { try { undo.redo(); } catch (CannotRedoException ex) { //System.out.println("Unable to redo: " + ex); //ex.printStackTrace(); } updateRedoState(); undoAction.updateUndoState(); } protected void updateRedoState() { if (undo.canRedo()) { redoItem.setEnabled(true); redoItem.setText(undo.getRedoPresentationName()); putValue(Action.NAME, undo.getRedoPresentationName()); } else { this.setEnabled(false); redoItem.setEnabled(false); redoItem.setText("Redo"); putValue(Action.NAME, "Redo"); } } } // these will be done in a more generic way soon, more like: // setHandler("action name", Runnable); // but for the time being, working out the kinks of how many things to // abstract from the editor in this fashion. public void setHandlers(Runnable runHandler, Runnable presentHandler, Runnable stopHandler, Runnable exportHandler, Runnable exportAppHandler) { this.runHandler = runHandler; this.presentHandler = presentHandler; this.stopHandler = stopHandler; this.exportHandler = exportHandler; this.exportAppHandler = exportAppHandler; } public void resetHandlers() { runHandler = new DefaultRunHandler(); presentHandler = new DefaultPresentHandler(); stopHandler = new DefaultStopHandler(); exportHandler = new DefaultExportHandler(); exportAppHandler = new DefaultExportAppHandler(); } /** * Gets the current sketch object. */ public Sketch getSketch() { return sketch; } /** * Get the JEditTextArea object for use (not recommended). This should only * be used in obscure cases that really need to hack the internals of the * JEditTextArea. Most tools should only interface via the get/set functions * found in this class. This will maintain compatibility with future releases, * which will not use JEditTextArea. */ public JEditTextArea getTextArea() { return textarea; } /** * Get the contents of the current buffer. Used by the Sketch class. */ public String getText() { return textarea.getText(); } /** * Get a range of text from the current buffer. */ public String getText(int start, int stop) { return textarea.getText(start, stop - start); } /** * Replace the entire contents of the front-most tab. */ public void setText(String what) { startCompoundEdit(); textarea.setText(what); stopCompoundEdit(); } public void insertText(String what) { startCompoundEdit(); int caret = getCaretOffset(); setSelection(caret, caret); textarea.setSelectedText(what); stopCompoundEdit(); } /** * Called to update the text but not switch to a different set of code * (which would affect the undo manager). */ // public void setText2(String what, int start, int stop) { // beginCompoundEdit(); // textarea.setText(what); // endCompoundEdit(); // // make sure that a tool isn't asking for a bad location // start = Math.max(0, Math.min(start, textarea.getDocumentLength())); // stop = Math.max(0, Math.min(start, textarea.getDocumentLength())); // textarea.select(start, stop); // textarea.requestFocus(); // get the caret blinking public String getSelectedText() { return textarea.getSelectedText(); } public void setSelectedText(String what) { textarea.setSelectedText(what); } public void setSelection(int start, int stop) { // make sure that a tool isn't asking for a bad location start = PApplet.constrain(start, 0, textarea.getDocumentLength()); stop = PApplet.constrain(stop, 0, textarea.getDocumentLength()); textarea.select(start, stop); } /** * Get the position (character offset) of the caret. With text selected, * this will be the last character actually selected, no matter the direction * of the selection. That is, if the user clicks and drags to select lines * 7 up to 4, then the caret position will be somewhere on line four. */ public int getCaretOffset() { return textarea.getCaretPosition(); } /** * True if some text is currently selected. */ public boolean isSelectionActive() { return textarea.isSelectionActive(); } /** * Get the beginning point of the current selection. */ public int getSelectionStart() { return textarea.getSelectionStart(); } /** * Get the end point of the current selection. */ public int getSelectionStop() { return textarea.getSelectionStop(); } /** * Get text for a specified line. */ public String getLineText(int line) { return textarea.getLineText(line); } /** * Replace the text on a specified line. */ public void setLineText(int line, String what) { startCompoundEdit(); textarea.select(getLineStartOffset(line), getLineStopOffset(line)); textarea.setSelectedText(what); stopCompoundEdit(); } /** * Get character offset for the start of a given line of text. */ public int getLineStartOffset(int line) { return textarea.getLineStartOffset(line); } /** * Get character offset for end of a given line of text. */ public int getLineStopOffset(int line) { return textarea.getLineStopOffset(line); } /** * Get the number of lines in the currently displayed buffer. */ public int getLineCount() { return textarea.getLineCount(); } /** * Use before a manipulating text to group editing operations together as a * single undo. Use stopCompoundEdit() once finished. */ public void startCompoundEdit() { compoundEdit = new CompoundEdit(); } /** * Use with startCompoundEdit() to group edit operations in a single undo. */ public void stopCompoundEdit() { compoundEdit.end(); undo.addEdit(compoundEdit); undoAction.updateUndoState(); redoAction.updateRedoState(); compoundEdit = null; } public int getScrollPosition() { return textarea.getScrollPosition(); } /** * Switch between tabs, this swaps out the Document object * that's currently being manipulated. */ protected void setCode(SketchCode code) { SyntaxDocument document = (SyntaxDocument) code.getDocument(); if (document == null) { // this document not yet inited document = new SyntaxDocument(); code.setDocument(document); // turn on syntax highlighting document.setTokenMarker(new PdeKeywords()); // insert the program text into the document object try { document.insertString(0, code.getProgram(), null); } catch (BadLocationException bl) { bl.printStackTrace(); } // set up this guy's own undo manager // code.undo = new UndoManager(); // connect the undo listener to the editor document.addUndoableEditListener(new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent e) { if (compoundEdit != null) { compoundEdit.addEdit(e.getEdit()); } else if (undo != null) { undo.addEdit(e.getEdit()); undoAction.updateUndoState(); redoAction.updateRedoState(); } } }); } // update the document object that's in use textarea.setDocument(document, code.getSelectionStart(), code.getSelectionStop(), code.getScrollPosition()); textarea.requestFocus(); // get the caret blinking this.undo = code.getUndo(); undoAction.updateUndoState(); redoAction.updateRedoState(); } /** * Implements Edit &rarr; Cut. */ public void handleCut() { textarea.cut(); sketch.setModified(true); } /** * Implements Edit &rarr; Copy. */ public void handleCopy() { textarea.copy(); } protected void handleDiscourseCopy() { new DiscourseFormat(Editor.this, false).show(); } protected void handleHTMLCopy() { new DiscourseFormat(Editor.this, true).show(); } /** * Implements Edit &rarr; Paste. */ public void handlePaste() { textarea.paste(); sketch.setModified(true); } /** * Implements Edit &rarr; Select All. */ public void handleSelectAll() { textarea.selectAll(); } protected void handleCommentUncomment() { startCompoundEdit(); int startLine = textarea.getSelectionStartLine(); int stopLine = textarea.getSelectionStopLine(); int lastLineStart = textarea.getLineStartOffset(stopLine); int selectionStop = textarea.getSelectionStop(); // If the selection ends at the beginning of the last line, // then don't (un)comment that line. if (selectionStop == lastLineStart) { // Though if there's no selection, don't do that if (textarea.isSelectionActive()) { stopLine } } // If the text is empty, ignore the user. // Also ensure that all lines are commented (not just the first) // when determining whether to comment or uncomment. int length = textarea.getDocumentLength(); boolean commented = true; for (int i = startLine; commented && (i <= stopLine); i++) { int pos = textarea.getLineStartOffset(i); if (pos + 2 > length) { commented = false; } else { // Check the first two characters to see if it's already a comment. String begin = textarea.getText(pos, 2); //System.out.println("begin is '" + begin + "'"); commented = begin.equals(" } } for (int line = startLine; line <= stopLine; line++) { int location = textarea.getLineStartOffset(line); if (commented) { // remove a comment textarea.select(location, location+2); if (textarea.getSelectedText().equals(" textarea.setSelectedText(""); } } else { // add a comment textarea.select(location, location); textarea.setSelectedText(" } } // Subtract one from the end, otherwise selects past the current line. // (Which causes subsequent calls to keep expanding the selection) textarea.select(textarea.getLineStartOffset(startLine), textarea.getLineStopOffset(stopLine) - 1); stopCompoundEdit(); } protected void handleIndentOutdent(boolean indent) { int tabSize = Preferences.getInteger("editor.tabs.size"); String tabString = Editor.EMPTY.substring(0, tabSize); startCompoundEdit(); int startLine = textarea.getSelectionStartLine(); int stopLine = textarea.getSelectionStopLine(); // If the selection ends at the beginning of the last line, // then don't (un)comment that line. int lastLineStart = textarea.getLineStartOffset(stopLine); int selectionStop = textarea.getSelectionStop(); if (selectionStop == lastLineStart) { // Though if there's no selection, don't do that if (textarea.isSelectionActive()) { stopLine } } for (int line = startLine; line <= stopLine; line++) { int location = textarea.getLineStartOffset(line); if (indent) { textarea.select(location, location); textarea.setSelectedText(tabString); } else { // outdent textarea.select(location, location + tabSize); // Don't eat code if it's not indented if (textarea.getSelectedText().equals(tabString)) { textarea.setSelectedText(""); } } } // Subtract one from the end, otherwise selects past the current line. // (Which causes subsequent calls to keep expanding the selection) textarea.select(textarea.getLineStartOffset(startLine), textarea.getLineStopOffset(stopLine) - 1); stopCompoundEdit(); } protected void handleFindReference() { String text = textarea.getSelectedText().trim(); if (text.length() == 0) { statusNotice("First select a word to find in the reference."); } else { String referenceFile = PdeKeywords.getReference(text); //System.out.println("reference file is " + referenceFile); if (referenceFile == null) { statusNotice("No reference available for \"" + text + "\""); } else { Base.showReference(referenceFile + ".html"); } } } /** * Implements Sketch &rarr; Run. * @param verbose Set true to run with verbose output. */ public void handleRun(final boolean verbose) { internalCloseRunner(); running = true; toolbar.activate(EditorToolbar.RUN); statusNotice("Compiling..."); // do this to advance/clear the terminal window / dos prompt / etc for (int i = 0; i < 10; i++) System.out.println(); // clear the console on each run, unless the user doesn't want to if (Preferences.getBoolean("console.auto_clear")) { console.clear(); } // Cannot use invokeLater() here, otherwise it gets // placed on the event thread and causes a hang--bad idea all around. new Thread(verbose ? presentHandler : runHandler).start(); } // DAM: in Arduino, this is compile class DefaultRunHandler implements Runnable { public void run() { try { sketch.prepare(); String appletClassName = sketch.build(false); statusNotice("Done compiling."); } catch (Exception e) { statusError(e); } toolbar.deactivate(EditorToolbar.RUN); } } // DAM: in Arduino, this is compile (with verbose output) class DefaultPresentHandler implements Runnable { public void run() { try { sketch.prepare(); String appletClassName = sketch.build(true); statusNotice("Done compiling."); } catch (Exception e) { statusError(e); } toolbar.deactivate(EditorToolbar.RUN); } } class DefaultStopHandler implements Runnable { public void run() { try { // DAM: we should try to kill the compilation or upload process here. } catch (Exception e) { statusError(e); } } } /** * Set the location of the sketch run window. Used by Runner to update the * Editor about window drag events while the sketch is running. */ public void setSketchLocation(Point p) { sketchWindowLocation = p; } /** * Get the last location of the sketch's run window. Used by Runner to make * the window show up in the same location as when it was last closed. */ public Point getSketchLocation() { return sketchWindowLocation; } /** * Implements Sketch &rarr; Stop, or pressing Stop on the toolbar. */ public void handleStop() { // called by menu or buttons toolbar.activate(EditorToolbar.STOP); internalCloseRunner(); toolbar.deactivate(EditorToolbar.RUN); toolbar.deactivate(EditorToolbar.STOP); // focus the PDE again after quitting presentation mode [toxi 030903] toFront(); } /** * Deactivate the Run button. This is called by Runner to notify that the * sketch has stopped running, usually in response to an error (or maybe * the sketch completing and exiting?) Tools should not call this function. * To initiate a "stop" action, call handleStop() instead. */ public void internalRunnerClosed() { running = false; toolbar.deactivate(EditorToolbar.RUN); } /** * Handle internal shutdown of the runner. */ public void internalCloseRunner() { running = false; if (stopHandler != null) try { stopHandler.run(); } catch (Exception e) { } sketch.cleanup(); } /** * Check if the sketch is modified and ask user to save changes. * @return false if canceling the close/quit operation */ protected boolean checkModified() { if (!sketch.isModified()) return true; // As of Processing 1.0.10, this always happens immediately. String prompt = "Save changes to " + sketch.getName() + "? "; if (!Base.isMacOS()) { int result = JOptionPane.showConfirmDialog(this, prompt, "Close", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { return handleSave(true); } else if (result == JOptionPane.NO_OPTION) { return true; // ok to continue } else if (result == JOptionPane.CANCEL_OPTION) { return false; } else { throw new IllegalStateException(); } } else { // This code is disabled unless Java 1.5 is being used on Mac OS X // because of a Java bug that prevents the initial value of the // dialog from being set properly (at least on my MacBook Pro). // The bug causes the "Don't Save" option to be the highlighted, // blinking, default. This sucks. But I'll tell you what doesn't // suck--workarounds for the Mac and Apple's snobby attitude about it! // I think it's nifty that they treat their developers like dirt. // Pane formatting adapted from the quaqua guide JOptionPane pane = new JOptionPane("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>Do you want to save changes to this sketch<BR>" + " before closing?</b>" + "<p>If you don't save, your changes will be lost.", JOptionPane.QUESTION_MESSAGE); String[] options = new String[] { "Save", "Cancel", "Don't Save" }; pane.setOptions(options); // highlight the safest option ala apple hig pane.setInitialValue(options[0]); // on macosx, setting the destructive property places this option // away from the others at the lefthand side pane.putClientProperty("Quaqua.OptionPane.destructiveOption", new Integer(2)); JDialog dialog = pane.createDialog(this, null); dialog.setVisible(true); Object result = pane.getValue(); if (result == options[0]) { // save (and close/quit) return handleSave(true); } else if (result == options[2]) { // don't save (still close/quit) return true; } else { // cancel? return false; } } } /** * Open a sketch from a particular path, but don't check to save changes. * Used by Sketch.saveAs() to re-open a sketch after the "Save As" */ protected void handleOpenUnchecked(String path, int codeIndex, int selStart, int selStop, int scrollPos) { internalCloseRunner(); handleOpenInternal(path); // Replacing a document that may be untitled. If this is an actual // untitled document, then editor.untitled will be set by Base. untitled = false; sketch.setCurrentCode(codeIndex); textarea.select(selStart, selStop); textarea.setScrollPosition(scrollPos); } /** * Second stage of open, occurs after having checked to see if the * modifications (if any) to the previous sketch need to be saved. */ protected boolean handleOpenInternal(String path) { // check to make sure that this .pde file is // in a folder of the same name File file = new File(path); File parentFile = new File(file.getParent()); String parentName = parentFile.getName(); String pdeName = parentName + ".pde"; File altFile = new File(file.getParent(), pdeName); if (pdeName.equals(file.getName())) { // no beef with this guy } else if (altFile.exists()) { // user selected a .java from the same sketch, // but open the .pde instead path = altFile.getAbsolutePath(); //System.out.println("found alt file in same folder"); } else if (!path.endsWith(".pde")) { Base.showWarning("Bad file selected", "Processing can only open its own sketches\n" + "and other files ending in .pde", null); return false; } else { String properParent = file.getName().substring(0, file.getName().length() - 4); Object[] options = { "OK", "Cancel" }; String prompt = "The file \"" + file.getName() + "\" needs to be inside\n" + "a sketch folder named \"" + properParent + "\".\n" + "Create this folder, move the file, and continue?"; int result = JOptionPane.showOptionDialog(this, prompt, "Moving", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.YES_OPTION) { // create properly named folder File properFolder = new File(file.getParent(), properParent); if (properFolder.exists()) { Base.showWarning("Error", "A folder named \"" + properParent + "\" " + "already exists. Can't open sketch.", null); return false; } if (!properFolder.mkdirs()) { //throw new IOException("Couldn't create sketch folder"); Base.showWarning("Error", "Could not create the sketch folder.", null); return false; } // copy the sketch inside File properPdeFile = new File(properFolder, file.getName()); File origPdeFile = new File(path); try { Base.copyFile(origPdeFile, properPdeFile); } catch (IOException e) { Base.showWarning("Error", "Could not copy to a proper location.", e); return false; } // remove the original file, so user doesn't get confused origPdeFile.delete(); // update with the new path path = properPdeFile.getAbsolutePath(); } else if (result == JOptionPane.NO_OPTION) { return false; } } try { sketch = new Sketch(this, path); } catch (IOException e) { Base.showWarning("Error", "Could not create the sketch.", e); return false; } header.rebuild(); // Set the title of the window to "sketch_070752a - Processing 0126" setTitle(sketch.getName() + " | Mpide " + Base.VERSION_NAME); // Disable untitled setting from previous document, if any untitled = false; // Store information on who's open and running // (in case there's a crash or something that can't be recovered) base.storeSketches(); Preferences.save(); // opening was successful return true; // } catch (Exception e) { // e.printStackTrace(); // statusError(e); // return false; } public boolean handleSave(boolean immediately) { //stopRunner(); handleStop(); // 0136 if (untitled) { return handleSaveAs(); // need to get the name, user might also cancel here } else if (immediately) { handleSave2(); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { handleSave2(); } }); } return true; } protected void handleSave2() { toolbar.activate(EditorToolbar.SAVE); statusNotice("Saving..."); try { if (sketch.save()) { statusNotice("Done Saving."); } else { statusEmpty(); } // rebuild sketch menu in case a save-as was forced // Disabling this for 0125, instead rebuild the menu inside // the Save As method of the Sketch object, since that's the // only one who knows whether something was renamed. //sketchbook.rebuildMenus(); //sketchbook.rebuildMenusAsync(); } catch (Exception e) { // show the error as a message in the window statusError(e); // zero out the current action, // so that checkModified2 will just do nothing //checkModifiedMode = 0; // this is used when another operation calls a save } //toolbar.clear(); toolbar.deactivate(EditorToolbar.SAVE); } public boolean handleSaveAs() { //stopRunner(); // formerly from 0135 handleStop(); toolbar.activate(EditorToolbar.SAVE); //SwingUtilities.invokeLater(new Runnable() { //public void run() { statusNotice("Saving..."); try { if (sketch.saveAs()) { statusNotice("Done Saving."); // Disabling this for 0125, instead rebuild the menu inside // the Save As method of the Sketch object, since that's the // only one who knows whether something was renamed. //sketchbook.rebuildMenusAsync(); } else { statusNotice("Save Canceled."); return false; } } catch (Exception e) { // show the error as a message in the window statusError(e); } finally { // make sure the toolbar button deactivates toolbar.deactivate(EditorToolbar.SAVE); } return true; } public boolean serialPrompt() { int count = serialMenu.getItemCount(); Object[] names = new Object[count]; for (int i = 0; i < count; i++) { names[i] = ((JCheckBoxMenuItem)serialMenu.getItem(i)).getText(); } String result = (String) JOptionPane.showInputDialog(this, "Serial port " + Preferences.get("serial.port") + " not found.\n" + "Retry the upload with another serial port?", "Serial port not found", JOptionPane.PLAIN_MESSAGE, null, names, 0); if (result == null) return false; selectSerialPort(result); return true; } /** * Called by Sketch &rarr; Export. * Handles calling the export() function on sketch, and * queues all the gui status stuff that comes along with it. * <p/> * Made synchronized to (hopefully) avoid problems of people * hitting export twice, quickly, and horking things up. */ /** * Handles calling the export() function on sketch, and * queues all the gui status stuff that comes along with it. * * Made synchronized to (hopefully) avoid problems of people * hitting export twice, quickly, and horking things up. */ synchronized public void handleExport(final boolean verbose) { //if (!handleExportCheckModified()) return; toolbar.activate(EditorToolbar.EXPORT); console.clear(); statusNotice("Uploading to I/O Board..."); new Thread(verbose ? exportAppHandler : exportHandler).start(); } // DAM: in Arduino, this is upload class DefaultExportHandler implements Runnable { public void run() { try { serialMonitor.closeSerialPort(); serialMonitor.setVisible(false); uploading = true; boolean success = sketch.exportApplet(false); if (success) { statusNotice("Done uploading."); } else { // error message will already be visible } } catch (SerialNotFoundException e) { populateSerialMenu(); if (serialMenu.getItemCount() == 0) statusError(e); else if (serialPrompt()) run(); else statusNotice("Upload canceled."); } catch (RunnerException e) { //statusError("Error during upload."); //e.printStackTrace(); statusError(e); } catch (Exception e) { e.printStackTrace(); } uploading = false; //toolbar.clear(); toolbar.deactivate(EditorToolbar.EXPORT); } } // DAM: in Arduino, this is upload (with verbose output) class DefaultExportAppHandler implements Runnable { public void run() { try { serialMonitor.closeSerialPort(); serialMonitor.setVisible(false); uploading = true; boolean success = sketch.exportApplet(true); if (success) { statusNotice("Done uploading."); } else { // error message will already be visible } } catch (SerialNotFoundException e) { populateSerialMenu(); if (serialMenu.getItemCount() == 0) statusError(e); else if (serialPrompt()) run(); else statusNotice("Upload canceled."); } catch (RunnerException e) { //statusError("Error during upload."); //e.printStackTrace(); statusError(e); } catch (Exception e) { e.printStackTrace(); } uploading = false; //toolbar.clear(); toolbar.deactivate(EditorToolbar.EXPORT); } } protected boolean handleExportCheckModified() { if (!sketch.isModified()) return true; Object[] options = { "OK", "Cancel" }; int result = JOptionPane.showOptionDialog(this, "Save changes before export?", "Save", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.OK_OPTION) { handleSave(true); } else { // why it's not CANCEL_OPTION is beyond me (at least on the mac) // but f-- it.. let's get this shite done.. //} else if (result == JOptionPane.CANCEL_OPTION) { statusNotice("Export canceled, changes must first be saved."); //toolbar.clear(); return false; } return true; } public void handleSerial() { if (uploading) return; try { serialMonitor.openSerialPort(); serialMonitor.setVisible(true); } catch (SerialException e) { statusError(e); } } protected void handleBurnBootloader(final String target, final String programmer) { console.clear(); statusNotice("Burning bootloader to I/O Board (this may take a minute)..."); SwingUtilities.invokeLater(new Runnable() { public void run() { try { Uploader uploader = new AvrdudeUploader(); /* if (Base.getBoardPreferences().get("upload.using").equals("picdude")) { uploader = new PicdudeUploader(); } */ if (uploader.burnBootloader(target, programmer)) { statusNotice("Done burning bootloader."); } else { statusError("Error while burning bootloader."); // error message will already be visible } } catch (RunnerException e) { statusError("Error while burning bootloader."); e.printStackTrace(); //statusError(e); } catch (Exception e) { statusError("Error while burning bootloader."); e.printStackTrace(); } }}); } /** * Handler for File &rarr; Page Setup. */ public void handlePageSetup() { //printerJob = null; if (printerJob == null) { printerJob = PrinterJob.getPrinterJob(); } if (pageFormat == null) { pageFormat = printerJob.defaultPage(); } pageFormat = printerJob.pageDialog(pageFormat); //System.out.println("page format is " + pageFormat); } /** * Handler for File &rarr; Print. */ public void handlePrint() { statusNotice("Printing..."); //printerJob = null; if (printerJob == null) { printerJob = PrinterJob.getPrinterJob(); } if (pageFormat != null) { //System.out.println("setting page format " + pageFormat); printerJob.setPrintable(textarea.getPainter(), pageFormat); } else { printerJob.setPrintable(textarea.getPainter()); } // set the name of the job to the code name printerJob.setJobName(sketch.getCurrentCode().getPrettyName()); if (printerJob.printDialog()) { try { printerJob.print(); statusNotice("Done printing."); } catch (PrinterException pe) { statusError("Error while printing."); pe.printStackTrace(); } } else { statusNotice("Printing canceled."); } //printerJob = null; // clear this out? } /** * Show an error int the status bar. */ public void statusError(String what) { status.error(what); //new Exception("deactivating RUN").printStackTrace(); toolbar.deactivate(EditorToolbar.RUN); } /** * Show an exception in the editor status bar. */ public void statusError(Exception e) { e.printStackTrace(); // if (e == null) { // System.err.println("Editor.statusError() was passed a null exception."); // return; if (e instanceof RunnerException) { RunnerException re = (RunnerException) e; if (re.hasCodeIndex()) { sketch.setCurrentCode(re.getCodeIndex()); } if (re.hasCodeLine()) { int line = re.getCodeLine(); // subtract one from the end so that the \n ain't included if (line >= textarea.getLineCount()) { // The error is at the end of this current chunk of code, // so the last line needs to be selected. line = textarea.getLineCount() - 1; if (textarea.getLineText(line).length() == 0) { // The last line may be zero length, meaning nothing to select. // If so, back up one more line. line } } logger.debug("Editor: line: " + line); logger.debug("Editor: textarea.getLineCount()" + textarea.getLineCount()); if (line < 0 || line >= textarea.getLineCount()) { System.err.println("Bad error line: " + line); } else { textarea.select(textarea.getLineStartOffset(line), textarea.getLineStopOffset(line) - 1); } } } // Since this will catch all Exception types, spend some time figuring // out which kind and try to give a better error message to the user. String mess = e.getMessage(); if (mess != null) { String javaLang = "java.lang."; if (mess.indexOf(javaLang) == 0) { mess = mess.substring(javaLang.length()); } String rxString = "RuntimeException: "; if (mess.indexOf(rxString) == 0) { mess = mess.substring(rxString.length()); } statusError(mess); } // e.printStackTrace(); } /** * Show a notice message in the editor status bar. */ public void statusNotice(String msg) { status.notice(msg); } /** * Clear the status area. */ public void statusEmpty() { statusNotice(EMPTY); } /** * Returns the edit popup menu. */ class TextAreaPopup extends JPopupMenu { //String currentDir = System.getProperty("user.dir"); String referenceFile = null; JMenuItem cutItem; JMenuItem copyItem; JMenuItem discourseItem; JMenuItem referenceItem; public TextAreaPopup() { JMenuItem item; cutItem = new JMenuItem("Cut"); cutItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCut(); } }); this.add(cutItem); copyItem = new JMenuItem("Copy"); copyItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCopy(); } }); this.add(copyItem); discourseItem = new JMenuItem("Copy for Forum"); discourseItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleDiscourseCopy(); } }); this.add(discourseItem); discourseItem = new JMenuItem("Copy as HTML"); discourseItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleHTMLCopy(); } }); this.add(discourseItem); item = new JMenuItem("Paste"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePaste(); } }); this.add(item); item = new JMenuItem("Select All"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSelectAll(); } }); this.add(item); this.addSeparator(); item = new JMenuItem("Comment/Uncomment"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCommentUncomment(); } }); this.add(item); item = new JMenuItem("Increase Indent"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleIndentOutdent(true); } }); this.add(item); item = new JMenuItem("Decrease Indent"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleIndentOutdent(false); } }); this.add(item); this.addSeparator(); referenceItem = new JMenuItem("Find in Reference"); referenceItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleFindReference(); } }); this.add(referenceItem); } // if no text is selected, disable copy and cut menu items public void show(Component component, int x, int y) { if (textarea.isSelectionActive()) { cutItem.setEnabled(true); copyItem.setEnabled(true); discourseItem.setEnabled(true); String sel = textarea.getSelectedText().trim(); referenceFile = PdeKeywords.getReference(sel); referenceItem.setEnabled(referenceFile != null); } else { cutItem.setEnabled(false); copyItem.setEnabled(false); discourseItem.setEnabled(false); referenceItem.setEnabled(false); } super.show(component, x, y); } } }
package tools.vitruv.testutils; import java.util.ArrayList; import java.util.Collection; import java.util.Random; import org.apache.log4j.Logger; import org.eclipse.emf.common.util.URI; import tools.vitruv.framework.change.interaction.ConfirmationUserInput; import tools.vitruv.framework.change.interaction.FreeTextUserInput; import tools.vitruv.framework.change.interaction.InteractionFactory; import tools.vitruv.framework.change.interaction.MultipleChoiceMultiSelectionUserInput; import tools.vitruv.framework.change.interaction.MultipleChoiceSingleSelectionUserInput; import tools.vitruv.framework.change.interaction.UserInputBase; import tools.vitruv.framework.userinteraction.NotificationDialogBuilder; import tools.vitruv.framework.userinteraction.impl.NormalUserInteractor; import tools.vitruv.framework.userinteraction.impl.PredefinedInputInteractor; public class TestUserInteractor extends PredefinedInputInteractor { private static final Logger logger = Logger.getLogger(TestUserInteractor.class); private final Random random; private final int minWaittime; private final int maxWaittime; private final int waitTimeRange; public TestUserInteractor(final int minWaittime, final int maxWaittime) { super(new ArrayList<UserInputBase>(), null); if (minWaittime > maxWaittime) { throw new RuntimeException( "Configure min and max waittime properly: Min" + minWaittime + " Max: " + maxWaittime); } this.minWaittime = minWaittime; this.maxWaittime = maxWaittime; this.waitTimeRange = maxWaittime - minWaittime; this.random = new Random(); } public TestUserInteractor() { this(-1, -1); } @Override public <T> T handleNothingPredefined(NormalUserInteractor<T> dialogBuilder) { throw new IllegalStateException("Missing predefined input"); // TODO DK: somehow parameterize the exception with the type of input missing? } public void addNextConfirmationInput(final boolean nextConfirmation) { Collection<UserInputBase> userInputs = getUserInputs(); //userInputs.removeIf(input -> input.getClass() == ConfirmationUserInput.class); // TODO DK ConfirmationUserInput input = InteractionFactory.eINSTANCE.createConfirmationUserInput(); input.setConfirmed(nextConfirmation); userInputs.add(input); } public void addNextTextInput(String nextInput) { Collection<UserInputBase> userInputs = getUserInputs(); FreeTextUserInput input = InteractionFactory.eINSTANCE.createFreeTextUserInput(); input.setText(nextInput); userInputs.add(input); } public void addNextSingleSelection(final int nextSelection) { Collection<UserInputBase> userInputs = getUserInputs(); //userInputs.removeIf(input -> input.getClass() == MultipleChoiceSingleSelectionUserInput.class); MultipleChoiceSingleSelectionUserInput input = InteractionFactory.eINSTANCE.createMultipleChoiceSingleSelectionUserInput(); input.setSelectedIndex(nextSelection); userInputs.add(input); } public void addNextMultiSelection(final int[] nextSelection) { Collection<UserInputBase> userInputs = getUserInputs(); //userInputs.removeIf(input -> input.getClass() == MultipleChoiceSingleSelectionUserInput.class); MultipleChoiceMultiSelectionUserInput input = InteractionFactory.eINSTANCE.createMultipleChoiceMultiSelectionUserInput(); for (int selection : nextSelection) { input.getSelectedIndices().add(selection); } userInputs.add(input); } public void addNextUriSelection(final URI nextSelection) { /*this.uriQueue.clear(); this.uriQueue.addAll(Arrays.asList(nextSelections));*/ // TODO DK } private void simulateUserThinktime() { // TODO DK if (-1 < this.maxWaittime) { final int currentWaittime = this.random.nextInt(this.waitTimeRange + 1) + this.minWaittime; try { Thread.sleep(currentWaittime); } catch (final InterruptedException e) { logger.trace("User think time simulation thread interrupted: " + e, e); } } } @Override public NotificationDialogBuilder getNotificationDialogBuilder() { simulateUserThinktime(); // TODO DK: necessary? return super.getNotificationDialogBuilder(); } }
package co.cask.cdc.plugins.source.sqlserver; import co.cask.cdap.api.data.format.StructuredRecord; import co.cask.cdap.api.data.schema.Schema; import co.cask.hydrator.plugin.DBUtils; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import scala.Serializable; import scala.runtime.AbstractFunction1; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * A serializable class to allow invoking {@link scala.Function1} from Java. The function converts {@link ResultSet} * to {@link StructuredRecord} for dml records */ public class ResultSetToDMLRecord extends AbstractFunction1<ResultSet, StructuredRecord> implements Serializable { private static final Schema.Field TABLE_SCHEMA_FIELD = Schema.Field.of("table", Schema.of(Schema.Type.STRING)); private static final Schema.Field PRIMARY_KEYS_SCHEMA_FIELD = Schema.Field.of("primary_keys", Schema.arrayOf(Schema.of(Schema.Type.STRING))); private static final Schema.Field OP_TYPE_SCHEMA_FIELD = Schema.Field.of("op_type", Schema.of(Schema.Type.STRING)); private static final int CHANGE_TABLE_COLUMNS_SIZE = 3; private final TableInformation tableInformation; static final String RECORD_NAME = "DMLRecord"; ResultSetToDMLRecord(TableInformation tableInformation) { this.tableInformation = tableInformation; } public StructuredRecord apply(ResultSet row) { try { return resultSetToStructureRecord(row); } catch (SQLException e) { throw new RuntimeException(e); } } private StructuredRecord resultSetToStructureRecord(ResultSet resultSet) throws SQLException { Schema changeSchema = getChangeSchema(resultSet); Schema dmlSchema = getDMLSchema(changeSchema); StructuredRecord.Builder recordBuilder = StructuredRecord.builder(dmlSchema); recordBuilder.set(TABLE_SCHEMA_FIELD.getName(), Joiner.on(".").join(tableInformation.getSchemaName(), tableInformation.getName())); recordBuilder.set(PRIMARY_KEYS_SCHEMA_FIELD.getName(), Lists.newArrayList(tableInformation.getPrimaryKeys())); recordBuilder.set(OP_TYPE_SCHEMA_FIELD.getName(), resultSet.getString("SYS_CHANGE_OPERATION")); return getChangeData(resultSet, changeSchema, recordBuilder); } private StructuredRecord getChangeData(ResultSet resultSet, Schema changeSchema, StructuredRecord.Builder recordBuilder) throws SQLException { StructuredRecord.Builder changeRecordBuilder = StructuredRecord.builder(changeSchema); ResultSetMetaData metadata = resultSet.getMetaData(); for (int i = 0; i < changeSchema.getFields().size(); i++) { int sqlColumnType = metadata.getColumnType(i + CHANGE_TABLE_COLUMNS_SIZE); int sqlPrecision = metadata.getPrecision(i + CHANGE_TABLE_COLUMNS_SIZE); int sqlScale = metadata.getScale(i + CHANGE_TABLE_COLUMNS_SIZE); Schema.Field field = changeSchema.getFields().get(i); changeRecordBuilder.set(field.getName(), DBUtils.transformValue(sqlColumnType, sqlPrecision, sqlScale, resultSet, field.getName())); } StructuredRecord changeRecord = changeRecordBuilder.build(); recordBuilder.set("change", changeRecord); return recordBuilder.build(); } private Schema getDMLSchema(Schema changeSchema) { List<Schema.Field> schemaFields = new ArrayList<>(); schemaFields.add(TABLE_SCHEMA_FIELD); schemaFields.add(PRIMARY_KEYS_SCHEMA_FIELD); schemaFields.add(OP_TYPE_SCHEMA_FIELD); schemaFields.add(Schema.Field.of("change", changeSchema)); return Schema.recordOf(RECORD_NAME, schemaFields); } private Schema getChangeSchema(ResultSet resultSet) throws SQLException { List<Schema.Field> schemaFields = DBUtils.getSchemaFields(resultSet); // drop first three columns as they are from change tracking tables and does not represent the change data return Schema.recordOf("rec", schemaFields.subList(CHANGE_TABLE_COLUMNS_SIZE, schemaFields.size())); } }
package com.demonwav.mcdev.buildsystem.gradle; import com.demonwav.mcdev.buildsystem.BuildSystem; import com.demonwav.mcdev.platform.AbstractModuleType; import com.demonwav.mcdev.platform.MinecraftModule; import com.demonwav.mcdev.platform.MinecraftModuleType; import com.demonwav.mcdev.platform.sponge.SpongeModule; import com.demonwav.mcdev.platform.sponge.SpongeModuleType; import com.google.common.base.Strings; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.externalSystem.model.DataNode; import com.intellij.openapi.externalSystem.model.Key; import com.intellij.openapi.externalSystem.model.ProjectKeys; import com.intellij.openapi.externalSystem.model.project.LibraryDependencyData; import com.intellij.openapi.externalSystem.model.project.ProjectData; import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider; import com.intellij.openapi.externalSystem.service.project.manage.AbstractProjectDataService; import com.intellij.openapi.externalSystem.util.ExternalSystemConstants; import com.intellij.openapi.externalSystem.util.Order; import com.intellij.openapi.module.JavaModuleType; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.gradle.util.GradleConstants; import java.util.Collection; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @Order(ExternalSystemConstants.UNORDERED) public abstract class AbstractDataService extends AbstractProjectDataService<LibraryDependencyData, Module> { @NotNull private final AbstractModuleType<?> type; public AbstractDataService(@NotNull final AbstractModuleType type) { this.type = type; } @NotNull @Override public Key<LibraryDependencyData> getTargetDataKey() { return ProjectKeys.LIBRARY_DEPENDENCY; } @Override public void importData(@NotNull Collection<DataNode<LibraryDependencyData>> toImport, @Nullable ProjectData projectData, @NotNull Project project, @NotNull IdeModifiableModelsProvider modelsProvider) { if (projectData == null || !projectData.getOwner().equals(GradleConstants.SYSTEM_ID)) { return; } Set<Module> goodModules = toImport.stream() .filter(n -> n.getData().getExternalName().startsWith(type.getGroupId() + ":" + type.getArtifactId())) .map(n -> modelsProvider.findIdeModule(n.getData().getOwnerModule())) .distinct() .collect(Collectors.toSet()); setupModules(goodModules, modelsProvider, type); } /** * We have two checks for Sponge, so we hold the first one here until the second one finishes. This is so hacky it hurts. */ private static Set<Module> firstGoodModules; public static void setupModules(@NotNull Set<Module> goodModules, @NotNull IdeModifiableModelsProvider modelsProvider, @NotNull AbstractModuleType<?> type) { if (type == SpongeModuleType.getInstance()) { if (firstGoodModules == null) { firstGoodModules = goodModules; return; } goodModules.addAll(firstGoodModules); } // So the way the Gradle plugin sets it up is with 3 modules. There's the parent module, which the Gradle // dependencies don't apply to, then submodules under it, normally main and test, which the Gradle dependencies // do apply to. We're interested (when setting the module type) in the parent, which is what we do here. The // first module should be the parent, but we check to make sure anyways ApplicationManager.getApplication().runReadAction(() -> { Set<Module> checkedModules = new HashSet<>(); Set<Module> badModules = new HashSet<>(); checkedModules.addAll(goodModules); goodModules.stream().forEach(m -> { String[] path = modelsProvider.getModifiableModuleModel().getModuleGroupPath(m); if (path == null) { // Always reset back to JavaModule m.setOption("type", JavaModuleType.getModuleType().getId()); checkedModules.add(m); MinecraftModuleType.addOption(m, type.getId()); Optional.ofNullable(BuildSystem.getInstance(m)).ifPresent(thisModule -> thisModule.reImport(m)); MinecraftModule.getInstance(m); } else { String parentName = path[0]; Module parentModule = modelsProvider.getModifiableModuleModel().findModuleByName(parentName); if (parentModule != null) { // Always reset back to JavaModule parentModule.setOption("type", JavaModuleType.getModuleType().getId()); badModules.add(m); checkedModules.add(parentModule); MinecraftModuleType.addOption(parentModule, type.getId()); Optional.ofNullable(BuildSystem.getInstance(parentModule)).ifPresent(thisModule -> thisModule.reImport(parentModule)); MinecraftModule.getInstance(parentModule); } } }); // Reset all other modules back to JavaModule && remove the type for (Module module : modelsProvider.getModules()) { if (!checkedModules.contains(module) || badModules.contains(module)) { if (Strings.nullToEmpty(module.getOptionValue("type")).equals(type.getId())) { module.setOption("type", JavaModuleType.getModuleType().getId()); } MinecraftModuleType.removeOption(module, type.getId()); } } }); if (firstGoodModules != null && type == SpongeModuleType.getInstance()) { firstGoodModules = null; } } }
package com.fangxuele.tool.wechat.push.ui.listener; import com.fangxuele.tool.wechat.push.logic.PushData; import com.fangxuele.tool.wechat.push.logic.PushManage; import com.fangxuele.tool.wechat.push.ui.Init; import com.fangxuele.tool.wechat.push.ui.MainWindow; import com.fangxuele.tool.wechat.push.util.DbUtilMySQL; import com.opencsv.CSVReader; import com.xiaoleilu.hutool.io.file.FileReader; import com.xiaoleilu.hutool.log.Log; import com.xiaoleilu.hutool.log.LogFactory; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.bean.result.WxMpUserList; import org.apache.commons.lang3.StringUtils; import javax.swing.JOptionPane; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class MemberListener { private static final Log logger = LogFactory.get(); public static void addListeners() { MainWindow.mainWindow.getImportFromFileButton().addActionListener(e -> new Thread(() -> { File file = new File(MainWindow.mainWindow.getMemberFilePathField().getText()); CSVReader reader = null; FileReader fileReader = null; int currentImported = 0; try { MainWindow.mainWindow.getMemberTabImportProgressBar().setIndeterminate(true); if (file.getName().endsWith(".csv")) { DataInputStream in = new DataInputStream(new FileInputStream(file)); reader = new CSVReader(new InputStreamReader(in, "utf-8")); String[] nextLine; PushData.allUser = Collections.synchronizedList(new ArrayList<>()); while ((nextLine = reader.readNext()) != null) { PushData.allUser.add(nextLine); currentImported++; MainWindow.mainWindow.getMemberTabCountLabel().setText(String.valueOf(currentImported)); MainWindow.mainWindow.getMemberTabImportProgressBar().setValue(currentImported); } } else { fileReader = new FileReader(file); PushData.allUser = Collections.synchronizedList(new ArrayList<>()); BufferedReader br = fileReader.getReader(); String line; while ((line = br.readLine()) != null) { PushData.allUser.add(line.split(",")); currentImported++; MainWindow.mainWindow.getMemberTabCountLabel().setText(String.valueOf(currentImported)); MainWindow.mainWindow.getMemberTabImportProgressBar().setValue(currentImported); } } MainWindow.mainWindow.getMemberTabImportProgressBar().setIndeterminate(false); JOptionPane.showMessageDialog(MainWindow.mainWindow.getMemberPanel(), "", "", JOptionPane.INFORMATION_MESSAGE); Init.configer.setMemberFilePath(MainWindow.mainWindow.getMemberFilePathField().getText()); Init.configer.save(); } catch (Exception e1) { JOptionPane.showMessageDialog(MainWindow.mainWindow.getMemberPanel(), "\n\n" + e1.getMessage(), "", JOptionPane.ERROR_MESSAGE); logger.error(e1); e1.printStackTrace(); } finally { MainWindow.mainWindow.getMemberTabImportProgressBar().setIndeterminate(false); if (reader != null) { try { reader.close(); } catch (IOException e1) { logger.error(e1); e1.printStackTrace(); } } } }).start()); MainWindow.mainWindow.getMemberImportAllButton().addActionListener(e -> new Thread(() -> { try { getMpUserList(); JOptionPane.showMessageDialog(MainWindow.mainWindow.getMemberPanel(), "", "", JOptionPane.INFORMATION_MESSAGE); } catch (WxErrorException e1) { JOptionPane.showMessageDialog(MainWindow.mainWindow.getMemberPanel(), "\n\n" + e1.getMessage(), "", JOptionPane.ERROR_MESSAGE); logger.error(e1); e1.printStackTrace(); } finally { MainWindow.mainWindow.getMemberTabImportProgressBar().setIndeterminate(false); } }).start()); MainWindow.mainWindow.getClearImportButton().addActionListener(e -> { int isClear = JOptionPane.showConfirmDialog(MainWindow.mainWindow.getMemberPanel(), "", "", JOptionPane.INFORMATION_MESSAGE); if (isClear == JOptionPane.YES_OPTION) { if (PushData.allUser != null) { PushData.allUser.clear(); MainWindow.mainWindow.getMemberTabCountLabel().setText("0"); } } }); MainWindow.mainWindow.getImportFromHisButton().addActionListener(e -> new Thread(() -> { File file = new File("data/push_his/" + MainWindow.mainWindow.getMemberHisComboBox().getSelectedItem().toString()); CSVReader reader = null; FileReader fileReader = null; int currentImported = 0; try { MainWindow.mainWindow.getMemberTabImportProgressBar().setIndeterminate(true); DataInputStream in = new DataInputStream(new FileInputStream(file)); reader = new CSVReader(new InputStreamReader(in, "utf-8")); String[] nextLine; PushData.allUser = Collections.synchronizedList(new ArrayList<>()); while ((nextLine = reader.readNext()) != null) { PushData.allUser.add(nextLine); currentImported++; MainWindow.mainWindow.getMemberTabCountLabel().setText(String.valueOf(currentImported)); MainWindow.mainWindow.getMemberTabImportProgressBar().setValue(currentImported); } MainWindow.mainWindow.getMemberTabImportProgressBar().setIndeterminate(false); JOptionPane.showMessageDialog(MainWindow.mainWindow.getMemberPanel(), "", "", JOptionPane.INFORMATION_MESSAGE); } catch (Exception e1) { JOptionPane.showMessageDialog(MainWindow.mainWindow.getMemberPanel(), "\n\n" + e1.getMessage(), "", JOptionPane.ERROR_MESSAGE); logger.error(e1); e1.printStackTrace(); } finally { MainWindow.mainWindow.getMemberTabImportProgressBar().setIndeterminate(false); if (reader != null) { try { reader.close(); } catch (IOException e1) { logger.error(e1); e1.printStackTrace(); } } } }).start()); // sql MainWindow.mainWindow.getImportFromSqlButton().addActionListener(e -> new Thread(() -> { MainWindow.mainWindow.getImportFromSqlButton().setEnabled(false); MainWindow.mainWindow.getImportFromSqlButton().updateUI(); DbUtilMySQL dbUtilMySQL = DbUtilMySQL.getInstance();// SQLServer String querySql = MainWindow.mainWindow.getImportFromSqlTextArea().getText(); MainWindow.mainWindow.getMemberTabImportProgressBar().setIndeterminate(true); if (StringUtils.isNotEmpty(querySql)) { try { ResultSet rs = dbUtilMySQL.executeQuery(querySql); PushData.allUser = Collections.synchronizedList(new ArrayList<>()); int currentImported = 0; while (rs.next()) { PushData.allUser.add(new String[]{rs.getString(1).trim()}); currentImported++; MainWindow.mainWindow.getMemberTabCountLabel().setText(String.valueOf(currentImported)); MainWindow.mainWindow.getMemberTabImportProgressBar().setValue(currentImported); } JOptionPane.showMessageDialog(MainWindow.mainWindow.getMemberPanel(), "", "", JOptionPane.INFORMATION_MESSAGE); Init.configer.setMemberSql(querySql); Init.configer.save(); } catch (Exception e1) { JOptionPane.showMessageDialog(MainWindow.mainWindow.getMemberPanel(), "\n\n" + e1.getMessage(), "", JOptionPane.ERROR_MESSAGE); logger.error(e1); e1.printStackTrace(); } finally { MainWindow.mainWindow.getImportFromSqlButton().setEnabled(true); MainWindow.mainWindow.getImportFromSqlButton().updateUI(); MainWindow.mainWindow.getMemberTabImportProgressBar().setIndeterminate(false); } } }).start()); } public static void getMpUserList() throws WxErrorException { MainWindow.mainWindow.getMemberTabImportProgressBar().setIndeterminate(true); WxMpService wxMpService = PushManage.getWxMpService(); WxMpUserList wxMpUserList = wxMpService.getUserService().userList(null); PushManage.console("" + wxMpUserList.getTotal()); PushManage.console("OPENID" + wxMpUserList.getCount()); MainWindow.mainWindow.getMemberTabImportProgressBar().setIndeterminate(false); MainWindow.mainWindow.getMemberTabImportProgressBar().setMaximum((int) wxMpUserList.getTotal()); int importedCount = 0; List<String> openIds = wxMpUserList.getOpenids(); PushData.allUser = Collections.synchronizedList(new ArrayList<>()); for (String openId : openIds) { PushData.allUser.add(new String[]{openId}); } importedCount += wxMpUserList.getCount(); MainWindow.mainWindow.getMemberTabCountLabel().setText(String.valueOf(importedCount)); MainWindow.mainWindow.getMemberTabImportProgressBar().setValue(importedCount); while (StringUtils.isNotEmpty(wxMpUserList.getNextOpenid())) { wxMpUserList = wxMpService.getUserService().userList(wxMpUserList.getNextOpenid()); PushManage.console("OPENID" + wxMpUserList.getCount()); if (wxMpUserList.getCount() == 0) { break; } openIds = wxMpUserList.getOpenids(); for (String openId : openIds) { PushData.allUser.add(new String[]{openId}); } importedCount += wxMpUserList.getCount(); MainWindow.mainWindow.getMemberTabCountLabel().setText(String.valueOf(importedCount)); MainWindow.mainWindow.getMemberTabImportProgressBar().setValue(importedCount); } MainWindow.mainWindow.getMemberTabImportProgressBar().setValue((int) wxMpUserList.getTotal()); } }
package com.fasterxml.jackson.databind.deser.impl; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.*; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.deser.SettableBeanProperty; import com.fasterxml.jackson.databind.util.NameTransformer; /** * Helper class used for storing mapping from property name to * {@link SettableBeanProperty} instances. *<p> * Note that this class is used instead of generic {@link java.util.HashMap} * for bit of performance gain (and some memory savings): although default * implementation is very good for generic use cases, it can be streamlined * a bit for specific use case we have. Even relatively small improvements * matter since this is directly on the critical path during deserialization, * as it is done for each and every POJO property deserialized. */ public abstract class BeanPropertyMap implements Iterable<SettableBeanProperty>, java.io.Serializable { private static final long serialVersionUID = 2L; /** * @since 2.5 */ protected final boolean _caseInsensitive; protected BeanPropertyMap(boolean caseInsensitive) { _caseInsensitive = caseInsensitive; } /** * @since 2.6 */ public static BeanPropertyMap construct(Collection<SettableBeanProperty> props, boolean caseInsensitive) { if (props.isEmpty()) { return new Small(caseInsensitive); } Iterator<SettableBeanProperty> it = props.iterator(); switch (props.size()) { case 1: return new Small(caseInsensitive, it.next()); case 2: return new Small(caseInsensitive, it.next(), it.next()); case 3: return new Small(caseInsensitive, it.next(), it.next(), it.next()); } return new Default(caseInsensitive, props); } /** * Fluent copy method that creates a new instance that is a copy * of this instance except for one additional property that is * passed as the argument. * Note that method does not modify this instance but constructs * and returns a new one. * * @since 2.0 */ public abstract BeanPropertyMap withProperty(SettableBeanProperty newProperty); public abstract BeanPropertyMap assignIndexes(); /** * Factory method for constructing a map where all entries use given * prefix */ public BeanPropertyMap renameAll(NameTransformer transformer) { if (transformer == null || (transformer == NameTransformer.NOP)) { return this; } Iterator<SettableBeanProperty> it = iterator(); ArrayList<SettableBeanProperty> newProps = new ArrayList<SettableBeanProperty>(); while (it.hasNext()) { SettableBeanProperty prop = it.next(); String newName = transformer.transform(prop.getName()); prop = prop.withSimpleName(newName); JsonDeserializer<?> deser = prop.getValueDeserializer(); if (deser != null) { @SuppressWarnings("unchecked") JsonDeserializer<Object> newDeser = (JsonDeserializer<Object>) deser.unwrappingDeserializer(transformer); if (newDeser != deser) { prop = prop.withValueDeserializer(newDeser); } } newProps.add(prop); } // should we try to re-index? Ordering probably changed but called probably doesn't want changes... return construct(newProps, _caseInsensitive); } // Confining this case insensitivity to this function (and the find method) in case we want to // apply a particular locale to the lower case function. For now, using the default. protected final String getPropertyName(SettableBeanProperty prop) { return _caseInsensitive ? prop.getName().toLowerCase() : prop.getName(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Properties=["); int count = 0; Iterator<SettableBeanProperty> it = iterator(); while (it.hasNext()) { SettableBeanProperty prop = it.next(); if (count++ > 0) { sb.append(", "); } sb.append(prop.getName()); sb.append('('); sb.append(prop.getType()); sb.append(')'); } sb.append(']'); return sb.toString(); } /** * Accessor for traversing over all contained properties. */ @Override public abstract Iterator<SettableBeanProperty> iterator(); /** * Method that will re-create initial insertion-ordering of * properties contained in this map. Note that if properties * have been removed, array may contain nulls; otherwise * it should be consecutive. * * @since 2.1 */ public abstract SettableBeanProperty[] getPropertiesInInsertionOrder(); public abstract int size(); public abstract SettableBeanProperty find(String key); /** * Convenience method that tries to find property with given name, and * if it is found, call {@link SettableBeanProperty#deserializeAndSet} * on it, and return true; or, if not found, return false. * Note, too, that if deserialization is attempted, possible exceptions * are wrapped if and as necessary, so caller need not handle those. * * @since 2.5 */ public abstract boolean findDeserializeAndSet(JsonParser p, DeserializationContext ctxt, Object bean, String key) throws IOException; /** * @since 2.3 */ public abstract SettableBeanProperty find(int propertyIndex); /** * Specialized method that can be used to replace an existing entry * (note: entry MUST exist; otherwise exception is thrown) with * specified replacement. */ public void replace(SettableBeanProperty property) { throw new NoSuchElementException("No entry '"+property.getName()+"' found, can't replace"); } /** * Specialized method for removing specified existing entry. * NOTE: entry MUST exist, otherwise an exception is thrown. */ public void remove(SettableBeanProperty property) { throw new NoSuchElementException("No entry '"+property.getName()+"' found, can't remove"); } /** * @since 2.5 */ protected void wrapAndThrow(Throwable t, Object bean, String fieldName, DeserializationContext ctxt) throws IOException { // inlined 'throwOrReturnThrowable' while (t instanceof InvocationTargetException && t.getCause() != null) { t = t.getCause(); } // Errors to be passed as is if (t instanceof Error) { throw (Error) t; } // StackOverflowErrors are tricky ones; need to be careful... boolean wrap = (ctxt == null) || ctxt.isEnabled(DeserializationFeature.WRAP_EXCEPTIONS); // Ditto for IOExceptions; except we may want to wrap JSON exceptions if (t instanceof IOException) { if (!wrap || !(t instanceof JsonProcessingException)) { throw (IOException) t; } } else if (!wrap) { // [JACKSON-407] -- allow disabling wrapping for unchecked exceptions if (t instanceof RuntimeException) { throw (RuntimeException) t; } } throw JsonMappingException.wrapWithPath(t, bean, fieldName); } /** * Note on implementation: can not make most fields final because of 'remove' * operation. */ protected static class Small extends BeanPropertyMap { private static final long serialVersionUID = 1L; protected String key1, key2, key3; protected SettableBeanProperty prop1, prop2, prop3; protected int size; public Small(boolean caseInsensitive) { super(caseInsensitive); size = 0; key1 = key2 = key3 = null; prop1 = prop2 = prop3 = null; } public Small(boolean caseInsensitive, SettableBeanProperty p1) { super(caseInsensitive); size = 1; key1 = p1.getName(); prop1 = p1; key2 = key3 = null; prop2 = prop3 = null; } public Small(boolean caseInsensitive, SettableBeanProperty p1, SettableBeanProperty p2) { super(caseInsensitive); size = 2; key1 = p1.getName(); prop1 = p1; key2 = p2.getName(); prop2 = p2; key3 = null; prop3 = null; } public Small(boolean caseInsensitive, SettableBeanProperty p1, SettableBeanProperty p2, SettableBeanProperty p3) { super(caseInsensitive); size = 3; key1 = p1.getName(); prop1 = p1; key2 = p2.getName(); prop2 = p2; key3 = p3.getName(); prop3 = p3; } @Override public BeanPropertyMap withProperty(SettableBeanProperty prop) { final String key = prop.getName(); // First: replace existing one? switch (size) { case 3: if (key.equals(key3)) { prop3 = prop; return this; } case 2: if (key.equals(key2)) { prop2 = prop; return this; } case 1: if (key.equals(key1)) { prop1 = prop; return this; } } // If not, append. Easy if we aren't yet full switch (size) { case 2: return new Small(_caseInsensitive, prop1, prop2, prop); case 1: return new Small(_caseInsensitive, prop1, prop); case 0: return new Small(_caseInsensitive, prop); } // But if we have all 3, "upgrade" prop.assignIndex(3); List<SettableBeanProperty> props = new ArrayList<SettableBeanProperty>(4); props.add(prop1); props.add(prop2); props.add(prop3); props.add(prop); return new Default(_caseInsensitive, props); } @Override public BeanPropertyMap assignIndexes() { int ix = 0; if (prop1 != null) { prop1.assignIndex(ix++); } if (prop2 != null) { prop2.assignIndex(ix++); } if (prop3 != null) { prop3.assignIndex(ix++); } return this; } @Override public Iterator<SettableBeanProperty> iterator() { if (size == 0) { return Collections.<SettableBeanProperty>emptyList().iterator(); } if (size == 1) { return Collections.singleton(prop1).iterator(); } ArrayList<SettableBeanProperty> list = new ArrayList<SettableBeanProperty>(); list.add(prop1); list.add(prop2); if (size > 2) { list.add(prop3); } return list.iterator(); } @Override public SettableBeanProperty[] getPropertiesInInsertionOrder() { SettableBeanProperty[] props = new SettableBeanProperty[size]; switch (size) { case 3: props[2] = prop3; case 2: props[1] = prop2; case 1: props[0] = prop1; } return props; } @Override public int size() { return size; } @Override public SettableBeanProperty find(String key) { if (key == key1) return prop1; if (key == key2) return prop2; if (key == key3) return prop3; return _findWithEquals(key); } private SettableBeanProperty _findWithEquals(String key) { if (key.equals(key1)) return prop1; if (key.equals(key2)) return prop2; if (key.equals(key3)) return prop3; return null; } @Override public boolean findDeserializeAndSet(JsonParser p, DeserializationContext ctxt, Object bean, String key) throws IOException { if (_caseInsensitive) { key = key.toLowerCase(); } SettableBeanProperty prop = find(key); if (prop != null) { try { prop.deserializeAndSet(p, ctxt, bean); } catch (Exception e) { wrapAndThrow(e, bean, key, ctxt); } return true; } return false; } @Override public SettableBeanProperty find(int index) { switch (size) { case 3: if (prop3.getPropertyIndex() == index) return prop3; case 2: if (prop2.getPropertyIndex() == index) return prop2; case 1: if (prop1.getPropertyIndex() == index) return prop1; } return null; } @Override public void replace(SettableBeanProperty prop) { final String key = prop.getName(); switch (size) { case 3: if (key.equals(key3)) { prop3 = prop; return; } case 2: if (key.equals(key2)) { prop2 = prop; return; } case 1: if (key.equals(key1)) { prop1 = prop; return; } } super.replace(prop); } @Override public void remove(SettableBeanProperty prop) { final String key = prop.getName(); switch (size) { case 3: if (key.equals(key3)) { prop3 = null; key3 = null; size = 2; return; } case 2: if (key.equals(key2)) { prop2 = prop3; key2 = key3; --size; return; } case 1: if (key.equals(key1)) { prop1 = prop2; key1 = key2; prop2 = prop3; key2 = key3; --size; return; } } super.remove(prop); } } /** * For non-trivial number of properties let's use a hash map. * Alas, can not use {@link com.fasterxml.jackson.databind.util.CompactStringObjectMap} * as is (need to add index), but structure is similar. */ protected final static class Default extends BeanPropertyMap { private static final long serialVersionUID = 1L; private int _hashMask, _size, _spillCount; private String[] _keys; /** * Hash area for properties, sparsely populated. Starts with the primary * hash (size of {@link #_size}), followed by secondary (with half the size * of primary), and with optional variable size spillover. */ private SettableBeanProperty[] _propsHash; /** * Array of properties in the exact order they were handed in. This is * used by as-array serialization, deserialization. */ private SettableBeanProperty[] _propsInOrder; /** * Counter we use to keep track of insertion order of properties * (to be able to recreate insertion order when needed). *<p> * Note: is kept up-to-date with additions, but can NOT handle * removals (i.e. "holes" may be left) */ protected int _nextBucketIndex = 0; public Default(boolean caseInsensitive, Collection<SettableBeanProperty> props) { super(caseInsensitive); _propsInOrder = props.toArray(new SettableBeanProperty[props.size()]); init(props); } protected void init(Collection<SettableBeanProperty> props) { _size = props.size(); // First: calculate size of primary hash area final int size = findSize(_size); _hashMask = size-1; // and allocate enough to contain primary/secondary, expand for spillovers as need be int alloc = size + (size>>1); String[] keys = new String[alloc]; SettableBeanProperty[] fieldHash = new SettableBeanProperty[alloc]; int spills = 0; for (SettableBeanProperty prop : props) { String key = getPropertyName(prop); int slot = key.hashCode() & _hashMask; // primary slot not free? if (keys[slot] != null) { // secondary? slot = size + (slot >> 1); if (keys[slot] != null) { // ok, spill over. slot = size + (size >> 1) + spills; ++spills; if (slot >= keys.length) { keys = Arrays.copyOf(keys, keys.length + 4); fieldHash = Arrays.copyOf(fieldHash, fieldHash.length + 4); } } } keys[slot] = key; fieldHash[slot] = prop; } _keys = keys; _propsHash = fieldHash; _spillCount = spills; } private final static int findSize(int size) { if (size <= 5) { return 8; } if (size <= 12) { return 16; } int needed = size + (size >> 2); // at most 80% full int result = 32; while (result < needed) { result += result; } return result; } @Override public BeanPropertyMap withProperty(SettableBeanProperty newProp) { // First: may be able to just replace? String key = getPropertyName(newProp); for (int i = 0, end = _propsHash.length; i < end; ++i) { SettableBeanProperty prop = _propsHash[i]; if ((prop != null) && prop.getName().equals(key)) { _propsHash[i] = newProp; return this; } } // If not, re-create List<SettableBeanProperty> props = properties(); props.add(newProp); init(props); ++_nextBucketIndex; // should we just create a new one? Or is resetting ok? return this; } @Override public BeanPropertyMap assignIndexes() { // order is arbitrary, but stable: int index = 0; for (SettableBeanProperty prop : _propsHash) { if (prop != null) { prop.assignIndex(index++); } } _nextBucketIndex = index; return this; } @Override public int size() { return _size; } @Override public void remove(SettableBeanProperty propToRm) { ArrayList<SettableBeanProperty> props = new ArrayList<SettableBeanProperty>(_size); String key = getPropertyName(propToRm); boolean found = false; for (SettableBeanProperty prop : _propsHash) { if (prop == null) { continue; } if (!found) { found = key.equals(prop.getName()); if (found) { // need to leave a hole here _propsInOrder[_findFromOrdered(prop)] = null; continue; } } props.add(prop); } if (found) { init(props); return; } super.remove(propToRm); } @Override public void replace(SettableBeanProperty newProp) { String key = getPropertyName(newProp); for (int i = 0, end = _propsHash.length; i < end; ++i) { SettableBeanProperty prop = _propsHash[i]; if ((prop != null) && prop.getName().equals(key)) { _propsHash[i] = newProp; // also, replace in in-order _propsInOrder[_findFromOrdered(prop)] = newProp; return; } } super.replace(newProp); } private List<SettableBeanProperty> properties() { ArrayList<SettableBeanProperty> p = new ArrayList<SettableBeanProperty>(_nextBucketIndex); for (SettableBeanProperty prop : _propsHash) { if (prop != null) { p.add(prop); } } return p; } @Override public Iterator<SettableBeanProperty> iterator() { return properties().iterator(); } @Override public SettableBeanProperty[] getPropertiesInInsertionOrder() { return _propsInOrder; } @Override public SettableBeanProperty find(int index) { for (SettableBeanProperty prop : _propsHash) { if ((prop != null) && (index == prop.getPropertyIndex())) { return prop; } } return null; } @Override public SettableBeanProperty find(String key) { if (key == null) { throw new IllegalArgumentException("Can not pass null property name"); } if (_caseInsensitive) { key = key.toLowerCase(); } int slot = key.hashCode() & _hashMask; String match = _keys[slot]; if ((match == key) || key.equals(match)) { return _propsHash[slot]; } if (match == null) { return null; } // no? secondary? slot = (_hashMask+1) + (slot>>1); match = _keys[slot]; if (key.equals(match)) { return _propsHash[slot]; } // or spill? return _findFromSpill(key); } @Override public boolean findDeserializeAndSet(JsonParser p, DeserializationContext ctxt, Object bean, String key) throws IOException { final SettableBeanProperty prop = find(key); if (prop == null) { return false; } try { prop.deserializeAndSet(p, ctxt, bean); } catch (Exception e) { wrapAndThrow(e, bean, key, ctxt); } return true; } private SettableBeanProperty _findFromSpill(String key) { int hashSize = _hashMask+1; int i = hashSize + (hashSize>>1); for (int end = i + _spillCount; i < end; ++i) { if (key.equals(_keys[i])) { return _propsHash[1]; } } return null; } private int _findFromOrdered(SettableBeanProperty prop) { for (int i = 0, end = _propsInOrder.length; i < end; ++i) { if (_propsInOrder[i] == prop) { return i; } } throw new IllegalStateException("Illegal state: property '"+prop.getName()+"' missing from _propsInOrder"); } } }
package com.amplitude.api; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import com.squareup.okhttp.FormEncodingBuilder; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import android.text.TextUtils; import android.util.Log; import android.util.Pair; public class AmplitudeClient { public static final String TAG = "com.amplitude.api.AmplitudeClient"; public static final String START_SESSION_EVENT = "session_start"; public static final String END_SESSION_EVENT = "session_end"; public static final String REVENUE_EVENT = "revenue_amount"; protected static AmplitudeClient instance = new AmplitudeClient(); public static AmplitudeClient getInstance() { return instance; } protected Context context; protected String apiKey; protected String userId; protected String deviceId; private boolean newDeviceIdPerInstall = false; private boolean useAdvertisingIdForDeviceId = false; private boolean initialized = false; private boolean optOut = false; private boolean offline = false; private DeviceInfo deviceInfo; /* VisibleForTesting */ JSONObject userProperties; private long sessionId = -1; private int eventUploadThreshold = Constants.EVENT_UPLOAD_THRESHOLD; private int eventUploadMaxBatchSize = Constants.EVENT_UPLOAD_MAX_BATCH_SIZE; private int eventMaxCount = Constants.EVENT_MAX_COUNT; private long eventUploadPeriodMillis = Constants.EVENT_UPLOAD_PERIOD_MILLIS; private long minTimeBetweenSessionsMillis = Constants.MIN_TIME_BETWEEN_SESSIONS_MILLIS; private long sessionTimeoutMillis = Constants.SESSION_TIMEOUT_MILLIS; private boolean backoffUpload = false; private int backoffUploadBatchSize = eventUploadMaxBatchSize; private boolean usingAccurateTracking = false; private boolean trackingSessionEvents = false; private boolean inPauseState = false; private Runnable endSessionRunnable; private AtomicBoolean updateScheduled = new AtomicBoolean(false); private AtomicBoolean uploadingCurrently = new AtomicBoolean(false); // Let test classes have access to these properties. Throwable lastError; String url = Constants.EVENT_LOG_URL; WorkerThread logThread = new WorkerThread("logThread"); WorkerThread httpThread = new WorkerThread("httpThread"); public AmplitudeClient() { logThread.start(); httpThread.start(); } public void initialize(Context context, String apiKey) { initialize(context, apiKey, null); } public synchronized void initialize(Context context, String apiKey, String userId) { if (context == null) { Log.e(TAG, "Argument context cannot be null in initialize()"); return; } AmplitudeClient.upgradePrefs(context); if (TextUtils.isEmpty(apiKey)) { Log.e(TAG, "Argument apiKey cannot be null or blank in initialize()"); return; } if (!initialized) { this.context = context.getApplicationContext(); this.apiKey = apiKey; initializeDeviceInfo(); SharedPreferences preferences = context.getSharedPreferences( getSharedPreferencesName(), Context.MODE_PRIVATE); if (userId != null) { this.userId = userId; preferences.edit().putString(Constants.PREFKEY_USER_ID, userId).commit(); } else { this.userId = preferences.getString(Constants.PREFKEY_USER_ID, null); } this.optOut = preferences.getBoolean(Constants.PREFKEY_OPT_OUT, false); initialized = true; } } private void initializeDeviceInfo() { deviceInfo = new DeviceInfo(context); runOnLogThread(new Runnable() { @Override public void run() { deviceId = initializeDeviceId(); deviceInfo.prefetch(); } }); } public void enableNewDeviceIdPerInstall(boolean newDeviceIdPerInstall) { this.newDeviceIdPerInstall = newDeviceIdPerInstall; } public void useAdvertisingIdForDeviceId() { this.useAdvertisingIdForDeviceId = true; } public void enableLocationListening() { if (deviceInfo == null) { throw new IllegalStateException( "Must initialize before acting on location listening."); } deviceInfo.setLocationListening(true); } public void disableLocationListening() { if (deviceInfo == null) { throw new IllegalStateException( "Must initialize before acting on location listening."); } deviceInfo.setLocationListening(false); } public void setEventUploadThreshold(int eventUploadThreshold) { this.eventUploadThreshold = eventUploadThreshold; } public void setEventUploadMaxBatchSize(int eventUploadMaxBatchSize) { this.eventUploadMaxBatchSize = eventUploadMaxBatchSize; this.backoffUploadBatchSize = eventUploadMaxBatchSize; } public void setEventMaxCount(int eventMaxCount) { this.eventMaxCount = eventMaxCount; } public void setEventUploadPeriodMillis(int eventUploadPeriodMillis) { this.eventUploadPeriodMillis = eventUploadPeriodMillis; } public void setMinTimeBetweenSessionsMillis(int minTimeBetweenSessionsMillis) { this.minTimeBetweenSessionsMillis = minTimeBetweenSessionsMillis; } public void setSessionTimeoutMillis(long sessionTimeoutMillis) { this.sessionTimeoutMillis = sessionTimeoutMillis; } public void setOptOut(boolean optOut) { this.optOut = optOut; SharedPreferences preferences = context.getSharedPreferences( getSharedPreferencesName(), Context.MODE_PRIVATE); preferences.edit().putBoolean(Constants.PREFKEY_OPT_OUT, optOut).commit(); } public void setOffline(boolean offline) { this.offline = offline; // Try to update to the server once offline mode is disabled. if (!offline) { uploadEvents(); } } public void trackSessionEvents(boolean trackingSessionEvents) { this.trackingSessionEvents = trackingSessionEvents; } public void logEvent(String eventType) { logEvent(eventType, null); } public void logEvent(String eventType, JSONObject eventProperties) { if (validateLogEvent(eventType)) { boolean checkSession = !usingAccurateTracking; logEventAsync(eventType, eventProperties, null, System.currentTimeMillis(), checkSession); } } public void logEventSync(String eventType, JSONObject eventProperties) { if (validateLogEvent(eventType)) { boolean checkSession = !usingAccurateTracking; logEvent(eventType, eventProperties, null, System.currentTimeMillis(), checkSession); } } protected boolean validateLogEvent(String eventType) { if (TextUtils.isEmpty(eventType)) { Log.e(TAG, "Argument eventType cannot be null or blank in logEvent()"); return false; } if (!contextAndApiKeySet("logEvent()")) { return false; } return true; } protected void logEventAsync(final String eventType, JSONObject eventProperties, final JSONObject apiProperties, final long timestamp, final boolean checkSession) { // Clone the incoming eventProperties object before sending over // to the log thread. Helps avoid ConcurrentModificationException // if the caller starts mutating the object they passed in. // Only does a shallow copy, so it's still possible, though unlikely, // to hit concurrent access if the caller mutates deep in the object. if (eventProperties != null) { eventProperties = cloneJSONObject(eventProperties); } final JSONObject copyEventProperties = eventProperties; runOnLogThread(new Runnable() { @Override public void run() { logEvent(eventType, copyEventProperties, apiProperties, timestamp, checkSession); } }); } protected long logEvent(String eventType, JSONObject eventProperties, JSONObject apiProperties, long timestamp, boolean checkSession) { Log.d(TAG, "Logged event to Amplitude: " + eventType); if (optOut) { return -1; } // corner case: using accurate tracking and log event in between onPause/onResume // inPauseState will indicate if in between onPause/onResume --> need to check session if (checkSession || inPauseState) { startNewSessionIfNeeded(timestamp); } refreshSessionTime(timestamp); JSONObject event = new JSONObject(); try { event.put("event_type", replaceWithJSONNull(eventType)); event.put("timestamp", timestamp); event.put("user_id", (userId == null) ? replaceWithJSONNull(deviceId) : replaceWithJSONNull(userId)); event.put("device_id", replaceWithJSONNull(deviceId)); event.put("session_id", sessionId); event.put("version_name", replaceWithJSONNull(deviceInfo.getVersionName())); event.put("os_name", replaceWithJSONNull(deviceInfo.getOsName())); event.put("os_version", replaceWithJSONNull(deviceInfo.getOsVersion())); event.put("device_brand", replaceWithJSONNull(deviceInfo.getBrand())); event.put("device_manufacturer", replaceWithJSONNull(deviceInfo.getManufacturer())); event.put("device_model", replaceWithJSONNull(deviceInfo.getModel())); event.put("carrier", replaceWithJSONNull(deviceInfo.getCarrier())); event.put("country", replaceWithJSONNull(deviceInfo.getCountry())); event.put("language", replaceWithJSONNull(deviceInfo.getLanguage())); event.put("platform", Constants.PLATFORM); JSONObject library = new JSONObject(); library.put("name", Constants.LIBRARY); library.put("version", Constants.VERSION); event.put("library", library); apiProperties = (apiProperties == null) ? new JSONObject() : apiProperties; Location location = deviceInfo.getMostRecentLocation(); if (location != null) { JSONObject locationJSON = new JSONObject(); locationJSON.put("lat", location.getLatitude()); locationJSON.put("lng", location.getLongitude()); apiProperties.put("location", locationJSON); } if (deviceInfo.getAdvertisingId() != null) { apiProperties.put("androidADID", deviceInfo.getAdvertisingId()); } event.put("api_properties", apiProperties); event.put("event_properties", (eventProperties == null) ? new JSONObject() : eventProperties); event.put("user_properties", (userProperties == null) ? new JSONObject() : userProperties); } catch (JSONException e) { Log.e(TAG, e.toString()); } return saveEvent(event); } protected long saveEvent(JSONObject event) { DatabaseHelper dbHelper = DatabaseHelper.getDatabaseHelper(context); long eventId = dbHelper.addEvent(event.toString()); long eventCount = dbHelper.getEventCount(); if (eventCount >= eventMaxCount) { dbHelper.removeEvents(dbHelper.getNthEventId(Constants.EVENT_REMOVE_BATCH_SIZE)); } if ((eventCount % eventUploadThreshold) == 0 && eventCount >= eventUploadThreshold) { updateServer(); } else { updateServerLater(eventUploadPeriodMillis); } return eventId; } private long getPreviousEventTime() { SharedPreferences preferences = context.getSharedPreferences( getSharedPreferencesName(), Context.MODE_PRIVATE); return preferences.getLong(Constants.PREFKEY_PREVIOUS_SESSION_TIME, -1); } void setPreviousEventTime(long timestamp) { SharedPreferences preferences = context.getSharedPreferences( getSharedPreferencesName(), Context.MODE_PRIVATE); preferences.edit().putLong(Constants.PREFKEY_PREVIOUS_SESSION_TIME, timestamp).commit(); } // private long getPreviousSessionId() { // SharedPreferences preferences = context.getSharedPreferences( // getSharedPreferencesName(), Context.MODE_PRIVATE); // return preferences.getLong(Constants.PREFKEY_PREVIOUS_SESSION_ID, -1); void setPreviousSessionId(long timestamp) { SharedPreferences preferences = context.getSharedPreferences( getSharedPreferencesName(), Context.MODE_PRIVATE); preferences.edit().putLong(Constants.PREFKEY_PREVIOUS_SESSION_ID, timestamp).commit(); } // private void startSession() { // long timestamp = System.currentTimeMillis(); // createOrContinueSession(timestamp); // private void createOrContinueSession(long timestamp) { // if (!startNewSessionIfNeeded(timestamp)) { // // not creating a session means we should continue the session // refreshSessionTime(timestamp); private boolean startNewSessionIfNeeded(long timestamp) { if (!inSession() || sessionExpired(timestamp)) { // end previous session if (trackingSessionEvents) { sendSessionEvent(END_SESSION_EVENT); } // start new session setSessionId(timestamp); refreshSessionTime(timestamp); if (trackingSessionEvents) { sendSessionEvent(START_SESSION_EVENT); } return true; } return false; } private boolean inSession() { return sessionId >= 0; } private boolean sessionExpired(long timestamp) { if (!inSession()) { return false; } long lastEventTime = getPreviousEventTime(); long sessionLimit = usingAccurateTracking ? minTimeBetweenSessionsMillis : sessionTimeoutMillis; return (timestamp - lastEventTime) > sessionLimit; } private void setSessionId(long timestamp) { sessionId = timestamp; setPreviousSessionId(timestamp); } private void refreshSessionTime(long timestamp) { if (!inSession()) { return; } setPreviousEventTime(timestamp); } private void sendSessionEvent(final String session_event) { if (!contextAndApiKeySet(String.format("sendSessionEvent('%s')", session_event))) { return; } final long timestamp = getPreviousEventTime(); runOnLogThread(new Runnable() { @Override public void run() { JSONObject apiProperties = new JSONObject(); try { apiProperties.put("special", session_event); } catch (JSONException e) { return; } logEvent(session_event, null, apiProperties, timestamp, false); } }); } public void logRevenue(double amount) { // Amount is in dollars // ex. $3.99 would be pass as logRevenue(3.99) logRevenue(null, 1, amount); } public void logRevenue(String productId, int quantity, double price) { logRevenue(productId, quantity, price, null, null); } public void logRevenue(String productId, int quantity, double price, String receipt, String receiptSignature) { if (!contextAndApiKeySet("logRevenue()")) { return; } // Log revenue in events JSONObject apiProperties = new JSONObject(); try { apiProperties.put("special", REVENUE_EVENT); apiProperties.put("productId", productId); apiProperties.put("quantity", quantity); apiProperties.put("price", price); apiProperties.put("receipt", receipt); apiProperties.put("receiptSig", receiptSignature); } catch (JSONException e) { } logEvent(REVENUE_EVENT, null, apiProperties, System.currentTimeMillis(), true); } public void setUserProperties(JSONObject userProperties) { setUserProperties(userProperties, false); } public void setUserProperties(final JSONObject userProperties, final boolean replace) { if (replace || this.userProperties == null) { this.userProperties = userProperties; return; } if (userProperties == null) { return; } // If merging is needed, do it on the log thread. Avoids an issue // where user properties is being mutated here at the same time // it's being iterated on for stringify in the event sending logic. final JSONObject currentUserProperties = this.userProperties; runOnLogThread(new Runnable() { @Override public void run() { Iterator<?> keys = userProperties.keys(); while (keys.hasNext()) { String key = (String) keys.next(); try { currentUserProperties.put(key, userProperties.get(key)); } catch (JSONException e) { Log.e(TAG, e.toString()); } } } }); } /** * @return The developer specified identifier for tracking within the analytics system. * Can be null. */ public String getUserId() { return userId; } public void setUserId(String userId) { if (!contextAndApiKeySet("setUserId()")) { return; } this.userId = userId; SharedPreferences preferences = context.getSharedPreferences( getSharedPreferencesName(), Context.MODE_PRIVATE); preferences.edit().putString(Constants.PREFKEY_USER_ID, userId).commit(); } public void uploadEvents() { if (!contextAndApiKeySet("uploadEvents()")) { return; } logThread.post(new Runnable() { @Override public void run() { updateServer(); } }); } private void updateServerLater(long delayMillis) { if (updateScheduled.getAndSet(true)) { return; } logThread.postDelayed(new Runnable() { @Override public void run() { updateScheduled.set(false); updateServer(); } }, delayMillis); } protected void updateServer() { updateServer(true); } // Always call this from logThread protected void updateServer(boolean limit) { if (optOut || offline) { return; } if (!uploadingCurrently.getAndSet(true)) { DatabaseHelper dbHelper = DatabaseHelper.getDatabaseHelper(context); try { long endSessionId = getEndSessionId(); int batchLimit = limit ? (backoffUpload ? backoffUploadBatchSize : eventUploadMaxBatchSize) : -1; Pair<Long, JSONArray> pair = dbHelper.getEvents(endSessionId, batchLimit); final long maxId = pair.first; final JSONArray events = pair.second; httpThread.post(new Runnable() { @Override public void run() { makeEventUploadPostRequest(new OkHttpClient(), events.toString(), maxId); } }); } catch (JSONException e) { uploadingCurrently.set(false); Log.e(TAG, e.toString()); } } } protected void makeEventUploadPostRequest(OkHttpClient client, String events, final long maxId) { String apiVersionString = "" + Constants.API_VERSION; String timestampString = "" + System.currentTimeMillis(); String checksumString = ""; try { String preimage = apiVersionString + apiKey + events + timestampString; checksumString = bytesToHexString(MessageDigest.getInstance("MD5").digest( preimage.getBytes("UTF-8"))); } catch (NoSuchAlgorithmException e) { // According to // this will never be thrown Log.e(TAG, e.toString()); } catch (UnsupportedEncodingException e) { // According to // this will never be thrown Log.e(TAG, e.toString()); } RequestBody body = new FormEncodingBuilder() .add("v", apiVersionString) .add("client", apiKey) .add("e", events) .add("upload_time", timestampString) .add("checksum", checksumString) .build(); Request request = new Request.Builder() .url(url) .post(body) .build(); boolean uploadSuccess = false; try { Response response = client.newCall(request).execute(); String stringResponse = response.body().string(); if (stringResponse.equals("success")) { uploadSuccess = true; logThread.post(new Runnable() { @Override public void run() { DatabaseHelper dbHelper = DatabaseHelper.getDatabaseHelper(context); dbHelper.removeEvents(maxId); uploadingCurrently.set(false); if (dbHelper.getEventCount() > eventUploadThreshold) { logThread.post(new Runnable() { @Override public void run() { updateServer(backoffUpload); } }); } else { backoffUpload = false; backoffUploadBatchSize = eventUploadMaxBatchSize; } } }); } else if (stringResponse.equals("invalid_api_key")) { Log.e(TAG, "Invalid API key, make sure your API key is correct in initialize()"); } else if (stringResponse.equals("bad_checksum")) { Log.w(TAG, "Bad checksum, post request was mangled in transit, will attempt to reupload later"); } else if (stringResponse.equals("request_db_write_failed")) { Log.w(TAG, "Couldn't write to request database on server, will attempt to reupload later"); } else if (response.code() == 413) { // If blocked by one massive event, drop it DatabaseHelper dbHelper = DatabaseHelper.getDatabaseHelper(context); if (backoffUpload && backoffUploadBatchSize == 1) { dbHelper.removeEvent(maxId); // maybe we want to reset backoffUploadBatchSize after dropping massive event } // Server complained about length of request, backoff and try again backoffUpload = true; int numEvents = Math.min((int)dbHelper.getEventCount(), backoffUploadBatchSize); backoffUploadBatchSize = (int)Math.ceil(numEvents / 2.0); Log.w(TAG, "Request too large, will decrease size and attempt to reupload"); logThread.post(new Runnable() { @Override public void run() { uploadingCurrently.set(false); updateServer(true); } }); } else { Log.w(TAG, "Upload failed, " + stringResponse + ", will attempt to reupload later"); } } catch (org.apache.http.conn.HttpHostConnectException e) { // Log.w(TAG, // "No internet connection found, unable to upload events"); lastError = e; } catch (java.net.UnknownHostException e) { // Log.w(TAG, // "No internet connection found, unable to upload events"); lastError = e; } catch (IOException e) { Log.e(TAG, e.toString()); lastError = e; } catch (AssertionError e) { // This can be caused by a NoSuchAlgorithmException thrown by DefaultHttpClient Log.e(TAG, "Exception:", e); lastError = e; } catch (Exception e) { // Just log any other exception so things don't crash on upload Log.e(TAG, "Exception:", e); lastError = e; } if (!uploadSuccess) { uploadingCurrently.set(false); } } /** * @return A unique identifier for tracking within the analytics system. Can be null if * deviceId hasn't been initialized yet; */ public String getDeviceId() { return deviceId; } private String initializeDeviceId() { Set<String> invalidIds = new HashSet<String>(); invalidIds.add(""); invalidIds.add("9774d56d682e549c"); invalidIds.add("unknown"); invalidIds.add("000000000000000"); // Common Serial Number invalidIds.add("Android"); invalidIds.add("DEFACE"); SharedPreferences preferences = context.getSharedPreferences( getSharedPreferencesName(), Context.MODE_PRIVATE); String deviceId = preferences.getString(Constants.PREFKEY_DEVICE_ID, null); if (!(TextUtils.isEmpty(deviceId) || invalidIds.contains(deviceId))) { return deviceId; } if (!newDeviceIdPerInstall && useAdvertisingIdForDeviceId) { // Android ID is deprecated by Google. // We are required to use Advertising ID, and respect the advertising ID preference String advertisingId = deviceInfo.getAdvertisingId(); if (!(TextUtils.isEmpty(advertisingId) || invalidIds.contains(advertisingId))) { preferences.edit().putString(Constants.PREFKEY_DEVICE_ID, advertisingId) .commit(); return advertisingId; } } // If this still fails, generate random identifier that does not persist // across installations. Append R to distinguish as randomly generated String randomId = deviceInfo.generateUUID() + "R"; preferences.edit().putString(Constants.PREFKEY_DEVICE_ID, randomId).commit(); return randomId; } private void runOnLogThread(Runnable r) { if (Thread.currentThread() != logThread) { logThread.post(r); } else { r.run(); } } protected Object replaceWithJSONNull(Object obj) { return obj == null ? JSONObject.NULL : obj; } protected synchronized boolean contextAndApiKeySet(String methodName) { if (context == null) { Log.e(TAG, "context cannot be null, set context with initialize() before calling " + methodName); return false; } if (TextUtils.isEmpty(apiKey)) { Log.e(TAG, "apiKey cannot be null or empty, set apiKey with initialize() before calling " + methodName); return false; } return true; } protected String getSharedPreferencesName() { return Constants.SHARED_PREFERENCES_NAME_PREFIX + "." + context.getPackageName(); } protected String bytesToHexString(byte[] bytes) { final char[] hexArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; char[] hexChars = new char[bytes.length * 2]; int v; for (int j = 0; j < bytes.length; j++) { v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } /** * Do a shallow copy of a JSONObject. Takes a bit of code to avoid * stringify and reparse given the API. */ private JSONObject cloneJSONObject(final JSONObject obj) { if (obj == null) { return null; } // obj.names returns null if the json obj is empty. JSONArray nameArray = obj.names(); int len = (nameArray != null ? nameArray.length() : 0); String[] names = new String[len]; for (int i = 0; i < len; i++) { names[i] = nameArray.optString(i); } try { return new JSONObject(obj, names); } catch (JSONException e) { Log.e(TAG, e.toString()); return null; } } /** * Move all preference data from the legacy name to the new, static name if needed. * * Constants.PACKAGE_NAME used to be set using "Constants.class.getPackage().getName()" * Some aggressive proguard optimizations broke the reflection and caused apps * to crash on startup. * * Now that Constants.PACKAGE_NAME is changed, old data on devices needs to be * moved over to the new location so that device ids remain consistent. * * This should only happen once -- the first time a user loads the app after updating. * This logic needs to remain in place for quite a long time. It was first introduced in * April 2015 in version 1.6.0. */ static boolean upgradePrefs(Context context) { return upgradePrefs(context, null, null); } static boolean upgradePrefs(Context context, String sourcePkgName, String targetPkgName) { try { if (sourcePkgName == null) { // Try to load the package name using the old reflection strategy. sourcePkgName = Constants.PACKAGE_NAME; try { sourcePkgName = Constants.class.getPackage().getName(); } catch (Exception e) { } } if (targetPkgName == null) { targetPkgName = Constants.PACKAGE_NAME; } // No need to copy if the source and target are the same. if (targetPkgName.equals(sourcePkgName)) { return false; } // Copy over any preferences that may exist in a source preference store. String sourcePrefsName = sourcePkgName + "." + context.getPackageName(); SharedPreferences source = context.getSharedPreferences(sourcePrefsName, Context.MODE_PRIVATE); // Nothing left in the source store to copy if (source.getAll().size() == 0) { return false; } String prefsName = targetPkgName + "." + context.getPackageName(); SharedPreferences targetPrefs = context.getSharedPreferences(prefsName, Context.MODE_PRIVATE); SharedPreferences.Editor target = targetPrefs.edit(); // Copy over all existing data. if (source.contains(sourcePkgName + ".previousSessionTime")) { target.putLong(Constants.PREFKEY_PREVIOUS_SESSION_TIME, source.getLong(sourcePkgName + ".previousSessionTime", -1)); } if (source.contains(sourcePkgName + ".previousSessionId")) { target.putLong(Constants.PREFKEY_PREVIOUS_SESSION_ID, source.getLong(sourcePkgName + ".previousSessionId", -1)); } if (source.contains(sourcePkgName + ".deviceId")) { target.putString(Constants.PREFKEY_DEVICE_ID, source.getString(sourcePkgName + ".deviceId", null)); } if (source.contains(sourcePkgName + ".userId")) { target.putString(Constants.PREFKEY_USER_ID, source.getString(sourcePkgName + ".userId", null)); } if (source.contains(sourcePkgName + ".optOut")) { target.putBoolean(Constants.PREFKEY_OPT_OUT, source.getBoolean(sourcePkgName + ".optOut", false)); } // Commit the changes and clear the source store so we don't recopy. target.apply(); source.edit().clear().apply(); Log.i(TAG, "Upgraded shared preferences from " + sourcePrefsName + " to " + prefsName); return true; } catch (Exception e) { Log.e(TAG, "Error upgrading shared preferences", e); return false; } }}
package core; import java.sql.*; public class Database { private static Connection conn = null; public Database(){ try{ Class.forName("org.sqlite.JDBC"); conn = DriverManager.getConnection("jdbc:sqlite:app_data/bullybot.db"); createTables(); }catch(Exception ex){ ex.printStackTrace(); } } /** * Creates database tables if they do not already exist */ private void createTables(){ try{ Statement statement = conn.createStatement(); statement.setQueryTimeout(30); statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + "DiscordServer(" + "id INTEGER NOT NULL, " + "name VARCHAR(50) NOT NULL, " + "PRIMARY KEY (id)" + ")"); statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + "Player(" + "id INTEGER NOT NULL, " + "name VARCHAR(50) NOT NULL, " + "PRIMARY KEY (id)" + ")"); statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + "Queue(" + "name VARCHAR(50) NOT NULL, " + "serverId INTEGER NOT NULL, " + "PRIMARY KEY (name, serverId), " + "FOREIGN KEY (serverId) REFERENCES Server(id)" + ")"); statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + "Game(" + "timestamp INTEGER NOT NULL, " + "queueName VARCHAR(50) NOT NULL, " + "serverId INTEGER NOT NULL, " + "PRIMARY KEY (timestamp, queueName, serverId), " + "FOREIGN KEY (serverId) REFERENCES Queue(serverId)" + ")"); statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + "PlayerGame(" + "playerId INTEGER NOT NULL, " + "timestamp INTEGER NOT NULL, " + "serverId INTEGER NOT NULL, " + "pickOrder INTEGER, " + "captain INTEGER DEFAULT 0, " + "PRIMARY KEY (playerId, timestamp, serverId), " + "FOREIGN KEY (playerId) REFERENCES Player(id), " + "FOREIGN KEY (serverId) REFERENCES Game(serverId), " + "FOREIGN KEY (timestamp) REFERENCES Game(timestamp)" + ")"); statement.executeUpdate("CREATE TABLE IF NOT EXISTS " + "PugServer(" + "serverId INTEGER NOT NULL, " + "ip VARCHAR(20) NOT NULL, " + "port INTEGER, " + "name VARCHAR(30), " + "password VARCHAR(30), " + "region VARCHAR(10), " + "gameId INTEGER NOT NULL, " + "PRIMARY KEY (ip, serverId), " + "FOREIGN KEY (serverId) REFERENCES DiscordServer(id)" + ")"); }catch(Exception ex){ ex.printStackTrace(); } } /** * Inserts a new record into the DiscordServer table * * @param id the id of the server * @param name the name of the server */ public static void insertDiscordServer(Long id, String name){ try{ PreparedStatement pStatement = conn.prepareStatement("INSERT OR IGNORE INTO DiscordServer VALUES(?, ?)"); pStatement.setLong(1, id); pStatement.setString(2, name); pStatement.execute(); }catch(SQLException ex){ ex.printStackTrace(); } } /** * Insert a user into the Player table * * @param id the id of the user * @param name the name of the user */ public static void insertPlayer(Long id, String name){ try{ PreparedStatement pStatement = conn.prepareStatement("INSERT OR IGNORE INTO Player VALUES(?, ?)"); pStatement.setLong(1, id); pStatement.setString(2, name); pStatement.execute(); }catch(SQLException ex){ ex.printStackTrace(); } } /** * Insert a queue into the Queue table * * @param serverId the id of the server * @param Name the name of the queue */ public static void insertQueue(Long serverId, String Name){ try{ PreparedStatement pStatement = conn.prepareStatement("INSERT OR IGNORE INTO Queue VALUES(?, ?)"); pStatement.setString(1, Name); pStatement.setLong(2, serverId); pStatement.execute(); }catch(SQLException ex){ ex.printStackTrace(); } } /** * Insert a game into the Game table * * @param timestamp the start time of the game * @param queueName the name of the queue * @param serverId the server id */ public static void insertGame(Long timestamp, String queueName, Long serverId){ try{ PreparedStatement pStatement = conn.prepareStatement("INSERT OR IGNORE INTO Game VALUES(?, ?, ?)"); pStatement.setLong(1, timestamp / 1000); pStatement.setString(2, queueName); pStatement.setLong(3, serverId); pStatement.execute(); }catch(SQLException ex){ ex.printStackTrace(); } } /** * Inserts a new record into the PlayerGame table * * @param playerId the id of the player * @param timestamp the time of the game start * @param serverId the id of the server */ public static void insertPlayerGame(Long playerId, Long timestamp, Long serverId){ try{ PreparedStatement pStatement = conn.prepareStatement("INSERT OR IGNORE INTO PlayerGame (playerId, timestamp, serverId) VALUES(?, ?, ?)"); pStatement.setLong(1, playerId); pStatement.setLong(2, timestamp / 1000); pStatement.setLong(3, serverId); pStatement.execute(); }catch(SQLException ex){ ex.printStackTrace(); } } /** * Updates a PlayerGame record with a new pickOrder * * @param playerId the id of the player * @param timestamp the time of the game start * @param serverId the id of the server * @param pickOrder the pick order of the player */ public static void updatePlayerGamePickOrder(Long playerId, Long timestamp, Long serverId, Integer pickOrder){ try{ PreparedStatement pStatement = conn.prepareStatement("UPDATE PlayerGame SET pickOrder = ? " + "WHERE playerId = ? AND timestamp = ? AND serverId = ?"); pStatement.setInt(1, pickOrder); pStatement.setLong(2, playerId); pStatement.setLong(3, timestamp / 1000); pStatement.setLong(4, serverId); pStatement.execute(); }catch(SQLException ex){ ex.printStackTrace(); } } /** * Updates a record in PlayerGame with captain information * * @param playerId the id of the player * @param timestamp the time of the game start * @param serverId the id of the server * @param captain true if the player is a captain */ public static void updatePlayerGameCaptain(Long playerId, Long timestamp, Long serverId, boolean captain){ Integer captainInt = 0; if(captain){ captainInt = 1; } try{ PreparedStatement pStatement = conn.prepareStatement("UPDATE PlayerGame SET captain = ? " + "WHERE playerId = ? AND timestamp = ? AND serverId = ?"); pStatement.setInt(1, captainInt); pStatement.setLong(2, playerId); pStatement.setLong(3, timestamp / 1000); pStatement.setLong(4, serverId); pStatement.execute(); }catch(SQLException ex){ ex.printStackTrace(); } } public static Integer queryGetTotalGamesPlayed(Long playerId){ try{ PreparedStatement pStatement = conn.prepareStatement("SELECT count(playerId) FROM PlayerGame " + "WHERE playerId = ?"); pStatement.setLong(1, playerId); pStatement.setQueryTimeout(10); return pStatement.executeQuery().getInt(1); }catch(SQLException ex){ ex.printStackTrace(); } return 0; } public static ResultSet queryGetPugServers(Long serverId, String region){ try{ PreparedStatement pStatement = conn.prepareStatement("SELECT * FROM PugServer " + "WHERE serverId = ? AND region = ?"); pStatement.setLong(1, serverId); pStatement.setString(2, region); pStatement.setQueryTimeout(10); return pStatement.executeQuery(); }catch(SQLException ex){ ex.printStackTrace(); } return null; } public static ResultSet queryGetPugServers(Long serverId){ try{ PreparedStatement pStatement = conn.prepareStatement("SELECT * FROM PugServer " + "WHERE serverId = ?"); pStatement.setLong(1, serverId); pStatement.setQueryTimeout(10); return pStatement.executeQuery(); }catch(SQLException ex){ ex.printStackTrace(); } return null; } }
package com.groupbyinc.quickstart.controller; import com.groupbyinc.api.CloudBridge; import com.groupbyinc.api.Query; import com.groupbyinc.api.model.*; import com.groupbyinc.api.request.RestrictNavigation; import com.groupbyinc.common.apache.commons.io.IOUtils; import com.groupbyinc.common.apache.commons.lang3.StringUtils; import com.groupbyinc.common.apache.http.HttpEntity; import com.groupbyinc.common.apache.http.client.methods.CloseableHttpResponse; import com.groupbyinc.common.apache.http.client.methods.HttpPost; import com.groupbyinc.common.apache.http.entity.StringEntity; import com.groupbyinc.common.apache.http.impl.client.CloseableHttpClient; import com.groupbyinc.common.apache.http.impl.client.HttpClients; import com.groupbyinc.common.blip.BlipClient; import com.groupbyinc.common.jackson.Mappers; import com.groupbyinc.common.jackson.databind.DeserializationFeature; import com.groupbyinc.common.jackson.databind.ObjectMapper; import com.groupbyinc.util.UrlBeautifier; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.ServletRequestUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.*; import java.util.logging.Logger; import static com.groupbyinc.common.jackson.core.JsonParser.Feature.ALLOW_SINGLE_QUOTES; import static com.groupbyinc.common.jackson.core.JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES; import static java.util.Collections.singletonList; /** * NavigationController is the single entry point for search and navigation * in the quickstart application. */ @SuppressWarnings("WeakerAccess") @Controller public class NavigationController { private static final transient Logger LOG = Logger.getLogger(NavigationController.class.getSimpleName()); private static final ObjectMapper OM = new ObjectMapper(); private static final ObjectMapper OM_MATCH_STRATEGY = new ObjectMapper(); // The UrlBeautifier deconstructs a URL into a query object. You can create as many url // beautifiers as you want which may correspond to different kinds of urls that you want // to generate. Here we construct one called 'default' that we use for every search and // navigation URL. private static UrlBeautifier defaultUrlBeautifier = null; static { OM.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); OM_MATCH_STRATEGY.enable(ALLOW_UNQUOTED_FIELD_NAMES).enable(ALLOW_SINGLE_QUOTES); UrlBeautifier.createUrlBeautifier("default"); defaultUrlBeautifier = UrlBeautifier.getUrlBeautifiers().get("default"); defaultUrlBeautifier.addRefinementMapping('s', "size"); defaultUrlBeautifier.setSearchMapping('q'); defaultUrlBeautifier.setAppend("/index.html"); defaultUrlBeautifier.addReplacementRule('/', ' '); defaultUrlBeautifier.addReplacementRule('\\', ' '); } /** * We hold all the bridges in a map so we're not creating a new one for each request. * Ideally, there should only be one bridge per jvm and they are expensive to create but thread safe. */ private static final Map<String, CloudBridge> BRIDGES = new HashMap<>(); private final BlipClient blipClient; @Autowired public NavigationController(BlipClient blipClient) { this.blipClient = blipClient; } @RequestMapping({"**/index.html"}) public String handleSearch(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { // Get the action from the request. String action = ServletRequestUtils.getStringParameter(request, "action", null); // Create the query object from the beautifier Query query = defaultUrlBeautifier.fromUrl(request.getRequestURI(), new Query()); // return all fields with each record. // If there are specific fields defined, use these, otherwise default to showing all fields. String fieldString = getCookie(request, "fields", "*").trim(); // If an image field is specified, always ask for it with the request. String imageField = getCookie(request, "imageField", ""); if (StringUtils.isNotBlank(imageField)) { fieldString += "," + imageField; } fieldString += ",id"; if (StringUtils.isNotBlank(fieldString)) { String[] fields = fieldString.split(","); for (String field : fields) { if (StringUtils.isNotBlank(field)) { query.addFields(field.trim()); } } } // Setup parameters for the bridge String customerId = getCookie(request, "customerId", "").trim(); String clientKey = getCookie(request, "clientKey", "").trim(); boolean skipCache = !Boolean.valueOf(getCookie(request, "cache", "false")); /** * DO NOT create a bridge per request. Create only one. * They are expensive and create HTTP connection pools behind the scenes. */ CloudBridge bridge = getCloudBridge(clientKey, customerId, skipCache); // If a specific area is set in the url params set it on the query. // Areas are used to name space rules / query rewrites. String area = getCookie(request, "area", "").trim(); if (StringUtils.isNotBlank(area)) { query.setArea(area); } // Use a specific language // See the documentation for which language codes are available. String language = getCookie(request, "language", "").trim(); if (StringUtils.isNotBlank(language)) { query.setLanguage(language); } // Visitor is used in personalized relevance. String visitorId = getCookie(request, "visitorId", "").trim(); if (StringUtils.isNotBlank(visitorId)) { query.setVisitorId(visitorId); } // Restrict Navigation (this performs two queries so may be slow) String restrictNavigationName = getCookie(request, "restrictNavigationName", "").trim(); if (StringUtils.isNotBlank(restrictNavigationName)) { RestrictNavigation restrictNavigation = new RestrictNavigation().setName(restrictNavigationName); String restrictNavigationCount = getCookie(request, "restrictNavigationCount", "").trim(); if (StringUtils.isNotBlank(restrictNavigationCount)) { try { restrictNavigation.setCount(new Integer(restrictNavigationCount)); } catch (Exception e) { LOG.warning("Couldn't parse restrictNavigation count: " + restrictNavigationCount + " " + e.getMessage()); } } query.setRestrictNavigation(restrictNavigation); } // By default refinements that boolean dontPruneRefinements = Boolean.valueOf(getCookie(request, "dontPruneRefinements", "false")); if (dontPruneRefinements) { query.setPruneRefinements(false); } // By default refinements that boolean disableAutocorrection = Boolean.valueOf(getCookie(request, "disableAutocorrection", "false")); if (disableAutocorrection) { query.setDisableAutocorrection(true); } // By default refinements that String customUrlParameters = getCookie(request, "customUrlParameters", ""); if (StringUtils.isNotBlank(customUrlParameters)) { query.addCustomUrlParamsByString(customUrlParameters); } // If you have data in different collections you can specify the specific // collection you wish to query against. String collection = getCookie(request, "collection", "").trim(); if (StringUtils.isNotBlank(collection)) { query.setCollection(collection); } // Set the page size String pageSize = getCookie(request, "pageSize", "").trim(); if (StringUtils.isNotBlank(pageSize)) { try { query.setPageSize(new Integer(pageSize)); } catch (NumberFormatException e) { query.setPageSize(10); } } // You can specify the sort field and order of the results. String sortField = getCookie(request, "sortField", "").trim(); if (StringUtils.isNotBlank(sortField)) { String sortOrder = getCookie(request, "sortOrder", "").trim(); String[] fields = sortField.split(","); String[] orders = sortOrder.split(","); for (int i = 0; i < fields.length; i++) { String field = fields[i].trim(); String order = i < orders.length ? orders[i].trim() : null; Sort sort = new Sort().setField(field); if (StringUtils.isNotBlank(order)) { if ("D".equals(order)) { sort.setOrder(Sort.Order.Descending); } } query.setSort(sort); } } String includedNavigations = getCookie(request, "includedNavigations", "").trim(); if (StringUtils.isNotBlank(includedNavigations)) { for (String name : StringUtils.split(includedNavigations, ",")) { query.addIncludedNavigations(name.trim()); } } String excludedNavigations = getCookie(request, "excludedNavigations", "").trim(); if (StringUtils.isNotBlank(excludedNavigations)) { for (String name : StringUtils.split(excludedNavigations, ",")) { query.addExcludedNavigations(name.trim()); } } String bringToTop = getCookie(request, "bringToTop", "").trim(); if (StringUtils.isNotBlank(bringToTop)) { for (String name : StringUtils.split(bringToTop, ",")) { query.setBringToTop(name.trim()); } } // If there are additional refinements that aren't being beautified get these from the // URL and add them to the query. String refinements = ServletRequestUtils.getStringParameter(request, "refinements", ""); if (StringUtils.isNotBlank(refinements)) { query.addRefinementsByString(refinements); } // If the search string has not been beautified get it from the URL parameters. String queryString = ServletRequestUtils.getStringParameter(request, "q", ""); if (StringUtils.isNotBlank(queryString)) { query.setQuery(queryString); } // If we're paging through results set the skip from the url params query.setSkip(ServletRequestUtils.getIntParameter(request, "p", 0)); // If the query is supposed to be beautified, and it was in fact in the URL params // send a redirect command to the browser to redirect to the beautified URL. String incoming = request.getRequestURI(); String beautified = request.getContextPath() + defaultUrlBeautifier.toUrl( query.getQuery(), query.getNavigations()); if (!beautified.startsWith(incoming)) { response.sendRedirect(beautified); return null; } // Create a model that we will pass into the rendering JSP String view = "getOrderList".equals(action) ? "orderList" : "index"; model.put("model", model); // put back the customerId model.put("customerId", customerId); model.put("collections", getCollections(customerId, clientKey)); // If a specific biasing profile is set in the url params set it on the query. String biasingProfile = getCookie(request, "biasingProfile", "").trim(); // We will run this query multiple times for each biasing profile found String[] biasingProfiles = biasingProfile.split(",", -1); if (biasingProfiles.length == 0) { biasingProfiles = new String[]{""}; } model.put("biasingProfileCount", biasingProfiles.length); // If a specific match strategy is set. String matchStrategy = getCookie(request, "matchStrategy", "").trim(); // We will run this query multiple times for each biasing profile found String[] matchStrategies = matchStrategy.split("\\|", -1); if (matchStrategies.length != biasingProfiles.length) { matchStrategies = new String[biasingProfiles.length]; for (int i = 0; i < matchStrategies.length; i++) { matchStrategies[i] = ""; } } // Put match strategies back in request model.put("matchStrategies", matchStrategies); List<String> matchStrategyErrors = new ArrayList<>(); model.put("matchStrategyErrors", matchStrategyErrors); // deal with column sorts. List<Sort> originalSorts = new ArrayList<>(query.getSort()); List<List<Sort>> colSorts = getColSorts(request, biasingProfiles.length, model); model.put("moreRefinementsQuery", OM.writeValueAsString(query)); for (int i = 0; i < biasingProfiles.length; i++) { String profile = biasingProfiles[i].trim(); String strategy = matchStrategies[i].trim(); query.getSort().clear(); query.getSort().addAll(originalSorts); query.setBiasingProfile(null); query.setMatchStrategy(null); if (StringUtils.isNotBlank(profile)) { query.setBiasingProfile(profile); } if (StringUtils.isNotBlank(strategy)) { query.setMatchStrategy(createMatchStrategy(matchStrategyErrors, strategy)); } if (colSorts.get(i) != null) { query.getSort().clear(); query.getSort().addAll(colSorts.get(i)); } // pass the raw json representation of the query into the view regardless of errors model.put("rawQuery" + i, query.setReturnBinary(false).getBridgeJson(clientKey)); model.put("originalQuery" + i, query); query.setReturnBinary(true); try { // execute the query Results results = new Results(); if (StringUtils.isNotBlank(clientKey)) { long startTime = System.currentTimeMillis(); results = bridge.search(query); long duration = System.currentTimeMillis() - startTime; model.put("time" + i, duration); blipClient.send("customerId", customerId, "eventType", "query", "columns", String.valueOf(biasingProfiles.length), "durationMillis", String.valueOf(duration)); } // pass the results into the view. model.put("results" + i, results); model.put("resultsJson" + i, Mappers.writeValueAsString(results)); } catch (Exception e) { blipClient.send("customerId", customerId, "eventType", "error", "message", e.getMessage()); LOG.warning(e.getMessage()); model.put("error" + i, e.getMessage()); model.put("cause" + i, e.getCause()); } } // render using index.jsp and the populated model. return view; } @SuppressWarnings("unchecked") private List<List<Sort>> getColSorts(HttpServletRequest request, int length, Map model) { Map<String, String[]> cs = new HashMap<>(); Map<String, String[]> cd = new HashMap<>(); for (int columns = 1; columns < 6; columns++) { String colSort = getCookie(request, "colSort" + columns, ""); cs.put("colSorts" + columns, colSort.split("\\|", -1)); String colDir = getCookie(request, "colDir" + columns, ""); cd.put("colDirs" + columns, colDir.split("\\|", -1)); model.put("sort" + columns, cs.get("colSorts" + columns)); model.put("sort" + columns + "Direction", cd.get("colDirs" + columns)); } List<List<Sort>> colSorts = new ArrayList<>(); for (int column = 0; column < length; column++) { List<Sort> sorts = null; if (cs.get("colSorts1").length > column) { for (int row = 1; row < 6; row++) { if (StringUtils.isNotBlank(cs.get("colSorts" + row)[column])) { if (sorts == null) { sorts = new ArrayList<>(); } Sort sort = new Sort(); sort.setField(cs.get("colSorts" + row)[column]); if (StringUtils.isNotBlank(cd.get("colDirs" + row)[column]) && cd.get("colDirs" + row)[column].toLowerCase().startsWith("d")) { sort.setOrder(Sort.Order.Descending); } else { sort.setOrder(Sort.Order.Ascending); } sorts.add(sort); } } } colSorts.add(sorts); } return colSorts; } private MatchStrategy createMatchStrategy(List<String> matchStrategyErrors, String strategy) { try { Map ms = OM_MATCH_STRATEGY.readValue(strategy, Map.class); MatchStrategy matchStrategy = new MatchStrategy(); List rules = (List) ms.get("rules"); for (Object rule : rules) { matchStrategy.getRules().add(OM_MATCH_STRATEGY.readValue(OM_MATCH_STRATEGY.writeValueAsString(rule), PartialMatchRule.class)); } matchStrategyErrors.add(""); return matchStrategy; } catch (Exception e) { e.printStackTrace(); matchStrategyErrors.add(e.getMessage()); return null; } } @SuppressWarnings("unchecked") public static List<String> getCollections(String customerId, String clientKey) { List<String> collections = new ArrayList<>(); if (!StringUtils.isBlank(customerId) && !StringUtils.isBlank(clientKey)) { try { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost getCollections = new HttpPost("https://" + customerId + ".groupbycloud.com/api/v1/collections"); getCollections.setEntity(new StringEntity("{clientKey: '" + clientKey + "'}", "UTF-8")); CloseableHttpResponse response = httpClient.execute(getCollections); HttpEntity responseEntity = response.getEntity(); LOG.info(response.getStatusLine().toString()); if (response.getStatusLine().getStatusCode() == 200) { String serverResponse = IOUtils.toString(responseEntity.getContent()); LOG.info(serverResponse); Map collectionsMap = Mappers.readValue(serverResponse.getBytes("UTF-8"), Map.class, false); Map collectionMap = (Map) collectionsMap.get("collections"); if (collectionMap != null) { Set<String> set = collectionMap.keySet(); for (String collection : set) { if (!collection.endsWith("-variants")) { collections.add(collection); } } } } return collections; } catch (IOException e) { LOG.warning("Couldn't load collections: " + e.getMessage()); } } return collections; } @RequestMapping(method = RequestMethod.POST, value = "**/moreRefinements.html") public String getMoreNavigations(Map<String, Object> model, HttpServletRequest request) throws ServletException { try { String clientKey = getCookie(request, "clientKey", "").trim(); String customerId = getCookie(request, "customerId", "").trim(); String originalQuery = ServletRequestUtils.getRequiredStringParameter(request, "originalQuery"); String navigationName = ServletRequestUtils.getRequiredStringParameter(request, "navigationName"); boolean skipCache = !Boolean.valueOf(getCookie(request, "cache", "false")); /** * DO NOT create a bridge per request. Create only one. * They are expensive and create HTTP connection pools behind the scenes. */ CloudBridge bridge = getCloudBridge(clientKey, customerId, skipCache); Query query = OM.readValue(originalQuery, Query.class); navigationName = navigationName.trim(); Navigation availableNavigation = new Navigation().setName(navigationName); Results results = new Results(); results.setSelectedNavigation(new ArrayList<>(query.getNavigations().values())); RefinementsResult refinementsResults = bridge.refinements(query, navigationName); if (refinementsResults != null && refinementsResults.getNavigation() != null) { List<Refinement> refinementList = refinementsResults.getNavigation().getRefinements(); if (refinementsResults.getNavigation().isOr()) { availableNavigation.setOr(true); } availableNavigation.setDisplayName(refinementsResults.getNavigation().getDisplayName()); availableNavigation.setRefinements(refinementList); } results.setQuery(query.getQuery()); results.setAvailableNavigation(singletonList(availableNavigation)); model.put("results", results); model.put("nav", availableNavigation); return "/includes/navLink"; } catch (IOException e) { throw new ServletException(e); } } private CloudBridge getCloudBridge(String clientKey, String customerId, boolean skipCache) { String key = customerId + clientKey + String.valueOf(skipCache); if (!BRIDGES.containsKey(key)) { CloudBridge cb = new CloudBridge(clientKey, customerId); if (skipCache) { cb.setCachingEnabled(false); } BRIDGES.put(key, cb); } return BRIDGES.get(key); } /** * Helper method to get cookie values. We use this for storing the clientKey and customerId, though * these values should typically be put in a properties file. */ private String getCookie(HttpServletRequest pRequest, String pName, String pDefault) { Cookie[] cookies = pRequest.getCookies(); if (pRequest.getCookies() != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(pName)) { try { return URLDecoder.decode(cookie.getValue(), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } } return pDefault; } }
package org.neo4j.kernel.impl.nioneo.store; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.neo4j.helpers.UTF8; import org.neo4j.kernel.IdGeneratorFactory; import org.neo4j.kernel.IdType; import org.neo4j.kernel.impl.util.StringLogger; /** * An abstract representation of a dynamic store. The difference between a * normal {@link AbstractStore} and a <CODE>AbstractDynamicStore</CODE> is * that the size of a record/entry can be dynamic. * <p> * Instead of a fixed record this class uses blocks to store a record. If a * record size is greater than the block size the record will use one or more * blocks to store its data. * <p> * A dynamic store don't have a {@link IdGenerator} because the position of a * record can't be calculated just by knowing the id. Instead one should use a * {@link AbstractStore} and store the start block of the record located in the * dynamic store. Note: This class makes use of an id generator internally for * managing free and non free blocks. * <p> * Note, the first block of a dynamic store is reserved and contains information * about the store. */ public abstract class AbstractDynamicStore extends CommonAbstractStore implements Store, RecordStore<DynamicRecord> { protected static void createEmptyStore( String fileName, int baseBlockSize, String typeAndVersionDescriptor, IdGeneratorFactory idGeneratorFactory, IdType idType ) { int blockSize = baseBlockSize; // sanity checks if ( fileName == null ) { throw new IllegalArgumentException( "Null filename" ); } File file = new File( fileName ); if ( file.exists() ) { throw new IllegalStateException( "Can't create store[" + fileName + "], file already exists" ); } if ( blockSize < 1 ) { throw new IllegalArgumentException( "Illegal block size[" + blockSize + "]" ); } if ( blockSize > 0xFFFF ) { throw new IllegalArgumentException( "Illegal block size[" + blockSize + "], limit is 65535" ); } blockSize += BLOCK_HEADER_SIZE; // write the header try { FileChannel channel = new FileOutputStream( fileName ).getChannel(); int endHeaderSize = blockSize + UTF8.encode( typeAndVersionDescriptor ).length; ByteBuffer buffer = ByteBuffer.allocate( endHeaderSize ); buffer.putInt( blockSize ); buffer.position( endHeaderSize - typeAndVersionDescriptor.length() ); buffer.put( UTF8.encode( typeAndVersionDescriptor ) ).flip(); channel.write( buffer ); channel.force( false ); channel.close(); } catch ( IOException e ) { throw new UnderlyingStorageException( "Unable to create store " + fileName, e ); } idGeneratorFactory.create( fileName + ".id" ); // TODO highestIdInUse = 0 works now, but not when slave can create store files. IdGenerator idGenerator = idGeneratorFactory.open( fileName + ".id", 1, idType, 0 ); idGenerator.nextId(); // reserv first for blockSize idGenerator.close(); } private int blockSize; public AbstractDynamicStore( String fileName, Map<?,?> config, IdType idType ) { super( fileName, config, idType ); } // public AbstractDynamicStore( String fileName ) // super( fileName ); @Override protected int getEffectiveRecordSize() { return getBlockSize(); } @Override protected void verifyFileSizeAndTruncate() throws IOException { int expectedVersionLength = UTF8.encode( buildTypeDescriptorAndVersion( getTypeDescriptor() ) ).length; long fileSize = getFileChannel().size(); if ( (fileSize - expectedVersionLength) % blockSize != 0 && !isReadOnly() ) { setStoreNotOk( new IllegalStateException( "Misaligned file size " + fileSize + " for " + this + ", expected version length " + expectedVersionLength ) ); } if ( getStoreOk() && !isReadOnly() ) { getFileChannel().truncate( fileSize - expectedVersionLength ); } } @Override protected void readAndVerifyBlockSize() throws IOException { ByteBuffer buffer = ByteBuffer.allocate( 4 ); getFileChannel().position( 0 ); getFileChannel().read( buffer ); buffer.flip(); blockSize = buffer.getInt(); if ( blockSize <= 0 ) { throw new InvalidRecordException( "Illegal block size: " + blockSize + " in " + getStorageFileName() ); } } /** * Returns the byte size of each block for this dynamic store * * @return The block size of this store */ public int getBlockSize() { return blockSize; } /** * Returns next free block. * * @return The next free block * @throws IOException * If capacity exceeded or closed id generator */ public long nextBlockId() { return nextId(); } public void freeBlockId( long blockId ) { freeId( blockId ); } /** * Calculate the size of a dynamic record given the size of the data block. * * @param dataSize the size of the data block in bytes. * @return the size of a dynamic record. */ public static int getRecordSize( int dataSize ) { return dataSize + BLOCK_HEADER_SIZE; } // (in_use+next high)(1 byte)+nr_of_bytes(3 bytes)+next_block(int) protected static final int BLOCK_HEADER_SIZE = 1 + 3 + 4; public void updateRecord( DynamicRecord record ) { long blockId = record.getId(); if ( isInRecoveryMode() ) { registerIdFromUpdateRecord( blockId ); } PersistenceWindow window = acquireWindow( blockId, OperationType.WRITE ); try { Buffer buffer = window.getOffsettedBuffer( blockId ); if ( record.inUse() ) { long nextProp = record.getNextBlock(); int nextModifier = nextProp == Record.NO_NEXT_BLOCK.intValue() ? 0 : (int) ( ( nextProp & 0xF00000000L ) >> 8 ); nextModifier |= ( Record.IN_USE.byteValue() << 28 ); /* * * [ x, ][ , ][ , ][ , ] inUse * [ ,xxxx][ , ][ , ][ , ] high next block bits * [ , ][xxxx,xxxx][xxxx,xxxx][xxxx,xxxx] nr of bytes * */ int mostlyNrOfBytesInt = record.getLength(); assert mostlyNrOfBytesInt < ( 1 << 24 ) - 1; mostlyNrOfBytesInt |= nextModifier; buffer.putInt( mostlyNrOfBytesInt ).putInt( (int) nextProp ); if ( !record.isLight() ) { buffer.put( record.getData() ); } else { assert getHighId() != record.getId() + 1; } } else { buffer.put( Record.NOT_IN_USE.byteValue() ); if ( !isInRecoveryMode() ) { freeBlockId( blockId ); } } } finally { releaseWindow( window ); } } @Override public void forceUpdateRecord( DynamicRecord record ) { updateRecord( record ); } protected Collection<DynamicRecord> allocateRecords( long startBlock, byte src[] ) { assert getFileChannel() != null : "Store closed, null file channel"; assert src != null : "Null src argument"; List<DynamicRecord> recordList = new LinkedList<DynamicRecord>(); long nextBlock = startBlock; int srcOffset = 0; int dataSize = getBlockSize() - BLOCK_HEADER_SIZE; do { DynamicRecord record = new DynamicRecord( nextBlock ); record.setCreated(); record.setInUse( true ); if ( src.length - srcOffset > dataSize ) { byte data[] = new byte[dataSize]; System.arraycopy( src, srcOffset, data, 0, dataSize ); record.setData( data ); nextBlock = nextBlockId(); record.setNextBlock( nextBlock ); srcOffset += dataSize; } else { byte data[] = new byte[src.length - srcOffset]; System.arraycopy( src, srcOffset, data, 0, data.length ); record.setData( data ); nextBlock = Record.NO_NEXT_BLOCK.intValue(); record.setNextBlock( nextBlock ); } recordList.add( record ); assert !record.isLight(); assert record.getLength() > 0; assert record.getData() != null; } while ( nextBlock != Record.NO_NEXT_BLOCK.intValue() ); return recordList; } public Collection<DynamicRecord> getLightRecords( long startBlockId ) { List<DynamicRecord> recordList = new LinkedList<DynamicRecord>(); long blockId = startBlockId; while ( blockId != Record.NO_NEXT_BLOCK.intValue() ) { PersistenceWindow window = acquireWindow( blockId, OperationType.READ ); try { DynamicRecord record = getRecord( blockId, window, RecordLoad.CHECK ); recordList.add( record ); blockId = record.getNextBlock(); } finally { releaseWindow( window ); } } return recordList; } public void makeHeavy( DynamicRecord record ) { long blockId = record.getId(); PersistenceWindow window = acquireWindow( blockId, OperationType.READ ); try { Buffer buf = window.getBuffer(); // NOTE: skip of header in offset int offset = (int) (blockId-buf.position()) * getBlockSize() + BLOCK_HEADER_SIZE; buf.setOffset( offset ); byte bytes[] = new byte[record.getLength()]; buf.get( bytes ); record.setData( bytes ); } finally { releaseWindow( window ); } } protected boolean isRecordInUse( ByteBuffer buffer ) { return ( ( buffer.get() & (byte) 0xF0 ) >> 4 ) == Record.IN_USE.byteValue(); } private DynamicRecord getRecord( long blockId, PersistenceWindow window, RecordLoad load ) { DynamicRecord record = new DynamicRecord( blockId ); Buffer buffer = window.getOffsettedBuffer( blockId ); /* * * [ x, ][ , ][ , ][ , ] inUse * [ ,xxxx][ , ][ , ][ , ] high next block bits * [ , ][xxxx,xxxx][xxxx,xxxx][xxxx,xxxx] nr of bytes * */ long firstInteger = buffer.getUnsignedInt(); int inUseByte = (int) ( ( firstInteger & 0xF0000000 ) >> 28 ); boolean inUse = inUseByte == Record.IN_USE.intValue(); if ( !inUse && load != RecordLoad.FORCE ) { throw new InvalidRecordException( "Not in use, blockId[" + blockId + "]" ); } int dataSize = getBlockSize() - BLOCK_HEADER_SIZE; int nrOfBytes = (int) ( firstInteger & 0xFFFFFF ); long nextBlock = buffer.getUnsignedInt(); long nextModifier = ( firstInteger & 0xF000000L ) << 8; long longNextBlock = longFromIntAndMod( nextBlock, nextModifier ); boolean readData = load != RecordLoad.CHECK; if ( longNextBlock != Record.NO_NEXT_BLOCK.intValue() && nrOfBytes < dataSize || nrOfBytes > dataSize ) { readData = false; if ( load != RecordLoad.FORCE ) throw new InvalidRecordException( "Next block set[" + nextBlock + "] current block illegal size[" + nrOfBytes + "/" + dataSize + "]" ); } record.setInUse( true ); record.setLength( nrOfBytes ); record.setNextBlock( longNextBlock ); if ( readData ) { byte byteArrayElement[] = new byte[nrOfBytes]; buffer.get( byteArrayElement ); record.setData( byteArrayElement ); } return record; } @Override public DynamicRecord getRecord( long id ) { PersistenceWindow window = acquireWindow( id, OperationType.READ ); try { return getRecord( id, window, RecordLoad.NORMAL ); } finally { releaseWindow( window ); } } @Override public DynamicRecord forceGetRecord( long id ) { PersistenceWindow window = acquireWindow( id, OperationType.READ ); try { return getRecord( id, window, RecordLoad.FORCE ); } finally { releaseWindow( window ); } } public Collection<DynamicRecord> getRecords( long startBlockId ) { List<DynamicRecord> recordList = new LinkedList<DynamicRecord>(); long blockId = startBlockId; while ( blockId != Record.NO_NEXT_BLOCK.intValue() ) { PersistenceWindow window = acquireWindow( blockId, OperationType.READ ); try { DynamicRecord record = getRecord( blockId, window, RecordLoad.NORMAL ); recordList.add( record ); blockId = record.getNextBlock(); } finally { releaseWindow( window ); } } return recordList; } private long findHighIdBackwards() throws IOException { FileChannel fileChannel = getFileChannel(); int recordSize = getBlockSize(); long fileSize = fileChannel.size(); long highId = fileSize / recordSize; ByteBuffer byteBuffer = ByteBuffer.allocate( 1 ); for ( long i = highId; i > 0; i { fileChannel.position( i * recordSize ); if ( fileChannel.read( byteBuffer ) > 0 ) { byteBuffer.flip(); boolean isInUse = isRecordInUse( byteBuffer ); byteBuffer.clear(); if ( isInUse ) { return i; } } } return 0; } /** * Rebuilds the internal id generator keeping track of what blocks are free * or taken. * * @throws IOException * If unable to rebuild the id generator */ @Override protected void rebuildIdGenerator() { if ( getBlockSize() <= 0 ) { throw new InvalidRecordException( "Illegal blockSize: " + getBlockSize() ); } logger.fine( "Rebuilding id generator for[" + getStorageFileName() + "] ..." ); closeIdGenerator(); File file = new File( getStorageFileName() + ".id" ); if ( file.exists() ) { boolean success = file.delete(); assert success; } createIdGenerator( getStorageFileName() + ".id" ); openIdGenerator(); // nextBlockId(); // reserved first block containing blockSize setHighId( 1 ); FileChannel fileChannel = getFileChannel(); long highId = 0; long defraggedCount = 0; try { long fileSize = fileChannel.size(); boolean fullRebuild = true; if ( getConfig() != null ) { String mode = (String) getConfig().get( "rebuild_idgenerators_fast" ); if ( mode != null && mode.toLowerCase().equals( "true" ) ) { fullRebuild = false; highId = findHighIdBackwards(); } } ByteBuffer byteBuffer = ByteBuffer.wrap( new byte[1] ); LinkedList<Long> freeIdList = new LinkedList<Long>(); if ( fullRebuild ) { for ( long i = 1; i * getBlockSize() < fileSize; i++ ) { fileChannel.position( i * getBlockSize() ); fileChannel.read( byteBuffer ); byteBuffer.flip(); byte inUse = byteBuffer.get(); byteBuffer.flip(); nextBlockId(); if ( inUse == Record.NOT_IN_USE.byteValue() ) { freeIdList.add( i ); } else { highId = i; while ( !freeIdList.isEmpty() ) { freeBlockId( freeIdList.removeFirst() ); defraggedCount++; } } } } } catch ( IOException e ) { throw new UnderlyingStorageException( "Unable to rebuild id generator " + getStorageFileName(), e ); } setHighId( highId + 1 ); logger.fine( "[" + getStorageFileName() + "] high id=" + getHighId() + " (defragged=" + defraggedCount + ")" ); if ( getConfig() != null ) { String storeDir = (String) getConfig().get( "store_dir" ); StringLogger msgLog = StringLogger.getLogger( storeDir ); msgLog.logMessage( getStorageFileName() + " rebuild id generator, highId=" + getHighId() + " defragged count=" + defraggedCount, true ); } closeIdGenerator(); openIdGenerator(); } // @Override // protected void updateHighId() // try // long highId = getFileChannel().size() / getBlockSize(); // if ( highId > getHighId() ) // setHighId( highId ); // catch ( IOException e ) // throw new UnderlyingStorageException( e ); @Override protected long figureOutHighestIdInUse() { try { return getFileChannel().size()/getBlockSize(); } catch ( IOException e ) { throw new RuntimeException( e ); } } @Override public void logIdUsage( StringLogger logger ) { NeoStore.logIdUsage( logger, this ); } }
package com.ecyrd.jspwiki.tags; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.ServletException; import com.ecyrd.jspwiki.TextUtil; import com.ecyrd.jspwiki.providers.ProviderException; /** * Includes an another JSP page, making sure that we actually pass * the WikiContext correctly. * * @author Janne Jalkanen * @since 2.0 */ // FIXME: Perhaps unnecessary? public class IncludeTag extends WikiTagBase { private static final long serialVersionUID = 0L; protected String m_page; public void initTag() { super.initTag(); m_page = null; } public void setPage( String page ) { m_page = page; } public String getPage() { return m_page; } public final int doWikiStartTag() throws IOException, ProviderException { // WikiEngine engine = m_wikiContext.getEngine(); return SKIP_BODY; } public final int doEndTag() throws JspException { try { String page = m_wikiContext.getEngine().getTemplateManager().findJSP( pageContext, m_wikiContext.getTemplate(), m_page ); if( page == null ) { pageContext.getOut().println("No template file called '"+TextUtil.replaceEntities(m_page)+"'"); } else { pageContext.include( page ); } } catch( ServletException e ) { log.warn( "Including failed, got a servlet exception from sub-page. "+ "Rethrowing the exception to the JSP engine.", e ); throw new JspException( e.getMessage() ); } catch( IOException e ) { log.warn( "I/O exception - probably the connection was broken. "+ "Rethrowing the exception to the JSP engine.", e ); throw new JspException( e.getMessage() ); } return EVAL_PAGE; } }
package com.hpe.application.automation.tools.run; import com.hpe.application.automation.tools.mc.JobConfigurationProxy; import com.hpe.application.automation.tools.model.MCServerSettingsModel; import com.hpe.application.automation.tools.model.ProxySettings; import com.hpe.application.automation.tools.model.UploadAppModel; import com.hpe.application.automation.tools.model.UploadAppPathModel; import com.hpe.application.automation.tools.settings.MCServerSettingsBuilder; import com.hpe.application.automation.tools.sse.common.StringUtils; import hudson.Extension; import hudson.Launcher; import hudson.Util; import hudson.model.*; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import net.minidev.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class UploadAppBuilder extends Builder { private final UploadAppModel uploadAppModel; @DataBoundConstructor public UploadAppBuilder(String mcServerName, String mcUserName, String mcPassword, ProxySettings proxySettings, List<UploadAppPathModel> applicationPaths) { uploadAppModel = new UploadAppModel(mcServerName, mcUserName, mcPassword, proxySettings, applicationPaths); } @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl) super.getDescriptor(); } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { // get the mc server settings MCServerSettingsModel mcServerSettingsModel = getMCServerSettingsModel(); JobConfigurationProxy job = JobConfigurationProxy.getInstance(); JSONObject app = null; String mcServerUrl = ""; PrintStream out = listener.getLogger(); List<UploadAppPathModel> paths = null; if(uploadAppModel != null){ paths = uploadAppModel.getApplicationPaths(); } boolean allSuccess = true; if(mcServerSettingsModel == null){ out.println("Failed to upload app to MC server. Cause: MC url didn't be configured." ); return false; }else{ mcServerUrl = mcServerSettingsModel.getProperties().getProperty("MobileHostAddress"); out.println(String.format("There are %d apps to be uploaded.", paths.size())); String workspace = new File(build.getWorkspace().toURI()).getCanonicalPath(); for(int i=1; i<=paths.size(); i++){ String path = paths.get(i-1).getMcAppPath(); if(StringUtils.isNullOrEmpty(path)){ out.println(String.format("ignore the empty app %d upload", i)); continue; } //case insensitive replace of workspace to its real path path = path.replaceAll("(?i)"+ Pattern.quote("${WORKSPACE}"), Matcher.quoteReplacement(workspace)); try{ out.println(String.format("starting to upload app %d %s", i, path)); if(uploadAppModel.getProxySettings() == null){ app = job.upload(mcServerUrl, uploadAppModel.getMcUserName(),uploadAppModel.getMcPassword(), null, null, null, path); }else{ app = job.upload(mcServerUrl, uploadAppModel.getMcUserName(),uploadAppModel.getMcPassword(), uploadAppModel.getProxySettings().getFsProxyAddress(),uploadAppModel.getProxySettings().getFsProxyUserName(), uploadAppModel.getProxySettings().getFsProxyPassword(),path); } if(app == null){ if(uploadAppModel.isUseProxy()){ out.println(String.format("Failed to upload app, Cause MC connection info is incorrect. url:%s, username:%s, Proxy url:%s", mcServerUrl, uploadAppModel.getMcUserName(), uploadAppModel.getProxySettings().getFsProxyAddress())); }else if(uploadAppModel.isUseAuthentication()){ out.println(String.format("Failed to upload app, Cause MC connection info is incorrect. url:%s, username:%s, Proxy url:%s, proxy userName:%s", mcServerUrl, uploadAppModel.getMcUserName(), uploadAppModel.getProxySettings().getFsProxyAddress(), uploadAppModel.getProxySettings().getFsProxyUserName())); }else{ out.println(String.format("Failed to upload app, Cause MC connection info is incorrect. url:%s, username:%s,", mcServerUrl, uploadAppModel.getMcUserName())); } build.setResult(Result.FAILURE); return false; } if((Boolean)app.get("error")){ out.println("Job failed because got error message during the application uploading. " + app.toJSONString()); allSuccess = false; build.setResult(Result.FAILURE); } out.println("uploaded app info: " + app.toJSONString()); } catch(FileNotFoundException fnf){ out.println(String.format("Failed to upload app to MC server. Cause: File: %s is not found.", path)); build.setResult(Result.FAILURE); allSuccess = false; continue; } catch (IOException ioe) { Util.displayIOException(ioe, listener); build.setResult(Result.FAILURE); allSuccess = false; continue; } catch (InterruptedException e) { build.setResult(Result.ABORTED); return false; } catch (Exception e){ if(uploadAppModel.isUseProxy()){ out.println(String.format("Failed to upload app, Cause MC connection info is incorrect. url:%s, username:%s, Proxy url:%s", mcServerUrl, uploadAppModel.getMcUserName(), uploadAppModel.getProxySettings().getFsProxyAddress())); }else if(uploadAppModel.isUseAuthentication()){ out.println(String.format("Failed to upload app, Cause MC connection info is incorrect. url:%s, username:%s, Proxy url:%s, proxy userName:%s", mcServerUrl, uploadAppModel.getMcUserName(), uploadAppModel.getProxySettings().getFsProxyAddress(), uploadAppModel.getProxySettings().getFsProxyUserName())); }else{ out.println(String.format("Failed to upload app, Cause MC connection info is incorrect. url:%s, username:%s,", mcServerUrl, uploadAppModel.getMcUserName())); } build.setResult(Result.FAILURE); return false; } } } return allSuccess; } public MCServerSettingsModel getMCServerSettingsModel() { for (MCServerSettingsModel mcServer : getDescriptor().getMcServers()) { if (this.uploadAppModel != null && uploadAppModel.getMcServerName().equals(mcServer.getMcServerName())) { return mcServer; } } return null; } public UploadAppModel getUploadAppModel() { return uploadAppModel; } // This indicates to Jenkins that this is an implementation of an extension point @Extension public static final class DescriptorImpl extends BuildStepDescriptor<Builder> { public DescriptorImpl() { load(); } @Override public boolean isApplicable( @SuppressWarnings("rawtypes") Class<? extends AbstractProject> jobType) { return true; } @Override public String getDisplayName() { return "Upload app to Mobile Center"; } public boolean hasMCServers() { return Hudson.getInstance().getDescriptorByType( MCServerSettingsBuilder.MCDescriptorImpl.class).hasMCServers(); } public MCServerSettingsModel[] getMcServers() { return Hudson.getInstance().getDescriptorByType( MCServerSettingsBuilder.MCDescriptorImpl.class).getInstallations(); } } }
package com.javacook.testdatagenerator.testdatamodel; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.SimpleDateFormat; import java.util.*; /** * Ein Speicher, in den Objekte anhand eines Beanpfades (als Key) abgespeichert und gelesen werden koennen. */ public class BeanPathTree extends TreeMap<BeanPath, Object> { public final static Object NIL = new Object() { @Override public String toString() { return "NIL";} }; public BeanPathTree() { } public Object put(String beanPathStr, Object element, int... indices) { return super.put(new BeanPath(beanPathStr, indices), element); } public Object nil(BeanPath beanPath) { return super.put(beanPath, NIL); } public Object nil(String beanPathStr, int... indices) { return nil(new BeanPath(beanPathStr, indices)); } public Object get(String beanPathStr, int... indices) { final Object result = get(new BeanPath(beanPathStr, indices)); if (result == null) throw new IllegalStateException("The path '" + beanPathStr + "' is not assigned."); else if (result == NIL) return null; else return result; } public boolean isNil(String beanPathStr, int... indices) { return isNil(new BeanPath(beanPathStr, indices)); } /** * Der referenzierte Wert isNil, wenn er * 1. explizit auf NIL gesetzt wurde, * 2. aber auch wenn das Object nur aus Referenzen besteht, die ihrerseits isNil erfuellen. * Beispiel: * <pre> * kunde.name = NIL * kunde.vorname = NIL * </pre> * Dann gilt: * <pre> * isNil(kunde.name) == true * isNil(kunde.vorname) == true * isNil(kunde) == true // aber auch dies * </pre> * @param beanPath * @return */ public boolean isNil(BeanPath beanPath) { if (get(beanPath) == NIL) return true; final SortedMap<BeanPath, Object> map = subTreeAsSortedMap(beanPath); if (map.size() == 0) return false; for (BeanPath subBeanPath : map.keySet()) { if (!isNil(subBeanPath)) return false; } return true; } /** * Checks whether i consist only of NIL-Elements */ public boolean isNil() { for (BeanPath subBeanPath : keySet()) { if (!isNil(subBeanPath)) return false; } return true; } private SortedMap<BeanPath, Object> subTreeAsSortedMap(BeanPath beanPath) { final String LOWEST_IDENTIFIER = ""; final String UPPER_BOUND_IDENTIFIER = String.valueOf((char)127); // hoechstes ASCII DEL BeanPath beanPathLowerBound = new BeanPath(beanPath) .addBeanPathElement(new BeanPathElement(LOWEST_IDENTIFIER)); BeanPath beanPathUpperBound = new BeanPath(beanPath) .addBeanPathElement(new BeanPathElement(UPPER_BOUND_IDENTIFIER)); return subMap(beanPathLowerBound, beanPathUpperBound); } public String getString(String beanPathStr, int... indices) { Object result = null; try { result = get(beanPathStr, indices); return (String) result; } catch (ClassCastException e) { throw new ClassCastException(result.getClass().getName() + " '" + result + "' cannot be cast to java.lang.String"); } } public Integer getInteger(String beanPathStr, int... indices) { Object result = null; try { result = get(beanPathStr, indices); return (Integer) result; } catch (ClassCastException e) { throw new ClassCastException(result.getClass().getName() + " '" + result + "' cannot be cast to java.lang.Integer"); } } public <T extends Enum<T>> T getEnum(Class<T> clazz, String beanPathStr, int... indices) { return Enum.valueOf(clazz, getString(beanPathStr, indices)); } public Date getDate(String beanPathStr, int... indices) { Object result = null; try { result = get(beanPathStr, indices); return (Date) result; } catch (ClassCastException e) { throw new ClassCastException(result.getClass().getName() + " '" + result + "' cannot be cast to java.lang.Date"); } } public Set<BeanPathElement> subtreeRoots() { Set<BeanPathElement> result = new TreeSet<>(); for (BeanPath beanPath : keySet()) { if (beanPath.head() != null) { result.add(beanPath.head()); } } return result; } public BeanPathTree subtree(BeanPathElement beanPathElement) { final BeanPathTree beanPathSubTree = new BeanPathTree(); final SortedMap<BeanPath, Object> map = subTreeAsSortedMap(new BeanPath(beanPathElement)); for (BeanPath beanPath : map.keySet()) { beanPathSubTree.put(beanPath.tail(), get(beanPath)); } return beanPathSubTree; } public byte[] getByteArray(String beanPathStr, int... indices) { final String string = getString(beanPathStr, indices); return string.getBytes(); } public Calendar getCalendar(String beanPathStr, int... indices) { final Calendar result = Calendar.getInstance(); final Date date= getDate(beanPathStr, indices); if (date == null) return null; result.setTime(date); return result; } public Double getDouble(String beanPathStr, int... indices) { Object result = null; try { result = get(beanPathStr, indices); // Sonderfall, da Excel&Poi sich weigert, eine Double zu liefert, falls der Betrag ganzzahig ist if (result instanceof Integer) return (double)(int)result; return (Double)result; } catch (ClassCastException e) { throw new ClassCastException(result.getClass().getName() + " '" + result + "' cannot be cast to java.lang.Double"); } } public BigDecimal getBigDecimal(String beanPathStr, int... indices) { return new BigDecimal(getDouble(beanPathStr, indices)); } public BigDecimal getBigDecimal(int nachkommastellen, String beanPathStr, int... indices) { final BigDecimal bigDecimal = getBigDecimal(beanPathStr, indices); return bigDecimal.setScale(nachkommastellen, RoundingMode.HALF_UP); } /** * Ermittelt, wieviele Elemente ein Array hat, das durch <code>beanPathStr</code> * definiert wird. Dabei muss <code>beanPathStr</code> mit "[]"enden. Beispiel: * <pre> * beanPathStr = "kunde[].stammdaten.adressen[].hausnummern[]" * </pre> * Dann koennte der Aufruf lauten: * <pre> * arraySize(beanPathStr, 4, 3) * </pre> * D.h. die Groesse von <code>indices</code> muss um eins kleiner sein als die * Anzahl der eckigen Klammerpaare. * Besonderheit: Falls alle Array-Elemente NIL sind, soll das Ergebnis auch 0 sein. * @param beanPathStr * @param indices * @return */ public int arraySize(String beanPathStr, int... indices) { if (!beanPathStr.endsWith("[]")) { throw new IllegalArgumentException("Argument beanPathStr = '"+beanPathStr+"' does not reference an array."); } int[] lowerBound = Arrays.copyOf(indices, indices.length+1); int[] upperBound = Arrays.copyOf(indices, indices.length+1); int size = 0; do { lowerBound[indices.length] = size; upperBound[indices.length] = size+1; final BeanPath beanPathLower = new BeanPath(beanPathStr, lowerBound); final BeanPath beanPathUppper = new BeanPath(beanPathStr, upperBound); if (subMap(beanPathLower, beanPathUppper).size() == 0) break; size++; } while (true); // Besonderheit: falls alle Array-Elemente NIL sind, so soll die size auch 0 sein. for (int i = 0; i < size; i++) { final int[] extIndices = Arrays.copyOf(indices, indices.length + 1); extIndices[indices.length] = i; if (!isNil(beanPathStr, extIndices)) return size; } return 0; } /** * Marshalls the tree (structure and data) into a JSON-Object * @return a JSON object structured by means of the tree */ public JSONObject toJSON() { if (isEmpty()) return null; JSONObject jsonObject = new JSONObject(); LinkedHashMap<String, Object> elements = new LinkedHashMap<>(); for (BeanPathElement subTreeRoot : subtreeRoots()) { if (subTreeRoot.arrayIndex == null) { elements.put(subTreeRoot.attrName, subTreeRoot); } else { if (elements.get(subTreeRoot.attrName) == null) { final ArrayList<BeanPathElement> arrayElements = new ArrayList<>(); elements.put(subTreeRoot.attrName, arrayElements); } final List<BeanPathElement> arrayElements = (List) elements.get(subTreeRoot.attrName); arrayElements.add(subTreeRoot); } } for (String key : elements.keySet()) { final Object elemOrArray = elements.get(key); if (elemOrArray instanceof List) { List<BeanPathElement> arrayOfSubTreeRoots = (List)elemOrArray; final JSONArray jsonArray = new JSONArray(); for (BeanPathElement subTreeRoot : arrayOfSubTreeRoots) { final BeanPathTree subtree = subtree(subTreeRoot); if (subtree.isEmpty()) { final Object value = get(new BeanPath(subTreeRoot)); jsonArray.add(jsonRenderer(value)); } // Subtrees, die nur aus NILs bestehen, sollen nicht hinzugefuegt werden else if (!subtree.isNil()) { jsonArray.add(subtree.toJSON()); } } jsonObject.put(key, jsonArray); } else { BeanPathElement subTreeRoot = (BeanPathElement)elemOrArray; final BeanPathTree subtree = subtree(subTreeRoot); if (subtree.isEmpty()) { final Object value = get(new BeanPath(subTreeRoot)); jsonObject.put(key, jsonRenderer(value)); } // Subtrees, die nur aus NILs bestehen, sollen nicht hinzugefuegt werden else if (!subtree.isNil()) { jsonObject.put(key, subtree.toJSON()); } } } return jsonObject; } public static final String JSON_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssX"; public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(JSON_DATE_FORMAT) {{ setTimeZone(TimeZone.getTimeZone("UTC")); }}; protected Object jsonRenderer(Object excelCell) { if (excelCell == NIL) return null; if (excelCell instanceof Date) { return DATE_FORMAT.format((Date)excelCell); } return excelCell; } public static void main(String[] args) { BeanPathTree bpt = new BeanPathTree(); bpt.put("vorname[0].erst", "Jörg"); bpt.put("vorname[1].erst", "Peter"); bpt.put("vorname[2].erst", "Armin"); bpt.put("vorname[3].erst", "Claus"); bpt.nil("kunde.name[0]"); bpt.nil("kunde.name[1]"); bpt.nil("kunde.name[2]"); bpt.put("firma.adresse.plz", 58730); bpt.put("firma.adresse.ort", "Fröndenberg"); bpt.put("firma.adresse.strasse", "Brückenstr."); bpt.put("temp[0]", 123); bpt.put("temp[1]", 456); bpt.put("temp[2]", 789); bpt.put("datum", new Date()); // final NavigableMap<BeanPath, Object> map = bpt.subMap( // new BeanPath("kunde.vorname[0]"), true, // new BeanPath("kunde.vorname[oo]"), true); // System.out.println(map.size()); // System.out.println(bpt.arraySize("kunde.name[]")); // System.out.println(bpt.isNil("kunde.name")); // final Set<BeanPathElement> subtreeRoots = bpt.subtreeRoots(); // for (BeanPathElement subtreeRoot : subtreeRoots) { // System.out.println(bpt.subtree(subtreeRoot)); // final BeanPathElement next = bpt.subtreeRoots().iterator().next(); // final BeanPathTree subtree = bpt.subtree(next); // System.out.println(subtree); // final BeanPathElement next1 = subtree.subtreeRoots().iterator().next(); // final BeanPathTree subtree1 = subtree.subtree(next1); // final BeanPathElement next2 = subtree1.subtreeRoots().iterator().next(); // final BeanPathTree subtree2 = subtree1.subtree(next2); // System.out.println(next); // System.out.println(next1); // System.out.println(next2); // System.out.println(subtree1.get(new BeanPath(next2))); // System.out.println(subtree2.isEmpty()); System.out.println(bpt.toJSON()); } }
package com.haxademic.core.app; import java.awt.Robot; import java.awt.event.KeyEvent; import java.io.IOException; import javax.sound.midi.InvalidMidiDataException; import krister.Ess.AudioInput; import oscP5.OscMessage; import processing.core.PApplet; import processing.video.Movie; import toxi.processing.ToxiclibsSupport; import SimpleOpenNI.SimpleOpenNI; import com.haxademic.core.audio.AudioInputWrapper; import com.haxademic.core.audio.AudioInputWrapperMinim; import com.haxademic.core.audio.WaveformData; import com.haxademic.core.debug.DebugText; import com.haxademic.core.debug.DebugUtil; import com.haxademic.core.debug.Stats; import com.haxademic.core.draw.mesh.MeshPool; import com.haxademic.core.hardware.kinect.KinectWrapper; import com.haxademic.core.hardware.midi.MidiWrapper; import com.haxademic.core.hardware.osc.OscWrapper; import com.haxademic.core.hardware.webcam.WebCamWrapper; import com.haxademic.core.render.JoonsWrapper; import com.haxademic.core.render.MIDISequenceRenderer; import com.haxademic.core.render.Renderer; import com.haxademic.core.system.FileUtil; import com.haxademic.core.system.P5Properties; import com.haxademic.core.system.SystemUtil; import ddf.minim.Minim; import de.voidplus.leapmotion.LeapMotion; /** * PAppletHax is a starting point for interactive visuals, giving you a unified * environment for both realtime and rendering modes. It loads several Java * libraries and wraps them up to play nicely with each other, all within the * context of Haxademic. * * @TODO: Add better Processing lights() situation * @TODO: Refactor MIDI input for easier switching between ableton & akai pad control * @TODO: Add MIDI debug flag in .properties * @TODO: Mesh traversal drawing * @TODO: Handle MIDI CC / Allow more than just note_on messages from PAppletHax base. should be able to respond to any midi data * @TODO: Implement new viz ideas from sketchbook * @TODO: Add SVG animation class * @TODO: Create PGraphics & PImage audio-reactive textures to apply to meshes across sketches/apps. See SphereTextureMap and abstracts some of the goodness. !!! - add current texture and iVizTextureDraw classes to VizCollection Module * * @TODO: Use a static Haxademic.support( PApplet ) type static instance to let us gain access to the applet without passing it everywhere. Look at Geomerative & Toxiclibs to see how they did it. * @TODO: ^^^ General cleanup of PAppletHax references throughout codebase * @TODO: Make sure it's cool to post all the 3rd-party code within. potentially rewrite these bits * @TODO: Address garbage collection - a larger project would be to have dispose() methods in every class, and implement disposal across the project. * @TODO: Come up with a single solution to be an IVizModule or an extension of PAppletHax. * @TODO: optimize the kinectMesh element - shit is slow * @TODO: MIDI signals from rendering and live should be abstracted as MIDI message objects? * @TODO: Mesh traversal drawing: more configurable. generative options - implement mesh drawing strategy pattern * @TODO: Finish converting old modules into new Elements: AudioTubes, Blobsheet, cacheRings outer rings, GridEQ w/lines, MaxCache outer rings, PlusRing, more spheres * @TODO: Create more abstract user/hardware input system that routes different inputs into certain types of commands. * @TODO: Fix stepping through audio for WaveformData - this was hacked for BNC video rendering but shouldn't have to play & cue() the audio to capture the data * @TODO: Don't initialize MIDI object if not defined in run.properties. Will need to prevent attempting to detect MIDI input on handleKeyboardInput() methods * @TODO: Figure out camera perspective stretching issues in MasterHax * @TODO: Improve launchpad visuals * @TODO: Add launchpad back in without a secondary AudioInputWrapper * @TODO: Improve color selecting - use test sketch to figure out how to deal with color-traversing * @TODO: New elements: trails, supershapes, GEARS, particles * @TODO: add foreground/background modes to elements that could use them. * @TODO: Create good input system for building up MasterHax module over time & manage flow of Elements. * @TODO: create more complex uses of new Elements * @TODO: Refine existing elements * * @author cacheflowe * */ public class PAppletHax extends PApplet { private static final long serialVersionUID = 1L; /** * Global/static ref to PApplet - any audio-reactive object should be passed this reference, or grabbed from this static ref. */ protected static PAppletHax p; /** * Loads the project .properties file to configure several app properties externally. */ protected P5Properties _appConfig; // we should move to public instance public P5Properties appConfig; /** * Loads an app-specific project .properties file. */ protected String _customPropsFile = null; /** * Single instance of Toxiclibs object */ public ToxiclibsSupport toxi; /** * Single instance and wrapper for the ESS audio object. */ public AudioInputWrapper _audioInput; public AudioInputWrapperMinim audioIn; public boolean _useLegacyAudio = false; /** * Single instance of the data needed to draw a realtime waveform / oscilloscpe. */ public WaveformData _waveformData; /** * Renderer object for saving frames and rendering movies. */ public Renderer _renderer; public MIDISequenceRenderer _midiRenderer; /** * Wraps up MIDI functionality with theMIDIbus library. */ public MidiWrapper _midi = null; public MidiWrapper midi = null; /** * Loads and stores a pool of WETriangleMesh objects. */ public MeshPool meshPool = null; /** * Wraps up Kinect functionality. */ public KinectWrapper kinectWrapper = null; /** * Wraps up Leap Motion functionality. */ public LeapMotion leapMotion = null; /** * A secondary system of running the visuals on the Launchpad. This should probably be integrated into Modules? */ // public LaunchpadViz _launchpadViz = null; /** * Wraps up incoming OSC commands with the oscP5 library. */ public OscWrapper _oscWrapper = null; /** * Native Java object that simulates occasional keystrokes to prevent the system's screensaver from starting. */ protected Robot _robot; /** * Single instance for minim audio library. */ public Minim minim; protected Boolean _is_setup = false; /** * Override this in a subclass of PAppletHax in main() if you want to remove the window chrome. Must be published as an Application, not an Applet. */ protected static Boolean _hasChrome = true; /** * Override this in a subclass of PAppletHax in main() if you want to go full screen. Must be published as an Application, not an Applet. */ protected static Boolean _isFullScreen = false; /** * Executable's target frames per second. * This value is set in .properties file. */ public int _fps; /** * Stats debug class */ public Stats _stats; /** * Flag for showing stats */ public boolean _showStats; /** * Text for showing stats */ public DebugText _debugText; /** * Graphical render mode */ public String _graphicsMode; /** * Joons renderer wrapper */ protected JoonsWrapper _jw; /** * Helps the Renderer object work with minimal reconfiguration. Maybe this should be moved at some point... */ protected Boolean _isRendering = true; protected int _renderShutdown = -1; /** * Helps the Renderer object work without trying to read an audio file */ protected Boolean _isRenderingAudio = true; /** * Helps the Renderer object work without trying to read a MIDI file */ protected Boolean _isRenderingMidi = true; // OVERRIDE THE FOLLOWING METHODS /** * Called by PApplet to run before the first draw() command. */ public void setup () { P.p = p = this; if ( !_is_setup ) { // load external properties and set flag _appConfig = new P5Properties(p); appConfig = _appConfig; if( _customPropsFile != null ) _appConfig.loadPropertiesFile( _customPropsFile ); overridePropsFile(); _is_setup = true; // set screen size and renderer String renderer = P.OPENGL; if( _appConfig.getBoolean("fills_screen", false) == true || _appConfig.getBoolean("fullscreen", false) == true ) { p.size(displayWidth,displayHeight,renderer); } else { p.size(_appConfig.getInt("width", 800),_appConfig.getInt("height", 600),renderer); } } _graphicsMode = p.g.getClass().getName(); if( frame != null ) frame.setBackground(new java.awt.Color(0,0,0)); setAppletProps(); initHaxademicObjects(); } protected void overridePropsFile() { if( _customPropsFile == null ) P.println("YOU SHOULD OVERRIDE overridePropsFile()"); } protected void drawApp() { P.println("YOU MUST OVERRIDE drawApp()"); } public boolean sketchFullScreen() { return _isFullScreen; } protected void handleInput( boolean isMidi ) { // p.println("YOU MUST OVERRIDE KEYPRESSED"); if( isMidi == true ) { } else { // P.println("p.key = "+p.key); // audio gain // if ( p.key == '.' || _midi.midiPadIsOn( MidiWrapper.PAD_14 ) == 1 ) _audioInput.gainUp(); // if ( p.key == ',' || _midi.midiPadIsOn( MidiWrapper.PAD_13 ) == 1 ) _audioInput.gainDown(); if ( p.key == '.' && _audioInput != null ) _audioInput.gainUp(); if ( p.key == ',' && _audioInput != null ) _audioInput.gainDown(); if ( p.key == '.' && audioIn != null ) audioIn.gainUp(); if ( p.key == ',' && audioIn != null ) audioIn.gainDown(); } } /** * Sets some initial Applet properties for OpenGL quality, FPS, and nocursor(). */ protected void setAppletProps() { _isRendering = _appConfig.getBoolean("rendering", false); if( _isRendering == true ) DebugUtil.printErr("When rendering, make sure to call super.keyPressed(); for esc key shutdown"); _isRenderingAudio = _appConfig.getBoolean("render_audio", false); _isRenderingMidi = _appConfig.getBoolean("render_midi", false); _showStats = _appConfig.getBoolean("show_stats", false); if(_graphicsMode == P.OPENGL) { if( _isRendering == true ) { // prevents an error // hint(DISABLE_OPENGL_2X_SMOOTH); } else { // OpenGLUtil.setQuality(p, OpenGLUtil.HIGH); } } _fps = _appConfig.getInt("fps", 30); frameRate(_fps); if( _appConfig.getBoolean("hide_cursor", false) == true ) p.noCursor(); } public void init() { // frame only exists on Java Applications, not Applets if( frame != null && _hasChrome == false ) { frame.removeNotify(); frame.setUndecorated(true); frame.addNotify(); } super.init(); } /** * Initializes app-wide support objects for hardware interaction and rendering purposes. */ protected void initHaxademicObjects() { // save single reference for other objects toxi = new ToxiclibsSupport(p); minim = new Minim( p ); if( _useLegacyAudio == true ) { _audioInput = new AudioInputWrapper( p, _isRenderingAudio ); _waveformData = new WaveformData( p, _audioInput._bufferSize ); } else { audioIn = new AudioInputWrapperMinim( p, _isRenderingAudio ); _waveformData = new WaveformData( p, audioIn.bufferSize() ); } _renderer = new Renderer( p, _fps, Renderer.OUTPUT_TYPE_MOVIE, _appConfig.getString( "render_output_dir", FileUtil.getHaxademicOutputPath() ) ); if( _appConfig.getBoolean( "kinect_active", false ) == true ) { kinectWrapper = new KinectWrapper( p, _appConfig.getBoolean( "kinect_depth", true ), _appConfig.getBoolean( "kinect_rgb", true ), _appConfig.getBoolean( "kinect_depth_image", true ) ); kinectWrapper.setMirror( _appConfig.getBoolean( "kinect_mirrored", true ) ); } if( _appConfig.getBoolean( "leap_active", false ) == true ) leapMotion = new LeapMotion(this); // _launchpadViz = new LaunchpadViz( p5 ); if( _appConfig.getBoolean( "osc_active", false ) ) _oscWrapper = new OscWrapper( p ); meshPool = new MeshPool( p ); _jw = ( _appConfig.getBoolean("sunflow", true ) == true ) ? new JoonsWrapper( p, width, height, ( _appConfig.getString("sunflow_quality", "high" ) == "high" ) ? JoonsWrapper.QUALITY_HIGH : JoonsWrapper.QUALITY_LOW, ( _appConfig.getBoolean("sunflow_active", true ) == true ) ? true : false ) : null; _debugText = new DebugText( p ); if( _showStats == true ) _stats = new Stats( p ); try { _robot = new Robot(); } catch( Exception error ) { println("couldn't init Robot for screensaver disabling"); } } protected void initializeExtraObjectsOn1stFrame() { if( p.frameCount == 1 ){ P.println("Using Java version: "+SystemUtil.getJavaVersion()); if( _appConfig.getString("midi_device_in", "") != "" ) { _midi = new MidiWrapper( p, _appConfig.getString("midi_device_in", ""), _appConfig.getString("midi_device_out", "") ); midi = _midi; } } } public void draw() { //if( keyPressed ) handleInput( false ); // handles overall keyboard commands killScreensaver(); initializeExtraObjectsOn1stFrame(); // wait until draw() happens, to avoid weird launch crash if midi signals were coming in as haxademic starts handleRenderingStepthrough(); if( _audioInput != null ) _audioInput.getBeatDetection(); // detect beats and pass through to current visual module // int[] beatDetectArr = if( audioIn != null ) { audioIn.update(); // detect beats and pass through to current visual module // int[] beatDetectArr = _waveformData.updateWaveformDataMinim( audioIn.getAudioInput() ); } if( kinectWrapper != null ) kinectWrapper.update(); if( _jw != null ) _jw.startFrame(); drawApp(); if( _jw != null ) _jw.endFrame( _appConfig.getBoolean("sunflow_save_images", false) == true ); if( _isRendering == true || _renderShutdown > 1 ) { if( _renderShutdown == -1 ) { _renderer.renderFrame(); } else if( p.frameCount >= _renderShutdown + 1 ) { P.println("should exit!"); p.exit(); } } if( _showStats == true ) showStats(); } protected void showStats() { _stats.update(); _debugText.draw( "FPS: " + _fps + " :: ACTUAL FPS: " + _stats.getFps() ); // display some info if( p.frameCount % 60 == 0 ) { _stats.printStats(); DebugUtil.showMemoryUsage(); } } protected void handleRenderingStepthrough() { // analyze & init audio if stepping through a render if( _isRendering == true ) { if( p.frameCount == 1 ) { if( _isRenderingAudio == true ) { _renderer.startRendererForAudio( _appConfig.getString("render_audio_file", ""), _audioInput ); _audioInput.gainDown(); _audioInput.gainDown(); _audioInput.gainDown(); } else { _renderer.startRenderer(); } if( _isRenderingMidi == true ) { try { _midiRenderer = new MIDISequenceRenderer(p); _midiRenderer.loadMIDIFile( _appConfig.getString("render_midi_file", ""), _appConfig.getFloat("render_midi_bpm", 150f), _fps, _appConfig.getFloat("render_midi_offset", -8f) ); } catch (InvalidMidiDataException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } // if( p.frameCount > 1 ) { // have renderer step through audio, then special call to update the single WaveformData storage object if( _isRenderingAudio == true ) { _renderer.analyzeAudio(); _waveformData.updateWaveformDataForRender( _renderer, _audioInput.getAudioInput(), _audioInput._bufferSize ); } if( _midiRenderer != null ) { boolean doneCheckingForMidi = false; boolean triggered = false; while( doneCheckingForMidi == false ) { int rendererNote = _midiRenderer.checkForCurrentFrameNoteEvents(); if( rendererNote != -1 ) { noteOn( 0, rendererNote, 100 ); triggered = true; } else { doneCheckingForMidi = true; } } if( triggered == false && _midi != null ) _midi.allOff(); } } } protected void killScreensaver(){ // keep screensaver off - hit shift every 1000 frames if( p.frameCount % 1000 == 0 ) _robot.keyRelease(KeyEvent.VK_SHIFT); } /** * Called by PApplet as the keyboard input listener. */ public void keyPressed() { // disable esc key - subclass must call super.keyPressed() if( p.key == P.ESC && ( _appConfig.getBoolean("disable_esc", false) == true || _appConfig.getBoolean("rendering", false) == true ) ) { key = 0; if( _isRendering ) { _renderShutdown = p.frameCount; _renderer.stop(); P.println("shutting down"); } } handleInput( false ); } /** * Called by PApplet to shut down the Applet. * We stop rendering if applicable, and clean up hardware connections that might barf if left open. */ public void stop() { WebCamWrapper.dispose(); // if( _launchpadViz != null ) _launchpadViz.dispose(); if( kinectWrapper != null ) kinectWrapper.stop(); super.stop(); } /** * PApplet-level listener for Movie frame update events */ public void movieEvent(Movie m) { m.read(); } /** * PApplet-level listener for MIDIBUS noteOn call */ public void noteOn(int channel, int pitch, int velocity) { if( _midi != null ) { if( _midi.midiNoteIsOn( pitch ) == 0 ) { _midi.noteOn( channel, pitch, velocity ); try{ handleInput( true ); } catch( ArrayIndexOutOfBoundsException e ){println("noteOn BROKE!");} } } } /** * PApplet-level listener for MIDIBUS noteOff call */ public void noteOff(int channel, int pitch, int velocity) { if( _midi != null ) _midi.noteOff( channel, pitch, velocity ); } /** * PApplet-level listener for MIDIBUS CC signal */ public void controllerChange(int channel, int number, int value) { if( _midi != null ) _midi.controllerChange( channel, number, value ); } /** * PApplet-level listener for AudioInput data from the ESS library */ public void audioInputData(AudioInput theInput) { _audioInput.getFFT().getSpectrum(theInput); // if( _launchpadViz != null ) _launchpadViz.getAudio().getFFT().getSpectrum(theInput); _audioInput.detector.detect(theInput); _waveformData.updateWaveformData( theInput, _audioInput._bufferSize ); } /** * PApplet-level listener for OSC data from the oscP5 library */ public void oscEvent(OscMessage theOscMessage) { float oscValue = theOscMessage.get(0).floatValue(); String oscMsg = theOscMessage.addrPattern(); // PAppletHax.println(oscMsg+": "+oscValue); _oscWrapper.setOscMapItem(oscMsg, oscValue); try { if( oscValue > 0 ) { handleInput( true ); } } catch( ArrayIndexOutOfBoundsException e ){println("noteOn BROKE!");} } /** * PApplet-level listeners for LeapMotion events */ void leapOnInit(){ // println("Leap Motion Init"); } void leapOnConnect(){ // println("Leap Motion Connect"); } void leapOnFrame(){ // println("Leap Motion Frame"); } void leapOnDisconnect(){ // println("Leap Motion Disconnect"); } void leapOnExit(){ // println("Leap Motion Exit"); } /** * PApplet-level listeners for SimpleOpenNI user events */ public void onNewUser(SimpleOpenNI curContext,int userId) { println("onNewUser - userId: " + userId); println("\tstart tracking skeleton"); p.kinectWrapper.openni().startTrackingSkeleton(userId); } public void onLostUser( SimpleOpenNI curContext, int userId ) { println("onLostUser - userId: " + userId); } public void onVisibleUser( SimpleOpenNI curContext, int userId ) { // println("onVisibleUser - userId: " + userId); } /** * Getters / Setters */ public static PAppletHax getInstance(){ return p; } public ToxiclibsSupport getToxi(){ return toxi; } public AudioInputWrapper getAudio() { return _audioInput; } public MidiWrapper getMidi() { return _midi; } public OscWrapper getOsc() { return _oscWrapper; } public Minim getMinim() { return minim; } public int getFps() { return _fps; } public float getFpsFactor() { return 30f / _fps; } // public Boolean getIsAutopilot() { return _isAutoPilot; } }
package com.neon.intellij.plugins.gitlab.controller; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.wm.ToolWindow; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentFactory; import com.neon.intellij.plugins.gitlab.*; import com.neon.intellij.plugins.gitlab.controller.editor.GLIssueVirtualFile; import com.neon.intellij.plugins.gitlab.GetUsersTask; import com.neon.intellij.plugins.gitlab.model.gitlab.GIPIssue; import com.neon.intellij.plugins.gitlab.view.GitLabView; import javax.swing.*; import java.io.IOException; import java.util.function.Supplier; import java.util.logging.Logger; public class GLIController { private static final Logger LOGGER = Logger.getLogger( GLIController.class.getName() ); private final Project project; private final ToolWindow toolWindow; private final JBFacade jbFacade; public GLIController(final Project project, final ToolWindow toolWindow) { this.project = project; this.toolWindow = toolWindow; this.jbFacade = new JBFacade( project ); } public void run() { final GitLabView view = new GitLabView( this ); refresh( view ); ContentFactory contentFactory = ContentFactory.SERVICE.getInstance(); Content content = contentFactory.createContent( view, "", false ); toolWindow.getContentManager().addContent( content ); } public void openEditor( final GIPIssue issue ) { jbFacade.openEditor( new GLIssueVirtualFile( this, issue ) ); } public void closeEditor( final GLIssueVirtualFile vf ) { jbFacade.closeEditor(vf); } public GIPIssue saveIssue(final GIPIssue issue) throws IOException { // TODO: persist issue if ( issue.id <= 0 ) { // return glFacade.createIssue(issue); } else { // return glFacade.editIssue(issue); } return issue; } public GIPIssue deleteIssue(final GIPIssue issue) throws IOException { // TODO: delete gitlab issue return issue; // return glFacade.closeIssue( issue ); } public GIPIssue changeState(final GIPIssue issue, final String newState) throws IOException { // TODO: switch issue state // if ( GLIssueState.REOPEN.equals( newState ) ) { // return glFacade.openIssue(issue); // } else if ( GLIssueState.CLOSED.equals( newState ) ) { // return glFacade.closeIssue(issue); return issue; } public void refresh(GitLabView view) { final GitLabService gitLabService = new GitLabServiceSupplier(new ConnectionPropertiesSupplier()).get(); GIPGroupObserver groupObserver = group -> { SwingUtilities.invokeLater(() -> view.accept( group )); GIPProjectObserver projectObserver = project -> { SwingUtilities.invokeLater(() -> view.accept( project )); GetIssuesTask getIssuesTask = new GetIssuesTask(GLIController.this.project, gitLabService, issue -> SwingUtilities.invokeLater(() -> view.accept(issue)), project.id); ProgressManager.getInstance().run(getIssuesTask); }; GetProjectsTask getProjectsTask = new GetProjectsTask( project, gitLabService, projectObserver, group.id); ProgressManager.getInstance().run(getProjectsTask); }; ProgressManager.getInstance().run( new GetGroupsTask( project, gitLabService, groupObserver ) ); ProgressManager.getInstance().run( new GetUsersTask( project, gitLabService, view ) ); } }
package com.hp.hpl.jena.db.impl; import java.net.UnknownHostException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import com.hp.hpl.jena.db.IDBConnection; import com.hp.hpl.jena.db.RDFRDBException; import com.hp.hpl.jena.graph.Graph; import com.hp.hpl.jena.util.Log; public abstract class DriverRDB implements IRDBDriver { // Cutomization variables /** * This Graph's db properties */ protected DBPropDatabase m_dbProps; /** * Name of this class's PSet_TripleStore_XXX class */ protected String m_psetClassName; /** * Cached name of this class's SpecializedGraph_XXX class */ protected String m_lsetClassName; /** The class name of the database driver (e.g. jdbc.sql.class)*/ protected String DRIVER_NAME; // Dummy - needs replacing when instantiated? /** The name of the database type this driver supports */ protected String DATABASE_TYPE; /** The maximum size of literals that can be added to Statement table */ protected int MAX_LITERAL; /** The SQL type to use for storing ids (compatible with wrapDBID) */ protected String ID_SQL_TYPE; /** Set to true if the insert operations already check for duplications */ protected boolean SKIP_DUPLICATE_CHECK; /** Set to true if the insert operations allocate object IDs themselves */ protected boolean SKIP_ALLOCATE_ID; /** Holds value of empty literal marker */ protected String EMPTY_LITERAL_MARKER; /** The name of the sql definition file for this database/layout combo */ protected String SQL_FILE; /** The name of the sql definition file for this database/layout combo */ protected String DEFAULT_SQL_FILE = "etc/generic_generic.sql"; /** Set to true if the insert operations should be done using the "proc" versions */ protected boolean INSERT_BY_PROCEDURE; // Common variables /** * Holds base name of AssertedStatement table. * Every triple store has at least one tables for AssertedStatements. */ protected static final String ASSERTED_TABLE_BASE ="JENA_"; /** Set to true to enable cache of pre-prepared statements */ protected boolean CACHE_PREPARED_STATEMENTS = true; /** The name of the layout type this driver supports */ protected String LAYOUT_TYPE = "TripleStore"; /** Default name of the table that holds system property graph asserted statements **/ protected final String SYSTEM_PROP_TNAME = "JENA_SYS_STMTASSERTED"; /** Name of the grpah holding default properties (the one's that a newly-created * graph will have by default **/ protected final String DEFAULT_PROPS = "JENA_DEFAULT_GRAPH_PROPERTIES"; /** Driver version number */ protected final String VERSION = "2.0alpha"; // Instance variables /** * Instance of SQLCache used by Driver for hard-coded db commands */ protected SQLCache m_sql = null; /** * Each PSet_TripleStore_RDB instance is associated with a given * instance of DBPropPSet. */ private Hashtable m_NameMap = new Hashtable(); /** Cache a reference to the system property graph (java) **/ protected SpecializedGraph m_sysProperties = null; protected IDBConnection m_dbcon = null; // for transaction support // caches whether or not underlying connection supports transactions private Boolean m_transactionsSupported; /** flag to indicate that there is a transaction active on the associated connection */ protected boolean inTransaction = false; // Constructor /** * Create a bare instance of the driver. It is not functional until a * database connection has been supplied via setConnection. */ public DriverRDB() { } // Methods /** * Return the connection */ public IDBConnection getConnection() { return m_dbcon; } /** * Return the specialized graph used to store system properties. * (Constuct a new one if necessary). */ public SpecializedGraph getSystemSpecializedGraph() { if (m_sysProperties != null) { return m_sysProperties; } if( !isDBFormatOK() ) { // Format the DB return formatAndConstructSystemSpecializedGraph(); } // The database has already been formatted - just grab the properties IPSet pSet = createIPSetInstanceFromName(m_psetClassName); pSet.setASTname(SYSTEM_PROP_TNAME); m_sysProperties = createLSetInstanceFromName(m_lsetClassName, pSet); return m_sysProperties; } /** * Format the database and construct a brand new system specialized graph. */ protected SpecializedGraph formatAndConstructSystemSpecializedGraph() { try { m_sql.runSQLGroup("initDBtables"); m_sql.runSQLGroup("initDBgenerators"); m_sql.runSQLGroup("initDBprocedures"); } catch (SQLException e) { com.hp.hpl.jena.util.Log.warning("Problem formatting database", e); throw new RDFRDBException("Failed to format database", e); } // Construct the system properties IPSet pSet = createIPSetInstanceFromName(m_psetClassName); pSet.setASTname(SYSTEM_PROP_TNAME); m_sysProperties = createLSetInstanceFromName(m_lsetClassName, pSet); // The following call constructs a new set of database properties and // adds them to the m_sysProperties specialized graph. m_dbProps = new DBPropDatabase( m_sysProperties, createUniqueIdentifier(), m_dbcon.getDatabaseType(), VERSION, String.valueOf(MAX_LITERAL)); // Now we also need to construct the parameters that will be the // default settings for any graph added to this database new DBPropGraph( m_sysProperties, DEFAULT_PROPS, "generic"); return m_sysProperties; } /** * Construct and return a list of specialized graphs to match those in the store. * @param graphProperties A set of customization properties for the graph. */ public List recreateSpecializedGraphs(DBPropGraph graphProperties) { List result = new ArrayList(); Iterator it = graphProperties.getAllLSets(); while(it.hasNext() ) { DBPropLSet lSet = (DBPropLSet)it.next(); result.add(recreateSpecializedGraph( lSet )); } return result; } /** * Construct and return a new specialized graph. * @param graphProperties A set of customization properties for the specialized graph. */ public List createSpecializedGraphs(DBPropGraph graphProperties) { List result = new ArrayList(); // In the future we should do something more sophisticated, // but for now we keep things simple. // First choose a pSet to hold things - for now, assume a new // pSet for each new Graph DBPropPSet pSet = new DBPropPSet(m_sysProperties, "PSET_"+graphProperties.getName(), m_psetClassName); DBPropLSet lSet = new DBPropLSet(m_sysProperties, "LSET_"+graphProperties.getName(), m_lsetClassName); lSet.setPSet(pSet); graphProperties.addLSet(lSet); result.add(createSpecializedGraph(lSet)); return result; } private SpecializedGraph createLSetInstanceFromName(String lSetName, IPSet pset) { SpecializedGraph sg = null; try { Class cls = Class.forName(lSetName); Class[] params = {IPSet.class}; java.lang.reflect.Constructor con = cls.getConstructor(params); Object[] args = {pset}; sg = (SpecializedGraph) con.newInstance(args); } catch (Exception e) { Log.severe("Unable to create instance of SpecializedGraph " + e); } return sg; } /** * Create a new IPSet instance of the named implementation class and set the db connection. * * @param pName name of a class that implements IPSet. * @return an instance of the named class with the db connection set. */ private IPSet createIPSetInstanceFromName(String pName) { IPSet pSet = null; try { Class cls = Class.forName(pName); // get PSet pSet = (IPSet) Class.forName(pName).newInstance(); pSet.setDriver(this); pSet.setMaxLiteral(MAX_LITERAL); pSet.setSQLType(ID_SQL_TYPE); pSet.setSkipDuplicateCheck(SKIP_DUPLICATE_CHECK); pSet.setSkipAllocateId(SKIP_ALLOCATE_ID); pSet.setEmptyLiteralMarker(EMPTY_LITERAL_MARKER); pSet.setSQLCache(m_sql); pSet.setInsertByProcedure(INSERT_BY_PROCEDURE); pSet.setCachePreparedStatements(CACHE_PREPARED_STATEMENTS); } catch (Exception e) { Log.warning("Unable to create IPSet instance " + e); } return pSet; } /** * Create a new SpecializedGraph instance from properties. * * @param lProp logical property set. * @return an instance of a class that implements SpecializedGraph. */ public SpecializedGraph createSpecializedGraph(DBPropLSet lProp) { DBPropPSet pProp = lProp.getPset(); IPSet pset = findOrCreatePSet(pProp); SpecializedGraph g = null; try { // get SpecializedGraph Class cls = Class.forName(lProp.getType()); Class[] params2 = {IPSet.class}; java.lang.reflect.Constructor con = cls.getConstructor(params2); Object[] args2 = {pset}; g = (SpecializedGraph)con.newInstance(args2); } catch (Exception e) { Log.severe("createSpecializedGraph: " + e); } return g; } // static methods /** * adds the IPSet instance to the m_NameMap hash table, using the * name of the DBPropPSet as the key. */ protected void addPSet(String name, IPSet pSet){ m_NameMap.put(name, pSet); } /** * retrieves the IPSet instance to the m_NameMap hash table, using the * name of the DBPropPSet as the key. * @return IPSet that was found */ protected IPSet findPSet(String name){ return (IPSet) m_NameMap.get(name); } /** * Given the name of an instance of a class that implements IPSet, * find or create an instance of it. * (This name is obtained from the DBPropPSet instance.) * * @param pName is the name of the IPSet instance. * @return IPSet that was found or created */ public IPSet findOrCreatePSet(String pName){ IPSet pSet = findPSet(pName); if (pSet == null) { pSet = createIPSetInstanceFromName(m_psetClassName); pSet.setASTname(ASSERTED_TABLE_BASE+pName); addPSet(pName, pSet); } return pSet; } /** * Given an instance of DBPropPSet (PSet properties), * get the property set's name find or create an instance of it. * * @param pProp is the DBPropPSet instance to be * associated with the new IPSet. * * @return IPSet that was found or created */ public IPSet findOrCreatePSet(DBPropPSet pProp){ String pName = pProp.getName(); return findOrCreatePSet(pName); } /** * Construct and return a specialized graph that already exists in the db. * @param graphProperties * @return SpecializedGraph which was recreated. */ public SpecializedGraph recreateSpecializedGraph(DBPropLSet lProp) { return createSpecializedGraph(lProp); } /** * Remove the specialized graph, erasing all trace of a Graph. * @param graphId The identity of the Graph which these specialized graphs should hold * @param graphProperties The properties for the graph to be removed. */ public void removeSpecializedGraphs( DBPropGraph graphProperties, List specializedGraphs) { Iterator it = specializedGraphs.iterator(); while (it.hasNext()){ removeSpecializedGraph((SpecializedGraph) it.next()); } // remove from system properties table // It is sufficient just to remove the lSet properties (it will // take care of deleting any pset properties automatically). m_dbProps.removeGraph(graphProperties); } /** * Remove specialized graph from the datastore. * @param graph is the graph to be removed. */ private void removeSpecializedGraph(SpecializedGraph graph) { graph.clear(); } /** * Method setDatabaseProperties. * * Sets the current properties for the database. * * @param databaseProperties is a Graph containing a full set of database properties */ public void setDatabaseProperties(Graph databaseProperties) { SpecializedGraph toGraph = getSystemSpecializedGraph(); // really need to start a transaction here // Here add code to check if the database has been used - if so, // it's too late to change the properties, so throw an exception toGraph.clear(); SpecializedGraph.CompletionFlag complete = new SpecializedGraph.CompletionFlag(); toGraph.add(databaseProperties, complete); // Now test the properties to see if it's a valid set - if not, // throw an exception - it's okay to check some things later (there's // no guarantee that every error will be caught here). // end transaction here. } /** * Method getDefaultModelProperties * * Return the default properties for a new model stored in this database. * If none are stored, then load default properties into the database. * @return Graph containg the default properties for a new model */ public DBPropGraph getDefaultModelProperties() { SpecializedGraph sg = getSystemSpecializedGraph(); DBPropGraph result = DBPropGraph.findPropGraph(sg, DEFAULT_PROPS); if (result == null) { Log.severe("No default Model Properties found"); // Construct the parameters that will be the // default settings for any graph added to this database //new DBPropGraph( m_sysProperties, "default", "generic"); //result = DBPropGraph.findPropGraph(sg, "default"); } return result; } /** * Test if the database has previously been formatted. * * @return boolean true if database is correctly formatted, false on any error. */ public boolean isDBFormatOK() { boolean result = false; try { DatabaseMetaData dbmd = m_dbcon.getConnection().getMetaData(); String[] tableTypes = { "TABLE" }; ResultSet alltables = dbmd.getTables(null, null, "JENA%", tableTypes); result = alltables.next(); alltables.close(); } catch (Exception e1) { ;// if anything goes wrong, the database is not formatted correctly; } return result; } /* (non-Javadoc) * @see com.hp.hpl.jena.graphRDB.IRDBDriver#cleanDB() */ public void cleanDB() { try { DatabaseMetaData dbmd = m_dbcon.getConnection().getMetaData(); String[] tableTypes = { "TABLE" }; ResultSet alltables = dbmd.getTables(null, null, "JENA%", tableTypes); List tablesPresent = new ArrayList(10); while (alltables.next()) { tablesPresent.add(alltables.getString("TABLE_NAME").toUpperCase()); } alltables.close(); Iterator it = tablesPresent.iterator(); while (it.hasNext()) { m_sql.runSQLGroup("dropTable", (String) it.next()); } } catch (SQLException e1) { throw new RDFRDBException("Internal SQL error in driver", e1); } } /** * Initialise a database ready to store RDF tables. * @throws RDFDBException if the is a problem opening the connection or an internal SQL error. * @deprecated Since Jena 2.0 this call is no longer needed - formatting * happens automatically as a side effect of creating Models - there should * be no need for an application to interact directly with the driver. */ public void formatDB() throws RDFRDBException { } /** * Throws an UnsupportedOperation exception. * * @param opName name of the operation that's not supported. */ private void notSupported(String opName) { throw new UnsupportedOperationException(opName); } /** * If underlying database connection supports transactions, call abort() * on the connection, then turn autocommit on. */ public synchronized void abort() throws RDFRDBException { if (transactionsSupported()) { try { if (inTransaction) { Connection c = m_sql.getConnection(); c.rollback(); c.commit(); c.setAutoCommit(true); inTransaction = false; } } catch (SQLException e) { throw new RDFRDBException("Transaction support failed: ", e); } } else { } } /** * If the underlying database connection supports transactions, * turn autocommit off, then begin a new transaction. * Note that transactions are associated with connections, not with * Models. This */ public synchronized void begin() throws RDFRDBException { if (transactionsSupported()) { try { if (!inTransaction) { // Starting a transaction could require us to lose any cached prepared statements // for some jdbc drivers, currently I think all the drivers we use are safe and // is a major performance hit so commented out for now. m_sql.flushPreparedStatementCache(); Connection c = m_sql.getConnection(); c.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); c.setAutoCommit(false); inTransaction = true; } } catch (SQLException e) { throw new RDFRDBException("Transaction support failed: ", e); } } else { notSupported("begin transaction"); } } /** * If the underlying database connection supports transactions, * call commit(), then turn autocommit on. */ public void commit() throws RDFRDBException{ if (transactionsSupported()) { try { if (inTransaction) { Connection c = m_sql.getConnection(); c.commit(); c.setAutoCommit(true); c.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); inTransaction = false; } } catch (SQLException e) { throw new RDFRDBException("Transaction support failed: ", e); } } else { notSupported("commit transaction"); } } /** * Returns true if the underlying database supports transactions. */ public boolean transactionsSupported() { if (m_transactionsSupported != null) { return(m_transactionsSupported.booleanValue()); } if (m_dbcon != null) { try { Connection c = m_sql.getConnection(); if ( c != null) { m_transactionsSupported = new Boolean(c.getMetaData().supportsMultipleTransactions()); return(m_transactionsSupported.booleanValue()); } } catch (SQLException e) { Log.severe("SQL Exception caught " + e); } } return (false); } /** * Close the driver * * Nothing to do for now. * * @throws RDFDBException if there is an access problem * @deprecated Since Jena 2.0 this call is no longer required - just * close the DBConnection - there should be no need for an application * to interact directly with the driver. * */ public void close() throws RDFRDBException { } /** * Returns true if the database layout supports multiple RDF models * in the same database. * @deprecated Since Jena 2.0 all databases support multiple models. */ public boolean supportsMultipleModels() { return true; } /** * Returns true if the database layout supports implicit reification * of statements (i.e. statements can be treated as resources). * @deprecated Since Jena 2.0 the reification API has changed. The * new API is supported in all models, but the old Jena 1 API is no * longer supported. This call will return false to indicate * to old code that the old style of jena reification is not supported. */ public boolean supportsJenaReification() { return false; } /** * Create a unique identifier. * Use the local IP address and the date - this is not perfect, but * sufficient for our simple needs. * @return String identifier. */ static String createUniqueIdentifier() { String localhost; try { localhost = java.net.InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { localhost = "localhost"; } return localhost + "/" + (new Date()).getTime(); } }
package org.jboss.as.connector.subsystems.jca; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; import org.jboss.as.controller.ReloadRequiredWriteAttributeHandler; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.client.helpers.MeasurementUnit; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.threads.BoundedQueueThreadPoolResourceDefinition; import org.jboss.as.threads.ThreadsServices; import org.jboss.dmr.ModelType; import static org.jboss.as.connector.subsystems.jca.Constants.WORKMANAGER; import static org.jboss.as.connector.subsystems.jca.Constants.WORKMANAGER_LONG_RUNNING; import static org.jboss.as.connector.subsystems.jca.Constants.WORKMANAGER_SHORT_RUNNING; public class JcaWorkManagerDefinition extends SimpleResourceDefinition { protected static final PathElement PATH_WORK_MANAGER = PathElement.pathElement(WORKMANAGER); private final boolean registerRuntimeOnly; private JcaWorkManagerDefinition(final boolean registerRuntimeOnly) { super(PATH_WORK_MANAGER, JcaExtension.getResourceDescriptionResolver(PATH_WORK_MANAGER.getKey()), WorkManagerAdd.INSTANCE, ReloadRequiredRemoveStepHandler.INSTANCE); this.registerRuntimeOnly = registerRuntimeOnly; } public static JcaWorkManagerDefinition createInstance(final boolean registerRuntimeOnly) { return new JcaWorkManagerDefinition(registerRuntimeOnly); } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { super.registerAttributes(resourceRegistration); for (final WmParameters parameter : WmParameters.values()) { AttributeDefinition ad = parameter.getAttribute(); resourceRegistration.registerReadWriteAttribute(ad, null, new ReloadRequiredWriteAttributeHandler(ad)); } } @Override public void registerChildren(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerSubModel(BoundedQueueThreadPoolResourceDefinition.create(WORKMANAGER_SHORT_RUNNING, ThreadsServices.STANDARD_THREAD_FACTORY_RESOLVER, ThreadsServices.STANDARD_HANDOFF_EXECUTOR_RESOLVER, ThreadsServices.EXECUTOR.append(WORKMANAGER_SHORT_RUNNING), registerRuntimeOnly)); resourceRegistration.registerSubModel(BoundedQueueThreadPoolResourceDefinition.create(WORKMANAGER_LONG_RUNNING, ThreadsServices.STANDARD_THREAD_FACTORY_RESOLVER, ThreadsServices.STANDARD_HANDOFF_EXECUTOR_RESOLVER, ThreadsServices.EXECUTOR.append(WORKMANAGER_LONG_RUNNING), registerRuntimeOnly)); } public static enum WmParameters { NAME(SimpleAttributeDefinitionBuilder.create("name", ModelType.STRING) .setAllowExpression(false) .setAllowNull(false) .setMeasurementUnit(MeasurementUnit.NONE) .setRestartAllServices() .setXmlName("name") .build()); private WmParameters(SimpleAttributeDefinition attribute) { this.attribute = attribute; } public SimpleAttributeDefinition getAttribute() { return attribute; } private SimpleAttributeDefinition attribute; } }
package com.nhn.pinpoint.profiler.interceptor.bci; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.nhn.pinpoint.bootstrap.interceptor.*; import com.nhn.pinpoint.profiler.util.ApiUtils; import com.nhn.pinpoint.profiler.interceptor.*; import com.nhn.pinpoint.profiler.util.DepthScope; import com.nhn.pinpoint.profiler.util.JavaAssistUtils; import javassist.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author emeroad * @author netspider */ public class JavaAssistClass implements InstrumentClass { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final boolean isDebug = logger.isDebugEnabled(); private JavaAssistByteCodeInstrumentor instrumentor; private CtClass ctClass; private static final int STATIC_INTERCEPTOR = 0; private static final int SIMPLE_INTERCEPTOR = 1; private static final int NOT_DEFINE_INTERCEPTOR_ID = -1; public JavaAssistClass(JavaAssistByteCodeInstrumentor instrumentor, CtClass ctClass) { this.instrumentor = instrumentor; this.ctClass = ctClass; } public boolean isInterface() { return this.ctClass.isInterface(); } public String getName() { return this.ctClass.getName(); } @Override public boolean insertCodeBeforeConstructor(String[] args, String code) { try { CtConstructor constructor = getConstructor(args); constructor.insertBefore(code); return true; } catch (Exception e) { if (logger.isWarnEnabled()) { logger.warn(e.getMessage(), e); } return false; } } @Override public boolean insertCodeAfterConstructor(String[] args, String code) { try { CtConstructor constructor = getConstructor(args); constructor.insertAfter(code); return true; } catch (Exception e) { if (logger.isWarnEnabled()) { logger.warn(e.getMessage(), e); } return false; } } @Override public boolean insertCodeBeforeMethod(String methodName, String[] args, String code) { try { CtMethod method = getMethod(methodName, args); method.insertBefore(code); return true; } catch (Exception e) { if (logger.isWarnEnabled()) { logger.warn(e.getMessage(), e); } return false; } } @Override public boolean insertCodeAfterMethod(String methodName, String[] args, String code) { try { CtMethod method = getMethod(methodName, args); method.insertAfter(code); return true; } catch (Exception e) { if (logger.isWarnEnabled()) { logger.warn(e.getMessage(), e); } return false; } } public void addTraceVariable(String variableName, String setterName, String getterName, String variableType, String initValue) throws InstrumentException { addTraceVariable0(variableName, setterName, getterName, variableType, initValue); } public void addTraceVariable(String variableName, String setterName, String getterName, String variableType) throws InstrumentException { addTraceVariable0(variableName, setterName, getterName, variableType, null); } public void addTraceVariable0(String variableName, String setterName, String getterName, String variableType, String initValue) throws InstrumentException { try { CtClass type = instrumentor.getClassPool().get(variableType); CtField traceVariable = new CtField(type, variableName, ctClass); if (initValue == null) { ctClass.addField(traceVariable); } else { ctClass.addField(traceVariable, initValue); } if (setterName != null) { CtMethod setterMethod = CtNewMethod.setter(setterName, traceVariable); ctClass.addMethod(setterMethod); } if (getterName != null) { CtMethod getterMethod = CtNewMethod.getter(getterName, traceVariable); ctClass.addMethod(getterMethod); } } catch (NotFoundException e) { throw new InstrumentException(variableName + " addTraceVariable fail. Cause:" + e.getMessage(), e); } catch (CannotCompileException e) { throw new InstrumentException(variableName + " addTraceVariable fail. Cause:" + e.getMessage(), e); } } public int addConstructorInterceptor(String[] args, Interceptor interceptor) throws InstrumentException, NotFoundInstrumentException { if (interceptor == null) { throw new IllegalArgumentException("interceptor is null"); } final CtBehavior behavior = getBehavior(null, args, interceptor, NOT_DEFINE_INTERCEPTOR_ID); return addInterceptor0(behavior, null, interceptor, NOT_DEFINE_INTERCEPTOR_ID, Type.around, false); } public int addConstructorInterceptor(String[] args, Interceptor interceptor, Type type) throws InstrumentException, NotFoundInstrumentException { if (interceptor == null) { throw new IllegalArgumentException("interceptor is null"); } final CtBehavior behavior = getBehavior(null, args, interceptor, NOT_DEFINE_INTERCEPTOR_ID); return addInterceptor0(behavior, null, interceptor, NOT_DEFINE_INTERCEPTOR_ID, type, false); } public int addAllConstructorInterceptor(Interceptor interceptor) throws InstrumentException, NotFoundInstrumentException{ return addAllConstructorInterceptor(interceptor, Type.around); } public int addAllConstructorInterceptor(Interceptor interceptor, Type type) throws InstrumentException, NotFoundInstrumentException { if (interceptor == null) { throw new IllegalArgumentException("interceptor is null"); } final CtConstructor[] constructorList = ctClass.getConstructors(); final int length = constructorList.length; if (length == 0) { throw new NotFoundInstrumentException("Constructor not found."); } int interceptorId = 0; if (length > 0) { interceptorId = addInterceptor0(constructorList[0], null, interceptor, NOT_DEFINE_INTERCEPTOR_ID, type, false); } if (length > 1) { for (int i = 1; i< length; i++) { addInterceptor0(constructorList[i], null, null, interceptorId, Type.around, false); } } return interceptorId; } @Override public int addInterceptorCallByContextClassLoader(String methodName, String[] args, Interceptor interceptor) throws InstrumentException, NotFoundInstrumentException { if (interceptor == null) { throw new IllegalArgumentException("interceptor is null"); } final CtBehavior behavior = getBehavior(methodName, args, interceptor, NOT_DEFINE_INTERCEPTOR_ID); return addInterceptor0(behavior, methodName, interceptor, NOT_DEFINE_INTERCEPTOR_ID, Type.around, true); } @Override public int addInterceptorCallByContextClassLoader(String methodName, String[] args, Interceptor interceptor, Type type) throws InstrumentException, NotFoundInstrumentException { if (interceptor == null) { throw new IllegalArgumentException("interceptor is null"); } final CtBehavior behavior = getBehavior(methodName, args, interceptor, NOT_DEFINE_INTERCEPTOR_ID); return addInterceptor0(behavior, methodName, interceptor, NOT_DEFINE_INTERCEPTOR_ID, type, true); } @Override public int addInterceptor(String methodName, String[] args, Interceptor interceptor) throws InstrumentException, NotFoundInstrumentException { if (methodName == null) { throw new NullPointerException("methodName must not be null"); } if (interceptor == null) { throw new IllegalArgumentException("interceptor is null"); } final CtBehavior behavior = getBehavior(methodName, args, interceptor, NOT_DEFINE_INTERCEPTOR_ID); return addInterceptor0(behavior, methodName, interceptor, NOT_DEFINE_INTERCEPTOR_ID, Type.around, false); } @Override public int addScopeInterceptor(String methodName, String[] args, Interceptor interceptor, DepthScope scope) throws InstrumentException, NotFoundInstrumentException { if (methodName == null) { throw new NullPointerException("methodName must not be null"); } if (interceptor == null) { throw new IllegalArgumentException("interceptor is null"); } if (scope == null) { throw new NullPointerException("scope must not be null"); } interceptor = wrapScopeInterceptor(interceptor, scope); return addInterceptor(methodName, args, interceptor); } /* * (non-Javadoc) * @see com.nhn.pinpoint.profiler.interceptor.bci.InstrumentClass#addScopeInterceptorIfDeclared(java.lang.String, java.lang.String[], com.nhn.pinpoint.bootstrap.interceptor.Interceptor, com.nhn.pinpoint.profiler.util.DepthScope) */ @Override public int addScopeInterceptorIfDeclared(String methodName, String[] args, Interceptor interceptor, DepthScope scope) throws InstrumentException { if (methodName == null) { throw new NullPointerException("methodName must not be null"); } if (interceptor == null) { throw new IllegalArgumentException("interceptor is null"); } if (scope == null) { throw new NullPointerException("scope must not be null"); } if (hasDeclaredMethod(methodName, args)) { interceptor = wrapScopeInterceptor(interceptor, scope); return addInterceptor(methodName, args, interceptor); } else { if (logger.isWarnEnabled()) { logger.warn("Method is not declared. class={}, methodName={}, args={}", ctClass.getName(), methodName, Arrays.toString(args)); } return -1; } } private Interceptor wrapScopeInterceptor(Interceptor interceptor, DepthScope scope) { final Logger interceptorLogger = LoggerFactory.getLogger(interceptor.getClass()); if (interceptor instanceof SimpleAroundInterceptor) { if (interceptorLogger.isDebugEnabled()) { return new DebugScopeDelegateSimpleInterceptor((SimpleAroundInterceptor)interceptor, scope); } else { return new ScopeDelegateSimpleInterceptor((SimpleAroundInterceptor)interceptor, scope); } } else if (interceptor instanceof StaticAroundInterceptor) { if (interceptorLogger.isDebugEnabled()) { return new DebugScopeDelegateStaticInterceptor((StaticAroundInterceptor)interceptor, scope); } else { return new ScopeDelegateStaticInterceptor((StaticAroundInterceptor)interceptor, scope); } } throw new IllegalArgumentException("unknown Interceptor Type:" + interceptor.getClass()); } @Override public int reuseInterceptor(String methodName, String[] args, int interceptorId) throws InstrumentException, NotFoundInstrumentException { final CtBehavior behavior = getBehavior(methodName, args, null, interceptorId); return addInterceptor0(behavior, methodName, null, interceptorId, Type.around, false); } @Override public int reuseInterceptor(String methodName, String[] args, int interceptorId, Type type) throws InstrumentException, NotFoundInstrumentException { final CtBehavior behavior = getBehavior(methodName, args, null, interceptorId); return addInterceptor0(behavior, methodName, null, interceptorId, type, false); } @Override public int addInterceptor(String methodName, String[] args, Interceptor interceptor, Type type) throws InstrumentException, NotFoundInstrumentException { if (interceptor == null) { throw new IllegalArgumentException("interceptor is null"); } final CtBehavior behavior = getBehavior(methodName, args, interceptor, NOT_DEFINE_INTERCEPTOR_ID); return addInterceptor0(behavior, methodName, interceptor, NOT_DEFINE_INTERCEPTOR_ID, type, false); } private CtBehavior getBehavior(String methodName, String[] args) throws NotFoundException { if (methodName == null) { return getConstructor(args); } return getMethod(methodName, args); } private CtBehavior getBehavior(String methodName, String[] args, Interceptor interceptor, int interceptorId) throws NotFoundInstrumentException { try { return getBehavior(methodName, args); } catch (NotFoundException e) { // target method constructor NotFoundInstrumentException . if (interceptor == null) { throw new NotFoundInstrumentException(interceptorId + " add fail. Cause:" + e.getMessage(), e); } else { throw new NotFoundInstrumentException(interceptor.getClass().getSimpleName() + " add fail. Cause:" + e.getMessage(), e); } } } private int addInterceptor0(CtBehavior behavior, String methodName, Interceptor interceptor, int interceptorId, Type type, boolean useContextClassLoader) throws InstrumentException, NotFoundInstrumentException { try { if (interceptor != null) { if(interceptor instanceof StaticAroundInterceptor) { StaticAroundInterceptor staticAroundInterceptor = (StaticAroundInterceptor) interceptor; interceptorId = InterceptorRegistry.addInterceptor(staticAroundInterceptor); } else if(interceptor instanceof SimpleAroundInterceptor) { SimpleAroundInterceptor simpleAroundInterceptor = (SimpleAroundInterceptor) interceptor; interceptorId = InterceptorRegistry.addSimpleInterceptor(simpleAroundInterceptor); } else { throw new InstrumentException("unsupported Interceptor Type:" + interceptor); } // traceContext inject . if (interceptor instanceof TraceContextSupport) { ((TraceContextSupport)interceptor).setTraceContext(instrumentor.getAgent().getTraceContext()); } if (interceptor instanceof ByteCodeMethodDescriptorSupport) { setMethodDescriptor(behavior, (ByteCodeMethodDescriptorSupport) interceptor); } } else { interceptor = InterceptorRegistry.findInterceptor(interceptorId); } // aroundType type . if (interceptor instanceof StaticAroundInterceptor) { switch (type) { case around: addStaticAroundInterceptor(methodName, interceptorId, behavior, useContextClassLoader); break; case before: addStaticBeforeInterceptor(methodName, interceptorId, behavior, useContextClassLoader); break; case after: addStaticAfterInterceptor(methodName, interceptorId, behavior, useContextClassLoader); break; default: throw new UnsupportedOperationException("unsupport type"); } } else if(interceptor instanceof SimpleAroundInterceptor) { switch (type) { case around: addSimpleAroundInterceptor(methodName, interceptorId, behavior, useContextClassLoader); break; case before: addSimpleBeforeInterceptor(methodName, interceptorId, behavior, useContextClassLoader); break; case after: addSimpleAfterInterceptor(methodName, interceptorId, behavior, useContextClassLoader); break; default: throw new UnsupportedOperationException("unsupport type"); } } else { throw new IllegalArgumentException("unsupported"); } return interceptorId; } catch (NotFoundException e) { throw new InstrumentException(interceptor.getClass().getSimpleName() + " add fail. Cause:" + e.getMessage(), e); } catch (CannotCompileException e) { throw new InstrumentException(interceptor.getClass().getSimpleName() + "add fail. Cause:" + e.getMessage(), e); } } private void setMethodDescriptor(CtBehavior behavior, ByteCodeMethodDescriptorSupport interceptor) throws NotFoundException { DefaultMethodDescriptor methodDescriptor = new DefaultMethodDescriptor(); String methodName = behavior.getName(); methodDescriptor.setMethodName(methodName); methodDescriptor.setClassName(ctClass.getName()); CtClass[] ctParameterTypes = behavior.getParameterTypes(); String[] parameterTypes = JavaAssistUtils.getParameterType(ctParameterTypes); methodDescriptor.setParameterTypes(parameterTypes); String[] parameterVariableName = JavaAssistUtils.getParameterVariableName(behavior); methodDescriptor.setParameterVariableName(parameterVariableName); int lineNumber = JavaAssistUtils.getLineNumber(behavior); methodDescriptor.setLineNumber(lineNumber); String parameterDescriptor = ApiUtils.mergeParameterVariableNameDescription(parameterTypes, parameterVariableName); methodDescriptor.setParameterDescriptor(parameterDescriptor); String apiDescriptor = ApiUtils.mergeApiDescriptor(ctClass.getName(), methodName, parameterDescriptor); methodDescriptor.setApiDescriptor(apiDescriptor); interceptor.setMethodDescriptor(methodDescriptor); } private void addStaticAroundInterceptor(String methodName, int id, CtBehavior method, boolean useContextClassLoader) throws NotFoundException, CannotCompileException { addStaticBeforeInterceptor(methodName, id, method, useContextClassLoader); addStaticAfterInterceptor(methodName, id, method, useContextClassLoader); } private void addStaticBeforeInterceptor(String methodName, int id, CtBehavior behavior, boolean useContextClassLoader) throws CannotCompileException, NotFoundException { addBeforeInterceptor(methodName, id, behavior, useContextClassLoader, STATIC_INTERCEPTOR); } private void addStaticAfterInterceptor(String methodName, int interceptorId, CtBehavior behavior, boolean useContextClassLoader) throws NotFoundException, CannotCompileException { addAfterInterceptor(methodName, interceptorId, behavior, useContextClassLoader, STATIC_INTERCEPTOR); } private void addSimpleAroundInterceptor(String methodName, int interceptorId, CtBehavior behavior, boolean useContextClassLoader) throws NotFoundException, CannotCompileException { addSimpleBeforeInterceptor(methodName, interceptorId, behavior, useContextClassLoader); addSimpleAfterInterceptor(methodName, interceptorId, behavior, useContextClassLoader); } private void addSimpleBeforeInterceptor(String methodName, int interceptorId, CtBehavior behavior, boolean useContextClassLoader) throws NotFoundException, CannotCompileException { addBeforeInterceptor(methodName, interceptorId, behavior, useContextClassLoader, SIMPLE_INTERCEPTOR); } private void addSimpleAfterInterceptor(String methodName, int interceptorId, CtBehavior behavior, boolean useContextClassLoader) throws NotFoundException, CannotCompileException { addAfterInterceptor(methodName, interceptorId, behavior, useContextClassLoader, SIMPLE_INTERCEPTOR); } private void addAfterInterceptor(String methodName, int id, CtBehavior behavior, boolean useContextClassLoader, int interceptorType) throws NotFoundException, CannotCompileException { String returnType = getReturnType(behavior); String target = getTarget(behavior); String parameterTypeString = null; if (interceptorType == STATIC_INTERCEPTOR) { parameterTypeString = JavaAssistUtils.getParameterDescription(behavior.getParameterTypes()); } final String parameter = getParameter(behavior); final CodeBuilder after = new CodeBuilder(); if (useContextClassLoader) { after.begin(); beginAddFindInterceptorCode(id, after, interceptorType); // TODO getMethod . if (interceptorType == STATIC_INTERCEPTOR) { after.append(" java.lang.Class[] methodArgsClassParams = new Class[]{java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object[].class, java.lang.Object.class, java.lang.Throwable.class};"); } else { after.append(" java.lang.Class[] methodArgsClassParams = new Class[]{java.lang.Object.class, java.lang.Object[].class, java.lang.Object.class, java.lang.Throwable.class};"); } after.format(" java.lang.reflect.Method method = interceptor.getClass().getMethod(\"%1$s\", methodArgsClassParams);", "after"); if (interceptorType == STATIC_INTERCEPTOR) { after.format(" java.lang.Object[] methodParams = new java.lang.Object[] { %1$s, \"%2$s\", \"%3$s\", \"%4$s\", %5$s, %6$s, null };", target, ctClass.getName(), methodName, parameterTypeString, parameter, returnType); } else { after.format(" java.lang.Object[] methodParams = new java.lang.Object[] { %1$s, %2$s, %3$s, null };", target, parameter, returnType); } after.append(" method.invoke(interceptor, methodParams);"); endAddFindInterceptorCode(after); after.end(); } else { after.begin(); if (interceptorType == STATIC_INTERCEPTOR) { after.format(" %1$s interceptor = com.nhn.pinpoint.bootstrap.interceptor.InterceptorRegistry.getInterceptor(%2$d);", StaticAroundInterceptor.class.getName(), id); after.format(" interceptor.after(%1$s, \"%2$s\", \"%3$s\", \"%4$s\", %5$s, %6$s, null);", target, ctClass.getName(), methodName, parameterTypeString, parameter, returnType); } else { after.format(" %1$s interceptor = com.nhn.pinpoint.bootstrap.interceptor.InterceptorRegistry.getSimpleInterceptor(%2$d);", SimpleAroundInterceptor.class.getName(), id); after.format(" interceptor.after(%1$s, %2$s, %3$s, null);", target, parameter, returnType); } after.end(); } final String buildAfter = after.toString(); if (isDebug) { logger.debug("addAfterInterceptor after behavior:{} code:{}", behavior.getLongName(), buildAfter); } behavior.insertAfter(buildAfter); CodeBuilder catchCode = new CodeBuilder(); if (useContextClassLoader) { catchCode.begin(); beginAddFindInterceptorCode(id, catchCode, interceptorType); if(interceptorType == STATIC_INTERCEPTOR) { catchCode.append(" java.lang.Class[] methodArgsClassParams = new Class[]{java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object[].class, java.lang.Object.class, java.lang.Throwable.class};"); } else { catchCode.append(" java.lang.Class[] methodArgsClassParams = new Class[]{java.lang.Object.class, java.lang.Object[].class, java.lang.Object.class, java.lang.Throwable.class};"); } catchCode.format(" java.lang.reflect.Method method = interceptor.getClass().getMethod(\"%1$s\", methodArgsClassParams);", "after"); if (interceptorType == STATIC_INTERCEPTOR) { catchCode.format(" java.lang.Object[] methodParams = new java.lang.Object[] { %1$s, \"%2$s\", \"%3$s\", \"%4$s\", %5$s, null, $e };", target, ctClass.getName(), methodName, parameterTypeString, parameter); } else { catchCode.format(" java.lang.Object[] methodParams = new java.lang.Object[] { %1$s, %2$s, null, $e };", target, parameter); } catchCode.append(" method.invoke(interceptor, methodParams);"); endAddFindInterceptorCode(catchCode); catchCode.append(" throw $e;"); catchCode.end(); } else { catchCode.begin(); if (interceptorType == STATIC_INTERCEPTOR) { catchCode.format(" %1$s interceptor = com.nhn.pinpoint.bootstrap.interceptor.InterceptorRegistry.getInterceptor(%2$d);", StaticAroundInterceptor.class.getName(), id); catchCode.format(" interceptor.after(%1$s, \"%2$s\", \"%3$s\", \"%4$s\", %5$s, null, $e);", target, ctClass.getName(), methodName, parameterTypeString, parameter); } else { catchCode.format(" %1$s interceptor = com.nhn.pinpoint.bootstrap.interceptor.InterceptorRegistry.getSimpleInterceptor(%2$d);", SimpleAroundInterceptor.class.getName(), id); catchCode.format(" interceptor.after(%1$s, %2$s, null, $e);", target, parameter); } catchCode.append(" throw $e;"); catchCode.end(); } String buildCatch = catchCode.toString(); if (isDebug) { logger.debug("addAfterInterceptor catch behavior:{} code:{}", behavior.getLongName(), buildCatch); } CtClass th = instrumentor.getClassPool().get("java.lang.Throwable"); behavior.addCatch(buildCatch, th); } private void endAddFindInterceptorCode(CodeBuilder catchCode) { catchCode.format("}"); } private void beginAddFindInterceptorCode(int id, CodeBuilder after, int interceptorType) { after.append("java.lang.ClassLoader contextClassLoader = java.lang.Thread.currentThread().getContextClassLoader();"); after.append("if (contextClassLoader != null) {"); after.append(" java.lang.Class interceptorRegistryClass = contextClassLoader.loadClass(\"com.nhn.pinpoint.bootstrap.interceptor.InterceptorRegistry\");"); if (interceptorType == STATIC_INTERCEPTOR) { after.append(" java.lang.reflect.Method getInterceptorMethod = interceptorRegistryClass.getMethod(\"getInterceptor\", new java.lang.Class[]{ int.class });"); } else { after.append(" java.lang.reflect.Method getInterceptorMethod = interceptorRegistryClass.getMethod(\"getSimpleInterceptor\", new java.lang.Class[]{ int.class });"); } after.format(" java.lang.Object[] interceptorParams = new java.lang.Object[] { java.lang.Integer.valueOf(%1$d) };", id); after.format(" java.lang.Object interceptor = getInterceptorMethod.invoke(interceptorRegistryClass, interceptorParams);"); } private String getTarget(CtBehavior behavior) { boolean staticMethod = JavaAssistUtils.isStaticBehavior(behavior); if (staticMethod) { return "null"; } else { return "this"; } } public String getReturnType(CtBehavior behavior) throws NotFoundException { if (behavior instanceof CtMethod) { CtClass returnType = ((CtMethod) behavior).getReturnType(); if (CtClass.voidType == returnType) { return "null"; } } return "($w)$_"; } private void addBeforeInterceptor(String methodName, int id, CtBehavior behavior, boolean useContextClassLoader, int interceptorType) throws CannotCompileException, NotFoundException { String target = getTarget(behavior); String parameterDescription = null; if (interceptorType == STATIC_INTERCEPTOR) { parameterDescription = JavaAssistUtils.getParameterDescription(behavior.getParameterTypes()); } String parameter = getParameter(behavior); CodeBuilder code = new CodeBuilder(); if (useContextClassLoader) { code.begin(); // java.lang.ClassLoader contextClassLoader = java.lang.Thread.currentThread().getContextClassLoader(); // java.lang.Class<?> interceptorRegistryClass = contextClassLoader.loadClass("com.nhn.pinpoint.bootstrap.interceptor.InterceptorRegistry"); // java.lang.reflect.Method getInterceptorMethod = interceptorRegistryClass.getMethod("getInterceptor", int.class); // java.lang.Object interceptor = getInterceptorMethod.invoke(interceptorRegistryClass, 1); // java.lang.reflect.Method beforeMethod = interceptor.getClass().getMethod("before", java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object[].class); // beforeMethod.invoke(interceptor, null, null, null, null, null); beginAddFindInterceptorCode(id, code, interceptorType); if(interceptorType == STATIC_INTERCEPTOR) { code.append(" java.lang.Class[] beforeMethodParams = new Class[]{java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object[].class};"); } else { code.append(" java.lang.Class[] beforeMethodParams = new Class[]{java.lang.Object.class, java.lang.Object[].class};"); } code.format(" java.lang.reflect.Method beforeMethod = interceptor.getClass().getMethod(\"%1$s\", beforeMethodParams);", "before"); if(interceptorType == STATIC_INTERCEPTOR) { code.format(" java.lang.Object[] beforeParams = new java.lang.Object[] { %1$s, \"%2$s\", \"%3$s\", \"%4$s\", %5$s };", target, ctClass.getName(), methodName, parameterDescription, parameter); } else { code.format(" java.lang.Object[] beforeParams = new java.lang.Object[] { %1$s, %2$s };", target, parameter); } code.append(" beforeMethod.invoke(interceptor, beforeParams);"); code.append("}"); code.end(); } else { code.begin(); if (interceptorType == STATIC_INTERCEPTOR) { code.format(" %1$s interceptor = com.nhn.pinpoint.bootstrap.interceptor.InterceptorRegistry.getInterceptor(%2$d);", StaticAroundInterceptor.class.getName(), id); code.format(" interceptor.before(%1$s, \"%2$s\", \"%3$s\", \"%4$s\", %5$s);", target, ctClass.getName(), methodName, parameterDescription, parameter); } else { // simpleInterceptor typecasting . code.format(" %1$s interceptor = com.nhn.pinpoint.bootstrap.interceptor.InterceptorRegistry.getSimpleInterceptor(%2$d);", SimpleAroundInterceptor.class.getName(), id); code.format(" interceptor.before(%1$s, %2$s);", target, parameter); } code.end(); } String buildBefore = code.toString(); if (isDebug) { logger.debug("addStaticBeforeInterceptor catch behavior:{} code:{}", behavior.getLongName(), buildBefore); } if (behavior instanceof CtConstructor) { ((CtConstructor) behavior).insertBeforeBody(buildBefore); } else { behavior.insertBefore(buildBefore); } } private String getParameter(CtBehavior behavior) throws NotFoundException { CtClass[] parameterTypes = behavior.getParameterTypes(); if (parameterTypes.length == 0) { return "null"; } return "$args"; } public boolean addDebugLogBeforeAfterMethod() { String className = this.ctClass.getName(); LoggingInterceptor loggingInterceptor = new LoggingInterceptor(className); int id = InterceptorRegistry.addInterceptor(loggingInterceptor); try { CtClass cc = this.instrumentor.getClassPool().get(className); CtMethod[] methods = cc.getDeclaredMethods(); for (CtMethod method : methods) { if (method.isEmpty()) { if (isDebug) { logger.debug("{} is empty.", method.getLongName()); } continue; } String methodName = method.getName(); // TODO method prameter type interceptor . String params = getParamsToString(method.getParameterTypes()); addStaticAroundInterceptor(methodName, id, method, false); } return true; } catch (Exception e) { if (logger.isWarnEnabled()) { logger.warn(e.getMessage(), e); } } return false; } /** * . bytecode . * * @return */ @Deprecated public boolean addDebugLogBeforeAfterConstructor() { String className = this.ctClass.getName(); LoggingInterceptor loggingInterceptor = new LoggingInterceptor(className); int id = InterceptorRegistry.addInterceptor(loggingInterceptor); try { CtClass cc = this.instrumentor.getClassPool().get(className); CtConstructor[] constructors = cc.getConstructors(); for (CtConstructor constructor : constructors) { if (constructor.isEmpty()) { if (isDebug) { logger.debug("{} is empty.", constructor.getLongName()); } continue; } String constructorName = constructor.getName(); String params = getParamsToString(constructor.getParameterTypes()); // constructorName + " Constructor:Param=(" + params + // ") is finished. \" + $args);}"); // constructorName + " Constructor:Param=(" + params + // ") is finished.\"); throw $e; }" // , instrumentor.getClassPool().get("java.lang.Throwable")); addStaticAroundInterceptor(constructorName, id, constructor, false); } return true; } catch (Exception e) { if (logger.isWarnEnabled()) { logger.warn(e.getMessage(), e); } } return false; } private String getParamsToString(CtClass[] params) throws NotFoundException { StringBuilder sb = new StringBuilder(512); if (params.length != 0) { int paramsLength = params.length; for (int loop = paramsLength - 1; loop > 0; loop sb.append(params[loop].getName()).append(","); } } String paramsStr = sb.toString(); if (isDebug) { logger.debug("params type:{}", paramsStr); } return paramsStr; } private CtMethod getMethod(String methodName, String[] args) throws NotFoundException { CtClass[] params = JavaAssistUtils.getCtParameter(args, instrumentor.getClassPool()); // cttime method . return ctClass.getDeclaredMethod(methodName, params); } private CtConstructor getConstructor(String[] args) throws NotFoundException { CtClass[] params = JavaAssistUtils.getCtParameter(args, instrumentor.getClassPool()); return ctClass.getDeclaredConstructor(params); } @Override public byte[] toBytecode() { try { byte[] bytes = ctClass.toBytecode(); ctClass.detach(); return bytes; } catch (IOException e) { logger.info("IoException class:{} Caused:{}", ctClass.getName(), e.getMessage(), e); } catch (CannotCompileException e) { logger.info("CannotCompileException class:{} Caused:{}", ctClass.getName(), e.getMessage(), e); } return null; } public Class<?> toClass() throws InstrumentException { try { return ctClass.toClass(); } catch (CannotCompileException e) { throw new InstrumentException( "CannotCompileException class:" + ctClass.getName() + " " + e.getMessage(), e); } } public List<Method> getDeclaredMethods() throws NotFoundInstrumentException { return getDeclaredMethods(SkipMethodFilter.FILTER); } public List<Method> getDeclaredMethods(MethodFilter methodFilter) throws NotFoundInstrumentException { if (methodFilter == null) { throw new NullPointerException("methodFilter must not be null"); } try { final CtMethod[] declaredMethod = ctClass.getDeclaredMethods(); final List<Method> candidateList = new ArrayList<Method>(declaredMethod.length); for (CtMethod ctMethod : declaredMethod) { if (methodFilter.filter(ctMethod)) { continue; } String methodName = ctMethod.getName(); CtClass[] paramTypes = ctMethod.getParameterTypes(); String[] parameterType = JavaAssistUtils.getParameterType(paramTypes); Method method = new Method(methodName, parameterType); candidateList.add(method); } return candidateList; } catch (NotFoundException e) { throw new NotFoundInstrumentException("getDeclaredMethods(), Caused:" + e.getMessage(), e); } } public boolean isInterceptable() { return !ctClass.isInterface() && !ctClass.isAnnotation() && !ctClass.isModified(); } @Override public boolean hasDeclaredMethod(String methodName, String[] args) { try { CtClass[] params = JavaAssistUtils.getCtParameter(args, instrumentor.getClassPool()); CtMethod m = ctClass.getDeclaredMethod(methodName, params); return m != null; } catch (NotFoundException e) { return false; } } /** * String methodName, String desc . . * @param methodName * @param args * @return */ @Override public boolean hasMethod(String methodName, String[] args) { final String parameterDescription = JavaAssistUtils.getParameterDescription(args); final CtMethod[] methods = ctClass.getMethods(); for (CtMethod method : methods) { if (methodName.equals(method.getName()) && method.getMethodInfo2().getDescriptor().startsWith(parameterDescription)) { return true; } } return false; } @Override public boolean hasMethod(String methodName, String desc) { try { CtMethod m = ctClass.getMethod(methodName, desc); return m != null; } catch (NotFoundException e) { return false; } } @Override public InstrumentClass getNestedClass(String className) { try { CtClass[] nestedClasses = ctClass.getNestedClasses(); if (nestedClasses == null || nestedClasses.length == 0) { return null; } for (CtClass nested : nestedClasses) { if (nested.getName().equals(className)) { return new JavaAssistClass(this.instrumentor, nested); } } } catch (NotFoundException e) { return null; } return null; } @Override public void addGetter(String getterName, String variableName, String variableType) throws InstrumentException { try { // FIXME getField, getDeclaredField . getter getField . CtField traceVariable = ctClass.getField(variableName); CtMethod getterMethod = CtNewMethod.getter(getterName, traceVariable); ctClass.addMethod(getterMethod); } catch (NotFoundException ex) { throw new InstrumentException(variableName + " addVariableAccessor fail. Cause:" + ex.getMessage(), ex); } catch (CannotCompileException ex) { throw new InstrumentException(variableName + " addVariableAccessor fail. Cause:" + ex.getMessage(), ex); } } }
// Package package com.hp.hpl.jena.ontology; // Imports import com.hp.hpl.jena.rdf.model.*; import com.hp.hpl.jena.util.iterator.ExtendedIterator; /** * <p> * Interface that represents an ontology node characterising a class description. * </p> * * @author Ian Dickinson, HP Labs * (<a href="mailto:Ian.Dickinson@hp.com" >email</a>) * @version CVS $Id: OntClass.java,v 1.34 2009-04-23 08:45:06 ian_dickinson Exp $ */ public interface OntClass extends OntResource { // Constants // External signature methods // Enumerated class constructor // subClassOf /** * <p>Assert that this class is sub-class of the given class. Any existing * statements for <code>subClassOf</code> will be removed.</p> * @param cls The class that this class is a sub-class of * @exception OntProfileException If the {@link Profile#SUB_CLASS_OF()} property is not supported in the current language profile. */ public void setSuperClass( Resource cls ); /** * <p>Add a super-class of this class.</p> * @param cls A class that is a super-class of this class. * @exception OntProfileException If the {@link Profile#SUB_CLASS_OF()} property is not supported in the current language profile. */ public void addSuperClass( Resource cls ); /** * <p>Answer a class that is the super-class of this class. If there is * more than one such class, an arbitrary selection is made. If there * is no such super-class, return null.</p> * @return A super-class of this class or null * @exception OntProfileException If the {@link Profile#SUB_CLASS_OF()} * property is not supported in the current language profile. */ public OntClass getSuperClass(); /** * <p>Answer an iterator over all of the classes that are super-classes of * this class. Each element of the iterator will be an {@link OntClass}.</p> * @return An iterator over the super-classes of this class. * @exception OntProfileException If the {@link Profile#SUB_CLASS_OF()} property is not supported in the current language profile. */ public ExtendedIterator<OntClass> listSuperClasses(); /** * <p>Answer an iterator over all of the classes that are super-classes of * this class. Each element of the iterator will be an {@link OntClass}. * See {@link #listSubClasses( boolean )} for a full explanation of the <em>direct</em> * parameter. * </p> * * @param direct If true, only answer the directly adjacent classes in the * super-class relation: i&#046;e&#046; eliminate any class for which there is a longer route * to reach that child under the super-class relation. * @return an iterator over the resources representing this class's sub-classes. * @exception OntProfileException If the {@link Profile#SUB_CLASS_OF()} property is not supported in the current language profile. */ public ExtendedIterator<OntClass> listSuperClasses( boolean direct ); /** * <p>Answer true if the given class is a super-class of this class.</p> * @param cls A class to test. * @return True if the given class is a super-class of this class. * @exception OntProfileException If the {@link Profile#SUB_CLASS_OF()} property is not supported in the current language profile. */ public boolean hasSuperClass( Resource cls ); /** * <p>Answer true if this class has any super-class in the model. Note that * when using a reasoner, all OWL classes have owl:Thing as a super-class.</p> * @return True if this class has any known super-class. * @exception OntProfileException If the {@link Profile#SUB_CLASS_OF()} property is not supported in the current language profile. */ public boolean hasSuperClass(); /** * <p>Answer true if the given class is a super-class of this class. * See {@link #listSubClasses( boolean )} for a full explanation of the <em>direct</em> * parameter. * </p> * @param cls A class to test. * @param direct If true, only search the classes that are directly adjacent to this * class in the class hierarchy. * @return True if the given class is a super-class of this class. * @exception OntProfileException If the {@link Profile#SUB_CLASS_OF()} property is not supported in the current language profile. */ public boolean hasSuperClass( Resource cls, boolean direct ); /** * <p>Remove the given class from the super-classes of this class. If this statement * is not true of the current model, nothing happens.</p> * @param cls A class to be removed from the super-classes of this class * @exception OntProfileException If the {@link Profile#SUB_CLASS_OF()} class is not supported in the current language profile. */ public void removeSuperClass( Resource cls); /** * <p>Assert that this class is super-class of the given class. Any existing * statements for <code>subClassOf</code> on <code>prop</code> will be removed.</p> * @param cls The class that is a sub-class of this class * @exception OntProfileException If the {@link Profile#SUB_CLASS_OF()} property is not supported in the current language profile. */ public void setSubClass( Resource cls ); /** * <p>Add a sub-class of this class.</p> * @param cls A class that is a sub-class of this class. * @exception OntProfileException If the {@link Profile#SUB_CLASS_OF()} property is not supported in the current language profile. */ public void addSubClass( Resource cls ); /** * <p>Answer a class that is the sub-class of this class. If there is * more than one such class, an arbitrary selection is made. If * there is no such class, return null.</p> * @return A sub-class of this class or null * @exception OntProfileException If the {@link Profile#SUB_CLASS_OF()} * property is not supported in the current language profile. */ public OntClass getSubClass(); /** * <p>Answer an iterator over all of the classes that are declared to be sub-classes of * this class. Each element of the iterator will be an {@link OntClass}.</p> * @return An iterator over the sub-classes of this class. * @exception OntProfileException If the {@link Profile#SUB_CLASS_OF()} property is not supported in the current language profile. */ public ExtendedIterator<OntClass> listSubClasses(); /** * <p> * Answer an iterator over the classes that are declared to be sub-classes of * this class. Each element of the iterator will be an {@link OntClass}. The * distinguishing extra parameter for this method is the flag <code>direct</code> * that allows some selectivity over the classes that appear in the iterator. * Consider the following scenario: * <code><pre> * :B rdfs:subClassOf :A. * :C rdfs:subClassOf :A. * :D rdfs:subClassof :C. * </pre></code> * (so A has two sub-classes, B and C, and C has sub-class D). In a raw model, with * no inference support, listing the sub-classes of A will answer B and C. In an * inferencing model, <code>rdfs:subClassOf</code> is known to be transitive, so * the sub-classes iterator will include D. The <code>direct</code> sub-classes * are those members of the closure of the subClassOf relation, restricted to classes that * cannot be reached by a longer route, i.e. the ones that are <em>directly</em> adjacent * to the given root. Thus, the direct sub-classes of A are B and C only, and not D - * even in an inferencing graph. Note that this is not the same as the entailments * from the raw graph. Suppose we add to this example: * <code><pre> * :D rdfs:subClassof :A. * </pre></code> * Now, in the raw graph, A has sub-class C. But the direct sub-classes of A remain * B and C, since there is a longer path A-C-D that means that D is not a direct sub-class * of A. The assertion in the raw graph that A has sub-class D is essentially redundant, * since this can be inferred from the closure of the graph. * </p> * <p> * <strong>Note:</strong> This is is a change from the behaviour of Jena 1, which took a * parameter <code>closed</code> to compute the closure over transitivity and equivalence * of sub-classes. The closure capability in Jena2 is determined by the inference engine * that is wrapped with the ontology model. The direct parameter is provided to allow, * for example, a level-by-level traversal of the class hierarchy, starting at some given * root. Observe that in Jena 1, passing <code>true</code> will tend to increase the number of * results returned; in Jena 2 passing <code>true</code> will tend to reduce the number * of results. * </p> * * @param direct If true, only answer the directly adjacent classes in the * sub-class relation: i&#046;e&#046; eliminate any class for which there is a longer route * to reach that child under the sub-class relation. * @return an iterator over the resources representing this class's sub-classes * @exception OntProfileException If the {@link Profile#SUB_CLASS_OF()} property is not supported in the current language profile. */ public ExtendedIterator<OntClass> listSubClasses( boolean direct ); /** * <p>Answer true if the given class is a sub-class of this class.</p> * @param cls A class to test. * @return True if the given class is a sub-class of this class. * @exception OntProfileException If the {@link Profile#SUB_CLASS_OF()} property is not supported in the current language profile. */ public boolean hasSubClass( Resource cls ); /** * <p>Answer true if this class has any sub-class in the model. Note that * when using a reasoner, all OWL classes have owl:Nothing as a sub-class.</p> * @return True if this class has any known sub-class. * @exception OntProfileException If the {@link Profile#SUB_CLASS_OF()} property is not supported in the current language profile. */ public boolean hasSubClass(); /** * <p>Answer true if the given class is a sub-class of this class. * See {@link #listSubClasses( boolean )} for a full explanation of the <em>direct</em> * parameter. * </p> * @param cls A class to test. * @param direct If true, only search the classes that are directly adjacent to this * class in the class hierarchy. * @return True if the given class is a sub-class of this class. * @exception OntProfileException If the {@link Profile#SUB_CLASS_OF()} property is not supported in the current language profile. */ public boolean hasSubClass( Resource cls, boolean direct ); /** * <p>Remove the given class from the sub-classes of this class. If this statement * is not true of the current model, nothing happens.</p> * @param cls A class to be removed from the sub-classes of this class * @exception OntProfileException If the {@link Profile#SUB_CLASS_OF()} class is not supported in the current language profile. */ public void removeSubClass( Resource cls ); // equivalentClass /** * <p>Assert that the given class is equivalent to this class. Any existing * statements for <code>equivalentClass</code> will be removed.</p> * @param cls The class that this class is a equivalent to. * @exception OntProfileException If the {@link Profile#EQUIVALENT_CLASS()} property is not supported in the current language profile. */ public void setEquivalentClass( Resource cls ); /** * <p>Add a class that is equivalent to this class.</p> * @param cls A class that is equivalent to this class. * @exception OntProfileException If the {@link Profile#EQUIVALENT_CLASS()} property is not supported in the current language profile. */ public void addEquivalentClass( Resource cls ); /** * <p>Answer a class that is equivalent to this class. If there is * more than one such class, an arbitrary selection is made. * See {@link #listEquivalentClasses()} for a note on equivalent classes * when using a reasoner. * </p> * @return A class equivalent to this class * @exception OntProfileException If the {@link Profile#EQUIVALENT_CLASS()} property is not supported in the current language profile. */ public OntClass getEquivalentClass(); /** * <p>Answer an iterator over all of the classes that are known to be equivalent to * this class. Equivalence may be asserted in the model (using, for example, * <code>owl:equivalentClass</code>, or may be inferred by the reasoner attached to the * model. <strong>Note</strong> that the OWL semantics entails that every class is * equivalent to itself, so when using a reasoning model clients should expect that * this class will appear as a member of its own equivalent classes.</p><p> * Each element of the returned iterator will be an {@link OntClass}.</p> * @return An iterator over the classes equivalent to this class. * @exception OntProfileException If the {@link Profile#EQUIVALENT_CLASS()} property is not supported in the current language profile. */ public ExtendedIterator<OntClass> listEquivalentClasses(); /** * <p>Answer true if the given class is equivalent to this class.</p> * @param cls A class to test for * @return True if the given property is equivalent to this class. * @exception OntProfileException If the {@link Profile#EQUIVALENT_CLASS()} property is not supported in the current language profile. */ public boolean hasEquivalentClass( Resource cls ); /** * <p>Remove the statement that this class and the given class are * equivalent. If this statement * is not true of the current model, nothing happens.</p> * @param cls A class that may be declared to be equivalent to this class, and which is no longer equivalent * @exception OntProfileException If the {@link Profile#EQUIVALENT_CLASS()()} property is not supported in the current language profile. */ public void removeEquivalentClass( Resource cls ); // disjointWith /** * <p>Assert that this class is disjoint with the given class. Any existing * statements for <code>disjointWith</code> will be removed.</p> * @param cls The property that this class is disjoint with. * @exception OntProfileException If the {@link Profile#DISJOINT_WITH()} property is not supported in the current language profile. */ public void setDisjointWith( Resource cls ); /** * <p>Add a class that this class is disjoint with.</p> * @param cls A class that has no instances in common with this class. * @exception OntProfileException If the {@link Profile#DISJOINT_WITH()} property is not supported in the current language profile. */ public void addDisjointWith( Resource cls ); /** * <p>Answer a class with which this class is disjoint. If there is * more than one such class, an arbitrary selection is made.</p> * @return A class disjoint with this class * @exception OntProfileException If the {@link Profile#DISJOINT_WITH()} property is not supported in the current language profile. */ public OntClass getDisjointWith(); /** * <p>Answer an iterator over all of the classes that this class is declared to be disjoint with. * Each element of the iterator will be an {@link OntClass}.</p> * @return An iterator over the classes disjoint with this class. * @exception OntProfileException If the {@link Profile#DISJOINT_WITH()} property is not supported in the current language profile. */ public ExtendedIterator<OntClass> listDisjointWith(); /** * <p>Answer true if this class is disjoint with the given class.</p> * @param cls A class to test * @return True if the this class is disjoint with the the given class. * @exception OntProfileException If the {@link Profile#DISJOINT_WITH()} property is not supported in the current language profile. */ public boolean isDisjointWith( Resource cls ); /** * <p>Remove the statement that this class and the given class are * disjoint. If this statement * is not true of the current model, nothing happens.</p> * @param cls A class that may be declared to be disjoint with this class, and which is no longer disjoint * @exception OntProfileException If the {@link Profile#DISJOINT_WITH()()()} property is not supported in the current language profile. */ public void removeDisjointWith( Resource cls ); // other utility methods /** * <p>Answer an iteration of the properties associated with a frame-like * view of this class. Note that many cases of determining whether a * property is associated with a class depends on RDFS or OWL reasoning. * This method may therefore return complete results only in models that * have an attached reasoner. * See the * <a href="../../../../../../how-to/rdf-frames.html">RDF frames how-to</a> * for full details.<p> * @return An iteration of the properties that are associated with this class * by their domain. */ public ExtendedIterator<OntProperty> listDeclaredProperties(); /** * <p>Answer an iteration of the properties associated with a frame-like * view of this class. Note that many cases of determining whether a * property is associated with a class depends on RDFS or OWL reasoning. * This method may therefore return complete results only in models that * have an attached reasoner. See the * <a href="../../../../../../how-to/rdf-frames.html">RDF frames how-to</a> * for full details.<p> * @param direct If true, restrict the properties returned to those directly * associated with this class. * @return An iteration of the properties that are associated with this class * by their domain. */ public ExtendedIterator<OntProperty> listDeclaredProperties( boolean direct ); /** * <p>Answer true if the given property is one of the declared properties * of this class. For details, see {@link #listDeclaredProperties(boolean)}.</p> * @param p A property to test * @param direct If true, only direct associations between classes and properties * are considered * @return True if <code>p</code> is one of the declared properties of * this class */ public boolean hasDeclaredProperty( Property p, boolean direct ); /** * <p>Answer an iterator over the individuals in the model that have this * class among their types. Equivalent to {@link #listInstances(boolean)} * with an argument <code>false</code>.<p> * * @return An iterator over those instances that have this class as one of * the classes to which they belong */ public ExtendedIterator<? extends OntResource> listInstances(); /** * <p>Answer an iterator over the individuals in the model that have this * class among their types, optionally excluding sub-classes of this class.<p> * * @param direct If true, only direct instances are counted (i.e. not instances * of sub-classes of this class) * @return An iterator over those instances that have this class as one of * the classes to which they belong */ public ExtendedIterator<? extends OntResource> listInstances( boolean direct ); /** * <p>Answer a new individual that has this class as its <code>rdf:type</code></p> * @return A new anonymous individual that is an instance of this class */ public Individual createIndividual(); /** * <p>Answer a new individual that has this class as its <code>rdf:type</code></p> * @param uri The URI of the new individual * @return A new named individual that is an instance of this class */ public Individual createIndividual( String uri ); /** * <p>Remove the given individual from the set of instances that are members of * this class. This is effectively equivalent to the {@link Individual#removeOntClass} method, * but invoked via the class resource rather than via the individual resource.</p> * @param individual A resource denoting an individual that is no longer to be a member * of this class */ public void dropIndividual( Resource individual ); /** * <p>Answer true if this class is one of the roots of the local class hierarchy. * This will be true if either (i) this class has <code>owl:Thing</code> * (or <code>daml:Thing</code>) as a direct super-class, or (ii) it has * no declared super-classes (including anonymous class expressions).</p> * @return True if this class is the root of the class hierarchy in the * model it is attached to */ public boolean isHierarchyRoot(); // access to facets /** * <p>Answer a view of this class as an enumerated class</p> * @return This class, but viewed as an EnumeratedClass facet * @exception ConversionException if the class cannot be converted to an enumerated class * given the language profile and the current state of the underlying model. */ public EnumeratedClass asEnumeratedClass(); /** * <p>Answer a view of this class as a union class</p> * @return This class, but viewed as a UnionClass facet * @exception ConversionException if the class cannot be converted to a union class * given the language profile and the current state of the underlying model. */ public UnionClass asUnionClass(); /** * <p>Answer a view of this class as an intersection class</p> * @return This class, but viewed as an IntersectionClass facet * @exception ConversionException if the class cannot be converted to an intersection class * given the language profile and the current state of the underlying model. */ public IntersectionClass asIntersectionClass(); /** * <p>Answer a view of this class as a complement class</p> * @return This class, but viewed as a ComplementClass facet * @exception ConversionException if the class cannot be converted to a complement class * given the language profile and the current state of the underlying model. */ public ComplementClass asComplementClass(); /** * <p>Answer a view of this class as a restriction class expression</p> * @return This class, but viewed as a Restriction facet * @exception ConversionException if the class cannot be converted to a restriction * given the language profile and the current state of the underlying model. */ public Restriction asRestriction(); // sub-type testing /** * <p>Answer true if this class is an enumerated class expression</p> * @return True if this is an enumerated class expression */ public boolean isEnumeratedClass(); /** * <p>Answer true if this class is a union class expression</p> * @return True if this is a union class expression */ public boolean isUnionClass(); /** * <p>Answer true if this class is an intersection class expression</p> * @return True if this is an intersection class expression */ public boolean isIntersectionClass(); /** * <p>Answer true if this class is a complement class expression</p> * @return True if this is a complement class expression */ public boolean isComplementClass(); /** * <p>Answer true if this class is a property restriction</p> * @return True if this is a restriction */ public boolean isRestriction(); // conversion operations /** * <p>Answer a view of this class as an enumeration of the given individuals.</p> * @param individuals A list of the individuals that will comprise the permitted values of this * class converted to an enumeration * @return This ontology class, converted to an enumeration of the given individuals */ public EnumeratedClass convertToEnumeratedClass( RDFList individuals ); /** * <p>Answer a view of this class as an intersection of the given classes.</p> * @param classes A list of the classes that will comprise the operands of the intersection * @return This ontology class, converted to an intersection of the given classes */ public IntersectionClass convertToIntersectionClass( RDFList classes ); /** * <p>Answer a view of this class as a union of the given classes.</p> * @param classes A list of the classes that will comprise the operands of the union * @return This ontology class, converted to an union of the given classes */ public UnionClass convertToUnionClass( RDFList classes ); /** * <p>Answer a view of this class as an complement of the given class.</p> * @param cls An ontology class that will be operand of the complement * @return This ontology class, converted to an complement of the given class */ public ComplementClass convertToComplementClass( Resource cls ); /** * <p>Answer a view of this class as an restriction on the given property.</p> * @param prop A property this is the subject of a property restriction class expression * @return This ontology class, converted to a restriction on the given property */ public Restriction convertToRestriction( Property prop ); }
package com.scottkillen.mod.dendrology.world.gen; import com.google.common.base.Objects; import com.google.common.collect.ImmutableSet; import com.scottkillen.mod.dendrology.config.Settings; import com.scottkillen.mod.dendrology.util.log.Logger; import com.scottkillen.mod.dendrology.util.world.BiomeDictionaryProxy; import com.scottkillen.mod.dendrology.world.gen.feature.Cypress; import cpw.mods.fml.common.IWorldGenerator; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.feature.WorldGenAbstractTree; import net.minecraftforge.common.BiomeDictionary; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.terraingen.DecorateBiomeEvent; import java.util.Random; import static net.minecraftforge.common.BiomeDictionary.Type.SWAMP; import static net.minecraftforge.event.terraingen.DecorateBiomeEvent.Decorate.EventType.TREE; @SuppressWarnings("NonSerializableFieldInSerializableClass") public enum CypressGenerator implements IWorldGenerator { INSTANCE; private final WorldGenAbstractTree treeGen = new Cypress(false); @SuppressWarnings("SimplifiableIfStatement") private static boolean isIdealHabitat(ImmutableSet<BiomeDictionary.Type> biomeTags) { return biomeTags.contains(SWAMP); } public static void init() { MinecraftForge.TERRAIN_GEN_BUS.register(INSTANCE); } @SubscribeEvent public void onDecorateBiome(DecorateBiomeEvent.Decorate event) { if (event.type != TREE) return; generate(event.rand, event.chunkX, event.chunkZ, event.world, null, null); } @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) { if (!Settings.TreeGen.doCypressTreeGeneration()) return; final ImmutableSet<BiomeDictionary.Type> biomeTags = ImmutableSet.copyOf(BiomeDictionaryProxy.getBiomeTags(world, chunkX, chunkZ)); if (isIdealHabitat(biomeTags)) { generateCypress(world, random, chunkX, chunkZ); } } private void generateCypress(World world, Random rand, int chunkX, int chunkZ) { if (rand.nextInt(10) > 1) return; final int numAttempts = rand.nextInt(7); for (int attempt = 0; attempt < numAttempts; attempt++) { final int x = chunkX + rand.nextInt(16) + 8; final int z = chunkZ + rand.nextInt(16) + 8; final int y = world.getHeightValue(x, z); if (treeGen.generate(world, rand, x, y, z)) { treeGen.func_150524_b(world, rand, x, y, z); Logger.info("Cypress: %d, %d, %d", x, y, z); } } } @Override public String toString() { return Objects.toStringHelper(this).add("treeGen", treeGen).toString(); } }
package com.sunteam.ebook.view; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import com.sunteam.ebook.R; import com.sunteam.ebook.entity.DiasyNode; import com.sunteam.ebook.entity.DiasySentenceNode; import com.sunteam.ebook.entity.ReadMode; import com.sunteam.ebook.entity.ReverseInfo; import com.sunteam.ebook.entity.SplitInfo; import com.sunteam.ebook.util.DaisyFileReaderUtils; import com.sunteam.ebook.util.MediaPlayerUtils; import com.sunteam.ebook.util.MediaPlayerUtils.OnMediaPlayerListener; import com.sunteam.ebook.util.MediaPlayerUtils.PlayStatus; import com.sunteam.ebook.util.PublicUtils; import com.sunteam.ebook.util.TTSUtils; import com.sunteam.ebook.util.TTSUtils.OnTTSListener; import com.sunteam.ebook.util.TTSUtils.SpeakStatus; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.FontMetrics; import android.graphics.RectF; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.text.TextUtils; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.GestureDetector.OnDoubleTapListener; import android.view.GestureDetector.OnGestureListener; import android.view.MotionEvent; import android.view.View; /** * Daisy * * @author wzp * */ public class DaisyReaderView extends View implements OnGestureListener, OnDoubleTapListener, OnTTSListener, OnMediaPlayerListener { private static final String TAG = "DaisyReaderView"; private static final float MARGIN_WIDTH = 0; private static final float MARGIN_HEIGHT = 0; private static final String CHARSET_NAME = "GB18030";//GB18030 private Context mContext = null; private Bitmap mCurPageBitmap = null; private Canvas mCurPageCanvas = null; private Paint mPaint = null; private float mLineSpace = 3.6f; private float mTextSize = 20.0f; private int mTextColor = Color.WHITE; private int mBkColor = Color.BLACK; private int mReverseColor = Color.RED; private int mLineCount = 0; private int mWidth = 0; private int mHeight = 0; private float mVisibleWidth; private float mVisibleHeight; private boolean mIsFirstPage = false; private boolean mIsLastPage = false; private ArrayList<SplitInfo> mSplitInfoList = new ArrayList<SplitInfo>(); private byte[] mMbBuf = null; private int mOffset = 0; //BOM private int mLineNumber = 0; private int mMbBufLen = 0; private int mCurPage = 1; private GestureDetector mGestureDetector = null; private OnPageFlingListener mOnPageFlingListener = null; private ReadMode mReadMode = ReadMode.READ_MODE_ALL; private ReverseInfo mReverseInfo = new ReverseInfo(); private int mCheckSum = 0; //bufferchecksum private ArrayList<DiasySentenceNode> mDaisySentenceNodeList = null; private String mDaisyPath = null; private int mChapterPosition = 0; public interface OnPageFlingListener { public void onLoadCompleted( String title, int pageCount, int curPage ); public void onPageFlingToTop(); public void onPageFlingToBottom(); public void onPageFlingCompleted( String title, int curPage ); } public DaisyReaderView(Context context) { super(context); initReaderView( context ); } public DaisyReaderView(Context context, AttributeSet attrs) { super(context, attrs); initReaderView( context ); } public DaisyReaderView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initReaderView( context ); } private void initReaderView( Context context ) { mContext = context; mGestureDetector = new GestureDetector( context, this ); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setTextAlign(Align.LEFT); final float scale = context.getResources().getDisplayMetrics().density/0.75f; //ldpi mLineSpace *= scale; mTextSize *= scale; TTSUtils.getInstance().OnTTSListener(this); MediaPlayerUtils.getInstance().OnMediaPlayerListener(this); } public void setOnPageFlingListener( OnPageFlingListener listener ) { mOnPageFlingListener = listener; } public void setReadMode( ReadMode rm ) { mReadMode = rm; } @Override public void setBackgroundColor( int color ) { mBkColor = color; } public void setTextColor( int color ) { mTextColor = color; } public void setReverseColor( int color ) { mReverseColor = color; } public void setTextSize( float size ) { mTextSize = size; } public void setSpaceSize( int size ) { mLineSpace = size; } public int getBackgroundColor() { return mBkColor; } public int getTextColor() { return mTextColor; } public int getReverseColor() { return mReverseColor; } public float getTextSize() { return mTextSize; } public float getSpaceSize() { return mLineSpace; } public int getLineCount() { return mLineCount; } public boolean isFirstPage() { return mIsFirstPage; } public boolean isLastPage() { return mIsLastPage; } public String getFirstLineText() { return getLineText(mLineNumber); } public ReverseInfo getReverseInfo() { return mReverseInfo; } public int getLineNumber() { return mLineNumber; } //bufferCheckSum public int getCheckSum() { return mCheckSum; } private int calcCheckSum( byte[] buffer ) { int checksum = 0; int len = buffer.length; int shang = len / 4; int yu = len % 4; for( int i = 0; i < shang; i++ ) { checksum += PublicUtils.byte2int(buffer, i*4); } byte[] data = new byte[4]; for( int i = 0; i < yu; i++ ) { data[i] = buffer[i]; } checksum += PublicUtils.byte2int(data, 0); return checksum; } private String getLineText( final int lineNumber ) { int size = mSplitInfoList.size(); if( lineNumber >= 0 && lineNumber < size ) { SplitInfo li = mSplitInfoList.get(lineNumber); try { String str = new String(mMbBuf, li.startPos, li.len, CHARSET_NAME); if( str != null ) { str = str.replaceAll("\n", ""); str = str.replaceAll("\r", ""); return str; } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return ""; } private int getCurReversePosition() { int length = 0; for( int i = 0; i < mDaisySentenceNodeList.size(); i++ ) { if( mReverseInfo.startPos == length ) { return i; } length += mDaisySentenceNodeList.get(i).sentence.length; } return 0; } /** * * @param list * * @param charsetName * * @param lineNumber * () * @param startPos * * @param len * * @param checksum * */ public boolean openBook(String path, int position, int lineNumber, int startPos, int len, int checksum) { ArrayList<DiasySentenceNode> list = DaisyFileReaderUtils.getInstance().getDiasySentenceNodeList(path, position); if( null == list ) { mDaisySentenceNodeList = new ArrayList<DiasySentenceNode>(); return false; } mDaisyPath = path; mDaisySentenceNodeList = list; mChapterPosition = position; mMbBufLen = 0; int size = mDaisySentenceNodeList.size(); for( int i = 0; i < size; i++ ) { mMbBufLen += mDaisySentenceNodeList.get(i).sentence.length; } mMbBuf = new byte[mMbBufLen]; int n = 0; for( int i = 0; i < size; i++ ) { for( int j = 0; j < mDaisySentenceNodeList.get(i).sentence.length; j++ ) { mMbBuf[n++] = mDaisySentenceNodeList.get(i).sentence[j]; } } mLineNumber = lineNumber; mCheckSum = 0;//calcCheckSum( mMbBuf ); //CheckSum if( ( checksum != 0 ) && ( mCheckSum != checksum ) ) { return false; } mReverseInfo.startPos = startPos; mReverseInfo.len = len; return true; } /** * * * @param startPos * * @return int */ private int getNextParagraphLength( final int startPos ) { int i = startPos; byte b0, b1; if( CHARSET_NAME.equals("utf-16le") ) { while( i < mMbBufLen - 1 ) { b0 = mMbBuf[i++]; b1 = mMbBuf[i++]; if( b0 == 0x0a && b1 == 0x00 ) { break; } } } else if( CHARSET_NAME.equals("utf-16be") ) { while( i < mMbBufLen - 1 ) { b0 = mMbBuf[i++]; b1 = mMbBuf[i++]; if( b0 == 0x00 && b1 == 0x0a ) { break; } } } else { while( i < mMbBufLen ) { b0 = mMbBuf[i++]; if( b0 == 0x0a ) { break; } } } int len = i - startPos; return len; } private void divideLines() { mPaint.setTextSize(mTextSize); mPaint.setTypeface(Typeface.MONOSPACE); float asciiWidth = mPaint.measureText(" "); //ascii int startPos = mOffset; while( startPos < mMbBufLen ) { int len = getNextParagraphLength(startPos); if( len <= 0 ) { break; } else if( 1 == len ) { if( 0x0a == mMbBuf[startPos+len-1] ) { SplitInfo li = new SplitInfo(startPos, len); mSplitInfoList.add(li); startPos += len; continue; } } else if( 2 == len ) { if( 0x0d == mMbBuf[startPos+len-2] && 0x0a == mMbBuf[startPos+len-1] ) { SplitInfo li = new SplitInfo(startPos, len); mSplitInfoList.add(li); startPos += len; continue; } } byte[] buffer = new byte[len]; for( int i = 0; i < len; i++ ) { buffer[i] = mMbBuf[startPos+i]; } int textWidth = 0; int start = startPos; int home = 0; int i = 0; for( i = 0; i < buffer.length; i++ ) { if( 0x0d == buffer[i] || 0x0a == buffer[i] ) { continue; } if( buffer[i] < 0x80 && buffer[i] >= 0x0 ) //ascii { textWidth += ((int)asciiWidth); if( textWidth > mVisibleWidth ) { int length = i-home; SplitInfo li = new SplitInfo(start, length); mSplitInfoList.add(li); start += length; home = i; i textWidth = 0; continue; } } else { textWidth += (int)mTextSize; if( textWidth > mVisibleWidth ) { int length = i-home; SplitInfo li = new SplitInfo(start, length); mSplitInfoList.add(li); start += length; home = i; i textWidth = 0; continue; } i++; } } if( textWidth > 0 ) { int length = i-home; SplitInfo li = new SplitInfo(start, length); mSplitInfoList.add(li); start += length; textWidth = 0; } startPos += len; } calcCurPage(); } private void calcCurPage() { //mCurPage = mLineNumber / mLineCount + 1; // class PageInfo { int page; int count; public PageInfo( int p, int c ) { page = p; count = c; } } int size = mSplitInfoList.size(); int maxLine = Math.min( size, mLineNumber+mLineCount ); HashMap<Integer, PageInfo> pageMap = new HashMap<Integer, PageInfo>(); for( int i = mLineNumber; i < maxLine; i++ ) { int curPage = i / mLineCount + 1; PageInfo pi = pageMap.get(curPage); if( null == pi ) { pi = new PageInfo( curPage, 1 ); pageMap.put(curPage, pi); } else { pi.count++; pageMap.remove(curPage); pageMap.put(curPage, pi); } } ArrayList<PageInfo> list = new ArrayList<PageInfo>(); Iterator<Integer> iterator = pageMap.keySet().iterator(); while(iterator.hasNext()) { list.add(pageMap.get(iterator.next())); } size = list.size(); PageInfo pi = null; for( int i = 0; i < size; i++ ) { if( null == pi ) { pi = list.get(i); } else { if( pi.count < list.get(i).count ) { pi = list.get(i); } } } mCurPage = pi.page; } public int getCurPage() { return mCurPage; } public int getPageCount() { return ( mSplitInfoList.size() + mLineCount - 1 ) / mLineCount; } public boolean setCurPage( int page ) { if( ( page < 1 ) || ( page > getPageCount() ) ) { return false; } MediaPlayerUtils.getInstance().stop(); mCurPage = page; mLineNumber = (mCurPage-1)*mLineCount; SplitInfo si = mSplitInfoList.get(mLineNumber); int length = 0; for( int i = 0; i < mDaisySentenceNodeList.size(); i++ ) { if( length == si.startPos ) { mReverseInfo.startPos = length; mReverseInfo.len = mDaisySentenceNodeList.get(i).sentence.length; break; } else if( length > si.startPos ) { mReverseInfo.startPos = length-mDaisySentenceNodeList.get(i).sentence.length; mReverseInfo.len = mDaisySentenceNodeList.get(i-1).sentence.length; break; } length += mDaisySentenceNodeList.get(i).sentence.length; } this.invalidate(); if( mOnPageFlingListener != null ) { DiasyNode node = DaisyFileReaderUtils.getInstance().getDiasyNode(mChapterPosition); if( null == node ) { mOnPageFlingListener.onLoadCompleted("", getPageCount(), mCurPage); } else { mOnPageFlingListener.onLoadCompleted(node.name, getPageCount(), mCurPage); } } return true; } private boolean nextLine() { if( mLineNumber+mLineCount >= mSplitInfoList.size() ) { mIsLastPage = true; return false; } else { mIsLastPage = false; } mLineNumber++; calcCurPage(); return true; } private boolean preLine() { if( mLineNumber <= 0 ) { mLineNumber = 0; mIsFirstPage = true; return false; } else { mIsFirstPage = false; } mLineNumber calcCurPage(); return true; } private boolean nextPage() { if( mLineNumber+mLineCount >= mSplitInfoList.size() ) { mIsLastPage = true; return false; } else { mIsLastPage = false; } mLineNumber += mLineCount; calcCurPage(); return true; } private boolean prePage() { if( mLineNumber <= 0 ) { mLineNumber = 0; mIsFirstPage = true; return false; } else { mIsFirstPage = false; } mLineNumber -= mLineCount; if( mLineNumber < 0 ) { mLineNumber = 0; } calcCurPage(); return true; } private void init(Context context) { mWidth = getWidth(); mHeight = getHeight(); mVisibleWidth = mWidth - MARGIN_WIDTH * 2; mVisibleHeight = mHeight - MARGIN_HEIGHT * 2; mLineCount = (int)( mVisibleHeight / (mTextSize+mLineSpace ) ); if( null == mCurPageBitmap ) { mCurPageBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888); } if( null == mCurPageCanvas ) { mCurPageCanvas = new Canvas(mCurPageBitmap); } if( 0 == mSplitInfoList.size() ) { divideLines(); initReverseInfo(); if( mOnPageFlingListener != null ) { DiasyNode node = DaisyFileReaderUtils.getInstance().getDiasyNode(mChapterPosition); if( null == node ) { mOnPageFlingListener.onLoadCompleted("", getPageCount(), mCurPage); } else { mOnPageFlingListener.onLoadCompleted(node.name, getPageCount(), mCurPage); } } } } private void initReverseInfo() { switch( mReadMode ) { case READ_MODE_ALL: case READ_MODE_PARAGRAPH: case READ_MODE_SENCENTE: curSentence(true); break; default: break; } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int width; int height ; Drawable bgDrawable = this.getBackground(); if (widthMode == MeasureSpec.EXACTLY) //MATCH_PARENT { width = widthSize; } else //WARP_CONTENT { float bgWidth = bgDrawable.getIntrinsicWidth(); int desired = (int) (getPaddingLeft() + bgWidth + getPaddingRight()); width = desired; } if (heightMode == MeasureSpec.EXACTLY) //MATCH_PARENT { height = heightSize; } else //WARP_CONTENT { float bgHeight = bgDrawable.getIntrinsicHeight(); int desired = (int) (getPaddingTop() + bgHeight + getPaddingBottom()); height = desired; } setMeasuredDimension(width, height); } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); init(mContext); mCurPageCanvas.drawColor(mBkColor); mPaint.setTextSize(mTextSize); mPaint.setColor(mTextColor); int size = mSplitInfoList.size(); if( size > 0 ) { Paint paint = new Paint(); paint.setColor(mReverseColor); //FontMetrics FontMetrics fontMetrics = mPaint.getFontMetrics(); /* // float baseX = MARGIN_WIDTH; float baseY = MARGIN_HEIGHT; float topY = baseY + fontMetrics.top; float ascentY = baseY + fontMetrics.ascent; float descentY = baseY + fontMetrics.descent; float bottomY = baseY + fontMetrics.bottom; */ float x = MARGIN_WIDTH; float y = MARGIN_HEIGHT; for( int i = mLineNumber, j = 0; i < size && j < mLineCount; i++, j++ ) { if( mReverseInfo.len > 0 ) { SplitInfo si = mSplitInfoList.get(i); if( ( mReverseInfo.startPos >= si.startPos ) && ( mReverseInfo.startPos < si.startPos+si.len ) ) { float xx = x; String str = null; try { str = new String(mMbBuf, si.startPos, mReverseInfo.startPos-si.startPos, CHARSET_NAME); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if( !TextUtils.isEmpty(str) ) { xx += mPaint.measureText(str); } int len = Math.min(mReverseInfo.len, si.startPos+si.len-mReverseInfo.startPos); try { str = new String(mMbBuf, mReverseInfo.startPos, len, CHARSET_NAME); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if( "\r\n".equals(str) || "\n".equals(str) ) { RectF rect = new RectF(xx, y+(fontMetrics.ascent-fontMetrics.top), getWidth()-MARGIN_WIDTH, y+(fontMetrics.descent-fontMetrics.top) ); mCurPageCanvas.drawRect(rect, paint); } else { RectF rect = new RectF(xx, y+(fontMetrics.ascent-fontMetrics.top), (xx+mPaint.measureText(str)), y+(fontMetrics.descent-fontMetrics.top) ); mCurPageCanvas.drawRect(rect, paint); } } else if( ( mReverseInfo.startPos < si.startPos ) && ( mReverseInfo.startPos+mReverseInfo.len-1 >= si.startPos ) ) { float xx = x; String str = null; int len = Math.min( si.len, mReverseInfo.startPos + mReverseInfo.len - si.startPos ); try { str = new String(mMbBuf, si.startPos, len, CHARSET_NAME); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if( "\r\n".equals(str) || "\n".equals(str) ) { RectF rect = new RectF(xx, y+(fontMetrics.ascent-fontMetrics.top), getWidth()-MARGIN_WIDTH, y+(fontMetrics.descent-fontMetrics.top) ); mCurPageCanvas.drawRect(rect, paint); } else { RectF rect = new RectF(xx, y+(fontMetrics.ascent-fontMetrics.top), (xx+mPaint.measureText(str)), y+(fontMetrics.descent-fontMetrics.top) ); mCurPageCanvas.drawRect(rect, paint); } } } float baseY = y - fontMetrics.top; mCurPageCanvas.drawText(getLineText(i), x, baseY, mPaint); //drawTextbaseXbaseY y += mTextSize; y += mLineSpace; } } canvas.drawBitmap(mCurPageBitmap, 0, 0, null); } @Override public boolean onTouchEvent(MotionEvent event) { return mGestureDetector.onTouchEvent(event); } @Override public boolean onDown(MotionEvent e) { // TODO Auto-generated method stub return true; } @Override public void onShowPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onSingleTapUp(MotionEvent e) { //TODO Auto-generated method stub return false; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // TODO Auto-generated method stub return false; } @Override public void onLongPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // TODO Auto-generated method stub final int FLING_MIN_DISTANCE_X = getWidth()/3; final int FLING_MIN_DISTANCE_Y = getHeight()/3; if( e1.getX() - e2.getX() > FLING_MIN_DISTANCE_X ) { right(); } else if( e2.getX() - e1.getX() > FLING_MIN_DISTANCE_X ) { left(); } else if( e1.getY() - e2.getY() > FLING_MIN_DISTANCE_Y ) { down(); } else if( e2.getY() - e1.getY() > FLING_MIN_DISTANCE_Y ) { up(); } return false; } @Override public boolean onSingleTapConfirmed(MotionEvent e) { // TODO Auto-generated method stub return false; } @Override public boolean onDoubleTap(MotionEvent e) { // TODO Auto-generated method stub enter(); return false; } @Override public boolean onDoubleTapEvent(MotionEvent e) { // TODO Auto-generated method stub return false; } public void up() { MediaPlayerUtils.getInstance().stop(); preSentence(); } public void down() { MediaPlayerUtils.getInstance().stop(); nextSentence(false, false); } public void left() { MediaPlayerUtils.getInstance().stop(); if( openBook(mDaisyPath, mChapterPosition-1, 0, 0, 0, 0) == false ) { if( mOnPageFlingListener != null ) { mOnPageFlingListener.onPageFlingToTop(); } return; } mSplitInfoList.clear(); this.invalidate(); } public void right() { MediaPlayerUtils.getInstance().stop(); if( openBook(mDaisyPath, mChapterPosition+1, 0, 0, 0, 0) == false ) { if( mOnPageFlingListener != null ) { mOnPageFlingListener.onPageFlingToBottom(); } return; } mSplitInfoList.clear(); this.invalidate(); } public void enter() { PlayStatus status = MediaPlayerUtils.getInstance().getPlayStatus(); switch( mReadMode ) { case READ_MODE_ALL: case READ_MODE_PARAGRAPH: if( status == PlayStatus.PLAY ) { MediaPlayerUtils.getInstance().pause(); } else if( status == PlayStatus.PAUSE ) { MediaPlayerUtils.getInstance().resume(); } else if( status == PlayStatus.STOP ) { nextSentence(false, true); } break; case READ_MODE_SENCENTE: if( status == PlayStatus.PLAY ) { MediaPlayerUtils.getInstance().pause(); } else if( status == PlayStatus.PAUSE ) { MediaPlayerUtils.getInstance().resume(); } else if( status == PlayStatus.STOP ) { curSentence(false); } break; default: break; } } private void preSentence() { int position = getCurReversePosition(); if( position <= 0 ) { if( mOnPageFlingListener != null ) { mOnPageFlingListener.onPageFlingToTop(); } return; } position mReverseInfo.startPos = 0; mReverseInfo.len = 0; for( int i = 0; i < mDaisySentenceNodeList.size(); i++ ) { if( position == i ) { mReverseInfo.len = mDaisySentenceNodeList.get(i).sentence.length; break; } mReverseInfo.startPos += mDaisySentenceNodeList.get(i).sentence.length; } readReverseText(false); recalcLineNumber(Action.PRE_LINE); this.invalidate(); } private void curSentence( boolean isSpeakPage ) { int position = getCurReversePosition(); if( position >= mDaisySentenceNodeList.size() ) { if( mOnPageFlingListener != null ) { mOnPageFlingListener.onPageFlingToBottom(); } return; } mReverseInfo.startPos = 0; mReverseInfo.len = 0; for( int i = 0; i < mDaisySentenceNodeList.size(); i++ ) { if( position == i ) { mReverseInfo.len = mDaisySentenceNodeList.get(i).sentence.length; break; } mReverseInfo.startPos += mDaisySentenceNodeList.get(i).sentence.length; } readReverseText(isSpeakPage); recalcLineNumber(Action.NEXT_LINE); this.invalidate(); } private void nextSentence( boolean isSpeakPage, boolean isAutoPlay ) { int position = getCurReversePosition(); position++; if( position >= mDaisySentenceNodeList.size() ) { if( isAutoPlay ) { right(); } else { if( mOnPageFlingListener != null ) { mOnPageFlingListener.onPageFlingToBottom(); } } return; } mReverseInfo.startPos = 0; mReverseInfo.len = 0; for( int i = 0; i < mDaisySentenceNodeList.size(); i++ ) { if( position == i ) { mReverseInfo.len = mDaisySentenceNodeList.get(i).sentence.length; break; } mReverseInfo.startPos += mDaisySentenceNodeList.get(i).sentence.length; } readReverseText(isSpeakPage); recalcLineNumber(Action.NEXT_LINE); this.invalidate(); } private void readReverseText( boolean isSpeakPage ) { if( mReverseInfo.len <= 0 ) { if( isSpeakPage ) { String tips = String.format(mContext.getResources().getString(R.string.page_read_tips), mCurPage, getPageCount() ); TTSUtils.getInstance().speakTips(tips); } return; } int postion = getCurReversePosition(); DiasySentenceNode node = mDaisySentenceNodeList.get(postion); if( isSpeakPage ) { String tips = String.format(mContext.getResources().getString(R.string.page_read_tips), mCurPage, getPageCount() ); TTSUtils.getInstance().speakContent(tips); } else { MediaPlayerUtils.getInstance().play(node.audioFile, node.startTime, node.endTime); } } private void recalcLineNumber( Action action ) { if( mReverseInfo.len <= 0 ) { return; } int size = mSplitInfoList.size(); SplitInfo si = null; switch( action ) { case NEXT_LINE: case NEXT_PAGE: while( true ) { int curPageLine = Math.min( mLineCount, (size-mLineNumber) ); si = mSplitInfoList.get(mLineNumber+curPageLine-1); if( ( mReverseInfo.startPos >= si.startPos+si.len ) || ( mReverseInfo.startPos + mReverseInfo.len > si.startPos + si.len ) ) { if( Action.NEXT_LINE == action ) { if( nextLine() ) { if( mOnPageFlingListener != null ) { DiasyNode node = DaisyFileReaderUtils.getInstance().getDiasyNode(mChapterPosition); if( null == node ) { mOnPageFlingListener.onPageFlingCompleted("",mCurPage); } else { mOnPageFlingListener.onPageFlingCompleted(node.name,mCurPage); } } } else { if( mOnPageFlingListener != null ) { mOnPageFlingListener.onPageFlingToBottom(); } break; } } else { if( nextPage() ) { if( mOnPageFlingListener != null ) { DiasyNode node = DaisyFileReaderUtils.getInstance().getDiasyNode(mChapterPosition); if( null == node ) { mOnPageFlingListener.onPageFlingCompleted("",mCurPage); } else { mOnPageFlingListener.onPageFlingCompleted(node.name,mCurPage); } } } else { if( mOnPageFlingListener != null ) { mOnPageFlingListener.onPageFlingToBottom(); } break; } } } else { break; } } break; case PRE_LINE: case PRE_PAGE: while( true ) { si = mSplitInfoList.get(mLineNumber); if( mReverseInfo.startPos < si.startPos ) { if( Action.PRE_LINE == action ) { if( preLine() ) { if( mOnPageFlingListener != null ) { DiasyNode node = DaisyFileReaderUtils.getInstance().getDiasyNode(mChapterPosition); if( null == node ) { mOnPageFlingListener.onPageFlingCompleted("",mCurPage); } else { mOnPageFlingListener.onPageFlingCompleted(node.name,mCurPage); } } } else { if( mOnPageFlingListener != null ) { mOnPageFlingListener.onPageFlingToTop(); } break; } } else { if( prePage() ) { if( mOnPageFlingListener != null ) { DiasyNode node = DaisyFileReaderUtils.getInstance().getDiasyNode(mChapterPosition); if( null == node ) { mOnPageFlingListener.onPageFlingCompleted("",mCurPage); } else { mOnPageFlingListener.onPageFlingCompleted(node.name,mCurPage); } } } else { if( mOnPageFlingListener != null ) { mOnPageFlingListener.onPageFlingToTop(); } break; } } } else { break; } } break; default: break; } } private enum Action { NEXT_LINE, NEXT_PAGE, PRE_LINE, PRE_PAGE, } @Override public void onSpeakCompleted() { // TODO Auto-generated method stub switch( mReadMode ) { case READ_MODE_ALL: case READ_MODE_PARAGRAPH: curSentence(false); break; default: break; } } @Override public void onSpeakError() { // TODO Auto-generated method stub } @Override public void onPlayCompleted() { // TODO Auto-generated method stub switch( mReadMode ) { case READ_MODE_ALL: case READ_MODE_PARAGRAPH: nextSentence(false, true); break; default: break; } } @Override public void onPlayError() { // TODO Auto-generated method stub } }
package com.inbravo.spark; import java.util.Arrays; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.PairFunction; import scala.Tuple2; /** * * @author amit.dixit * */ public final class SparkKeyValueEx { public final static void main(final String... args) { /* Spark context for java */ final JavaSparkContext jsc = new JavaSparkContext(new SparkConf().setAppName("SparkKeyValueEx").setMaster("local")); /* Create RDDs of integer array */ final JavaRDD<Integer> rddOne = jsc.parallelize(Arrays.asList(1, 2, 3, 3, 4)); final JavaRDD<Integer> rddTwo = jsc.parallelize(Arrays.asList(3, 4, 4, 5, 6)); System.out.println("========================================================================================================="); System.out.println(" /* Collect all elements */ System.out.println(" /* Show union */ System.out.println(" /* Show intersection */ System.out.println("--Intersection : " + rddOne.intersection(rddTwo).collect()); /* Apply subtract */ System.out.println(" /* Apply cartesian */ System.out.println(" /* Count all elements in RDDs */ System.out.println(" /* Count all element values */ System.out.println("--CountByValue : " + rddOne.countByValue()); /* Get third element */ System.out.println(" /* Get only values which are less than 3 */ System.out.println(" /* Show Reduce result */ System.out.println(" /* Show Map result */ System.out.println(" /* FlatMap returns java.lang.Iterable */ System.out.println(" /* MapToPair returns Tuple2 */ final JavaPairRDD<Integer, Integer> jpRDD = rddOne.mapToPair(convertToKeyValue()); System.out.println(" /* Keys returns JavaRDD */ System.out.println(" /* Values returns JavaRDD */ System.out.println(" /* Values returns JavaRDD */ System.out.println(" /* Keys returns JavaRDD */ System.out.println("----GroupByKey : " + jpRDD.groupByKey().collect()); /* ReduceByKey returns Function2 */ System.out.println("---ReduceByKey : " + jpRDD.reduceByKey((x, y) -> x + y).collect()); /* ReduceByKey returns Function */ System.out.println(" /* ReduceByKey returns Function */ System.out.println("-FlatMapValues : " + jpRDD.flatMapValues(x -> Arrays.asList(x * x * x)).collect()); System.out.println("========================================================================================================="); /* Close spark context */ jsc.close(); } @SuppressWarnings("serial") private static final PairFunction<Integer, Integer, Integer> convertToKeyValue() { /** * Convert to key-value [key (integer) : value (integer * integer)] */ return new PairFunction<Integer, Integer, Integer>() { @Override public final Tuple2<Integer, Integer> call(final Integer integer) throws Exception { /* Tuple : key (integer) : value (integer * integer) */ return new Tuple2<Integer, Integer>(integer, integer * integer); } }; } }
package fi.nls.oskari.control.data; import fi.mml.portti.service.search.SearchCriteria; import fi.mml.portti.service.search.SearchService; import fi.mml.portti.service.search.SearchServiceImpl; import fi.nls.oskari.SearchWorker; import fi.nls.oskari.annotation.OskariActionRoute; import fi.nls.oskari.control.ActionException; import fi.nls.oskari.control.ActionHandler; import fi.nls.oskari.control.ActionParameters; import fi.nls.oskari.control.ActionParamsException; import fi.nls.oskari.search.channel.SearchableChannel; import fi.nls.oskari.util.PropertyUtil; import fi.nls.oskari.util.ResponseHelper; import org.json.JSONObject; import java.util.*; @OskariActionRoute("GetReverseGeocodingResult") public class GetReverseGeocodingResultHandler extends ActionHandler { private static final String PARAM_LON = "lon"; private static final String PARAM_LAT = "lat"; private static final String PARAM_BUFFER = "buffer"; private static final String PARAM_SCALE = "scale"; private static final String PARAM_MAXFEATURES = "maxfeatures"; private static final String PARAM_EPSG_KEY = "epsg"; private static final String PROPERTY_CHANNELS = "actionhandler.GetReverseGeocodingResult.channels"; private static final String PROPERTY_MAXFEATURES = "actionhandler.GetReverseGeocodingResult.maxfeatures"; private static final String PROPERTY_BUFFER = "actionhandler.GetReverseGeocodingResult.buffer"; // Reverse search is executed only to requested channels, if channel_ids parameter is used // TODO: refactor to channels to be consistent with GetSearchResultHandler private static final String PARAM_OPTIONAL_CHANNEL_IDS_KEY = "channel_ids"; private int maxFeatures = -1; private int buffer = 1000; private String[] channels = new String[0]; public void init() { channels = PropertyUtil.getCommaSeparatedList(PROPERTY_CHANNELS); maxFeatures = PropertyUtil.getOptional(PROPERTY_MAXFEATURES, maxFeatures); buffer = PropertyUtil.getOptional(PROPERTY_BUFFER, buffer); if(channels.length == 0) { SearchService searchService = new SearchServiceImpl(); Map<String, SearchableChannel> availableChannels = searchService.getAvailableChannels(); List<String> geocodeChannels = new ArrayList<>(availableChannels.size()); for (Map.Entry<String, SearchableChannel> entry : availableChannels.entrySet()) { if(entry.getValue().getCapabilities().canGeocode()) { geocodeChannels.add(entry.getKey()); } } channels = geocodeChannels.toArray(new String[0]); } } public void handleAction(final ActionParameters params) throws ActionException { final double lon = params.getRequiredParamDouble(PARAM_LON); final double lat = params.getRequiredParamDouble(PARAM_LAT); final String epsg = params.getRequiredParam(PARAM_EPSG_KEY); final String scale = params.getHttpParam(PARAM_SCALE); final SearchCriteria sc = new SearchCriteria(); if (scale != null) { sc.addParam(PARAM_SCALE, scale); } sc.setReverseGeocode(lat, lon); // eg. EPSG:3067 sc.setSRS(epsg); // Search distance around the point (unit m) sc.addParam(PARAM_BUFFER, params.getHttpParam(PARAM_BUFFER, buffer)); sc.setLocale(params.getLocale().getLanguage()); // Requested channels. Option to use only e.g. one channel for to request the result List<String> requestedChannels = getChannels(params.getHttpParam(PARAM_OPTIONAL_CHANNEL_IDS_KEY)); for (String channelId : requestedChannels) { sc.addChannel(channelId); } // determine max result feature count - in this order parameter value, property, number of channels to query sc.setMaxResults(getMaxResults(params.getHttpParam(PARAM_MAXFEATURES, maxFeatures), requestedChannels.size())); if (sc.getChannels().size() == 0) { throw new ActionParamsException("No reverse geocoding channels available or configured or invalid channel ID"); } final JSONObject result = SearchWorker.doSearch(sc); ResponseHelper.writeResponse(params, result); } private int getMaxResults(int requested, int defaultValue) { if(requested != -1) { return requested; } return defaultValue; } private List<String> getChannels(final String requested) { if (requested != null) { return Arrays.asList(requested.split(",")); } return Arrays.asList(channels); } }
package com.skelril.skree.content.zone; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.block.ChangeBlockEvent; import org.spongepowered.api.event.filter.cause.First; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; import java.util.Optional; import java.util.function.Function; public class ZoneImmutableBlockListener<T> extends ZoneApplicableListener<T> { public ZoneImmutableBlockListener(Function<Location<World>, Optional<T>> applicabilityFunct) { super(applicabilityFunct); } @Listener public void onBlockChange(ChangeBlockEvent event, @First Entity entity) { if (isApplicable(entity)) { event.setCancelled(true); } } }
package com.jcwhatever.nucleus.utils; import java.util.List; import java.util.concurrent.ThreadLocalRandom; /** * Randomizing utilities. */ public final class Rand { private Rand() {} static final String SAFE_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; static final String UNSAFE_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + "01234567890`~!@ private static final ThreadSingletons<XORShiftRandom> RANDOMS = new ThreadSingletons<>( new ThreadSingletons.ISingletonFactory<XORShiftRandom>() { @Override public XORShiftRandom create(Thread thread) { return new XORShiftRandom(); } }); /** * Get a random item from a list. * * @param items The list to get a random item from. * * @param <T> The list generic type. */ public static <T> T get(List<T> items) { PreCon.notNull(items); PreCon.isValid(items.size() > 0); if (items.size() == 1) return items.get(0); return items.get(getInt(items.size())); } /** * Get a random item from an array of items. * * @param items The array of items. * * @param <T> The array item type. */ public static <T> T get(T[] items) { PreCon.notNull(items); PreCon.isValid(items.length > 0); if (items.length == 1) return items[0]; return items[getInt(items.length)]; } /** * Remove a random item from a list. * * @param items The list to remove a random item from. * * @param <T> The list generic type. */ public static <T> T remove(List<T> items) { PreCon.notNull(items); PreCon.isValid(items.size() > 0); if (items.size() == 1) return items.remove(0); return items.remove(getInt(items.size())); } /** * Get a random integer equal to or between the specified minimum and maximum * amount. * * @param min The minimum result. * @param max The maximum result. */ public static int getInt(int min, int max) { int range = max - min + 1; int i = Math.abs(RANDOMS.get().nextInt()) % range; return min + i; } /** * Get a random integer from 0 up to the specified maximum number. * * @param max The maximum result. */ public static int getInt(int max) { return RANDOMS.get().nextInt(max); } /** * Get a random integer. */ public static int getInt() { return RANDOMS.get().nextInt(); } /** * Get a random double equal to or between the specified minimum and maximum * amount. * * @param min The minimum result. * @param max The maximum result. */ public static double getDouble(double min, double max) { return ThreadLocalRandom.current().nextDouble(min, max); } /** * Get a random double from 0 up to the specified maximum number. * * @param max The maximum result. */ public static double getDouble(double max) { return ThreadLocalRandom.current().nextDouble(0, max); } /** * Get a random double. */ public static double getDouble() { return ThreadLocalRandom.current().nextDouble(); } /** * Get a random gaussian double with an average of 0 and a * deviation of 1. */ public static double getGaussian() { return ThreadLocalRandom.current().nextGaussian(); } /** * Get a random gaussian double. * * @param average The average. * @param deviation The deviation from average. */ public static double getGaussian(double average, double deviation) { return ThreadLocalRandom.current().nextGaussian() * deviation + average; } /** * Get a random alphabet string of the specified length. * * <p>Returned string should be safe to use in contexts such as node names in * config files.</p> * * @param length The length of the returned string. */ public static String getSafeString(int length) { PreCon.positiveNumber(length); return getString(length, SAFE_CHARACTERS); } /** * Get a random string of characters, including symbols, of the specified length. * * <p>May not be safe to use where the usage context does not allow for symbols in * the string.</p> * * @param length The length of the returned string. */ public static String getUnsafeString(int length) { PreCon.positiveNumber(length); return getString(length, UNSAFE_CHARACTERS); } /** * Get a random string of characters using the specified character pool. * * @param length The length of the returned string. * @param characterPool The pool of characters to construct a string with. */ public static String getString(int length, String characterPool) { PreCon.positiveNumber(length); PreCon.notNullOrEmpty(characterPool); StringBuilder sb = new StringBuilder(length); for (int i=0; i < length; i++) { int index = getInt(0, characterPool.length() - 1); sb.append(characterPool.charAt(index)); } return sb.toString(); } /** * Get a random boolean using the specified chance. * * <p>The maximum effective chance is 100.</p> * * @param chance The chance of getting a result of true. */ public static boolean chance(int chance) { return chance(chance / 100.0D); } /** * Get a random boolean using the specified chance. * * <p>The maximum effective chance is 1.0.</p> * * @param chance The chance of getting a result of true. */ public static boolean chance(double chance) { return chance > Rand.getDouble(1); } /** * Roll dice of the specified number of sides. * * <p>Maximum effective sides is 100.</p> * * @param sides The number of sides the dice has. */ public static boolean rollDice(int sides) { PreCon.positiveNumber(sides); if (sides == 0 || sides > 100) return false; if (sides == 1) return true; int chance = 100 / sides; return chance(chance); } private static class XORShiftRandom { long x = System.currentTimeMillis(); long next() { x ^= (x << 21); x ^= (x >>> 35); x ^= (x << 4); return x; } int nextInt() { next(); return Math.abs((int)((x >> 32) ^ ((int)x))); } int nextInt(int max) { if (max <= 1) return 0; return nextInt() % (max - 1); } } }
package com.sonymobile.tools.gerrit.gerritevents; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.nio.CharBuffer; import java.util.Collections; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSchException; import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sonymobile.tools.gerrit.gerritevents.dto.attr.Provider; import com.sonymobile.tools.gerrit.gerritevents.ssh.Authentication; import com.sonymobile.tools.gerrit.gerritevents.ssh.AuthenticationUpdater; import com.sonymobile.tools.gerrit.gerritevents.ssh.SshAuthenticationException; import com.sonymobile.tools.gerrit.gerritevents.ssh.SshConnectException; import com.sonymobile.tools.gerrit.gerritevents.ssh.SshConnection; import com.sonymobile.tools.gerrit.gerritevents.ssh.SshConnectionFactory; import com.sonymobile.tools.gerrit.gerritevents.watchdog.StreamWatchdog; import com.sonymobile.tools.gerrit.gerritevents.watchdog.WatchTimeExceptionData; //CS IGNORE LineLength FOR NEXT 7 LINES. REASON: static import. /** * Main class for connection. Contains the main loop for connecting to Gerrit. * * @author rinrinne &lt;rinrin.ne@gmail.com&gt; */ public class GerritConnection extends Thread implements Connector { /** * Time to wait between connection attempts. */ public static final int CONNECT_SLEEP = 2000; /** * Command to open gerrit event stream. */ public static final String CMD_STREAM_EVENTS = "gerrit stream-events"; private static final String GERRIT_VERSION_PREFIX = "gerrit version "; private static final int SSH_RX_BUFFER_SIZE = 262400; private static final int SSH_RX_SLEEP_MILLIS = 100; /** * The standard scheme used for stream-events. */ public static final String GERRIT_PROTOCOL_SCHEME_NAME = "ssh"; private static final Logger logger = LoggerFactory.getLogger(GerritConnection.class); private String gerritName; private String gerritHostName; private int gerritSshPort; private String gerritProxy; private Authentication authentication; private String gerritFrontEndUrl; private SshConnection sshConnection; private volatile boolean shutdownInProgress = false; private volatile boolean connected = false; private String gerritVersion = null; private int watchdogTimeoutSeconds; private WatchTimeExceptionData exceptionData; private StreamWatchdog watchdog; private int reconnectCallCount = 0; private GerritHandler handler; private AuthenticationUpdater authenticationUpdater = null; private final Set<ConnectionListener> listeners = new CopyOnWriteArraySet<ConnectionListener>(); private int sshRxBufferSize = SSH_RX_BUFFER_SIZE; /** * Creates a GerritHandler with all the default values set. * * @see GerritDefaultValues#DEFAULT_GERRIT_NAME * @see GerritDefaultValues#DEFAULT_GERRIT_HOSTNAME * @see GerritDefaultValues#DEFAULT_GERRIT_SSH_PORT * @see GerritDefaultValues#DEFAULT_GERRIT_PROXY * @see GerritDefaultValues#DEFAULT_GERRIT_USERNAME * @see GerritDefaultValues#DEFAULT_GERRIT_AUTH_KEY_FILE * @see GerritDefaultValues#DEFAULT_GERRIT_AUTH_KEY_FILE_PASSWORD */ public GerritConnection() { this(GerritDefaultValues.DEFAULT_GERRIT_NAME, GerritDefaultValues.DEFAULT_GERRIT_HOSTNAME, GerritDefaultValues.DEFAULT_GERRIT_SSH_PORT, GerritDefaultValues.DEFAULT_GERRIT_PROXY, GerritDefaultValues.DEFAULT_GERRIT_FRONT_END_URL, new Authentication(GerritDefaultValues.DEFAULT_GERRIT_AUTH_KEY_FILE, GerritDefaultValues.DEFAULT_GERRIT_USERNAME, GerritDefaultValues.DEFAULT_GERRIT_AUTH_KEY_FILE_PASSWORD)); } /** * Creates a GerritHandler with the specified values. * * @param gerritName the name of the gerrit server. * @param gerritHostName the hostName * @param gerritSshPort the ssh port that the gerrit server listens to. * @param authentication the authentication credentials. */ public GerritConnection(String gerritName, String gerritHostName, int gerritSshPort, Authentication authentication) { this(gerritName, gerritHostName, gerritSshPort, GerritDefaultValues.DEFAULT_GERRIT_PROXY, GerritDefaultValues.DEFAULT_GERRIT_FRONT_END_URL, authentication); } /** * Standard Constructor. * * @param gerritName the name of the gerrit server. * @param config the configuration containing the connection values. */ public GerritConnection(String gerritName, GerritConnectionConfig config) { this(gerritName, config, GerritDefaultValues.DEFAULT_GERRIT_PROXY, 0, null); } /** * Standard Constructor. * * @param gerritName the name of the gerrit server. * @param config the configuration containing the connection values. */ public GerritConnection(String gerritName, GerritConnectionConfig2 config) { this(gerritName, config, config.getGerritProxy(), config.getWatchdogTimeoutSeconds(), config.getExceptionData()); } /** * Creates a GerritHandler with the specified values. * * @param gerritName the name of the gerrit server. * @param config the configuration containing the connection values. * @param gerritProxy the URL of gerrit proxy. * @param watchdogTimeoutSeconds number of seconds before the connection watch dog restarts the connection set to 0 * or less to disable it. * @param exceptionData time info for when the watch dog's timeout should not be in effect. set to null to * disable the watch dog. */ public GerritConnection(String gerritName, GerritConnectionConfig config, String gerritProxy, int watchdogTimeoutSeconds, WatchTimeExceptionData exceptionData) { this(gerritName, config.getGerritHostName(), config.getGerritSshPort(), gerritProxy, config.getGerritFrontEndUrl(), config.getGerritAuthentication(), watchdogTimeoutSeconds, exceptionData); } public GerritConnection(String gerritName, String gerritHostName, int gerritSshPort, String gerritProxy, String gerritFrontEndUrl, Authentication authentication) { this(gerritName, gerritHostName, gerritSshPort, gerritProxy, gerritFrontEndUrl, authentication, 0, null); } public GerritConnection(String gerritName, String gerritHostName, int gerritSshPort, String gerritProxy, String gerritFrontEndUrl, Authentication authentication, int watchdogTimeoutSeconds, WatchTimeExceptionData exceptionData) { this.gerritName = gerritName; this.gerritHostName = gerritHostName; this.gerritSshPort = gerritSshPort; this.gerritProxy = gerritProxy; this.gerritFrontEndUrl = gerritFrontEndUrl; this.authentication = authentication; this.watchdogTimeoutSeconds = watchdogTimeoutSeconds; this.exceptionData = exceptionData; } /** * Sets Buffer size for receiving SSH stream. * * @param size buffer size. * @return The previous size. */ public int setSshRxBufferSize(int size) { int prev = sshRxBufferSize; sshRxBufferSize = size; return prev; } /** * Sets gerrit handler. * * @param handler the handler. */ public void setHandler(GerritHandler handler) { this.handler = handler; } /** * Gets gerrit handler. * * @return the handler. */ public GerritHandler getHandler() { return handler; } /** * The gerrit version we are connected to. * * @return the gerrit version. */ public String getGerritVersion() { return gerritVersion; } /** * Add listener for GerrirtConnectionEvent. * * @param listener the listener. */ public void addListener(ConnectionListener listener) { if (!listeners.add(listener)) { logger.warn("The connection listener was doubly-added: {}", listener); } } /** * Remove listener for GerrirtConnectionEvent. * * @param listener the listener. */ public void removeListener(ConnectionListener listener) { listeners.remove(listener); } /** * Removes all connection listeners. */ public void removeListeners() { listeners.clear(); } /** * Returns an unmodifiable view of the set of {@link ConnectionListener}s. * * @return the set of connection listeners. * @see Collections#unmodifiableSet(Set) */ public Set<ConnectionListener> getListenersView() { return Collections.unmodifiableSet(listeners); } /** * Sets {@link AuthenticationUpdater}. * @param authenticationUpdater The {@link AuthenticationUpdater}. */ public void setAuthenticationUpdater(AuthenticationUpdater authenticationUpdater) { this.authenticationUpdater = authenticationUpdater; } /** * If watchdog field is not null, shut it down and put it to null. */ private void nullifyWatchdog() { if (watchdog != null) { watchdog.shutdown(); watchdog = null; } } /** * Offers lines in buffer to queue. * * @param cb a buffer to have received text data. * @return the line string. null if no EOL, otherwise buffer is compacted. */ private String getLine(CharBuffer cb) { String line = null; int pos = cb.position(); cb.flip(); for (int i = 0; i < cb.length(); i++) { if (cb.charAt(i) == '\n') { line = getSubSequence(cb, 0, i).toString().trim(); cb.position(i + 1); break; } } if (line != null) { cb.compact(); } else { cb.clear().position(pos); } return line; } /** * Get sub sequence of buffer. * * This method avoids error in java-api-check. * animal-sniffer is confused by the signature of CharBuffer.subSequence() * due to declaration of this method has been changed since Java7. * (abstract -> non-abstract) * * @param cb a buffer * @param start start of sub sequence * @param end end of sub sequence * @return sub sequence. */ @IgnoreJRERequirement private CharSequence getSubSequence(CharBuffer cb, int start, int end) { return cb.subSequence(start, end); } /** * Main loop for connecting and reading Gerrit JSON Events and dispatching them to Workers. */ @Override public void run() { logger.info("Starting Up " + gerritName); do { sshConnection = connect(); if (sshConnection == null) { return; } if (watchdogTimeoutSeconds > 0 && exceptionData != null) { nullifyWatchdog(); watchdog = new StreamWatchdog(this, watchdogTimeoutSeconds, exceptionData); } ChannelExec channel = null; try { logger.trace("Executing stream-events command."); channel = sshConnection.executeCommandChannel(CMD_STREAM_EVENTS, false); if (channel == null) { throw new IOException("Cannot open SSH channel."); } Reader reader = new InputStreamReader(channel.getInputStream(), "utf-8"); channel.connect(); CharBuffer cb = CharBuffer.allocate(sshRxBufferSize); notifyConnectionEstablished(); Provider provider = new Provider( gerritName, gerritHostName, String.valueOf(gerritSshPort), GERRIT_PROTOCOL_SCHEME_NAME, gerritFrontEndUrl, getGerritVersionString()); logger.info("Ready to receive data from Gerrit: " + gerritName); String line; Integer readCount; while ((readCount = reader.read(cb)) != -1) { logger.debug("Read count from Gerrit stream: {}", String.valueOf(readCount)); while ((line = getLine(cb)) != null) { logger.debug("Data-line from Gerrit: {}", line); if (handler != null) { handler.post(line, provider); } } if (shutdownInProgress || interrupted()) { throw new InterruptedException("shutdown requested: " + shutdownInProgress); } if (readCount > 0 && watchdog != null) { watchdog.signal(); } if (!channel.isConnected() || !sshConnection.isConnected()) { throw new IllegalStateException("SSH connection is already lost."); } sleep(SSH_RX_SLEEP_MILLIS); } } catch (IOException ex) { logger.error("Stream events command error. ", ex); } catch (IllegalStateException ex) { logger.error("Unexpected disconnection occurred after initial moment of connection. ", ex); } catch (InterruptedException ex) { logger.error("Interrupted.", ex); } catch (JSchException ex) { logger.error("Error when establishing SSH connection. ", ex); } finally { nullifyWatchdog(); if (channel != null && !channel.isClosed()) { logger.trace("Close channel."); try { channel.disconnect(); } catch (Exception ex) { logger.warn("Error when disconnecting SSH command channel.", ex); } } if (!sshConnection.isConnected()) { sshConnection = null; } notifyConnectionDown(); } } while (!shutdownInProgress); handler = null; logger.debug("End of GerritConnection Thread."); } /** * Connects to the Gerrit server and authenticates as the specified user. * * @return not null if everything is well, null if connect and reconnect failed. */ private SshConnection connect() { if (sshConnection != null && sshConnection.isConnected()) { return sshConnection; } while (!shutdownInProgress) { SshConnection ssh = null; try { logger.debug("Connecting..."); ssh = SshConnectionFactory.getConnection(gerritHostName, gerritSshPort, gerritProxy, authentication, authenticationUpdater); gerritVersion = formatVersion(ssh.executeCommand("gerrit version")); logger.debug("connection seems ok, returning it."); return ssh; } catch (SshConnectException sshConEx) { logger.error("Could not connect to Gerrit server! " + "Host: {} Port: {}", gerritHostName, gerritSshPort); logger.error(" Proxy: {}", gerritProxy); logger.error(" User: {} KeyFile: {}", authentication.getUsername(), authentication.getPrivateKeyFile()); logger.error("ConnectionException: ", sshConEx); } catch (SshAuthenticationException sshAuthEx) { logger.error("Could not authenticate to Gerrit server!" + "\n\tUsername: {}\n\tKeyFile: {}\n\tPassword: {}", new Object[]{authentication.getUsername(), authentication.getPrivateKeyFile(), authentication.getPrivateKeyFilePassword(), }); logger.error("AuthenticationException: ", sshAuthEx); } catch (IOException ex) { logger.error("Could not connect to Gerrit server! " + "Host: {} Port: {}", gerritHostName, gerritSshPort); logger.error(" Proxy: {}", gerritProxy); logger.error(" User: {} KeyFile: {}", authentication.getUsername(), authentication.getPrivateKeyFile()); logger.error("IOException: ", ex); } if (ssh != null) { logger.trace("Disconnecting bad connection."); try { //The ssh lib used is starting at least one thread for each connection. //The thread isn't shutdown properly when the connection goes down, //so we need to close it "manually" ssh.disconnect(); } catch (Exception ex) { logger.warn("Error when disconnecting bad connection.", ex); } finally { ssh = null; } } if (!shutdownInProgress) { //If we end up here, sleep for a while and then go back up in the loop. logger.trace("Sleeping for a bit."); try { Thread.sleep(CONNECT_SLEEP); } catch (InterruptedException ex) { logger.warn("Got interrupted while sleeping.", ex); } } } return null; } /** * Removes the "gerrit version " from the start of the response from gerrit. * @param version the response from gerrit. * @return the input string with "gerrit version " removed. */ private String formatVersion(String version) { if (version == null) { return version; } String[] split = version.split(GERRIT_VERSION_PREFIX); if (split.length < 2) { return version.trim(); } return split[1].trim(); } /** * Gets the gerrit version. * @return the gerrit version as valid string. */ private String getGerritVersionString() { String version = getGerritVersion(); if (version == null) { version = ""; } return version; } /** * The authentication credentials for ssh connection. * * @return the credentials. */ public Authentication getAuthentication() { return authentication; } /** * The authentication credentials for ssh connection. * * @param authentication the credentials. */ public void setAuthentication(Authentication authentication) { this.authentication = authentication; } /** * gets the hostname where Gerrit is running. * * @return the hostname. */ public String getGerritHostName() { return gerritHostName; } /** * Sets the hostname where Gerrit is running. * * @param gerritHostName the hostname. */ public void setGerritHostName(String gerritHostName) { this.gerritHostName = gerritHostName; } /** * Gets the port for gerrit ssh commands. * * @return the port nr. */ public int getGerritSshPort() { return gerritSshPort; } /** * Sets the port for gerrit ssh commands. * * @param gerritSshPort the port nr. */ public void setGerritSshPort(int gerritSshPort) { this.gerritSshPort = gerritSshPort; } /** * Gets the proxy for gerrit ssh commands. * * @return the proxy url. */ public String getGerritProxy() { return gerritProxy; } /** * Sets the proxy for gerrit ssh commands. * * @param gerritProxy the port nr. */ public void setGerritProxy(String gerritProxy) { this.gerritProxy = gerritProxy; } /** * Sets the shutdown flag. */ private void setShutdownInProgress() { this.shutdownInProgress = true; } /** * If the system is shutting down. I.e. the shutdown method has been called. * * @return true if so. */ public boolean isShutdownInProgress() { return shutdownInProgress; } /** * If already connected. * @return true if already connected. */ public boolean isConnected() { return connected; } @Override public void reconnect() { reconnectCallCount++; nullifyWatchdog(); sshConnection.disconnect(); } /** * Count how many times {@link #reconnect()} has been called since object creation. * * @return the count. */ public int getReconnectCallCount() { return reconnectCallCount; } /** * Closes the connection. * * @param join if the method should wait for the thread to finish before returning. */ public void shutdown(boolean join) { setShutdownInProgress(); nullifyWatchdog(); if (sshConnection != null) { logger.info("Shutting down the ssh connection."); try { sshConnection.disconnect(); } catch (Exception ex) { logger.warn("Error when disconnecting sshConnection.", ex); } } if (join) { try { this.join(); } catch (InterruptedException ex) { logger.warn("Got interrupted while waiting for shutdown.", ex); } } } /** * Notifies all listeners of a Gerrit connection event. * * @param event the event. */ public void notifyListeners(GerritConnectionEvent event) { for (ConnectionListener listener : listeners) { try { switch(event) { case GERRIT_CONNECTION_ESTABLISHED: listener.connectionEstablished(); break; case GERRIT_CONNECTION_DOWN: listener.connectionDown(); break; default: break; } } catch (Exception ex) { logger.error("ConnectionListener threw Exception. ", ex); } } } /** * Notifies all ConnectionListeners that the connection is down. */ protected void notifyConnectionDown() { connected = false; notifyListeners(GerritConnectionEvent.GERRIT_CONNECTION_DOWN); } /** * Notifies all ConnectionListeners that the connection is established. */ protected void notifyConnectionEstablished() { connected = true; notifyListeners(GerritConnectionEvent.GERRIT_CONNECTION_ESTABLISHED); } }
package com.mcbans.firestar.mcbans; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import net.h31ix.anticheat.Anticheat; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import com.mcbans.firestar.mcbans.api.MCBansAPI; import com.mcbans.firestar.mcbans.bukkitListeners.PlayerListener; import com.mcbans.firestar.mcbans.callBacks.BanSync; import com.mcbans.firestar.mcbans.callBacks.MainCallBack; import com.mcbans.firestar.mcbans.callBacks.ServerChoose; import com.mcbans.firestar.mcbans.commands.BaseCommand; import com.mcbans.firestar.mcbans.commands.CommandAltlookup; import com.mcbans.firestar.mcbans.commands.CommandBan; import com.mcbans.firestar.mcbans.commands.CommandBanip; import com.mcbans.firestar.mcbans.commands.CommandBanlookup; import com.mcbans.firestar.mcbans.commands.CommandGlobalban; import com.mcbans.firestar.mcbans.commands.CommandKick; import com.mcbans.firestar.mcbans.commands.CommandLookup; import com.mcbans.firestar.mcbans.commands.CommandMcbans; import com.mcbans.firestar.mcbans.commands.CommandRban; import com.mcbans.firestar.mcbans.commands.CommandTempban; import com.mcbans.firestar.mcbans.commands.CommandUnban; import com.mcbans.firestar.mcbans.commands.MCBansCommandHandler; import com.mcbans.firestar.mcbans.permission.Perms; import com.mcbans.firestar.mcbans.rollback.RollbackHandler; import fr.neatmonster.nocheatplus.NoCheatPlus; public class MCBans extends JavaPlugin { public final String apiRequestSuffix = "4.1"; private static MCBans instance; public int taskID = 0; public HashMap<String, Integer> connectionData = new HashMap<String, Integer>(); public HashMap<String, HashMap<String, String>> playerCache = new HashMap<String, HashMap<String, String>>(); public HashMap<String, Long> resetTime = new HashMap<String, Long>(); public ArrayList<String> mcbStaff = new ArrayList<String>(); public long last_req = 0; public long timeRecieved = 0; public Thread callbackThread = null; public BanSync bansync = null; public Thread syncBan = null; public long lastID = 0; public boolean syncRunning = false; public long lastCallBack = 0; public long lastSync = 0; public String apiServer = null; private ActionLog log = null; private RollbackHandler rbHandler = null; private boolean ncpEnabled = false; private boolean acEnabled = false; private ConfigurationManager config; private MCBansCommandHandler commandHandler; @Override public void onDisable() { if (callbackThread != null) { if (callbackThread.isAlive()) { callbackThread.interrupt(); } } if (syncBan != null) { if (syncBan.isAlive()) { syncBan.interrupt(); } } getServer().getScheduler().cancelTasks(this); instance = null; final PluginDescriptionFile pdfFile = this.getDescription(); log.info(pdfFile.getName() + " version " + pdfFile.getVersion() + " is disabled!"); } @Override public void onEnable() { instance = this; PluginManager pm = getServer().getPluginManager(); log = new ActionLog(this); // setup logger // check online-mode, Do NOT remove this check! /*if (!this.getServer().getOnlineMode()) { log.severe("This server is not in online mode!"); pm.disablePlugin(this); return; }*/ // load configuration config = new ConfigurationManager(this); try{ config.loadConfig(true); }catch (Exception ex){ log.warning("an error occured while trying to load the config file."); ex.printStackTrace(); } if (!pm.isPluginEnabled(this)){ return; } // load language log.info("Loading language file: " + config.getLanguage()); I18n.init(config.getLanguage()); pm.registerEvents(new PlayerListener(this), this); Perms.setupPermissionHandler(); // regist commands commandHandler = new MCBansCommandHandler(this); registerCommands(); MainCallBack thisThread = new MainCallBack(this); callbackThread = new Thread(thisThread); callbackThread.start(); // ban sync bansync = new BanSync(this); syncBan = new Thread(bansync); syncBan.start(); ServerChoose serverChooser = new ServerChoose(this); (new Thread(serverChooser)).start(); // rollback handler rbHandler = new RollbackHandler(this); rbHandler.setupHandler(); // hookup integration plugin checkPlugin(true); if (ncpEnabled) log.info("NoCheatPlus plugin found! Enabled this integration!"); if (acEnabled) log.info("AntiCheat plugin found! Enabled this integration!"); final PluginDescriptionFile pdfFile = this.getDescription(); log.info(pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!"); } @Override public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args){ return commandHandler.onCommand(sender, command, label, args); } @Override public List<String> onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args){ return commandHandler.onTabComplete(sender, command, alias, args); } private void registerCommands(){ List<BaseCommand> cmds = new ArrayList<BaseCommand>(); // Banning Commands cmds.add(new CommandBan()); cmds.add(new CommandGlobalban()); cmds.add(new CommandTempban()); cmds.add(new CommandRban()); // IP Banning Commands cmds.add(new CommandBanip()); // Other action commands cmds.add(new CommandUnban()); cmds.add(new CommandKick()); // Other commands cmds.add(new CommandLookup()); cmds.add(new CommandBanlookup()); cmds.add(new CommandAltlookup()); cmds.add(new CommandMcbans()); for (final BaseCommand cmd : cmds){ commandHandler.registerCommand(cmd); } } public void debug(final String message){ if (getConfigs().isDebug()){ getLog().info(message); } } public void checkPlugin(final boolean startup){ // Check NoCheatPlus Plugin checkNCP = getServer().getPluginManager().getPlugin("NoCheatPlus"); this.ncpEnabled = (checkNCP != null && checkNCP instanceof NoCheatPlus); // Check AntiCheat Plugin checkAC = getServer().getPluginManager().getPlugin("AntiCheat"); this.acEnabled = (checkAC != null && checkAC instanceof Anticheat); if (!startup){ if (ncpEnabled) ncpEnabled = (checkNCP.isEnabled()); if (acEnabled) acEnabled = (checkAC.isEnabled()); } } public boolean isEnabledNCP(){ return this.ncpEnabled; } public boolean isEnabledAC(){ return this.acEnabled; } public RollbackHandler getRbHandler(){ return this.rbHandler; } public MCBansAPI getAPI(final Plugin plugin){ return MCBansAPI.getHandle(this, plugin); } public ConfigurationManager getConfigs(){ return this.config; } public ActionLog getLog(){ return this.log; } public static String getPrefix(){ return instance.config.getPrefix(); } public static MCBans getInstance(){ return instance; } }
package com.sunny.grokkingalgorithms.basic_2020.warmup; import java.util.Stack; public class EquiLeader { public static int solution(int[] A) { int eCount = 0; int dominator = -1; if(A.length > 0) { if(A.length == 1) { return 0; } Stack<Integer> stack = new Stack<Integer>(); stack.push(A[0]); int candidate = Integer.MIN_VALUE; for(int i = 1; i < A.length ; i++) { int current = A[i]; if(stack.isEmpty() || stack.peek() == current) { stack.push(A[i]); //candidate = current; }else if(stack.peek() != current) { stack.pop(); //stack.add(current); } } //System.out.println(stack); //System.out.println(stack.peek()); if(!stack.isEmpty()) { if(stack.size() == 1) { candidate = stack.pop(); }else { int prev = stack.pop(); while(!stack.isEmpty() && stack.peek() != prev) { prev = stack.pop(); } candidate = prev; } } //System.out.println(candidate); //System.out.println(); if(candidate != Integer.MIN_VALUE) { //System.out.println(candidate); int count = 0; for(int i = 0; i < A.length ; i++) { if(candidate == A[i]) { dominator = i; count++; } } //System.out.println(count); //System.out.println(A.length/2); if(count <= (A.length/2)) { dominator = -1; } } //System.out.println(dominator); if(dominator >= 0) { int[] tracker = new int[A.length]; int tCount = 0; for(int i = 0; i < A.length ; i++) { if(A[i] == candidate) { tCount++; } tracker[i] = tCount; } //print(tracker); for(int i = 0; i < tracker.length ; i++) { //System.out.println(i); int curCount = tracker[i]; int leftLength = (i+1); /* * 1 2 3 * 0 1 2 */ int rightLength = A.length - i - 1; //System.out.println(curCount); //System.out.println(leftLength); //System.out.println(rightLength); //System.out.println(); int rightCount = tracker[A.length - 1] - curCount; /* * if(i == A.length - 1) { rightCount = A[A.length - 1]; } */ //System.out.println(rightCount); //System.out.println(); //System.out.println(); if(curCount > leftLength/2 && rightCount > rightLength/2) { //System.out.println(); System.out.println(" i " + i); //System.out.println(leftLength); System.out.println(rightLength); //System.out.println(curCount); System.out.println(eCount); //System.out.println(); eCount++; } } } } return eCount; } public static void print(int[] input) { for(int i : input) { System.out.print(i + " "); } System.out.println(); } public static void main(String[] args) { // TODO Auto-generated method stub /* * A[0] = 4 A[1] = 3 A[2] = 4 A[3] = 4 A[4] = 4 A[5] = 2 1,1,2,3,4,4 0,1,2,3,4,5 */ int[] input = new int[] {4,3,4,4,4,2}; System.out.println(solution(input)); input = new int[] {4, 4, 2, 5, 3, 4, 4, 4}; System.out.println(solution(input)); input = new int[] {4,4,4,4,2,2,2}; System.out.println(solution(input)); } }
package module1.pechincha.cruds; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import module1.pechincha.interf.DAOBehavior; import module1.pechincha.model.Leilao; import module1.pechincha.model.Produto; import module1.pechincha.util.ConnectionFactory; public class JDBCLeilaoDAO extends DAOBehavior<Leilao>{ private Connection c; public JDBCLeilaoDAO(){ c = ConnectionFactory.getConnection(); }; @Override public void insert(Leilao arg) { String sql = "Insert into Leilao (etiqueta,descricao,comprador,ativo,idLeiloeiro,lanceInicial,tempoLimite,nickname,precolote,termino) values ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) "; try { PreparedStatement ps = c.prepareStatement(sql); ps.setString(1,arg.getEtiqueta()); ps.setString(2, arg.getDescricao()); ps.setInt(3, arg.getComprador()); ps.setBoolean(4, arg.isAtivo()); ps.setInt(5, arg.getIdLeiloeiro()); ps.setFloat(6, arg.getLanceInicial()); ps.setInt(7,arg.getTempoLimite()); ps.setString(8, arg.getNickname()); ps.setFloat(9, arg.getPrecolote()); ps.setString(10, arg.getTermino()); ps.execute(); ps.close(); } catch (SQLException e) { throw new RuntimeException("Erro ao inserir dados. Classe JDBCLeilaoDAO", e); } } public boolean verificarProprietarioLeilao(int pkUsuario, int pkLeilao){ try { PreparedStatement ps = c.prepareStatement("select idleiloeiro from leilao where leilao.idleiloeiro=? and leilao.idleilao=?"); ps.setInt(1,pkUsuario); ps.setInt(2,pkLeilao); ResultSet result = ps.executeQuery(); while(result.next()){ if(result.getInt("idleiloeiro")==pkUsuario){ result.close(); ps.close(); return true; } else { result.close(); ps.close(); return false; } } }catch (SQLException e) { throw new RuntimeException("Erro ao listar dados. Classe JDBCLoteProdutoDAO", e); } return false; } public int insertReturningPk(Leilao arg){ String sql = "Insert into Leilao (etiqueta,descricao,comprador,ativo,idLeiloeiro,lanceInicial,tempoLimite,nickname,precolote,termino) values ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) returning idleilao"; System.out.println(sql); try { PreparedStatement ps = c.prepareStatement(sql); ps.setString(1,arg.getEtiqueta()); ps.setString(2, arg.getDescricao()); ps.setInt(3, arg.getComprador()); ps.setBoolean(4, arg.isAtivo()); ps.setInt(5, arg.getIdLeiloeiro()); ps.setFloat(6, arg.getLanceInicial()); ps.setInt(7,arg.getTempoLimite()); ps.setString(8, arg.getNickname()); ps.setFloat(9, arg.getPrecolote()); ps.setString(10, arg.getTermino()); ResultSet result=ps.executeQuery(); int idleilao = 0; while(result.next()){ idleilao = result.getInt("idleilao"); break; } result.close(); ps.close(); return idleilao; } catch (SQLException e) { throw new RuntimeException("Erro ao inserir dados. Classe JDBCLeilaoDAO", e); } } @Override public void delete(int pk) { // TODO Auto-generated method stub } @Override public List<Leilao> list() { List<Leilao> list = new ArrayList<Leilao>(); Leilao temp; try { PreparedStatement ps = c.prepareStatement("select * from leilao"); ResultSet result = ps.executeQuery(); while(result.next()){ temp = new Leilao(); temp.setIdLeilao(result.getInt("idleilao")); temp.setEtiqueta(result.getString("etiqueta")); temp.setTempoLimite(result.getInt("tempolimite")); temp.setDescricao(result.getString("descricao")); temp.setComprador(result.getInt("comprador")); temp.setAtivo(result.getBoolean("ativo")); temp.setIdLeiloeiro(result.getInt("idleiloeiro")); temp.setLanceInicial(result.getFloat("lanceinicial")); temp.setNickname(result.getString("nickname")); temp.setPrecolote(result.getFloat("precolote")); temp.setTermino(result.getString("termino")); list.add(temp); } result.close(); ps.close(); } catch (SQLException e) { throw new RuntimeException("Erro ao listar dados. Classe JDBCLeilaoDAO", e); } return list; } @Override public Leilao select(int pk) { Leilao temp = null; try { PreparedStatement ps = c.prepareStatement("select * from leilao where idleilao = ?"); ps.setInt(1,pk); ResultSet result = ps.executeQuery(); while(result.next()){ temp = new Leilao(); temp.setIdLeilao(result.getInt("idleilao")); temp.setEtiqueta(result.getString("etiqueta")); temp.setTempoLimite(result.getInt("tempolimite")); temp.setDescricao(result.getString("descricao")); temp.setComprador(result.getInt("comprador")); temp.setAtivo(result.getBoolean("ativo")); temp.setIdLeiloeiro(result.getInt("idleiloeiro")); temp.setLanceInicial(result.getFloat("lanceinicial")); temp.setNickname(result.getString("nickname")); temp.setPrecolote(result.getFloat("precolote")); temp.setTermino(result.getString("termino")); break; } result.close(); ps.close(); } catch (SQLException e) { throw new RuntimeException("Erro ao procurar dados. Classe JDBCLeilaoDAO", e); } return temp; } public List<Leilao> getHistorico(int pk) { List<Leilao> list = new ArrayList<Leilao>(); Leilao temp; try { PreparedStatement ps = c.prepareStatement("select * from leilao where idleiloeiro = ? and ativo=false"); ps.setInt(1,pk); ResultSet result = ps.executeQuery(); while(result.next()){ temp = new Leilao(); temp.setIdLeilao(result.getInt("idleilao")); temp.setEtiqueta(result.getString("etiqueta")); temp.setTempoLimite(result.getInt("tempolimite")); temp.setDescricao(result.getString("descricao")); temp.setComprador(result.getInt("comprador")); temp.setAtivo(result.getBoolean("ativo")); temp.setIdLeiloeiro(result.getInt("idleiloeiro")); temp.setLanceInicial(result.getFloat("lanceinicial")); temp.setNickname(result.getString("nickname")); temp.setPrecolote(result.getFloat("precolote")); temp.setTermino(result.getString("termino")); list.add(temp); } result.close(); ps.close(); } catch (SQLException e) { throw new RuntimeException("Erro ao listar dados. Classe JDBCLeilaoDAO", e); } return list; } public Leilao searchEtiqueta(String etiqueta) { Leilao temp = null; try { PreparedStatement ps = c.prepareStatement("select * from leilao where etiqueta= ? "); ps.setString(1,etiqueta); ResultSet result = ps.executeQuery(); while(result.next()){ temp = new Leilao(); temp.setIdLeilao(result.getInt("idleilao")); temp.setEtiqueta(result.getString("etiqueta")); temp.setTempoLimite(result.getInt("tempolimite")); temp.setDescricao(result.getString("descricao")); temp.setComprador(result.getInt("comprador")); temp.setAtivo(result.getBoolean("ativo")); temp.setIdLeiloeiro(result.getInt("idleiloeiro")); temp.setLanceInicial(result.getFloat("lanceinicial")); temp.setNickname(result.getString("nickname")); temp.setPrecolote(result.getFloat("precolote")); temp.setTermino(result.getString("termino")); break; } result.close(); ps.close(); } catch (SQLException e) { throw new RuntimeException("Erro ao procurar dados. Classe JDBCLeilaoDAO", e); } return temp; } @Override public void update(Leilao arg) { String sql = "Update " + arg.getTableName() + " set " + "etiqueta = ?,descricao = ?, comprador = ?, ativo = ?, idleiloeiro = ?, lanceinicial = ?, tempolimite = ?, nickname = ?, precolote = ?, termino = ? " + "where idleilao = ?"; try { PreparedStatement ps = c.prepareStatement(sql); ps.setString(1,arg.getEtiqueta()); ps.setString(2, arg.getDescricao()); ps.setInt(3, arg.getComprador()); ps.setBoolean(4, arg.isAtivo()); ps.setInt(5, arg.getIdLeiloeiro()); ps.setFloat(6, arg.getLanceInicial()); ps.setInt(7,arg.getTempoLimite()); ps.setString(8, arg.getNickname()); ps.setFloat(9, arg.getPrecolote()); ps.setString(10, arg.getTermino()); ps.setInt(11, arg.getIdLeilao()); ps.execute(); ps.close(); } catch (SQLException e) { throw new RuntimeException("Erro ao atualizar dados. Classe JDBCLeilaoDAO", e); } } }
package com.ra4king.shadowtest; import static org.lwjgl.opengl.ARBDepthClamp.*; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL12.*; import static org.lwjgl.opengl.GL13.*; import static org.lwjgl.opengl.GL20.*; import static org.lwjgl.opengl.GL30.*; import java.nio.ByteBuffer; import java.util.HashMap; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import com.ra4king.opengl.util.GLProgram; import com.ra4king.opengl.util.Mesh; import com.ra4king.opengl.util.ShaderProgram; import com.ra4king.opengl.util.Utils; import com.ra4king.opengl.util.loader.XMLMeshLoader; import com.ra4king.opengl.util.math.Matrix3; import com.ra4king.opengl.util.math.Matrix4; import com.ra4king.opengl.util.math.MatrixStack; import com.ra4king.opengl.util.math.Vector3; import com.ra4king.opengl.util.math.Vector4; /** * @author ra4king */ public class ShadowTest extends GLProgram { public static void main(String[] args) { new ShadowTest().run(3, 0); } private Shader shadowShader, shadowDummyShader; private Mesh cube, plane; private int shadowTexture; private int shadowFBO; private int shadowTextureWidth = 3200, shadowTextureHeight = 2400; private float xRot, yRot; private float radius; private boolean showLightPerspective; public ShadowTest() { super("Shadow Test", 800, 600, true); Mouse.setGrabbed(true); } @Override public void init() { setFPS(0); glClearColor(0, 0, 0, 0); glClearDepth(1); glEnable(GL_DEPTH_TEST); glDepthRange(0, 1); glDepthMask(true); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glFrontFace(GL_CW); glEnable(GL_DEPTH_CLAMP); HashMap<Integer,String> attribs = new HashMap<>(); attribs.put(0, "position"); attribs.put(1, "norm"); shadowShader = new Shader(new ShaderProgram(readFromFile("shadow_test.vert"), readFromFile("shadow_test.frag"), attribs)); shadowDummyShader = new Shader(new ShaderProgram(readFromFile("shadow_dummy.vert"), readFromFile("shadow_dummy.frag"), attribs)); try { cube = XMLMeshLoader.createMesh(getClass().getResource("cube.xml")); plane = XMLMeshLoader.createMesh(getClass().getResource("plane.xml")); } catch(Exception exc) { exc.printStackTrace(); System.exit(-1); } shadowTexture = glGenTextures(); glBindTexture(GL_TEXTURE_2D, shadowTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, shadowTextureWidth, shadowTextureHeight, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, (ByteBuffer)null); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glBindTexture(GL_TEXTURE_2D, 0); shadowFBO = glGenFramebuffers(); glBindFramebuffer(GL_FRAMEBUFFER, shadowFBO); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, shadowTexture, 0); int i = glCheckFramebufferStatus(GL_FRAMEBUFFER); if(i != GL_FRAMEBUFFER_COMPLETE) { System.err.println("ERROR: " + i); System.exit(-1); } glBindFramebuffer(GL_FRAMEBUFFER, 0); } @Override public void resized() {} @Override public void update(long deltaTime) { xRot += Mouse.getDX() * 0.5f; yRot -= Mouse.getDY() * 0.5f; int dwheel = Mouse.getDWheel(); if(dwheel > 0) radius += 0.5f; else if(dwheel < 0) radius -= 0.5f; yRot = Utils.clamp(yRot, -90, 90); radius = Utils.clamp(radius, -Float.MAX_VALUE, -4); } @Override public void keyPressed(int key, char c) { switch(key) { case Keyboard.KEY_SPACE: Mouse.setGrabbed(!Mouse.isGrabbed()); break; case Keyboard.KEY_C: showLightPerspective = !showLightPerspective; break; } } @Override public void render() { final Vector4 lightDir = new Vector4(-1, -1, 0.5f, 0); final Matrix4 shadowViewMatrix = Utils.lookAt(new Vector3(lightDir.copy().mult(-5)), new Vector3(0, 0, 0), new Vector3(0, 1, 0)); final Matrix4 shadowProjectionMatrix = new Matrix4().clearToOrtho(-5, 5, -4, 3, 1, 1000); { glBindFramebuffer(GL_FRAMEBUFFER, shadowFBO); glViewport(0, 0, shadowTextureWidth, shadowTextureHeight); glClear(GL_DEPTH_BUFFER_BIT); shadowDummyShader.program.begin(); glUniformMatrix4(shadowDummyShader.projectionMatrixUniform, false, shadowProjectionMatrix.toBuffer()); glUniformMatrix4(shadowDummyShader.viewMatrixUniform, false, shadowViewMatrix.toBuffer()); drawScene(shadowDummyShader); shadowDummyShader.program.end(); glBindFramebuffer(GL_FRAMEBUFFER, 0); } { glViewport(0, 0, getWidth(), getHeight()); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shadowShader.program.begin(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, shadowTexture); glUniformMatrix4(shadowShader.shadowProjectionMatrixUniform, false, shadowProjectionMatrix.toBuffer()); glUniformMatrix4(shadowShader.shadowViewMatrixUniform, false, shadowViewMatrix.toBuffer()); final Matrix4 viewMatrix; if(showLightPerspective) { glUniformMatrix4(shadowShader.projectionMatrixUniform, false, shadowProjectionMatrix.toBuffer()); viewMatrix = shadowViewMatrix; } else { glUniformMatrix4(shadowShader.projectionMatrixUniform, false, new Matrix4().clearToPerspectiveDeg(90, getWidth(), getHeight(), 1, 1000).toBuffer()); viewMatrix = new Matrix4().clearToIdentity(); viewMatrix.translate(0, 0, radius); viewMatrix.rotateDeg(yRot, 1, 0, 0); viewMatrix.rotateDeg(xRot, 0, 1, 0); } glUniformMatrix4(shadowShader.viewMatrixUniform, false, viewMatrix.toBuffer()); glUniform4(shadowShader.lightPositionUniform, viewMatrix.mult(lightDir).toBuffer()); drawScene(shadowShader); shadowShader.program.end(); glBindTexture(GL_TEXTURE_2D, 0); } } private void drawScene(Shader program) { MatrixStack modelMatrix = new MatrixStack(); Vector4 cubeColor = new Vector4(0.1f, 0.3f, 0.9f, 1); Vector4 cubeAmbient = cubeColor.copy().mult(0.1f).w(0); Vector4 planeColor = new Vector4(0.9f, 0.9f, 0, 1); Vector4 planeAmbient = planeColor.copy().mult(0.1f).w(0); { modelMatrix.pushMatrix(); modelMatrix.getTop().translate(0, 0, -1); { modelMatrix.pushMatrix(); if(program.diffuseUniform != -1) { glUniform4(program.diffuseUniform, cubeColor.toBuffer()); glUniform4(program.ambientUniform, cubeAmbient.toBuffer()); glUniformMatrix3(program.normalMatrixUniform, false, new Matrix3(modelMatrix.getTop()).inverse().transpose().toBuffer()); } glUniformMatrix4(program.modelMatrixUniform, false, modelMatrix.getTop().toBuffer()); cube.render(); modelMatrix.popMatrix(); } { modelMatrix.pushMatrix(); modelMatrix.getTop().translate(2, 0, 2); modelMatrix.getTop().rotateDeg(45, 0, 1, 0); if(program.diffuseUniform != -1) { glUniform4(program.diffuseUniform, cubeColor.toBuffer()); glUniform4(program.ambientUniform, cubeAmbient.toBuffer()); glUniformMatrix3(program.normalMatrixUniform, false, new Matrix3(modelMatrix.getTop()).inverse().transpose().toBuffer()); } glUniformMatrix4(program.modelMatrixUniform, false, modelMatrix.getTop().toBuffer()); cube.render(); modelMatrix.popMatrix(); } { modelMatrix.pushMatrix(); modelMatrix.getTop().translate(1, 2, 1); modelMatrix.getTop().rotateDeg(20, 0, 1, 0); if(program.diffuseUniform != -1) { glUniform4(program.diffuseUniform, cubeColor.toBuffer()); glUniform4(program.ambientUniform, cubeAmbient.toBuffer()); glUniformMatrix3(program.normalMatrixUniform, false, new Matrix3(modelMatrix.getTop()).inverse().transpose().toBuffer()); } glUniformMatrix4(program.modelMatrixUniform, false, modelMatrix.getTop().toBuffer()); cube.render(); modelMatrix.popMatrix(); } modelMatrix.popMatrix(); } { modelMatrix.pushMatrix(); modelMatrix.getTop().translate(0, -1.01f, 0); modelMatrix.getTop().scale(5); if(program.diffuseUniform != -1) { glUniform4(program.diffuseUniform, planeColor.toBuffer()); glUniform4(program.ambientUniform, planeAmbient.toBuffer()); glUniformMatrix3(program.normalMatrixUniform, false, new Matrix3(modelMatrix.getTop()).inverse().transpose().toBuffer()); } glUniformMatrix4(program.modelMatrixUniform, false, modelMatrix.getTop().toBuffer()); plane.render(); modelMatrix.popMatrix(); } } private static class Shader { private ShaderProgram program; private int lightPositionUniform; private int diffuseUniform; private int ambientUniform; private int normalMatrixUniform; private int modelMatrixUniform; private int viewMatrixUniform; private int projectionMatrixUniform; private int shadowViewMatrixUniform; private int shadowProjectionMatrixUniform; public Shader(ShaderProgram program) { this.program = program; lightPositionUniform = program.getUniformLocation("lightPosition"); diffuseUniform = program.getUniformLocation("diffuse"); ambientUniform = program.getUniformLocation("ambient"); normalMatrixUniform = program.getUniformLocation("normalMatrix"); modelMatrixUniform = program.getUniformLocation("modelMatrix"); viewMatrixUniform = program.getUniformLocation("viewMatrix"); projectionMatrixUniform = program.getUniformLocation("projectionMatrix"); shadowViewMatrixUniform = program.getUniformLocation("shadowViewMatrix"); shadowProjectionMatrixUniform = program.getUniformLocation("shadowProjectionMatrix"); program.begin(); glUniform1i(glGetUniformLocation(program.getProgram(), "shadowMap"), 0); program.end(); } } }
package com.urbandroid.sleep.captcha.launcher; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.urbandroid.sleep.captcha.CaptchaConstant; import com.urbandroid.sleep.captcha.CaptchaSupportException; import com.urbandroid.sleep.captcha.annotation.CaptchaDifficulty; import com.urbandroid.sleep.captcha.annotation.CaptchaEvent; import com.urbandroid.sleep.captcha.annotation.CaptchaMode; import com.urbandroid.sleep.captcha.annotation.SleepOperation; import com.urbandroid.sleep.captcha.domain.CaptchaInfo; import com.urbandroid.sleep.captcha.intent.CallbackIntentCreator; import com.urbandroid.sleep.captcha.util.IntentUtil; import static com.urbandroid.sleep.captcha.CaptchaConstant.CAPTCHA_ACTION_LAUNCH; import static com.urbandroid.sleep.captcha.CaptchaConstant.CAPTCHA_ACTION_SOLVED; import static com.urbandroid.sleep.captcha.CaptchaConstant.CAPTCHA_BACK_INFO; import static com.urbandroid.sleep.captcha.CaptchaConstant.CAPTCHA_CONFIG_DIFFICULTY; import static com.urbandroid.sleep.captcha.CaptchaConstant.CAPTCHA_ORIGIN_INTENT; import static com.urbandroid.sleep.captcha.CaptchaConstant.SUCCESS; import static com.urbandroid.sleep.captcha.CaptchaConstant.TAG; public class BaseCaptchaLauncher implements CaptchaLauncher { protected final Context context; protected final Intent originIntent; protected @CaptchaDifficulty int difficulty = CaptchaDifficulty.VERY_SIMPLE; protected @CaptchaMode int mode = CaptchaMode.CAPTCHA_MODE_OPERATIONAL; protected @SleepOperation String operation = SleepOperation.OPERATION_NONE; protected CallbackIntentCreator callbackIntentCreator; protected int flags = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP; public BaseCaptchaLauncher(final @NonNull Context context) { this(context, null); } public BaseCaptchaLauncher(final @NonNull Context context, final @Nullable Intent originIntent) { this.context = context; this.originIntent = originIntent; } @Override public CaptchaLauncher difficulty(final @CaptchaDifficulty int difficulty) { this.difficulty = difficulty; return this; } @Override public CaptchaLauncher operation(final @SleepOperation String operation) { this.operation = operation; return this; } @Override public CaptchaLauncher callbackIntentCreator(final @NonNull CallbackIntentCreator callbackIntentCreator) { this.callbackIntentCreator = callbackIntentCreator; return this; } @Override public CaptchaLauncher addFlags(final int flags) { this.flags |= flags; return this; } @Override public CaptchaLauncher mode(@CaptchaMode int mode) { this.mode = mode; return this; } @Override public void start(final @NonNull CaptchaInfo captchaInfo) { Log.i(TAG, "Starting captcha mode: " + mode + " difficulty: " + difficulty + " operation: " + operation + " " + captchaInfo); final Intent intent = prepareIntent(captchaInfo); final StringBuilder sb = new StringBuilder(); IntentUtil.traceIntent(sb, intent); Log.d(TAG, sb.toString()); context.startActivity(intent); } @NonNull @Override public Intent prepareIntent(final @NonNull CaptchaInfo captchaInfo) { switch (mode) { case CaptchaMode.CAPTCHA_MODE_CONFIGURATION: return new Intent(CaptchaConstant.CAPTCHA_ACTION_CONFIG) .setClassName(captchaInfo.getPackageName(), captchaInfo.getActivityName()) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .putExtra(CaptchaConstant.CAPTCHA_CONFIG_DIFFICULTY, difficulty); case CaptchaMode.CAPTCHA_MODE_PREVIEW: return new Intent(CaptchaConstant.CAPTCHA_ACTION_LAUNCH) .setClassName(captchaInfo.getPackageName(), captchaInfo.getActivityName()) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .putExtra(CaptchaConstant.CAPTCHA_CONFIG_DIFFICULTY, difficulty) .putExtra(CaptchaConstant.PREVIEW, true); case CaptchaMode.CAPTCHA_MODE_OPERATIONAL: final Intent solvedCaptchaIntent = callbackIntentCreator == null ? new Intent(CAPTCHA_ACTION_SOLVED) .putExtra(CAPTCHA_ORIGIN_INTENT, originIntent) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .setPackage(context.getPackageName()) : callbackIntentCreator.createSolvedIntent(context, operation); solvedCaptchaIntent.putExtra(operation, true); solvedCaptchaIntent.putExtra(CAPTCHA_BACK_INFO, captchaInfo); final Intent unsolvedCaptchaIntent = callbackIntentCreator == null ? new Intent(CAPTCHA_ACTION_SOLVED) .putExtra(CAPTCHA_ORIGIN_INTENT, originIntent) .putExtra(SUCCESS, false) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .setPackage(context.getPackageName()) : callbackIntentCreator.createUnsolvedIntent(context, operation); unsolvedCaptchaIntent.putExtra(CAPTCHA_BACK_INFO, captchaInfo); final Intent captchaAliveIntent = new Intent(CaptchaConstant.CAPTCHA_ACTION_ALIVE); return new Intent(CAPTCHA_ACTION_LAUNCH) .setClassName(captchaInfo.getPackageName(), captchaInfo.getActivityName()) .setFlags(flags) // back call intents .putExtra(CaptchaEvent.CAPTCHA_BACK_INTENT_SOLVED, solvedCaptchaIntent) .putExtra(CaptchaEvent.CAPTCHA_BACK_INTENT_UNSOLVED, unsolvedCaptchaIntent) .putExtra(CaptchaEvent.CAPTCHA_BACK_INTENT_ALIVE, captchaAliveIntent) // config params .putExtra(CAPTCHA_CONFIG_DIFFICULTY, difficulty) .putExtra(operation, true); } throw new CaptchaSupportException("Unknown captcha mode: " + mode); } }
package de.hpi.bpmn2bpel.factories.apacheode; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringReader; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.commons.configuration.DatabaseConfiguration; import org.apache.log4j.Logger; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.jdom.input.SAXBuilder; import de.hpi.bpmn2bpel.TransformationResult; import de.hpi.bpmn2bpel.TransformationResult.Type; import de.hpi.bpmn2bpel.factories.apacheode.deploymentservice.DeploymentServiceLayer; import de.hpi.bpmn2bpel.factories.apacheode.deploymentservice.stub.DeployUnit; /** * This class provides methods to create the process WSDL and the deployment * descriptor on the basis of the BPEL-Process document. * * @author Paul Schroeder * @author Sven Wagner-Boysen */ public class DeployProcessFactory { /** logger variable */ private static Logger logger = Logger.getLogger(DeployProcessFactory.class); private final static String partnerLinkNamespaceTag = "plnk"; private String ODE_URL = "http://localhost:8080/ode/"; private Document bpelDocument; private Document processWsdlDocument; private Element definitions; private Document deployDocument; private Element deploy; private Set<String> wsdlUrls; private HashMap<String, String> wsdls; private List<TransformationResult> deployProcessData; public static DeployProcessFactory getNewDeployProcessFactory(String apacheOdeUrl) { DeployProcessFactory deployProcessFactory = new DeployProcessFactory(); deployProcessFactory.wsdls = new HashMap<String, String>(); deployProcessFactory.ODE_URL = apacheOdeUrl; return deployProcessFactory; } /** * Creates t * @param bpelProcess */ public List<TransformationResult> buildDeployProcessData( TransformationResult bpelProcess, Set<String> wsdlUrls) { this.deployProcessData = new ArrayList<TransformationResult>(); /* retrieve BPEL Document */ this.bpelDocument = createDocumentFromString(createStringFromDocument(bpelProcess.getDocument())); /* set wsdlUrls */ this.wsdlUrls = wsdlUrls; /* document builder */ DocumentBuilder builder = null; try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); builder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { logger.error(e.getMessage(), e); } processWsdlDocument = builder.newDocument(); Element processWsdl = createBpelProcessWsdl(); processWsdlDocument.appendChild(processWsdl); /* Append process WSDL to process's deployment data */ this.deployProcessData.add( new TransformationResult(Type.PROCESS_WSDL, processWsdlDocument)); /* * Generate Apache ODE Deployment Descriptor */ /* Build new document for deployment descriptor */ deployDocument = builder.newDocument(); Element deploymentDescriptorDocument = createDeploymentDescriptor(); deployDocument.appendChild(deploymentDescriptorDocument); /* Append deployment descriptor to process's deployment data */ this.deployProcessData.add( new TransformationResult(Type.DEPLOYMENT_DESCRIPTOR, deployDocument)); return this.deployProcessData; } /** * Creates the WSDL document to describe the web-service, representing the * business process in Apache ODE. * * @return * The WSDL definition element */ private Element createBpelProcessWsdl() { this.definitions = this.processWsdlDocument.createElement("definitions"); Element bpelProcessElement = (Element) bpelDocument.getElementsByTagName( "process").item(0); String processName = bpelProcessElement.getAttribute("name"); String processTargetNamespace = bpelProcessElement.getAttribute("targetNamespace"); this.definitions.setAttribute("name", processName); this.definitions.setAttribute("targetNamespace", processTargetNamespace); this.definitions.setAttribute("xmlns:tns", processTargetNamespace); this.definitions.setAttribute("xmlns", "http://schemas.xmlsoap.org/wsdl/"); this.definitions.setAttribute("xmlns:soap", "http://schemas.xmlsoap.org/wsdl/soap/"); this.definitions.setAttribute("xmlns:" + partnerLinkNamespaceTag, "http://docs.oasis-open.org/wsbpel/2.0/plnktype"); NodeList partnerLinksNodeList = bpelDocument.getElementsByTagNameNS("http://docs.oasis-open.org/wsbpel/2.0/process/executable", "partnerLink"); /* add partner links */ for( Element e: createPartnerLinkType(partnerLinksNodeList)){ this.definitions.appendChild(e); } NodeList importsNodeList = bpelDocument.getElementsByTagNameNS("http://docs.oasis-open.org/wsbpel/2.0/process/executable", "import"); for( Element e: copyImports(importsNodeList)){ this.definitions.appendChild(e); } Element processWsdlTypes = createTypes(); this.definitions.appendChild(processWsdlTypes); for( Element e: createMessages()){ this.definitions.appendChild(e); } Element processWsdlPortType = createPortType(); this.definitions.appendChild(processWsdlPortType); Element processWsdlBinding = createBindings(); this.definitions.appendChild(processWsdlBinding); Element processWsdlService = createServiceElement(); this.definitions.appendChild(processWsdlService); return this.definitions; } private Element createDeploymentDescriptor() { this.deploy = deployDocument.createElement("deploy"); this.deploy.setAttribute("xmlns", "http: Element process = deployDocument.createElement("process"); this.deploy.appendChild(process); Element processNode = (Element) bpelDocument.getElementsByTagName("process").item(0); String processName = processNode.getAttribute("name"); String deploymProcessName = "tns:" + processName; process.setAttribute("name", deploymProcessName); Element processEvents = deployDocument.createElement("process-events"); process.appendChild(processEvents); processEvents.setAttribute("generate", "all"); for( Element e: createProvide()){ process.appendChild(e); } for( Element e: createInvoke()){ process.appendChild(e); } return deploy; } private List<Element> createProvide() { List<Element> provideList = new ArrayList<Element>(); NodeList provideNodeList = bpelDocument.getElementsByTagName("receive"); for(int provideNr = 0; provideNr < provideNodeList.getLength(); provideNr++) { Element provideTag = (Element) provideNodeList.item(provideNr); String providePartnerLink = provideTag.getAttribute("partnerLink"); String provideServiceName = provideTag.getAttribute("serviceName"); String providePortType = provideTag.getAttribute("portType"); Element provide = deployDocument.createElement("provide"); provide.setAttribute("partnerLink", providePartnerLink); Element service = createProvideInvokeService(provideServiceName, providePortType, null); provide.appendChild(service); provideList.add(provide); } return provideList; } private List<Element> createInvoke() { // List<EWSDL> ewsdls = executionPlan.getEwsdlsForExecution(); List<Element> invokeList = new ArrayList<Element>(); /*get all invoke tags*/ NodeList invokeNodeList = bpelDocument.getElementsByTagName("invoke"); /* test if there are more than one soap:address tag in the wsdl*/ for(int invokeNr = 0; invokeNr < invokeNodeList.getLength(); invokeNr++) { Element invokeTag = (Element) invokeNodeList.item(invokeNr); String invokePartnerLink = invokeTag.getAttribute("partnerLink"); String invokePortType = invokeTag.getAttribute("portType"); String wsdlPortTypeName = getLastPartofString(invokePortType, ":"); Element deployInvoke = deployDocument.createElement("invoke"); deployInvoke.setAttribute("partnerLink", invokePartnerLink); // String proxyUrl = systemConfiguration.getString(SystemConfiguration.STATION_PROXY_URL_PROPERTY); for(String wsdlUrl : this.wsdlUrls) { Document docWsdl = createDocumentFromUrl(wsdlUrl); NodeList wsdlPortTypeNodeList = docWsdl.getElementsByTagNameNS("http://schemas.xmlsoap.org/wsdl/", "portType"); for(int wsdlPortTypeNr = 0; wsdlPortTypeNr < wsdlPortTypeNodeList.getLength(); wsdlPortTypeNr++) { Element wsdlPortType = (Element) wsdlPortTypeNodeList.item(wsdlPortTypeNr); if(wsdlPortType.getAttribute("name").equals(wsdlPortTypeName)){ String serviceName = invokeTag.getAttribute("serviceName"); String portType = invokeTag.getAttribute("portType"); Element invokeService = createProvideInvokeService(serviceName, portType, docWsdl); deployInvoke.appendChild(invokeService); // String wsdlName = wsdlNameTag.getAttribute("name"); // String invokeServiceName = wsdlTargetNamespacePrefix + ":" + wsdlName; //// invokeService.setAttribute("name", invokeServiceName); //// NodeList wsdlServiceNameNodeList = docWsdl.getElementsByTagName("service"); //// for(int wsdlServiceNameNr = 0; wsdlServiceNameNr < wsdlServiceNameNodeList.getLength(); wsdlServiceNameNr++) { //// Element wsdlServiceNameTag = (Element) wsdlServiceNameNodeList.item(wsdlServiceNameNr); //// if(wsdlServiceNameTag.getAttribute("name").equals(wsdlName)) { //// Element wsdlServicePort = (Element) wsdlServiceNameTag.getElementsByTagName("port").item(0); //// String invokeServicePort = wsdlServicePort.getAttribute("name"); //// invokeService.setAttribute("port", invokeServicePort); } } } invokeList.add(deployInvoke); } return invokeList; } private Element createProvideInvokeService(String serviceName, String portType, Document wsdl) { Element service = deployDocument.createElement("service"); String serviceNamePrefix = getFirstPartofString(portType, ":"); String name = serviceNamePrefix + ":" + serviceName; service.setAttribute("name", name); setNamespace(deploy , portType); String port = getPortForServiceName(serviceName, wsdl); service.setAttribute("port", port); return service; } private void setNamespace(Element document, String portType) { String prefix = getFirstPartofString(portType, ":"); String namespaceUri = bpelDocument.lookupNamespaceURI(prefix); document.setAttribute("xmlns:" + prefix, namespaceUri); } private String getPortForServiceName(String serviceName, Document wsdl) { String port = null; NodeList bpelServiceNodeList = null; if(wsdl == null){ bpelServiceNodeList = processWsdlDocument.getElementsByTagName("service"); for(int bpelServiceNodeListNr = 0; bpelServiceNodeListNr < bpelServiceNodeList.getLength(); bpelServiceNodeListNr++){ Element bpelServiceNode = (Element) bpelServiceNodeList.item(bpelServiceNodeListNr); String bpelServiceName = bpelServiceNode.getAttribute("name"); if(bpelServiceName.equals(serviceName)){ Element portTag = (Element) bpelServiceNode.getElementsByTagName("port").item(0); port = portTag.getAttribute("name"); } } } else{ bpelServiceNodeList = wsdl.getElementsByTagName("service"); for(int bpelServiceNodeListNr = 0; bpelServiceNodeListNr < bpelServiceNodeList.getLength(); bpelServiceNodeListNr++){ Element bpelServiceNode = (Element) bpelServiceNodeList.item(bpelServiceNodeListNr); String bpelServiceName = bpelServiceNode.getAttribute("name"); if(bpelServiceName.equals(serviceName)){ Element portTag = (Element) bpelServiceNode.getElementsByTagName("port").item(0); port = portTag.getAttribute("name"); } } } return port; } private Element createServiceElement() { String serviceName = getBpelProcessServiceName(); Element service = processWsdlDocument.createElement("service"); service.setAttribute("name", serviceName); Element port = processWsdlDocument.createElement("port"); port.setAttribute("name", "InvokePort"); port.setAttribute("binding", "tns:WsBinding"); service.appendChild(port); Element soapAddress = processWsdlDocument.createElement("soap:address"); soapAddress.setAttribute("location", ODE_URL + "/processes/" + serviceName); port.appendChild(soapAddress); return service; } private String getBpelProcessServiceName() { NodeList partnerLinkNodeList = bpelDocument.getElementsByTagName("partnerLink"); String serviceName = null; for(int partnerLinkNodeListNr = 0; partnerLinkNodeListNr < partnerLinkNodeList.getLength(); partnerLinkNodeListNr++){ Element partnerLinkNode = (Element) partnerLinkNodeList.item(partnerLinkNodeListNr); String partnerLinkServiceName = partnerLinkNode.getAttribute("serviceName"); if(partnerLinkServiceName.contains("InvokeProcess")){ serviceName = partnerLinkServiceName; break; } } this.deployProcessData.add(new TransformationResult(Type.SERVICE_NAME, serviceName)); return serviceName; } private Element createBindings() { Element binding = processWsdlDocument.createElement("binding"); binding.setAttribute("name", "WsBinding"); binding.setAttribute("type", "tns:InvokeProcess"); Element soapBinding = processWsdlDocument.createElement("soap:binding"); soapBinding.setAttribute("style", "document"); soapBinding.setAttribute("transport", "http://schemas.xmlsoap.org/soap/http"); binding.appendChild(soapBinding); Element operation = processWsdlDocument.createElement("operation"); operation.setAttribute("name", "process"); binding.appendChild(operation); String targetNamespace = this.definitions.getAttribute("targetNamespace"); Element soapOperation = processWsdlDocument.createElement("soap:operation"); soapOperation.setAttribute("soapAction", targetNamespace); operation.appendChild(soapOperation); Element input = processWsdlDocument.createElement("input"); operation.appendChild(input); Element soapBody1 = processWsdlDocument.createElement("soap:body"); soapBody1.setAttribute("use", "literal"); input.appendChild(soapBody1); Element output = processWsdlDocument.createElement("output"); operation.appendChild(output); Element soapBody2 = processWsdlDocument.createElement("soap:body"); soapBody2.setAttribute("use", "literal"); output.appendChild(soapBody2); return binding; } private Element createPortType() { Element portType = processWsdlDocument.createElement("portType"); portType.setAttribute("name", "InvokeProcess"); Element operation = processWsdlDocument.createElement("operation"); operation.setAttribute("name", "process"); portType.appendChild(operation); Element input = processWsdlDocument.createElement("input"); input.setAttribute("message", "tns:InvokeProcessRequestMessage"); operation.appendChild(input); Element output = processWsdlDocument.createElement("output"); output.setAttribute("message", "tns:InvokeProcessResponseMessage"); operation.appendChild(output); return portType; } private List<Element> createMessages() { List<Element> messages = new ArrayList<Element>(); Element message1 = processWsdlDocument.createElement("message"); message1.setAttribute("name", "InvokeProcessRequestMessage"); Element part1 = processWsdlDocument.createElement("part"); message1.appendChild(part1); part1.setAttribute("name", "payload"); part1.setAttribute("element", "tns:InvokeProcessRequest"); Element message2 = processWsdlDocument.createElement("message"); message2.setAttribute("name", "InvokeProcessResponseMessage"); Element part2 = processWsdlDocument.createElement("part"); message2.appendChild(part2); part2.setAttribute("name", "payload"); part2.setAttribute("element", "tns:InvokeProcessResponse"); messages.add(message1); messages.add(message2); return messages; } private Element createTypes() { Element type = processWsdlDocument.createElement("types"); Element schema = processWsdlDocument.createElement("schema"); type.appendChild(schema); String targetNamespace = this.definitions.getAttribute("targetNamespace"); schema.setAttribute("attributeFormDefault","unqualified"); schema.setAttribute("elementFormDefault","qualified"); schema.setAttribute("xmlns","http: schema.setAttribute("targetNamespace",targetNamespace); Element element1 = processWsdlDocument.createElement("element"); element1.setAttribute("name", "InvokeProcessRequest"); Element complexType1 = processWsdlDocument.createElement("complexType"); Element sequence1 = processWsdlDocument.createElement("sequence"); Element element11 = processWsdlDocument.createElement("element"); element11.setAttribute("name", "token"); element11.setAttribute("type", "string"); Element element12 = processWsdlDocument.createElement("element"); element12.setAttribute("name", "reportingServiceUrl"); element12.setAttribute("type", "string"); Element element2 = processWsdlDocument.createElement("element"); element2.setAttribute("name", "InvokeProcessResponse"); Element complexType2 = processWsdlDocument.createElement("complexType"); Element sequence2 = processWsdlDocument.createElement("sequence"); Element element21 = processWsdlDocument.createElement("element"); element21.setAttribute("name", "result"); element21.setAttribute("type", "string"); schema.appendChild(element1); element1.appendChild(complexType1); complexType1.appendChild(sequence1); sequence1.appendChild(element11); sequence1.appendChild(element12); schema.appendChild(element2); element2.appendChild(complexType2); complexType2.appendChild(sequence2); sequence2.appendChild(element21); return type; } private List<Element> createPartnerLinkType(NodeList partnerLinks) { List<Element> partnerLinkTypes = new ArrayList<Element>(); for(int partnerLinksNr = 0; partnerLinksNr < partnerLinks.getLength(); partnerLinksNr++){ Element partnerLinkNode = (Element) partnerLinks.item(partnerLinksNr); String partnerLinkTypeTag = partnerLinkNode.getAttribute("partnerLinkType"); Element partnerLinkType = processWsdlDocument.createElement(partnerLinkNamespaceTag + ":partnerLinkType"); String partnerTypeLinkName = getLastPartofString(partnerLinkTypeTag, ":"); partnerLinkType.setAttribute("name", partnerTypeLinkName); partnerLinkType.appendChild(createPartnerLinkTypeRole(partnerLinkNode, partnerLinksNr + 1)); partnerLinkTypes.add(partnerLinkType); } return partnerLinkTypes; } private Element createPartnerLinkTypeRole(Element partnerLinkNode, int partnerLinkNr) { Element partnerLinkTypeRole = processWsdlDocument.createElement(partnerLinkNamespaceTag + ":role"); String partnerTypeLinkRoleName = partnerLinkNode.getAttribute("partnerRole"); if(partnerTypeLinkRoleName.length() == 0){ partnerTypeLinkRoleName = partnerLinkNode.getAttribute("myRole"); } partnerLinkTypeRole.setAttribute("name", partnerTypeLinkRoleName); String partnerLinkServiceName = partnerLinkNode.getAttribute("serviceName"); String BpelInvokePortType = getPortTypeForServiceName(partnerLinkServiceName); String partnerLinkTypePortTypePrefix = null; if(BpelInvokePortType == null){ BpelInvokePortType = getBpelTnsAndServiceName(); partnerLinkTypePortTypePrefix = "tns"; } else{ partnerLinkTypePortTypePrefix = "wsdl" + partnerLinkNr; } String partnerLinkTypePortType = getLastPartofString(BpelInvokePortType, ":"); String partnerLinkNamespacePrefix = getFirstPartofString(BpelInvokePortType, ":"); String partnerLinkNamespace = bpelDocument.lookupNamespaceURI(partnerLinkNamespacePrefix); partnerLinkTypeRole.setAttribute("portType", partnerLinkTypePortTypePrefix + ":" + partnerLinkTypePortType); setNamespacePrefix(partnerLinkTypePortTypePrefix, partnerLinkNamespace); return partnerLinkTypeRole; } private List<Element> copyImports(NodeList importsNodeList) { List<Element> imports = new ArrayList<Element>(); for(int importsNodeListNr = 0; importsNodeListNr < importsNodeList.getLength(); importsNodeListNr++){ Element importNode = (Element) importsNodeList.item(importsNodeListNr); String importNodeLocation = importNode.getAttribute("location"); String importNodeNamespace = importNode.getAttribute("namespace"); String wsdlNamespace = bpelDocument.lookupNamespaceURI("tns"); if(!importNodeNamespace.equals(wsdlNamespace)){ Element importTag = processWsdlDocument.createElement("import"); importTag.setAttribute("location", importNodeLocation); importTag.setAttribute("namespace", importNodeNamespace); imports.add(importTag); } } return imports; } /** * Create a w3c document from a given URI. * * @param uri * @return * @throws IOException */ private Document createDocumentFromUrl(String wsdlUrl) { try { URL url = new URL(wsdlUrl); URLConnection connection = url.openConnection(); BufferedReader responseReader = new BufferedReader( new InputStreamReader(connection.getInputStream())); String line; String responseText = ""; while ((line = responseReader.readLine()) != null) { responseText += line; } Document wsdlDocument = createDocumentFromString(responseText); Element defElement = (Element) wsdlDocument.getElementsByTagNameNS("http://schemas.xmlsoap.org/wsdl/", "definitions").item(0); Element sElement = (Element) defElement.getElementsByTagNameNS("http://schemas.xmlsoap.org/wsdl/", "service").item(0); String serviceName = sElement.getAttribute("name"); this.wsdls.put(serviceName, responseText); return wsdlDocument; } catch (Exception e) { logger.error("Cannnot create document from uri", e); } return null; } /** * Create a w3c document from a given string. * * @param stringVar * @return * @throws BuildBpelAccessoriesFailException */ private Document createDocumentFromString(String stringVar) { /* Wrap WSDL string in an InputSource for the DocumentBuilder */ InputSource stringSource = new InputSource(new StringReader(stringVar)); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); /* Activate validation and namespace support */ documentBuilderFactory.setValidating(false); documentBuilderFactory.setNamespaceAware(true); /* Create the w3c.dom.Document */ Document docDocument = null; try { docDocument = documentBuilderFactory.newDocumentBuilder().parse(stringSource); } catch (Exception e) { logger.error("Cannnot create document from string", e); } return docDocument; } /** * Create a string from a given w3c document. * * @param docDocument * @return * @throws BuildBpelAccessoriesFailException */ private String createStringFromDocument(Document docDocument) { OutputFormat format = new OutputFormat(docDocument); StringWriter stringOut = new StringWriter(); XMLSerializer serial = new XMLSerializer(stringOut, format); try { serial.serialize(docDocument); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String docOutString = stringOut.toString(); return docOutString; // Source source = new DOMSource(docDocument); // StringWriter stringWriter = new StringWriter(); // Result result = new StreamResult(stringWriter); // //TODO fill exceptions messageses // try { // TransformerFactory transformerFactory = TransformerFactory.newInstance(); // Transformer transformer = transformerFactory.newTransformer(); // transformer.transform(source, result); // } catch (Exception e) { // logger.error(e.getMessage(), e); // String docDocumentString = stringWriter.getBuffer().toString(); // return docDocumentString; } private String getPortTypeForServiceName(String servicename) { String portType = null; NodeList invokeNodeList = bpelDocument.getElementsByTagName("invoke"); for(int invokeNodeListNr = 0; invokeNodeListNr < invokeNodeList.getLength();invokeNodeListNr++){ Element invokeNode = (Element) invokeNodeList.item(invokeNodeListNr); String invokeNodeServiceName = invokeNode.getAttribute("serviceName"); if(invokeNodeServiceName.equals(servicename)){ portType = invokeNode.getAttribute("portType"); } } return portType; } /** * Used to get the last part of a string. The String will be * splitted at the position of the given separator. * * @param identifier * @param separator * @return */ private String getLastPartofString(String identifier, String separator){ return identifier.substring(identifier.lastIndexOf(separator) + 1); } /** * Used to get the first part of a string. The String will be * splitted at the position of the given separator. * * @param identifier * @param separator * @return */ private String getFirstPartofString(String identifier, String separator){ return identifier.substring(0, identifier.lastIndexOf(separator)); } private String getBpelTnsAndServiceName(){ Element bpelRootElement = (Element) bpelDocument.getElementsByTagNameNS("http://docs.oasis-open.org/wsbpel/2.0/process/executable", "process").item(0); String serviceName = "InvokeProcess"; String targetNamespace = bpelRootElement.getAttribute("targetNamespace"); String targetNamespacePrefix = bpelRootElement.lookupPrefix(targetNamespace); return targetNamespacePrefix + ":" + serviceName; } private void setNamespacePrefix(String prefix, String url){ this.definitions.setAttribute("xmlns:" + prefix, url); } public void deployProcessOnApacheOde() { DeploymentServiceLayer deploymentServiceLayer = new DeploymentServiceLayer(this.ODE_URL); DeployUnit du = deploymentServiceLayer.deploy( "myProcess", createStringFromDocument(this.bpelDocument), createStringFromDocument(this.processWsdlDocument), createStringFromDocument(this.deployDocument), this.wsdls); String name = du.getName(); } }
package net.dlogic.kryonet.common.entity; public class User { public int id; public String username; public boolean isPlayer; public boolean isItMe; }
package de.tum.in.www1.artemis.web.rest; import static de.tum.in.www1.artemis.web.rest.util.ResponseUtil.forbidden; import java.util.Optional; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import de.tum.in.www1.artemis.domain.ExampleSubmission; import de.tum.in.www1.artemis.service.AuthorizationCheckService; import de.tum.in.www1.artemis.service.ExampleSubmissionService; import de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException; import io.github.jhipster.web.util.ResponseUtil; /** * REST controller for managing ExampleSubmission. */ @RestController @RequestMapping("/api") public class ExampleSubmissionResource { private static final String ENTITY_NAME = "exampleSubmission"; private final Logger log = LoggerFactory.getLogger(ExampleSubmissionResource.class); private final ExampleSubmissionService exampleSubmissionService; private final AuthorizationCheckService authCheckService; public ExampleSubmissionResource(ExampleSubmissionService exampleSubmissionService, AuthorizationCheckService authCheckService) { this.exampleSubmissionService = exampleSubmissionService; this.authCheckService = authCheckService; } /** * POST /exercises/{exerciseId}/example-submissions : Create a new exampleSubmission. * * @param exerciseId the id of the corresponding exercise * @param exampleSubmission the exampleSubmission to create * @return the ResponseEntity with status 200 (OK) and the Result as its body, or with status 4xx if the request is invalid */ @PostMapping("/exercises/{exerciseId}/example-submissions") @PreAuthorize("hasAnyRole('INSTRUCTOR', 'ADMIN')") @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED) public ResponseEntity<ExampleSubmission> createExampleSubmission(@PathVariable Long exerciseId, @RequestBody ExampleSubmission exampleSubmission) { log.debug("REST request to save ExampleSubmission : {}", exampleSubmission); if (exampleSubmission.getId() != null) { throw new BadRequestAlertException("A new exampleSubmission cannot already have an ID", ENTITY_NAME, "idexists"); } return handleExampleSubmission(exerciseId, exampleSubmission); } /** * PUT /exercises/{exerciseId}/example-submissions : Updates an existing exampleSubmission. * * @param exerciseId the id of the corresponding exercise * @param exampleSubmission the exampleSubmission to update * @return the ResponseEntity with status 200 (OK) and with body the updated exampleSubmission, or with status 400 (Bad Request) if the exampleSubmission is not valid, or with * status 500 (Internal Server Error) if the exampleSubmission couldn't be updated */ @PutMapping("/exercises/{exerciseId}/example-submissions") @PreAuthorize("hasAnyRole('INSTRUCTOR', 'ADMIN')") @Transactional public ResponseEntity<ExampleSubmission> updateExampleSubmission(@PathVariable Long exerciseId, @RequestBody ExampleSubmission exampleSubmission) { log.debug("REST request to update ExampleSubmission : {}", exampleSubmission); if (exampleSubmission.getId() == null) { return createExampleSubmission(exerciseId, exampleSubmission); } return handleExampleSubmission(exerciseId, exampleSubmission); } @NotNull private ResponseEntity<ExampleSubmission> handleExampleSubmission(Long exerciseId, ExampleSubmission exampleSubmission) { if (!authCheckService.isAtLeastInstructorForExercise(exampleSubmission.getExercise())) { return forbidden(); } if (!exampleSubmission.getExercise().getId().equals(exerciseId)) { throw new BadRequestAlertException("The exercise id in the path does not match the exercise id of the submission", ENTITY_NAME, "idsNotMatching"); } exampleSubmission = exampleSubmissionService.save(exampleSubmission); return ResponseEntity.ok(exampleSubmission); } /** * GET /example-submissions/:id : get the "id" exampleSubmission. * * @param id the id of the exampleSubmission to retrieve * @return the ResponseEntity with status 200 (OK) and with body the exampleSubmission, or with status 404 (Not Found) */ @GetMapping("/example-submissions/{id}") @PreAuthorize("hasAnyRole('TA', 'INSTRUCTOR', 'ADMIN')") public ResponseEntity<ExampleSubmission> getExampleSubmission(@PathVariable Long id) { log.debug("REST request to get ExampleSubmission : {}", id); Optional<ExampleSubmission> exampleSubmission = exampleSubmissionService.getWithEagerExercise(id); if (exampleSubmission.isPresent()) { if (! authCheckService.isAtLeastTeachingAssistantForExercise(exampleSubmission.get().getExercise())) { return forbidden(); } } return ResponseUtil.wrapOrNotFound(exampleSubmission); } }
package com.whiteout.task; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.RelativeLayout; import android.widget.TextView; import com.whiteout.task.ToDoItem.Status; public class ToDoListAdapter extends BaseAdapter { // List of ToDoItems // TODO: Consider new way to store, allow for sorting? // Create custom List, needs to be sorted on Priority, then due date private final List<ToDoItem> mItems = new ArrayList<ToDoItem>(); private final Context mContext; private static final String TAG = "Whiteout-Debug"; public ToDoListAdapter(Context context) { mContext = context; } // Add a ToDoItem to adapter // Notify the data set changed public void add(ToDoItem item) { mItems.add(item); notifyDataSetChanged(); } // Clear entire list public void clear() { mItems.clear(); notifyDataSetChanged(); } // Remove a single ToDoItem public void remove(int pos) { mItems.remove(pos); for(int i=0; i<mItems.size(); i++){ mItems.get(i).setPosition(i); } notifyDataSetChanged(); } // Get number of ToDoItems public int getCount() { return mItems.size(); } // Retrieve a ToDoItem @Override public Object getItem(int pos) { return mItems.get(pos); } // Get ID for ToDoItem, aka:position @Override public long getItemId(int pos) { return pos; } // Create a View to display to ToDoItem // at specific position in mItems @Override public View getView(final int position, View convertView, ViewGroup parent) { final ToDoItem toDoItem = (ToDoItem) getItem(position); // Retrieve an inflater LayoutInflater inflater = (LayoutInflater) mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // Inflate the entireLayout RelativeLayout itemLayout = (RelativeLayout) inflater.inflate( R.layout.todo_item, null); // Create the titleView final TextView titleView = (TextView) itemLayout .findViewById(R.id.titleView); titleView.setText(toDoItem.getTitle()); // Create the finished checkBox final CheckBox statusView = (CheckBox) itemLayout .findViewById(R.id.statusCheckBox); statusView.setChecked(toDoItem.getStatus().equals(Status.DONE) ? true : false); statusView.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { log("Enter onCheckedChanged()"); if (toDoItem.getStatus().equals(Status.DONE)) toDoItem.setStatus(Status.NOTDONE); else toDoItem.setStatus(Status.DONE); } }); // Create the delete button final Button deleteButton = (Button) itemLayout.findViewById(R.id.deleteButton); deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { remove(position); } }); // Create the priorityView final TextView priorityView = (TextView) itemLayout .findViewById(R.id.priorityView); priorityView.setText(toDoItem.getPriority().toString()); // Create the dateView final TextView dateView = (TextView) itemLayout .findViewById(R.id.dateView); dateView.setText(ToDoItem.FORMAT.format(toDoItem.getDate())); // Return's the entire view just created return itemLayout; // Magical... } private void log(String msg) { Log.i(TAG, msg); } }
package com.orientechnologies.orient.core.sql; import com.orientechnologies.common.profiler.OProfilerMBean; import com.orientechnologies.orient.core.Orient; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.iterator.ORecordIteratorClass; import com.orientechnologies.orient.core.metadata.schema.OSchema; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.testng.Assert.*; @Test public class OCommandExecutorSQLSelectTest { private static String DB_STORAGE = "memory"; private static String DB_NAME = "OCommandExecutorSQLSelectTest"; ODatabaseDocumentTx db; @BeforeClass public void beforeClass() throws Exception { db = new ODatabaseDocumentTx(DB_STORAGE + ":" + DB_NAME); db.create(); getProfilerInstance().startRecording(); db.command(new OCommandSQL("CREATE class foo")).execute(); db.command(new OCommandSQL("CREATE property foo.name STRING")).execute(); db.command(new OCommandSQL("CREATE property foo.bar INTEGER")).execute(); db.command(new OCommandSQL("CREATE property foo.address EMBEDDED")).execute(); db.command(new OCommandSQL("CREATE property foo.comp STRING")).execute(); db.command(new OCommandSQL("CREATE property foo.osite INTEGER")).execute(); db.command(new OCommandSQL("CREATE index foo_name on foo (name) NOTUNIQUE")).execute(); db.command(new OCommandSQL("CREATE index foo_bar on foo (bar) NOTUNIQUE")).execute(); db.command(new OCommandSQL("CREATE index foo_comp_osite on foo (comp, osite) NOTUNIQUE")).execute(); db.command( new OCommandSQL("insert into foo (name, bar, address) values ('a', 1, {'street':'1st street', 'city':'NY', '@type':'d'})")) .execute(); db.command(new OCommandSQL("insert into foo (name, bar) values ('b', 2)")).execute(); db.command(new OCommandSQL("insert into foo (name, bar) values ('c', 3)")).execute(); db.command(new OCommandSQL("insert into foo (comp, osite) values ('a', 1)")).execute(); db.command(new OCommandSQL("insert into foo (comp, osite) values ('b', 2)")).execute(); db.command(new OCommandSQL("CREATE class bar")).execute(); db.command(new OCommandSQL("insert into bar (name, foo) values ('a', 1)")).execute(); db.command(new OCommandSQL("insert into bar (name, foo) values ('b', 2)")).execute(); db.command(new OCommandSQL("insert into bar (name, foo) values ('c', 3)")).execute(); db.command(new OCommandSQL("insert into bar (name, foo) values ('d', 4)")).execute(); db.command(new OCommandSQL("insert into bar (name, foo) values ('e', 5)")).execute(); db.command(new OCommandSQL("insert into bar (name, foo) values ('f', 1)")).execute(); db.command(new OCommandSQL("insert into bar (name, foo) values ('g', 2)")).execute(); db.command(new OCommandSQL("insert into bar (name, foo) values ('h', 3)")).execute(); db.command(new OCommandSQL("insert into bar (name, foo) values ('i', 4)")).execute(); db.command(new OCommandSQL("insert into bar (name, foo) values ('j', 5)")).execute(); db.command(new OCommandSQL("insert into bar (name, foo) values ('k', 1)")).execute(); db.command(new OCommandSQL("insert into bar (name, foo) values ('l', 2)")).execute(); db.command(new OCommandSQL("insert into bar (name, foo) values ('m', 3)")).execute(); db.command(new OCommandSQL("insert into bar (name, foo) values ('n', 4)")).execute(); db.command(new OCommandSQL("insert into bar (name, foo) values ('o', 5)")).execute(); db.command(new OCommandSQL("CREATE class ridsorttest")).execute(); db.command(new OCommandSQL("CREATE property ridsorttest.name INTEGER")).execute(); db.command(new OCommandSQL("CREATE index ridsorttest_name on ridsorttest (name) NOTUNIQUE")).execute(); db.command(new OCommandSQL("insert into ridsorttest (name) values (1)")).execute(); db.command(new OCommandSQL("insert into ridsorttest (name) values (5)")).execute(); db.command(new OCommandSQL("insert into ridsorttest (name) values (3)")).execute(); db.command(new OCommandSQL("insert into ridsorttest (name) values (4)")).execute(); db.command(new OCommandSQL("insert into ridsorttest (name) values (1)")).execute(); db.command(new OCommandSQL("insert into ridsorttest (name) values (8)")).execute(); db.command(new OCommandSQL("insert into ridsorttest (name) values (6)")).execute(); db.command(new OCommandSQL("CREATE class unwindtest")).execute(); db.command(new OCommandSQL("insert into unwindtest (name, coll) values ('foo', ['foo1', 'foo2'])")).execute(); db.command(new OCommandSQL("insert into unwindtest (name, coll) values ('bar', ['bar1', 'bar2'])")).execute(); db.command(new OCommandSQL("CREATE class edge")).execute(); db.command(new OCommandSQL("CREATE class TestFromInSquare")).execute(); db.command(new OCommandSQL("insert into TestFromInSquare set tags = {' from ':'foo',' to ':'bar'}")).execute(); db.command(new OCommandSQL("CREATE class TestMultipleClusters")).execute(); db.command(new OCommandSQL("alter class TestMultipleClusters addcluster testmultipleclusters1 ")).execute(); db.command(new OCommandSQL("alter class TestMultipleClusters addcluster testmultipleclusters2 ")).execute(); db.command(new OCommandSQL("insert into cluster:testmultipleclusters set name = 'aaa'")).execute(); db.command(new OCommandSQL("insert into cluster:testmultipleclusters1 set name = 'foo'")).execute(); db.command(new OCommandSQL("insert into cluster:testmultipleclusters2 set name = 'bar'")).execute(); db.command(new OCommandSQL("CREATE class TestUrl")).execute(); db.command(new OCommandSQL("insert into TestUrl content { \"url\": \"http: db.command(new OCommandSQL("CREATE class TestParams")).execute(); db.command(new OCommandSQL("insert into TestParams set name = 'foo', surname ='foo'")).execute(); db.command(new OCommandSQL("insert into TestParams set name = 'foo', surname ='bar'")).execute();
package net.sf.mzmine.project.io; import com.Ostermiller.util.Base64; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Hashtable; import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; import net.sf.mzmine.data.ChromatographicPeak; import net.sf.mzmine.data.DataPoint; import net.sf.mzmine.data.Parameter; import net.sf.mzmine.data.ParameterType; import net.sf.mzmine.data.PeakIdentity; import net.sf.mzmine.data.PeakList; import net.sf.mzmine.data.PeakListAppliedMethod; import net.sf.mzmine.data.PeakListRow; import net.sf.mzmine.data.RawDataFile; import net.sf.mzmine.data.impl.SimpleParameterSet; import net.sf.mzmine.data.impl.SimplePeakIdentity; import net.sf.mzmine.data.impl.SimplePeakList; import net.sf.mzmine.main.MZmineCore; import net.sf.mzmine.util.Range; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; public class PeakListSave { private Logger logger = Logger.getLogger(this.getClass().getName()); public static DateFormat dateFormat = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss"); private Hashtable<RawDataFile, Integer> dataFilesIDMap; private int numberOfRows; private double progress; private ZipOutputStream zipOutputStream; public PeakListSave(ZipOutputStream zipStream) { dataFilesIDMap = new Hashtable<RawDataFile, Integer>(); this.zipOutputStream = zipStream; } /** * Create an XML document with the peak list information an save it into * the project zip file * @param peakList * @param peakListSavedName name of the peak list * @throws java.io.IOException */ public void savePeakList(PeakList peakList, String peakListSavedName) throws IOException, TransformerConfigurationException, SAXException { logger.info("Saving peak list: " + peakList.getName()); progress = 0.0; numberOfRows = peakList.getNumberOfRows(); zipOutputStream.putNextEntry(new ZipEntry(peakListSavedName + ".xml")); OutputStream finalStream = zipOutputStream; StreamResult streamResult = new StreamResult(finalStream); SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler hd = tf.newTransformerHandler(); Transformer serializer = hd.getTransformer(); serializer.setOutputProperty(OutputKeys.INDENT,"yes"); serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); hd.setResult(streamResult); hd.startDocument(); AttributesImpl atts = new AttributesImpl(); hd.startElement("", "", PeakListElementName.PEAKLIST.getElementName(), atts); atts.clear(); // <NAME> hd.startElement("", "", PeakListElementName.NAME.getElementName(), atts); hd.characters(peakList.getName().toCharArray(), 0, peakList.getName().length()); hd.endElement("", "", PeakListElementName.NAME.getElementName()); // <PEAKLIST_DATE> String dateText = ""; if (((SimplePeakList) peakList).getDateCreated() == null) { dateText = ((SimplePeakList) peakList).getDateCreated(); } else { Date date = new Date(); dateText = dateFormat.format(date); } hd.startElement("", "", PeakListElementName.PEAKLIST_DATE.getElementName(), atts); hd.characters(dateText.toCharArray(), 0, dateText.length()); hd.endElement("", "", PeakListElementName.PEAKLIST_DATE.getElementName()); // <QUANTITY> hd.startElement("", "", PeakListElementName.QUANTITY.getElementName(), atts); hd.characters(String.valueOf(numberOfRows).toCharArray(), 0, String.valueOf(numberOfRows).length()); hd.endElement("", "", PeakListElementName.QUANTITY.getElementName()); // <PROCESS> PeakListAppliedMethod[] processes = peakList.getAppliedMethods(); for (PeakListAppliedMethod proc : processes) { atts.clear(); atts.addAttribute("", "", "description", "CDATA", proc.getDescription()); hd.startElement("", "", PeakListElementName.PROCESS.getElementName(), atts); this.fillProcessParameters((SimpleParameterSet)proc.getParameterSet(), hd); hd.endElement("", "", PeakListElementName.PROCESS.getElementName()); } atts.clear(); // <RAWFILE> RawDataFile[] dataFiles = peakList.getRawDataFiles(); for (int i = 1; i <= dataFiles.length; i++) { int ID = 0; RawDataFile[] files = MZmineCore.getCurrentProject().getDataFiles(); for (int e = 0; e < files.length; e++) { if (files[e].equals(dataFiles[i - 1])) { ID = e; break; } } atts.clear(); atts.addAttribute("", "", PeakListElementName.ID.getElementName(), "CDATA", String.valueOf(ID)); hd.startElement("", "", PeakListElementName.RAWFILE.getElementName(), atts); try { fillRawDataFileElement(dataFiles[i - 1], hd); } catch (Exception ex) { MZmineCore.getDesktop().displayErrorMessage("Error. No raw data exists for the peak list: " + peakList.getName()); return; } dataFilesIDMap.put(dataFiles[i - 1], ID); hd.endElement("", "", PeakListElementName.RAWFILE.getElementName()); } // <ROW> PeakListRow row; for (int i = 0; i < numberOfRows; i++) { atts.clear(); row = peakList.getRow(i); atts.addAttribute("", "", PeakListElementName.ID.getElementName(), "CDATA", String.valueOf(row.getID())); hd.startElement("", "", PeakListElementName.ROW.getElementName(), atts); fillRowElement(row, hd); hd.endElement("", "", PeakListElementName.ROW.getElementName()); progress = (double) i / numberOfRows; } hd.endElement("", "", PeakListElementName.PEAKLIST.getElementName()); hd.endDocument(); } /** * Add the process parameters into the XML document * @param parameterSet * @param hd * @throws org.xml.sax.SAXException */ private void fillProcessParameters(SimpleParameterSet parameterSet, TransformerHandler hd) throws SAXException { if ((parameterSet == null) || (parameterSet.getParameters() == null)) return; AttributesImpl atts = new AttributesImpl(); for (Parameter p : parameterSet.getParameters()) { atts.clear(); atts.addAttribute("", "", "name", "CDATA", p.getName()); atts.addAttribute("", "", "type", "CDATA", p.getType().toString()); hd.startElement("", "", PeakListElementName.PARAMETER.getElementName(), atts); if ((p.getType() == ParameterType.MULTIPLE_SELECTION) || (p.getType() == ParameterType.ORDERED_LIST)) { Object[] values = p.getPossibleValues(); if (values != null) { String valueAsString = ""; for (int i = 0; i < values.length; i++) { if (i == values.length - 1) { valueAsString += String.valueOf(values[i]); } else { valueAsString += String.valueOf(values[i]) + ","; } } hd.characters(valueAsString.toCharArray(), 0, valueAsString.length()); } } else { Object value = parameterSet.getParameterValue(p); if (value != null) { String valueAsString; if (value instanceof Range) { Range rangeValue = (Range) value; valueAsString = String.valueOf(rangeValue.getMin()) + "-" + String.valueOf(rangeValue.getMax()); } else { valueAsString = value.toString(); } hd.characters(valueAsString.toCharArray(), 0, valueAsString.length()); } } hd.endElement("", "", PeakListElementName.PARAMETER.getElementName()); } } /** * Add the row information into the XML document * @param row * @param element */ private void fillRowElement(PeakListRow row, TransformerHandler hd) throws SAXException { // <PEAK_IDENTITY> PeakIdentity preferredIdentity = row.getPreferredPeakIdentity(); PeakIdentity[] identities = row.getPeakIdentities(); AttributesImpl atts = new AttributesImpl(); for (int i = 0; i < identities.length; i++) { atts.addAttribute("", "", PeakListElementName.ID.getElementName(), "CDATA", String.valueOf(i)); atts.addAttribute("", "", PeakListElementName.PREFERRED.getElementName(), "CDATA", String.valueOf(identities[i] == preferredIdentity)); hd.startElement("", "", PeakListElementName.PEAK_IDENTITY.getElementName(), atts); fillIdentityElement(identities[i], hd); hd.endElement("", "", PeakListElementName.PEAK_IDENTITY.getElementName()); } // <PEAK> int dataFileID = 0; ChromatographicPeak[] peaks = row.getPeaks(); for (ChromatographicPeak p : peaks) { atts.clear(); dataFileID = dataFilesIDMap.get(p.getDataFile()); atts.addAttribute("", "", PeakListElementName.COLUMN.getElementName(), "CDATA", String.valueOf(dataFileID)); atts.addAttribute("", "", PeakListElementName.MASS.getElementName(), "CDATA", String.valueOf(p.getMZ())); atts.addAttribute("", "", PeakListElementName.RT.getElementName(), "CDATA", String.valueOf(p.getRT())); atts.addAttribute("", "", PeakListElementName.HEIGHT.getElementName(), "CDATA", String.valueOf(p.getHeight())); atts.addAttribute("", "", PeakListElementName.AREA.getElementName(), "CDATA", String.valueOf(p.getArea())); atts.addAttribute("", "", PeakListElementName.STATUS.getElementName(), "CDATA", p.getPeakStatus().toString()); hd.startElement("", "", PeakListElementName.PEAK.getElementName(), atts); fillPeakElement(p, hd); hd.endElement("", "", PeakListElementName.PEAK.getElementName()); } } /** * Add the raw data information into the XML document * @param file * @param element */ private void fillRawDataFileElement(RawDataFile file, TransformerHandler hd) throws Exception { AttributesImpl atts = new AttributesImpl(); // <NAME> hd.startElement("", "", PeakListElementName.RAWDATA_NAME.getElementName(), atts); hd.characters(file.getName().toCharArray(), 0, file.getName().length()); hd.endElement("", "", PeakListElementName.RAWDATA_NAME.getElementName()); } /** * Add the peak identity information into the XML document * @param identity * @param element */ private void fillIdentityElement(PeakIdentity identity, TransformerHandler hd) throws SAXException { AttributesImpl atts = new AttributesImpl(); // <NAME> String name = identity.getName() != null ? identity.getName() : " "; hd.startElement("", "", PeakListElementName.NAME.getElementName(), atts); hd.characters(name.toCharArray(), 0, name.length()); hd.endElement("", "", PeakListElementName.NAME.getElementName()); // <FORMULA> String formula = ""; if (identity instanceof SimplePeakIdentity) { SimplePeakIdentity id = (SimplePeakIdentity) identity; formula = id.getCompoundFormula(); } atts.clear(); hd.startElement("", "", PeakListElementName.FORMULA.getElementName(), atts); hd.characters(formula.toCharArray(), 0, formula.length()); hd.endElement("", "", PeakListElementName.FORMULA.getElementName()); // <IDENTIFICATION> atts.clear(); hd.startElement("", "", PeakListElementName.IDENTIFICATION.getElementName(), atts); name = identity.getIdentificationMethod() != null ? identity.getIdentificationMethod() : " "; hd.characters(name.toCharArray(), 0, name.length()); hd.endElement("", "", PeakListElementName.IDENTIFICATION.getElementName()); } /** * Add the peaks information into the XML document * @param peak * @param element * @param dataFileID */ private void fillPeakElement(ChromatographicPeak peak, TransformerHandler hd) throws SAXException { AttributesImpl atts = new AttributesImpl(); // <MZPEAK> int scanNumbers[] = peak.getScanNumbers(); atts.addAttribute("", "", PeakListElementName.QUANTITY.getElementName(), "CDATA", String.valueOf(scanNumbers.length)); hd.startElement("", "", PeakListElementName.MZPEAK.getElementName(), atts); atts.clear(); // <REPRESENTATIVE_SCAN> hd.startElement("", "", PeakListElementName.REPRESENTATIVE_SCAN.getElementName(), atts); hd.characters(String.valueOf(peak.getRepresentativeScanNumber()).toCharArray(), 0, String.valueOf(peak.getRepresentativeScanNumber()).length()); hd.endElement("", "", PeakListElementName.REPRESENTATIVE_SCAN.getElementName()); // <FRAGMENT_SCAN> hd.startElement("", "", PeakListElementName.FRAGMENT_SCAN.getElementName(), atts); hd.characters(String.valueOf(peak.getMostIntenseFragmentScanNumber()).toCharArray(), 0, String.valueOf(peak.getMostIntenseFragmentScanNumber()).length()); hd.endElement("", "", PeakListElementName.FRAGMENT_SCAN.getElementName()); // <SCAN_ID> <MASS> <HEIGHT> ByteArrayOutputStream byteScanStream = new ByteArrayOutputStream(); DataOutputStream dataScanStream = new DataOutputStream(byteScanStream); ByteArrayOutputStream byteMassStream = new ByteArrayOutputStream(); DataOutputStream dataMassStream = new DataOutputStream(byteMassStream); ByteArrayOutputStream byteHeightStream = new ByteArrayOutputStream(); DataOutputStream dataHeightStream = new DataOutputStream( byteHeightStream); float mass, height; for (int scan : scanNumbers) { try { dataScanStream.writeInt(scan); dataScanStream.flush(); DataPoint mzPeak = peak.getDataPoint(scan); if (mzPeak != null) { mass = (float) mzPeak.getMZ(); height = (float) mzPeak.getIntensity(); } else { mass = 0f; height = 0f; } dataMassStream.writeFloat(mass); dataMassStream.flush(); dataHeightStream.writeFloat(height); dataHeightStream.flush(); } catch (IOException e) { e.printStackTrace(); } } byte[] bytes = Base64.encode(byteScanStream.toByteArray()); hd.startElement("", "", PeakListElementName.SCAN_ID.getElementName(), atts); String sbytes = new String(bytes); hd.characters(sbytes.toCharArray(), 0, sbytes.length()); hd.endElement("", "", PeakListElementName.SCAN_ID.getElementName()); bytes = Base64.encode(byteMassStream.toByteArray()); hd.startElement("", "", PeakListElementName.MASS.getElementName(), atts); sbytes = new String(bytes); hd.characters(sbytes.toCharArray(), 0, sbytes.length()); hd.endElement("", "", PeakListElementName.MASS.getElementName()); bytes = Base64.encode(byteHeightStream.toByteArray()); hd.startElement("", "", PeakListElementName.HEIGHT.getElementName(), atts); sbytes = new String(bytes); hd.characters(sbytes.toCharArray(), 0, sbytes.length()); hd.endElement("", "", PeakListElementName.HEIGHT.getElementName()); hd.endElement("", "", PeakListElementName.MZPEAK.getElementName()); } /** * @return the progress of these functions saving the peak list to the zip file. */ public double getProgress() { return progress; } }
package fi.otavanopisto.kuntaapi.server.rest; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.ejb.Stateful; import javax.enterprise.context.RequestScoped; import javax.enterprise.inject.Instance; import javax.inject.Inject; import javax.ws.rs.core.Context; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import org.apache.commons.lang3.EnumUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import fi.otavanopisto.kuntaapi.server.controllers.AnnouncementController; import fi.otavanopisto.kuntaapi.server.controllers.BannerController; import fi.otavanopisto.kuntaapi.server.controllers.ContactController; import fi.otavanopisto.kuntaapi.server.controllers.EventController; import fi.otavanopisto.kuntaapi.server.controllers.FileController; import fi.otavanopisto.kuntaapi.server.controllers.HttpCacheController; import fi.otavanopisto.kuntaapi.server.controllers.JobController; import fi.otavanopisto.kuntaapi.server.controllers.MenuController; import fi.otavanopisto.kuntaapi.server.controllers.NewsController; import fi.otavanopisto.kuntaapi.server.controllers.OrganizationController; import fi.otavanopisto.kuntaapi.server.controllers.PageController; import fi.otavanopisto.kuntaapi.server.controllers.TileController; import fi.otavanopisto.kuntaapi.server.id.AnnouncementId; import fi.otavanopisto.kuntaapi.server.id.AttachmentId; import fi.otavanopisto.kuntaapi.server.id.BannerId; import fi.otavanopisto.kuntaapi.server.id.ContactId; import fi.otavanopisto.kuntaapi.server.id.EventId; import fi.otavanopisto.kuntaapi.server.id.FileId; import fi.otavanopisto.kuntaapi.server.id.JobId; import fi.otavanopisto.kuntaapi.server.id.MenuId; import fi.otavanopisto.kuntaapi.server.id.MenuItemId; import fi.otavanopisto.kuntaapi.server.id.NewsArticleId; import fi.otavanopisto.kuntaapi.server.id.OrganizationId; import fi.otavanopisto.kuntaapi.server.id.OrganizationServiceId; import fi.otavanopisto.kuntaapi.server.id.PageId; import fi.otavanopisto.kuntaapi.server.id.TileId; import fi.otavanopisto.kuntaapi.server.integrations.AnnouncementProvider; import fi.otavanopisto.kuntaapi.server.integrations.AnnouncementProvider.AnnouncementOrder; import fi.otavanopisto.kuntaapi.server.integrations.AnnouncementProvider.AnnouncementOrderDirection; import fi.otavanopisto.kuntaapi.server.integrations.AttachmentData; import fi.otavanopisto.kuntaapi.server.integrations.EventProvider; import fi.otavanopisto.kuntaapi.server.integrations.JobProvider; import fi.otavanopisto.kuntaapi.server.integrations.JobProvider.JobOrder; import fi.otavanopisto.kuntaapi.server.integrations.JobProvider.JobOrderDirection; import fi.otavanopisto.kuntaapi.server.integrations.KuntaApiConsts; import fi.otavanopisto.kuntaapi.server.integrations.OrganizationServiceProvider; import fi.metatavu.kuntaapi.server.rest.OrganizationsApi; import fi.metatavu.kuntaapi.server.rest.model.Announcement; import fi.metatavu.kuntaapi.server.rest.model.Attachment; import fi.metatavu.kuntaapi.server.rest.model.Banner; import fi.metatavu.kuntaapi.server.rest.model.Contact; import fi.metatavu.kuntaapi.server.rest.model.Event; import fi.metatavu.kuntaapi.server.rest.model.FileDef; import fi.metatavu.kuntaapi.server.rest.model.Job; import fi.metatavu.kuntaapi.server.rest.model.LocalizedValue; import fi.metatavu.kuntaapi.server.rest.model.Menu; import fi.metatavu.kuntaapi.server.rest.model.MenuItem; import fi.metatavu.kuntaapi.server.rest.model.NewsArticle; import fi.metatavu.kuntaapi.server.rest.model.Organization; import fi.metatavu.kuntaapi.server.rest.model.OrganizationService; import fi.metatavu.kuntaapi.server.rest.model.OrganizationSetting; import fi.metatavu.kuntaapi.server.rest.model.Page; import fi.metatavu.kuntaapi.server.rest.model.Tile; import fi.otavanopisto.kuntaapi.server.system.OrganizationSettingProvider; @RequestScoped @Stateful @SuppressWarnings ("squid:S3306") public class OrganizationsApiImpl extends OrganizationsApi { private static final String INVALID_SETTING_ID = "Invalid setting id"; private static final String MAX_RESULTS_MUST_BY_A_POSITIVE_INTEGER = "maxResults must by a positive integer"; private static final String FIRST_RESULT_MUST_BY_A_POSITIVE_INTEGER = "firstResult must by a positive integer"; private static final String NOT_FOUND = "Not Found"; private static final String NOT_IMPLEMENTED = "Not implemented"; private static final String INTERNAL_SERVER_ERROR = "Internal Server Error"; @Inject private OrganizationSettingProvider organizationSettingProvider; @Inject private OrganizationController organizationController; @Inject private PageController pageController; @Inject private FileController fileController; @Inject private MenuController menuController; @Inject private BannerController bannerController; @Inject private AnnouncementController announcementController; @Inject private TileController tileController; @Inject private NewsController newsController; @Inject private EventController eventController; @Inject private JobController jobController; @Inject private ContactController contactController; @Inject private HttpCacheController httpCacheController; @Inject private Instance<OrganizationServiceProvider> organizationServiceProviders; @Override public Response listOrganizations(String businessName, String businessCode, String search, Long firstResult, Long maxResults, @Context Request request) { List<Organization> organizations; if (search != null) { organizations = organizationController.searchOrganizations(search, businessName, businessCode, firstResult, maxResults); } else { organizations = organizationController.listOrganizations(businessName, businessCode, firstResult, maxResults); } List<String> ids = httpCacheController.getEntityIds(organizations); Response notModified = httpCacheController.getNotModified(request, ids); if (notModified != null) { return notModified; } return httpCacheController.sendModified(organizations, ids); } @Override public Response findOrganization(String organizationIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } Response notModified = httpCacheController.getNotModified(request, organizationId); if (notModified != null) { return notModified; } Organization organization = organizationController.findOrganization(organizationId); if (organization != null) { return httpCacheController.sendModified(organization, organization.getId()); } return createNotFound(NOT_FOUND); } @Override public Response createOrganizationService(String organizationId, OrganizationService body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response findOrganizationService(String organizationIdParam, String organizationServiceIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); OrganizationServiceId organizationServiceId = toOrganizationServiceId(organizationId, organizationServiceIdParam); for (OrganizationServiceProvider organizationServiceProvider : getOrganizationServiceProviders()) { OrganizationService organizationService = organizationServiceProvider.findOrganizationService(organizationId, organizationServiceId); if (organizationService != null) { return Response.ok(organizationService) .build(); } } return createNotFound(NOT_FOUND); } @Override public Response listOrganizationOrganizationServices(String organizationIdParam, Long firstResult, Long maxResults, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createBadRequest("Organization parameter is mandatory"); } Response validationResponse = validateListLimitParams(firstResult, maxResults); if (validationResponse != null) { return validationResponse; } List<OrganizationService> result = new ArrayList<>(); for (OrganizationServiceProvider organizationServiceProvider : getOrganizationServiceProviders()) { result.addAll(organizationServiceProvider.listOrganizationServices(organizationId)); } int resultCount = result.size(); int firstIndex = firstResult == null ? 0 : Math.min(firstResult.intValue(), resultCount); int toIndex = maxResults == null ? resultCount : Math.min(firstIndex + maxResults.intValue(), resultCount); return Response.ok(result.subList(firstIndex, toIndex)) .build(); } @Override public Response updateOrganizationService(String organizationId, String organizationServiceId, OrganizationService body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response findOrganizationEvent(String organizationIdParam, String eventIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); EventId eventId = toEventId(organizationId, eventIdParam); Response notModified = httpCacheController.getNotModified(request, eventId); if (notModified != null) { return notModified; } Event event = eventController.findEvent(organizationId, eventId); if (event != null) { return httpCacheController.sendModified(event, event.getId()); } return createNotFound(NOT_FOUND); } @Override public Response findOrganizationEventImage(String organizationIdParam, String eventIdParam, String imageIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); EventId eventId = toEventId(organizationId, eventIdParam); AttachmentId attachmentId = new AttachmentId(organizationId, KuntaApiConsts.IDENTIFIER_NAME, imageIdParam); Response notModified = httpCacheController.getNotModified(request, attachmentId); if (notModified != null) { return notModified; } Attachment attachment = eventController.findEventImage(organizationId, eventId, attachmentId); if (attachment != null) { return httpCacheController.sendModified(attachment, attachment.getId()); } return createNotFound(NOT_FOUND); } @Override public Response getOrganizationEventImageData(String organizationIdParam, String eventIdParam, String imageIdParam, Integer size, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); EventId eventId = toEventId(organizationId, eventIdParam); AttachmentId attachmentId = new AttachmentId(organizationId, KuntaApiConsts.IDENTIFIER_NAME, imageIdParam); Response notModified = httpCacheController.getNotModified(request, attachmentId); if (notModified != null) { return notModified; } AttachmentData attachmentData = eventController.getEventImageData(size, organizationId, eventId, attachmentId); if (attachmentData != null) { return httpCacheController.streamModified(attachmentData.getData(), attachmentData.getType(), attachmentId); } return createNotFound(NOT_FOUND); } @Override public Response listOrganizationEventImages(String organizationIdParam, String eventIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); EventId eventId = toEventId(organizationId, eventIdParam); List<Attachment> result = eventController.listEventImages(organizationId, eventId); List<String> ids = httpCacheController.getEntityIds(result); Response notModified = httpCacheController.getNotModified(request, ids); if (notModified != null) { return notModified; } return httpCacheController.sendModified(result, ids); } @Override public Response listOrganizationEvents(String organizationIdParam, String startBefore, String startAfter, String endBefore, String endAfter, Integer firstResult, Integer maxResults, String orderBy, String orderDir, @Context Request request) { EventProvider.EventOrder order = EventProvider.EventOrder.START_DATE; EventProvider.EventOrderDirection orderDirection = EventProvider.EventOrderDirection.DESCENDING; if (StringUtils.isNotBlank(orderBy)) { order = EnumUtils.getEnum(EventProvider.EventOrder.class, orderBy); if (order == null) { return createBadRequest(String.format("Invalid event order %s", orderBy)); } } if (StringUtils.isNotBlank(orderDir)) { orderDirection = EnumUtils.getEnum(EventProvider.EventOrderDirection.class, orderDir); if (orderDirection == null) { return createBadRequest(String.format("Invalid event order direction %s", orderDir)); } } OrganizationId organizationId = toOrganizationId(organizationIdParam); List<Event> result = eventController.listEvents(getDateTime(startBefore), getDateTime(startAfter), getDateTime(endBefore), getDateTime(endAfter), firstResult, maxResults, order, orderDirection, organizationId); List<String> ids = httpCacheController.getEntityIds(result); Response notModified = httpCacheController.getNotModified(request, ids); if (notModified != null) { return notModified; } return httpCacheController.sendModified(result, ids); } /* News */ @Override public Response listOrganizationNews(String organizationIdParam, String slug, String publishedBefore, String publishedAfter, Integer firstResult, Integer maxResults, Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); List<NewsArticle> result = newsController.listNewsArticles(slug, getDateTime(publishedBefore), getDateTime(publishedAfter), firstResult, maxResults, organizationId); List<String> ids = httpCacheController.getEntityIds(result); Response notModified = httpCacheController.getNotModified(request, ids); if (notModified != null) { return notModified; } return httpCacheController.sendModified(result, ids); } @Override public Response findOrganizationNewsArticle(String organizationIdParam, String newsArticleIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); NewsArticleId newsArticleId = toNewsArticleId(organizationId, newsArticleIdParam); Response notModified = httpCacheController.getNotModified(request, newsArticleId); if (notModified != null) { return notModified; } NewsArticle newsArticle = newsController.findNewsArticle(organizationId, newsArticleId); if (newsArticle != null) { return httpCacheController.sendModified(newsArticle, newsArticle.getId()); } return createNotFound(NOT_FOUND); } @Override public Response findOrganizationNewsArticleImage(String organizationIdParam, String newsArticleIdParam, String imageIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); NewsArticleId newsArticleId = toNewsArticleId(organizationId, newsArticleIdParam); AttachmentId attachmentId = toAttachmentId(organizationId, imageIdParam); Response notModified = httpCacheController.getNotModified(request, attachmentId); if (notModified != null) { return notModified; } Attachment attachment = newsController.findNewsArticleImage(organizationId, newsArticleId, attachmentId); if (attachment != null) { return httpCacheController.sendModified(attachment, attachment.getId()); } return createNotFound(NOT_FOUND); } @Override public Response getOrganizationNewsArticleImageData(String organizationIdParam, String newsArticleIdParam, String imageIdParam, Integer size, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); NewsArticleId newsArticleId = toNewsArticleId(organizationId, newsArticleIdParam); AttachmentId attachmentId = toAttachmentId(organizationId, imageIdParam); Response notModified = httpCacheController.getNotModified(request, attachmentId); if (notModified != null) { return notModified; } AttachmentData attachmentData = newsController.getNewsArticleImageData(organizationId, newsArticleId, attachmentId, size); if (attachmentData != null) { return httpCacheController.streamModified(attachmentData.getData(), attachmentData.getType(), attachmentId); } return createNotFound(NOT_FOUND); } @Override public Response listOrganizationNewsArticleImages(String organizationIdParam, String newsArticleIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); NewsArticleId newsArticleId = toNewsArticleId(organizationId, newsArticleIdParam); List<Attachment> result = newsController.listNewsArticleImages(organizationId, newsArticleId); List<String> ids = httpCacheController.getEntityIds(result); Response notModified = httpCacheController.getNotModified(request, ids); if (notModified != null) { return notModified; } return httpCacheController.sendModified(result, ids); } /* Banners */ @Override public Response listOrganizationBanners(String organizationIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); List<Banner> result = bannerController.listBanners(organizationId); List<String> ids = httpCacheController.getEntityIds(result); Response notModified = httpCacheController.getNotModified(request, ids); if (notModified != null) { return notModified; } return httpCacheController.sendModified(result, ids); } @Override public Response findOrganizationBanner(String organizationIdParam, String bannerIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); BannerId bannerId = toBannerId(organizationId, bannerIdParam); Response notModified = httpCacheController.getNotModified(request, bannerId); if (notModified != null) { return notModified; } Banner banner = bannerController.findBanner(organizationId, bannerId); if (banner != null) { return httpCacheController.sendModified(banner, banner.getId()); } return createNotFound(NOT_FOUND); } @Override public Response listOrganizationBannerImages(String organizationIdParam, String bannerIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); BannerId bannerId = toBannerId(organizationId, bannerIdParam); List<Attachment> result = bannerController.listBannerImages(organizationId, bannerId); List<String> ids = httpCacheController.getEntityIds(result); Response notModified = httpCacheController.getNotModified(request, ids); if (notModified != null) { return notModified; } return httpCacheController.sendModified(result, ids); } @Override public Response findOrganizationBannerImage(String organizationIdParam, String bannerIdParam, String imageIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); BannerId bannerId = toBannerId(organizationId, bannerIdParam); AttachmentId attachmentId = toAttachmentId(organizationId, imageIdParam); Response notModified = httpCacheController.getNotModified(request, attachmentId); if (notModified != null) { return notModified; } Attachment attachment = bannerController.findBannerImage(organizationId, bannerId, attachmentId); if (attachment != null) { return httpCacheController.sendModified(attachment, attachment.getId()); } return createNotFound(NOT_FOUND); } @Override public Response getOrganizationBannerImageData(String organizationIdParam, String bannerIdParam, String imageIdParam, Integer size, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); BannerId bannerId = toBannerId(organizationId, bannerIdParam); AttachmentId attachmentId = toAttachmentId(organizationId, imageIdParam); Response notModified = httpCacheController.getNotModified(request, attachmentId); if (notModified != null) { return notModified; } AttachmentData attachmentData = bannerController.getBannerImageData(organizationId, bannerId, attachmentId, size); if (attachmentData != null) { return httpCacheController.streamModified(attachmentData.getData(), attachmentData.getType(), attachmentId); } return createNotFound(NOT_FOUND); } /* Tiles */ @Override public Response listOrganizationTiles(String organizationIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); List<Tile> result = tileController.listTiles(organizationId); List<String> ids = httpCacheController.getEntityIds(result); Response notModified = httpCacheController.getNotModified(request, ids); if (notModified != null) { return notModified; } return httpCacheController.sendModified(result, ids); } @Override public Response findOrganizationTile(String organizationIdParam, String tileIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); TileId tileId = toTileId(organizationId, tileIdParam); Response notModified = httpCacheController.getNotModified(request, tileId); if (notModified != null) { return notModified; } Tile tile = tileController.findTile(organizationId, tileId); if (tile != null) { return httpCacheController.sendModified(tile, tile.getId()); } return createNotFound(NOT_FOUND); } @Override public Response listOrganizationTileImages(String organizationIdParam, String tileIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); TileId tileId = toTileId(organizationId, tileIdParam); List<Attachment> result = tileController.listTileImages(organizationId, tileId); List<String> ids = httpCacheController.getEntityIds(result); Response notModified = httpCacheController.getNotModified(request, ids); if (notModified != null) { return notModified; } return httpCacheController.sendModified(result, ids); } @Override public Response findOrganizationTileImage(String organizationIdParam, String tileIdParam, String imageIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); TileId tileId = toTileId(organizationId, tileIdParam); AttachmentId attachmentId = toAttachmentId(organizationId, imageIdParam); Response notModified = httpCacheController.getNotModified(request, attachmentId); if (notModified != null) { return notModified; } Attachment attachment = tileController.findTileImage(organizationId, tileId, attachmentId); if (attachment != null) { return httpCacheController.sendModified(attachment, attachment.getId()); } return createNotFound(NOT_FOUND); } @Override public Response getOrganizationTileImageData(String organizationIdParam, String tileIdParam, String imageIdParam, Integer size, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); TileId tileId = toTileId(organizationId, tileIdParam); AttachmentId attachmentId = toAttachmentId(organizationId, imageIdParam); Response notModified = httpCacheController.getNotModified(request, attachmentId); if (notModified != null) { return notModified; } AttachmentData attachmentData = tileController.getTileImageData(organizationId, tileId, attachmentId, size); if (attachmentData != null) { return httpCacheController.streamModified(attachmentData.getData(), attachmentData.getType(), attachmentId); } return createNotFound(NOT_FOUND); } @Override @SuppressWarnings("squid:MethodCyclomaticComplexity") public Response createOrganizationSetting(String organizationIdParam, OrganizationSetting setting, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } if (StringUtils.isBlank(setting.getKey())) { return createBadRequest("Key is required"); } if (StringUtils.isBlank(setting.getValue())) { return createBadRequest("Value is required"); } List<OrganizationSetting> organizationSettings = organizationSettingProvider.listOrganizationSettings(organizationId, setting.getKey()); if (!organizationSettings.isEmpty()) { return createBadRequest("Setting already exists"); } OrganizationSetting organizationSetting = organizationSettingProvider.createOrganizationSetting(organizationId, setting.getKey(), setting.getValue()); if (organizationSetting == null) { return createInternalServerError(INTERNAL_SERVER_ERROR); } return Response.ok() .entity(organizationSetting) .build(); } @Override public Response listOrganizationSettings(String organizationIdParam, String key, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } List<OrganizationSetting> result = organizationSettingProvider.listOrganizationSettings(organizationId, key); return Response.ok() .entity(result) .build(); } @Override public Response findOrganizationSetting(String organizationIdParam, String settingIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } if (!StringUtils.isNumeric(settingIdParam)) { return createBadRequest(INVALID_SETTING_ID); } Long settingId = NumberUtils.createLong(settingIdParam); OrganizationSetting organizationSetting = organizationSettingProvider.findOrganizationSetting(organizationId, settingId); if (organizationSetting == null) { return createNotFound(NOT_FOUND); } return Response.ok() .entity(organizationSetting) .build(); } @Override @SuppressWarnings ("squid:MethodCyclomaticComplexity") public Response updateOrganizationSetting(String organizationIdParam, String settingIdParam, OrganizationSetting setting, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } if (StringUtils.isBlank(setting.getKey())) { return createBadRequest("Key is required"); } if (StringUtils.isBlank(setting.getValue())) { return createBadRequest("Value is required"); } if (!StringUtils.isNumeric(settingIdParam)) { return createBadRequest(INVALID_SETTING_ID); } Long settingId = NumberUtils.createLong(settingIdParam); OrganizationSetting organizationSetting = organizationSettingProvider.findOrganizationSetting(organizationId, settingId); if (organizationSetting == null) { return createNotFound(NOT_FOUND); } if (!StringUtils.equals(organizationSetting.getKey(), setting.getKey())) { return createBadRequest("Cannot update setting key"); } OrganizationSetting updatedOrganizationSetting = organizationSettingProvider.updateOrganizationSetting(settingId, setting.getValue()); if (updatedOrganizationSetting == null) { return createNotFound(NOT_FOUND); } return Response.ok() .entity(updatedOrganizationSetting) .build(); } @Override public Response deleteOrganizationSetting(String organizationIdParam, String settingIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } if (!StringUtils.isNumeric(settingIdParam)) { return createBadRequest(INVALID_SETTING_ID); } Long settingId = NumberUtils.createLong(settingIdParam); OrganizationSetting organizationSetting = organizationSettingProvider.findOrganizationSetting(organizationId, settingId); if (organizationSetting == null) { return createNotFound(NOT_FOUND); } organizationSettingProvider.deleteOrganizationSetting(settingId); return Response.noContent() .build(); } /* Pages */ @Override public Response listOrganizationPages(String organizationIdParam, String parentIdParam, String path, String search, Long firstResult, Long maxResults, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } if (search != null && (parentIdParam != null || path != null)) { return createNotImplemented("Search parameter can not be combined with path or parentId parameters"); } boolean onlyRootPages = StringUtils.equals("ROOT", parentIdParam); PageId parentId = onlyRootPages ? null : toPageId(organizationId, parentIdParam); List<Page> result = listOrganizationPages(organizationId, onlyRootPages, parentId, path, search, firstResult, maxResults); List<String> ids = httpCacheController.getEntityIds(result); Response notModified = httpCacheController.getNotModified(request, ids); if (notModified != null) { return notModified; } return httpCacheController.sendModified(result, ids); } @Override public Response findOrganizationPage(String organizationIdParam, String pageIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } PageId pageId = toPageId(organizationId, pageIdParam); if (pageId == null) { return createNotFound(NOT_FOUND); } Response notModified = httpCacheController.getNotModified(request, pageId); if (notModified != null) { return notModified; } Page page = pageController.findPage(organizationId, pageId); if (page != null) { return httpCacheController.sendModified(page, page.getId()); } return createNotFound(NOT_FOUND); } @Override public Response findOrganizationPageContent(String organizationIdParam, String pageIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } PageId pageId = toPageId(organizationId, pageIdParam); if (pageId == null) { return createNotFound(NOT_FOUND); } Response notModified = httpCacheController.getNotModified(request, pageId); if (notModified != null) { return notModified; } if (pageController.findPage(organizationId, pageId) != null) { List<LocalizedValue> pageContents = pageController.getPageContents(organizationId, pageId); if (pageContents != null) { return httpCacheController.sendModified(pageContents, pageId.getId()); } } return createNotFound(NOT_FOUND); } @Override public Response listOrganizationPageImages(String organizationIdParam, String pageIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); PageId pageId = toPageId(organizationId, pageIdParam); List<Attachment> result = pageController.listPageImages(organizationId, pageId); List<String> ids = httpCacheController.getEntityIds(result); Response notModified = httpCacheController.getNotModified(request, ids); if (notModified != null) { return notModified; } if (pageController.findPage(organizationId, pageId) == null) { return createNotFound(NOT_FOUND); } return httpCacheController.sendModified(result, ids); } @Override public Response findOrganizationPageImage(String organizationIdParam, String pageIdParam, String imageIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); PageId pageId = toPageId(organizationId, pageIdParam); AttachmentId attachmentId = toAttachmentId(organizationId, imageIdParam); Response notModified = httpCacheController.getNotModified(request, attachmentId); if (notModified != null) { return notModified; } Attachment attachment = pageController.findPageImage(organizationId, pageId, attachmentId); if (attachment != null) { return httpCacheController.sendModified(attachment, attachment.getId()); } return createNotFound(NOT_FOUND); } @Override public Response getOrganizationPageImageData(String organizationIdParam, String pageIdParam, String imageIdParam, Integer size, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); PageId pageId = toPageId(organizationId, pageIdParam); AttachmentId attachmentId = toAttachmentId(organizationId, imageIdParam); Response notModified = httpCacheController.getNotModified(request, attachmentId); if (notModified != null) { return notModified; } AttachmentData attachmentData = pageController.getPageAttachmentData(organizationId, pageId, attachmentId, size); if (attachmentData != null) { return httpCacheController.streamModified(attachmentData.getData(), attachmentData.getType(), attachmentId); } return createNotFound(NOT_FOUND); } /* Menus */ @Override public Response listOrganizationMenus(String organizationIdParam, String slug, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } List<Menu> result = menuController.listMenus(slug, organizationId); List<String> ids = httpCacheController.getEntityIds(result); Response notModified = httpCacheController.getNotModified(request, ids); if (notModified != null) { return notModified; } return httpCacheController.sendModified(result, ids); } @Override public Response findOrganizationMenu(String organizationIdParam, String menuIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } MenuId menuId = toMenuId(organizationId, menuIdParam); if (menuId == null) { return createNotFound(NOT_FOUND); } Response notModified = httpCacheController.getNotModified(request, menuId); if (notModified != null) { return notModified; } Menu menu = menuController.findMenu(organizationId, menuId); if (menu != null) { return httpCacheController.sendModified(menu, menu.getId()); } return createNotFound(NOT_FOUND); } /* Menu Items */ @Override public Response listOrganizationMenuItems(String organizationIdParam, String menuIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } MenuId menuId = toMenuId(organizationId, menuIdParam); if (menuId == null) { return createNotFound(NOT_FOUND); } List<MenuItem> result = menuController.listMenuItems(organizationId, menuId); List<String> ids = httpCacheController.getEntityIds(result); Response notModified = httpCacheController.getNotModified(request, ids); if (notModified != null) { return notModified; } return httpCacheController.sendModified(result, ids); } @Override public Response findOrganizationMenuItem(String organizationIdParam, String menuIdParam, String menuItemIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } MenuId menuId = toMenuId(organizationId, menuIdParam); if (menuId == null) { return createNotFound(NOT_FOUND); } MenuItemId menuItemId = toMenuItemId(organizationId, menuItemIdParam); if (menuItemId == null) { return createNotFound(NOT_FOUND); } return findOrganizationMenuItem(organizationId, menuId, menuItemId, request); } private Response findOrganizationMenuItem(OrganizationId organizationId, MenuId menuId, MenuItemId menuItemId, Request request) { Response notModified = httpCacheController.getNotModified(request, menuItemId); if (notModified != null) { return notModified; } MenuItem menuItem = menuController.findMenuItem(organizationId, menuId, menuItemId); if (menuItem != null) { return httpCacheController.sendModified(menuItem, menuItem.getId()); } return createNotFound(NOT_FOUND); } /* Files */ @Override public Response listOrganizationFiles(String organizationIdParam, String pageIdParam, String search, Long firstResult, Long maxResults, Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } PageId pageId = toPageId(organizationId, pageIdParam); List<FileDef> result; if (search != null) { result = fileController.searchFiles(organizationId, pageId, search, firstResult, maxResults); } else { result = fileController.listFiles(organizationId, pageId, firstResult, maxResults); } List<String> ids = httpCacheController.getEntityIds(result); Response notModified = httpCacheController.getNotModified(request, ids); if (notModified != null) { return notModified; } return httpCacheController.sendModified(result, ids); } @Override public Response findOrganizationFile(String organizationIdParam, String fileIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } FileId fileId = toFileId(organizationId, fileIdParam); if (fileId == null) { return createNotFound(NOT_FOUND); } Response notModified = httpCacheController.getNotModified(request, fileId); if (notModified != null) { return notModified; } FileDef file = fileController.findFile(organizationId, fileId); if (file != null) { return httpCacheController.sendModified(file, file.getId()); } return createNotFound(NOT_FOUND); } @Override public Response getOrganizationFileData(String organizationIdParam, String fileIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } FileId fileId = toFileId(organizationId, fileIdParam); if (fileId == null) { return createNotFound(NOT_FOUND); } Response notModified = httpCacheController.getNotModified(request, fileId); if (notModified != null) { return notModified; } AttachmentData data = fileController.getFileData(organizationId, fileId); if (data != null) { return httpCacheController.streamModified(data.getData(), data.getType(), fileId); } return createNotFound(NOT_FOUND); } /* Jobs */ @Override public Response findOrganizationJob(String organizationIdParam, String jobIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } JobId jobId = toJobId(organizationId, jobIdParam); if (jobId == null) { return createNotFound(NOT_FOUND); } Response notModified = httpCacheController.getNotModified(request, jobId); if (notModified != null) { return notModified; } Job job = jobController.findJob(organizationId, jobId); if (job != null) { return httpCacheController.sendModified(job, job.getId()); } return createNotFound(NOT_FOUND); } @Override public Response listOrganizationJobs(String organizationIdParam, String sortBy, String sortDir, Long firstResult, Long maxResults, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } JobOrder order = null; JobOrderDirection orderDirection = null; if (StringUtils.isNotBlank(sortBy)) { order = EnumUtils.getEnum(JobProvider.JobOrder.class, sortBy); if (order == null) { return createBadRequest("Invalid value for sortBy"); } } if (StringUtils.isNotBlank(sortDir)) { orderDirection = EnumUtils.getEnum(JobOrderDirection.class, sortDir); if (orderDirection == null) { return createBadRequest("Invalid value for sortDir"); } } return listOrganizationJobs(request, organizationId, order, orderDirection, firstResult, maxResults); } /* Announcements */ @Override public Response findOrganizationAnnouncement(String organizationIdParam, String announcementIdParam, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } AnnouncementId announcementId = toAnnouncementId(organizationId, announcementIdParam); if (announcementId == null) { return createNotFound(NOT_FOUND); } Response notModified = httpCacheController.getNotModified(request, announcementId); if (notModified != null) { return notModified; } Announcement announcement = announcementController.findAnnouncement(organizationId, announcementId); if (announcement != null) { return httpCacheController.sendModified(announcement, announcement.getId()); } return createNotFound(NOT_FOUND); } @Override public Response listOrganizationAnnouncements(String organizationIdParam, Integer firstResult, Integer maxResults, String sortBy, String sortDir, @Context Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } AnnouncementProvider.AnnouncementOrder order = null; AnnouncementProvider.AnnouncementOrderDirection orderDirection = null; if (StringUtils.isNotBlank(sortBy)) { order = EnumUtils.getEnum(AnnouncementProvider.AnnouncementOrder.class, sortBy); if (order == null) { return createBadRequest("Invalid value for sortBy"); } } if (StringUtils.isNotBlank(sortDir)) { orderDirection = EnumUtils.getEnum(AnnouncementProvider.AnnouncementOrderDirection.class, sortDir); if (orderDirection == null) { return createBadRequest("Invalid value for sortDir"); } } return listOrganizationAnnouncements(request, organizationId, order, orderDirection, firstResult, maxResults); } /* Contacts */ @Override public Response findOrganizationContact(String organizationIdParam, String contactIdParam, Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } ContactId contactId = toContactId(organizationId, contactIdParam); if (contactId == null) { return createNotFound(NOT_FOUND); } Response notModified = httpCacheController.getNotModified(request, contactId); if (notModified != null) { return notModified; } Contact contact = contactController.findContact(organizationId, contactId); if (contact != null) { return httpCacheController.sendModified(contact, contact.getId()); } return createNotFound(NOT_FOUND); } @Override public Response listOrganizationContacts(String organizationIdParam, Request request) { OrganizationId organizationId = toOrganizationId(organizationIdParam); if (organizationId == null) { return createNotFound(NOT_FOUND); } return listOrganizationContacts(request, organizationId, null, null); } private List<Page> listOrganizationPages(OrganizationId organizationId, boolean onlyRootPages, PageId parentId, String path, String search, Long firstResult, Long maxResults) { if (search != null) { return pageController.searchPages(organizationId, search, firstResult, maxResults); } else { return pageController.listPages(organizationId, path, onlyRootPages, parentId, firstResult, maxResults); } } private Response listOrganizationJobs(Request request, OrganizationId organizationId, JobOrder order, JobOrderDirection orderDirection, Long firstResult, Long maxResults) { List<Job> result = jobController.listJobs(organizationId, order, orderDirection, firstResult, maxResults); List<String> ids = httpCacheController.getEntityIds(result); Response notModified = httpCacheController.getNotModified(request, ids); if (notModified != null) { return notModified; } return httpCacheController.sendModified(result, ids); } private Response listOrganizationAnnouncements(Request request, OrganizationId organizationId, AnnouncementOrder order, AnnouncementOrderDirection orderDirection, Integer firstResult, Integer maxResults) { List<Announcement> result = announcementController.listAnnouncements(organizationId, order, orderDirection, firstResult, maxResults); List<String> ids = httpCacheController.getEntityIds(result); Response notModified = httpCacheController.getNotModified(request, ids); if (notModified != null) { return notModified; } return httpCacheController.sendModified(result, ids); } private Response listOrganizationContacts(Request request, OrganizationId organizationId, Integer firstResult, Integer maxResults) { List<Contact> result = contactController.listContacts(organizationId, firstResult, maxResults); List<String> ids = httpCacheController.getEntityIds(result); Response notModified = httpCacheController.getNotModified(request, ids); if (notModified != null) { return notModified; } return httpCacheController.sendModified(result, ids); } private Response validateListLimitParams(Long firstResult, Long maxResults) { if (firstResult != null && firstResult < 0) { return createBadRequest(FIRST_RESULT_MUST_BY_A_POSITIVE_INTEGER); } if (maxResults != null && maxResults < 0) { return createBadRequest(MAX_RESULTS_MUST_BY_A_POSITIVE_INTEGER); } return null; } private BannerId toBannerId(OrganizationId organizationId, String id) { if (StringUtils.isNotBlank(id)) { return new BannerId(organizationId, KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private TileId toTileId(OrganizationId organizationId, String id) { if (StringUtils.isNotBlank(id)) { return new TileId(organizationId, KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private NewsArticleId toNewsArticleId(OrganizationId organizationId, String id) { if (StringUtils.isNotBlank(id)) { return new NewsArticleId(organizationId, KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private OrganizationId toOrganizationId(String id) { if (StringUtils.isNotBlank(id)) { return new OrganizationId(KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private OrganizationServiceId toOrganizationServiceId(OrganizationId organizationId, String id) { if (StringUtils.isNotBlank(id)) { return new OrganizationServiceId(organizationId, KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private EventId toEventId(OrganizationId organizationId, String id) { if (StringUtils.isNotBlank(id)) { return new EventId(organizationId,KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private AttachmentId toAttachmentId(OrganizationId organizationId, String id) { if (StringUtils.isNotBlank(id)) { return new AttachmentId(organizationId, KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private FileId toFileId(OrganizationId organizationId, String id) { if (StringUtils.isNotBlank(id)) { return new FileId(organizationId, KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private PageId toPageId(OrganizationId organizationId, String id) { if (StringUtils.isNotBlank(id)) { return new PageId(organizationId, KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private MenuId toMenuId(OrganizationId organizationId, String id) { if (StringUtils.isNotBlank(id)) { return new MenuId(organizationId, KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private MenuItemId toMenuItemId(OrganizationId organizationId, String id) { if (StringUtils.isNotBlank(id)) { return new MenuItemId(organizationId, KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private JobId toJobId(OrganizationId organizationId, String id) { if (StringUtils.isNotBlank(id)) { return new JobId(organizationId, KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private AnnouncementId toAnnouncementId(OrganizationId organizationId, String id) { if (StringUtils.isNotBlank(id)) { return new AnnouncementId(organizationId, KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private ContactId toContactId(OrganizationId organizationId, String id) { if (StringUtils.isNotBlank(id)) { return new ContactId(organizationId, KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private OffsetDateTime getDateTime(String timeString) { if (StringUtils.isNotBlank(timeString)) { return OffsetDateTime.parse(timeString); } return null; } private List<OrganizationServiceProvider> getOrganizationServiceProviders() { List<OrganizationServiceProvider> result = new ArrayList<>(); Iterator<OrganizationServiceProvider> iterator = organizationServiceProviders.iterator(); while (iterator.hasNext()) { result.add(iterator.next()); } return Collections.unmodifiableList(result); } }
package com.sequenceiq.cloudbreak.sigmadbus; import static com.google.common.base.Preconditions.checkNotNull; import static com.sequenceiq.cloudbreak.sigmadbus.converter.DatabusRequestConverter.convert; import static com.sequenceiq.cloudbreak.sigmadbus.converter.DatabusRequestConverter.getPayload; import static io.grpc.internal.GrpcUtil.DEFAULT_MAX_MESSAGE_SIZE; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.cloudera.sigma.service.dbus.DbusProto; import com.cloudera.sigma.service.dbus.SigmaDbusGrpc; import com.sequenceiq.cloudbreak.auth.crn.RegionAwareInternalCrnGeneratorFactory; import com.sequenceiq.cloudbreak.grpc.ManagedChannelWrapper; import com.sequenceiq.cloudbreak.grpc.altus.AltusMetadataInterceptor; import com.sequenceiq.cloudbreak.grpc.util.GrpcUtil; import com.sequenceiq.cloudbreak.logger.MDCBuilder; import com.sequenceiq.cloudbreak.logger.MdcContext; import com.sequenceiq.cloudbreak.sigmadbus.config.SigmaDatabusConfig; import com.sequenceiq.cloudbreak.sigmadbus.model.DatabusRecordProcessingException; import com.sequenceiq.cloudbreak.sigmadbus.model.DatabusRequest; import com.sequenceiq.cloudbreak.sigmadbus.model.DatabusRequestContext; import com.sequenceiq.cloudbreak.telemetry.databus.AbstractDatabusStreamConfiguration; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.opentracing.Tracer; public class SigmaDatabusClient<D extends AbstractDatabusStreamConfiguration> implements AutoCloseable { private static final Logger LOGGER = LoggerFactory.getLogger(SigmaDatabusClient.class); private final Tracer tracer; private final SigmaDatabusConfig sigmaDatabusConfig; private final D databusStreamConfiguration; private ManagedChannelWrapper managedChannelWrapper; private RegionAwareInternalCrnGeneratorFactory regionAwareInternalCrnGeneratorFactory; public SigmaDatabusClient(Tracer tracer, SigmaDatabusConfig sigmaDatabusConfig, D databusStreamConfiguration, RegionAwareInternalCrnGeneratorFactory regionAwareInternalCrnGeneratorFactory) { this.tracer = tracer; this.sigmaDatabusConfig = sigmaDatabusConfig; this.databusStreamConfiguration = databusStreamConfiguration; this.regionAwareInternalCrnGeneratorFactory = regionAwareInternalCrnGeneratorFactory; } /** * Upload data into databus. If the payload is larger than 1 MB, the data will be uploaded to cloudera S3. * @param request databus record payload input * @throws DatabusRecordProcessingException error during databus record processing */ public void putRecord(DatabusRequest request) throws DatabusRecordProcessingException { ManagedChannelWrapper channelWrapper = getMessageWrapper(); DbusProto.PutRecordRequest recordRequest = convert(request, databusStreamConfiguration); String requestId = MDCBuilder.getOrGenerateRequestId(); String streamName = recordRequest.getRecord().getStreamName(); LOGGER.debug("Creating databus request with request id: {} [stream: {}]", requestId, streamName); buildMdcContext(request, requestId); DbusProto.PutRecordResponse recordResponse = newStub(channelWrapper.getChannel(), requestId, regionAwareInternalCrnGeneratorFactory.iam().getInternalCrnForServiceAsString()) .putRecord(recordRequest); DbusProto.Record.Reply.Status status = recordResponse.getRecord().getStatus(); LOGGER.debug("Returned dbus record status is {} [stream: {}]", status, streamName); if (DbusProto.Record.Reply.Status.SENT.equals(status)) { String recordId = recordResponse.getRecord().getRecordId(); LOGGER.debug("Dbus record successfully processed with record id: {} [stream: {}]", recordId, streamName); } else if (DbusProto.Record.Reply.Status.PENDING.equals(status)) { String recordId = recordResponse.getRecord().getRecordId(); String s3BucketUrl = recordResponse.getRecord().getUploadUrl(); LOGGER.debug("Dbus record can be uploaded to s3 [record id: {}], [s3 url: {}], [stream: {}]", recordId, s3BucketUrl, streamName); uploadRecordToS3(s3BucketUrl, request, recordId); } else { throw new DatabusRecordProcessingException(String.format("Cannot process record to Sigma Databus. [stream: %s]", streamName)); } } private void uploadRecordToS3(String s3Url, DatabusRequest request, String recordId) throws DatabusRecordProcessingException { String payload = getPayload(request); try { HttpClient client = HttpClient.newHttpClient(); HttpRequest httpRequest = HttpRequest.newBuilder() .uri(new URI(s3Url)) .PUT(HttpRequest.BodyPublishers.ofString(payload)) .build(); HttpResponse<String> response = client.send(httpRequest, HttpResponse.BodyHandlers.ofString()); Response.Status.Family statusFamily = Response.Status.Family.familyOf(response.statusCode()); LOGGER.debug("Databus (upload to S3) response status code: {}", response.statusCode()); if (Response.Status.Family.SUCCESSFUL.equals(statusFamily) || Response.Status.Family.REDIRECTION.equals(statusFamily)) { LOGGER.debug("Databus record with id {} successfully uploaded to s3.", recordId); } else { throw new DatabusRecordProcessingException(String.format("S3 upload failed for databus record with id %s", recordId)); } } catch (URISyntaxException | IOException | InterruptedException e) { throw new DatabusRecordProcessingException(String.format("Error during uploading record with id %s to s3", recordId), e); } } /** * Creates Managed Channel wrapper from endpoint address * * @return the wrapper object */ private ManagedChannelWrapper makeWrapper() { return new ManagedChannelWrapper( ManagedChannelBuilder.forAddress(sigmaDatabusConfig.getHost(), sigmaDatabusConfig.getPort()) .usePlaintext() .maxInboundMessageSize(DEFAULT_MAX_MESSAGE_SIZE) .build()); } /** * Creates a new stub with the appropriate metadata injecting interceptors. * * @param channel channel * @param requestId the request ID * @param actorCrn actor * @return the stub */ private SigmaDbusGrpc.SigmaDbusBlockingStub newStub(ManagedChannel channel, String requestId, String actorCrn) { checkNotNull(requestId, "requestId should not be null."); return SigmaDbusGrpc.newBlockingStub(channel) .withInterceptors(GrpcUtil.getTimeoutInterceptor(sigmaDatabusConfig.getGrpcTimeoutSec().longValue())) .withInterceptors(GrpcUtil.getTracingInterceptor(tracer), new AltusMetadataInterceptor(requestId, actorCrn)); } @Override public void close() { if (managedChannelWrapper != null) { managedChannelWrapper.close(); } } private ManagedChannelWrapper getMessageWrapper() { if (managedChannelWrapper == null) { managedChannelWrapper = makeWrapper(); } return managedChannelWrapper; } private void buildMdcContext(DatabusRequest request, String requestId) { if (request.getContext().isPresent()) { DatabusRequestContext context = request.getContext().get(); MdcContext.builder() .requestId(requestId) .tenant(context.getAccountId()) .environmentCrn(context.getEnvironmentCrn()) .resourceCrn(context.getResourceCrn()) .resourceName(context.getResourceName()) .buildMdc(); } } }
package net.floodlightcontroller.nfvtest.nfvcorestructure; import java.util.ArrayList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.floodlightcontroller.nfvtest.nfvutils.HostServer.VmInstance; public class NFVNode { public class SimpleSM{ private int state; private final ArrayList<Integer> list; private final int listSize; private int index; public int getState(){ return this.state; } public SimpleSM(int listSize){ this.listSize = listSize; list = new ArrayList<Integer>(listSize); this.state = NFVNode.IDLE; this.index = 0; for(int i=0; i<this.listSize; i++){ this.list.add(new Integer(0)); } } public void updateTransientState(int transientState){ this.list.set(this.index, new Integer(transientState)); this.index+=1; if(this.index == this.listSize){ updateFinalState(); this.index = 0; } } private void updateFinalState(){ int nOverload = 0; int nNormal = 0; int nIdle = 0; Integer overload = new Integer(NFVNode.OVERLOAD); Integer normal = new Integer(NFVNode.NORMAL); Integer idle = new Integer(NFVNode.IDLE); for(Integer elem : this.list){ if(elem.equals(overload)){ nOverload += 1; } if(elem.equals(normal)){ nNormal += 1; } if(elem.equals(idle)){ nIdle += 1; } } if((nOverload==nNormal)&&(nOverload==nIdle)){ this.state = NFVNode.NORMAL; } else if((nOverload>=nNormal)&&(nOverload>=nIdle)){ this.state = NFVNode.OVERLOAD; } else if((nNormal>=nOverload)&&(nNormal>=nIdle)){ this.state = NFVNode.NORMAL; } else if((nIdle>=nNormal)&&(nIdle>=nOverload)){ this.state = NFVNode.IDLE; } } } public class CircularList<E extends Comparable<E>>{ private final ArrayList<E> list; private final int size; private int index; private boolean filledUp; public CircularList(int size, E e){ this.list = new ArrayList<E>(size); this.size = size; this.index = 0; this.filledUp = false; for(int i=0; i<this.size; i++){ this.list.add(e); } } public void add(E element){ this.list.set(this.index, element); this.index = (this.index+1)%this.size; if(this.filledUp == false){ if(this.index == 0){ this.filledUp = true; } } } public boolean getFilledUp(){ return this.filledUp; } public ArrayList<E> getCircularList(){ return this.list; } public int getIndex(){ return this.index; } } public class NFVBufferNodeProperty{ private final SimpleSM cpuState; private final SimpleSM memState; private final SimpleSM eth0RecvState; private final SimpleSM eth0SendState; private final SimpleSM eth1RecvState; private final SimpleSM eth1SendState; public final CircularList<Float> cpuUsage; public final CircularList<Float> memUsage; public final CircularList<Long> eth0RecvPkt; public final CircularList<Long> eth0SendPkt; public final CircularList<Long> eth1RecvPkt; public final CircularList<Long> eth1SendPkt; public NFVBufferNodeProperty(int listSize){ cpuState = new SimpleSM(listSize); memState = new SimpleSM(listSize); eth0RecvState = new SimpleSM(listSize); eth0SendState = new SimpleSM(listSize); eth1RecvState = new SimpleSM(listSize); eth1SendState = new SimpleSM(listSize); cpuUsage = new CircularList<Float>(listSize, new Float(0)); memUsage = new CircularList<Float>(listSize, new Float(0)); eth0RecvPkt = new CircularList<Long>(listSize, new Long(0)); eth0SendPkt = new CircularList<Long>(listSize, new Long(0)); eth1RecvPkt = new CircularList<Long>(listSize, new Long(0)); eth1SendPkt = new CircularList<Long>(listSize, new Long(0)); } public void updateNodeProperty(Float cpuUsage, Float memUsage, Long eth0RecvPkt, Long eth0SendPkt, Long eth1RecvPkt, Long eth1SendPkt){ this.cpuUsage.add(cpuUsage); this.memUsage.add(memUsage); this.eth0RecvPkt.add(eth0RecvPkt); this.eth0SendPkt.add(eth0SendPkt); this.eth1RecvPkt.add(eth1RecvPkt); this.eth1SendPkt.add(eth1SendPkt); } public int getNodeState(){ if(cpuUsage.getFilledUp()){ cpuState.updateTransientState(checkStatus(cpuUsage.getCircularList(), new Float(30.0), new Float(60.0))); } if(memUsage.getFilledUp()){ memState.updateTransientState(checkStatus(memUsage.getCircularList(), new Float(20.0), new Float(50.0))); } if(eth0RecvPkt.getFilledUp()){ eth0RecvState.updateTransientState(checkStatus(eth0RecvPkt.getCircularList(), new Long(10000), new Long(50000))); } if(eth0SendPkt.getFilledUp()){ eth0SendState.updateTransientState(checkStatus(eth0SendPkt.getCircularList(), new Long(10000), new Long(50000))); } if(eth1RecvPkt.getFilledUp()){ eth1RecvState.updateTransientState(checkStatus(eth1RecvPkt.getCircularList(), new Long(10000), new Long(50000))); } if(eth1SendPkt.getFilledUp()){ eth1SendState.updateTransientState(checkStatus(eth1SendPkt.getCircularList(), new Long(10000), new Long(50000))); } int[] stateList = new int[6]; stateList[0] = cpuState.getState(); stateList[1] = memState.getState(); stateList[2] = eth0RecvState.getState(); stateList[3] = eth0SendState.getState(); stateList[4] = eth1RecvState.getState(); stateList[5] = eth1SendState.getState(); int nNormal = 0; int nIdle = 0; for(int i=0; i<6; i++){ if(stateList[i] == NFVNode.OVERLOAD){ return NFVNode.OVERLOAD; } else if(stateList[i] == NFVNode.NORMAL){ nNormal += 1; } else if(stateList[i] == NFVNode.IDLE){ nIdle += 1; } } if(nIdle == 6){ return NFVNode.IDLE; } else{ return NFVNode.NORMAL; } } private <E extends Comparable<E>> int checkStatus(ArrayList<E> list, E lowerT, E upperT){ int largerThanUpperT = 0; int smallerThanLowerT = 0; int inBetween = 0; for(E elem : list){ if(elem.compareTo(upperT)>0){ largerThanUpperT +=1; } else if(elem.compareTo(lowerT)<0){ smallerThanLowerT +=1; } else{ inBetween += 1; } } int returnVal = 0; if((largerThanUpperT == smallerThanLowerT)&&(largerThanUpperT == inBetween)){ returnVal = NFVNode.NORMAL; } else if((largerThanUpperT >= smallerThanLowerT)&&(largerThanUpperT >= inBetween)){ returnVal = NFVNode.OVERLOAD; } else if((inBetween>=largerThanUpperT)&&(inBetween>=smallerThanLowerT)){ returnVal = NFVNode.NORMAL; } else if((smallerThanLowerT>=inBetween)&&(smallerThanLowerT>=largerThanUpperT)){ returnVal = NFVNode.IDLE; } return returnVal; } } public class NFVNodeProperty{ private final SimpleSM cpuState; private final SimpleSM memState; private final SimpleSM eth0RecvState; private final SimpleSM eth0SendState; private final SimpleSM eth1RecvState; private final SimpleSM eth1SendState; private final SimpleSM tranState; public final CircularList<Float> cpuUsage; public final CircularList<Float> memUsage; public final CircularList<Integer> eth0RecvInt; public final CircularList<Long> eth0RecvPkt; public final CircularList<Integer> eth0SendInt; public final CircularList<Integer> eth1RecvInt; public final CircularList<Long> eth1RecvPkt; public final CircularList<Integer> eth1SendInt; public final CircularList<Integer> goodTran; public final CircularList<Integer> badTran; public final CircularList<Integer> srdSt250ms; public final CircularList<Integer> srdLt250ms; public NFVNodeProperty(int listSize){ cpuUsage = new CircularList<Float>(listSize, new Float(0)); memUsage = new CircularList<Float>(listSize, new Float(0)); eth0RecvInt = new CircularList<Integer>(listSize, new Integer(0)); eth0RecvPkt = new CircularList<Long>(listSize, new Long(0)); eth0SendInt = new CircularList<Integer>(listSize, new Integer(0)); eth1RecvInt = new CircularList<Integer>(listSize, new Integer(0)); eth1RecvPkt = new CircularList<Long>(listSize, new Long(0)); eth1SendInt = new CircularList<Integer>(listSize, new Integer(0)); cpuState = new SimpleSM(listSize); memState = new SimpleSM(listSize); eth0RecvState = new SimpleSM(listSize); eth0SendState = new SimpleSM(listSize); eth1RecvState = new SimpleSM(listSize); eth1SendState = new SimpleSM(listSize); goodTran = new CircularList<Integer>(6, new Integer(0)); badTran = new CircularList<Integer>(6, new Integer(0)); srdSt250ms = new CircularList<Integer>(6, new Integer(0)); srdLt250ms = new CircularList<Integer>(6, new Integer(0)); tranState = new SimpleSM(6); } public void updateTranProperty(Integer goodTran, Integer badTran, Integer srdSt250ms, Integer srdLt250ms){ this.goodTran.add(goodTran); this.badTran.add(badTran); this.srdSt250ms.add(srdSt250ms); this.srdLt250ms.add(srdLt250ms); } public int getTranState(){ if(goodTran.getFilledUp()&&badTran.getFilledUp()&&srdSt250ms.getFilledUp() &&srdLt250ms.getFilledUp()){ tranState.updateTransientState(checkTranStatus(goodTran.getCircularList(), badTran.getCircularList(), srdSt250ms.getCircularList(), srdLt250ms.getCircularList())); return tranState.getState(); } else{ return NFVNode.NORMAL; } } public void updateNodeProperty(Float cpuUsage, Float memUsage, Integer eth0RecvInt, Long eth0RecvPkt, Integer eth0SendInt, Integer eth1RecvInt, Long eth1RecvPkt, Integer eth1SendInt){ this.cpuUsage.add(cpuUsage); this.memUsage.add(memUsage); this.eth0RecvInt.add(eth0RecvInt); this.eth0RecvPkt.add(eth0RecvPkt); this.eth0SendInt.add(eth0SendInt); this.eth1RecvInt.add(eth1RecvInt); this.eth1RecvPkt.add(eth1RecvPkt); this.eth1SendInt.add(eth1SendInt); } public int getNodeState(){ if(cpuUsage.getFilledUp()){ cpuState.updateTransientState(checkStatus(cpuUsage.getCircularList(), new Float(30.0), new Float(85.0))); } if(memUsage.getFilledUp()){ memState.updateTransientState(checkStatus(memUsage.getCircularList(), new Float(30.0), new Float(70.0))); } if(eth0SendInt.getFilledUp()){ eth0SendState.updateTransientState(checkStatus(eth0SendInt.getCircularList(), new Integer(10), new Integer(20))); } if(eth1SendInt.getFilledUp()){ eth1SendState.updateTransientState(checkStatus(eth1SendInt.getCircularList(), new Integer(10), new Integer(20))); } if(eth0RecvInt.getFilledUp()&&eth0RecvPkt.getFilledUp()){ eth0RecvState.updateTransientState(checkRecvStatus(eth0RecvInt.getCircularList(), eth0RecvPkt.getCircularList(), (float)18)); } if(eth1RecvInt.getFilledUp()&&eth1RecvPkt.getFilledUp()){ eth1RecvState.updateTransientState(checkRecvStatus(eth1RecvInt.getCircularList(), eth1RecvPkt.getCircularList(), (float)18)); } int[] stateList = new int[6]; stateList[0] = cpuState.getState(); stateList[1] = memState.getState(); stateList[2] = eth0RecvState.getState(); stateList[3] = eth0SendState.getState(); stateList[4] = eth1RecvState.getState(); stateList[5] = eth1SendState.getState(); int nNormal = 0; int nIdle = 0; for(int i=0; i<6; i++){ if(stateList[i] == NFVNode.OVERLOAD){ return NFVNode.OVERLOAD; } else if(stateList[i] == NFVNode.NORMAL){ nNormal += 1; } else if(stateList[i] == NFVNode.IDLE){ nIdle += 1; } } if(nIdle == 6){ return NFVNode.IDLE; } else{ return NFVNode.NORMAL; } } private int checkTranStatus(ArrayList<Integer> goodTranList, ArrayList<Integer> badTranList, ArrayList<Integer> srdSt250List, ArrayList<Integer> srdLt250List){ float totalGoodTran = 0; float totalBadTran = 0; float totalSrdSt250 = 0; float totalSrdLt250 = 0; for(int i=0; i<goodTranList.size(); i++){ totalGoodTran += goodTranList.get(i).floatValue(); totalBadTran += badTranList.get(i).floatValue(); totalSrdSt250 += srdSt250List.get(i).floatValue(); totalSrdLt250 += srdLt250List.get(i).floatValue(); } float tranRatio = ((totalGoodTran+totalBadTran)==0)?1: (totalGoodTran/(totalGoodTran+totalBadTran)); float srdRatio = ((totalSrdSt250+totalSrdLt250)==0)?1: (totalSrdSt250/(totalSrdSt250+totalSrdLt250)); if( (tranRatio>=0.99) && (srdRatio>=0.95) ){ return NFVNode.NORMAL; } else{ return NFVNode.OVERLOAD; } } private <E extends Comparable<E>> int checkStatus(ArrayList<E> list, E lowerT, E upperT){ int largerThanUpperT = 0; int smallerThanLowerT = 0; int inBetween = 0; for(E elem : list){ if(elem.compareTo(upperT)>0){ largerThanUpperT +=1; } else if(elem.compareTo(lowerT)<0){ smallerThanLowerT +=1; } else{ inBetween += 1; } } int returnVal = 0; if((largerThanUpperT == smallerThanLowerT)&&(largerThanUpperT == inBetween)){ returnVal = NFVNode.NORMAL; } else if((largerThanUpperT >= smallerThanLowerT)&&(largerThanUpperT >= inBetween)){ returnVal = NFVNode.OVERLOAD; } else if((inBetween>=largerThanUpperT)&&(inBetween>=smallerThanLowerT)){ returnVal = NFVNode.NORMAL; } else if((smallerThanLowerT>=inBetween)&&(smallerThanLowerT>=largerThanUpperT)){ returnVal = NFVNode.IDLE; } return returnVal; } private int checkRecvStatus(ArrayList<Integer> intList, ArrayList<Long> pktList, float t){ int nOverload = 0; int nIdle = 0; for(int i=0; i<intList.size(); i++){ float val = pktList.get(i).floatValue()/intList.get(i).floatValue(); if(val>=t){ nOverload+=1; } else{ nIdle+=1; } } if(nOverload>=nIdle){ return NFVNode.OVERLOAD; } else{ return NFVNode.IDLE; } } } //immutable field. public final VmInstance vmInstance; private NFVNodeProperty property; private NFVBufferNodeProperty bufferProperty; private int state; private int tranState; private int activeFlows; private static Logger logger; //node state: idel, normal, overload public static final int IDLE = 1; public static final int NORMAL = 2; public static final int OVERLOAD = 3; public NFVNode(VmInstance vmInstance){ this.vmInstance = vmInstance; this.property = new NFVNodeProperty(4); this.state = NFVNode.IDLE; this.tranState = NFVNode.NORMAL; this.activeFlows = 0; logger = LoggerFactory.getLogger(NFVNode.class); this.bufferProperty = new NFVBufferNodeProperty(4); } public String getChainName(){ return this.vmInstance.serviceChainConfig.name; } public int getNumInterfaces(){ return this.vmInstance.serviceChainConfig.nVmInterface; } public String getMacAddress(int whichMac){ if(whichMac>=this.vmInstance.macList.size()){ return "no-such-mac"; } else{ return this.vmInstance.macList.get(whichMac); } } public String getBridgeDpid(int whichMac){ if(whichMac>=this.vmInstance.bridgeDpidList.size()){ return "no-such-bridge"; } else{ return this.vmInstance.bridgeDpidList.get(whichMac); } } public int getPort(int whichMac){ if(whichMac>=this.vmInstance.serviceChainConfig.nVmInterface){ return -10; } else{ return this.vmInstance.getPort(whichMac); } } public String getManagementIp(){ return this.vmInstance.managementIp; } public String getManagementMac(){ return this.vmInstance.managementMac; } public void updateNodeProperty(Float cpuUsage, Float memUsage, Integer eth0RecvInt, Long eth0RecvPkt, Integer eth0SendInt, Long eth0SendPkt, Integer eth1RecvInt, Long eth1RecvPkt, Integer eth1SendInt, Long eth1SendPkt){ String stat = cpuUsage.toString()+" "+memUsage.toString()+" "+eth0RecvInt.toString()+" "+ eth0RecvPkt.toString()+" "+eth0SendInt.toString()+" "+eth0SendPkt.toString()+" "+eth1RecvInt.toString() +" "+eth1RecvPkt.toString()+" "+eth1SendInt.toString()+" "+eth1SendPkt.toString(); float recvPkt = eth0RecvPkt.floatValue(); float recvInt = eth0RecvInt.floatValue(); stat = stat+" "+new Float(recvPkt/recvInt).toString(); if(!this.vmInstance.isBufferNode){ this.property.updateNodeProperty(cpuUsage, memUsage, eth0RecvInt, eth0RecvPkt, eth0SendInt, eth1RecvInt, eth1RecvPkt, eth1SendInt); this.state = this.property.getNodeState(); } else{ this.bufferProperty.updateNodeProperty(cpuUsage, memUsage, eth0RecvPkt, eth0SendPkt, eth1RecvPkt, eth1SendPkt); this.state = this.bufferProperty.getNodeState(); } //if(this.vmInstance.stageIndex == 0){ if(this.state == NFVNode.IDLE){ String output = "Node-"+this.getManagementIp()+" is IDLE : "+stat; logger.info("{}", output); } if(this.state == NFVNode.NORMAL){ String output = "Node-"+this.getManagementIp()+" is NORMAL : "+stat; logger.info("{}", output); } if(this.state == NFVNode.OVERLOAD){ String output = "Node-"+this.getManagementIp()+" is OVERLOAD : "+stat; logger.info("{}", output); } } public void updateTranProperty(Integer goodTran, Integer badTran, Integer srdSt250ms, Integer srdLt250ms){ String stat = goodTran.toString()+" "+badTran.toString()+" "+srdSt250ms.toString()+" "+srdLt250ms.toString()+" "; float p1 = goodTran.floatValue()/(goodTran.floatValue()+badTran.floatValue()); float p2 = srdSt250ms.floatValue()/(srdSt250ms.floatValue()+srdLt250ms.floatValue()); stat = stat + new Float(p1).toString() + " " + new Float(p2).toString(); this.property.updateTranProperty(goodTran, badTran, srdSt250ms, srdLt250ms); this.tranState = this.property.getTranState(); if(this.tranState == NFVNode.IDLE){ String output = "Tran Node-"+this.getManagementIp()+" is IDLE : "+stat; logger.info("{}", output); } if(this.tranState == NFVNode.NORMAL){ String output = "Tran Node-"+this.getManagementIp()+" is NORMAL : "+stat; logger.info("{}", output); } if(this.tranState == NFVNode.OVERLOAD){ String output = "Tran Node-"+this.getManagementIp()+" is OVERLOAD : "+stat; logger.info("{}", output); } } public int getState(){ return this.state; } public int getTranState(){ return this.tranState; } public void addActiveFlow(){ this.activeFlows += 1; } public void deleteActiveFlow(){ this.activeFlows -= 1; } public int getActiveFlows(){ return this.activeFlows; } }
package com.mimacom.liferay.portal.setup.core; import com.liferay.document.library.kernel.model.DLFolder; import com.liferay.portal.kernel.model.RoleConstants; import com.liferay.portal.kernel.repository.model.Folder; import com.liferay.portal.kernel.security.permission.ActionKeys; import com.mimacom.liferay.portal.setup.LiferaySetup; import com.mimacom.liferay.portal.setup.core.util.FolderUtil; import com.mimacom.liferay.portal.setup.domain.DocumentFolder; import com.mimacom.liferay.portal.setup.domain.Organization; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public final class SetupDocumentFolders { public static final HashMap<String, List<String>> DEFAULT_PERMISSIONS; static { DEFAULT_PERMISSIONS = new HashMap<>(); List<String> actionsOwner = new ArrayList<>(); actionsOwner.add(ActionKeys.VIEW); actionsOwner.add(ActionKeys.UPDATE); actionsOwner.add(ActionKeys.PERMISSIONS); actionsOwner.add(ActionKeys.DELETE); actionsOwner.add(ActionKeys.ADD_SUBFOLDER); actionsOwner.add(ActionKeys.ADD_ARTICLE); actionsOwner.add(ActionKeys.ACCESS); actionsOwner.add(ActionKeys.SUBSCRIBE); DEFAULT_PERMISSIONS.put(RoleConstants.OWNER, actionsOwner); List<String> actionsUser = new ArrayList<>(); actionsUser.add(ActionKeys.VIEW); DEFAULT_PERMISSIONS.put(RoleConstants.USER, actionsUser); List<String> actionsGuest = new ArrayList<>(); actionsGuest.add(ActionKeys.VIEW); DEFAULT_PERMISSIONS.put(RoleConstants.GUEST, actionsGuest); } private SetupDocumentFolders() { } public static void setupDocumentFolders(final Organization org, final long groupId, final long companyId) { for (DocumentFolder df : org.getDocumentFolder()) { boolean create = df.isCreateIfNotExists(); String folderName = df.getFolderName(); Folder folder = FolderUtil.findFolder(companyId, groupId, groupId, LiferaySetup.getRunAsUserId(), folderName, create); SetupPermissions.updatePermission("Document folder " + folderName, groupId, companyId, folder.getFolderId(), DLFolder.class, df.getRolePermissions(), DEFAULT_PERMISSIONS); } } }
package net.openhft.chronicle.queue.reader; import net.openhft.chronicle.core.util.Histogram; import net.openhft.chronicle.queue.ExcerptTailer; import net.openhft.chronicle.queue.impl.single.SingleChronicleQueue; import net.openhft.chronicle.queue.impl.single.SingleChronicleQueueBuilder; import net.openhft.chronicle.wire.MessageHistory; import net.openhft.chronicle.wire.MethodReader; import net.openhft.chronicle.wire.VanillaMessageHistory; import net.openhft.chronicle.wire.WireParselet; import org.jetbrains.annotations.NotNull; import java.nio.file.Files; import java.nio.file.Path; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; public class ChronicleHistoryReader { private Path basePath; private Consumer<String> messageSink; private boolean progress = false; private TimeUnit timeUnit = TimeUnit.NANOSECONDS; protected boolean histosByMethod = false; protected Map<String, Histogram> histos = new LinkedHashMap<>(); public ChronicleHistoryReader withMessageSink(final Consumer<String> messageSink) { this.messageSink = messageSink; return this; } public ChronicleHistoryReader withBasePath(final Path path) { this.basePath = path; return this; } public ChronicleHistoryReader withProgress(boolean p) { this.progress = p; return this; } public ChronicleHistoryReader withTimeUnit(TimeUnit p) { this.timeUnit = p; return this; } public ChronicleHistoryReader withHistosByMethod(boolean b) { this.histosByMethod = b; return this; } @NotNull private SingleChronicleQueue createQueue() { if (!Files.exists(basePath)) { throw new IllegalArgumentException(String.format("Path %s does not exist", basePath)); } return SingleChronicleQueueBuilder .binary(basePath.toFile()) .readOnly(true) .build(); } public void execute() { readChronicle(); printPercentilesSummary(); } public Map<String, Histogram> readChronicle() { final SingleChronicleQueue q = createQueue(); final ExcerptTailer tailer = q.createTailer(); final WireParselet parselet = parselet(); final MethodReader mr = new MethodReader(tailer, true, parselet, null, parselet); MessageHistory.set(new VanillaMessageHistory()); int counter = 0; while (! Thread.currentThread().isInterrupted() && mr.readOne()) { ++counter; if (this.progress && counter % 1_000_000 == 0) { System.out.println("Progress: " + counter); } } return histos; } public void printPercentilesSummary() { // we should also consider the case where >1 output messages are from 1 incoming if (histos.size() == 0) { messageSink.accept("No data"); return; } int counter = 0; messageSink.accept("Timings below in " + timeUnit.name()); final StringBuilder sb = new StringBuilder("sourceId "); histos.forEach((id, histogram) -> sb.append(String.format("%12s ", id))); messageSink.accept(sb.toString()); messageSink.accept("count: " + count()); messageSink.accept("50: " + percentiles(counter++)); messageSink.accept("90: " + percentiles(counter++)); messageSink.accept("99: " + percentiles(counter++)); messageSink.accept("99.9: " + percentiles(counter++)); messageSink.accept("99.99: " + percentiles(counter++)); messageSink.accept("99.999: " + percentiles(counter++)); messageSink.accept("99.9999:" + percentiles(counter++)); messageSink.accept("worst: " + percentiles(-1)); } private String count() { final StringBuilder sb = new StringBuilder(" "); histos.forEach((id, histogram) -> sb.append(String.format("%12d ", histogram.totalCount()))); return sb.toString(); } private String percentiles(final int index) { final StringBuilder sb = new StringBuilder(" "); histos.forEach((id, histogram) -> { double[] percentiles = histogram.getPercentiles(); if (index >= percentiles.length - 1) { sb.append(String.format("%12s ", " ")); return; } int myIndex = index; if (myIndex == -1) myIndex = percentiles.length - 1; double value = percentiles[myIndex]; sb.append(String.format("%12d ", timeUnit.convert((long)value, TimeUnit.NANOSECONDS))); }); return sb.toString(); } protected WireParselet parselet() { return (methodName, v, $) -> { v.skipValue(); CharSequence extraHistoId = histosByMethod ? ("_"+methodName) : ""; final MessageHistory history = MessageHistory.get(); long lastTime = 0; // if the tailer has recordHistory(true) then the MessageHistory will be // written with a single timing and nothing else. This is then carried through int firstWriteOffset = history.timings() - (history.sources() * 2); if (! (firstWriteOffset == 0 || firstWriteOffset == 1)) // don't know how this can happen, but there is at least one CQ that exhibits it return; for (int sourceIndex=0; sourceIndex<history.sources(); sourceIndex++) { String histoId = Integer.toString(history.sourceId(sourceIndex)) + extraHistoId; Histogram histo = histos.computeIfAbsent(histoId, s -> histogram()); long receivedByThisComponent = history.timing((2 * sourceIndex) + firstWriteOffset); long processedByThisComponent = history.timing((2 * sourceIndex) + firstWriteOffset + 1); histo.sample(processedByThisComponent - receivedByThisComponent); if (lastTime == 0 && firstWriteOffset > 0) { Histogram histo1 = histos.computeIfAbsent("startTo" + histoId, s -> histogram()); histo1.sample(receivedByThisComponent - history.timing(0)); } else if (lastTime != 0) { Histogram histo1 = histos.computeIfAbsent(Integer.toString(history.sourceId(sourceIndex-1)) + "to" + histoId, s -> histogram()); // here we are comparing System.nanoTime across processes. YMMV histo1.sample(receivedByThisComponent - lastTime); } lastTime = processedByThisComponent; } if (history.sources() > 1) { Histogram histoE2E = histos.computeIfAbsent("endToEnd", s -> histogram()); histoE2E.sample(history.timing(history.timings() - 1) - history.timing(0)); } }; } @NotNull protected Histogram histogram() { return new Histogram(60, 4); } }
//$HeadURL$ package org.deegree.commons.xml; import static junit.framework.Assert.assertEquals; import java.io.StringWriter; import javax.xml.namespace.QName; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.apache.axiom.om.OMAttribute; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMText; import org.apache.axiom.om.xpath.AXIOMXPath; import org.deegree.commons.xml.stax.IndentingXMLStreamWriter; import org.jaxen.JaxenException; import org.junit.Before; import org.junit.Test; public class XMLAdapterTest { private static String WFS_NS = "http: private static String APP_NS = "http: private NamespaceBindings nsContext; private XMLAdapter adapter; /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { adapter = new XMLAdapter( XMLAdapterTest.class.getResourceAsStream( "testdocument.xml" ) ); nsContext = new NamespaceBindings(); nsContext.addNamespace( "ogc", "http: nsContext.addNamespace( "gml", "http: nsContext.addNamespace( "wfs", "http: nsContext.addNamespace( "app", "http: } @Test public void testRootElement() throws XMLStreamException { assertEquals( new QName( WFS_NS, "GetFeature" ), adapter.getRootElement().getQName() ); } @Test public void testTypeNameAttribute() throws JaxenException { OMElement root = adapter.getRootElement(); AXIOMXPath xpath = new AXIOMXPath( "wfs:Query" ); xpath.addNamespace( "wfs", WFS_NS ); OMElement queryElement = (OMElement) xpath.selectSingleNode( root ); OMAttribute typeNameAttr = queryElement.getAttribute( new QName( "typeName" ) ); QName ftName = queryElement.resolveQName( typeNameAttr.getAttributeValue() ); assertEquals( new QName( APP_NS, "Philosopher" ), ftName ); } @Test public void testGetNode() { OMElement root = adapter.getRootElement(); // select text node Object textNode = adapter.getNode( root, new XPath( "wfs:Query/ogc:Filter/ogc:BBOX/ogc:PropertyName/text()", nsContext ) ); assertEquals( "app:placeOfBirth/app:Place/app:country/app:Country/app:geom", ( (OMText) textNode ).getText() ); // select attribute node Object attributeNode = adapter.getNode( root, new XPath( "wfs:Query/@typeName", nsContext ) ); assertEquals( "app:Philosopher", ( (OMAttribute) attributeNode ).getAttributeValue() ); } @Test public void testGetNodeAsString() { OMElement root = adapter.getRootElement(); // select text node String textNode = adapter.getNodeAsString( root, new XPath( "wfs:Query/ogc:Filter/ogc:BBOX/ogc:PropertyName/text()", nsContext ), null ); assertEquals( "app:placeOfBirth/app:Place/app:country/app:Country/app:geom", textNode ); // select attribute node QName attributeNode = adapter.getNodeAsQName( root, new XPath( "wfs:Query/@typeName", nsContext ), null ); assertEquals( QName.valueOf( "{http: // select element node String elementNode = adapter.getNodeAsString( root, new XPath( "wfs:Query/ogc:Filter/ogc:BBOX/gml:Envelope/gml:coord/gml:X", nsContext ), null ); assertEquals( "-1", elementNode ); } @Test(expected = XMLProcessingException.class) public void testGetRequiredNodeAsString() { OMElement root = adapter.getRootElement(); String value = adapter.getRequiredNodeAsString( root, new XPath( "wfs:Query/ogc:Filter/ogc:BBOX/ogc:PropertyName/text()", nsContext ) ); assertEquals( "app:placeOfBirth/app:Place/app:country/app:Country/app:geom", value ); adapter.getRequiredNodeAsString( root, new XPath( "wfs:Query/@doesNotExist", nsContext ) ); } @Test(expected = XMLProcessingException.class) public void testGetRequiredNodeAsQName() { OMElement root = adapter.getRootElement(); QName value = adapter.getRequiredNodeAsQName( root, new XPath( "wfs:Query/@typeName", nsContext ) ); assertEquals( new QName( APP_NS, "Philosopher" ), value ); adapter.getRequiredNodeAsQName( root, new XPath( "wfs:Query/@doesNotExist", nsContext ) ); } @Test public void testWriteElement() throws XMLStreamException { StringWriter stringWriter = new StringWriter(); XMLOutputFactory factory = XMLOutputFactory.newInstance(); factory.setProperty( XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE ); XMLStreamWriter writer = new IndentingXMLStreamWriter( factory.createXMLStreamWriter( stringWriter ) ); adapter.getRootElement().serializeAndConsume( writer ); } }
package org.cyclops.integrateddynamics.tileentity; import com.google.common.collect.Sets; import lombok.experimental.Delegate; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumParticleTypes; import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.fluids.FluidStack; import org.apache.commons.lang3.tuple.Pair; import org.apache.logging.log4j.Level; import org.cyclops.cyclopscore.datastructure.SingleCache; import org.cyclops.cyclopscore.helper.FluidHelpers; import org.cyclops.cyclopscore.persist.nbt.NBTPersist; import org.cyclops.cyclopscore.recipe.custom.api.IRecipe; import org.cyclops.cyclopscore.recipe.custom.api.IRecipeRegistry; import org.cyclops.cyclopscore.recipe.custom.component.DurationRecipeProperties; import org.cyclops.cyclopscore.recipe.custom.component.ItemAndFluidStackRecipeComponent; import org.cyclops.cyclopscore.tileentity.CyclopsTileEntity; import org.cyclops.cyclopscore.tileentity.TankInventoryTileEntity; import org.cyclops.integrateddynamics.IntegratedDynamics; import org.cyclops.integrateddynamics.block.BlockDryingBasin; /** * A tile entity for drying stuff. * @author rubensworks */ public class TileDryingBasin extends TankInventoryTileEntity implements CyclopsTileEntity.ITickingTile { private static final int WOOD_IGNITION_TEMPERATURE = 573; // 300 degrees celcius @Delegate private final ITickingTile tickingTileComponent = new TickingTileComponent(this); @NBTPersist private Float randomRotation = 0F; @NBTPersist private int progress = 0; @NBTPersist private int fire = 0; private SingleCache<Pair<ItemStack, FluidStack>, IRecipe<ItemAndFluidStackRecipeComponent, ItemAndFluidStackRecipeComponent, DurationRecipeProperties>> recipeCache; public TileDryingBasin() { super(1, "dryingBasingInventory", 1, FluidContainerRegistry.BUCKET_VOLUME, "dryingBasingTank"); addSlotsToSide(EnumFacing.UP, Sets.newHashSet(1)); addSlotsToSide(EnumFacing.DOWN, Sets.newHashSet(1)); addSlotsToSide(EnumFacing.NORTH, Sets.newHashSet(1)); addSlotsToSide(EnumFacing.SOUTH, Sets.newHashSet(1)); addSlotsToSide(EnumFacing.WEST, Sets.newHashSet(1)); addSlotsToSide(EnumFacing.EAST, Sets.newHashSet(1)); // Efficient cache to retrieve the current craftable recipe. recipeCache = new SingleCache<>( new SingleCache.ICacheUpdater<Pair<ItemStack, FluidStack>, IRecipe<ItemAndFluidStackRecipeComponent, ItemAndFluidStackRecipeComponent, DurationRecipeProperties>>() { @Override public IRecipe<ItemAndFluidStackRecipeComponent, ItemAndFluidStackRecipeComponent, DurationRecipeProperties> getNewValue(Pair<ItemStack, FluidStack> key) { ItemAndFluidStackRecipeComponent recipeInput = new ItemAndFluidStackRecipeComponent(key.getLeft(), key.getRight()); IRecipe<ItemAndFluidStackRecipeComponent, ItemAndFluidStackRecipeComponent, DurationRecipeProperties> maxRecipe = null; for (IRecipe<ItemAndFluidStackRecipeComponent, ItemAndFluidStackRecipeComponent, DurationRecipeProperties> recipe : getRegistry().findRecipesByInput(recipeInput)) { if(key.getRight() == null) { return recipe; } else if(key.getRight().amount >= recipe.getInput().getFluidStack().amount && (maxRecipe == null || recipe.getInput().getFluidStack().amount > maxRecipe.getInput().getFluidStack().amount)) { maxRecipe = recipe; } } return maxRecipe; } @Override public boolean isKeyEqual(Pair<ItemStack, FluidStack> cacheKey, Pair<ItemStack, FluidStack> newKey) { return cacheKey == null || newKey == null || (ItemStack.areItemStacksEqual(cacheKey.getLeft(), newKey.getLeft()) && FluidStack.areFluidStackTagsEqual(cacheKey.getRight(), newKey.getRight())) && FluidHelpers.getAmount(cacheKey.getRight()) == FluidHelpers.getAmount(newKey.getRight()); } }); } protected IRecipeRegistry<BlockDryingBasin, ItemAndFluidStackRecipeComponent, ItemAndFluidStackRecipeComponent, DurationRecipeProperties> getRegistry() { return BlockDryingBasin.getInstance().getRecipeRegistry(); } protected IRecipe<ItemAndFluidStackRecipeComponent, ItemAndFluidStackRecipeComponent, DurationRecipeProperties> getCurrentRecipe() { return recipeCache.get(Pair.of(getStackInSlot(0), FluidHelpers.copy(getTank().getFluid()))); } @Override protected void updateTileEntity() { super.updateTileEntity(); if(!worldObj.isRemote) { if (!getTank().isEmpty() && getTank().getFluid().getFluid().getTemperature(getTank().getFluid()) >= WOOD_IGNITION_TEMPERATURE) { if (++fire >= 100) { getWorld().setBlockState(getPos(), Blocks.fire.getDefaultState()); } else if (getWorld().isAirBlock(getPos().offset(EnumFacing.UP)) && worldObj.rand.nextInt(10) == 0) { getWorld().setBlockState(getPos().offset(EnumFacing.UP), Blocks.fire.getDefaultState()); } } else if (getCurrentRecipe() != null) { IRecipe<ItemAndFluidStackRecipeComponent, ItemAndFluidStackRecipeComponent, DurationRecipeProperties> recipe = getCurrentRecipe(); if (progress >= recipe.getProperties().getDuration()) { setInventorySlotContents(0, recipe.getOutput().getItemStack()); int amount = FluidHelpers.getAmount(recipe.getInput().getFluidStack()); drain(amount, true); if (recipe.getOutput().getFluidStack() != null) { if (fill(recipe.getOutput().getFluidStack(), true) == 0) { IntegratedDynamics.clog(Level.ERROR, "Encountered an invalid recipe: " + recipe.getNamedId()); } } progress = 0; } else { progress++; sendUpdate(); } fire = 0; } else { progress = 0; fire = 0; sendUpdate(); } } else if(progress > 0 && worldObj.rand.nextInt(5) == 0) { if(!getTank().isEmpty()) { Block block = getTank().getFluid().getFluid().getBlock(); if(block != null) { int blockStateId = Block.getStateId(block.getDefaultState()); getWorld().spawnParticle(EnumParticleTypes.BLOCK_DUST, getPos().getX() + Math.random() * 0.8D + 0.1D, getPos().getY() + Math.random() * 0.1D + 0.9D, getPos().getZ() + Math.random() * 0.8D + 0.1D, 0, 0.1D, 0, blockStateId); } } if(getStackInSlot(0) != null) { int itemId = Item.getIdFromItem(getStackInSlot(0).getItem()); getWorld().spawnParticle(EnumParticleTypes.ITEM_CRACK, getPos().getX() + Math.random() * 0.8D + 0.1D, getPos().getY() + Math.random() * 0.1D + 0.9D, getPos().getZ() + Math.random() * 0.8D + 0.1D, 0, 0.1D, 0, itemId); } } } @Override public void setInventorySlotContents(int slotId, ItemStack itemstack) { super.setInventorySlotContents(slotId, itemstack); this.randomRotation = worldObj.rand.nextFloat() * 360; sendUpdate(); } /** * Get the random rotation for displaying the item. * @return The random rotation. */ public float getRandomRotation() { return randomRotation; } }
package org.openhab.binding.heos.internal.resources; /** * The {@link HeosConstants} provides the constants used within the HEOS * network * * @author Johannes Einig - Initial contribution */ public class HeosConstants { public static final String HEOS = "heos"; public static final String CONNECTION_LOST = "connection_lost"; public static final String CONNECTION_RESTORED = "connection_restored"; public static final String PID = "pid"; public static final String GID = "gid"; public static final String BROWSE = "browse"; public static final String GET_MUSIC_SOURCES = "get_music_sources"; // Event Results public static final String FAIL = "fail"; public static final String SUCCESS = "success"; public static final String TRUE = "true"; public static final String FALSE = "false"; public static final String COM_UNDER_PROCESS = "command under process"; // Event Types public static final String EVENTTYPE_SYSTEM = "system"; public static final String EVENTTYPE_EVENT = "event"; public static final String EVENTTYPE_THING = "thing"; public static final String EVENTTYPE_GROUP = "group"; public static final String EVENTTYPE_BROWSE = "browse"; public static final String EVENTTYPE_PLAYER = "player"; // Event Commands public static final String SING_IN = "sign_in"; public static final String USER_CHANGED = "user_changed"; public static final String GROUPS_CHANGED = "groups_changed"; public static final String PLAYER_VOLUME_CHANGED = "player_volume_changed"; public static final String PLAYER_QUEUE_CHANGED = "player_queue_changed"; public static final String PLAYER_STATE_CHANGED = "player_state_changed"; public static final String PLAYER_NOW_PLAYING_CHANGED = "player_now_playing_changed"; public static final String PLAYERS_CHANGED = "players_changed"; public static final String PLAYER_NOW_PLAYING_PROGRESS = "player_now_playing_progress"; public static final String SOURCES_CHANGED = "sources_changed"; // Browse Command public static final String FAVORIT_SID = "1028"; public static final String PLAYLISTS_SID = "1025"; public static final String INPUT_SID = "1027"; public static final String CID = "cid"; public static final String MID = "mid"; public static final String SID = "sid"; public static final String QID = "qid"; // State commands public static final String HEOS_VOLUME = "volume"; public static final String HEOS_MUTE = "mute"; public static final String HEOS_LEVEL = "level"; public static final String HEOS_STATE = "state"; public static final String HEOS_CUR_POS = "cur_pos"; public static final String HEOS_DURATION = "duration"; // Player commands public static final String GET_NOW_PLAYING_MEDIA = "get_now_playing_media"; public static final String GET_PLAYER_INFO = "get_player_info"; public static final String GET_PLAY_STATE = "get_play_state"; public static final String GET_VOLUME = "get_volume"; public static final String GET_MUTE = "get_mute"; public static final String GET_QUEUE = "get_queue"; public static final String SET_PLAY_STATE = "set_play_state"; public static final String SET_VOLUME = "set_volume"; }
package org.opentripplanner.analyst.cluster; import java.io.Serializable; /** * Superclass for requests sent to an SPTWorker. * Not abstract, so we can bind JSON to it and discover the subclass to re-parse. * @author matthewc * */ public class AnalystClusterRequest implements Serializable { /** The ID of the destinations pointset */ public String destinationPointsetId; /** The ID of the graph against which to calculate this request */ public String graphId; /** The job ID this is associated with */ public String jobId; /** The id of this particular origin */ public String id; /** To where should the result be POSTed */ public String directOutputUrl; /** * To what queue should the notification of the result be delivered? */ public String outputQueue; /** * Where should the job be saved? */ public String outputLocation; /** Should times be included in the results (i.e. ResultSetWithTimes rather than ResultSet) */ public boolean includeTimes = false; /** Is this a profile request? */ public boolean profile; public AnalystClusterRequest(String destinationPointsetId, String graphId, boolean profile) { this.destinationPointsetId = destinationPointsetId; this.graphId = graphId; this.profile = profile; } /** used for deserialization from JSON */ public AnalystClusterRequest () { /* do nothing */ } }
package org.sagebionetworks.web.server.servlet.filter; import static org.apache.commons.lang.StringEscapeUtils.escapeHtml; import static org.sagebionetworks.repo.model.EntityBundle.ANNOTATIONS; import static org.sagebionetworks.repo.model.EntityBundle.ENTITY; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.zip.GZIPInputStream; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.jsoup.Jsoup; import org.sagebionetworks.markdown.SynapseMarkdownProcessor; import org.sagebionetworks.repo.model.Annotations; import org.sagebionetworks.repo.model.Entity; import org.sagebionetworks.repo.model.EntityBundle; import org.sagebionetworks.repo.model.EntityChildrenRequest; import org.sagebionetworks.repo.model.EntityChildrenResponse; import org.sagebionetworks.repo.model.EntityHeader; import org.sagebionetworks.repo.model.EntityType; import org.sagebionetworks.repo.model.ObjectType; import org.sagebionetworks.repo.model.Project; import org.sagebionetworks.repo.model.Team; import org.sagebionetworks.repo.model.UserProfile; import org.sagebionetworks.repo.model.discussion.DiscussionFilter; import org.sagebionetworks.repo.model.discussion.DiscussionReplyBundle; import org.sagebionetworks.repo.model.discussion.DiscussionReplyOrder; import org.sagebionetworks.repo.model.discussion.DiscussionThreadBundle; import org.sagebionetworks.repo.model.discussion.DiscussionThreadOrder; import org.sagebionetworks.repo.model.discussion.Forum; import org.sagebionetworks.repo.model.search.Hit; import org.sagebionetworks.repo.model.search.SearchResults; import org.sagebionetworks.repo.model.search.query.SearchQuery; import org.sagebionetworks.repo.model.wiki.WikiPage; import org.sagebionetworks.schema.adapter.JSONObjectAdapter; import org.sagebionetworks.schema.adapter.JSONObjectAdapterException; import org.sagebionetworks.schema.adapter.org.json.EntityFactory; import org.sagebionetworks.schema.adapter.org.json.JSONObjectAdapterImpl; import org.sagebionetworks.web.client.DisplayConstants; import org.sagebionetworks.web.client.place.TeamSearch; import org.sagebionetworks.web.server.servlet.DiscussionForumClientImpl; import org.sagebionetworks.web.server.servlet.ServiceUrlProvider; import org.sagebionetworks.web.server.servlet.SynapseClientImpl; import org.sagebionetworks.web.shared.PaginatedResults; import org.sagebionetworks.web.shared.SearchQueryUtils; import org.sagebionetworks.web.shared.TeamMemberBundle; import org.sagebionetworks.web.shared.TeamMemberPagedResults; import org.sagebionetworks.web.shared.WebConstants; import org.sagebionetworks.web.shared.WikiPageKey; import org.sagebionetworks.web.shared.exceptions.RestServiceException; import com.google.gwt.thirdparty.guava.common.base.Supplier; import com.google.gwt.thirdparty.guava.common.base.Suppliers; /** * This filter detects ajax crawler (Google). If so, it takes over the renders the javascript page and handles the response. * */ public class CrawlFilter implements Filter { private static final String DISCUSSION_THREAD_ID = "/discussion/threadId="; public static final String ESCAPED_FRAGMENT = "_escaped_fragment_="; ServletContext sc; private final Supplier<String> homePageCached = Suppliers.memoizeWithExpiration(homePageSupplier(), 1, TimeUnit.DAYS); public static final int MAX_CHILD_PAGES = 5; public String getCachedHomePageHtml() { return homePageCached.get(); } private Supplier<String> homePageSupplier() { return new Supplier<String>() { public String get() { try { return getHomePageHtml(); } catch (JSONObjectAdapterException | RestServiceException e) { return e.getMessage(); } } }; } /** * Injected with Gin */ private SynapseClientImpl synapseClient; private DiscussionForumClientImpl discussionForumClient; JSONObjectAdapter jsonObjectAdapter; @Override public void destroy() { sc = null; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRqst = (HttpServletRequest) request; // Is this an ugly url that we need to convert/handle? String queryString = httpRqst.getQueryString(); if (queryString != null && queryString.contains(ESCAPED_FRAGMENT)) { try { String uri = httpRqst.getRequestURI(); int port = request.getServerPort(); String domain = request.getServerName(); String lowerCaseDomain = domain.toLowerCase(); if (!(lowerCaseDomain.contains("www.synapse.org") || lowerCaseDomain.contains("127.0.0.1"))) { response.setContentType("text/html"); HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.setStatus(HttpServletResponse.SC_OK); PrintWriter out = httpResponse.getWriter(); out.println("Synapse test site - " + domain); return; } String scheme = request.getScheme(); //build an html page for this request String html = ""; String fixedQueryString = uri + rewriteQueryString(queryString); if (fixedQueryString.contains("#!Home")) { //send back info about the site html = getCachedHomePageHtml(); } else if (fixedQueryString.contains("#!Synapse")) { if (fixedQueryString.contains(DISCUSSION_THREAD_ID)) { String threadId = fixedQueryString.substring(fixedQueryString.indexOf(DISCUSSION_THREAD_ID)+DISCUSSION_THREAD_ID.length()); html=getThreadHtml(threadId); } else { //index information about the synapse entity String entityId = fixedQueryString.substring(fixedQueryString.indexOf(":",fixedQueryString.indexOf("#!"))+1); html=getEntityHtml(entityId); } } else if (fixedQueryString.contains("#!Search")) { //index all projects String searchQueryJson = fixedQueryString.substring(fixedQueryString.indexOf(":",fixedQueryString.indexOf("#!"))+1); html=getAllProjectsHtml(URLDecoder.decode(searchQueryJson)); } else if (fixedQueryString.contains("#!TeamSearch")) { //index all teams String startIndex = fixedQueryString.substring(fixedQueryString.indexOf(TeamSearch.START_DELIMITER,fixedQueryString.indexOf("#!"))+TeamSearch.START_DELIMITER.length()); html=getAllTeamsHtml(startIndex); } else if (fixedQueryString.contains("#!Team")) { //index team (including members) String teamId = fixedQueryString.substring(fixedQueryString.indexOf(":",fixedQueryString.indexOf("#!"))+1); html=getTeamHtml(teamId); } else if (fixedQueryString.contains("#!Profile")) { //index team (including members) String profileId = fixedQueryString.substring(fixedQueryString.indexOf(":",fixedQueryString.indexOf("#!"))+1); html=getProfileHtml(profileId); } URL url = new URL(scheme, domain, port, fixedQueryString); //replace all relative links with full links due to this Google AJAX crawler support chicken-dance String originalUrl = url.toString(); String toPage = originalUrl.substring(0, originalUrl.indexOf(" String replacedWithFullHrefs = html.replace("href=\"#", "href=\""+toPage); response.setContentType("text/html"); HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.setStatus(HttpServletResponse.SC_OK); PrintWriter out = httpResponse.getWriter(); out.println(replacedWithFullHrefs); } catch (Exception e) { e.printStackTrace(); } } else { chain.doFilter(request, response); } } private String getHomePageHtml() throws JSONObjectAdapterException, RestServiceException{ StringBuilder html = new StringBuilder(); html.append("<!DOCTYPE html><html><head><title>"+DisplayConstants.DEFAULT_PAGE_TITLE+"</title><meta name=\"description\" content=\""+DisplayConstants.DEFAULT_PAGE_DESCRIPTION+"\" /></head><body>"); //add direct links to all public projects in the system SearchQuery query = SearchQueryUtils.getDefaultSearchQuery(); html.append("<h1>"+DisplayConstants.DEFAULT_PAGE_TITLE+"</h1>" + DisplayConstants.DEFAULT_PAGE_DESCRIPTION + "<br />"); //add link to team search html.append("<h3><a href=\"https: SearchResults results = synapseClient.search(query); //append this set to the list while(results.getHits().size() > 0) { for (Hit hit : results.getHits()) { //add links html.append("<a href=\"https: } long newStart = results.getStart() + results.getHits().size(); query.setStart(newStart); results = synapseClient.search(query); } html.append("</body></html>"); return html.toString(); } private String getCreatedByString(String userId) throws RestServiceException { UserProfile profile = synapseClient.getUserProfile(userId); return getUserProfileString(profile); } private String getUserProfileString(UserProfile profile) { StringBuilder createdByBuilder = new StringBuilder(); createdByBuilder.append("<a href=\"https: if (profile.getFirstName() != null) { createdByBuilder.append(profile.getFirstName() + " "); } if (profile.getLastName() != null) { createdByBuilder.append(profile.getLastName() + " "); } createdByBuilder.append(profile.getUserName()); createdByBuilder.append("</a>"); return createdByBuilder.toString(); } private String getEntityHtml(String entityId) throws RestServiceException, JSONObjectAdapterException{ int mask = ENTITY | ANNOTATIONS; EntityBundle bundle = synapseClient.getEntityBundle(entityId, mask); Entity entity = bundle.getEntity(); Annotations annotations = bundle.getAnnotations(); String name = escapeHtml(entity.getName()); String description = escapeHtml(entity.getDescription()); String markdown = null; String createdBy = null; try{ createdBy = getCreatedByString(entity.getCreatedBy()); } catch (Exception e) {} try{ WikiPage rootPage = synapseClient.getV2WikiPageAsV1(new WikiPageKey(entity.getId(), ObjectType.ENTITY.toString(), null)); markdown = escapeHtml(rootPage.getMarkdown()); } catch (Exception e) {} StringBuilder html = new StringBuilder(); //note: can't set description meta tag, since it might be markdown. html.append("<!DOCTYPE html><html><head><title>"+name +" - "+ entity.getId()+"</title></head><body>"); html.append("<h1>"+name+"</h1>"); if (description != null) { html.append(description + "<br />"); } if (createdBy != null) { html.append("Created By " + createdBy + "<br />"); } if (markdown != null) { try { String wikiHtml = SynapseMarkdownProcessor.getInstance().markdown2Html(markdown, "", ""); //extract plain text from wiki html markdown = Jsoup.parse(wikiHtml).text(); } catch (IOException e) { } html.append(markdown + "<br />"); } html.append("<br />"); for (String key : annotations.getStringAnnotations().keySet()) { List<String> value = annotations.getStringAnnotations().get(key); html.append(escapeHtml(key) + escapeHtml(getValueString(value)) + "<br />"); } for (String key : annotations.getLongAnnotations().keySet()) { List<Long> value = annotations.getLongAnnotations().get(key); html.append(escapeHtml(key) + escapeHtml(getValueString(value)) + "<br />"); } for (String key : annotations.getDoubleAnnotations().keySet()) { List<Double> value = annotations.getDoubleAnnotations().get(key); html.append(escapeHtml(key) + escapeHtml(getValueString(value)) + "<br />"); } //and link to the discussion forum (all threads and replies) if this is a project. if (entity instanceof Project) { Forum forum = discussionForumClient.getForumByProjectId(entity.getId()); if (forum != null) { String forumId = forum.getId(); long currentOffset = 0; PaginatedResults<DiscussionThreadBundle> paginatedThreads; do { paginatedThreads = discussionForumClient.getThreadsForForum(forumId, 20L, currentOffset, DiscussionThreadOrder.PINNED_AND_LAST_ACTIVITY, false, DiscussionFilter.EXCLUDE_DELETED); List<DiscussionThreadBundle> threadList = paginatedThreads.getResults(); for (DiscussionThreadBundle thread : threadList) { html.append("<a href=\"https: } currentOffset += 20; } while (!paginatedThreads.getResults().isEmpty()); } } //and ask for all children // only show the first few pages. EntityChildrenRequest request = createGetChildrenQuery(entityId); EntityChildrenResponse childList; int i = 0; do { childList = synapseClient.getEntityChildren(request); for (EntityHeader childId : childList.getPage()) { html.append("<a href=\"https: } request.setNextPageToken(childList.getNextPageToken()); i++; } while (i < MAX_CHILD_PAGES && childList.getNextPageToken() != null); html.append("</body></html>"); return html.toString(); } private String getThreadHtml(String threadId) throws JSONObjectAdapterException, RestServiceException, IOException { StringBuilder html = new StringBuilder(); DiscussionThreadBundle thread = discussionForumClient .getThread(threadId); html.append("<!DOCTYPE html><html><head><title>" + thread.getTitle() + "</title></head><body>"); html.append("<h1>" + thread.getTitle() + "</h1>"); try { String url = discussionForumClient.getThreadUrl(thread .getMessageKey()); html.append("<h4>" + getURLContents(url) + "</h4>"); } catch (Exception e1) {} String createdBy = null; try { createdBy = getCreatedByString(thread.getCreatedBy()); } catch (Exception e) { } html.append("Created by " + createdBy + "<br>"); PaginatedResults<DiscussionReplyBundle> replies = discussionForumClient .getRepliesForThread(thread.getId(), 100L, 0L, DiscussionReplyOrder.CREATED_ON, false, DiscussionFilter.EXCLUDE_DELETED); for (DiscussionReplyBundle reply : replies.getResults()) { try { String replyURL = discussionForumClient.getReplyUrl(reply .getMessageKey()); html.append(getURLContents(replyURL) + "<br>"); } catch (Exception e) {} } html.append("</body></html>"); return html.toString(); } private String getTeamHtml(String teamId) throws JSONObjectAdapterException, RestServiceException, IOException { StringBuilder html = new StringBuilder(); Team team = synapseClient.getTeam(teamId); html.append("<!DOCTYPE html><html><head><title>" + team.getName() + "</title></head><body>"); html.append("<h1>" + team.getName() + "</h1>"); if (team.getDescription() != null) { html.append("<h3>" + team.getDescription() + "</h3>"); } TeamMemberPagedResults teamMembers = synapseClient.getTeamMembers(team.getId(), "", 20, 0); for (TeamMemberBundle teamMember : teamMembers.getResults()) { try { html.append(getUserProfileString(teamMember.getUserProfile()) + "<br>"); } catch (Exception e) {} } html.append("</body></html>"); return html.toString(); } private String getProfileHtml(String profileId) throws JSONObjectAdapterException, RestServiceException, IOException { StringBuilder html = new StringBuilder(); UserProfile profile = synapseClient.getUserProfile(profileId); String display = profile.getFirstName() + " " + profile.getLastName() + " " + profile.getUserName(); html.append("<!DOCTYPE html><html><head><title>" + display + "</title></head><body>"); html.append("<h1>" + display + "</h1>"); if (profile.getSummary() != null) { html.append("<h4>" + profile.getSummary() + "</h4>"); } if (profile.getLocation() != null) { html.append("<p>" + profile.getLocation() + "</p>"); } if (profile.getPosition() != null) { html.append("<p>" + profile.getPosition() + "</p>"); } if (profile.getIndustry() != null) { html.append("<p>" + profile.getIndustry() + "</p>"); } if (profile.getCompany() != null) { html.append("<p>" + profile.getCompany() + "</p>"); } html.append("</body></html>"); return html.toString(); } private String getURLContents(String urlTarget) throws IOException { URL url = new URL(urlTarget); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); try { conn.setRequestProperty(WebConstants.CONTENT_TYPE, WebConstants.TEXT_PLAIN_CHARSET_UTF8); InputStream in = new GZIPInputStream(conn.getInputStream()); try { return IOUtils.toString(in, "UTF-8"); } finally { IOUtils.closeQuietly(in); } } finally { conn.disconnect(); } } private String getValueString(List value) { StringBuilder valueBuilder = new StringBuilder(); if (value != null) { valueBuilder.append(": "); for (Object object : value) { if (object != null) valueBuilder.append(object.toString() + " "); } } return valueBuilder.toString(); } private String getAllProjectsHtml(String searchQueryJson) throws RestServiceException, JSONObjectAdapterException{ SearchQuery inputQuery = EntityFactory.createEntityFromJSONString(searchQueryJson, SearchQuery.class); SearchResults results = synapseClient.search(inputQuery); //append this set to the list StringBuilder html = new StringBuilder(); html.append("<!DOCTYPE html><html><head><title>Sage Synapse: All Projects - starting from "+inputQuery.getStart()+"</title><meta name=\"description\" content=\"\" /></head><body>"); for (Hit hit : results.getHits()) { //add links html.append("<a href=\"https: } //add another link for the next page of results long newStart = results.getStart() + results.getHits().size(); inputQuery.setStart(newStart); String newJson = EntityFactory.createJSONStringForEntity(inputQuery); html.append("<a href=\"https: html.append("</body></html>"); return html.toString(); } private String getAllTeamsHtml(String startIndex) throws RestServiceException{ int start = Integer.parseInt(startIndex); PaginatedResults<Team> teams = synapseClient.getTeamsBySearch("", 50, start); //append this set to the list StringBuilder html = new StringBuilder(); html.append("<!DOCTYPE html><html><head><title>Sage Synapse: All Teams - from "+startIndex+"</title><meta name=\"description\" content=\"\" /></head><body>"); for (Team team : teams.getResults()) { //add links html.append("<a href=\"https: } //add another link for the next page of results long newStart = start + teams.getResults().size(); html.append("<h4><a href=\"https: html.append("</body></html>"); return html.toString(); } public String rewriteQueryString(String uglyUrl) { try { String decoded = URLDecoder.decode(uglyUrl, "UTF-8"); // dev mode String result = decoded.replace("gwt", "?gwt"); result = result.replace("&"+ESCAPED_FRAGMENT, "#!"); result = result.replace("?"+ESCAPED_FRAGMENT, "#!"); result = result.replace(ESCAPED_FRAGMENT, "#!"); return result; } catch (UnsupportedEncodingException e) { return ""; } } public EntityChildrenRequest createGetChildrenQuery(String parentId) { EntityChildrenRequest newQuery = new EntityChildrenRequest(); newQuery.setParentId(parentId); List<EntityType> types = new ArrayList<EntityType>(); types.add(EntityType.file); types.add(EntityType.folder); newQuery.setIncludeTypes(types); return newQuery; } @Override public void init(FilterConfig config) throws ServletException { this.sc = config.getServletContext(); synapseClient = new SynapseClientImpl(); ServiceUrlProvider urlProvider = new ServiceUrlProvider(); synapseClient.setServiceUrlProvider(urlProvider); discussionForumClient = new DiscussionForumClientImpl(); discussionForumClient.setServiceUrlProvider(urlProvider); jsonObjectAdapter = new JSONObjectAdapterImpl(); } }
package org.segator.plex.cloud.transcoding.entity; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Objects; /** * * @author isaac_000 */ public class PlexUserSession { @JsonProperty("Accept-Language") private String acceptLanguage; private String subtitles; @JsonProperty("X-Plex-Chunked") private Integer plexChunked; @JsonProperty("X-Plex-Username") private String plexUsername; @JsonProperty("X-Plex-Device-Name") private String plexDeviceName; @JsonProperty("X-Plex-Platform-Version") private Double plexPlatformVersion; @JsonProperty("X-Plex-Client-Profile-Extra") private String plexClientProfileExtra; @JsonProperty("session") private String session; @JsonProperty("X-Plex-Product") private String plexProduct; private Integer mediaIndex; private Double maxVideoBitrate; private Double videoQuality; private String videoResolution; private Integer fastSeek; private Integer directPlay; @JsonProperty("X-Plex-Device") private String plexDevice; private String protocol; private Integer copyts; private Integer partIndex; private Integer audioBoost; private String path; @JsonProperty("X-Plex-Client-Identifier") private String plexClientIdentifier; private Double offset; @JsonProperty("X-Plex-Platform") private String plexPlatform; @JsonProperty("X-Plex-Version") private String plexVersion; @JsonProperty("X-Plex-Token") private String plexToken; private Integer directStream; private Integer subtitleSize; public String getAcceptLanguage() { return acceptLanguage; } public void setAcceptLanguage(String acceptLanguage) { this.acceptLanguage = acceptLanguage; } public String getSubtitles() { return subtitles; } public void setSubtitles(String subtitles) { this.subtitles = subtitles; } public Integer getPlexChunked() { return plexChunked; } public void setPlexChunked(Integer plexChunked) { this.plexChunked = plexChunked; } public String getPlexClientProfileExtra() { return plexClientProfileExtra; } public void setPlexClientProfileExtra(String plexClientProfileExtra) { this.plexClientProfileExtra = plexClientProfileExtra; } public String getPlexDeviceName() { return plexDeviceName; } public void setPlexDeviceName(String plexDeviceName) { this.plexDeviceName = plexDeviceName; } public Double getPlexPlatformVersion() { return plexPlatformVersion; } public void setPlexPlatformVersion(Double plexPlatformVersion) { this.plexPlatformVersion = plexPlatformVersion; } public String getSession() { return session; } public void setSession(String session) { this.session = session; } public String getPlexProduct() { return plexProduct; } public void setPlexProduct(String plexProduct) { this.plexProduct = plexProduct; } public Double getMaxVideoBitrate() { return maxVideoBitrate; } public void setMaxVideoBitrate(Double maxVideoBitrate) { this.maxVideoBitrate = maxVideoBitrate; } public String getPlexUsername() { return plexUsername; } public void setPlexUsername(String plexUsername) { this.plexUsername = plexUsername; } public Double getVideoQuality() { return videoQuality; } public void setVideoQuality(Double videoQuality) { this.videoQuality = videoQuality; } public String getVideoResolution() { return videoResolution; } public void setVideoResolution(String videoResolution) { this.videoResolution = videoResolution; } public Integer getMediaIndex() { return mediaIndex; } public void setMediaIndex(Integer mediaIndex) { this.mediaIndex = mediaIndex; } public Integer getFastSeek() { return fastSeek; } public void setFastSeek(Integer fastSeek) { this.fastSeek = fastSeek; } public Integer getDirectPlay() { return directPlay; } public void setDirectPlay(Integer directPlay) { this.directPlay = directPlay; } public String getPlexDevice() { return plexDevice; } public void setPlexDevice(String plexDevice) { this.plexDevice = plexDevice; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public Integer getCopyts() { return copyts; } public void setCopyts(Integer copyts) { this.copyts = copyts; } public Integer getPartIndex() { return partIndex; } public void setPartIndex(Integer partIndex) { this.partIndex = partIndex; } public Integer getAudioBoost() { return audioBoost; } public void setAudioBoost(Integer audioBoost) { this.audioBoost = audioBoost; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getPlexClientIdentifier() { return plexClientIdentifier; } public void setPlexClientIdentifier(String plexClientIdentifier) { this.plexClientIdentifier = plexClientIdentifier; } public Double getOffset() { return offset; } public void setOffset(Double offset) { this.offset = offset; } public String getPlexPlatform() { return plexPlatform; } public void setPlexPlatform(String plexPlatform) { this.plexPlatform = plexPlatform; } public String getPlexVersion() { return plexVersion; } public void setPlexVersion(String plexVersion) { this.plexVersion = plexVersion; } public String getPlexToken() { return plexToken; } public void setPlexToken(String plexToken) { this.plexToken = plexToken; } public Integer getDirectStream() { return directStream; } public void setDirectStream(Integer directStream) { this.directStream = directStream; } public Integer getSubtitleSize() { return subtitleSize; } public void setSubtitleSize(Integer subtitleSize) { this.subtitleSize = subtitleSize; } @Override public int hashCode() { int hash = 5; hash = 53 * hash + Objects.hashCode(this.plexToken); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final PlexUserSession other = (PlexUserSession) obj; if (!Objects.equals(this.plexToken, other.plexToken)) { return false; } return true; } @Override public String toString() { return "PlexUserSession{" + "acceptLanguage=" + acceptLanguage + ", subtitles=" + subtitles + ", plexChunked=" + plexChunked + ", plexDeviceName=" + plexDeviceName + ", plexPlatformVersion=" + plexPlatformVersion + ", session=" + session + ", plexProduct=" + plexProduct + ", mediaIndex=" + mediaIndex + ", fastSeek=" + fastSeek + ", directPlay=" + directPlay + ", plexDevice=" + plexDevice + ", protocol=" + protocol + ", copyts=" + copyts + ", partIndex=" + partIndex + ", audioBoost=" + audioBoost + ", path=" + path + ", plexClientIdentifier=" + plexClientIdentifier + ", offset=" + offset + ", plexPlatform=" + plexPlatform + ", plexVersion=" + plexVersion + ", plexToken=" + plexToken + ", directStream=" + directStream + ", subtitleSize=" + subtitleSize + '}'; } }
package org.springframework.social.evernote.api; /** * @author Tadaya Tsuyukubo */ public interface StoreClientHolder { <T> T getStoreClient(); }
package org.supercsv.ext.builder.impl; import java.lang.annotation.Annotation; import org.supercsv.cellprocessor.FmtBool; import org.supercsv.cellprocessor.ift.BoolCellProcessor; import org.supercsv.cellprocessor.ift.CellProcessor; import org.supercsv.cellprocessor.ift.StringCellProcessor; import org.supercsv.ext.annotation.CsvBooleanConverter; import org.supercsv.ext.annotation.CsvColumn; import org.supercsv.ext.builder.AbstractCellProcessorBuilder; import org.supercsv.ext.cellprocessor.ParseBoolean; import org.supercsv.ext.exception.SuperCsvInvalidAnnotationException; /** * * @version 1.2 * @author T.TSUCHIE * */ public class BooleanCellProcessorBuilder extends AbstractCellProcessorBuilder<Boolean> { @Override protected CellProcessor buildInputCellProcessorWithConvertNullTo(final Class<Boolean> type, final Annotation[] annos, final CellProcessor cellProcessor, final CsvColumn csvColumnAnno) { // false if(type.isPrimitive() && csvColumnAnno.optional() && csvColumnAnno.inputDefaultValue().isEmpty()) { return prependConvertNullToProcessor(type, cellProcessor, false); } else if(!csvColumnAnno.inputDefaultValue().isEmpty()) { return prependConvertNullToProcessor(type, cellProcessor, getParseValue(type, annos, csvColumnAnno.inputDefaultValue())); } return cellProcessor; } protected CsvBooleanConverter getAnnotation(final Annotation[] annos) { for(Annotation anno : annos) { if(anno instanceof CsvBooleanConverter) { return (CsvBooleanConverter) anno; } } return null; } protected String getOutputTrueValue(final CsvBooleanConverter converterAnno) { if(converterAnno == null) { return "true"; } return converterAnno.outputTrueValue(); } protected String getOutputFalseValue(final CsvBooleanConverter converterAnno) { if(converterAnno == null) { return "false"; } return converterAnno.outputFalseValue(); } protected String[] getInputTrueValue(final CsvBooleanConverter converterAnno) { if(converterAnno == null) { return new String[]{"true", "1", "yes", "on", "y", "t"}; } return converterAnno.inputTrueValue(); } protected String[] getInputFalseValue(final CsvBooleanConverter converterAnno) { if(converterAnno == null) { return new String[]{"false", "0", "no", "off", "f", "n"}; } return converterAnno.inputFalseValue(); } protected boolean getIgnoreCase(final CsvBooleanConverter converterAnno) { if(converterAnno == null) { return false; } return converterAnno.ignoreCase(); } protected boolean getFailToFalse(final CsvBooleanConverter converterAnno) { if(converterAnno == null) { return false; } return converterAnno.failToFalse(); } @Override public CellProcessor buildOutputCellProcessor(final Class<Boolean> type, final Annotation[] annos, final CellProcessor processor, final boolean ignoreValidationProcessor) { final CsvBooleanConverter converterAnno = getAnnotation(annos); final String trueValue = getOutputTrueValue(converterAnno); final String falseValue = getOutputFalseValue(converterAnno); CellProcessor cp = processor; cp = (cp == null ? new FmtBool(trueValue, falseValue) : new FmtBool(trueValue, falseValue, (StringCellProcessor) cp)); return cp; } @Override public CellProcessor buildInputCellProcessor(final Class<Boolean> type, final Annotation[] annos, final CellProcessor processor) { final CsvBooleanConverter converterAnno = getAnnotation(annos); final String[] trueValue = getInputTrueValue(converterAnno); final String[] falseValue = getInputFalseValue(converterAnno); final boolean ignoreCase = getIgnoreCase(converterAnno); final boolean failToFalse = getFailToFalse(converterAnno); CellProcessor cp = processor; cp = (cp == null ? new ParseBoolean(trueValue, falseValue, ignoreCase).setFailToFalse(failToFalse) : new ParseBoolean(trueValue, falseValue, ignoreCase, (BoolCellProcessor) cp).setFailToFalse(failToFalse)); return cp; } @Override public Boolean getParseValue(final Class<Boolean> type, final Annotation[] annos, final String strValue) { final CsvBooleanConverter converterAnno = getAnnotation(annos); final String[] trueValue = getInputTrueValue(converterAnno); final String[] falseValue = getInputFalseValue(converterAnno); final boolean ignoreCase = getIgnoreCase(converterAnno); final boolean failToFalse = getFailToFalse(converterAnno); for(String trueStr : trueValue) { if(ignoreCase && trueStr.equalsIgnoreCase(strValue)) { return Boolean.TRUE; } else if(!ignoreCase && trueStr.equals(strValue)) { return Boolean.TRUE; } } for(String falseStr : falseValue) { if(ignoreCase && falseStr.equalsIgnoreCase(strValue)) { return Boolean.FALSE; } else if(!ignoreCase && falseStr.equals(strValue)) { return Boolean.FALSE; } } if(failToFalse) { return Boolean.FALSE; } throw new SuperCsvInvalidAnnotationException(String.format("defaultValue '%s' cannot parse.", strValue)); } }
package org.zalando.nakadi.service.subscription.zk; import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.zalando.nakadi.exceptions.NakadiRuntimeException; import java.util.concurrent.atomic.AtomicBoolean; public abstract class ChangeListener implements ZKSubscription, Watcher { protected final CuratorFramework curatorFramework; protected final String key; private final Runnable listener; private final AtomicBoolean cancelled = new AtomicBoolean(); private final AtomicBoolean registered = new AtomicBoolean(); protected ChangeListener(final CuratorFramework curatorFramework, final String key, final Runnable listener) { this.curatorFramework = curatorFramework; this.key = key; this.listener = listener; refresh(); } @Override public void process(final WatchedEvent event) { registered.set(false); if (!cancelled.get()) { listener.run(); } } protected abstract void setInternal() throws Exception; @Override public void refresh() { if (!cancelled.get() && !registered.get()) { try { registered.set(true); setInternal(); } catch (final Exception e) { throw new NakadiRuntimeException(e); } } } @Override public void cancel() { this.cancelled.set(true); } public static ChangeListener forChildren( final CuratorFramework curatorFramework, final String key, final Runnable listener) { return new ChildrenListener(curatorFramework, key, listener); } public static ChangeListener forData( final CuratorFramework curatorFramework, final String key, final Runnable listener) { return new ValueListener(curatorFramework, key, listener); } private static class ChildrenListener extends ChangeListener { ChildrenListener(final CuratorFramework curatorFramework, final String key, final Runnable listener) { super(curatorFramework, key, listener); } @Override protected void setInternal() throws Exception { curatorFramework.getChildren().usingWatcher(this).forPath(key); } } private static class ValueListener extends ChangeListener { ValueListener(final CuratorFramework curatorFramework, final String key, final Runnable listener) { super(curatorFramework, key, listener); } @Override protected void setInternal() throws Exception { curatorFramework.getData().usingWatcher(this).forPath(key); } } }
package permafrost.tundra.server; import java.util.concurrent.SynchronousQueue; import com.wm.app.b2b.server.InvokeState; import permafrost.tundra.util.concurrent.BlockingRejectedExecutionHandler; /** * A Integration Server ThreadPoolExecutor which blocks on submit when all threads are busy. */ public class BlockingServerThreadPoolExecutor extends ServerThreadPoolExecutor { /** * Creates a new BlockingServerThreadPoolExecutor. * * @param threadPoolSize The number of threads to allocate to the pool. */ public BlockingServerThreadPoolExecutor(int threadPoolSize) { this(threadPoolSize, "Tundra"); } /** * Creates a new BlockingServerThreadPoolExecutor. * * @param threadPoolSize The number of threads to allocate to the pool. * @param threadNamePrefix The prefix to use on all created thread names. */ public BlockingServerThreadPoolExecutor(int threadPoolSize, String threadNamePrefix) { this(threadPoolSize, threadNamePrefix, Thread.NORM_PRIORITY); } /** * Creates a new BlockingServerThreadPoolExecutor. * * @param threadPoolSize The number of threads to allocate to the pool. * @param threadNamePrefix The prefix to use on all created thread names. * @param threadPriority The priority each created thread will have. */ public BlockingServerThreadPoolExecutor(int threadPoolSize, String threadNamePrefix, int threadPriority) { this(threadPoolSize, threadNamePrefix, threadPriority, false); } /** * Creates a new BlockingServerThreadPoolExecutor. * * @param threadPoolSize The number of threads to allocate to the pool. * @param threadNamePrefix The prefix to use on all created thread names. * @param threadPriority The priority each created thread will have. * @param threadDaemon Whether the created threads should be daemons. */ public BlockingServerThreadPoolExecutor(int threadPoolSize, String threadNamePrefix, int threadPriority, boolean threadDaemon) { this(threadPoolSize, threadNamePrefix, null, threadPriority, threadDaemon); } /** * Creates a new BlockingServerThreadPoolExecutor. * * @param threadPoolSize The number of threads to allocate to the pool. * @param threadNamePrefix The prefix to use on all created thread names. * @param threadNameSuffix The suffix used on all created thread names. * @param threadPriority The priority each created thread will have. * @param threadDaemon Whether the created threads should be daemons. */ public BlockingServerThreadPoolExecutor(int threadPoolSize, String threadNamePrefix, String threadNameSuffix, int threadPriority, boolean threadDaemon) { this(threadPoolSize, threadNamePrefix, threadNameSuffix, threadPriority, threadDaemon, InvokeState.getCurrentState()); } /** * Creates a new BlockingServerThreadPoolExecutor. * * @param threadPoolSize The number of threads to allocate to the pool. * @param threadNamePrefix The prefix to use on all created thread names. * @param threadNameSuffix The suffix used on all created thread names. * @param threadPriority The priority each created thread will have. * @param threadDaemon Whether the created threads should be daemons. * @param invokeState The invoke state to clone for each thread created. */ public BlockingServerThreadPoolExecutor(int threadPoolSize, String threadNamePrefix, String threadNameSuffix, int threadPriority, boolean threadDaemon, InvokeState invokeState) { super(threadPoolSize, threadNamePrefix, threadNameSuffix, threadPriority, threadDaemon, invokeState, new SynchronousQueue<Runnable>(true), new BlockingRejectedExecutionHandler()); } }
package red.sukun1899.shishamo.embedded.mysql; import com.wix.mysql.config.Charset; import com.wix.mysql.distribution.Version; import static com.wix.mysql.config.Charset.LATIN1; import static com.wix.mysql.config.Charset.UTF8; import static com.wix.mysql.config.Charset.UTF8MB4; /** * @author su-kun1899 */ public class EmbeddedMySqlConfig { private boolean enable; private int port; private Version version; private String username; private String password; private String schemaName; private String charset; public EmbeddedMySqlConfig() { this.port = 3306; this.version = Version.v5_7_latest; this.username = "root"; this.schemaName = "test"; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public Version getVersion() { return version; } public void setVersion(Version version) { this.version = version; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSchemaName() { return schemaName; } public void setSchemaName(String schemaName) { this.schemaName = schemaName; } public Charset getWixCharset() { if (getCharset().equalsIgnoreCase(UTF8.getCharset())) { return UTF8; } else if (getCharset().equalsIgnoreCase(UTF8MB4.getCharset())) { return UTF8MB4; } else if (getCharset().equalsIgnoreCase(LATIN1.getCharset())) { return LATIN1; } else { // default return UTF8; } } public String getCharset() { return charset; } public void setCharset(String charset) { this.charset = charset; } public boolean isEnable() { return enable; } public void setEnable(boolean enable) { this.enable = enable; } }
package team.creative.creativecore.common.util.type.list; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.function.Predicate; import javax.annotation.Nullable; import com.google.common.collect.ImmutableList; public class PairList<K, V> extends ArrayList<Pair<K, V>> { public PairList() { super(); } public PairList(List<Pair<K, V>> list) { super(list); updateEntireMap(); } protected HashMap<K, Integer> keyIndex = new LinkedHashMap<>(); protected List<V> values = new ArrayList<>(); protected void updateEntireMap() { keyIndex.clear(); values.clear(); for (int i = 0; i < size(); i++) { keyIndex.put(this.get(i).key, i); values.add(this.get(i).value); } } @Override public boolean add(Pair<K, V> e) { Objects.requireNonNull(e); if (keyIndex.containsKey(e.key)) throw new IllegalArgumentException("Duplicates are not allowed key: " + e.key); if (super.add(e)) { keyIndex.put(e.key, size() - 1); values.add(e.value); return true; } return false; } @Override public void add(int index, Pair<K, V> element) { Objects.requireNonNull(element); if (keyIndex.containsKey(element.key)) throw new IllegalArgumentException("Duplicates are not allowed key: " + element.key); super.add(index, element); updateEntireMap(); } @Override public boolean addAll(Collection<? extends Pair<K, V>> c) { Objects.requireNonNull(c); for (Pair<K, V> pair : c) { Objects.requireNonNull(pair); if (keyIndex.containsKey(pair.key)) throw new IllegalArgumentException("Duplicates are not allowed key: " + pair.key); } int sizeBefore = size(); if (super.addAll(c)) { for (int i = 0; i < c.size(); i++) { int index = sizeBefore + i; keyIndex.put(this.get(index).key, index); values.add(this.get(index).value); } return true; } return false; } @Override public boolean addAll(int index, Collection<? extends Pair<K, V>> c) { Objects.requireNonNull(c); for (Pair<K, V> pair : c) { Objects.requireNonNull(pair); if (keyIndex.containsKey(pair.key)) throw new IllegalArgumentException("Duplicates are not allowed key: " + pair.key); } if (super.addAll(index, c)) { updateEntireMap(); return true; } return false; } public boolean add(K key, V value) { return add(new Pair<>(key, value)); } public void set(K key, V value) { Pair<K, V> pair = getPair(key); if (pair != null) pair.value = value; } @Override public Pair<K, V> remove(int index) { Pair<K, V> pair; if ((pair = super.remove(index)) != null) { updateEntireMap(); return pair; } return null; } @Override public boolean remove(Object o) { if (super.remove(o)) { updateEntireMap(); return true; } return false; } @Override public boolean removeAll(Collection<?> c) { if (super.removeAll(c)) { updateEntireMap(); return true; } return false; } @Override public boolean removeIf(Predicate<? super Pair<K, V>> filter) { if (super.removeIf(filter)) { updateEntireMap(); return true; } return false; } @Override public boolean retainAll(Collection<?> c) { if (super.retainAll(c)) { updateEntireMap(); return true; } return false; } @Override public void clear() { super.clear(); keyIndex.clear(); values.clear(); } @Override public Pair<K, V> set(int index, Pair<K, V> element) { Objects.requireNonNull(element); Integer exisiting = keyIndex.get(element.key); if (exisiting != null && exisiting != index) throw new IllegalArgumentException("Duplicates are not allowed key: " + element.key); Pair<K, V> old = super.set(index, element); if (old != null) { keyIndex.remove(old.key); keyIndex.put(element.key, index); values.set(index, element.value); } return old; } @Override public void sort(Comparator<? super Pair<K, V>> c) { super.sort(c); updateEntireMap(); } public boolean containsKey(K key) { return keyIndex.containsKey(key); } public int indexOfKey(K key) { return keyIndex.getOrDefault(key, -1); } public boolean removeKey(K key) { Integer index = keyIndex.get(key); if (index != null) return remove((int) index) != null; return false; } public List<V> values() { return ImmutableList.copyOf(values); } public Set<K> keys() { return keyIndex.keySet(); } public Pair<K, V> getFirst() { if (isEmpty()) return null; return get(0); } public Pair<K, V> getLast() { if (isEmpty()) return null; return get(size() - 1); } @Nullable public V getValue(K key) { Integer index = keyIndex.get(key); if (index != null) return get(index).value; return null; } @Nullable public Pair<K, V> getPair(K key) { Integer index = keyIndex.get(key); if (index != null) return get(index); return null; } public void setKey(int index, K key) { set(index, new Pair<>(key, get(index).value)); updateEntireMap(); } }
package uk.ac.ebi.phenotype.chart; import java.io.IOException; import java.net.URISyntaxException; 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 org.apache.commons.lang.WordUtils; import org.apache.log4j.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.stereotype.Service; import uk.ac.ebi.phenotype.dao.DiscreteTimePoint; import uk.ac.ebi.phenotype.pojo.BiologicalModel; import uk.ac.ebi.phenotype.pojo.Parameter; import uk.ac.ebi.phenotype.pojo.SexType; import uk.ac.ebi.phenotype.pojo.ZygosityType; import uk.ac.ebi.phenotype.service.dto.ExperimentDTO; import uk.ac.ebi.phenotype.service.dto.ObservationDTO; @Service public class TimeSeriesChartAndTableProvider { private static final Logger logger = Logger .getLogger(TimeSeriesChartAndTableProvider.class); public ChartData doTimeSeriesOverviewData( Map<String, List<DiscreteTimePoint>> lines, Parameter p) { if (lines == null) { return new ChartData(); } String title = p.getName(); // create CharData ChartData chartsNTablesForParameter = creatDiscretePointTimeSeriesChartOverview( "1", title, lines, p.checkParameterUnit(1), p.checkParameterUnit(2), 1, "org", p); return chartsNTablesForParameter; } public ChartData doTimeSeriesData(ExperimentDTO experiment, Parameter parameter, String experimentNumber, BiologicalModel expBiologicalModel) throws IOException, URISyntaxException { ChartData chartNTableForParameter = null; Map<String, List<DiscreteTimePoint>> lines = new HashMap<String, List<DiscreteTimePoint>>(); for (SexType sex : experiment.getSexes()) { List<DiscreteTimePoint> controlDataPoints = new ArrayList<>(); for (ObservationDTO control : experiment.getControls()) { String docGender = control.getSex(); if (SexType.valueOf(docGender).equals(sex)) { Float dataPoint = control.getDataPoint(); logger.debug("data value=" + dataPoint); Float discreteTimePoint = control.getDiscretePoint(); controlDataPoints.add(new DiscreteTimePoint(discreteTimePoint, dataPoint)); } } logger.debug("finished putting control to data points"); TimeSeriesStats stats = new TimeSeriesStats(); String label = ChartUtils.getLabel(null, sex); List<DiscreteTimePoint> controlMeans = stats.getMeanDataPoints(controlDataPoints); lines.put(label, controlMeans); for (ZygosityType zType : experiment.getZygosities()) { List<DiscreteTimePoint> mutantData = new ArrayList<>(); Set<ObservationDTO> expObservationsSet = Collections.emptySet(); if (zType.equals(ZygosityType.heterozygote) || zType.equals(ZygosityType.hemizygote)) { expObservationsSet = experiment.getHeterozygoteMutants(); } if (zType.equals(ZygosityType.homozygote)) { expObservationsSet = experiment.getHomozygoteMutants(); } for (ObservationDTO expDto : expObservationsSet) { // get the attributes of this data point String docGender = expDto.getSex(); if (SexType.valueOf(docGender).equals(sex)) { Float dataPoint = expDto.getDataPoint(); logger.debug("data value=" + dataPoint); Float discreateTimePoint = expDto.getDiscretePoint(); mutantData.add(new DiscreteTimePoint(discreateTimePoint, new Float(dataPoint))); } } logger.debug("doing mutant data"); List<DiscreteTimePoint> mutantMeans = stats.getMeanDataPoints(mutantData); label = ChartUtils.getLabel(zType, sex); lines.put(label, mutantMeans); } } String title = "Mean " + parameter.getName(); if (lines.size() > 1) { // if lines are greater than one i.e. more than just control create charts and tables int decimalPlaces = ChartUtils.getDecimalPlaces(experiment); chartNTableForParameter = creatDiscretePointTimeSeriesChart( experimentNumber, title, lines, parameter.checkParameterUnit(1), parameter.checkParameterUnit(2), decimalPlaces, experiment.getOrganisation(), parameter); chartNTableForParameter.setExperiment(experiment); } chartNTableForParameter.setLines(lines); return chartNTableForParameter; } /** * Creates a single chart and adds it to the chart array that is then added * to the model by the main method * * @param title * @param lines * @param xUnitsLabel * @param yUnitsLabel * @param organisation * TODO * @param parameter * @param model * @param timeSeriesCharts * * @return */ private ChartData creatDiscretePointTimeSeriesChart(String expNumber, String title, Map<String, List<DiscreteTimePoint>> lines, String xUnitsLabel, String yUnitsLabel, int decimalPlaces, String organisation, Parameter parameter) { JSONArray series = new JSONArray(); String seriesString = ""; Set<Float> categoriesSet = new HashSet<Float>(); Float maxForChart = new Float(0); Float minForChart = new Float(1000000000); String mColor = ChartColors.getMutantColor(ChartColors.alphaTranslucid70).replaceAll("'", ""); String wtColor = ChartColors.getWTColor(ChartColors.alphaTranslucid70).replaceAll("'", ""); try { int i = 0; for (String key : lines.keySet()) {// key is control hom or het String color = mColor; JSONObject object = new JSONObject(); System.out.println("KEY ::: " + key); JSONArray data = new JSONArray(); object.put("name", key); SexType sexType = SexType.male; if(key.contains("Female")) { sexType = SexType.female; } if (key.contains("WT")){ color = wtColor; } JSONObject errorBarsObject = null; try { errorBarsObject = new JSONObject();// "{ name: 'Confidence', type: 'errorbar', color: 'black', data: [ [7.5, 8.5], [2.8, 4], [1.5, 2.5], [3, 4.1], [6.5, 7.5], [3.3, 4.1], [4.8, 5.1], [2.2, 3.0], [5.1, 8] ] } "); errorBarsObject.put("name", "Standard Deviation"); errorBarsObject.put("type", "errorbar"); errorBarsObject.put("color", color); } catch (JSONException e) { e.printStackTrace(); } JSONArray errorsDataJson = new JSONArray(); for (DiscreteTimePoint pt : lines.get(key)) { JSONArray pair = new JSONArray(); pair.put(pt.getDiscreteTime()); pair.put(pt.getData()); categoriesSet.add(pt.getDiscreteTime()); data.put(pair); // set the error bars JSONArray errorBarsJ = new JSONArray(); errorBarsJ.put(pt.getDiscreteTime()); errorBarsJ.put(pt.getErrorPair().get(0)); errorBarsJ.put(pt.getErrorPair().get(1)); errorsDataJson.put(errorBarsJ); errorBarsObject.put("data", errorsDataJson); } object.put("data", data); object.put("color", color); // add a placeholder string so we can add a tooltip method // specifically for data that is not error bars later on in this // code String placeholderString = "placeholder"; object.put(placeholderString, placeholderString); series.put(object); series.put(errorBarsObject); i++; } } catch (JSONException e) { e.printStackTrace(); } // need to add error bars to series data as well! // sort the categories by time as means are all sorted already List<Float> cats = new ArrayList<Float>(); for (Float cat : categoriesSet) { cats.add(cat); } Collections.sort(cats); String noDecimalsString = ""; if (xUnitsLabel.equals("number")) { // set the xAxis to be numbers with no decimals noDecimalsString = "allowDecimals:false,"; } String decimalFormatString = ":." + decimalPlaces + "f"; String headerFormatString = "headerFormat: '<span style=\"font-size: 12px\">" + WordUtils.capitalize(xUnitsLabel) + " {point.key}</span><br/>',"; String pointToolTip = "tooltip: { " + headerFormatString + "pointFormat: '<span style=\"font-weight: bold; color: {series.color}\">{series.name}</span>:<b>{point.y" + decimalFormatString + "}" + yUnitsLabel + "</b> '}"; String escapedPlaceholder = "\"placeholder\":\"placeholder\""; seriesString = series.toString().replace(escapedPlaceholder, pointToolTip); String errorBarsToolTip = "tooltip: { pointFormat: 'SD: {point.low" + decimalFormatString + "}-{point.high" + decimalFormatString + "}<br/>' }"; int index = series.toString().indexOf("\"errorbar"); String escapedErrorString = "\"errorbar\""; seriesString = seriesString.replace(escapedErrorString, escapedErrorString + "," + errorBarsToolTip); String axisFontSize = "15"; String javascript = "$(document).ready(function() { chart = new Highcharts.Chart({ " // +" colors:" + colors + ", " +" chart: { zoomType: 'x', renderTo: 'timechart" + expNumber + "', type: 'line' }, title: { text: '" + title + "', x: -20 }, credits: { enabled: false }, subtitle: { text: '" + parameter.getStableId() + "', x: -20 }, xAxis: { " + noDecimalsString + " labels: { style:{ fontSize:" + axisFontSize + " }}, title: { text: '" // + xUnitsLabel + "Age - rounded to nearest week" + "' } }, yAxis: { labels: { style:{ fontSize:" + axisFontSize + " }}, title: { text: ' " + yUnitsLabel + "' }, plotLines: [{ value: 0, width: 1, color: '#808080' }] }, " + "tooltip: {shared: true}," + "series: " + seriesString + " }); }); "; ChartData chartAndTable = new ChartData(); chartAndTable.setChart(javascript); chartAndTable.setOrganisation(organisation); chartAndTable.setId(expNumber); System.out.println("TIMESERIES CHART :: " + javascript); return chartAndTable; } private ChartData creatDiscretePointTimeSeriesChartOverview(String expNumber, String title, Map<String, List<DiscreteTimePoint>> lines, String xUnitsLabel, String yUnitsLabel, int decimalPlaces, String organisation, Parameter parameter) { JSONArray series = new JSONArray(); String seriesString = ""; Set<Float> categoriesSet = new HashSet<Float>(); Float maxForChart = new Float(0); Float minForChart = new Float(1000000000); try { int i = 0; for (String key : lines.keySet()) {// key is line name or "Control" JSONObject object = new JSONObject(); JSONArray data = new JSONArray(); object.put("name", key); String colorString; if (key.equalsIgnoreCase("Control")){ colorString = ChartColors.getDefaultControlColor(ChartColors.alphaTranslucid70); } else { colorString = ChartColors.getRgbaString(SexType.male, i, ChartColors.alphaTranslucid70); } object.put("color", colorString); JSONObject errorBarsObject = null; try { errorBarsObject = new JSONObject(); errorBarsObject.put("name", "Standard Deviation"); errorBarsObject.put("type", "errorbar"); errorBarsObject.put("color", colorString); } catch (JSONException e) { e.printStackTrace(); } JSONArray errorsDataJson = new JSONArray(); for (DiscreteTimePoint pt : lines.get(key)) { JSONArray pair = new JSONArray(); pair.put(pt.getDiscreteTime()); pair.put(pt.getData()); categoriesSet.add(pt.getDiscreteTime()); data.put(pair); // set the error bars JSONArray errorBarsJ = new JSONArray(); errorBarsJ.put(pt.getDiscreteTime()); errorBarsJ.put(pt.getErrorPair().get(0)); errorBarsJ.put(pt.getErrorPair().get(1)); errorsDataJson.put(errorBarsJ); errorBarsObject.put("data", errorsDataJson); } object.put("data", data); String placeholderString = "placeholder"; object.put(placeholderString, placeholderString); series.put(object); series.put(errorBarsObject); i++; } } catch (JSONException e) { e.printStackTrace(); } // need to add error bars to series data as well! // sort the categories by time as means are all sorted already List<Float> cats = new ArrayList<Float>(); for (Float cat : categoriesSet) { cats.add(cat); } Collections.sort(cats); String noDecimalsString = ""; if (xUnitsLabel.equals("number")) { // set the xAxis to be numbers with no decimals noDecimalsString = "allowDecimals:false,"; } String decimalFormatString = ":." + decimalPlaces + "f"; String headerFormatString = "headerFormat: '<span style=\"font-size: 12px\">" + WordUtils.capitalize(xUnitsLabel) + " {point.key}</span><br/>',"; String pointToolTip = "tooltip: { " + headerFormatString + "pointFormat: '<span style=\"font-weight: bold; color: {series.color}\">{series.name}</span>:<b>{point.y" + decimalFormatString + "}" + yUnitsLabel + "</b> '}"; String escapedPlaceholder = "\"placeholder\":\"placeholder\""; seriesString = series.toString().replace(escapedPlaceholder, pointToolTip); String errorBarsToolTip = "tooltip: { pointFormat: 'SD: {point.low" + decimalFormatString + "}-{point.high" + decimalFormatString + "}<br/>' }"; int index = series.toString().indexOf("\"errorbar"); String escapedErrorString = "\"errorbar\""; seriesString = seriesString.replace(escapedErrorString, escapedErrorString + "," + errorBarsToolTip); String axisFontSize = "15"; List<String> colors=ChartColors.getFemaleMaleColorsRgba(ChartColors.alphaTranslucid70); // JSONArray colorArray = new JSONArray(colors); String javascript = "$(document).ready(function() { chart = new Highcharts.Chart({ " // +" colors:"+colorArray +" chart: { zoomType: 'x', renderTo: 'single-chart-div', type: 'line', marginRight: 130, marginBottom: 50 }, title: { text: '" + WordUtils.capitalize(title) + "', x: -20 }, credits: { enabled: false }, subtitle: { text: '" + parameter.getStableId() + "', x: -20 }, xAxis: { " + noDecimalsString + " labels: { style:{ fontSize:" + axisFontSize + " }}, title: { text: '" + xUnitsLabel + "' } }, yAxis: { labels: { style:{ fontSize:" + axisFontSize + " }}, title: { text: ' " + yUnitsLabel + "' }, plotLines: [{ value: 0, width: 1, color: '#808080' }] }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'top', x: -10, y: 100, borderWidth: 0 }, " + "tooltip: {shared: true}," + "series: " + seriesString + " }); }); "; ChartData chartAndTable = new ChartData(); chartAndTable.setChart(javascript); chartAndTable.setOrganisation(organisation); chartAndTable.setId(parameter.getStableId()); return chartAndTable; } }
package uk.ac.ebi.phenotype.solr.indexer; import org.apache.commons.lang.StringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import uk.ac.ebi.phenotype.service.dto.StatisticalResultDTO; import uk.ac.ebi.phenotype.solr.indexer.beans.ImpressBean; import uk.ac.ebi.phenotype.solr.indexer.beans.OntologyTermBean; import uk.ac.ebi.phenotype.solr.indexer.beans.OrganisationBean; import uk.ac.ebi.phenotype.solr.indexer.utils.IndexerMap; import javax.sql.DataSource; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; /** * Load documents into the statistical-results SOLR core */ public class StatisticalResultIndexer extends AbstractIndexer { private static final Logger logger = LoggerFactory.getLogger(StatisticalResultIndexer.class); private static Connection connection; @Autowired @Qualifier("komp2DataSource") DataSource komp2DataSource; @Autowired @Qualifier("ontodbDataSource") DataSource ontodbDataSource; @Autowired @Qualifier("statisticalResultsIndexing") SolrServer statResultCore; Map<String, List<OntologyTermBean>> mpTopTerms = new HashMap<>(); Map<String, List<OntologyTermBean>> mpIntTerms = new HashMap<>(); Map<String, OntologyTermBean> mpTerms = new HashMap<>(); Map<Integer, ImpressBean> pipelineMap = new HashMap<>(); Map<Integer, ImpressBean> procedureMap = new HashMap<>(); Map<Integer, ImpressBean> parameterMap = new HashMap<>(); Map<Integer, OrganisationBean> organisationMap = new HashMap<>(); Map<Integer, BiologicalDataBean> biologicalDataMap = new HashMap<>(); public StatisticalResultIndexer() { } public static final long MIN_EXPECTED_ROWS = 400000; @Override public void validateBuild() throws IndexerException { SolrQuery query = new SolrQuery().setQuery("*:*").setRows(0); try { Long numFound = statResultCore.query(query).getResults().getNumFound(); if (numFound < MIN_EXPECTED_ROWS) { throw new IndexerException("validateBuild(): Expected " + MIN_EXPECTED_ROWS + " rows but found " + numFound + " rows."); } logger.info("MIN_EXPECTED_ROWS: " + MIN_EXPECTED_ROWS + ". Actual rows: " + numFound); } catch (SolrServerException sse) { throw new IndexerException(sse); } } @Override public void initialise(String[] args) throws IndexerException { super.initialise(args); try { connection = komp2DataSource.getConnection(); logger.info("Populating mp maps"); mpTopTerms = IndexerMap.getMpTopLevelTerms(ontodbDataSource.getConnection()); mpIntTerms = IndexerMap.getMpIntermediateLevelTerms(ontodbDataSource.getConnection()); mpTerms = IndexerMap.getMpTerms(ontodbDataSource.getConnection()); logger.info("MP terms has {} entries", mpTerms.size()); logger.info("Populating impress maps"); pipelineMap = IndexerMap.getImpressPipelines(connection); procedureMap = IndexerMap.getImpressProcedures(connection); parameterMap = IndexerMap.getImpressParameters(connection); organisationMap = IndexerMap.getOrganisationMap(connection); logger.info("Populating biological data map"); populateBiologicalDataMap(); } catch (SQLException e) { throw new IndexerException(e); } printConfiguration(); } public static void main(String[] args) throws IndexerException { StatisticalResultIndexer main = new StatisticalResultIndexer(); main.initialise(args); main.run(); main.validateBuild(); logger.info("Process finished. Exiting."); } @Override protected Logger getLogger() { return logger; } @Override public void run() throws IndexerException { Long start = System.currentTimeMillis(); logger.info("Populating statistical-results solr core"); populateStatisticalResultsSolrCore(); logger.info("Populating statistical-results solr core - done [took: {}s]", (System.currentTimeMillis() - start) / 1000.0); } private void populateStatisticalResultsSolrCore() throws IndexerException { try { int count = 0; statResultCore.deleteByQuery("*:*"); // Populate unidimensional statistic results String query = "SELECT CONCAT(dependent_variable, '_', sr.id) as doc_id, " + " 'unidimensional' AS data_type, " + " sr.id AS db_id, control_id, experimental_id, experimental_zygosity, " + " external_db_id, organisation_id, " + " pipeline_id, procedure_id, parameter_id, colony_id, " + " dependent_variable, control_selection_strategy, male_controls, " + " male_mutants, female_controls, female_mutants, " + " metadata_group, statistical_method, status, " + " batch_significance, " + " variance_significance, null_test_significance, genotype_parameter_estimate, " + " genotype_percentage_change, " + " genotype_stderr_estimate, genotype_effect_pvalue, gender_parameter_estimate, " + " gender_stderr_estimate, gender_effect_pvalue, weight_parameter_estimate, " + " weight_stderr_estimate, weight_effect_pvalue, gp1_genotype, " + " gp1_residuals_normality_test, gp2_genotype, gp2_residuals_normality_test, " + " blups_test, rotated_residuals_normality_test, intercept_estimate, " + " intercept_stderr_estimate, interaction_significance, interaction_effect_pvalue, " + " gender_female_ko_estimate, gender_female_ko_stderr_estimate, gender_female_ko_pvalue, " + " gender_male_ko_estimate, gender_male_ko_stderr_estimate, gender_male_ko_pvalue, " + " classification_tag, additional_information, " + " mp_acc, " + " db.short_name as resource_name, db.name as resource_fullname, db.id as resource_id, " + " proj.name as project_name, proj.id as project_id, " + " org.name as phenotyping_center, org.id as phenotyping_center_id " + "FROM stats_unidimensional_results sr " + "INNER JOIN external_db db on db.id=sr.external_db_id " + "INNER JOIN project proj on proj.id=sr.project_id " + "INNER JOIN organisation org on org.id=sr.organisation_id " + "WHERE dependent_variable NOT LIKE '%FER%' AND dependent_variable NOT LIKE '%VIA%'"; try (PreparedStatement p = connection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { p.setFetchSize(Integer.MIN_VALUE); ResultSet r = p.executeQuery(); while (r.next()) { StatisticalResultDTO doc = parseUnidimensionalResult(r); statResultCore.addBean(doc, 30000); count ++; if (count % 10000 == 0) { logger.info(" added {} unidimensional beans", count); } } } // Populate categorical statistic results query = "SELECT CONCAT(dependent_variable, '_', sr.id) as doc_id, " + " 'categorical' AS data_type, sr.id AS db_id, control_id, " + " experimental_id, experimental_sex as sex, experimental_zygosity, " + " external_db_id, organisation_id, " + " pipeline_id, procedure_id, parameter_id, colony_id, " + " dependent_variable, control_selection_strategy, male_controls, " + " male_mutants, female_controls, female_mutants, " + " metadata_group, statistical_method, status, " + " category_a, category_b, " + " p_value as categorical_p_value, effect_size AS categorical_effect_size, " + " mp_acc, " + " db.short_name as resource_name, db.name as resource_fullname, db.id as resource_id, " + " proj.name as project_name, proj.id as project_id, " + " org.name as phenotyping_center, org.id as phenotyping_center_id " + "FROM stats_categorical_results sr " + "INNER JOIN external_db db on db.id=sr.external_db_id " + "INNER JOIN project proj on proj.id=sr.project_id " + "INNER JOIN organisation org on org.id=sr.organisation_id " + "WHERE dependent_variable NOT LIKE '%FER%' AND dependent_variable NOT LIKE '%VIA%'"; try (PreparedStatement p = connection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { p.setFetchSize(Integer.MIN_VALUE); ResultSet r = p.executeQuery(); while (r.next()) { StatisticalResultDTO doc = parseCategoricalResult(r); statResultCore.addBean(doc, 30000); count ++; if (count % 10000 == 0) { logger.info(" added {} categorical beans", count); } } } // Final commit to save the rest of the docs logger.info(" added {} totalbeans", count); statResultCore.commit(true, true); // waitflush & waitserver. } catch (SQLException | IOException | SolrServerException e) { logger.error("Big error {}", e.getMessage(), e); } } private StatisticalResultDTO parseUnidimensionalResult(ResultSet r) throws SQLException { StatisticalResultDTO doc = parseResultCommonFields(r); doc.setNullTestPValue(r.getDouble("null_test_significance")); doc.setpValue(r.getDouble("null_test_significance")); doc.setGroup1Genotype(r.getString("gp1_genotype")); doc.setGroup1ResidualsNormalityTest(r.getDouble("gp1_residuals_normality_test")); doc.setGroup2Genotype(r.getString("gp2_genotype")); doc.setGroup2ResidualsNormalityTest(r.getDouble("gp2_residuals_normality_test")); doc.setBatchSignificant(r.getBoolean("batch_significance")); doc.setVarianceSignificant(r.getBoolean("variance_significance")); doc.setInteractionSignificant(r.getBoolean("interaction_significance")); doc.setGenotypeEffectParameterEstimate(r.getDouble("genotype_parameter_estimate")); String percentageChange = r.getString("genotype_percentage_change"); if ( ! r.wasNull()) { Double femalePercentageChange = getFemalePercentageChange(percentageChange); if (femalePercentageChange != null) { doc.setFemalePercentageChange(femalePercentageChange.toString() + "%"); } Double malePercentageChange = getMalePercentageChange(percentageChange); if (malePercentageChange != null) { doc.setMalePercentageChange(malePercentageChange.toString() + "%"); } } doc.setGenotypeEffectStderrEstimate(r.getDouble("genotype_stderr_estimate")); doc.setGenotypeEffectPValue(r.getDouble("genotype_effect_pvalue")); doc.setSexEffectParameterEstimate(r.getDouble("gender_parameter_estimate")); doc.setSexEffectStderrEstimate(r.getDouble("gender_stderr_estimate")); doc.setSexEffectPValue(r.getDouble("gender_effect_pvalue")); doc.setWeightEffectParameterEstimate(r.getDouble("weight_parameter_estimate")); doc.setWeightEffectStderrEstimate(r.getDouble("weight_stderr_estimate")); doc.setWeightEffectPValue(r.getDouble("weight_effect_pvalue")); doc.setInterceptEstimate(r.getDouble("intercept_estimate")); doc.setInterceptEstimateStderrEstimate(r.getDouble("intercept_stderr_estimate")); doc.setInteractionEffectPValue(r.getDouble("interaction_effect_pvalue")); doc.setFemaleKoParameterEstimate(r.getDouble("gender_female_ko_estimate")); doc.setFemaleKoEffectStderrEstimate(r.getDouble("gender_female_ko_stderr_estimate")); doc.setFemaleKoEffectPValue(r.getDouble("gender_female_ko_pvalue")); doc.setMaleKoParameterEstimate(r.getDouble("gender_male_ko_estimate")); doc.setMaleKoEffectStderrEstimate(r.getDouble("gender_male_ko_stderr_estimate")); doc.setMaleKoEffectPValue(r.getDouble("gender_male_ko_pvalue")); doc.setBlupsTest(r.getDouble("blups_test")); doc.setRotatedResidualsTest(r.getDouble("rotated_residuals_normality_test")); doc.setClassificationTag(r.getString("classification_tag")); doc.setAdditionalInformation(r.getString("additional_information")); return doc; } private Double getFemalePercentageChange(String token) { Double retVal = null; List<String> sexes = Arrays.asList(token.split(",")); for (String sex : sexes) { if (sex.contains("Female")) { try { String[] pieces = sex.split(":"); retVal = Double.parseDouble(pieces[1].replaceAll("%", "")); } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { // null statement; } break; } } return retVal; } private Double getMalePercentageChange(String token) { Double retVal = null; List<String> sexes = Arrays.asList(token.split(",")); for (String sex : sexes) { if (sex.contains("Male")) { try { String[] pieces = sex.split(":"); retVal = Double.parseDouble(pieces[1].replaceAll("%", "")); } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { // null statement; } break; } } return retVal; } private StatisticalResultDTO parseCategoricalResult(ResultSet r) throws SQLException { StatisticalResultDTO doc = parseResultCommonFields(r); doc.setSex(r.getString("sex")); doc.setpValue(r.getDouble("categorical_p_value")); doc.setEffectSize(r.getDouble("categorical_effect_size")); Set<String> categories = new HashSet<>(); if (StringUtils.isNotEmpty(r.getString("category_a"))) { categories.addAll(Arrays.asList(r.getString("category_a").split("|"))); } if (StringUtils.isNotEmpty(r.getString("category_b"))) { categories.addAll(Arrays.asList(r.getString("category_b").split("|"))); } doc.setCategories(new ArrayList<>(categories)); return doc; } private StatisticalResultDTO parseResultCommonFields(ResultSet r) throws SQLException { StatisticalResultDTO doc = new StatisticalResultDTO(); doc.setDocId(r.getString("doc_id")); doc.setDataType(r.getString("data_type")); // Experiment details doc.setResourceId(r.getInt("resource_id")); doc.setResourceName(r.getString("resource_name")); doc.setResourceFullname(r.getString("resource_fullname")); doc.setProjectId(r.getInt("project_id")); doc.setProjectName(r.getString("project_name")); doc.setPhenotypingCenter(r.getString("phenotyping_center")); doc.setPipelineId(pipelineMap.get(r.getInt("pipeline_id")).id); doc.setPipelineStableKey(pipelineMap.get(r.getInt("pipeline_id")).stableKey); doc.setPipelineName(pipelineMap.get(r.getInt("pipeline_id")).name); doc.setPipelineStableId(pipelineMap.get(r.getInt("pipeline_id")).stableId); doc.setProcedureId(procedureMap.get(r.getInt("procedure_id")).id); doc.setProcedureStableKey(procedureMap.get(r.getInt("procedure_id")).stableKey); doc.setProcedureName(procedureMap.get(r.getInt("procedure_id")).name); doc.setProcedureStableId(procedureMap.get(r.getInt("procedure_id")).stableId); doc.setParameterId(parameterMap.get(r.getInt("parameter_id")).id); doc.setParameterStableKey(parameterMap.get(r.getInt("parameter_id")).stableKey); doc.setParameterName(parameterMap.get(r.getInt("parameter_id")).name); doc.setParameterStableId(parameterMap.get(r.getInt("parameter_id")).stableId); doc.setControlBiologicalModelId(r.getInt("control_id")); doc.setMutantBiologicalModelId(r.getInt("experimental_id")); doc.setZygosity(r.getString("experimental_zygosity")); doc.setDependentVariable(r.getString("dependent_variable")); doc.setExternalDbId(r.getInt("external_db_id")); doc.setDbId(r.getInt("db_id")); doc.setOrganisationId(r.getInt("organisation_id")); doc.setPhenotypingCenterId(r.getInt("phenotyping_center_id")); // Biological details BiologicalDataBean b = biologicalDataMap.get(r.getInt("experimental_id")); doc.setMarkerAccessionId(b.geneAcc); doc.setMarkerSymbol(b.geneSymbol); doc.setAlleleAccessionId(b.alleleAccession); doc.setAlleleName(b.alleleName); doc.setAlleleSymbol(b.alleleSymbol); doc.setStrainAccessionId(b.strainAcc); doc.setStrainName(b.strainName); // Data details // Always set a metadata group here to allow for simpler searching for // unique results and to maintain parity with the observation index // where "empty string" metadata group means no required metadata. if (StringUtils.isNotEmpty(r.getString("metadata_group"))) { doc.setMetadataGroup(r.getString("metadata_group")); } else { doc.setMetadataGroup(""); } doc.setControlSelectionMethod(r.getString("control_selection_strategy")); doc.setStatisticalMethod(r.getString("statistical_method")); doc.setMaleControlCount(r.getInt("male_controls")); doc.setFemaleControlCount(r.getInt("female_controls")); doc.setMaleMutantCount(r.getInt("male_mutants")); doc.setFemaleMutantCount(r.getInt("female_mutants")); doc.setColonyId(r.getString("colony_id")); doc.setStatus(r.getString("status")); // MP Terms /* TODO: The sexes can have different MP terms!!! Need to handle this case */ OntologyTermBean otBean = mpTerms.get(r.getString("mp_acc")); if (otBean != null) { doc.setMpTermId(otBean.getTermId()); doc.setMpTermName(otBean.getName()); } List<String> termIds = new ArrayList<>(); List<String> termNames = new ArrayList<>(); Set<String> termSynonyms = new HashSet<>(); List<String> termDefinitions = new ArrayList<>(); if (doc.getMpTermId() != null && mpTopTerms.containsKey(doc.getMpTermId())) { for (OntologyTermBean term : new HashSet<>(mpTopTerms.get(doc.getMpTermId()))) { termIds.add(term.getTermId()); termNames.add(term.getName()); termSynonyms.addAll(term.getSynonyms()); termDefinitions.add(term.getDefinition()); } doc.setTopLevelMpTermId(termIds); doc.setTopLevelMpTermName(termNames); } termIds = new ArrayList<>(); termNames = new ArrayList<>(); termSynonyms = new HashSet<>(); termDefinitions = new ArrayList<>(); if (doc.getMpTermId() != null && mpIntTerms.containsKey(doc.getMpTermId())) { for (OntologyTermBean term : new HashSet<>(mpIntTerms.get(doc.getMpTermId()))) { termIds.add(term.getTermId()); termNames.add(term.getName()); termSynonyms.addAll(term.getSynonyms()); termDefinitions.add(term.getDefinition()); } doc.setIntermediateMpTermId(termIds); doc.setIntermediateMpTermName(termNames); } return doc; } /** * Add all the relevant data required quickly looking up biological data * associated to a biological sample * * @throws SQLException when a database exception occurs */ private void populateBiologicalDataMap() throws SQLException { String query = "SELECT bm.id, " + "strain.acc AS strain_acc, strain.name AS strain_name, " + "(SELECT DISTINCT allele_acc FROM biological_model_allele bma WHERE bma.biological_model_id=bm.id) AS allele_accession, " + "(SELECT DISTINCT a.symbol FROM biological_model_allele bma INNER JOIN allele a on (a.acc=bma.allele_acc AND a.db_id=bma.allele_db_id) WHERE bma.biological_model_id=bm.id) AS allele_symbol, " + "(SELECT DISTINCT a.name FROM biological_model_allele bma INNER JOIN allele a on (a.acc=bma.allele_acc AND a.db_id=bma.allele_db_id) WHERE bma.biological_model_id=bm.id) AS allele_name, " + "(SELECT DISTINCT gf_acc FROM biological_model_genomic_feature bmgf WHERE bmgf.biological_model_id=bm.id) AS acc, " + "(SELECT DISTINCT gf.symbol FROM biological_model_genomic_feature bmgf INNER JOIN genomic_feature gf ON gf.acc=bmgf.gf_acc WHERE bmgf.biological_model_id=bm.id) AS symbol " + "FROM biological_model bm " + "INNER JOIN biological_model_strain bmstrain ON bmstrain.biological_model_id=bm.id " + "INNER JOIN strain strain ON strain.acc=bmstrain.strain_acc " + "WHERE exists(SELECT DISTINCT gf.symbol FROM biological_model_genomic_feature bmgf INNER JOIN genomic_feature gf ON gf.acc=bmgf.gf_acc WHERE bmgf.biological_model_id=bm.id)"; try (PreparedStatement p = connection.prepareStatement(query)) { ResultSet resultSet = p.executeQuery(); while (resultSet.next()) { BiologicalDataBean b = new BiologicalDataBean(); b.alleleAccession = resultSet.getString("allele_accession"); b.alleleSymbol = resultSet.getString("allele_symbol"); b.alleleName = resultSet.getString("allele_name"); b.geneAcc = resultSet.getString("acc"); b.geneSymbol = resultSet.getString("symbol"); b.strainAcc = resultSet.getString("strain_acc"); b.strainName = resultSet.getString("strain_name"); biologicalDataMap.put(resultSet.getInt("id"), b); } } logger.info("Populated biological data map with {} entries", biologicalDataMap.size()); } /** * Internal class to act as Map value DTO for biological data */ protected class BiologicalDataBean { public String alleleAccession; public String alleleSymbol; public String alleleName; public String colonyId; public String externalSampleId; public String geneAcc; public String geneSymbol; public String sex; public String strainAcc; public String strainName; public String zygosity; } }
package org.apache.fop.render.pdf; // FOP import org.apache.fop.render.PrintRenderer; import org.apache.fop.messaging.MessageHandler; import org.apache.fop.image.ImageArea; import org.apache.fop.image.FopImage; import org.apache.fop.apps.FOPException; import org.apache.fop.fo.properties.*; import org.apache.fop.layout.inline.*; import org.apache.fop.pdf.*; import org.apache.fop.layout.*; import org.apache.fop.image.*; import org.apache.fop.extensions.*; import org.apache.fop.datatypes.IDReferences; import org.w3c.dom.svg.*; import org.apache.fop.dom.svg.*; // Java import java.io.IOException; import java.io.OutputStream; import java.util.Enumeration; import java.util.Vector; import java.util.Hashtable; /** * Renderer that renders areas to PDF */ public class PDFRenderer extends PrintRenderer { /** the PDF Document being created */ protected PDFDocument pdfDoc; /** the /Resources object of the PDF document being created */ protected PDFResources pdfResources; /** the current stream to add PDF commands to */ PDFStream currentStream; /** the current annotation list to add annotations to */ PDFAnnotList currentAnnotList; /** the current page to add annotations to */ PDFPage currentPage; PDFColor currentColor; /** true if a TJ command is left to be written */ boolean textOpen = false; /** the previous Y coordinate of the last word written. Used to decide if we can draw the next word on the same line. */ int prevWordY = 0; /** the previous X coordinate of the last word written. used to calculate how much space between two words */ int prevWordX = 0; /** The width of the previous word. Used to calculate space between */ int prevWordWidth = 0; private PDFOutline rootOutline; /** reusable word area string buffer to reduce memory usage */ private StringBuffer _wordAreaPDF = new StringBuffer(); /** * create the PDF renderer */ public PDFRenderer() { this.pdfDoc = new PDFDocument(); } /** * set the PDF document's producer * * @param producer string indicating application producing PDF */ public void setProducer(String producer) { this.pdfDoc.setProducer(producer); } /** * render the areas into PDF * * @param areaTree the laid-out area tree * @param stream the OutputStream to write the PDF to */ public void render(AreaTree areaTree, OutputStream stream) throws IOException, FOPException { MessageHandler.logln("rendering areas to PDF"); idReferences = areaTree.getIDReferences(); this.pdfResources = this.pdfDoc.getResources(); this.pdfDoc.setIDReferences(idReferences); Enumeration e = areaTree.getPages().elements(); while (e.hasMoreElements()) { this.renderPage((Page) e.nextElement()); } if (!idReferences.isEveryIdValid()) { // throw new FOPException("The following id's were referenced but not found: "+idReferences.getInvalidIds()+"\n"); MessageHandler.errorln("WARNING: The following id's were referenced but not found: "+ idReferences.getInvalidIds() + "\n"); } renderRootExtensions(areaTree); FontSetup.addToResources(this.pdfDoc, fontInfo); MessageHandler.logln("writing out PDF"); this.pdfDoc.output(stream); } /** * add a line to the current stream * * @param x1 the start x location in millipoints * @param y1 the start y location in millipoints * @param x2 the end x location in millipoints * @param y2 the end y location in millipoints * @param th the thickness in millipoints * @param r the red component * @param g the green component * @param b the blue component */ protected void addLine(int x1, int y1, int x2, int y2, int th, PDFPathPaint stroke) { closeText(); currentStream.add("ET\nq\n" + stroke.getColorSpaceOut(false) + (x1 / 1000f) + " "+ (y1 / 1000f) + " m " + (x2 / 1000f) + " "+ (y2 / 1000f) + " l " + (th / 1000f) + " w S\n" + "Q\nBT\n"); } /** * add a line to the current stream * * @param x1 the start x location in millipoints * @param y1 the start y location in millipoints * @param x2 the end x location in millipoints * @param y2 the end y location in millipoints * @param th the thickness in millipoints * @param rs the rule style * @param r the red component * @param g the green component * @param b the blue component */ protected void addLine(int x1, int y1, int x2, int y2, int th, int rs, PDFPathPaint stroke) { closeText(); currentStream.add("ET\nq\n" + stroke.getColorSpaceOut(false) + setRuleStylePattern(rs) + (x1 / 1000f) + " "+ (y1 / 1000f) + " m " + (x2 / 1000f) + " "+ (y2 / 1000f) + " l " + (th / 1000f) + " w S\n" + "Q\nBT\n"); } /** * add a rectangle to the current stream * * @param x the x position of left edge in millipoints * @param y the y position of top edge in millipoints * @param w the width in millipoints * @param h the height in millipoints * @param stroke the stroke color/gradient */ protected void addRect(int x, int y, int w, int h, PDFPathPaint stroke) { closeText(); currentStream.add("ET\nq\n" + stroke.getColorSpaceOut(false) + (x / 1000f) + " " + (y / 1000f) + " " + (w / 1000f) + " " + (h / 1000f) + " re s\n" + "Q\nBT\n"); } /** * add a filled rectangle to the current stream * * @param x the x position of left edge in millipoints * @param y the y position of top edge in millipoints * @param w the width in millipoints * @param h the height in millipoints * @param fill the fill color/gradient * @param stroke the stroke color/gradient */ protected void addRect(int x, int y, int w, int h, PDFPathPaint stroke, PDFPathPaint fill) { closeText(); currentStream.add("ET\nq\n" + fill.getColorSpaceOut(true) + stroke.getColorSpaceOut(false) + (x / 1000f) + " " + (y / 1000f) + " " + (w / 1000f) + " " + (h / 1000f) + " re b\n" + "Q\nBT\n"); } /** * render image area to PDF * * @param area the image area to render */ public void renderImageArea(ImageArea area) { // adapted from contribution by BoBoGi int x = this.currentAreaContainerXPosition + area.getXOffset(); int y = this.currentYPosition; int w = area.getContentWidth(); int h = area.getHeight(); this.currentYPosition -= h; FopImage img = area.getImage(); if (img instanceof SVGImage) { try { closeText(); SVGSVGElement svg = ((SVGImage) img).getSVGDocument().getRootElement(); currentStream.add("ET\nq\n" + (((float) w) / 1000f) + " 0 0 " + (((float) h) / 1000f) + " " + (((float) x) / 1000f) + " " + (((float)(y - h)) / 1000f) + " cm\n"); // renderSVG(svg, (int) x, (int) y); currentStream.add("Q\nBT\n"); } catch (FopImageException e) { } } else { int xObjectNum = this.pdfDoc.addImage(img); closeText(); currentStream.add("ET\nq\n" + (((float) w) / 1000f) + " 0 0 " + (((float) h) / 1000f) + " " + (((float) x) / 1000f) + " " + (((float)(y - h)) / 1000f) + " cm\n" + "/Im" + xObjectNum + " Do\nQ\nBT\n"); } } /** render a foreign object area */ public void renderForeignObjectArea(ForeignObjectArea area) { // if necessary need to scale and align the content this.currentXPosition = this.currentXPosition + area.getXOffset(); this.currentYPosition = this.currentYPosition; switch (area.getAlign()) { case TextAlign.START: break; case TextAlign.END: break; case TextAlign.CENTER: case TextAlign.JUSTIFY: break; } switch (area.getVerticalAlign()) { case VerticalAlign.BASELINE: break; case VerticalAlign.MIDDLE: break; case VerticalAlign.SUB: break; case VerticalAlign.SUPER: break; case VerticalAlign.TEXT_TOP: break; case VerticalAlign.TEXT_BOTTOM: break; case VerticalAlign.TOP: break; case VerticalAlign.BOTTOM: break; } closeText(); // in general the content will not be text currentStream.add("ET\n"); // align and scale currentStream.add("q\n"); switch (area.scalingMethod()) { case Scaling.UNIFORM: break; case Scaling.NON_UNIFORM: break; } // if the overflow is auto (default), scroll or visible // then the contents should not be clipped, since this // is considered a printing medium. switch (area.getOverflow()) { case Overflow.VISIBLE: case Overflow.SCROLL: case Overflow.AUTO: break; case Overflow.HIDDEN: break; } area.getObject().render(this); currentStream.add("Q\n"); currentStream.add("BT\n"); this.currentXPosition += area.getEffectiveWidth(); // this.currentYPosition -= area.getEffectiveHeight(); } /** * render SVG area to PDF * * @param area the SVG area to render */ public void renderSVGArea(SVGArea area) { // place at the current instream offset int x = this.currentXPosition; // Buggy: Method getXOffset() not found in class org.apache.fop.dom.svg.SVGArea //int x = this.currentAreaContainerXPosition + area.getXOffset(); int y = this.currentYPosition; SVGSVGElement svg = area.getSVGDocument().getRootElement(); int w = (int)(svg.getWidth().getBaseVal().getValue() * 1000); int h = (int)(svg.getHeight().getBaseVal().getValue() * 1000); float sx = 1, sy = -1; int xOffset = x, yOffset = y; // translate and scale according to viewbox. if (svg.getViewBox () != null) { SVGRect view = svg.getViewBox().getBaseVal(); // TODO take aspect constraints (attribute preserveAspectRatio) // into account. // Viewbox coordinates are all relative to the viewport // (ie. the x,y,w and h values calculated above). sx = svg.getWidth().getBaseVal().getValue() / view.getWidth (); sy = svg.getHeight().getBaseVal().getValue() / view.getHeight (); // move the origin xOffset -= (int)(sx * view.getX () * 1000f); yOffset -= (int)(sy * view.getY () * 1000f); sy = -sy; } /* * Clip to the svg area. * Note: To have the svg overlay (under) a text area then use * an fo:block-container */ currentStream.add("q\n"); if (w != 0 && h != 0) { currentStream.add(x / 1000f + " " + y / 1000f + " m\n"); currentStream.add((x + w) / 1000f + " " + y / 1000f + " l\n"); currentStream.add((x + w) / 1000f + " " + (y - h) / 1000f + " l\n"); currentStream.add(x / 1000f + " " + (y - h) / 1000f + " l\n"); currentStream.add("h\n"); currentStream.add("W\n"); currentStream.add("n\n"); } // transform so that the coordinates (0,0) is from the top left // and positive is down and to the right. (0,0) is where the // viewBox puts it. currentStream.add(sx + " 0 0 " + sy + " " + xOffset / 1000f + " " + yOffset / 1000f + " cm\n"); SVGRenderer svgRenderer = new SVGRenderer(area.getFontState(), pdfDoc, currentFontName, currentFontSize, currentXPosition, currentYPosition); svgRenderer.renderSVG(svg, 0, 0); currentStream.add(svgRenderer.getString()); currentStream.add("Q\n"); } /** * render inline area to PDF * * @param area inline area to render */ public void renderWordArea(WordArea area) { synchronized (_wordAreaPDF) { StringBuffer pdf = _wordAreaPDF; pdf.setLength(0); Hashtable kerning = null; boolean kerningAvailable = false; kerning = area.getFontState().getKerning(); if (kerning != null && !kerning.isEmpty()) { kerningAvailable = true; } String name = area.getFontState().getFontName(); int size = area.getFontState().getFontSize(); // This assumes that *all* CIDFonts use a /ToUnicode mapping boolean useMultiByte = false; Font f = (Font) area.getFontState().getFontInfo().getFonts().get( name); if (f instanceof CIDFont) useMultiByte = true; //String startText = useMultiByte ? "<FEFF" : "("; String startText = useMultiByte ? "<" : "("; String endText = useMultiByte ? "> " : ") "; if ((!name.equals(this.currentFontName)) || (size != this.currentFontSize)) { closeText(); this.currentFontName = name; this.currentFontSize = size; pdf = pdf.append("/" + name + " " + (size / 1000) + " Tf\n"); } PDFColor areaColor = null; if (this.currentFill instanceof PDFColor) { areaColor = (PDFColor)this.currentFill; } if (areaColor == null || areaColor.red() != (double)area.getRed() || areaColor.green() != (double)area.getGreen() || areaColor.blue() != (double)area.getBlue()) { areaColor = new PDFColor((double) area.getRed(), (double) area.getGreen(), (double) area.getBlue()); closeText(); this.currentFill = areaColor; pdf.append(this.currentFill.getColorSpaceOut(true)); } int rx = this.currentXPosition; int bl = this.currentYPosition; addWordLines(area, rx, bl, size, areaColor); if (!textOpen || bl != prevWordY) { closeText(); pdf.append("1 0 0 1 " +(rx / 1000f) + " " + (bl / 1000f) + " Tm [" + startText); prevWordY = bl; textOpen = true; } else { // express the space between words in thousandths of an em int space = prevWordX - rx + prevWordWidth; float emDiff = (float) space / (float) currentFontSize * 1000f; pdf.append(Float.toString(emDiff)); pdf.append(" "); pdf.append(startText); } prevWordWidth = area.getContentWidth(); prevWordX = rx; String s; if (area.getPageNumberID() != null) { // this text is a page number, so resolve it s = idReferences.getPageNumber(area.getPageNumberID()); if (s == null) { s = ""; } } else { s = area.getText(); } int l = s.length(); for (int i = 0; i < l; i++) { char ch = s.charAt(i); if (!useMultiByte) { if (ch > 127) { pdf.append("\\"); pdf.append(Integer.toOctalString((int) ch)); } else { switch (ch) { case '(': case ')': case '\\': pdf.append("\\"); break; } pdf.append(ch); } } else { pdf.append(getUnicodeString(ch)); } if (kerningAvailable && (i + 1) < l) { addKerning(pdf, (new Integer((int) ch)), (new Integer((int) s.charAt(i + 1))), kerning, startText, endText); } } pdf.append(endText); currentStream.add(pdf.toString()); this.currentXPosition += area.getContentWidth(); } } /** * Convert a char to a multibyte hex representation */ private String getUnicodeString(char c) { StringBuffer buf = new StringBuffer(4); byte[] uniBytes = null; try { char[] a = {c}; uniBytes = new String(a).getBytes("UnicodeBigUnmarked"); } catch (Exception e) { // This should never fail } for (int i = 0; i < uniBytes.length; i++) { int b = (uniBytes[i] < 0) ? (int)(256 + uniBytes[i]) : (int) uniBytes[i]; String hexString = Integer.toHexString(b); if (hexString.length() == 1) buf = buf.append("0"+hexString); else buf = buf.append(hexString); } return buf.toString(); } /** Checks to see if we have some text rendering commands open * still and writes out the TJ command to the stream if we do */ private void closeText() { if (textOpen) { currentStream.add("] TJ\n"); textOpen = false; prevWordX = 0; prevWordY = 0; } } private void addKerning(StringBuffer buf, Integer ch1, Integer ch2, Hashtable kerning, String startText, String endText) { Hashtable kernPair = (Hashtable) kerning.get(ch1); if (kernPair != null) { Integer width = (Integer) kernPair.get(ch2); if (width != null) { buf.append(endText) .append(-(width.intValue())) .append(' ').append(startText); } } } /** * render page into PDF * * @param page page to render */ public void renderPage(Page page) { BodyAreaContainer body; AreaContainer before, after, start, end; currentStream = this.pdfDoc.makeStream(); body = page.getBody(); before = page.getBefore(); after = page.getAfter(); start = page.getStart(); end = page.getEnd(); this.currentFontName = ""; this.currentFontSize = 0; currentStream.add("BT\n"); renderBodyAreaContainer(body); if (before != null) { renderAreaContainer(before); } if (after != null) { renderAreaContainer(after); } if (start != null) { renderAreaContainer(start); } if (end != null) { renderAreaContainer(end); } closeText(); currentStream.add("ET\n"); currentPage = this.pdfDoc.makePage(this.pdfResources, currentStream, page.getWidth() / 1000, page.getHeight() / 1000, page); if (page.hasLinks()) { currentAnnotList = this.pdfDoc.makeAnnotList(); currentPage.setAnnotList(currentAnnotList); Enumeration e = page.getLinkSets().elements(); while (e.hasMoreElements()) { LinkSet linkSet = (LinkSet) e.nextElement(); linkSet.align(); String dest = linkSet.getDest(); int linkType = linkSet.getLinkType(); Enumeration f = linkSet.getRects().elements(); while (f.hasMoreElements()) { LinkedRectangle lrect = (LinkedRectangle) f.nextElement(); currentAnnotList.addLink( this.pdfDoc.makeLink(lrect.getRectangle(), dest, linkType)); } } } else { // just to be on the safe side currentAnnotList = null; } // ensures that color is properly reset for blocks that carry over pages this.currentFill = null; } /** * defines a string containing dashArray and dashPhase for the rule style */ private String setRuleStylePattern (int style) { String rs = ""; switch (style) { case org.apache.fop.fo.properties.RuleStyle.SOLID: rs = "[] 0 d "; break; case org.apache.fop.fo.properties.RuleStyle.DASHED: rs = "[3 3] 0 d "; break; case org.apache.fop.fo.properties.RuleStyle.DOTTED: rs = "[1 3] 0 d "; break; case org.apache.fop.fo.properties.RuleStyle.DOUBLE: rs = "[] 0 d "; break; default: rs = "[] 0 d "; } return rs; } protected void renderRootExtensions(AreaTree areaTree) { Vector v = areaTree.getExtensions(); if (v != null) { Enumeration e = v.elements(); while (e.hasMoreElements()) { ExtensionObj ext = (ExtensionObj) e.nextElement(); if (ext instanceof Outline) { renderOutline((Outline) ext); } } } } private void renderOutline(Outline outline) { if (rootOutline == null) { rootOutline = this.pdfDoc.makeOutlineRoot(); } PDFOutline pdfOutline = null; Outline parent = outline.getParentOutline(); if (parent == null) { pdfOutline = this.pdfDoc.makeOutline(rootOutline, outline.getLabel().toString(), outline.getInternalDestination()); } else { PDFOutline pdfParentOutline = (PDFOutline) parent.getRendererObject(); if (pdfParentOutline == null) { MessageHandler.errorln("Error: pdfParentOutline is null"); } else { pdfOutline = this.pdfDoc.makeOutline(pdfParentOutline, outline.getLabel().toString(), outline.getInternalDestination()); } } outline.setRendererObject(pdfOutline); // handle sub outlines Vector v = outline.getOutlines(); Enumeration e = v.elements(); while (e.hasMoreElements()) { renderOutline((Outline) e.nextElement()); } } }
package org.apache.james.core; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import org.apache.avalon.AbstractLoggable; import org.apache.avalon.Component; import org.apache.avalon.ComponentNotAccessibleException; import org.apache.avalon.ComponentNotFoundException; import org.apache.avalon.ComponentManagerException; import org.apache.avalon.Composer; import org.apache.avalon.ComponentManager; import org.apache.avalon.Configurable; import org.apache.avalon.Configuration; import org.apache.avalon.ConfigurationException; import org.apache.avalon.Initializable; import org.apache.james.services.MailRepository; import org.apache.james.services.MailStore; import org.apache.log.LogKit; import org.apache.log.Logger; import org.apache.phoenix.Block; /** * * @author <a href="mailto:fede@apache.org">Federico Barbieri</a> */ public class AvalonMailStore extends AbstractLoggable implements Block, Composer, Configurable, MailStore, Initializable { private static final String REPOSITORY_NAME = "Repository"; private static long id; private HashMap repositories; private HashMap models; private HashMap classes; protected Configuration configuration; protected ComponentManager componentManager; public void compose( final ComponentManager componentManager ) throws ComponentManagerException { this.componentManager = componentManager; } public void configure( final Configuration configuration ) throws ConfigurationException { this.configuration = configuration; } public void init() throws Exception { getLogger().info("JamesMailStore init..."); repositories = new HashMap(); models = new HashMap(); classes = new HashMap(); Iterator registeredClasses = configuration.getChild("repositories").getChildren("repository"); while (registeredClasses.hasNext()) { registerRepository((Configuration) registeredClasses.next()); } getLogger().info("James RepositoryManager ...init"); } public void registerRepository(Configuration repConf) throws ConfigurationException { String className = repConf.getAttribute("class"); getLogger().info("Registering Repository " + className); Iterator protocols = repConf.getChild("protocols").getChildren("protocol"); Iterator types = repConf.getChild("types").getChildren("type"); Iterator models = repConf.getChild("models").getChildren("model"); while (protocols.hasNext()) { String protocol = ((Configuration) protocols.next()).getValue(); while (types.hasNext()) { String type = ((Configuration) types.next()).getValue(); while (models.hasNext()) { String model = ((Configuration) models.next()).getValue(); classes.put(protocol + type + model, className); getLogger().info(" for " + protocol + "," + type + "," + model); } } } } public void release(Component component) { } public Component select(Object hint) throws ComponentNotFoundException, ComponentNotAccessibleException { Configuration repConf = null; try { repConf = (Configuration) hint; } catch (ClassCastException cce) { throw new ComponentNotAccessibleException("hint is of the wrong type. Must be a Configuration", cce); } URL destination = null; try { destination = new URL(repConf.getAttribute("destinationURL")); } catch (ConfigurationException ce) { throw new ComponentNotAccessibleException("Malformed configuration has no destinationURL attribute", ce); } catch (MalformedURLException mue) { throw new ComponentNotAccessibleException("destination is malformed. Must be a valid URL", mue); } try { String type = repConf.getAttribute("type"); String repID = destination + type; MailRepository reply = (MailRepository) repositories.get(repID); String model = (String) repConf.getAttribute("model"); if (reply != null) { if (models.get(repID).equals(model)) { return (Component)reply; } else { throw new ComponentNotFoundException("There is already another repository with the same destination and type but with different model"); } } else { String protocol = destination.getProtocol(); String repClass = (String) classes.get( protocol + type + model ); getLogger().debug( "Need instance of " + repClass + " to handle: " + protocol + type + model ); try { reply = (MailRepository) Class.forName(repClass).newInstance(); if (reply instanceof Configurable) { ((Configurable) reply).configure(repConf); } if (reply instanceof Composer) { ((Composer) reply).compose( componentManager ); } /* if (reply instanceof Contextualizable) { ((Contextualizable) reply).contextualize(context); }*/ if (reply instanceof Initializable) { ((Initializable) reply).init(); } repositories.put(repID, reply); models.put(repID, model); getLogger().info( "New instance of " + repClass + " created for " + destination ); return (Component)reply; } catch (Exception e) { getLogger().warn( "Exception while creating repository:" + e.getMessage(), e ); throw new ComponentNotAccessibleException( "Cannot find or init repository", e ); } } } catch( final ConfigurationException ce ) { throw new ComponentNotAccessibleException( "Malformed configuration", ce ); } } public static final String getName() { return REPOSITORY_NAME + id++; } }
package org.appwork.utils.swing.dialog; import java.awt.Window; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.ListCellRenderer; import javax.swing.UIManager; import javax.swing.filechooser.FileFilter; import org.appwork.storage.JSonStorage; import org.appwork.utils.BinaryLogic; import org.appwork.utils.ImageProvider.ImageProvider; import org.appwork.utils.interfaces.ValueConverter; import org.appwork.utils.locale.APPWORKUTILS; import org.appwork.utils.locale.Loc; import org.appwork.utils.logging.Log; import org.appwork.utils.swing.EDTHelper; /** * A Dialog Instance which provides extended Dialog features and thus replaces * JOptionPane */ public class Dialog { /** * Requests a FileChooserDialog. * * @param id * ID of the dialog (used to save and restore the old directory) * @param title * The Dialog's Window Title dialog-title or null for default * @param fileSelectionMode * mode for selecting files (like JFileChooser.FILES_ONLY) or * null for default * @param fileFilter * filters the choosable files or null for default * @param multiSelection * Multiple files choosable? or null for default * @param preSelection * File which will be selected by default. leave null for * automode * @return an array of files or null if the user cancel the dialog */ public static enum FileChooserSelectionMode { FILES_ONLY(JFileChooser.FILES_ONLY), DIRECTORIES_ONLY(JFileChooser.DIRECTORIES_ONLY), FILES_AND_DIRECTORIES(JFileChooser.FILES_AND_DIRECTORIES); private final int id; private FileChooserSelectionMode(final int num) { id = num; } /** * @return the id */ public int getId() { return id; } } public static enum FileChooserType { OPEN_DIALOG(JFileChooser.OPEN_DIALOG), SAVE_DIALOG(JFileChooser.SAVE_DIALOG), CUSTOM_DIALOG(JFileChooser.CUSTOM_DIALOG), OPEN_DIALOG_WITH_PRESELECTION(JFileChooser.OPEN_DIALOG); private final int id; private FileChooserType(final int id) { this.id = id; } /** * @return the id */ public int getId() { return id; } } static { // AWU has their own filechooser extensions UIManager.put("Synthetica.extendedFileChooser.rememberPreferences", Boolean.FALSE); UIManager.put("Synthetica.extendedFileChooser.rememberLastDirectory", Boolean.FALSE); } /** * Hide the cancel Button */ public static final int BUTTONS_HIDE_CANCEL = 1 << 4; /** * Hide the OK button */ public static final int BUTTONS_HIDE_OK = 1 << 3; /** * Icon Key for Error Icons * * @see org.appwork.utils.ImageProvider.ImageProvider#getImageIcon(String, * int, int, boolean) */ public static final String ICON_ERROR = "error"; /** * Icon Key for Information Icons * * @see org.appwork.utils.ImageProvider.ImageProvider#getImageIcon(String, * int, int, boolean) */ public static final String ICON_INFO = "info"; /** * Icon Key for Question Icons * * @see org.appwork.utils.ImageProvider.ImageProvider#getImageIcon(String, * int, int, boolean) */ public static final String ICON_QUESTION = "help"; /** * Icon Key for Warning Icons * * @see org.appwork.utils.ImageProvider.ImageProvider#getImageIcon(String, * int, int, boolean) */ public static final String ICON_WARNING = "warning"; /** * internal singleton instance to access the instance of this class */ private static final Dialog INSTANCE = new Dialog(); /** * LOGIC_BYPASS all dialogs. Try to fill automatically or return null */ public static final int LOGIC_BYPASS = 1 << 1; /** * Use this flag to show display of the Timer */ public static final int LOGIC_COUNTDOWN = 1 << 2; /** * Don't show again is only valid for this session, but is not saved for * further sessions */ public static final int LOGIC_DONT_SHOW_AGAIN_DELETE_ON_EXIT = 1 << 11; public static final int LOGIC_DONOTSHOW_BASED_ON_TITLE_ONLY = 1 << 12; /** * Often, the {@link #STYLE_SHOW_DO_NOT_DISPLAY_AGAIN} option does not make * sense for the cancel option. Use this flag if the option should be * ignored if the user selects Cancel */ public static final int LOGIC_DONT_SHOW_AGAIN_IGNORES_CANCEL = 1 << 9; /** * Often, the {@link #STYLE_SHOW_DO_NOT_DISPLAY_AGAIN} option does not make * sense for the ok option. Use this flag if the option should be ignored if * the user selects OK */ public static final int LOGIC_DONT_SHOW_AGAIN_IGNORES_OK = 1 << 10; /** * if the user pressed cancel, the return mask will contain this mask */ public static final int RETURN_CANCEL = 1 << 2; /** * if user closed the window */ public static final int RETURN_CLOSED = 1 << 6; /** * this return flag can be set in two situations:<br> * a) The user selected the {@link #STYLE_SHOW_DO_NOT_DISPLAY_AGAIN} Option<br> * b) The dialog has been skipped because the DO NOT SHOW AGAIN flag has * been set previously<br> * <br> * Check {@link #RETURN_SKIPPED_BY_DONT_SHOW} to know if the dialog has been * visible or autoskipped */ public static final int RETURN_DONT_SHOW_AGAIN = 1 << 3; /** * If the user pressed OK, the return mask will contain this flag */ public static final int RETURN_OK = 1 << 1; /** * If the dialog has been skipped due to previously selected * {@link #STYLE_SHOW_DO_NOT_DISPLAY_AGAIN} Option, this return flag is set. * * @see #RETURN_DONT_SHOW_AGAIN */ public static final int RETURN_SKIPPED_BY_DONT_SHOW = 1 << 4; /** * If the Timeout ({@link #LOGIC_COUNTDOWN}) has run out, the return mask * contains this flag */ public static final int RETURN_TIMEOUT = 1 << 5; private static boolean ShellFolderIDWorkaround = false; /** * Do Not use an Icon. By default dialogs have an Icon */ public static final int STYLE_HIDE_ICON = 1 << 8; /** * Some dialogs are able to render HTML. Use this switch to enable html */ public static final int STYLE_HTML = 1 << 7; /** * Some dialogs are able to layout themselves in a large mode. E:g. to * display a huge text. */ public static final int STYLE_LARGE = 1 << 6; /** * Displays a Checkbox with "do not show this again" text. If the user * selects this box, the UserInteraktion class will remember the answer and * will not disturb the user with the same question (same title) */ public static final int STYLE_SHOW_DO_NOT_DISPLAY_AGAIN = 1 << 5; /** * Inputdialogs will use passwordfields instead of textfields */ public static final int STYLE_PASSWORD = 1 << 9; /** * tries to find some special markers in the text and selects an appropriate * icon * * @param text * @return */ public static ImageIcon getIconByText(final String text) { try { if (text.contains("?")) { return ImageProvider.getImageIcon(Dialog.ICON_QUESTION, 32, 32, true); } else if (text.matches(Loc.getErrorRegex())) { return ImageProvider.getImageIcon(Dialog.ICON_ERROR, 32, 32, true); } else if (text.contains("!")) { return ImageProvider.getImageIcon(Dialog.ICON_WARNING, 32, 32, true); } else { return ImageProvider.getImageIcon(Dialog.ICON_INFO, 32, 32, true); } } catch (final IOException e) { Log.exception(e); return null; } } /** * Return the singleton instance of Dialog * * @return */ public static Dialog getInstance() { return Dialog.INSTANCE; } public static boolean isClosed(final Object value) { if (!(value instanceof Integer)) { return false; } return BinaryLogic.containsSome((Integer) value, Dialog.RETURN_CLOSED); } public static boolean isOK(final Object value) { if (!(value instanceof Integer)) { return false; } return BinaryLogic.containsSome((Integer) value, Dialog.RETURN_OK); } /** * The max counter value for a timeout Dialog */ private int countdownTime = 20; /** * Parent window for all dialogs created with abstractdialog */ private JFrame owner = null; private Window window; /** * @return the {@link Dialog#countdownTime} * @see Dialog#countdownTime */ protected int getCountdownTime() { return countdownTime; } /** * @return the {@link Dialog#owner} * @see Dialog#owner */ public JFrame getParentOwner() { if (owner == null) { window = owner = new EDTHelper<JFrame>() { @Override public JFrame edtRun() { // TODO Auto-generated method stub return new JFrame(); } }.getReturnValue(); } return owner; } public Window getParentWindow() { return window; } /** * @param countdownTime * the {@link Dialog#countdownTime} to set * @see Dialog#countdownTime */ public void setCountdownTime(final int countdownTime) { this.countdownTime = countdownTime; } /** * @param parent * the {@link Dialog#owner} to set * @see Dialog#owner */ public void setParentOwner(final JFrame parent) { owner = parent; if (parent == null) { Log.exception(new NullPointerException("parent == null")); } window = owner; } /** * this is needed for correct parentWindow handling for correct dialog show * order * * @param window */ protected void setParentWindow(final Window window) { this.window = window; if (window == null) { Log.exception(new NullPointerException("window == null")); } } /** * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog * @param title * The Dialog's Window Title * @param question * The Dialog is able to show a question to the user. * @param options * A list of various options to select * @param defaultSelection * The option which is selected by default * @param icon * The dialog is able to display an Icon If this is null, the * dialog might select an Icon derived from the message and title * text * @param okOption * Text for OK Button [null for default] * @param cancelOption * Text for Cancel Button [null for default] * @param renderer * A renderer to customize the Dialog. Might be null * @return * @throws DialogCanceledException * @throws DialogClosedException */ public int showComboDialog(final int flag, final String title, final String question, final Object[] options, final int defaultSelection, final ImageIcon icon, final String okOption, final String cancelOption, final ListCellRenderer renderer) throws DialogClosedException, DialogCanceledException { if ((flag & Dialog.LOGIC_BYPASS) > 0) { return defaultSelection; } return this.showDialog(new ComboBoxDialog(flag, title, question, options, defaultSelection, icon, okOption, cancelOption, renderer)); } /** * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog * @param question * The Dialog is able to show a question to the user. * @return * @throws DialogCanceledException * @throws DialogClosedException */ public int showConfirmDialog(final int flag, final String question) throws DialogClosedException, DialogCanceledException { return this.showConfirmDialog(flag, APPWORKUTILS.T.DIALOG_CONFIRMDIALOG_TITLE(), question, Dialog.getIconByText(question), null, null); } /** * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog * @param title * The Dialog's Window Title * @param question * The Dialog is able to show a question to the user. * @return * @throws DialogCanceledException * @throws DialogClosedException */ public int showConfirmDialog(final int flag, final String title, final String question) throws DialogClosedException, DialogCanceledException { return this.showConfirmDialog(flag, title, question, Dialog.getIconByText(title + question), null, null); } /** * Requests a ConfirmDialog * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog * @param title * The Dialog's Window Title * @param message * The Dialog is able to show a message to the user * @param icon * The dialog is able to display an Icon If this is null, the * dialog might select an Icon derived from the message and title * text * @param okOption * Text for OK Button [null for default] Text for OK Button [null * for default] * @param cancelOption * Text for Cancel Button [null for default] Text for cancel * Button [null for default] * @return * @throws DialogCanceledException * @throws DialogClosedException */ public int showConfirmDialog(final int flag, final String title, final String message, final ImageIcon tmpicon, final String okOption, final String cancelOption) throws DialogClosedException, DialogCanceledException { if ((flag & Dialog.LOGIC_BYPASS) > 0) { return 0; } final ImageIcon icon; if (tmpicon == null) { icon = Dialog.getIconByText(title + message); } else { icon = tmpicon; } return this.showDialog(new ConfirmDialog(flag, title, message, icon, okOption, cancelOption)); } /** * note: showdialog must not call init itself!! * * @param <T> * @param dialog * @return * @throws DialogClosedException * @throws DialogCanceledException */ public <T> T showDialog(final AbstractDialog<T> dialog) throws DialogClosedException, DialogCanceledException { if (dialog == null) { return null; } final T ret = new EDTHelper<T>() { @Override public T edtRun() { dialog.displayDialog(); return dialog.getReturnValue(); } }.getReturnValue(); final int mask = dialog.getReturnmask(); if (BinaryLogic.containsSome(mask, Dialog.RETURN_CLOSED)) { throw new DialogClosedException(mask); } if (BinaryLogic.containsSome(mask, Dialog.RETURN_CANCEL)) { throw new DialogCanceledException(mask); } return ret; } public int showErrorDialog(final String s) { try { try { return this.showConfirmDialog(Dialog.BUTTONS_HIDE_CANCEL | Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN, APPWORKUTILS.T.DIALOG_ERROR_TITLE(), s, ImageProvider.getImageIcon(Dialog.ICON_ERROR, 32, 32, true), null, null); } catch (final DialogClosedException e) { return Dialog.RETURN_CLOSED; } catch (final DialogCanceledException e) { return Dialog.RETURN_CANCEL; } } catch (final IOException e) { e.printStackTrace(); } return 0; } /** * @param string * @param message * @param e */ public int showExceptionDialog(final String title, final String message, final Throwable e) { try { final ExceptionDialog dialog = new ExceptionDialog(Dialog.LOGIC_DONT_SHOW_AGAIN_DELETE_ON_EXIT | Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN | Dialog.BUTTONS_HIDE_CANCEL, title, message, e, null, null); this.showDialog(dialog); } catch (final DialogClosedException e1) { return Dialog.RETURN_CLOSED; } catch (final DialogCanceledException e1) { return Dialog.RETURN_CANCEL; } return 0; } public File[] showFileChooser(final String id, final String title, final FileChooserSelectionMode fileSelectionMode, final FileFilter fileFilter, final boolean multiSelection, final FileChooserType dialogType, final File preSelect) throws DialogCanceledException, DialogClosedException { final int[] maskWrapper = new int[1]; final File[] ret = new EDTHelper<File[]>() { @Override public File[] edtRun() { for (int tried = 0; tried < 2; tried++) { try { if (Dialog.ShellFolderIDWorkaround) { UIManager.put("FileChooser.useShellFolder", false); } else { UIManager.put("FileChooser.useShellFolder", true); } UIManager.put("FileChooser.homeFolderToolTipText", APPWORKUTILS.T.DIALOG_FILECHOOSER_TOOLTIP_HOMEFOLDER()); UIManager.put("FileChooser.newFolderToolTipText", APPWORKUTILS.T.DIALOG_FILECHOOSER_TOOLTIP_NEWFOLDER()); UIManager.put("FileChooser.upFolderToolTipText", APPWORKUTILS.T.DIALOG_FILECHOOSER_TOOLTIP_UPFOLDER()); UIManager.put("FileChooser.detailsViewButtonToolTipText", APPWORKUTILS.T.DIALOG_FILECHOOSER_TOOLTIP_DETAILS()); UIManager.put("FileChooser.listViewButtonToolTipText", APPWORKUTILS.T.DIALOG_FILECHOOSER_TOOLTIP_LIST()); final JFileChooser fc = new JFileChooser(); if (Dialog.ShellFolderIDWorkaround) { fc.putClientProperty("FileChooser.useShellFolder", false); } else { fc.putClientProperty("FileChooser.useShellFolder", true); } if (title != null) { fc.setDialogTitle(title); } boolean allowFilePreview = true; if (fileSelectionMode != null) { fc.setFileSelectionMode(fileSelectionMode.getId()); if (fileSelectionMode.getId() == FileChooserSelectionMode.DIRECTORIES_ONLY.getId()) { allowFilePreview = false; } } if (fileFilter != null) { fc.setFileFilter(fileFilter); } if (multiSelection && (dialogType == null || dialogType.getId() == FileChooserType.SAVE_DIALOG.getId())) { fc.setMultiSelectionEnabled(true); } else { fc.setMultiSelectionEnabled(false); } if (dialogType != null) { fc.setDialogType(dialogType.getId()); if (dialogType.getId() != FileChooserType.OPEN_DIALOG.getId()) { allowFilePreview = false; } } if (allowFilePreview) { fc.setAccessory(new FilePreview(fc)); } /* preSelection */ File preSelection = preSelect; if (preSelection == null && JSonStorage.getStorage("FILECHOOSER").get("LASTSELECTION_" + id, (String) null) != null) { preSelection = new File(JSonStorage.getStorage("FILECHOOSER").get("LASTSELECTION_" + id, (String) null)); Log.L.info("Preselection: " + id + ": " + JSonStorage.getStorage("FILECHOOSER").get("LASTSELECTION_" + id, (String) null)); } else { Log.L.info("Given Preselection: " + preSelection); } while (preSelection != null) { if (!preSelection.exists() && dialogType != null && dialogType.getId() == FileChooserType.OPEN_DIALOG.getId()) { /* file does not exist, try ParentFile */ preSelection = preSelection.getParentFile(); } else { if (preSelection.isDirectory()) { fc.setCurrentDirectory(preSelection); /* * we have to setSelectedFile here too, so * the folder is preselected */ /* * only preselect folder in case of * savedialog */ if (dialogType != null && (dialogType.getId() == FileChooserType.SAVE_DIALOG.getId() || dialogType == FileChooserType.OPEN_DIALOG_WITH_PRESELECTION)) { fc.setSelectedFile(preSelection); } } else { fc.setCurrentDirectory(preSelection.getParentFile()); /* only preselect file in savedialog */ if (dialogType != null && (dialogType.getId() == FileChooserType.SAVE_DIALOG.getId() || dialogType == FileChooserType.OPEN_DIALOG_WITH_PRESELECTION)) { if (fileSelectionMode != null) { if (fileSelectionMode.getId() == FileChooserSelectionMode.DIRECTORIES_ONLY.getId()) { fc.setSelectedFile(preSelection.getParentFile()); } else { fc.setSelectedFile(preSelection); } } } } break; } } if (dialogType == null || dialogType.getId() == FileChooserType.OPEN_DIALOG.getId()) { switch (maskWrapper[0] = fc.showOpenDialog(Dialog.this.getParentWindow())) { case JFileChooser.APPROVE_OPTION: if (multiSelection) { final ArrayList<File> rets = new ArrayList<File>(); for (File ret : fc.getSelectedFiles()) { ret = Dialog.this.validateFileType(ret, fileSelectionMode.getId(), false); if (ret != null) { rets.add(ret); } } if (rets.size() > 0) { final File[] files = rets.toArray(new File[rets.size()]); final File first = files[0]; if (first != null) { JSonStorage.getStorage("FILECHOOSER").put("LASTSELECTION_" + id, first.getAbsolutePath()); } return files; } else { return null; } } File ret = fc.getSelectedFile(); /* * validate selectedFile against * fileSelectionMode */ ret = Dialog.this.validateFileType(ret, fileSelectionMode.getId(), false); if (ret != null) { JSonStorage.getStorage("FILECHOOSER").put("LASTSELECTION_" + id, ret.getAbsolutePath()); return new File[] { ret }; } else { return null; } } } else if (dialogType.getId() == FileChooserType.SAVE_DIALOG.getId()) { if ((maskWrapper[0] = fc.showSaveDialog(Dialog.this.getParentWindow())) == JFileChooser.APPROVE_OPTION) { File ret = fc.getSelectedFile(); /* * validate selectedFile against * fileSelectionMode */ ret = Dialog.this.validateFileType(ret, fileSelectionMode.getId(), true); if (ret != null) { JSonStorage.getStorage("FILECHOOSER").put("LASTSELECTION_" + id, ret.getAbsolutePath()); return new File[] { ret }; } else { return null; } } } return null; } catch (final Exception e) { if (e != null && e.getMessage() != null && e.getMessage().contains("shell") && !Dialog.ShellFolderIDWorkaround) { Log.L.info("Enabling Workaround for \"Could not get shell folder ID list\""); Dialog.ShellFolderIDWorkaround = true; } else { Log.exception(e); return null; } } } return null; } }.getReturnValue(); if (maskWrapper[0] == JFileChooser.CANCEL_OPTION) { throw new DialogCanceledException(Dialog.RETURN_CANCEL); } if (maskWrapper[0] == JFileChooser.ERROR_OPTION) { throw new DialogClosedException(Dialog.RETURN_CLOSED); } return ret; } /** * @Deprecated Use * {@link #showFileChooser(String, String, FileChooserSelectionMode, FileFilter, boolean, FileChooserType, File)} * instead * @param id * @param title * @param fileSelectionMode * @param fileFilter * @param multiSelection * @param dialogType * @param preSelect * @return * @throws DialogClosedException * @throws DialogCanceledException */ @Deprecated public File[] showFileChooser(final String id, final String title, final int fileSelectionMode, final FileFilter fileFilter, final boolean multiSelection, final int dialogType, final File preSelect) throws DialogCanceledException, DialogClosedException { FileChooserSelectionMode fsm = null; for (final FileChooserSelectionMode f : FileChooserSelectionMode.values()) { if (f.getId() == fileSelectionMode) { fsm = f; break; } } FileChooserType fct = null; for (final FileChooserType f : FileChooserType.values()) { if (f.getId() == dialogType) { fct = f; break; } } return this.showFileChooser(id, title, fsm, fileFilter, multiSelection, fct, preSelect); } /** * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog flag * @param question * The Dialog is able to show a question to the user. question * @param defaultvalue * defaultvalue * @return * @throws DialogCanceledException * @throws DialogClosedException */ public String showInputDialog(final int flag, final String question, final String defaultvalue) throws DialogClosedException, DialogCanceledException { return this.showInputDialog(flag, APPWORKUTILS.T.DIALOG_INPUT_TITLE(), question, defaultvalue, Dialog.getIconByText(question), null, null); } /** * Requests in Inputdialog. * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog * @param title * The Dialog's Window Title * @param message * The Dialog is able to show a message to the user * @param defaultMessage * @param icon * The dialog is able to display an Icon If this is null, the * dialog might select an Icon derived from the message and title * text * @param okOption * Text for OK Button [null for default] * @param cancelOption * Text for Cancel Button [null for default] * @return * @throws DialogCanceledException * @throws DialogClosedException */ public String showInputDialog(final int flag, final String title, final String message, final String defaultMessage, final ImageIcon icon, final String okOption, final String cancelOption) throws DialogClosedException, DialogCanceledException { if ((flag & Dialog.LOGIC_BYPASS) > 0) { return defaultMessage; } return this.showDialog(new InputDialog(flag, title, message, defaultMessage, icon, okOption, cancelOption)); } /** * * @param message * The Dialog is able to show a message to the user * @return * @throws DialogCanceledException * @throws DialogClosedException */ public String showInputDialog(final String message) throws DialogClosedException, DialogCanceledException { return this.showInputDialog(0, message, null); } /** * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog * @param message * The Dialog is able to show a message to the user * @throws DialogCanceledException * @throws DialogClosedException */ public void showMessageDialog(final int flag, final String message) { this.showMessageDialog(flag, APPWORKUTILS.T.DIALOG_MESSAGE_TITLE(), message); } /** * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog * @param title * The Dialog's Window Title * @param message * The Dialog is able to show a message to the user * @throws DialogCanceledException * @throws DialogClosedException */ public void showMessageDialog(final int flag, final String title, final String message) { try { this.showConfirmDialog(Dialog.BUTTONS_HIDE_CANCEL | flag, title, message, Dialog.getIconByText(title + message), null, null); } catch (final DialogClosedException e) { } catch (final DialogCanceledException e) { } } /** * * @param message * The Dialog is able to show a message to the user * @throws DialogCanceledException * @throws DialogClosedException */ public void showMessageDialog(final String message) { this.showMessageDialog(0, APPWORKUTILS.T.DIALOG_MESSAGE_TITLE(), message); } /** * * @param title * The Dialog's Window Title * @param message * The Dialog is able to show a message to the user * @throws DialogCanceledException * @throws DialogClosedException */ public void showMessageDialog(final String title, final String message) { this.showMessageDialog(0, title, message); } /** * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog flag * @param question * The Dialog is able to show 3 Passwordfields to the user. * question * @param defaultvalue * defaultvalue * @return * @throws DialogCanceledException * @throws DialogClosedException */ public String showPasswordDialog(final int flag, final String question, final String defaultvalue) throws DialogClosedException, DialogCanceledException { return this.showPasswordDialog(flag, APPWORKUTILS.T.DIALOG_PASSWORD_TITLE(), question, defaultvalue, Dialog.getIconByText(question), null, null); } /** * Requests in MultiInputdialog. * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog * @param title * The Dialog's Window Title * @param message * The Dialog is able to show a message to the user * @param defaultMessage * @param icon * The dialog is able to display an Icon If this is null, the * dialog might select an Icon derived from the message and title * text * @param okOption * Text for OK Button [null for default] * @param cancelOption * Text for Cancel Button [null for default] * @return * @throws DialogCanceledException * @throws DialogClosedException */ protected String showPasswordDialog(final int flag, final String title, final String message, final String defaultMessage, final ImageIcon icon, final String okOption, final String cancelOption) throws DialogClosedException, DialogCanceledException { if ((flag & Dialog.LOGIC_BYPASS) > 0) { return defaultMessage; } return this.showDialog(new PasswordDialog(flag, title, message, icon, okOption, cancelOption)); } /** * * @param message * The Dialog is able to show a message to the user * @return * @throws DialogCanceledException * @throws DialogClosedException */ public String showPasswordDialog(final String message) throws DialogClosedException, DialogCanceledException { return this.showPasswordDialog(0, message, null); } /** * * @param title * The Dialog's Window Title * @param message * The Dialog is able to show a message to the user * @param def * @return * @throws DialogCanceledException * @throws DialogClosedException */ public String showTextAreaDialog(final String title, final String message, final String def) throws DialogClosedException, DialogCanceledException { return this.showDialog(new TextAreaDialog(title, message, def)); } /** * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog flag * @param question * The Dialog is able to show a slider to the user. question * @param defaultvalue * defaultvalue * @param min * Min slider value * @param max * Max slider value * @param step * slider step * @param valueConverter * TODO * @return * @throws DialogCanceledException * @throws DialogClosedException */ public long showValueDialog(final int flag, final String question, final long defaultvalue, final long min, final long max, final long step, final ValueConverter valueConverter) throws DialogClosedException, DialogCanceledException { return this.showValueDialog(flag, APPWORKUTILS.T.DIALOG_SLIDER_TITLE(), question, defaultvalue, Dialog.getIconByText(question), null, null, min, max, step, valueConverter); } /** * Requests in ValueDialog. * * @param flag * see {@link Dialog} - Flags. There are various flags to * customize the dialog * @param title * The Dialog's Window Title * @param message * The Dialog is able to show a message to the user * @param defaultMessage * @param icon * The dialog is able to display an Icon If this is null, the * dialog might select an Icon derived from the message and title * text * @param okOption * Text for OK Button [null for default] * @param cancelOption * Text for Cancel Button [null for default] * @param min * Min slider value * @param max * Max slider value * @param step * slider step * @param valueConverter * @return * @throws DialogCanceledException * @throws DialogClosedException */ protected long showValueDialog(final int flag, final String title, final String message, final long defaultMessage, final ImageIcon icon, final String okOption, final String cancelOption, final long min, final long max, final long step, final ValueConverter valueConverter) throws DialogClosedException, DialogCanceledException { if ((flag & Dialog.LOGIC_BYPASS) > 0) { return defaultMessage; } return this.showDialog(new ValueDialog(flag, title, message, icon, okOption, cancelOption, defaultMessage, min, max, step, valueConverter)); } private File validateFileType(final File ret, final Integer fileSelectionMode, final boolean mkdir) { if (ret == null) { return null; } if (fileSelectionMode != null) { if (fileSelectionMode == JFileChooser.DIRECTORIES_ONLY) { if (ret.isFile()) { /* * is file, we need parent folder here */ return ret.getParentFile(); } else if (!ret.exists() && mkdir) { /* * folder but it does not exist yet, we create it */ ret.mkdirs(); ret.mkdir(); } else if (!ret.exists()) { return null; } } else if (fileSelectionMode == JFileChooser.FILES_ONLY) { if (ret.isDirectory()) { /* * we return null cause directory is not a file */ return null; } } } return ret; } }
package org.broad.igv.data; import org.apache.log4j.Logger; import org.broad.igv.Globals; import org.broad.igv.feature.Chromosome; import org.broad.igv.feature.LocusScore; import org.broad.igv.feature.genome.Genome; import org.broad.igv.tdf.Accumulator; import org.broad.igv.track.WindowFunction; import org.broad.igv.ui.panel.FrameManager; import org.broad.igv.util.collections.LRUCache; import java.util.*; /** * @author jrobinso */ public abstract class AbstractDataSource implements DataSource { private static Logger log = Logger.getLogger(AbstractDataSource.class); // DataManager dataManager; boolean cacheSummaryTiles = true; WindowFunction windowFunction = WindowFunction.mean; LRUCache<String, SummaryTile> summaryTileCache = new LRUCache(this, 10); protected Genome genome; public AbstractDataSource(Genome genome) { this.genome = genome; } // abstract protected TrackType getTrackType(); /** * Return "raw" (i.e. not summarized) data for the specified interval. * * @param chr * @param startLocation * @param endLocation * @return */ abstract protected DataTile getRawData(String chr, int startLocation, int endLocation); /** * Return the precomputed summary tiles for the given locus and zoom level. If * there are non return null. * * @param chr * @param startLocation * @param endLocation * @param zoom * @return */ abstract protected List<LocusScore> getPrecomputedSummaryScores(String chr, int startLocation, int endLocation, int zoom); public int getChrLength(String chr) { if (chr.equals(Globals.CHR_ALL)) { return (int) (genome.getLength() / 1000); } else { Chromosome c = genome.getChromosome(chr); return c == null ? 0 : c.getLength(); } } /** * Refresh the underlying data. Default implementation does nothing, subclasses * can override * * @param timestamp */ public void refreshData(long timestamp) { // ignore -- } /** * Return the longest feature in the dataset for the given chromosome. This * is needed when computing summary data for a region. * <p/> * TODO - This default implementaiton is crude and should be overriden by subclasses. * * @param chr * @return */ public abstract int getLongestFeature(String chr); // if (getTrackType() == TrackType.GENE_EXPRESSION) { // String genomeId = GenomeManager.getInstance().getGenomeId(); // GeneManager gm = GeneManager.getGeneManager(genomeId); // return (gm == null) ? 1000000 : gm.getLongestGeneLength(chr); // } else { // return 1000; public List<LocusScore> getSummaryScoresForRange(String chr, int startLocation, int endLocation, int zoom) { List<LocusScore> scores = getPrecomputedSummaryScores(chr, startLocation, endLocation, zoom); if (scores != null) { return scores; } List<SummaryTile> tiles = getSummaryTilesForRange(chr, startLocation, endLocation, zoom); scores = new ArrayList(tiles.size() * 700); for (SummaryTile tile : tiles) { scores.addAll(tile.getScores()); } //FeatureUtils.sortFeatureList(summaryScores); return scores; } private List<SummaryTile> getSummaryTilesForRange(String chr, int startLocation, int endLocation, int zReq) { int chrLength = getChrLength(chr); if (chrLength == 0) { return Collections.emptyList(); } endLocation = Math.min(endLocation, chrLength); int adjustedStart = Math.max(0, startLocation); int adjustedEnd = Math.min(chrLength, endLocation); if (cacheSummaryTiles && !FrameManager.isGeneListMode() && !FrameManager.isExomeMode()) { // By definition there are 2^z tiles per chromosome, and 700 bins per tile, where z is the zoom level. //int maxZoom = (int) (Math.log(chrLength/700) / Globals.log2) + 1; //int z = Math.min(zReq, maxZoom); int z = zReq; int virtualTileCount = (int) Math.pow(2, z); double tileWidth = ((double) chrLength) / virtualTileCount; int startTile = (int) (adjustedStart / tileWidth); int endTile = (int) (Math.min(chrLength, adjustedEnd) / tileWidth) + 1; List<SummaryTile> tiles = null; tiles = new ArrayList(endTile - startTile + 1); for (int t = startTile; t <= endTile; t++) { int tileStart = (int) (t * tileWidth); int tileEnd = Math.min(chrLength, (int) ((t + 1) * tileWidth)); String key = chr + "_" + z + "_" + t + getWindowFunction(); SummaryTile summaryTile = summaryTileCache.get(key); if (summaryTile == null) { summaryTile = computeSummaryTile(chr, t, tileStart, tileEnd, 700); if (cacheSummaryTiles && !FrameManager.isGeneListMode()) { synchronized (summaryTileCache) { summaryTileCache.put(key, summaryTile); } } } if (summaryTile != null) { tiles.add(summaryTile); } } return tiles; } else { SummaryTile summaryTile = computeSummaryTile(chr, 0, startLocation, endLocation, 700); return Arrays.asList(summaryTile); } } /** * Note: Package scope used so this method can be unit tested * * @param chr * @param tileNumber * @param startLocation * @param endLocation * @param nBins * @return */ SummaryTile computeSummaryTile(String chr, int tileNumber, int startLocation, int endLocation, int nBins) { // TODO -- we should use an index here int longestGene = getLongestFeature(chr); int adjustedStart = Math.max(startLocation - longestGene, 0); DataTile rawTile = getRawData(chr, adjustedStart, endLocation); SummaryTile tile = null; if ((rawTile != null) && !rawTile.isEmpty() && nBins > 0) { int[] starts = rawTile.getStartLocations(); int[] ends = rawTile.getEndLocations(); float[] values = rawTile.getValues(); String[] features = rawTile.getFeatureNames(); tile = new SummaryTile(); if (windowFunction == WindowFunction.none) { for (int i = 0; i < starts.length; i++) { int s = starts[i]; int e = ends == null ? s + 1 : Math.max(s + 1, ends[i]); if (e < startLocation) { continue; } else if (s >= endLocation) { break; } String probeName = features == null ? null : features[i]; float v = values[i]; BasicScore score = new NamedScore(s, e, v, probeName); tile.addScore(score); } } else { float normalizationFactor = 1.0f; List<LocusScore> scores = new ArrayList(nBins); double scale = (double) (endLocation - startLocation) / nBins; Accumulator accumulator = new Accumulator(windowFunction, 5); int accumulatedStart = -1; int accumulatedEnd = -1; int lastEndBin = 0; int size = starts.length; // Loop through and bin scores for this interval. for (int i = 0; i < size; i++) { int true_end = ends == null ? starts[i] + 1 : ends[i]; float v = values[i] * normalizationFactor; if (starts[i] >= endLocation) { break; // We're beyond the end of the requested interval } else if (true_end <= startLocation || Float.isNaN(v)) { //Not yet to interval, or not a number continue; } // Bound feature at interval, other "piece" will be in another tile. int s = Math.max(startLocation, starts[i]); int e = Math.min(endLocation, true_end); String probeName = features == null ? null : features[i]; // Compute bin numbers, relative to start of this tile int endBin = (int) ((e - startLocation) / scale); int startBin = (int) ((s - startLocation) / scale); // If this feature spans multiple bins, or extends beyond last end bin, record if (endBin > lastEndBin || endBin > startBin) { if (accumulator.hasData()) { scores.add(getCompositeScore(accumulator, accumulatedStart, accumulatedEnd)); accumulator = new Accumulator(windowFunction, 5); } } if (endBin > startBin) { scores.add(new NamedScore(s, e, v, probeName)); } else { if (!accumulator.hasData()) accumulatedStart = s; accumulatedEnd = e; accumulator.add(e - s, v, probeName); } lastEndBin = endBin; } // Cleanup if (accumulator.hasData()) { scores.add(getCompositeScore(accumulator, accumulatedStart, accumulatedEnd)); } tile.addAllScores(scores); } } return tile; } private LocusScore getCompositeScore(Accumulator accumulator, int accumulatedStart, int accumulatedEnd) { LocusScore ls; if (accumulator.getNpts() == 1) { ls = new NamedScore(accumulatedStart, accumulatedEnd, accumulator.getRepData()[0], accumulator.getRepProbes()[0]); } else { float value = accumulator.getValue(); ls = new CompositeScore(accumulatedStart, accumulatedEnd, value, accumulator.getRepData(), accumulator.getRepProbes(), windowFunction); } return ls; } /** * Return true if the data has been log normalized. * * @return */ public boolean isLogNormalized() { return true; } public void setWindowFunction(WindowFunction statType) { this.windowFunction = statType; this.summaryTileCache.clear(); } public WindowFunction getWindowFunction() { return windowFunction; } // TODO -- get window functions dynamically from data static List<WindowFunction> wfs = new ArrayList(); static { wfs.add(WindowFunction.min); wfs.add(WindowFunction.percentile10); wfs.add(WindowFunction.median); wfs.add(WindowFunction.mean); wfs.add(WindowFunction.percentile90); wfs.add(WindowFunction.max); } public Collection<WindowFunction> getAvailableWindowFunctions() { return wfs; } }
package org.broad.igv.sam; import net.sf.samtools.util.CloseableIterator; import org.apache.log4j.Logger; import org.broad.igv.Globals; import org.broad.igv.PreferenceManager; import org.broad.igv.feature.SpliceJunctionFeature; import org.broad.igv.sam.reader.AlignmentReader; import org.broad.igv.sam.reader.ReadGroupFilter; import org.broad.igv.ui.IGV; import org.broad.igv.ui.util.MessageUtils; import org.broad.igv.ui.util.ProgressMonitor; import org.broad.igv.util.ObjectCache; import org.broad.igv.util.RuntimeUtils; import org.broad.igv.util.collections.LRUCache; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.*; /** * A wrapper for an AlignmentQueryReader that caches query results * * @author jrobinso */ public class AlignmentTileLoader { private static Logger log = Logger.getLogger(AlignmentTileLoader.class); private static Set<WeakReference<AlignmentTileLoader>> activeLoaders = Collections.synchronizedSet(new HashSet()); /** * Flag to mark a corrupt index. Without this attempted reads will continue in an infinite loop */ private boolean corruptIndex = false; private AlignmentReader reader; private boolean cancel = false; private boolean pairedEnd = false; static void cancelReaders() { for (WeakReference<AlignmentTileLoader> readerRef : activeLoaders) { AlignmentTileLoader reader = readerRef.get(); if (reader != null) { reader.cancel = true; } } log.debug("Readers canceled"); activeLoaders.clear(); } public AlignmentTileLoader(AlignmentReader reader) { this.reader = reader; activeLoaders.add(new WeakReference<AlignmentTileLoader>(this)); } public void close() throws IOException { reader.close(); } public List<String> getSequenceNames() { return reader.getSequenceNames(); } public CloseableIterator<Alignment> iterator() { return reader.iterator(); } public boolean hasIndex() { return reader.hasIndex(); } AlignmentTile loadTile(String chr, int start, int end, SpliceJunctionHelper spliceJunctionHelper, AlignmentDataManager.DownsampleOptions downsampleOptions, Map<String, PEStats> peStats, AlignmentTrack.BisulfiteContext bisulfiteContext, ProgressMonitor monitor) { AlignmentTile t = new AlignmentTile(start, end, spliceJunctionHelper, downsampleOptions, bisulfiteContext); //assert (tiles.size() > 0); if (corruptIndex) { return t; } final PreferenceManager prefMgr = PreferenceManager.getInstance(); boolean filterFailedReads = prefMgr.getAsBoolean(PreferenceManager.SAM_FILTER_FAILED_READS); boolean filterSecondaryAlignments = prefMgr.getAsBoolean(PreferenceManager.SAM_FILTER_SECONDARY_ALIGNMENTS); ReadGroupFilter filter = ReadGroupFilter.getFilter(); boolean showDuplicates = prefMgr.getAsBoolean(PreferenceManager.SAM_SHOW_DUPLICATES); int qualityThreshold = prefMgr.getAsInt(PreferenceManager.SAM_QUALITY_THRESHOLD); CloseableIterator<Alignment> iter = null; //log.debug("Loading : " + start + " - " + end); int alignmentCount = 0; WeakReference<AlignmentTileLoader> ref = new WeakReference(this); try { ObjectCache<String, Alignment> mappedMates = new ObjectCache<String, Alignment>(1000); ObjectCache<String, Alignment> unmappedMates = new ObjectCache<String, Alignment>(1000); activeLoaders.add(ref); iter = reader.query(chr, start, end, false); while (iter != null && iter.hasNext()) { if (cancel) { return t; } Alignment record = iter.next(); // Set mate sequence of unmapped mates // Put a limit on the total size of this collection. String readName = record.getReadName(); if (record.isPaired()) { pairedEnd = true; if (record.isMapped()) { if (!record.getMate().isMapped()) { // record is mapped, mate is not Alignment mate = unmappedMates.get(readName); if (mate == null) { mappedMates.put(readName, record); } else { record.setMateSequence(mate.getReadSequence()); unmappedMates.remove(readName); mappedMates.remove(readName); } } } else if (record.getMate().isMapped()) { // record not mapped, mate is Alignment mappedMate = mappedMates.get(readName); if (mappedMate == null) { unmappedMates.put(readName, record); } else { mappedMate.setMateSequence(record.getReadSequence()); unmappedMates.remove(readName); mappedMates.remove(readName); } } } if (!record.isMapped() || (!showDuplicates && record.isDuplicate()) || (filterFailedReads && record.isVendorFailedRead()) || (filterSecondaryAlignments && !record.isPrimary()) || record.getMappingQuality() < qualityThreshold || (filter != null && filter.filterAlignment(record))) { continue; } t.addRecord(record); alignmentCount++; int interval = Globals.isTesting() ? 100000 : 1000; if (alignmentCount % interval == 0) { if (cancel) return null; String msg = "Reads loaded: " + alignmentCount; MessageUtils.setStatusBarMessage(msg); if(monitor != null){ monitor.updateStatus(msg); } if (memoryTooLow()) { if(monitor != null) monitor.fireProgressChange(100); cancelReaders(); t.finish(); return t; // <= TODO need to cancel all readers } } // Update pe stats if (peStats != null && record.isPaired() && record.isProperPair()) { String lb = record.getLibrary(); if (lb == null) lb = "null"; PEStats stats = peStats.get(lb); if (stats == null) { stats = new PEStats(lb); peStats.put(lb, stats); } stats.update(record); } } // End iteration over alignments // Compute peStats if (peStats != null) { // TODO -- something smarter re the percentiles. For small samples these will revert to min and max double minPercentile = prefMgr.getAsFloat(PreferenceManager.SAM_MIN_INSERT_SIZE_PERCENTILE); double maxPercentile = prefMgr.getAsFloat(PreferenceManager.SAM_MAX_INSERT_SIZE_PERCENTILE); for (PEStats stats : peStats.values()) { stats.compute(minPercentile, maxPercentile); } } // Clean up any remaining unmapped mate sequences for (String mappedMateName : mappedMates.getKeys()) { Alignment mappedMate = mappedMates.get(mappedMateName); Alignment mate = unmappedMates.get(mappedMate.getReadName()); if (mate != null) { mappedMate.setMateSequence(mate.getReadSequence()); } } t.finish(); return t; } catch (java.nio.BufferUnderflowException e) { // This almost always indicates a corrupt BAM index, or less frequently a corrupt bam file corruptIndex = true; MessageUtils.showMessage("<html>Error encountered querying alignments: " + e.toString() + "<br>This is often caused by a corrupt index file."); return null; } catch (Exception e) { log.error("Error loading alignment data", e); MessageUtils.showMessage("<html>Error encountered querying alignments: " + e.toString()); return null; } finally { // reset cancel flag. It doesn't matter how we got here, the read is complete and this flag is reset // for the next time cancel = false; activeLoaders.remove(ref); if(monitor != null){ monitor.fireProgressChange(100); } if (iter != null) { iter.close(); } if (!Globals.isHeadless()) { IGV.getInstance().resetStatusMessage(); } } } private static synchronized boolean memoryTooLow() { if (RuntimeUtils.getAvailableMemoryFraction() < 0.2) { LRUCache.clearCaches(); System.gc(); if (RuntimeUtils.getAvailableMemoryFraction() < 0.2) { String msg = "Memory is low, reading terminating."; MessageUtils.showMessage(msg); return true; } } return false; } /** * Does this file contain paired end data? Assume not until proven otherwise. */ public boolean isPairedEnd() { return pairedEnd; } public Set<String> getPlatforms() { return reader.getPlatforms(); } /** * Caches alignments, coverage, splice junctions, and downsampled intervals */ public static class AlignmentTile { private boolean loaded = false; private int end; private int start; private AlignmentCounts counts; private List<Alignment> alignments; private List<DownsampledInterval> downsampledIntervals; private SpliceJunctionHelper spliceJunctionHelper; private boolean isPairedEnd; private static final Random RAND = new Random(); private boolean downsample; private int samplingWindowSize; private int samplingDepth; private int currentSamplingWindowStart = -1; private int curEffSamplingWindowDepth = 0; //Although not strictly necessary, we keep track of the currentDownsampledInterval //for easy incrementing private DownsampledInterval currentDownsampledInterval; /** * We keep a data structure of alignments which can efficiently * look up by string (read name) or index (for random replacement) */ IndexableMap<String, Alignment> imAlignments; private int downsampledCount = 0; private int offset = 0; AlignmentTile(int start, int end, SpliceJunctionHelper spliceJunctionHelper, AlignmentDataManager.DownsampleOptions downsampleOptions, AlignmentTrack.BisulfiteContext bisulfiteContext) { this.start = start; this.end = end; this.downsampledIntervals = new ArrayList<DownsampledInterval>(); long seed = System.currentTimeMillis(); //System.out.println("seed: " + seed); RAND.setSeed(seed); // Use a sparse array for large regions (> 10 mb) if ((end - start) > 10000000) { this.counts = new SparseAlignmentCounts(start, end, bisulfiteContext); } else { this.counts = new DenseAlignmentCounts(start, end, bisulfiteContext); } // Set the max depth, and the max depth of the sampling bucket. if (downsampleOptions == null) { // Use default settings (from preferences) downsampleOptions = new AlignmentDataManager.DownsampleOptions(); } this.downsample = downsampleOptions.isDownsample(); this.samplingWindowSize = downsampleOptions.getSampleWindowSize(); this.samplingDepth = Math.max(1, downsampleOptions.getMaxReadCount()); this.spliceJunctionHelper = spliceJunctionHelper; if(this.downsample){ imAlignments = new IndexableMap<String, Alignment>(8000); }else{ alignments = new ArrayList<Alignment>(16000); } } public int getStart() { return start; } public void setStart(int start) { this.start = start; } int ignoredCount = 0; // <= just for debugging /** * Add an alignment record to this tile. This record is not necessarily retained after down-sampling. * * @param alignment */ public void addRecord(Alignment alignment) { counts.incCounts(alignment); isPairedEnd |= alignment.isPaired(); if (spliceJunctionHelper != null) { spliceJunctionHelper.addAlignment(alignment); } if (downsample) { final int alignmentStart = alignment.getAlignmentStart(); int currentSamplingBucketEnd = currentSamplingWindowStart + samplingWindowSize; if (currentSamplingWindowStart < 0 || alignmentStart >= currentSamplingBucketEnd) { setCurrentSamplingBucket(alignmentStart); } attemptAddRecordDownsampled(alignment); } else { alignments.add(alignment); } alignment.finish(); } /** * Attempt to add this alignment. The alignment is definitely added iff it's mate was added. * If we haven't seen the mate, the record is added with some probability according to * reservoir sampling * @param alignment */ private void attemptAddRecordDownsampled(Alignment alignment) { String readName = alignment.getReadName(); //A simple way to turn off the mate-checking is to replace the read name with a random string //so that there are no repeats //readName = String.format("%s%d", readName, RAND.nextInt()); //There are 3 possibilities: mate-kept, mate-rejected, mate-unknown (haven't seen, or non-paired reads) //If we kept or rejected the mate, we do the same for this one boolean hasRead = imAlignments.containsKey(readName); if(hasRead){ List<Alignment> mateAlignments = imAlignments.get(readName); boolean haveMate = false; if(mateAlignments != null){ for(Alignment al: mateAlignments){ ReadMate mate = al.getMate(); haveMate |= mate.getChr().equals(alignment.getChr()) && mate.getStart() == alignment.getStart(); } } if(haveMate){ //We keep the alignment if it's mate is kept imAlignments.append(readName, alignment); }else{ currentDownsampledInterval.incCount(); } }else{ if (curEffSamplingWindowDepth < samplingDepth) { imAlignments.append(readName, alignment); curEffSamplingWindowDepth++; } else { double samplingProb = ((double) samplingDepth) / (samplingDepth + downsampledCount + 1); if (RAND.nextDouble() < samplingProb) { int rndInt = (int) (RAND.nextDouble() * (samplingDepth - 1)); int idx = offset + rndInt; // Replace random record with this one List<Alignment> removedValues = imAlignments.replace(idx, readName, alignment); incrementDownsampledIntervals(removedValues); }else{ //Mark that record was not kept imAlignments.markNull(readName); currentDownsampledInterval.incCount(); } downsampledCount++; } } } private void setCurrentSamplingBucket(int alignmentStart) { curEffSamplingWindowDepth = 0; downsampledCount = 0; currentSamplingWindowStart = alignmentStart; offset = imAlignments.size(); int currentSamplingBucketEnd = currentSamplingWindowStart + samplingWindowSize; currentDownsampledInterval = new DownsampledInterval(alignmentStart, currentSamplingBucketEnd, 0); downsampledIntervals.add(currentDownsampledInterval); } private void incrementDownsampledIntervals(List<Alignment> removedValues) { if(removedValues == null) return; for(Alignment al: removedValues){ DownsampledInterval interval = findDownsampledInterval(al, downsampledIntervals.size() / 2); if(interval != null) interval.incCount(); } } private DownsampledInterval findDownsampledInterval(Alignment al, int startInd) { //Attempt to find by binary search DownsampledInterval curInterval = downsampledIntervals.get(startInd); if (al.getStart() >= curInterval.getStart() && al.getStart() < curInterval.getEnd()) { //Found return curInterval; } int sz = downsampledIntervals.size(); int newStart = -1; if(al.getStart() >= curInterval.getEnd()){ // startInd + (sz - startInd)/2 = (sz + startInd)/2 newStart = (sz + startInd)/2; }else{ // startInd - (startInd)/2 = startInd/2 newStart = startInd/2; } //This would be infinite regress, we give up if(newStart == startInd) return null; return findDownsampledInterval(al, newStart); } /** * Sort the alignments by start position, and filter {@code downsampledIntervals}. * This will have the same results as if no downsampling occurred, although will incur * extra computational cost * */ private void sortFilterDownsampled() { if((this.alignments == null || this.alignments.size() == 0) && this.downsample){ this.alignments = imAlignments.getAllValues(); imAlignments.clear(); } Comparator<Alignment> alignmentSorter = new Comparator<Alignment>() { public int compare(Alignment alignment, Alignment alignment1) { return alignment.getStart() - alignment1.getStart(); } }; Collections.sort(this.alignments, alignmentSorter); //Only keep the intervals for which count > 0 List<DownsampledInterval> tmp = new ArrayList<DownsampledInterval>(this.downsampledIntervals.size()); for(DownsampledInterval interval: this.downsampledIntervals){ if(interval.getCount() > 0){ tmp.add(interval); } } this.downsampledIntervals = tmp; } public List<Alignment> getAlignments() { return alignments; } public List<DownsampledInterval> getDownsampledIntervals() { return downsampledIntervals; } public void finish() { //If we downsampled, we need to sort if (downsample) { sortFilterDownsampled(); } finalizeSpliceJunctions(); counts.finish(); } public AlignmentCounts getCounts() { return counts; } private void finalizeSpliceJunctions() { if (spliceJunctionHelper != null) { spliceJunctionHelper.finish(); } } public List<SpliceJunctionFeature> getSpliceJunctionFeatures() { if(spliceJunctionHelper == null) return null; return spliceJunctionHelper.getFilteredJunctions(); } public SpliceJunctionHelper getSpliceJunctionHelper() { return spliceJunctionHelper; } /** * Map-like structure designed to be accessible both by key, and by numeric index * Multiple values are stored for each key, and a list is returned * If the key for a value is set as null, nothing can be added * * Intended to support downsampling, where if a read name is added and then removed * we don't want to add the read pair * @param <K> * @param <V> */ private class IndexableMap<K, V>{ private HashMap<K, List<V>> map; private List<K> list; IndexableMap(int size){ this.map = new HashMap<K, List<V>>(size); this.list = new ArrayList<K>(size); } public List<V> get(K key){ return map.get(key); } /** * Append a value for the specified key, unless * the current value is null. If the current value is * null, it's a no-op. * @param key * @param value * @return Whether the element was added */ public boolean append(K key, V value){ if(!map.containsKey(key)){ addNewValueToMap(key, value); return list.add(key); }else{ List<V> curList = map.get(key); if(curList == null) return false; return curList.add(value); } } public List<V> markNull(K key){ return map.put(key, null); } private void addNewValueToMap(K key, V value){ List<V> curList = new ArrayList<V>(1); curList.add(value); map.put(key, curList); } /** * Place the specified {@code key} and {@code value} in the map, * at index {@code index}. * * In the unlikely event that {@code key} is already * at {@code index}, {@code value} will be appended * @param index * @param key * @param value * @return Whether the replacement actually happened */ public List<V> replace(int index, K key, V value){ checkSize(index); K oldKey = list.get(index); if(!oldKey.equals(key)){ //Remove the old key from map, and make sure nothing else gets put there List<V> oldValue = markNull(oldKey); addNewValueToMap(key, value); list.set(index, key); return oldValue; }else{ append(key, value); return null; } } public int size(){ return list.size(); } private void checkSize(int index){ if(index >= size()){ throw new IllegalArgumentException("index " + index + " greater than current size" + size()); } } public List<V> getAllValues() { List<V> allValues = new ArrayList<V>(2*size()); for(K k: list){ allValues.addAll(map.get(k)); } return allValues; } public boolean containsKey(K key) { return map.containsKey(key); } public void clear() { map.clear(); list.clear(); } } } }
package org.connectbot.service; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.connectbot.R; import org.connectbot.TerminalView; import org.connectbot.bean.HostBean; import org.connectbot.bean.PortForwardBean; import org.connectbot.bean.PubkeyBean; import org.connectbot.bean.SelectionArea; import org.connectbot.util.HostDatabase; import org.connectbot.util.PreferenceConstants; import org.connectbot.util.PubkeyDatabase; import org.connectbot.util.PubkeyUtils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.graphics.Bitmap.Config; import android.graphics.Paint.FontMetrics; import android.text.ClipboardManager; import android.util.Log; import android.view.KeyCharacterMap; import android.view.KeyEvent; import android.view.View; import android.view.View.OnKeyListener; import com.trilead.ssh2.Connection; import com.trilead.ssh2.ConnectionInfo; import com.trilead.ssh2.ConnectionMonitor; import com.trilead.ssh2.DynamicPortForwarder; import com.trilead.ssh2.InteractiveCallback; import com.trilead.ssh2.KnownHosts; import com.trilead.ssh2.LocalPortForwarder; import com.trilead.ssh2.ServerHostKeyVerifier; import com.trilead.ssh2.Session; import com.trilead.ssh2.crypto.PEMDecoder; import de.mud.terminal.VDUBuffer; import de.mud.terminal.VDUDisplay; import de.mud.terminal.vt320; /** * Provides a bridge between a MUD terminal buffer and a possible TerminalView. * This separation allows us to keep the TerminalBridge running in a background * service. A TerminalView shares down a bitmap that we can use for rendering * when available. * * This class also provides SSH hostkey verification prompting, and password * prompting. */ public class TerminalBridge implements VDUDisplay, OnKeyListener, InteractiveCallback, ConnectionMonitor { public final static String TAG = TerminalBridge.class.toString(); public final static int DEFAULT_FONT_SIZE = 10; public static final String AUTH_PUBLICKEY = "publickey", AUTH_PASSWORD = "password", AUTH_KEYBOARDINTERACTIVE = "keyboard-interactive"; protected final static int AUTH_TRIES = 20; private List<PortForwardBean> portForwards = new LinkedList<PortForwardBean>(); public int color[]; public final static int COLOR_FG_STD = 7; public final static int COLOR_BG_STD = 0; protected final TerminalManager manager; public HostBean host; public final Connection connection; protected Session session; private final Paint defaultPaint; protected OutputStream stdin; protected InputStream stdout; private InputStream stderr; private Relay relay; private final String emulation; private final int scrollback; public Bitmap bitmap = null; public VDUBuffer buffer = null; private TerminalView parent = null; private final Canvas canvas = new Canvas(); private int metaState = 0; public final static int META_CTRL_ON = 0x01; public final static int META_CTRL_LOCK = 0x02; public final static int META_ALT_ON = 0x04; public final static int META_ALT_LOCK = 0x08; public final static int META_SHIFT_ON = 0x10; public final static int META_SHIFT_LOCK = 0x20; public final static int META_SLASH = 0x40; public final static int META_TAB = 0x80; // The bit mask of momentary and lock states for each public final static int META_CTRL_MASK = META_CTRL_ON | META_CTRL_LOCK; public final static int META_ALT_MASK = META_ALT_ON | META_ALT_LOCK; public final static int META_SHIFT_MASK = META_SHIFT_ON | META_SHIFT_LOCK; // All the transient key codes public final static int META_TRANSIENT = META_CTRL_ON | META_ALT_ON | META_SHIFT_ON; private boolean pubkeysExhausted = false; private boolean authenticated = false; private boolean sessionOpen = false; private boolean disconnected = false; private boolean awaitingClose = false; private boolean forcedSize = false; private int termWidth; private int termHeight; private String keymode = null; private boolean selectingForCopy = false; private final SelectionArea selectionArea; private ClipboardManager clipboard; protected KeyCharacterMap keymap = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD); public int charWidth = -1; public int charHeight = -1; private int charTop = -1; private float fontSize = -1; private final List<FontSizeChangedListener> fontSizeChangedListeners; private final List<String> localOutput; /** * Flag indicating if we should perform a full-screen redraw during our next * rendering pass. */ private boolean fullRedraw = false; public PromptHelper promptHelper; protected BridgeDisconnectedListener disconnectListener = null; protected ConnectionInfo connectionInfo; public class HostKeyVerifier implements ServerHostKeyVerifier { public boolean verifyServerHostKey(String hostname, int port, String serverHostKeyAlgorithm, byte[] serverHostKey) throws IOException { // read in all known hosts from hostdb KnownHosts hosts = manager.hostdb.getKnownHosts(); Boolean result; String matchName = String.format("%s:%d", hostname, port); String fingerprint = KnownHosts.createHexFingerprint(serverHostKeyAlgorithm, serverHostKey); String algorithmName; if ("ssh-rsa".equals(serverHostKeyAlgorithm)) algorithmName = "RSA"; else if ("ssh-dss".equals(serverHostKeyAlgorithm)) algorithmName = "DSA"; else algorithmName = serverHostKeyAlgorithm; switch(hosts.verifyHostkey(matchName, serverHostKeyAlgorithm, serverHostKey)) { case KnownHosts.HOSTKEY_IS_OK: outputLine(String.format("Verified host %s key: %s", algorithmName, fingerprint)); return true; case KnownHosts.HOSTKEY_IS_NEW: // prompt user outputLine(String.format(manager.res.getString(R.string.host_authenticity_warning), hostname)); outputLine(String.format(manager.res.getString(R.string.host_fingerprint), algorithmName, fingerprint)); result = promptHelper.requestBooleanPrompt(null, manager.res.getString(R.string.prompt_continue_connecting)); if(result == null) return false; if(result.booleanValue()) { // save this key in known database manager.hostdb.saveKnownHost(hostname, port, serverHostKeyAlgorithm, serverHostKey); } return result.booleanValue(); case KnownHosts.HOSTKEY_HAS_CHANGED: String header = String.format("@ %s @", manager.res.getString(R.string.host_verification_failure_warning_header)); char[] atsigns = new char[header.length()]; Arrays.fill(atsigns, '@'); String border = new String(atsigns); outputLine(border); outputLine(manager.res.getString(R.string.host_verification_failure_warning)); outputLine(border); outputLine(String.format(manager.res.getString(R.string.host_fingerprint), algorithmName, fingerprint)); // Users have no way to delete keys, so we'll prompt them for now. result = promptHelper.requestBooleanPrompt(null, manager.res.getString(R.string.prompt_continue_connecting)); if(result == null) return false; if(result.booleanValue()) { // save this key in known database manager.hostdb.saveKnownHost(hostname, port, serverHostKeyAlgorithm, serverHostKey); } return result.booleanValue(); default: return false; } } } /** * Create a new terminal bridge suitable for unit testing. */ public TerminalBridge() { buffer = new vt320() { @Override public void write(byte[] b) {} @Override public void write(int b) {} @Override public void sendTelnetCommand(byte cmd) {} @Override public void setWindowSize(int c, int r) {} @Override public void debug(String s) {} }; emulation = null; manager = null; defaultPaint = new Paint(); selectionArea = new SelectionArea(); scrollback = 1; localOutput = new LinkedList<String>(); fontSizeChangedListeners = new LinkedList<FontSizeChangedListener>(); connection = null; } /** * Create new terminal bridge with following parameters. We will immediately * launch thread to start SSH connection and handle any hostkey verification * and password authentication. */ public TerminalBridge(final TerminalManager manager, final HostBean host) throws IOException { this.manager = manager; this.host = host; emulation = manager.getEmulation(); scrollback = manager.getScrollback(); // create prompt helper to relay password and hostkey requests up to gui promptHelper = new PromptHelper(this); // create our default paint defaultPaint = new Paint(); defaultPaint.setAntiAlias(true); defaultPaint.setTypeface(Typeface.MONOSPACE); defaultPaint.setFakeBoldText(true); // more readable? localOutput = new LinkedList<String>(); fontSizeChangedListeners = new LinkedList<FontSizeChangedListener>(); setFontSize(DEFAULT_FONT_SIZE); // create terminal buffer and handle outgoing data // this is probably status reply information buffer = new vt320() { @Override public void debug(String s) { Log.d(TAG, s); } @Override public void write(byte[] b) { try { if (b != null && stdin != null) stdin.write(b); } catch (IOException e) { Log.e(TAG, "Problem writing outgoing data in vt320() thread", e); } } @Override public void write(int b) { try { if (stdin != null) stdin.write(b); } catch (IOException e) { Log.e(TAG, "Problem writing outgoing data in vt320() thread", e); } } // We don't use telnet sequences. @Override public void sendTelnetCommand(byte cmd) { } // We don't want remote to resize our window. @Override public void setWindowSize(int c, int r) { } @Override public void beep() { if (parent.isShown()) manager.playBeep(); else manager.sendActivityNotification(host); } }; buffer.setBufferSize(scrollback); resetColors(); buffer.setDisplay(this); selectionArea = new SelectionArea(); portForwards = manager.hostdb.getPortForwardsForHost(host); // prepare the ssh connection for opening // we perform the actual connection later in startConnection() outputLine(String.format("Connecting to %s:%d", host.getHostname(), host.getPort())); connection = new Connection(host.getHostname(), host.getPort()); connection.addConnectionMonitor(this); connection.setCompression(host.getCompression()); } /** * Spawn thread to open connection and start login process. */ protected void startConnection() { Thread connectionThread = new Thread(new Runnable() { public void run() { try { /* Uncomment when debugging SSH protocol: DebugLogger logger = new DebugLogger() { public void log(int level, String className, String message) { Log.d("SSH", message); } }; connection.enableDebugging(true, logger); */ connectionInfo = connection.connect(new HostKeyVerifier()); if (connectionInfo.clientToServerCryptoAlgorithm .equals(connectionInfo.serverToClientCryptoAlgorithm) && connectionInfo.clientToServerMACAlgorithm .equals(connectionInfo.serverToClientMACAlgorithm)) { outputLine(String.format("Using algorithm: %s %s", connectionInfo.clientToServerCryptoAlgorithm, connectionInfo.clientToServerMACAlgorithm)); } else { outputLine(String.format( "Client-to-server algorithm: %s %s", connectionInfo.clientToServerCryptoAlgorithm, connectionInfo.clientToServerMACAlgorithm)); outputLine(String.format( "Server-to-client algorithm: %s %s", connectionInfo.serverToClientCryptoAlgorithm, connectionInfo.serverToClientMACAlgorithm)); } } catch (IOException e) { Log.e(TAG, "Problem in SSH connection thread during authentication", e); // Display the reason in the text. outputLine(e.getCause().getMessage()); dispatchDisconnect(false); return; } try { // enter a loop to keep trying until authentication int tries = 0; while(!connection.isAuthenticationComplete() && tries++ < AUTH_TRIES && !disconnected) { handleAuthentication(); // sleep to make sure we dont kill system Thread.sleep(1000); } } catch(Exception e) { Log.e(TAG, "Problem in SSH connection thread during authentication", e); } } }); connectionThread.setName("Connection"); connectionThread.start(); } /** * Attempt connection with database row pointed to by cursor. * @param cursor * @return true for successful authentication * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws IOException */ private boolean tryPublicKey(PubkeyBean pubkey) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException { Object trileadKey = null; if(manager.isKeyLoaded(pubkey.getNickname())) { // load this key from memory if its already there Log.d(TAG, String.format("Found unlocked key '%s' already in-memory", pubkey.getNickname())); trileadKey = manager.getKey(pubkey.getNickname()); } else { // otherwise load key from database and prompt for password as needed String password = null; if (pubkey.isEncrypted()) { password = promptHelper.requestStringPrompt(null, String.format(manager.res.getString(R.string.prompt_pubkey_password), pubkey.getNickname())); // Something must have interrupted the prompt. if (password == null) return false; } if(PubkeyDatabase.KEY_TYPE_IMPORTED.equals(pubkey.getType())) { // load specific key using pem format trileadKey = PEMDecoder.decode(new String(pubkey.getPrivateKey()).toCharArray(), password); } else { // load using internal generated format PrivateKey privKey; try { privKey = PubkeyUtils.decodePrivate(pubkey.getPrivateKey(), pubkey.getType(), password); } catch (Exception e) { String message = String.format("Bad password for key '%s'. Authentication failed.", pubkey.getNickname()); Log.e(TAG, message, e); outputLine(message); return false; } PublicKey pubKey = PubkeyUtils.decodePublic(pubkey.getPublicKey(), pubkey.getType()); // convert key to trilead format trileadKey = PubkeyUtils.convertToTrilead(privKey, pubKey); Log.d(TAG, "Unlocked key " + PubkeyUtils.formatKey(pubKey)); } Log.d(TAG, String.format("Unlocked key '%s'", pubkey.getNickname())); // save this key in-memory if option enabled if(manager.isSavingKeys()) { manager.addKey(pubkey.getNickname(), trileadKey); } } return this.tryPublicKey(host.getUsername(), pubkey.getNickname(), trileadKey); } private boolean tryPublicKey(String username, String keyNickname, Object trileadKey) throws IOException { //outputLine(String.format("Attempting 'publickey' with key '%s' [%s]...", keyNickname, trileadKey.toString())); boolean success = connection.authenticateWithPublicKey(username, trileadKey); if(!success) outputLine(String.format("Authentication method 'publickey' with key '%s' failed", keyNickname)); return success; } protected void handleAuthentication() { try { if (connection.authenticateWithNone(host.getUsername())) { finishConnection(); return; } } catch(Exception e) { Log.d(TAG, "Host does not support 'none' authentication."); } outputLine(manager.res.getString(R.string.terminal_auth)); try { long pubkeyId = host.getPubkeyId(); if (!pubkeysExhausted && pubkeyId != HostDatabase.PUBKEYID_NEVER && connection.isAuthMethodAvailable(host.getUsername(), AUTH_PUBLICKEY)) { // if explicit pubkey defined for this host, then prompt for password as needed // otherwise just try all in-memory keys held in terminalmanager if (pubkeyId == HostDatabase.PUBKEYID_ANY) { // try each of the in-memory keys outputLine(manager.res.getString(R.string.terminal_auth_pubkey_any)); for(String nickname : manager.loadedPubkeys.keySet()) { Object trileadKey = manager.loadedPubkeys.get(nickname); if(this.tryPublicKey(host.getUsername(), nickname, trileadKey)) { finishConnection(); break; } } } else { outputLine(manager.res.getString(R.string.terminal_auth_pubkey_specific)); // use a specific key for this host, as requested PubkeyBean pubkey = manager.pubkeydb.findPubkeyById(pubkeyId); if (pubkey == null) outputLine(manager.res.getString(R.string.terminal_auth_pubkey_invalid)); else if (tryPublicKey(pubkey)) finishConnection(); } pubkeysExhausted = true; } else if (connection.isAuthMethodAvailable(host.getUsername(), AUTH_PASSWORD)) { outputLine(manager.res.getString(R.string.terminal_auth_pass)); String password = promptHelper.requestStringPrompt(null, manager.res.getString(R.string.prompt_password)); if (password != null && connection.authenticateWithPassword(host.getUsername(), password)) { finishConnection(); } else { outputLine(manager.res.getString(R.string.terminal_auth_pass_fail)); } } else if(connection.isAuthMethodAvailable(host.getUsername(), AUTH_KEYBOARDINTERACTIVE)) { // this auth method will talk with us using InteractiveCallback interface // it blocks until authentication finishes outputLine(manager.res.getString(R.string.terminal_auth_ki)); if(connection.authenticateWithKeyboardInteractive(host.getUsername(), TerminalBridge.this)) { finishConnection(); } else { outputLine(manager.res.getString(R.string.terminal_auth_ki_fail)); } } else { outputLine(manager.res.getString(R.string.terminal_auth_fail)); } } catch(Exception e) { Log.e(TAG, "Problem during handleAuthentication()", e); } } /** * Handle challenges from keyboard-interactive authentication mode. */ public String[] replyToChallenge(String name, String instruction, int numPrompts, String[] prompt, boolean[] echo) { String[] responses = new String[numPrompts]; for(int i = 0; i < numPrompts; i++) { // request response from user for each prompt responses[i] = promptHelper.requestStringPrompt(instruction, prompt[i]); } return responses; } /** * Convenience method for writing a line into the underlying MUD buffer. * Should never be called once the session is established. */ protected final void outputLine(String line) { if (session != null) Log.e(TAG, "Session established, cannot use outputLine!", new IOException("outputLine call traceback")); synchronized (localOutput) { final String s = line + "\r\n"; localOutput.add(s); ((vt320) buffer).putString(s); } } /** * Inject a specific string into this terminal. Used for post-login strings * and pasting clipboard. */ public void injectString(final String string) { Thread injectStringThread = new Thread(new Runnable() { public void run() { if(string == null || string.length() == 0) return; KeyEvent[] events = keymap.getEvents(string.toCharArray()); if(events == null || events.length == 0) return; for(KeyEvent event : events) { onKey(null, event.getKeyCode(), event); } } }); injectStringThread.setName("InjectString"); injectStringThread.start(); } /** * Internal method to request actual PTY terminal once we've finished * authentication. If called before authenticated, it will just fail. */ private void finishConnection() { setAuthenticated(true); // Start up predefined port forwards for (PortForwardBean pfb : portForwards) { try { enablePortForward(pfb); outputLine(String.format("Enable port forward: %s", pfb.getDescription())); } catch (Exception e) { Log.e(TAG, "Error setting up port forward during connect", e); } } if (!host.getWantSession()) { outputLine("Session will not be started due to host preference."); return; } try { session = connection.openSession(); ((vt320) buffer).reset(); // We no longer need our local output. localOutput.clear(); // previously tried vt100 and xterm for emulation modes // "screen" works the best for color and escape codes // TODO: pull this value from the preferences ((vt320) buffer).setAnswerBack(emulation); session.requestPTY(emulation, termWidth, termHeight, 0, 0, null); session.startShell(); // grab stdin/out from newly formed session stdin = session.getStdin(); stdout = session.getStdout(); stderr = session.getStderr(); // create thread to relay incoming connection data to buffer relay = new Relay(this, session, stdout, stderr, (vt320) buffer, host.getEncoding()); Thread relayThread = new Thread(relay); relayThread.setName("Relay"); relayThread.start(); // force font-size to make sure we resizePTY as needed setFontSize(fontSize); sessionOpen = true; // finally send any post-login string, if requested injectString(host.getPostLogin()); } catch (IOException e1) { Log.e(TAG, "Problem while trying to create PTY in finishConnection()", e1); } } /** * @return whether a session is open or not */ public boolean isSessionOpen() { return sessionOpen; } public void setOnDisconnectedListener(BridgeDisconnectedListener disconnectListener) { this.disconnectListener = disconnectListener; } /** * Force disconnection of this terminal bridge. */ public void dispatchDisconnect(boolean immediate) { // We don't need to do this multiple times. if (disconnected && !immediate) return; // disconnection request hangs if we havent really connected to a host yet // temporary fix is to just spawn disconnection into a thread Thread disconnectThread = new Thread(new Runnable() { public void run() { if(session != null) session.close(); connection.close(); } }); disconnectThread.setName("Disconnect"); disconnectThread.start(); disconnected = true; authenticated = false; sessionOpen = false; if (immediate) { awaitingClose = true; if (disconnectListener != null) disconnectListener.onDisconnected(TerminalBridge.this); } else { Thread disconnectPromptThread = new Thread(new Runnable() { public void run() { Boolean result = promptHelper.requestBooleanPrompt(null, manager.res.getString(R.string.prompt_host_disconnected), true); if (result == null || result.booleanValue()) { awaitingClose = true; // Tell the TerminalManager that we can be destroyed now. if (disconnectListener != null) disconnectListener.onDisconnected(TerminalBridge.this); } } }); disconnectPromptThread.setName("DisconnectPrompt"); disconnectPromptThread.start(); } } public void refreshKeymode() { keymode = manager.getKeyMode(); } /** * Handle onKey() events coming down from a {@link TerminalView} above us. * We might collect these for our internal buffer when working with hostkeys * or passwords, but otherwise we pass them directly over to the SSH host. */ public boolean onKey(View v, int keyCode, KeyEvent event) { try { // Ignore all key-up events except for the special keys if (event.getAction() == KeyEvent.ACTION_UP) { // skip keys if we aren't connected yet or have been disconnected if (disconnected || !sessionOpen) return false; if (PreferenceConstants.KEYMODE_RIGHT.equals(keymode)) { if (keyCode == KeyEvent.KEYCODE_ALT_RIGHT && (metaState & META_SLASH) != 0) { metaState &= ~(META_SLASH | META_TRANSIENT); stdin.write('/'); return true; } else if (keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT && (metaState & META_TAB) != 0) { metaState &= ~(META_TAB | META_TRANSIENT); stdin.write(0x09); return true; } } else if (PreferenceConstants.KEYMODE_LEFT.equals(keymode)) { if (keyCode == KeyEvent.KEYCODE_ALT_LEFT && (metaState & META_SLASH) != 0) { metaState &= ~(META_SLASH | META_TRANSIENT); stdin.write('/'); return true; } else if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT && (metaState & META_TAB) != 0) { metaState &= ~(META_TAB | META_TRANSIENT); stdin.write(0x09); return true; } } return false; } // check for terminal resizing keys if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) { forcedSize = false; setFontSize(fontSize + 2); return true; } else if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { forcedSize = false; setFontSize(fontSize - 2); return true; } // skip keys if we aren't connected yet or have been disconnected if (disconnected || !sessionOpen) return false; // if we're in scrollback, scroll to bottom of window on input if (buffer.windowBase != buffer.screenBase) buffer.setWindowBase(buffer.screenBase); boolean printing = (keymap.isPrintingKey(keyCode) || keyCode == KeyEvent.KEYCODE_SPACE); // otherwise pass through to existing session // print normal keys if (printing) { int curMetaState = event.getMetaState(); metaState &= ~(META_SLASH | META_TAB); if ((metaState & META_SHIFT_MASK) != 0) { curMetaState |= KeyEvent.META_SHIFT_ON; metaState &= ~META_SHIFT_ON; redraw(); } if ((metaState & META_ALT_MASK) != 0) { curMetaState |= KeyEvent.META_ALT_ON; metaState &= ~META_ALT_ON; redraw(); } int key = keymap.get(keyCode, curMetaState); if ((metaState & META_CTRL_MASK) != 0) { // Support CTRL-a through CTRL-z if (key >= 0x61 && key <= 0x7A) key -= 0x60; // Support CTRL-A through CTRL-_ else if (key >= 0x41 && key <= 0x5F) key -= 0x40; else if (key == 0x20) key = 0x00; metaState &= ~META_CTRL_ON; redraw(); } // handle pressing f-keys if ((metaState & META_TAB) != 0) { switch(key) { case '!': ((vt320)buffer).keyPressed(vt320.KEY_F1, ' ', 0); return true; case '@': ((vt320)buffer).keyPressed(vt320.KEY_F2, ' ', 0); return true; case '#': ((vt320)buffer).keyPressed(vt320.KEY_F3, ' ', 0); return true; case '$': ((vt320)buffer).keyPressed(vt320.KEY_F4, ' ', 0); return true; case '%': ((vt320)buffer).keyPressed(vt320.KEY_F5, ' ', 0); return true; case '^': ((vt320)buffer).keyPressed(vt320.KEY_F6, ' ', 0); return true; case '&': ((vt320)buffer).keyPressed(vt320.KEY_F7, ' ', 0); return true; case '*': ((vt320)buffer).keyPressed(vt320.KEY_F8, ' ', 0); return true; case '(': ((vt320)buffer).keyPressed(vt320.KEY_F9, ' ', 0); return true; case ')': ((vt320)buffer).keyPressed(vt320.KEY_F10, ' ', 0); return true; } } if (key < 0x80) stdin.write(key); else // TODO write encoding routine that doesn't allocate each time stdin.write(new String(Character.toChars(key)) .getBytes(host.getEncoding())); return true; } if (keyCode == KeyEvent.KEYCODE_UNKNOWN && event.getAction() == KeyEvent.ACTION_MULTIPLE) { byte[] input = event.getCharacters().getBytes(host.getEncoding()); stdin.write(input); } // try handling keymode shortcuts if (event.getRepeatCount() == 0) { if ("Use right-side keys".equals(keymode)) { switch(keyCode) { case KeyEvent.KEYCODE_ALT_RIGHT: metaState |= META_SLASH; return true; case KeyEvent.KEYCODE_SHIFT_RIGHT: metaState |= META_TAB; return true; case KeyEvent.KEYCODE_SHIFT_LEFT: metaPress(META_SHIFT_ON); return true; case KeyEvent.KEYCODE_ALT_LEFT: metaPress(META_ALT_ON); return true; default: break; } } else if ("Use left-side keys".equals(keymode)) { switch(keyCode) { case KeyEvent.KEYCODE_ALT_LEFT: metaState |= META_SLASH; return true; case KeyEvent.KEYCODE_SHIFT_LEFT: metaState |= META_TAB; return true; case KeyEvent.KEYCODE_SHIFT_RIGHT: metaPress(META_SHIFT_ON); return true; case KeyEvent.KEYCODE_ALT_RIGHT: metaPress(META_ALT_ON); return true; default: break; } } } // look for special chars switch(keyCode) { case KeyEvent.KEYCODE_CAMERA: // check to see which shortcut the camera button triggers String camera = manager.prefs.getString( PreferenceConstants.CAMERA, PreferenceConstants.CAMERA_CTRLA_SPACE); if(PreferenceConstants.CAMERA_CTRLA_SPACE.equals(camera)) { stdin.write(0x01); stdin.write(' '); } else if(PreferenceConstants.CAMERA_CTRLA.equals(camera)) { stdin.write(0x01); } else if(PreferenceConstants.CAMERA_ESC.equals(camera)) { ((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0); } break; case KeyEvent.KEYCODE_DEL: ((vt320) buffer).keyPressed(vt320.KEY_BACK_SPACE, ' ', getStateForBuffer()); metaState &= ~META_TRANSIENT; return true; case KeyEvent.KEYCODE_ENTER: ((vt320)buffer).keyTyped(vt320.KEY_ENTER, ' ', 0); metaState &= ~META_TRANSIENT; return true; case KeyEvent.KEYCODE_DPAD_LEFT: if (selectingForCopy) { selectionArea.decrementColumn(); redraw(); } else { ((vt320) buffer).keyPressed(vt320.KEY_LEFT, ' ', getStateForBuffer()); metaState &= ~META_TRANSIENT; tryKeyVibrate(); } return true; case KeyEvent.KEYCODE_DPAD_UP: if (selectingForCopy) { selectionArea.decrementRow(); redraw(); } else { ((vt320) buffer).keyPressed(vt320.KEY_UP, ' ', getStateForBuffer()); metaState &= ~META_TRANSIENT; tryKeyVibrate(); } return true; case KeyEvent.KEYCODE_DPAD_DOWN: if (selectingForCopy) { selectionArea.incrementRow(); redraw(); } else { ((vt320) buffer).keyPressed(vt320.KEY_DOWN, ' ', getStateForBuffer()); metaState &= ~META_TRANSIENT; tryKeyVibrate(); } return true; case KeyEvent.KEYCODE_DPAD_RIGHT: if (selectingForCopy) { selectionArea.incrementColumn(); redraw(); } else { ((vt320) buffer).keyPressed(vt320.KEY_RIGHT, ' ', getStateForBuffer()); metaState &= ~META_TRANSIENT; tryKeyVibrate(); } return true; case KeyEvent.KEYCODE_DPAD_CENTER: if (selectingForCopy) { if (selectionArea.isSelectingOrigin()) selectionArea.finishSelectingOrigin(); else { if (parent != null && clipboard != null) { // copy selected area to clipboard String copiedText = selectionArea.copyFrom(buffer); clipboard.setText(copiedText); parent.notifyUser(parent.getContext().getString( R.string.console_copy_done, copiedText.length())); selectingForCopy = false; selectionArea.reset(); } } } else { if ((metaState & META_CTRL_ON) != 0) { ((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0); metaState &= ~META_CTRL_ON; } else metaState |= META_CTRL_ON; } redraw(); return true; } } catch (IOException e) { Log.e(TAG, "Problem while trying to handle an onKey() event", e); try { stdin.flush(); } catch (IOException ioe) { // Our stdin got blown away, so we must be closed. Log.d(TAG, "Our stdin was closed, dispatching disconnect event"); dispatchDisconnect(false); } } catch (NullPointerException npe) { Log.d(TAG, "Input before connection established ignored."); return true; } return false; } /** * Handle meta key presses where the key can be locked on. * <p> * 1st press: next key to have meta state<br /> * 2nd press: meta state is locked on<br /> * 3rd press: disable meta state * * @param code */ private void metaPress(int code) { if ((metaState & (code << 1)) != 0) { metaState &= ~(code << 1); } else if ((metaState & code) != 0) { metaState &= ~code; metaState |= code << 1; } else metaState |= code; redraw(); } public int getMetaState() { return metaState; } private int getStateForBuffer() { int bufferState = 0; if ((metaState & META_CTRL_MASK) != 0) bufferState |= vt320.KEY_CONTROL; if ((metaState & META_SHIFT_MASK) != 0) bufferState |= vt320.KEY_SHIFT; if ((metaState & META_ALT_MASK) != 0) bufferState |= vt320.KEY_ALT; return bufferState; } public void setSelectingForCopy(boolean selectingForCopy) { this.selectingForCopy = selectingForCopy; } public boolean isSelectingForCopy() { return selectingForCopy; } public SelectionArea getSelectionArea() { return selectionArea; } public synchronized void tryKeyVibrate() { manager.tryKeyVibrate(); } /** * Request a different font size. Will make call to parentChanged() to make * sure we resize PTY if needed. */ private final void setFontSize(float size) { if (size <= 0.0) return; defaultPaint.setTextSize(size); fontSize = size; // read new metrics to get exact pixel dimensions FontMetrics fm = defaultPaint.getFontMetrics(); charTop = (int)Math.ceil(fm.top); float[] widths = new float[1]; defaultPaint.getTextWidths("X", widths); charWidth = (int)Math.ceil(widths[0]); charHeight = (int)Math.ceil(fm.descent - fm.top); // refresh any bitmap with new font size if(parent != null) parentChanged(parent); for (FontSizeChangedListener ofscl : fontSizeChangedListeners) ofscl.onFontSizeChanged(size); } /** * Add an {@link FontSizeChangedListener} to the list of listeners for this * bridge. * * @param listener * listener to add */ public void addFontSizeChangedListener(FontSizeChangedListener listener) { fontSizeChangedListeners.add(listener); } /** * Remove an {@link FontSizeChangedListener} from the list of listeners for * this bridge. * * @param listener */ public void removeFontSizeChangedListener(FontSizeChangedListener listener) { fontSizeChangedListeners.remove(listener); } /** * Something changed in our parent {@link TerminalView}, maybe it's a new * parent, or maybe it's an updated font size. We should recalculate * terminal size information and request a PTY resize. */ public final synchronized void parentChanged(TerminalView parent) { this.parent = parent; int width = parent.getWidth(); int height = parent.getHeight(); clipboard = (ClipboardManager) parent.getContext().getSystemService(Context.CLIPBOARD_SERVICE); if (!forcedSize) { // recalculate buffer size int newTermWidth, newTermHeight; newTermWidth = width / charWidth; newTermHeight = height / charHeight; // If nothing has changed in the terminal dimensions and not an intial // draw then don't blow away scroll regions and such. if (newTermWidth == termWidth && newTermHeight == termHeight) return; termWidth = newTermWidth; termHeight = newTermHeight; } // reallocate new bitmap if needed boolean newBitmap = (bitmap == null); if(bitmap != null) newBitmap = (bitmap.getWidth() != width || bitmap.getHeight() != height); if (newBitmap) { if (bitmap != null) bitmap.recycle(); bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888); canvas.setBitmap(bitmap); } // clear out any old buffer information defaultPaint.setColor(Color.BLACK); canvas.drawPaint(defaultPaint); // Stroke the border of the terminal if the size is being forced; if (forcedSize) { int borderX = (termWidth * charWidth) + 1; int borderY = (termHeight * charHeight) + 1; defaultPaint.setColor(Color.GRAY); defaultPaint.setStrokeWidth(0.0f); if (width >= borderX) canvas.drawLine(borderX, 0, borderX, borderY + 1, defaultPaint); if (height >= borderY) canvas.drawLine(0, borderY, borderX + 1, borderY, defaultPaint); } try { // request a terminal pty resize int prevRow = buffer.getCursorRow(); buffer.setScreenSize(termWidth, termHeight, true); // Work around weird vt320.java behavior where cursor is an offset from the bottom?? buffer.setCursorPosition(buffer.getCursorColumn(), prevRow); if(session != null) session.resizePTY(termWidth, termHeight, width, height); } catch(Exception e) { Log.e(TAG, "Problem while trying to resize screen or PTY", e); } // redraw local output if we don't have a sesson to receive our resize request if (session == null) { synchronized (localOutput) { ((vt320) buffer).reset(); for (String line : localOutput) ((vt320) buffer).putString(line); } } // force full redraw with new buffer size fullRedraw = true; redraw(); parent.notifyUser(String.format("%d x %d", termWidth, termHeight)); Log.i(TAG, String.format("parentChanged() now width=%d, height=%d", termWidth, termHeight)); } /** * Somehow our parent {@link TerminalView} was destroyed. Now we don't need * to redraw anywhere, and we can recycle our internal bitmap. */ public synchronized void parentDestroyed() { parent = null; canvas.setBitmap(null); if (bitmap != null) bitmap.recycle(); bitmap = null; } public void setVDUBuffer(VDUBuffer buffer) { this.buffer = buffer; } public VDUBuffer getVDUBuffer() { return buffer; } public void onDraw() { int fg, bg; boolean entireDirty = buffer.update[0] || fullRedraw; // walk through all lines in the buffer for(int l = 0; l < buffer.height; l++) { // check if this line is dirty and needs to be repainted // also check for entire-buffer dirty flags if (!entireDirty && !buffer.update[l + 1]) continue; // reset dirty flag for this line buffer.update[l + 1] = false; // walk through all characters in this line for (int c = 0; c < buffer.width; c++) { int addr = 0; int currAttr = buffer.charAttributes[buffer.windowBase + l][c]; // reset default colors fg = color[COLOR_FG_STD]; bg = color[COLOR_BG_STD]; // check if foreground color attribute is set if ((currAttr & VDUBuffer.COLOR_FG) != 0) { int fgcolor = ((currAttr & VDUBuffer.COLOR_FG) >> VDUBuffer.COLOR_FG_SHIFT) - 1; if (fgcolor < 8 && (currAttr & VDUBuffer.BOLD) != 0) fg = color[fgcolor + 8]; else fg = color[fgcolor]; } // check if background color attribute is set if ((currAttr & VDUBuffer.COLOR_BG) != 0) bg = color[((currAttr & VDUBuffer.COLOR_BG) >> VDUBuffer.COLOR_BG_SHIFT) - 1]; // support character inversion by swapping background and foreground color if ((currAttr & VDUBuffer.INVERT) != 0) { int swapc = bg; bg = fg; fg = swapc; } // set underlined attributes if requested defaultPaint.setUnderlineText((currAttr & VDUBuffer.UNDERLINE) != 0); // determine the amount of continuous characters with the same settings and print them all at once while(c + addr < buffer.width && buffer.charAttributes[buffer.windowBase + l][c + addr] == currAttr) { addr++; } // Save the current clip region canvas.save(Canvas.CLIP_SAVE_FLAG); // clear this dirty area with background color defaultPaint.setColor(bg); canvas.clipRect(c * charWidth, l * charHeight, (c + addr) * charWidth, (l + 1) * charHeight); canvas.drawPaint(defaultPaint); // write the text string starting at 'c' for 'addr' number of characters defaultPaint.setColor(fg); if((currAttr & VDUBuffer.INVISIBLE) == 0) canvas.drawText(buffer.charArray[buffer.windowBase + l], c, addr, c * charWidth, (l * charHeight) - charTop, defaultPaint); // Restore the previous clip region canvas.restore(); // advance to the next text block with different characteristics c += addr - 1; } } // reset entire-buffer flags buffer.update[0] = false; fullRedraw = false; } public void redraw() { if (parent != null) parent.postInvalidate(); } // We don't have a scroll bar. public void updateScrollBar() { } public void connectionLost(Throwable reason) { // weve lost our ssh connection, so pass along to manager and gui Log.e(TAG, "Somehow our underlying SSH socket died", reason); dispatchDisconnect(false); } /** * Resize terminal to fit [rows]x[cols] in screen of size [width]x[height] * @param rows * @param cols * @param width * @param height */ public synchronized void resizeComputed(int cols, int rows, int width, int height) { float size = 8.0f; float step = 8.0f; float limit = 0.125f; int direction; while ((direction = fontSizeCompare(size, cols, rows, width, height)) < 0) size += step; if (direction == 0) { Log.d("fontsize", String.format("Found match at %f", size)); return; } step /= 2.0f; size -= step; while ((direction = fontSizeCompare(size, cols, rows, width, height)) != 0 && step >= limit) { step /= 2.0f; if (direction > 0) { size -= step; } else { size += step; } } if (direction > 0) size -= step; forcedSize = true; termWidth = cols; termHeight = rows; setFontSize(size); } private int fontSizeCompare(float size, int cols, int rows, int width, int height) { // read new metrics to get exact pixel dimensions defaultPaint.setTextSize(size); FontMetrics fm = defaultPaint.getFontMetrics(); float[] widths = new float[1]; defaultPaint.getTextWidths("X", widths); int termWidth = (int)widths[0] * cols; int termHeight = (int)Math.ceil(fm.descent - fm.top) * rows; Log.d("fontsize", String.format("font size %f resulted in %d x %d", size, termWidth, termHeight)); // Check to see if it fits in resolution specified. if (termWidth > width || termHeight > height) return 1; if (termWidth == width || termHeight == height) return 0; return -1; } /** * Adds the {@link PortForwardBean} to the list. * @param portForward the port forward bean to add * @return true on successful addition */ public boolean addPortForward(PortForwardBean portForward) { return portForwards.add(portForward); } /** * Removes the {@link PortForwardBean} from the list. * @param portForward the port forward bean to remove * @return true on successful removal */ public boolean removePortForward(PortForwardBean portForward) { // Make sure we don't have a phantom forwarder. disablePortForward(portForward); return portForwards.remove(portForward); } /** * @return the list of port forwards */ public List<PortForwardBean> getPortForwards() { return portForwards; } /** * Enables a port forward member. After calling this method, the port forward should * be operational. * @param portForward member of our current port forwards list to enable * @return true on successful port forward setup */ public boolean enablePortForward(PortForwardBean portForward) { if (!portForwards.contains(portForward)) { Log.e(TAG, "Attempt to enable port forward not in list"); return false; } if (HostDatabase.PORTFORWARD_LOCAL.equals(portForward.getType())) { LocalPortForwarder lpf = null; try { lpf = connection.createLocalPortForwarder(portForward.getSourcePort(), portForward.getDestAddr(), portForward.getDestPort()); } catch (IOException e) { Log.e(TAG, "Could not create local port forward", e); return false; } if (lpf == null) { Log.e(TAG, "returned LocalPortForwarder object is null"); return false; } portForward.setIdentifier(lpf); portForward.setEnabled(true); return true; } else if (HostDatabase.PORTFORWARD_REMOTE.equals(portForward.getType())) { try { connection.requestRemotePortForwarding("", portForward.getSourcePort(), portForward.getDestAddr(), portForward.getDestPort()); } catch (IOException e) { Log.e(TAG, "Could not create remote port forward", e); return false; } portForward.setEnabled(false); return true; } else if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(portForward.getType())) { DynamicPortForwarder dpf = null; try { dpf = connection.createDynamicPortForwarder(portForward.getSourcePort()); } catch (IOException e) { Log.e(TAG, "Could not create dynamic port forward", e); return false; } portForward.setIdentifier(dpf); portForward.setEnabled(true); return true; } else { // Unsupported type Log.e(TAG, String.format("attempt to forward unknown type %s", portForward.getType())); return false; } } /** * Disables a port forward member. After calling this method, the port forward should * be non-functioning. * @param portForward member of our current port forwards list to enable * @return true on successful port forward tear-down */ public boolean disablePortForward(PortForwardBean portForward) { if (!portForwards.contains(portForward)) { Log.e(TAG, "Attempt to disable port forward not in list"); return false; } if (HostDatabase.PORTFORWARD_LOCAL.equals(portForward.getType())) { LocalPortForwarder lpf = null; lpf = (LocalPortForwarder)portForward.getIdentifier(); if (!portForward.isEnabled() || lpf == null) { Log.d(TAG, String.format("Could not disable %s; it appears to be not enabled or have no handler", portForward.getNickname())); return false; } portForward.setEnabled(false); try { lpf.close(); } catch (IOException e) { Log.e(TAG, "Could not stop local port forwarder, setting enabled to false", e); return false; } return true; } else if (HostDatabase.PORTFORWARD_REMOTE.equals(portForward.getType())) { portForward.setEnabled(false); try { connection.cancelRemotePortForwarding(portForward.getSourcePort()); } catch (IOException e) { Log.e(TAG, "Could not stop remote port forwarding, setting enabled to false", e); return false; } return true; } else if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(portForward.getType())) { DynamicPortForwarder dpf = null; dpf = (DynamicPortForwarder)portForward.getIdentifier(); if (!portForward.isEnabled() || dpf == null) { Log.d(TAG, String.format("Could not disable %s; it appears to be not enabled or have no handler", portForward.getNickname())); return false; } portForward.setEnabled(false); try { dpf.close(); } catch (IOException e) { Log.e(TAG, "Could not stop dynamic port forwarder, setting enabled to false", e); return false; } return true; } else { // Unsupported type Log.e(TAG, String.format("attempt to forward unknown type %s", portForward.getType())); return false; } } /** * @param authenticated the authenticated to set */ public void setAuthenticated(boolean authenticated) { this.authenticated = authenticated; } /** * @return the authenticated */ public boolean isAuthenticated() { return authenticated; } /** * @return whether the TerminalBridge should close */ public boolean isAwaitingClose() { return awaitingClose; } /** * @return whether this connection had started and subsequently disconnected */ public boolean isDisconnected() { return disconnected; } /* (non-Javadoc) * @see de.mud.terminal.VDUDisplay#setColor(byte, byte, byte, byte) */ public void setColor(int index, int red, int green, int blue) { // Don't allow the system colors to be overwritten for now. May violate specs. if (index < color.length && index >= 16) color[index] = 0xff000000 | red << 16 | green << 8 | blue; } public final void resetColors() { color = new int[] { 0xff000000, // black 0xffcc0000, // red 0xff00cc00, // green 0xffcccc00, // brown 0xff0000cc, // blue 0xffcc00cc, // purple 0xff00cccc, // cyan 0xffcccccc, // light grey 0xff444444, // dark grey 0xffff4444, // light red 0xff44ff44, // light green 0xffffff44, // yellow 0xff4444ff, // light blue 0xffff44ff, // light purple 0xff44ffff, // light cyan 0xffffffff, // white 0xff000000, 0xff00005f, 0xff000087, 0xff0000af, 0xff0000d7, 0xff0000ff, 0xff005f00, 0xff005f5f, 0xff005f87, 0xff005faf, 0xff005fd7, 0xff005fff, 0xff008700, 0xff00875f, 0xff008787, 0xff0087af, 0xff0087d7, 0xff0087ff, 0xff00af00, 0xff00af5f, 0xff00af87, 0xff00afaf, 0xff00afd7, 0xff00afff, 0xff00d700, 0xff00d75f, 0xff00d787, 0xff00d7af, 0xff00d7d7, 0xff00d7ff, 0xff00ff00, 0xff00ff5f, 0xff00ff87, 0xff00ffaf, 0xff00ffd7, 0xff00ffff, 0xff5f0000, 0xff5f005f, 0xff5f0087, 0xff5f00af, 0xff5f00d7, 0xff5f00ff, 0xff5f5f00, 0xff5f5f5f, 0xff5f5f87, 0xff5f5faf, 0xff5f5fd7, 0xff5f5fff, 0xff5f8700, 0xff5f875f, 0xff5f8787, 0xff5f87af, 0xff5f87d7, 0xff5f87ff, 0xff5faf00, 0xff5faf5f, 0xff5faf87, 0xff5fafaf, 0xff5fafd7, 0xff5fafff, 0xff5fd700, 0xff5fd75f, 0xff5fd787, 0xff5fd7af, 0xff5fd7d7, 0xff5fd7ff, 0xff5fff00, 0xff5fff5f, 0xff5fff87, 0xff5fffaf, 0xff5fffd7, 0xff5fffff, 0xff870000, 0xff87005f, 0xff870087, 0xff8700af, 0xff8700d7, 0xff8700ff, 0xff875f00, 0xff875f5f, 0xff875f87, 0xff875faf, 0xff875fd7, 0xff875fff, 0xff878700, 0xff87875f, 0xff878787, 0xff8787af, 0xff8787d7, 0xff8787ff, 0xff87af00, 0xff87af5f, 0xff87af87, 0xff87afaf, 0xff87afd7, 0xff87afff, 0xff87d700, 0xff87d75f, 0xff87d787, 0xff87d7af, 0xff87d7d7, 0xff87d7ff, 0xff87ff00, 0xff87ff5f, 0xff87ff87, 0xff87ffaf, 0xff87ffd7, 0xff87ffff, 0xffaf0000, 0xffaf005f, 0xffaf0087, 0xffaf00af, 0xffaf00d7, 0xffaf00ff, 0xffaf5f00, 0xffaf5f5f, 0xffaf5f87, 0xffaf5faf, 0xffaf5fd7, 0xffaf5fff, 0xffaf8700, 0xffaf875f, 0xffaf8787, 0xffaf87af, 0xffaf87d7, 0xffaf87ff, 0xffafaf00, 0xffafaf5f, 0xffafaf87, 0xffafafaf, 0xffafafd7, 0xffafafff, 0xffafd700, 0xffafd75f, 0xffafd787, 0xffafd7af, 0xffafd7d7, 0xffafd7ff, 0xffafff00, 0xffafff5f, 0xffafff87, 0xffafffaf, 0xffafffd7, 0xffafffff, 0xffd70000, 0xffd7005f, 0xffd70087, 0xffd700af, 0xffd700d7, 0xffd700ff, 0xffd75f00, 0xffd75f5f, 0xffd75f87, 0xffd75faf, 0xffd75fd7, 0xffd75fff, 0xffd78700, 0xffd7875f, 0xffd78787, 0xffd787af, 0xffd787d7, 0xffd787ff, 0xffd7af00, 0xffd7af5f, 0xffd7af87, 0xffd7afaf, 0xffd7afd7, 0xffd7afff, 0xffd7d700, 0xffd7d75f, 0xffd7d787, 0xffd7d7af, 0xffd7d7d7, 0xffd7d7ff, 0xffd7ff00, 0xffd7ff5f, 0xffd7ff87, 0xffd7ffaf, 0xffd7ffd7, 0xffd7ffff, 0xffff0000, 0xffff005f, 0xffff0087, 0xffff00af, 0xffff00d7, 0xffff00ff, 0xffff5f00, 0xffff5f5f, 0xffff5f87, 0xffff5faf, 0xffff5fd7, 0xffff5fff, 0xffff8700, 0xffff875f, 0xffff8787, 0xffff87af, 0xffff87d7, 0xffff87ff, 0xffffaf00, 0xffffaf5f, 0xffffaf87, 0xffffafaf, 0xffffafd7, 0xffffafff, 0xffffd700, 0xffffd75f, 0xffffd787, 0xffffd7af, 0xffffd7d7, 0xffffd7ff, 0xffffff00, 0xffffff5f, 0xffffff87, 0xffffffaf, 0xffffffd7, 0xffffffff, 0xff080808, 0xff121212, 0xff1c1c1c, 0xff262626, 0xff303030, 0xff3a3a3a, 0xff444444, 0xff4e4e4e, 0xff585858, 0xff626262, 0xff6c6c6c, 0xff767676, 0xff808080, 0xff8a8a8a, 0xff949494, 0xff9e9e9e, 0xffa8a8a8, 0xffb2b2b2, 0xffbcbcbc, 0xffc6c6c6, 0xffd0d0d0, 0xffdadada, 0xffe4e4e4, 0xffeeeeee, }; } }
package org.exist.xquery.functions; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.exist.EXistException; import org.exist.dom.DocumentSet; import org.exist.dom.ExtArrayNodeSet; import org.exist.dom.NodeProxy; import org.exist.dom.NodeSet; import org.exist.dom.QName; import org.exist.storage.DBBroker; import org.exist.xquery.Cardinality; import org.exist.xquery.Dependency; import org.exist.xquery.Expression; import org.exist.xquery.Function; import org.exist.xquery.FunctionSignature; import org.exist.xquery.Module; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.util.RegexTranslator; import org.exist.xquery.util.RegexTranslator.RegexSyntaxException; import org.exist.xquery.value.BooleanValue; import org.exist.xquery.value.Item; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceType; import org.exist.xquery.value.Type; /** * Implements the fn:matches() function. * * Based on the jakarta ORO package for regular expression support. * * @author Wolfgang Meier (wolfgang@exist-db.org) */ public class FunMatches extends Function { public final static FunctionSignature signatures[] = { new FunctionSignature( new QName("matches", Module.BUILTIN_FUNCTION_NS), "Returns true if the first argument string matches the regular expression specified " + "by the second argument. This function is optimized internally if a range index of type xs:string " + "is defined on the nodes passed to the first argument.", new SequenceType[] { new SequenceType(Type.STRING, Cardinality.ZERO_OR_ONE), new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE) }, new SequenceType(Type.BOOLEAN, Cardinality.EXACTLY_ONE) ), new FunctionSignature( new QName("matches", Module.BUILTIN_FUNCTION_NS), "Returns true if the first argument string matches the regular expression specified " + "by the second argument. This function is optimized internally if a range index of type xs:string " + "is defined on the nodes passed to the first argument.", new SequenceType[] { new SequenceType(Type.STRING, Cardinality.ZERO_OR_ONE), new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE), new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE) }, new SequenceType(Type.BOOLEAN, Cardinality.EXACTLY_ONE) ) }; protected Matcher matcher = null; protected Pattern pat = null; /** * @param context */ public FunMatches(XQueryContext context, FunctionSignature signature) { super(context, signature); } /* (non-Javadoc) * @see org.exist.xquery.Function#setArguments(java.util.List) */ public void setArguments(List arguments) throws XPathException { steps.addAll(arguments); } /* (non-Javadoc) * @see org.exist.xquery.Function#getDependencies() */ public int getDependencies() { final Expression stringArg = getArgument(0); final Expression patternArg = getArgument(1); if(Type.subTypeOf(stringArg.returnsType(), Type.NODE) && (stringArg.getDependencies() & Dependency.CONTEXT_ITEM) == 0 && (patternArg.getDependencies() & Dependency.CONTEXT_ITEM) == 0) { return Dependency.CONTEXT_SET; } else { return Dependency.CONTEXT_SET + Dependency.CONTEXT_ITEM; } } /* (non-Javadoc) * @see org.exist.xquery.Function#returnsType() */ public int returnsType() { if (inPredicate && (getDependencies() & Dependency.CONTEXT_ITEM) == 0) { /* If one argument is a node set we directly * return the matching nodes from the context set. This works * only inside predicates. */ return Type.NODE; } // In all other cases, we return boolean return Type.BOOLEAN; } public void analyze(Expression parent, int flags) throws XPathException { // call analyze for each argument inPredicate = (flags & IN_PREDICATE) > 0; for(int i = 0; i < getArgumentCount(); i++) { getArgument(i).analyze(this, flags); } } /* (non-Javadoc) * @see org.exist.xquery.Expression#eval(org.exist.dom.DocumentSet, org.exist.xquery.value.Sequence, org.exist.xquery.value.Item) */ public Sequence eval( Sequence contextSequence, Item contextItem) throws XPathException { if(contextItem != null) contextSequence = contextItem.toSequence(); Sequence input = getArgument(0).eval(contextSequence, contextItem); if(input.getLength() == 0) return Sequence.EMPTY_SEQUENCE; if(inPredicate && (getDependencies() & Dependency.CONTEXT_ITEM) == 0) { return evalWithIndex(contextSequence, contextItem, input); } else { return evalGeneric(contextSequence, contextItem, input); } } /** * @param contextSequence * @param contextItem * @param stringArg * @return * @throws XPathException */ private Sequence evalWithIndex(Sequence contextSequence, Item contextItem, Sequence input) throws XPathException { String pattern = translateRegexp(getArgument(1).eval(contextSequence, contextItem).getStringValue()); NodeSet nodes = input.toNodeSet(); int flags = 0; boolean caseSensitive = true; if(getSignature().getArgumentCount() == 3) { String flagsArg = getArgument(2).eval(contextSequence, contextItem).getStringValue(); caseSensitive = flagsArg.indexOf('i') < 0; flags = parseFlags(flagsArg); } // get the type of a possible index int indexType = nodes.getIndexType(); if(Type.subTypeOf(indexType, Type.STRING)) { DocumentSet docs = nodes.getDocumentSet(); try { return context.getBroker().getValueIndex().match(docs, nodes, pattern, DBBroker.MATCH_REGEXP, flags, caseSensitive); } catch (EXistException e) { throw new XPathException(getASTNode(), e.getMessage(), e); } } else { ExtArrayNodeSet result = new ExtArrayNodeSet(); for(Iterator i = nodes.iterator(); i.hasNext(); ) { NodeProxy node = (NodeProxy) i.next(); if(match(node.getStringValue(), pattern, flags)) result.add(node); } return result; } } /** * Translates the regular expression from XPath2 syntax to java regex * syntax. * * @param pattern * @return * @throws XPathException */ protected String translateRegexp(String pattern) throws XPathException { // convert pattern to Java regex syntax try { pattern = RegexTranslator.translate(pattern, true); } catch (RegexSyntaxException e) { throw new XPathException(getASTNode(), "Conversion from XPath2 to Java regular expression " + "syntax failed: " + e.getMessage(), e); } return pattern; } /** * @param contextSequence * @param contextItem * @param stringArg * @return * @throws XPathException */ private Sequence evalGeneric(Sequence contextSequence, Item contextItem, Sequence stringArg) throws XPathException { String string = stringArg.getStringValue(); String pattern = translateRegexp(getArgument(1).eval(contextSequence, contextItem).getStringValue()); int flags = 0; if(getSignature().getArgumentCount() == 3) flags = parseFlags(getArgument(2).eval(contextSequence, contextItem).getStringValue()); return BooleanValue.valueOf(match(string, pattern, flags)); } /** * @param string * @param pattern * @param flags * @return * @throws XPathException */ private boolean match(String string, String pattern, int flags) throws XPathException { try { if(pat == null || (!pattern.equals(pat.pattern())) || flags != pat.flags()) { pat = Pattern.compile(pattern, flags); matcher = pat.matcher(string); } else { matcher.reset(string); } if(matcher.find()) return true; else return false; } catch (PatternSyntaxException e) { throw new XPathException("Invalid regular expression: " + e.getMessage(), e); } } protected final static int parseFlags(String s) throws XPathException { int flags = 0; for(int i = 0; i < s.length(); i++) { char ch = s.charAt(i); switch(ch) { case 'm': flags |= Pattern.MULTILINE; break; case 'i': flags = flags | Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE; break; case 'x': flags |= Pattern.COMMENTS; break; case 's': flags |= Pattern.DOTALL; break; default: throw new XPathException("Invalid regular expression flag: " + ch); } } return flags; } }
/* * @author <a href="mailto:novotny@gridsphere.org">Jason Novotny</a> * @version $Id: PortletTitleBar.java 5032 2006-08-17 18:15:06Z novotny $ */ package org.gridsphere.layout; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.gridsphere.layout.event.PortletTitleBarEvent; import org.gridsphere.layout.event.PortletTitleBarListener; import org.gridsphere.layout.event.PortletWindowEvent; import org.gridsphere.layout.event.impl.PortletTitleBarEventImpl; import org.gridsphere.layout.event.impl.PortletWindowEventImpl; import org.gridsphere.layout.view.Render; import org.gridsphere.portlet.impl.SportletProperties; import org.gridsphere.portlet.impl.StoredPortletResponseImpl; import org.gridsphere.portlet.service.spi.PortletServiceFactory; import org.gridsphere.portletcontainer.ApplicationPortlet; import org.gridsphere.portletcontainer.GridSphereEvent; import org.gridsphere.portletcontainer.impl.PortletInvoker; import org.gridsphere.services.core.registry.PortletRegistryService; import org.gridsphere.services.core.security.role.PortletRole; import javax.portlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.io.Serializable; import java.io.StringWriter; import java.security.Principal; import java.util.*; /** * A <code>PortletTitleBar</code> represents the visual display of the portlet title bar * within a portlet frame and is contained by {@link PortletFrame}. * The title bar contains portlet mode and window state as well as a title. */ public class PortletTitleBar extends BasePortletComponent implements Serializable, Cloneable { private Log log = LogFactory.getLog(PortletTitleBar.class); private String title = "unknown title"; private String portletClass = null; private transient PortletRegistryService portletRegistryService = null; private transient PortletInvoker portletInvoker = null; private transient WindowState windowState = WindowState.NORMAL; private transient PortletMode portletMode = PortletMode.VIEW; private transient PortletMode previousMode = PortletMode.VIEW; private transient List<javax.portlet.WindowState> allowedWindowStates = new ArrayList<javax.portlet.WindowState>(); private transient String errorMessage = ""; private transient boolean hasError = false; private transient boolean isActive = false; private transient List<PortletTitleBar.PortletModeLink> modeLinks = null; private transient List<PortletTitleBar.PortletStateLink> windowLinks = null; private transient Render titleView = null; // display modes in title bar at all? private transient boolean displayModes = true; // display states in title bar at all? private transient boolean displayStates = true; /** * Link is an abstract representation of a hyperlink with an href, image and * alt tags. */ abstract class Link { protected String href = ""; protected String imageSrc = ""; protected String altTag = ""; protected String symbol = ""; protected String cursor = ""; /** * Returns the image source attribute in the link * * @return the image source attribute in the link */ public String getImageSrc() { return imageSrc; } public String getSymbol() { //WAP 2.0 Extention return symbol; } /** * Returns the CSS cursor style to use * * @return the cursor */ public String getCursor() { return cursor; } /** * Sets the CSS cursor style to use * * @param cursor the cursor */ public void setCursor(String cursor) { this.cursor = cursor; } /** * Sets the href attribute in the link * * @param href the href attribute in the link */ public void setHref(String href) { this.href = href; } /** * Returns the href attribute in the link * * @return the href attribute in the link */ public String getHref() { return href; } /** * Returns the alt tag attribute in the link * * @return the alt tag attribute in the link */ public String getAltTag() { return altTag; } /** * Returns a string containing the image src, href and alt tag attributes * Used primarily for debugging purposes */ public String toString() { StringBuffer sb = new StringBuffer("\n"); sb.append("image src: ").append(imageSrc).append("\n"); sb.append("href: ").append(href).append("\n"); sb.append("alt tag: ").append(altTag).append("\n"); return sb.toString(); } } /** * PortletModeLink is a concrete instance of a Link used for creating * portlet mode hyperlinks */ public class PortletModeLink extends Link { public static final String configImage = "images/window_configure.gif"; public static final String configSymbol = "c";//WAP 2.0 Extention public static final String editImage = "images/window_edit.gif"; public static final String editSymbol = "/";//WAP 2.0 Extention public static final String helpImage = "images/window_help.gif"; public static final String helpSymbol = "?";//WAP 2.0 Extention public static final String viewImage = "images/window_view.gif"; public static final String viewSymbol = "V";//WAP 2.0Extention /** * Constructs an instance of PortletModeLink with the supplied portlet mode * * @param mode the portlet mode * @param locale the locale * @throws PortletModeException if the mode is not supported */ public PortletModeLink(PortletMode mode, Locale locale) throws PortletModeException { if (mode == null) return; ResourceBundle bundle = ResourceBundle.getBundle("gridsphere.resources.Portlet", locale); String key = mode.toString().toUpperCase(); altTag = bundle.getString(key); // Set the image src if (mode.equals(new PortletMode("CONFIG"))) { imageSrc = configImage; symbol = configSymbol;//WAP 2.0 } else if (mode.equals(PortletMode.EDIT)) { imageSrc = editImage; symbol = editSymbol;//WAP 2.0 } else if (mode.equals(PortletMode.HELP)) { imageSrc = helpImage; symbol = helpSymbol;//WAP 2.0 cursor = "help"; } else if (mode.equals(PortletMode.VIEW)) { imageSrc = viewImage; symbol = viewSymbol;//WAP 2.0 } else { throw new PortletModeException("Unsupported portlet mode: ", mode); } } } /** * PortletStateLink is a concrete instance of a Link used for creating * portlet window state hyperlinks */ public class PortletStateLink extends Link { public static final String closeImage = "images/window_close.gif"; public static final String minimizeImage = "images/window_minimize.gif"; public static final String maximizeImage = "images/window_maximize.gif"; public static final String normalImage = "images/window_normal.gif"; public static final String floatImage = "images/window_float.gif"; public static final String closeSymbol = "X"; //WAP 2.0 public static final String minimizeSymbol = "_"; //WAP 2.0 public static final String maximizeSymbol = "="; //WAP 2.0 public static final String normalSymbol = "-"; //WAP 2.0 public static final String floatSymbol = "^"; //WAP 2.0 /** * Constructs an instance of PortletStateLink with the supplied window state * * @param state the window state * @param locale the client locale * @throws WindowStateException if the state is unsupported */ public PortletStateLink(WindowState state, Locale locale) throws WindowStateException { if (state == null) return; // Set the image src if (state.equals(WindowState.MINIMIZED)) { imageSrc = minimizeImage; symbol = minimizeSymbol; } else if (state.equals(WindowState.MAXIMIZED)) { imageSrc = maximizeImage; symbol = maximizeSymbol; } else if (state.equals(WindowState.NORMAL)) { imageSrc = normalImage; symbol = normalSymbol; } else if (state.equals(new WindowState("closed"))) { imageSrc = closeImage; symbol = closeSymbol; } else if (state.equals(new WindowState("floating"))) { imageSrc = floatImage; symbol = floatSymbol; } else { throw new WindowStateException("Unsupported window state window mode: ", state); } ResourceBundle bundle = ResourceBundle.getBundle("gridsphere.resources.Portlet", locale); String key = state.toString().toUpperCase(); altTag = bundle.getString(key); } } /** * Constructs an instance of PortletTitleBar */ public PortletTitleBar() { } /** * Sets the portlet class used to render the title bar * * @param portletClass the concrete portlet class */ public void setPortletClass(String portletClass) { this.portletClass = portletClass; } /** * Returns the portlet class used in rendering the title bar * * @return the concrete portlet class */ public String getPortletClass() { return portletClass; } public boolean isActive() { return isActive; } public void setActive(boolean isActive) { this.isActive = isActive; } /** * Returns the title of the portlet title bar * * @return the portlet title bar */ public String getTitle() { return title; } /** * Sets the title of the portlet title bar * * @param title the portlet title bar */ public void setTitle(String title) { this.title = title; } /** * Sets the window state of this title bar * * @param state the portlet window state expressed as a string */ public void setWindowState(WindowState state) { if (state != null) this.windowState = state; } /** * Returns the window state of this title bar * * @return the portlet window state expressed as a string */ public WindowState getWindowState() { return windowState; } /** * Sets the window state of this title bar * * @param state the portlet window state expressed as a string */ public void setWindowStateAsString(String state) { if (state != null) { try { this.windowState = new WindowState(state); } catch (IllegalArgumentException e) { // do nothing } } } /** * Returns the window state of this title bar * * @return the portlet window state expressed as a string */ public String getWindowStateAsString() { return windowState.toString(); } /** * Sets the portlet mode of this title bar * * @param mode the portlet mode expressed as a string */ public void setPortletMode(PortletMode mode) { if (mode != null) this.portletMode = mode; } /** * Returns the portlet mode of this title bar * * @return the portlet mode expressed as a string */ public PortletMode getPortletMode() { return portletMode; } /** * Sets the portlet mode of this title bar * * @param mode the portlet mode expressed as a string */ public void setPreviousMode(PortletMode mode) { if (mode != null) this.previousMode = mode; } /** * Returns the portlet mode of this title bar * * @return the portlet mode expressed as a string */ public PortletMode getPreviousMode() { return previousMode; } /** * Sets the portlet mode of this title bar * * @param mode the portlet mode expressed as a string */ public void setPortletModeAsString(String mode) { if (mode == null) return; try { this.portletMode = new PortletMode(mode); } catch (IllegalArgumentException e) { // do nothing } } /** * Returns the portlet mode of this title bar * * @return the portlet mode expressed as a string */ public String getPortletModeAsString() { return portletMode.toString(); } /** * Indicates an error ocurred suring the processing of this title bar * * @return <code>true</code> if an error occured during rendering, * <code>false</code> otherwise */ public boolean hasRenderError() { return hasError; } /** * Returns any errors associated with the functioning of this title bar * * @return any title bar errors that occured */ public String getErrorMessage() { return errorMessage; } /** * Initializes the portlet title bar. Since the components are isolated * after Castor unmarshalls from XML, the ordering is determined by a * passed in List containing the previous portlet components in the tree. * * @param list a list of component identifiers * @return a list of updated component identifiers * @see ComponentIdentifier */ public List<ComponentIdentifier> init(PortletRequest req, List<ComponentIdentifier> list) { list = super.init(req, list); titleView = (Render) getRenderClass(req, "TitleBar"); portletInvoker = new PortletInvoker(); ComponentIdentifier compId = new ComponentIdentifier(); compId.setPortletComponent(this); compId.setPortletClass(portletClass); compId.setComponentID(list.size()); compId.setComponentLabel(label); compId.setClassName(this.getClass().getName()); list.add(compId); portletRegistryService = (PortletRegistryService) PortletServiceFactory.createPortletService(PortletRegistryService.class, true); String appID = portletRegistryService.getApplicationPortletID(portletClass); ApplicationPortlet appPortlet = portletRegistryService.getApplicationPortlet(appID); if (appPortlet != null) { allowedWindowStates = appPortlet.getAllowedWindowStates(); allowedWindowStates = sort(allowedWindowStates); if (canModify) { if (!allowedWindowStates.contains(new WindowState("CLOSED"))) { allowedWindowStates.add(new WindowState("CLOSED")); } } } displayModes = req.getAttribute(SportletProperties.DISPLAY_MODES).equals(Boolean.TRUE); displayStates = req.getAttribute(SportletProperties.DISPLAY_STATES).equals(Boolean.TRUE); return list; } /** * Simple sorting algoritm that sorts in increasing order a <code>List</code> * containing objects that implement <code>Comparator</code> * * @param list a <code>List</code> to be sorted * @return the sorted list */ private List<javax.portlet.WindowState> sort(List<javax.portlet.WindowState> list) { List<javax.portlet.WindowState> tmp = new ArrayList<javax.portlet.WindowState>(); if (list.contains(WindowState.MINIMIZED)) { tmp.add(WindowState.MINIMIZED); } if (list.contains(WindowState.NORMAL)) { tmp.add(WindowState.NORMAL); } if (list.contains(WindowState.MAXIMIZED)) { tmp.add(WindowState.MAXIMIZED); } if (list.contains(new WindowState("CLOSED"))) { tmp.add(new WindowState("CLOSED")); } if (list.contains(new WindowState("FLOATING"))) { tmp.add(new WindowState("FLOATING")); } return tmp; } /** * Creates the portlet window state hyperlinks displayed in the title bar * * @param event the gridsphere event * @return a list of window state hyperlinks */ public List<PortletStateLink> createWindowLinks(GridSphereEvent event) { super.doRender(event); PortletURL portletURL; RenderResponse res = event.getRenderResponse(); if (allowedWindowStates.isEmpty()) return null; if (!displayStates) return null; //String[] windowStates = new String[allowedWindowStates.size()]; List<javax.portlet.WindowState> windowStates = new ArrayList<javax.portlet.WindowState>(); for (WindowState state : allowedWindowStates) { windowStates.add(state); // remove current state from list if (state.equals(windowState) && (!windowState.equals(new WindowState("closed")))) { windowStates.remove(state); } } // get rid of floating if window state is minimized if (windowState.equals(WindowState.MINIMIZED)) { windowStates.remove(new WindowState("floating")); } // Localize the window state names RenderRequest req = event.getRenderRequest(); Locale locale = req.getLocale(); // create a URI for each of the window states PortletStateLink stateLink; List<PortletStateLink> stateLinks = new ArrayList<PortletStateLink>(); for (WindowState state : windowStates) { portletURL = res.createActionURL(); try { stateLink = new PortletStateLink(state, locale); portletURL.setWindowState(state); stateLink.setHref(portletURL.toString()); if (state.equals(new WindowState("floating"))) { stateLink.setHref(portletURL.toString() + "\" onclick=\"return GridSphere_popup(this, 'notes')\""); } stateLinks.add(stateLink); } catch (WindowStateException e) { log.error("a window state exception occurred! " + state); } } return stateLinks; } /** * Creates the portlet mode hyperlinks displayed in the title bar * * @param event the gridsphere event * @return a list of portlet mode hyperlinks */ public List<PortletTitleBar.PortletModeLink> createModeLinks(GridSphereEvent event) { super.doRender(event); RenderResponse res = event.getRenderResponse(); RenderRequest req = event.getRenderRequest(); if (!displayModes) return null; // make modes from supported modes Set<String> supportedModes = (Set<String>) req.getAttribute(SportletProperties.ALLOWED_MODES); if (supportedModes == null) return null; // Unless user is admin they should not see configure mode boolean hasConfigurePermission = req.isUserInRole(PortletRole.ADMIN.getName()); List<String> smodes = new ArrayList<String>(); for (String mode : supportedModes) { if (mode.equalsIgnoreCase("config")) { if (hasConfigurePermission) { smodes.add(mode); } } else { smodes.add(mode); } // remove current mode from list smodes.remove(portletMode.toString()); } // Localize the portlet mode names Locale locale = req.getLocale(); List<PortletModeLink> portletLinks = new ArrayList<PortletModeLink>(); for (String mode : smodes) { // create a URI for each of the portlet modes PortletModeLink modeLink; PortletURL portletURL = res.createActionURL(); try { PortletMode pmode = new PortletMode(mode); modeLink = new PortletModeLink(pmode, locale); portletURL.setPortletMode(pmode); modeLink.setHref(portletURL.toString()); portletLinks.add(modeLink); } catch (PortletModeException e) { log.error("Unable to get mode for : " + mode); } } return portletLinks; } /** * Performs an action on this portlet title bar component * * @param event a gridsphere event */ public void actionPerformed(GridSphereEvent event) { super.actionPerformed(event); isActive = true; HttpServletRequest req = event.getHttpServletRequest(); ActionResponse res = event.getActionResponse(); req.setAttribute(SportletProperties.PORTLETID, portletClass); // Render title bar Set<String> supportedModes = null; String appID = portletRegistryService.getApplicationPortletID(portletClass); ApplicationPortlet appPortlet = portletRegistryService.getApplicationPortlet(appID); if (appPortlet != null) { supportedModes = appPortlet.getSupportedModes(event.getClient().getMimeType()); } req.setAttribute(SportletProperties.ALLOWED_MODES, supportedModes); // pop last event off stack event.getLastRenderEvent(); PortletTitleBarEvent titleBarEvent = new PortletTitleBarEventImpl(this, event, COMPONENT_ID); Principal principal = event.getActionRequest().getUserPrincipal(); if (principal != null) { if (titleBarEvent.hasAction()) { if (titleBarEvent.hasWindowStateAction()) { // don't set window state if it is floating if (!titleBarEvent.getState().equals(new WindowState("floating"))) windowState = titleBarEvent.getState(); //System.err.println("setting window state= " + windowState); PortletWindowEvent winEvent = null; // if receive a window state that is not supported do nothing if (!allowedWindowStates.contains(windowState)) return; if (windowState.equals(WindowState.MAXIMIZED)) { winEvent = new PortletWindowEventImpl(req, PortletWindowEvent.WINDOW_MAXIMIZED); } else if (windowState.equals(WindowState.MINIMIZED)) { winEvent = new PortletWindowEventImpl(req, PortletWindowEvent.WINDOW_MINIMIZED); } else if (windowState.equals(WindowState.NORMAL)) { winEvent = new PortletWindowEventImpl(req, PortletWindowEvent.WINDOW_RESTORED); } else if (windowState.equals(new WindowState("CLOSED"))) { winEvent = new PortletWindowEventImpl(req, PortletWindowEvent.WINDOW_CLOSED); } if (winEvent != null) { try { portletInvoker.windowEvent((String) req.getAttribute(SportletProperties.PORTLETID), winEvent, req, (HttpServletResponse) res); } catch (Exception e) { hasError = true; errorMessage += "Failed to invoke window event method of portlet: " + portletClass; } } } if (titleBarEvent.hasPortletModeAction()) { /* if (titleBarEvent.getMode().equals(Portlet.Mode.CONFIGURE)) { @TODO fix me boolean hasrole = aclService.hasRequiredRole(req, portletClass, true); if (!hasrole) return; }*/ previousMode = portletMode; portletMode = titleBarEvent.getMode(); //System.err.println("mode = " + portletMode); //System.err.println("prev mode = " + previousMode); } } } req.setAttribute(SportletProperties.PORTLET_WINDOW, windowState); try { res.setPortletMode(portletMode); } catch (PortletModeException e) { log.error("Unable to set mode to " + portletMode); } req.setAttribute(SportletProperties.PREVIOUS_MODE, previousMode); for (PortletComponent comp : listeners) { event.addNewRenderEvent(titleBarEvent); comp.actionPerformed(event); } } /** * Fires a title bar event notification * * @param event a portlet title bar event */ protected void fireTitleBarEvent(PortletTitleBarEvent event) { for (PortletComponent titleBarListener : listeners) { ((PortletTitleBarListener) titleBarListener).handleTitleBarEvent(event); } } public List<PortletTitleBar.PortletModeLink> getModeLinks() { return modeLinks; } public List<PortletTitleBar.PortletStateLink> getWindowLinks() { return windowLinks; } public void doRender(GridSphereEvent event) { super.doRender(event); hasError = false; // title bar: configure, edit, help, title, min, max RenderRequest req = event.getRenderRequest(); RenderResponse res = event.getRenderResponse(); Set<String> supportedModes = null; String appID = portletRegistryService.getApplicationPortletID(portletClass); ApplicationPortlet appPortlet = portletRegistryService.getApplicationPortlet(appID); if (appPortlet != null) { supportedModes = appPortlet.getSupportedModes(event.getClient().getMimeType()); } req.setAttribute(SportletProperties.ALLOWED_MODES, supportedModes); PortalContext portalContext = appPortlet.getPortalContext(); req.setAttribute(SportletProperties.PORTAL_CONTEXT, portalContext); // get the appropriate title for this client Locale locale = req.getLocale(); Principal principal = req.getUserPrincipal(); if (principal != null) { if (portletClass != null) { modeLinks = createModeLinks(event); windowLinks = createWindowLinks(event); } } //System.err.println("in title bar render portletclass=" + portletClass + ": setting prev mode= " + previousMode + " cur mode= " + portletMode); req.setAttribute(SportletProperties.PORTLET_MODE, portletMode); req.setAttribute(SportletProperties.PREVIOUS_MODE, previousMode); req.setAttribute(SportletProperties.PORTLET_WINDOW, windowState); StringBuffer preTitle = titleView.doStart(event, this); req.setAttribute(SportletProperties.RENDER_OUTPUT + COMPONENT_ID + ".pre", preTitle.toString()); StringBuffer postTitle = titleView.doEnd(event, this); req.setAttribute(SportletProperties.RENDER_OUTPUT + COMPONENT_ID + ".post", postTitle.toString()); StringWriter storedWriter = new StringWriter(); PrintWriter writer = new PrintWriter(storedWriter); PortletResponse wrappedResponse = new StoredPortletResponseImpl((HttpServletRequest) req, (HttpServletResponse) res, writer); try { //System.err.println("invoking doTitle:" + title); portletInvoker.doTitle((String) req.getAttribute(SportletProperties.PORTLETID), (HttpServletRequest) req, (HttpServletResponse) wrappedResponse); //out.println(" (" + portletMode.toString() + ") "); title = storedWriter.toString(); } catch (Exception e) { ResourceBundle bundle = ResourceBundle.getBundle("gridsphere.resources.Portlet", locale); title = bundle.getString("PORTLET_UNAVAILABLE"); hasError = true; errorMessage = portletClass + " " + title + "!\n"; //"PortletException:" + e.getMessage(); log.error(portletClass + " is currently unavailable:", e); } } public String getPreBufferedTitle(PortletRequest req) { String preTitle = (String) req.getAttribute(SportletProperties.RENDER_OUTPUT + COMPONENT_ID + ".pre"); req.removeAttribute(SportletProperties.RENDER_OUTPUT + COMPONENT_ID + ".pre"); return preTitle; } public String getPostBufferedTitle(PortletRequest req) { String postTitle = (String) req.getAttribute(SportletProperties.RENDER_OUTPUT + COMPONENT_ID + ".post"); req.removeAttribute(SportletProperties.RENDER_OUTPUT + COMPONENT_ID + ".post"); return postTitle; } public Object clone() throws CloneNotSupportedException { PortletTitleBar t = (PortletTitleBar) super.clone(); t.title = this.title; t.portletClass = this.portletClass; t.portletMode = new PortletMode(this.portletMode.toString()); t.windowState = new WindowState(this.windowState.toString()); t.previousMode = this.previousMode; return t; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append(super.toString()); return sb.toString(); } }
/* * $Id: BaseServletManager.java,v 1.9 2005-07-08 23:16:38 tlipkis Exp $ */ package org.lockss.servlet; import java.io.*; import java.net.*; import java.util.*; import org.lockss.app.*; import org.lockss.config.Configuration; import org.lockss.daemon.*; import org.lockss.util.*; import org.lockss.config.*; import org.lockss.jetty.*; import org.mortbay.http.*; import org.mortbay.http.handler.*; import org.mortbay.jetty.servlet.*; /** * Base class for servlet managers. * Note: this class may be used in an environment where the LOCKSS app is * not running (<i>e.g.</i>, for {@link org.lockss.servlet.TinyUi}), so it * must not rely on any non-static app services, nor any other managers. */ public abstract class BaseServletManager extends JettyManager implements ServletManager { public static final String UI_REALM = "LOCKSS Admin"; public static final String PASSWORD_PROPERTY_FILE = "admin.props"; public static final String PREFIX = Configuration.PREFIX + "ui."; public static final String PARAM_START = PREFIX + "start"; public static final String PARAM_PORT = PREFIX + "port"; public static final String IP_ACCESS_PREFIX = PREFIX + "access.ip."; public static final String PARAM_IP_INCLUDE = IP_ACCESS_PREFIX + "include"; public static final String PARAM_IP_EXCLUDE = IP_ACCESS_PREFIX + "exclude"; public static final String PARAM_LOG_FORBIDDEN = IP_ACCESS_PREFIX + "logForbidden"; public static final boolean DEFAULT_LOG_FORBIDDEN = true; public static final String PARAM_USER_AUTH = PREFIX + "access.auth"; public static final boolean DEFAULT_USER_AUTH = true; public static final String PARAM_LOGDIR = Configuration.PREFIX + "platform.logdirectory"; public static final boolean DEFAULT_START = true; public static final int DEFAULT_PORT = 8081; public static final String PARAM_PLATFORM_USERNAME = Configuration.PLATFORM + "ui.username"; public static final String PARAM_PLATFORM_PASSWORD = Configuration.PLATFORM + "ui.password"; private static Logger log = Logger.getLogger("ServletMgr"); private static String textMimes[] = { "out", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", }; protected int port; private boolean start; private String includeIps; private String excludeIps; private boolean logForbidden; protected boolean doAuth; protected String logdir; List accessHandlers = new ArrayList(); public BaseServletManager(String serverName) { super(serverName); } /** Start servlets */ public void startService() { if (start) { super.startService(); startServlets(); } } /** Stop servlets */ public void stopService() { stopServer(); super.stopService(); } protected LockssDaemon getDaemon() { return (LockssDaemon)getApp(); } public void setConfig(Configuration config, Configuration prevConfig, Configuration.Differences changedKeys) { super.setConfig(config, prevConfig, changedKeys); port = config.getInt(PARAM_PORT, DEFAULT_PORT); start = config.getBoolean(PARAM_START, DEFAULT_START); logdir = config.get(PARAM_LOGDIR); doAuth = config.getBoolean(PARAM_USER_AUTH, DEFAULT_USER_AUTH); if (changedKeys.contains(PARAM_IP_INCLUDE) || changedKeys.contains(PARAM_IP_EXCLUDE) || changedKeys.contains(PARAM_LOG_FORBIDDEN)) { includeIps = config.get(PARAM_IP_INCLUDE, ""); excludeIps = config.get(PARAM_IP_EXCLUDE, ""); logForbidden = config.getBoolean(PARAM_LOG_FORBIDDEN, DEFAULT_LOG_FORBIDDEN); log.debug("Installing new ip filter: incl: " + includeIps + ", excl: " + excludeIps); setIpFilters(); } } void setIpFilters() { for (Iterator iter = accessHandlers.iterator(); iter.hasNext(); ) { setIpFilter((IpAccessHandler)iter.next()); } } void setIpFilter(IpAccessHandler ah) { try { IpFilter filter = new IpFilter(); filter.setFilters(includeIps, excludeIps, ';'); ah.setFilter(filter); } catch (IpFilter.MalformedException e) { log.warning("Malformed IP filter, filters not changed", e); } ah.setLogForbidden(logForbidden); ah.setAllowLocal(true); } // Manually install password set by platform config. // XXX Doesn't handle roles, will need to be integrated with daemon // password setting mechanism protected void setConfiguredPasswords(HashUserRealm realm) { // Use platform config in case real config hasn't been loaded yet (when // used from TinyUI) Configuration platConfig = ConfigManager.getPlatformConfig(); String platUser = platConfig.get(PARAM_PLATFORM_USERNAME); String platPass = platConfig.get(PARAM_PLATFORM_PASSWORD); if (!StringUtil.isNullString(platUser) && !StringUtil.isNullString(platPass)) { realm.put(platUser, platPass); } } protected abstract void startServlets(); protected void addAccessHandler(HttpContext context) { IpAccessHandler ah = new IpAccessHandler(serverName); setIpFilter(ah); context.addHandler(ah); accessHandlers.add(ah); } protected void setContextAuthHandler(HttpContext context, UserRealm realm) { if (realm != null) { context.setRealm(realm); context.setAuthenticator(new BasicAuthenticator()); context.addHandler(new SecurityHandler()); context.addSecurityConstraint("/", new SecurityConstraint("Admin", "*")); } } protected void setupLogContext(HttpServer server, UserRealm realm, String contextPath, String logdir) throws MalformedURLException { HttpContext context = server.getContext(contextPath); // Don't consume memory with cached log files context.setMaxCachedFileSize(0); // IpAccessHandler is always first handler addAccessHandler(context); // user authentication handler setContextAuthHandler(context, realm); // log dir resource String logdirname = (logdir != null) ? logdir : ""; URL logResourceUrl=new URL("file", null, new File(logdirname).getAbsolutePath()); log.debug("Log Resource URL: " + logResourceUrl); context.setResourceBase(logResourceUrl.toString()); ResourceHandler logRHandler = new ResourceHandler(); logRHandler.setDirAllowed(true); // logRHandler.setPutAllowed(false); // rHandler.setDelAllowed(false); // rHandler.setAcceptRanges(true); context.addHandler(logRHandler); for (int ix = 0; ix < textMimes.length; ix++) { context.setMimeMapping(textMimes[ix], "text/plain"); } // context.setMimeMapping("gz", "text/gzip"); // context.setTypeEncoding("text/gzip", "x-gzip"); // NotFoundHandler context.addHandler(new NotFoundHandler()); } // Add a servlet if its class can be loaded. protected void addServletIfAvailable(ServletHandler handler, String name, String pathSpec, String servletClass) { try { Class.forName(servletClass); handler.addServlet(name, pathSpec, servletClass); } catch (ClassNotFoundException e) { log.warning("Not starting servlet \"" + name + "\", class not found: " + servletClass); } } }
package org.lunatecs316.frc2014.vision; import edu.wpi.first.wpilibj.networktables.NetworkTable; import java.awt.GridLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.List; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.WindowConstants; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.MatOfInt; import org.opencv.core.MatOfPoint; import org.opencv.core.MatOfPoint2f; import org.opencv.core.Point; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.core.Size; import org.opencv.highgui.Highgui; import org.opencv.highgui.VideoCapture; import org.opencv.imgproc.Imgproc; /** * 2014 FRC Vision Processing * @author Domenic Rodriguez */ public class LuNaCV { public static final String kCameraAddress = "http://10.3.16.11/mjpg/video.mjpg"; public static final int kImageWidth = 320; public static final int kImageHeight = 240; public static final int kMinHue = 70; public static final int kMinSat = 53; public static final int kMinVal = 93; public static final int kMaxHue = 180; public static final int kMaxSat = 255; public static final int kMaxVal = 255; public static final int kMorphKernelSize = 2; public static final int kMinTargetArea = 75; public static final int kMaxTargetArea = 750; public static final double kApproxPolyTolerance = 0.0295; public static final double kStaticTargetWidth = 4; // Inches public static final double kStaticTargetHeight = 32; // Inches public static final double kDynamicTargetWidth = 4; // Inches public static final double kDynamicTargetLength = 23.5; // Inches public static final int kCameraViewAngle = 47; // Degrees // Compute once instead of every loop public static final double kTanTheta = Math.tan(((kCameraViewAngle / 2) * Math.PI) / 180); private NetworkTable table; private JFrame frame; private CVMatPanel originalPanel; private CVMatPanel processedPanel; private VideoCapture camera; private JSlider minHueSlider; private JSlider minSatSlider; private JSlider minValSlider; private JSlider maxHueSlider; private JSlider maxSatSlider; private JSlider maxValSlider; private boolean done = false; private boolean debug = false; public void run() { // Load OpenCV native library System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // Initialize NetworkTables if (!debug) { NetworkTable.setClientMode(); NetworkTable.setIPAddress("10.3.16.2"); table = NetworkTable.getTable("visionData"); } // Setup the GUI setupGUI(); if (debug) { processSampleImages(); //while (true) { // processSampleImage("sample_images/image1.jpg"); } else { // Open the camera feed camera = new VideoCapture(kCameraAddress); // Process images from the camera processCameraFeed(); } } /** * Create the GUI elements */ private void setupGUI() { // Setup GUI frame = new JFrame("LuNaCV"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent we) { done = true; } }); frame.getContentPane().setLayout(new GridLayout(2, 2)); // Add Image panels originalPanel = new CVMatPanel(kImageWidth, kImageHeight); frame.getContentPane().add(originalPanel); processedPanel = new CVMatPanel(kImageWidth, kImageHeight); frame.getContentPane().add(processedPanel); // Add sliders JPanel sliders = new JPanel(); sliders.setLayout(new BoxLayout(sliders, BoxLayout.Y_AXIS)); JLabel minHueLabel = new JLabel("minHue"); minHueSlider = new JSlider(JSlider.HORIZONTAL, 0, 180, kMinHue); JLabel minSatLabel = new JLabel("minSat"); minSatSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, kMinSat); JLabel minValLabel = new JLabel("minVal"); minValSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, kMinVal); JLabel maxHueLabel = new JLabel("maxHue"); maxHueSlider = new JSlider(JSlider.HORIZONTAL, 0, 180, kMaxHue); JLabel maxSatLabel = new JLabel("maxSat"); maxSatSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, kMaxSat); JLabel maxValLabel = new JLabel("maxVal"); maxValSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, kMaxVal); sliders.add(minHueLabel); sliders.add(minHueSlider); sliders.add(minSatLabel); sliders.add(minSatSlider); sliders.add(minValLabel); sliders.add(minValSlider); sliders.add(maxHueLabel); sliders.add(maxHueSlider); sliders.add(maxSatLabel); sliders.add(maxSatSlider); sliders.add(maxValLabel); sliders.add(maxValSlider); frame.getContentPane().add(sliders); // Display the frame frame.pack(); frame.setVisible(true); } /** * Process a continuous feed of images from the camera */ private void processCameraFeed() { Mat original = new Mat(); while (!done) { if (camera.isOpened()) {// && table.getBoolean("enabled", true)) { if (camera.read(original)) { Mat processed = processImage(original); originalPanel.showMat(original); processedPanel.showMat(processed); } else { System.err.println("Error: unable to read image"); } } else { System.out.println("Error: camera is not open"); try { Thread.sleep(5000); } catch (InterruptedException ex) { } } } } /** * Process the sample images. Used for testing */ private void processSampleImages() { for (int i = 1; i <= 10; i++) { System.out.println("Image " + i); processSampleImage("sample_images/image" + i + ".jpg"); try { Thread.sleep(2000); } catch (InterruptedException ex){ } } } /** * Process a single sample image * @param filepath the path to the image */ private void processSampleImage(String filepath) { Mat original = Highgui.imread(filepath); Mat processed = processImage(original); originalPanel.showMat(original); processedPanel.showMat(processed); } /** * Process the image and search for the targets * @param image the original image * @return the processed image */ private Mat processImage(Mat image) { double startTime = System.currentTimeMillis(); // Convert image to HSV color space Mat hsv = new Mat(); Imgproc.cvtColor(image, hsv, Imgproc.COLOR_BGR2HSV); // Apply color threshold Mat thresh = new Mat(); Scalar lowerBound = new Scalar(minHueSlider.getValue(), minSatSlider.getValue(), minValSlider.getValue()); Scalar upperBound = new Scalar(maxHueSlider.getValue(), maxSatSlider.getValue(), maxValSlider.getValue()); Core.inRange(hsv, lowerBound, upperBound, thresh); System.out.println("Threshold: " + lowerBound + " " + upperBound); // Morph operations to filter out small blobs Mat morphKernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(kMorphKernelSize, kMorphKernelSize)); Imgproc.morphologyEx(thresh, thresh, Imgproc.MORPH_OPEN, morphKernel); // Find contours List<MatOfPoint> contours = new ArrayList<>(); Mat heirarchy = new Mat(); Imgproc.findContours(thresh.clone(), contours, heirarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE); // Check the number of contours if (contours.size() > 2) { System.out.println("Warning: more than 2 contours found! Proceed with caution..."); } // Process contours for targets MatOfInt hullIndices = new MatOfInt(); List<Point> hullPointList = new ArrayList<>(); MatOfPoint hull = new MatOfPoint(); MatOfPoint2f approx2f = new MatOfPoint2f(); List<MatOfPoint> polygons = new ArrayList<>(); Rect target; List<Rect> horizontalTargets = new ArrayList<>(); List<Rect> verticalTargets = new ArrayList<>(); double distanceSum = 0; for (int i = 0; i < contours.size(); i++) { // Get the next contour MatOfPoint contour = contours.get(i); // Skip any contours too big or small to be the target double contourArea = Imgproc.contourArea(contour); if (contourArea < kMinTargetArea || contourArea > kMaxTargetArea) { continue; } // Convex Hull Imgproc.convexHull(contour, hullIndices); // hullIndices is the indices of the points // in the original contour that form the convex hull List<Integer> hullIndexList = hullIndices.toList(); hullPointList.clear(); for (int j = 0; j < hullIndexList.size(); j++) { // Build the required points from the contour into a list hullPointList.add(contour.toList().get(hullIndexList.get(j))); } hull.fromList(hullPointList); // Create a MatOfPoint from the list we built // Approximate a polygon from the convex hull MatOfPoint2f contour2f = new MatOfPoint2f(hull.toArray()); double contourLength = Imgproc.arcLength(contour2f, true); Imgproc.approxPolyDP(contour2f, approx2f, contourLength * kApproxPolyTolerance, true); MatOfPoint polygon = new MatOfPoint(approx2f.toArray()); polygons.add(polygon); // Find the bounding rectangle of the polygon target = Imgproc.boundingRect(polygon); // Draw the rectangle over the original image Core.rectangle(image, target.tl(), target.br(), new Scalar(255, 0, 0)); // Check the orientation of the target boolean isHorizontal = target.width > target.height; if (isHorizontal) { horizontalTargets.add(target); } else { verticalTargets.add(target); } // Display information about target System.out.print("Target " + i + ": Vertices " + polygon.total() + " "); System.out.print("Position: (" + target.x + "," + target.y + ") "); System.out.print("Width: " + target.width + " Height: " + target.height + " "); System.out.print("Area: " + (target.width * target.height) + " "); double distance = getTargetDistance(target.width, isHorizontal); distanceSum += distance; System.out.print("Distance: " + distance + " "); if (isHorizontal) { System.out.println("Horizontal"); } else { System.out.println("Vertical"); } } // Draw the polygons in the output image Mat drawing = Mat.zeros(thresh.size(), thresh.type()); for (int i = 0; i < polygons.size(); i++) Imgproc.drawContours(drawing, polygons, i, new Scalar(255, 255, 255), -1); // Estimate the distance to the target double distance = distanceSum / polygons.size(); System.out.println("Estimated distance: " + distance); // Determine if the goal is hot or not System.out.println("Horizontal Targets: " + horizontalTargets.size() + " Vertical Targets: " + verticalTargets.size()); boolean goalIsHot; if (verticalTargets.size() == 1 && horizontalTargets.size() == 1) { System.out.println("Goal is Hot"); goalIsHot = true; } else if (verticalTargets.size() == 1 && horizontalTargets.isEmpty()) { System.out.println("Goal is not hot"); goalIsHot = false; } else { System.out.println("Unsure if goal is hot or not..."); goalIsHot = false; } System.out.println("Image processed in " + (System.currentTimeMillis() - startTime) + "ms"); // Send data to the robot if (!debug) { table.putBoolean("goalIsHot", goalIsHot); table.putNumber("distance", distance); } System.out.println(); return drawing; } /** * Get the distance to the specified target * @param pxWidth * @param horizontal * @return the distance in inches to the target */ private double getTargetDistance(double pxWidth, boolean dynamic) { double result; if (dynamic) { result = (kDynamicTargetLength * kImageWidth) / (2 * kTanTheta * pxWidth); } else { result = (kStaticTargetWidth * kImageWidth) / (2 * kTanTheta * pxWidth); } return result; } public static void main(String[] args) { new LuNaCV().run(); } }
package org.mozilla.mozstumbler; import android.net.wifi.ScanResult; final class SSIDBlockList { private static final String[] PREFIX_LIST = { // Mobile devices "AndroidAP", "AndroidHotspot", "Android Hotspot", "barnacle", // Android tether app "Galaxy Note", "Galaxy S", "Galaxy Tab", "HTC ", "iPhone", "Lenovo P780_ROW", "LG-MS770", "LG-MS870", "LG VS910 4G", "LG Vortex", "MIFI", "MiFi", "myLGNet", "myTouch 4G Hotspot", "NOKIA Lumia", "PhoneAP", "SCH-I", "Sprint MiFi", "Verizon ", "Verizon-", "VirginMobile MiFi", "VodafoneMobileWiFi-", "FirefoxHotspot", "Mobile Hotspot", // BlackBerry OS 10 // Transportation Wi-Fi "ac_transit_wifi_bus", "AirportExpressZone", // Oslo airport express train on-train WiFi (Norway) "AmtrakConnect", "Amtrak_", "amtrak_", "arriva", //Arriva Nederland on-train Wifi (Netherlands) "Barcelona Bus Turistic ", "Boreal_Kundenett", // Tromso on-boat (and probably bus) WiFi (Norway) "Bus4You-", // Bus4You on-bus WiFi (Norway) "CapitalBus", // Capital Bus on-bus WiFi (Taiwan) "CDWiFi", "CommuteNet", "csadplzen_bus", // CSAD Plzen bus hotspots: http://www.csadplzen.cz/?ob=aktuality#wifi7 "EMT-Madrid", "Flybussekspressen", // Oslo airport transportation on-bus WiFi (Norway) "Flybussen", // Airport transportation on-bus WiFi all over Norway (Norway) "Flygbussarna Free WiFi ", // Flygbussarna.se on-bus WiFi (Sweden) "GBUS", "GBusWifi", "gogoinflight", // Gogo in-flight WiFi "Hot-Spot-KS", // Koleje Slaskie transportation services (Poland) "wifi_rail", // BART "egged.co.il", // Egged transportation services (Israel) "gb-tours.com", // GB Tours transportation services (Israel) "ISRAEL-RAILWAYS", "Kolumbus", // Stavanger public transport on-boat WiFi (Norway) "KOLUMBUS", // Stavanger public transport on-bus WiFi (Norway) "Kystbussen_Kundennett", // Kystbussen on-bus WiFi (Norway) "MAVSTART-WiFi", // Hungarian State Railways onboard hotspot on InterCity trains (Hungary) "Nateev-WiFi", // Nateev Express transportation services (Israel) "NationalExpress", // National Express on-bus WiFi (United Kingdom) "Norgesbuss", // Norgesbuss on-bus WiFi (Norway) "Norwegian Internet Access", // Norwegian in-flight WiFi (Norway) "NSB_INTERAKTIV", // NSB on-train WiFi (Norway) "Omni-WiFi", // Omnibus transportation services (Israel) "Oxford Tube", // Oxford Tube on-bus WiFi (United Kindom) "QbuzzWIFI", //Qbuzz on-bus WiFi (Netherlands) "SF Shuttle Wireless", "ShuttleWiFi", "Southwest WiFi", // Southwest Airlines in-flight WiFi "SST-PR-1", // Sears Home Service van hotspot?! "stagecoach-wifi", // Stagecoach on-bus WiFi (United Kingdom) "Telekom_ICE", // Deutsche Bahn on-train WiFi "TPE-Free Bus", // Taipei City on-bus WiFi (Taiwan) "THSR-VeeTIME", // Taiwan High Speed Rail on-train WiFi "TriangleTransitWiFi_", // Triangle Transit on-bus WiFi "VR-junaverkko", // VR on-train WiFi (Finland) "WiFi in de trein", //Nederlandse Spoorwegen on-train WiFi (Netherlands) "wifi@boreal.no", // Boreal on-bus WiFi (Norway) "wifi@nettbuss.no", // Nettbuss on-bus WiFi (Norway) "first-wifi" // First Bus wifi (United Kingdom) }; private static final String[] SUFFIX_LIST = { // Mobile devices "iPhone", "iphone", "MIFI", "MIFI", "MiFi", "Mifi", "mifi", "mi-fi", "MyWi", "Phone", "Portable Hotspot", "Tether", "tether", // Google's SSID opt-out "_nomap", }; private SSIDBlockList() { } static boolean contains(ScanResult scanResult) { String SSID = scanResult.SSID; if (SSID == null) { return true; // no SSID? } for (String prefix : PREFIX_LIST) { if (SSID.startsWith(prefix)) { return true; // blocked! } } for (String suffix : SUFFIX_LIST) { if (SSID.endsWith(suffix)) { return true; // blocked! } } return false; } }
package org.vertexium.elasticsearch; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.index.query.FilterBuilder; import org.elasticsearch.index.query.FilterBuilders; import org.vertexium.*; import org.vertexium.elasticsearch.score.ScoringStrategy; import org.vertexium.query.VertexQuery; import java.util.List; import java.util.Map; import static org.vertexium.util.IterableUtils.toArray; public class ElasticSearchSearchVertexQuery extends ElasticSearchSearchQueryBase implements VertexQuery { private final Vertex sourceVertex; public ElasticSearchSearchVertexQuery( TransportClient client, Graph graph, Vertex sourceVertex, String queryString, Map<String, PropertyDefinition> propertyDefinitions, ScoringStrategy scoringStrategy, IndexSelectionStrategy indexSelectionStrategy, Authorizations authorizations ) { super(client, graph, queryString, propertyDefinitions, scoringStrategy, indexSelectionStrategy, authorizations); this.sourceVertex = sourceVertex; } @Override protected List<FilterBuilder> getFilters(ElasticSearchElementType elementType) { List<FilterBuilder> results = super.getFilters(elementType); if (elementType.equals(ElasticSearchElementType.VERTEX)) { String[] ids = toArray(sourceVertex.getVertexIds(Direction.BOTH, getParameters().getAuthorizations()), String.class); results.add(FilterBuilders.idsFilter().ids(ids)); } return results; } }
package com.github.droibit.plugin.truth.postfix.example; import org.junit.Test; import java.util.Arrays; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import static java.util.Arrays.asList; import static org.junit.Assert.fail; /** * @author kumagai */ public class TruthPostfixTest { @Test public void truthAssertThatWithInt() { int actual = 100; assertThat(actual).isEqualTo(100); } @Test public void truthAssertThatWithFloat() { float actual = 100.0f; assertThat(actual).isWithin(100.0f); } @Test public void truthAssertThatWithDouble() { double actual = 100.0; assertThat(actual).isWithin(100); } @Test public void truthAssertWithMessage() { try { assertWithMessage("custom msg").that(asList(1, 2, 3)).contains(5); fail("Should have thrown."); } catch (AssertionError e) { assertThat(e).hasMessage("custom msg: <[1, 2, 3]> should have contained <5>"); } } }
package com.proofpoint.experimental.http.client; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.proofpoint.experimental.discovery.client.ServiceDescriptor; import com.proofpoint.experimental.discovery.client.ServiceSelector; import java.net.URI; import java.net.URISyntaxException; import java.util.Collections; import java.util.List; import static java.lang.String.format; public class HttpServiceSelector { private final ServiceSelector serviceSelector; public HttpServiceSelector(ServiceSelector serviceSelector) { Preconditions.checkNotNull(serviceSelector, "serviceSelector is null"); this.serviceSelector = serviceSelector; } public URI selectHttpService() { List<ServiceDescriptor> serviceDescriptors = Lists.newArrayList(serviceSelector.selectAllServices()); if (serviceDescriptors.isEmpty()) { throw new IllegalStateException(format("No '%s' services from pool '%s' are available", serviceSelector.getType(), serviceSelector.getPool())); } Collections.shuffle(serviceDescriptors); // favor https over http for (ServiceDescriptor serviceDescriptor : serviceDescriptors) { String https = serviceDescriptor.getProperties().get("https"); if (https != null) { try { return new URI(https); } catch (URISyntaxException ignored) { } } } for (ServiceDescriptor serviceDescriptor : serviceDescriptors) { String http = serviceDescriptor.getProperties().get("http"); if (http != null) { try { return new URI(http); } catch (URISyntaxException ignored) { } } } throw new IllegalStateException(format("No '%s' services from pool '%s' with a http or https property available", serviceSelector.getType(), serviceSelector.getPool())); } }
package io.quarkus.arc.runtime.context; import java.util.Map; import org.eclipse.microprofile.context.ThreadContext; import org.eclipse.microprofile.context.spi.ThreadContextController; import org.eclipse.microprofile.context.spi.ThreadContextProvider; import org.eclipse.microprofile.context.spi.ThreadContextSnapshot; import io.quarkus.arc.Arc; import io.quarkus.arc.ArcContainer; import io.quarkus.arc.InjectableContext; import io.quarkus.arc.ManagedContext; /** * Context propagation for Arc * Only handles Request context as that's currently the only one in Arc that needs propagation. */ public class ArcContextProvider implements ThreadContextProvider { protected static final ThreadContextController NOOP_CONTROLLER = new ThreadContextController() { @Override public void endContext() throws IllegalStateException { } }; @Override public ThreadContextSnapshot currentContext(Map<String, String> map) { ArcContainer arc = Arc.container(); if (arc == null || !arc.isRunning()) { //return null as per docs to state that propagation of this context is not supported return null; } // capture the state, null indicates no active context while capturing snapshot InjectableContext.ContextState state = isContextActiveOnThisThread(arc) ? arc.requestContext().getState() : null; return new ThreadContextSnapshot() { @Override public ThreadContextController begin() { // can be called later on, we should retrieve the container again ArcContainer arcContainer = Arc.container(); if (arcContainer == null || !arcContainer.isRunning()) { //this happens on shutdown, if we blow up here it can break shutdown, and stop //resources from being cleaned up, causing tests to fail return NOOP_CONTROLLER; } ThreadContextController controller; ManagedContext requestContext = arcContainer.requestContext(); // this is executed on another thread, context can but doesn't need to be active here if (ArcContextProvider.this.isContextActiveOnThisThread(arcContainer)) { // context active, store current state, feed it new one and restore state afterwards InjectableContext.ContextState stateToRestore = requestContext.getState(); requestContext.deactivate(); if (state != null) { // only activate if previous thread had it active requestContext.activate(state); } controller = new ThreadContextController() { @Override public void endContext() throws IllegalStateException { // clean up, reactivate context with previous values if (state != null) { // only deactivate if previous thread had it active requestContext.deactivate(); } requestContext.activate(stateToRestore); } }; } else { // context not active, activate and pass it new instance, deactivate afterwards if (state != null) { // only activate if previous thread had it active requestContext.activate(state); } controller = new ThreadContextController() { @Override public void endContext() throws IllegalStateException { if (state != null) { // only deactivate if previous thread had it active requestContext.deactivate(); } } }; } return controller; } }; } @Override public ThreadContextSnapshot clearedContext(Map<String, String> map) { // note that by cleared we mean that we still activate context if need be, just leave the contents blank ArcContainer arc = Arc.container(); if (arc == null || !arc.isRunning()) { //return null as per docs to state that propagation of this context is not supported return null; } return new ThreadContextSnapshot() { @Override public ThreadContextController begin() { // an be called later on, we should retrieve the container again ArcContainer arcContainer = Arc.container(); if (arcContainer == null || !arcContainer.isRunning()) { return NOOP_CONTROLLER; } ThreadContextController controller; ManagedContext requestContext = arcContainer.requestContext(); // this is executed on another thread, context can but doesn't need to be active here if (ArcContextProvider.this.isContextActiveOnThisThread(arcContainer)) { // context active, store current state, start blank context anew and restore state afterwards InjectableContext.ContextState stateToRestore = requestContext.getState(); requestContext.deactivate(); requestContext.activate(); controller = () -> { // clean up, reactivate context with previous values requestContext.deactivate(); requestContext.activate(stateToRestore); }; } else { // context not active, activate blank one, deactivate afterwards requestContext.activate(); controller = new ThreadContextController() { @Override public void endContext() throws IllegalStateException { requestContext.deactivate(); } }; } return controller; } }; } @Override public String getThreadContextType() { return ThreadContext.CDI; } private boolean isContextActiveOnThisThread(ArcContainer arc) { return arc.requestContext().isActive(); } }
package com.oracle.graal.replacements; import static com.oracle.graal.api.meta.MetaUtil.*; import static com.oracle.graal.compiler.GraalCompiler.*; import static com.oracle.graal.phases.GraalOptions.*; import java.lang.reflect.*; import java.util.*; import java.util.concurrent.*; import sun.misc.*; import com.oracle.graal.api.code.*; import com.oracle.graal.api.meta.*; import com.oracle.graal.api.replacements.*; import com.oracle.graal.debug.*; import com.oracle.graal.debug.internal.*; import com.oracle.graal.graph.*; import com.oracle.graal.java.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.java.*; import com.oracle.graal.nodes.java.MethodCallTargetNode.InvokeKind; import com.oracle.graal.nodes.spi.*; import com.oracle.graal.phases.*; import com.oracle.graal.phases.common.*; import com.oracle.graal.phases.tiers.*; import com.oracle.graal.phases.util.*; import com.oracle.graal.replacements.Snippet.DefaultSnippetInliningPolicy; import com.oracle.graal.replacements.Snippet.SnippetInliningPolicy; import com.oracle.graal.word.phases.*; public class ReplacementsImpl implements Replacements { protected final Providers providers; protected final TargetDescription target; protected final Assumptions assumptions; /** * The preprocessed replacement graphs. */ private final ConcurrentMap<ResolvedJavaMethod, StructuredGraph> graphs; // These data structures are all fully initialized during single-threaded // compiler startup and so do not need to be concurrent. private final Map<ResolvedJavaMethod, ResolvedJavaMethod> registeredMethodSubstitutions; private final Map<ResolvedJavaMethod, Class<? extends FixedWithNextNode>> registeredMacroSubstitutions; private final Set<ResolvedJavaMethod> forcedSubstitutions; private final Map<Class<? extends SnippetTemplateCache>, SnippetTemplateCache> snippetTemplateCache; public ReplacementsImpl(Providers providers, Assumptions assumptions) { this.providers = providers.copyWith(this); this.target = providers.getCodeCache().getTarget(); this.assumptions = assumptions; this.graphs = new ConcurrentHashMap<>(); this.registeredMethodSubstitutions = new HashMap<>(); this.registeredMacroSubstitutions = new HashMap<>(); this.forcedSubstitutions = new HashSet<>(); this.snippetTemplateCache = new HashMap<>(); } private static final boolean UseSnippetGraphCache = Boolean.parseBoolean(System.getProperty("graal.useSnippetGraphCache", "true")); private static final DebugTimer SnippetPreparationTime = Debug.timer("SnippetPreparationTime"); public StructuredGraph getSnippet(ResolvedJavaMethod method) { assert method.getAnnotation(Snippet.class) != null : "Snippet must be annotated with @" + Snippet.class.getSimpleName(); assert !Modifier.isAbstract(method.getModifiers()) && !Modifier.isNative(method.getModifiers()) : "Snippet must not be abstract or native"; StructuredGraph graph = UseSnippetGraphCache ? graphs.get(method) : null; if (graph == null) { try (TimerCloseable a = SnippetPreparationTime.start()) { StructuredGraph newGraph = makeGraph(method, null, inliningPolicy(method), method.getAnnotation(Snippet.class).removeAllFrameStates()); if (UseSnippetGraphCache) { return newGraph; } graphs.putIfAbsent(method, newGraph); graph = graphs.get(method); } } return graph; } public StructuredGraph getMethodSubstitution(ResolvedJavaMethod original) { ResolvedJavaMethod substitute = registeredMethodSubstitutions.get(original); if (substitute == null) { return null; } StructuredGraph graph = graphs.get(substitute); if (graph == null) { graphs.putIfAbsent(substitute, makeGraph(substitute, original, inliningPolicy(substitute), false)); graph = graphs.get(substitute); } return graph; } public Class<? extends FixedWithNextNode> getMacroSubstitution(ResolvedJavaMethod method) { return registeredMacroSubstitutions.get(method); } public Assumptions getAssumptions() { return assumptions; } public void registerSubstitutions(Class<?> substitutions) { ClassSubstitution classSubstitution = substitutions.getAnnotation(ClassSubstitution.class); assert classSubstitution != null; assert !Snippets.class.isAssignableFrom(substitutions); for (Method substituteMethod : substitutions.getDeclaredMethods()) { MethodSubstitution methodSubstitution = substituteMethod.getAnnotation(MethodSubstitution.class); MacroSubstitution macroSubstitution = substituteMethod.getAnnotation(MacroSubstitution.class); if (methodSubstitution == null && macroSubstitution == null) { continue; } int modifiers = substituteMethod.getModifiers(); if (!Modifier.isStatic(modifiers)) { throw new GraalInternalError("Substitution methods must be static: " + substituteMethod); } if (methodSubstitution != null) { if (macroSubstitution != null && macroSubstitution.isStatic() != methodSubstitution.isStatic()) { throw new GraalInternalError("Macro and method substitution must agree on isStatic attribute: " + substituteMethod); } if (Modifier.isAbstract(modifiers) || Modifier.isNative(modifiers)) { throw new GraalInternalError("Substitution method must not be abstract or native: " + substituteMethod); } String originalName = originalName(substituteMethod, methodSubstitution.value()); Class[] originalParameters = originalParameters(substituteMethod, methodSubstitution.signature(), methodSubstitution.isStatic()); Member originalMethod = originalMethod(classSubstitution, methodSubstitution.optional(), originalName, originalParameters); if (originalMethod != null) { ResolvedJavaMethod original = registerMethodSubstitution(originalMethod, substituteMethod); if (original != null && methodSubstitution.forced() && shouldIntrinsify(original)) { forcedSubstitutions.add(original); } } } if (macroSubstitution != null) { String originalName = originalName(substituteMethod, macroSubstitution.value()); Class[] originalParameters = originalParameters(substituteMethod, macroSubstitution.signature(), macroSubstitution.isStatic()); Member originalMethod = originalMethod(classSubstitution, macroSubstitution.optional(), originalName, originalParameters); if (originalMethod != null) { ResolvedJavaMethod original = registerMacroSubstitution(originalMethod, macroSubstitution.macro()); if (original != null && macroSubstitution.forced() && shouldIntrinsify(original)) { forcedSubstitutions.add(original); } } } } } /** * Registers a method substitution. * * @param originalMember a method or constructor being substituted * @param substituteMethod the substitute method * @return the original method */ protected ResolvedJavaMethod registerMethodSubstitution(Member originalMember, Method substituteMethod) { MetaAccessProvider metaAccess = providers.getMetaAccess(); ResolvedJavaMethod substitute = metaAccess.lookupJavaMethod(substituteMethod); ResolvedJavaMethod original; if (originalMember instanceof Method) { original = metaAccess.lookupJavaMethod((Method) originalMember); } else { original = metaAccess.lookupJavaConstructor((Constructor) originalMember); } Debug.log("substitution: " + MetaUtil.format("%H.%n(%p)", original) + " --> " + MetaUtil.format("%H.%n(%p)", substitute)); registeredMethodSubstitutions.put(original, substitute); return original; } /** * Registers a macro substitution. * * @param originalMethod a method or constructor being substituted * @param macro the substitute macro node class * @return the original method */ protected ResolvedJavaMethod registerMacroSubstitution(Member originalMethod, Class<? extends FixedWithNextNode> macro) { ResolvedJavaMethod originalJavaMethod; MetaAccessProvider metaAccess = providers.getMetaAccess(); if (originalMethod instanceof Method) { originalJavaMethod = metaAccess.lookupJavaMethod((Method) originalMethod); } else { originalJavaMethod = metaAccess.lookupJavaConstructor((Constructor) originalMethod); } registeredMacroSubstitutions.put(originalJavaMethod, macro); return originalJavaMethod; } private SnippetInliningPolicy inliningPolicy(ResolvedJavaMethod method) { Class<? extends SnippetInliningPolicy> policyClass = SnippetInliningPolicy.class; Snippet snippet = method.getAnnotation(Snippet.class); if (snippet != null) { policyClass = snippet.inlining(); } if (policyClass == SnippetInliningPolicy.class) { return new DefaultSnippetInliningPolicy(providers.getMetaAccess()); } try { return policyClass.getConstructor().newInstance(); } catch (Exception e) { throw new GraalInternalError(e); } } /** * Creates a preprocessed graph for a snippet or method substitution. * * @param method the snippet or method substitution for which a graph will be created * @param original the original method if {@code method} is a {@linkplain MethodSubstitution * substitution} otherwise null * @param policy the inlining policy to use during preprocessing * @param removeAllFrameStates removes all frame states from side effecting instructions */ public StructuredGraph makeGraph(ResolvedJavaMethod method, ResolvedJavaMethod original, SnippetInliningPolicy policy, boolean removeAllFrameStates) { return createGraphMaker(method, original).makeGraph(policy, removeAllFrameStates); } /** * Can be overridden to return an object that specializes various parts of graph preprocessing. */ protected GraphMaker createGraphMaker(ResolvedJavaMethod substitute, ResolvedJavaMethod original) { return new GraphMaker(substitute, original); } /** * Cache to speed up preprocessing of replacement graphs. */ final ConcurrentMap<ResolvedJavaMethod, StructuredGraph> graphCache = new ConcurrentHashMap<>(); /** * Creates and preprocesses a graph for a replacement. */ protected class GraphMaker { /** * The method for which a graph is being created. */ protected final ResolvedJavaMethod method; /** * The original method if {@link #method} is a {@linkplain MethodSubstitution substitution} * otherwise null. */ protected final ResolvedJavaMethod original; boolean substituteCallsOriginal; protected GraphMaker(ResolvedJavaMethod substitute, ResolvedJavaMethod original) { this.method = substitute; this.original = original; } public StructuredGraph makeGraph(final SnippetInliningPolicy policy, final boolean removeAllFrameStates) { return Debug.scope("BuildSnippetGraph", new Object[]{method}, new Callable<StructuredGraph>() { @Override public StructuredGraph call() throws Exception { StructuredGraph graph = parseGraph(method, policy); // Cannot have a finalized version of a graph in the cache graph = graph.copy(); finalizeGraph(graph, removeAllFrameStates); Debug.dump(graph, "%s: Final", method.getName()); return graph; } }); } /** * Does final processing of a snippet graph. */ protected void finalizeGraph(StructuredGraph graph, boolean removeAllFrameStates) { new NodeIntrinsificationPhase(providers).apply(graph); if (!SnippetTemplate.hasConstantParameter(method)) { NodeIntrinsificationVerificationPhase.verify(graph); } new ConvertDeoptimizeToGuardPhase().apply(graph); if (original == null) { if (removeAllFrameStates) { for (Node node : graph.getNodes()) { if (node instanceof StateSplit) { ((StateSplit) node).setStateAfter(null); } } } else { new SnippetFrameStateCleanupPhase().apply(graph); } } new DeadCodeEliminationPhase().apply(graph); } private StructuredGraph parseGraph(final ResolvedJavaMethod methodToParse, final SnippetInliningPolicy policy) { StructuredGraph graph = graphCache.get(methodToParse); if (graph == null) { StructuredGraph newGraph = Debug.scope("ParseGraph", new Object[]{methodToParse}, new Callable<StructuredGraph>() { public StructuredGraph call() throws Exception { return buildGraph(methodToParse, policy == null ? inliningPolicy(methodToParse) : policy); } }); graphCache.putIfAbsent(methodToParse, newGraph); graph = graphCache.get(methodToParse); assert graph != null; } return graph; } /** * Builds the initial graph for a snippet. */ protected StructuredGraph buildInitialGraph(final ResolvedJavaMethod methodToParse) { final StructuredGraph graph = new StructuredGraph(methodToParse); Debug.scope("buildInitialGraph", graph, new Runnable() { @Override public void run() { MetaAccessProvider metaAccess = providers.getMetaAccess(); ForeignCallsProvider foreignCalls = providers.getForeignCalls(); new GraphBuilderPhase(metaAccess, foreignCalls, GraphBuilderConfiguration.getSnippetDefault(), OptimisticOptimizations.NONE).apply(graph); new WordTypeVerificationPhase(metaAccess, target.wordKind).apply(graph); new WordTypeRewriterPhase(metaAccess, target.wordKind).apply(graph); if (OptCanonicalizer.getValue()) { new CanonicalizerPhase(true).apply(graph, new PhaseContext(providers, assumptions)); } } }); return graph; } protected Object beforeInline(@SuppressWarnings("unused") MethodCallTargetNode callTarget, @SuppressWarnings("unused") StructuredGraph callee) { return null; } /** * Called after a graph is inlined. * * @param caller the graph into which {@code callee} was inlined * @param callee the graph that was inlined into {@code caller} * @param beforeInlineData value returned by {@link #beforeInline}. */ protected void afterInline(StructuredGraph caller, StructuredGraph callee, Object beforeInlineData) { if (OptCanonicalizer.getValue()) { new CanonicalizerPhase(true).apply(caller, new PhaseContext(providers, assumptions)); } } /** * Called after all inlining for a given graph is complete. */ protected void afterInlining(StructuredGraph graph) { new NodeIntrinsificationPhase(providers).apply(graph); new DeadCodeEliminationPhase().apply(graph); if (OptCanonicalizer.getValue()) { new CanonicalizerPhase(true).apply(graph, new PhaseContext(providers, assumptions)); } } private StructuredGraph buildGraph(final ResolvedJavaMethod methodToParse, final SnippetInliningPolicy policy) { assert !Modifier.isAbstract(methodToParse.getModifiers()) && !Modifier.isNative(methodToParse.getModifiers()) : methodToParse; final StructuredGraph graph = buildInitialGraph(methodToParse); Debug.scope("buildGraph", graph, new Runnable() { @Override public void run() { for (MethodCallTargetNode callTarget : graph.getNodes(MethodCallTargetNode.class)) { ResolvedJavaMethod callee = callTarget.targetMethod(); if (callee == method) { final StructuredGraph originalGraph = new StructuredGraph(original); MetaAccessProvider metaAccess = providers.getMetaAccess(); ForeignCallsProvider foreignCalls = providers.getForeignCalls(); new GraphBuilderPhase(metaAccess, foreignCalls, GraphBuilderConfiguration.getSnippetDefault(), OptimisticOptimizations.NONE).apply(originalGraph); new WordTypeVerificationPhase(metaAccess, target.wordKind).apply(graph); new WordTypeRewriterPhase(metaAccess, target.wordKind).apply(graph); InliningUtil.inline(callTarget.invoke(), originalGraph, true); Debug.dump(graph, "after inlining %s", callee); afterInline(graph, originalGraph, null); substituteCallsOriginal = true; } else { StructuredGraph intrinsicGraph = InliningUtil.getIntrinsicGraph(ReplacementsImpl.this, callee); if ((callTarget.invokeKind() == InvokeKind.Static || callTarget.invokeKind() == InvokeKind.Special) && (policy.shouldInline(callee, methodToParse) || (intrinsicGraph != null && policy.shouldUseReplacement(callee, methodToParse)))) { StructuredGraph targetGraph; if (intrinsicGraph != null && policy.shouldUseReplacement(callee, methodToParse)) { targetGraph = intrinsicGraph; } else { if (callee.getName().startsWith("$jacoco")) { throw new GraalInternalError("Parsing call to JaCoCo instrumentation method " + format("%H.%n(%p)", callee) + " from " + format("%H.%n(%p)", methodToParse) + " while preparing replacement " + format("%H.%n(%p)", method) + ". Placing \"//JaCoCo Exclude\" anywhere in " + methodToParse.getDeclaringClass().getSourceFileName() + " should fix this."); } targetGraph = parseGraph(callee, policy); } Object beforeInlineData = beforeInline(callTarget, targetGraph); InliningUtil.inline(callTarget.invoke(), targetGraph, true); Debug.dump(graph, "after inlining %s", callee); afterInline(graph, targetGraph, beforeInlineData); } } } afterInlining(graph); for (LoopEndNode end : graph.getNodes(LoopEndNode.class)) { end.disableSafepoint(); } new DeadCodeEliminationPhase().apply(graph); } }); return graph; } } private static String originalName(Method substituteMethod, String methodSubstitution) { if (methodSubstitution.isEmpty()) { return substituteMethod.getName(); } else { return methodSubstitution; } } /** * Resolves a name to a class. * * @param className the name of the class to resolve * @param optional if true, resolution failure returns null * @return the resolved class or null if resolution fails and {@code optional} is true */ static Class resolveType(String className, boolean optional) { try { // Need to use launcher class path to handle classes // that are not on the boot class path ClassLoader cl = Launcher.getLauncher().getClassLoader(); return Class.forName(className, false, cl); } catch (ClassNotFoundException e) { if (optional) { return null; } throw new GraalInternalError("Could not resolve type " + className); } } private static Class resolveType(JavaType type) { JavaType base = type; int dimensions = 0; while (base.getComponentType() != null) { base = base.getComponentType(); dimensions++; } Class baseClass = base.getKind() != Kind.Object ? base.getKind().toJavaClass() : resolveType(toJavaName(base), false); return dimensions == 0 ? baseClass : Array.newInstance(baseClass, new int[dimensions]).getClass(); } private Class[] originalParameters(Method substituteMethod, String methodSubstitution, boolean isStatic) { Class[] parameters; if (methodSubstitution.isEmpty()) { parameters = substituteMethod.getParameterTypes(); if (!isStatic) { assert parameters.length > 0 : "must be a static method with the 'this' object as its first parameter"; parameters = Arrays.copyOfRange(parameters, 1, parameters.length); } } else { Signature signature = providers.getMetaAccess().parseMethodDescriptor(methodSubstitution); parameters = new Class[signature.getParameterCount(false)]; for (int i = 0; i < parameters.length; i++) { parameters[i] = resolveType(signature.getParameterType(i, null)); } } return parameters; } private static Member originalMethod(ClassSubstitution classSubstitution, boolean optional, String name, Class[] parameters) { Class<?> originalClass = classSubstitution.value(); if (originalClass == ClassSubstitution.class) { originalClass = resolveType(classSubstitution.className(), classSubstitution.optional()); if (originalClass == null) { // optional class was not found return null; } } try { if (name.equals("<init>")) { return originalClass.getDeclaredConstructor(parameters); } else { return originalClass.getDeclaredMethod(name, parameters); } } catch (NoSuchMethodException | SecurityException e) { if (optional) { return null; } throw new GraalInternalError(e); } } @Override public Collection<ResolvedJavaMethod> getAllReplacements() { HashSet<ResolvedJavaMethod> result = new HashSet<>(); result.addAll(registeredMethodSubstitutions.keySet()); result.addAll(registeredMacroSubstitutions.keySet()); return result; } @Override public boolean isForcedSubstitution(ResolvedJavaMethod method) { return forcedSubstitutions.contains(method); } @Override public void registerSnippetTemplateCache(SnippetTemplateCache templates) { assert snippetTemplateCache.get(templates.getClass()) == null; snippetTemplateCache.put(templates.getClass(), templates); } @Override public <T extends SnippetTemplateCache> T getSnippetTemplateCache(Class<T> templatesClass) { SnippetTemplateCache ret = snippetTemplateCache.get(templatesClass); return templatesClass.cast(ret); } }
package peergos.server; import java.util.concurrent.atomic.*; import java.util.logging.*; import peergos.server.space.*; import peergos.server.storage.*; import peergos.server.util.*; import peergos.server.corenode.*; import peergos.server.mutable.*; import peergos.shared.*; import peergos.shared.cbor.*; import peergos.shared.corenode.*; import peergos.shared.crypto.asymmetric.*; import peergos.shared.crypto.hash.*; import peergos.shared.mutable.*; import peergos.shared.storage.*; import peergos.shared.user.*; import peergos.shared.util.*; import java.time.*; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.*; import java.util.concurrent.*; import java.util.stream.Collectors; /** This class checks whether a given user is using more storage space than their quota * */ public class SpaceCheckingKeyFilter implements SpaceUsage { private static final Logger LOG = Logging.LOG(); private static final long USAGE_TOLERANCE = 1024 * 1024; private final CoreNode core; private final MutablePointers mutable; private final ContentAddressedStorage dht; private final UserQuotas quotaSupplier; private final JdbcSpaceRequests spaceRequests; private final Path statePath; private final State state; private boolean initializedFully = false; private final AtomicBoolean isRunning = new AtomicBoolean(true); private final BlockingQueue<MutableEvent> mutableQueue = new ArrayBlockingQueue<>(1000); /** * * @param core * @param mutable * @param dht * @param quotaSupplier The quota supplier * @param statePath path to local file with user usages */ public SpaceCheckingKeyFilter(CoreNode core, MutablePointers mutable, ContentAddressedStorage dht, UserQuotas quotaSupplier, JdbcSpaceRequests spaceRequests, Path statePath) { this.core = core; this.mutable = mutable; this.dht = dht; this.quotaSupplier = quotaSupplier; this.spaceRequests = spaceRequests; this.statePath = statePath; this.state = initState(statePath, mutable, dht); new Thread(() -> { while (isRunning.get()) { try { MutableEvent event = mutableQueue.take(); processMutablePointerEvent(event); } catch (InterruptedException e) {} } }, "SpaceCheckingKeyFilter").start(); //add shutdown-hook to call close Runtime.getRuntime().addShutdownHook(new Thread(this::close, "SpaceChecker shutdown")); } public static class State implements Cborable { final Map<PublicKeyHash, Stat> currentView; final Map<String, Usage> usage; public State(Map<PublicKeyHash, Stat> currentView, Map<String, Usage> usage) { this.currentView = currentView; this.usage = usage; } @Override public CborObject toCbor() { TreeMap<CborObject, ? extends Cborable> viewsMap = currentView.entrySet() .stream() .collect(Collectors.toMap( e -> e.getKey().toCbor(), e -> (Cborable) (e.getValue()), (a,b) -> a, TreeMap::new )); CborObject.CborMap views = new CborObject.CborMap(viewsMap); CborObject.CborMap usages = CborObject.CborMap.build(usage); Map<String, Cborable> map = new HashMap<>(); map.put("views", views); map.put("usages", usages); return CborObject.CborMap.build(map); } public static State fromCbor(CborObject cbor) { CborObject.CborMap map = (CborObject.CborMap) cbor; CborObject.CborMap viewsMap = (CborObject.CborMap) map.get("views"); CborObject.CborMap usagesMap = (CborObject.CborMap) map.get("usages"); return new State(viewsMap.getMap(PublicKeyHash::fromCbor, Stat::fromCbor), usagesMap.getMap(e -> ((CborObject.CborString) e).value, Usage::fromCbor)); } public Map<String, Usage> getUsage() { return new ConcurrentHashMap<>(usage); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; State state = (State) o; if (currentView != null ? !currentView.equals(state.currentView) : state.currentView != null) return false; return usage != null ? usage.equals(state.usage) : state.usage == null; } @Override public int hashCode() { int result = currentView != null ? currentView.hashCode() : 0; result = 31 * result + (usage != null ? usage.hashCode() : 0); return result; } } public static class Stat implements Cborable { public final String owner; private MaybeMultihash target; private long directRetainedStorage; private Set<PublicKeyHash> ownedKeys; public Stat(String owner, MaybeMultihash target, long directRetainedStorage, Set<PublicKeyHash> ownedKeys) { this.owner = owner; this.target = target; this.directRetainedStorage = directRetainedStorage; this.ownedKeys = ownedKeys; } public synchronized void update(MaybeMultihash target, Set<PublicKeyHash> ownedKeys, long retainedStorage) { this.target = target; this.ownedKeys = Collections.unmodifiableSet(ownedKeys); this.directRetainedStorage = retainedStorage; } public synchronized long getDirectRetainedStorage() { return directRetainedStorage; } public synchronized MaybeMultihash getRoot() { return target; } public synchronized Set<PublicKeyHash> getOwnedKeys() { return Collections.unmodifiableSet(ownedKeys); } @Override public CborObject toCbor() { Map<String, Cborable> map = new HashMap<>(); map.put("owner", new CborObject.CborString(owner)); map.put("target", target); map.put("storage", new CborObject.CborLong(directRetainedStorage)); map.put("ownedKey", new CborObject.CborList(ownedKeys.stream().collect(Collectors.toList()))); return CborObject.CborMap.build(map); } public static Stat fromCbor(Cborable cbor) { CborObject.CborMap map = (CborObject.CborMap) cbor; String owner = map.getString("owner"); MaybeMultihash target = map.get("target", MaybeMultihash::fromCbor); long storage = map.getLong("storage"); List<PublicKeyHash> ownedKeys = map.getList("ownedKey").map(PublicKeyHash::fromCbor); return new Stat(owner, target, storage, new HashSet<>(ownedKeys)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Stat stat = (Stat) o; if (directRetainedStorage != stat.directRetainedStorage) return false; if (owner != null ? !owner.equals(stat.owner) : stat.owner != null) return false; if (target != null ? !target.equals(stat.target) : stat.target != null) return false; return ownedKeys != null ? ownedKeys.equals(stat.ownedKeys) : stat.ownedKeys == null; } @Override public int hashCode() { int result = owner != null ? owner.hashCode() : 0; result = 31 * result + (target != null ? target.hashCode() : 0); result = 31 * result + (int) (directRetainedStorage ^ (directRetainedStorage >>> 32)); result = 31 * result + (ownedKeys != null ? ownedKeys.hashCode() : 0); return result; } } public static class Usage implements Cborable { private long totalBytes; private boolean errored; private Map<PublicKeyHash, Long> pending = new HashMap<>(); public Usage(long totalBytes) { this.totalBytes = totalBytes; } protected synchronized void confirmUsage(PublicKeyHash writer, long usageDelta) { pending.remove(writer); totalBytes += usageDelta; errored = false; } protected synchronized void addPending(PublicKeyHash writer, long usageDelta) { pending.put(writer, pending.getOrDefault(writer, 0L) + usageDelta); } protected synchronized void clearPending(PublicKeyHash writer) { pending.remove(writer); } protected synchronized long getPending(PublicKeyHash writer) { return pending.getOrDefault(writer, 0L); } protected synchronized long expectedUsage() { return totalBytes + pending.values().stream().mapToLong(x -> x).sum(); } protected synchronized void setErrored(boolean errored) { this.errored = errored; } protected synchronized boolean isErrored() { return errored; } @Override public CborObject toCbor() { return new CborObject.CborLong(totalBytes); } public static Usage fromCbor(Cborable cborable) { long usage = ((CborObject.CborLong) cborable).value; return new Usage(usage); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Usage usage1 = (Usage) o; if (totalBytes != usage1.totalBytes) return false; return pending != null ? pending.equals(usage1.pending) : usage1.pending == null; } @Override public int hashCode() { int result = (int) (totalBytes ^ (totalBytes >>> 32)); result = 31 * result + (pending != null ? pending.hashCode() : 0); return result; } } private static State initState(Path statePath, MutablePointers mutable, ContentAddressedStorage dht) { State state; try { // Read stored usages and update current view. state = load(statePath); Logging.LOG().info("Successfully loaded usage-state from "+ statePath); } catch (IOException ioe) { Logging.LOG().info("Could not read usage-state from "+ statePath); // calculate usage from scratch state = new State(new ConcurrentHashMap<>(), new ConcurrentHashMap<>()); } Logging.LOG().info("Checking for updated mutable pointers..."); long t1 = System.currentTimeMillis(); for (Map.Entry<PublicKeyHash, Stat> entry : new HashSet<>(state.currentView.entrySet())) { PublicKeyHash writerKey = entry.getKey(); Stat stat = entry.getValue(); Logging.LOG().info("Checking for updates from user: " + stat.owner + ", writer key: " + writerKey); try { PublicKeyHash owner = writerKey; //NB: owner is a dummy value MaybeMultihash rootHash = mutable.getPointerTarget(owner, writerKey, dht).join(); boolean isChanged = ! stat.target.equals(rootHash); if (isChanged) { Logging.LOG().info("Root hash changed from " + stat.target + " to " + rootHash); long updatedSize = dht.getRecursiveBlockSize(rootHash.get()).get(); long deltaUsage = updatedSize - stat.directRetainedStorage; state.usage.get(stat.owner).confirmUsage(writerKey, deltaUsage); Set<PublicKeyHash> directOwnedKeys = WriterData.getDirectOwnedKeys(owner, writerKey, mutable, dht).join(); List<PublicKeyHash> newOwnedKeys = directOwnedKeys.stream() .filter(key -> !stat.ownedKeys.contains(key)) .collect(Collectors.toList()); for (PublicKeyHash newOwnedKey : newOwnedKeys) { state.currentView.putIfAbsent(newOwnedKey, new Stat(stat.owner, MaybeMultihash.empty(), 0, Collections.emptySet())); processMutablePointerEvent(state, owner, newOwnedKey, MaybeMultihash.empty(), mutable.getPointerTarget(owner, newOwnedKey, dht).get(), mutable, dht); } stat.update(rootHash, directOwnedKeys, updatedSize); Logging.LOG().info("Updated space used by " + writerKey + " to " + updatedSize); } } catch (Throwable t) { Logging.LOG().log(Level.WARNING, "Failed calculating usage for " + stat.owner, t); } } long t2 = System.currentTimeMillis(); Logging.LOG().info(LocalDateTime.now() + " Finished updating space usage for all usernames in " + (t2 - t1)/1000 + " s"); return state; } /** * Write current view of usages to this.statePath, completing any pending operations */ private synchronized void close() { try { isRunning.set(false); if (initializedFully) { store(); Logging.LOG().info("Successfully stored usage-state to " + this.statePath); } } catch (Throwable t) { Logging.LOG().info("Failed to store "+ this); t.printStackTrace(); } } /** * Read local file with cached user usages. * @return previous usages * @throws IOException */ private static State load(Path statePath) throws IOException { Logging.LOG().info("Reading state from "+ statePath +" which exists ? "+ Files.exists(statePath) +" from cwd "+ System.getProperty("cwd")); byte[] data = Files.readAllBytes(statePath); CborObject object = CborObject.deserialize(new CborDecoder(new ByteArrayInputStream(data)), data.length); return State.fromCbor(object); } /** * Store usages * @throws IOException */ private synchronized void store() throws IOException { byte[] serialized = state.toCbor().serialize(); Logging.LOG().info("Writing "+ serialized.length +" bytes to "+ statePath); Files.write( statePath, serialized, StandardOpenOption.CREATE); } /** * Walk the virtual file-system to calculate space used by each owner not already checked */ public void calculateUsage() { try { List<String> usernames = quotaSupplier.getLocalUsernames(); Logging.LOG().info("Calculating space usage for " + usernames.size() + " local users..."); for (String username : usernames) { Logging.LOG().info("Calculating space usage of " + username); try { Optional<PublicKeyHash> identity = core.getPublicKeyHash(username).get(); if (identity.isPresent()) { processCorenodeEvent(username, identity.get()); LOG.info("Updated space usage of user: " + username + " to " + state.usage.get(username).totalBytes); } else LOG.info("Identity key absent in pki for user: " + username); } catch (Exception e) { e.printStackTrace(); LOG.log(Level.WARNING, "ERROR calculating usage for user: " + username + "\n" + e.getMessage(), e); } } initializedFully = true; Logging.LOG().info("Finished calculating space usage for " + usernames.size() + " local users..."); } catch (Exception e) { LOG.log(Level.WARNING, e.getMessage(), e); } } public void accept(CorenodeEvent event) { state.currentView.computeIfAbsent(event.keyHash, k -> new Stat(event.username, MaybeMultihash.empty(), 0, Collections.emptySet())); state.usage.putIfAbsent(event.username, new Usage(0)); ForkJoinPool.commonPool().submit(() -> processCorenodeEvent(event.username, event.keyHash)); } /** Update our view of the world because a user has changed their public key (or registered) * * @param username * @param writer */ public void processCorenodeEvent(String username, PublicKeyHash writer) { try { state.usage.putIfAbsent(username, new Usage(0)); Set<PublicKeyHash> childrenKeys = WriterData.getDirectOwnedKeys(writer, writer, mutable, dht) .join() .stream() .filter(k -> ! k.equals(writer)) .collect(Collectors.toSet()); state.currentView.computeIfAbsent(writer, k -> new Stat(username, MaybeMultihash.empty(), 0, childrenKeys)); Stat current = state.currentView.get(writer); MaybeMultihash updatedRoot = mutable.getPointerTarget(writer, writer, dht).get(); processMutablePointerEvent(state, writer, writer, current.target, updatedRoot, mutable, dht); for (PublicKeyHash childKey : childrenKeys) { processCorenodeEvent(username, childKey); } } catch (Throwable e) { LOG.severe("Error loading storage for user: " + username); Exceptions.getRootCause(e).printStackTrace(); } } public void accept(MutableEvent event) { mutableQueue.add(event); try { HashCasPair hashCasPair = dht.getSigningKey(event.writer) .thenApply(signer -> HashCasPair.fromCbor(CborObject.fromByteArray(signer.get() .unsignMessage(event.writerSignedBtreeRootHash)))).get(); Set<PublicKeyHash> updatedOwned = WriterData.getDirectOwnedKeys(event.writer, hashCasPair.updated, dht).join(); Stat current = state.currentView.get(event.writer); for (PublicKeyHash owned : updatedOwned) { state.currentView.computeIfAbsent(owned, k -> new Stat(current.owner, MaybeMultihash.empty(), 0, Collections.emptySet())); } } catch (Exception e) { e.printStackTrace(); } } private void processMutablePointerEvent(MutableEvent event) { try { HashCasPair hashCasPair = dht.getSigningKey(event.writer) .thenApply(signer -> HashCasPair.fromCbor(CborObject.fromByteArray(signer.get() .unsignMessage(event.writerSignedBtreeRootHash)))).get(); processMutablePointerEvent(state, event.owner, event.writer, hashCasPair.original, hashCasPair.updated, mutable, dht); } catch (Exception e) { LOG.log(Level.WARNING, e.getMessage(), e); } } private static void processMutablePointerEvent(State state, PublicKeyHash owner, PublicKeyHash writer, MaybeMultihash existingRoot, MaybeMultihash newRoot, MutablePointers mutable, ContentAddressedStorage dht) { if (existingRoot.equals(newRoot)) return; Stat current = state.currentView.get(writer); if (current == null) throw new IllegalStateException("Unknown writer key hash: " + writer); if (! newRoot.isPresent()) { current.update(MaybeMultihash.empty(), Collections.emptySet(), 0); if (existingRoot.isPresent()) { try { // subtract data size from orphaned child keys (this assumes the keys form a tree without dupes) Set<PublicKeyHash> updatedOwned = WriterData.getDirectOwnedKeys(writer, newRoot, dht).join(); processRemovedOwnedKeys(state, owner, updatedOwned, mutable, dht); } catch (Exception e) { LOG.log(Level.WARNING, e.getMessage(), e); } } return; } try { synchronized (current) { long changeInStorage = dht.getChangeInContainedSize(current.target, newRoot.get()).get(); Set<PublicKeyHash> updatedOwned = WriterData.getDirectOwnedKeys(writer, newRoot, dht).join(); for (PublicKeyHash owned : updatedOwned) { state.currentView.computeIfAbsent(owned, k -> new Stat(current.owner, MaybeMultihash.empty(), 0, Collections.emptySet())); } Usage currentUsage = state.usage.get(current.owner); currentUsage.confirmUsage(writer, changeInStorage); HashSet<PublicKeyHash> removedChildren = new HashSet<>(current.getOwnedKeys()); removedChildren.removeAll(updatedOwned); processRemovedOwnedKeys(state, owner, removedChildren, mutable, dht); current.update(newRoot, updatedOwned, current.directRetainedStorage + changeInStorage); } } catch (Exception e) { Exceptions.getRootCause(e).printStackTrace(); } } private static void processRemovedOwnedKeys(State state, PublicKeyHash owner, Set<PublicKeyHash> removed, MutablePointers mutable, ContentAddressedStorage dht) { for (PublicKeyHash ownedKey : removed) { try { MaybeMultihash currentTarget = mutable.getPointerTarget(owner, ownedKey, dht).get(); processMutablePointerEvent(state, owner, ownedKey, currentTarget, MaybeMultihash.empty(), mutable, dht); } catch (Exception e) { LOG.log(Level.WARNING, e.getMessage(), e); } } } @Override public CompletableFuture<Long> getUsage(PublicKeyHash owner) { Stat stat = state.currentView.get(owner); if (stat == null) return Futures.errored(new IllegalStateException("Unknown identity key: " + owner)); Usage usage = state.usage.get(stat.owner); if (usage == null) return Futures.errored(new IllegalStateException("No usage present for user: " + stat.owner)); return CompletableFuture.completedFuture(usage.totalBytes); } @Override public CompletableFuture<Long> getQuota(PublicKeyHash owner, byte[] signedTime) { TimeLimited.isAllowedTime(signedTime, 120, dht, owner); Stat stat = state.currentView.get(owner); if (stat == null) return Futures.errored(new IllegalStateException("Unknown identity key: " + owner)); return CompletableFuture.completedFuture(quotaSupplier.getQuota(stat.owner)); } @Override public CompletableFuture<Boolean> requestSpace(PublicKeyHash owner, byte[] signedRequest) { // check request is valid Optional<PublicSigningKey> ownerOpt = dht.getSigningKey(owner).join(); if (!ownerOpt.isPresent()) throw new IllegalStateException("Couldn't retrieve owner key!"); byte[] raw = ownerOpt.get().unsignMessage(signedRequest); CborObject cbor = CborObject.fromByteArray(raw); SpaceUsage.SpaceRequest req = SpaceUsage.SpaceRequest.fromCbor(cbor); if (req.utcMillis < System.currentTimeMillis() - 30_000) throw new IllegalStateException("Stale auth time in space request!"); // TODO check proof of payment (if required) // TODO check user is signed up to this server return CompletableFuture.completedFuture(spaceRequests.addSpaceRequest(req.username, signedRequest)); } public boolean allowWrite(PublicKeyHash writer, int size) { Stat stat = state.currentView.get(writer); if (stat == null) throw new IllegalStateException("Unknown writing key hash: " + writer); Usage usage = state.usage.get(stat.owner); long quota = quotaSupplier.getQuota(stat.owner); long expectedUsage = usage.expectedUsage(); boolean errored = usage.isErrored(); if ((! errored && expectedUsage + size > quota) || (errored && expectedUsage + size > quota + USAGE_TOLERANCE)) { long pending = usage.getPending(writer); usage.clearPending(writer); usage.setErrored(true); throw new IllegalStateException("Storage quota reached! \nUsed " + usage.totalBytes + " out of " + quota + " bytes. Rejecting write of size " + (size + pending) + ". \n" + "Please delete some files or request more space."); } usage.addPending(writer, size); return true; } }
package com.twelvemonkeys.imageio.plugins.bmp; import com.twelvemonkeys.image.ImageUtil; import com.twelvemonkeys.imageio.ImageReaderBase; import com.twelvemonkeys.imageio.stream.SubImageInputStream; import com.twelvemonkeys.imageio.util.ImageTypeSpecifiers; import com.twelvemonkeys.util.WeakWeakMap; import javax.imageio.*; import javax.imageio.spi.ImageReaderSpi; import javax.imageio.stream.ImageInputStream; import javax.swing.*; import java.awt.*; import java.awt.color.ColorSpace; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.*; import java.io.File; import java.io.IOException; import java.nio.ByteOrder; import java.util.*; import java.util.List; // TODO: Decide whether DirectoryEntry or DIBHeader should be primary source for color count/bit count // TODO: Support loading icons from DLLs, see // Known issue: 256x256 PNG encoded icons does not have IndexColorModel even if stated in DirectoryEntry // (seem impossible as the PNGs are all true color) abstract class DIBImageReader extends ImageReaderBase { // TODO: Consider moving the reading to inner classes (subclasses of BitmapDescriptor) private Directory directory; // TODO: Review these, make sure we don't have a memory leak private Map<DirectoryEntry, DIBHeader> headers = new WeakHashMap<>(); private Map<DirectoryEntry, BitmapDescriptor> descriptors = new WeakWeakMap<>(); private ImageReader pngImageReader; protected DIBImageReader(final ImageReaderSpi pProvider) { super(pProvider); } protected void resetMembers() { directory = null; headers.clear(); descriptors.clear(); if (pngImageReader != null) { pngImageReader.dispose(); pngImageReader = null; } } public Iterator<ImageTypeSpecifier> getImageTypes(final int pImageIndex) throws IOException { DirectoryEntry entry = getEntry(pImageIndex); // NOTE: Delegate to PNG reader if (isPNG(entry)) { return getImageTypesPNG(entry); } List<ImageTypeSpecifier> types = new ArrayList<>(); DIBHeader header = getHeader(entry); // Use data from header to create specifier ImageTypeSpecifier specifier; switch (header.getBitCount()) { case 1: case 2: case 4: case 8: // TODO: This is slightly QnD... int offset = entry.getOffset() + header.getSize(); if (offset != imageInput.getStreamPosition()) { imageInput.seek(offset); } BitmapIndexed indexed = new BitmapIndexed(entry, header); readColorMap(indexed); specifier = ImageTypeSpecifiers.createFromIndexColorModel(indexed.createColorModel()); break; case 16: // TODO: May have mask?! specifier = ImageTypeSpecifiers.createFromBufferedImageType(BufferedImage.TYPE_USHORT_555_RGB); break; case 24: specifier = new BitmapRGB(entry, header).hasMask() ? ImageTypeSpecifiers.createFromBufferedImageType(BufferedImage.TYPE_4BYTE_ABGR) : ImageTypeSpecifiers.createFromBufferedImageType(BufferedImage.TYPE_3BYTE_BGR); break; case 32: specifier = ImageTypeSpecifiers.createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB); break; default: throw new IIOException(String.format("Unknown bit depth: %d", header.getBitCount())); } types.add(specifier); return types.iterator(); } @Override public int getNumImages(final boolean allowSearch) throws IOException { return getDirectory().count(); } public int getWidth(final int pImageIndex) throws IOException { return getEntry(pImageIndex).getWidth(); } public int getHeight(final int pImageIndex) throws IOException { return getEntry(pImageIndex).getHeight(); } public BufferedImage read(final int pImageIndex, final ImageReadParam pParam) throws IOException { checkBounds(pImageIndex); processImageStarted(pImageIndex); DirectoryEntry entry = getEntry(pImageIndex); BufferedImage destination; if (isPNG(entry)) { // NOTE: Special case for Windows Vista, 256x256 PNG encoded images, with no DIB header... destination = readPNG(entry, pParam); } else { // NOTE: If param does not have explicit destination, we'll try to create a BufferedImage later, // to allow for storing the cursor hotspot for CUR images destination = hasExplicitDestination(pParam) ? getDestination(pParam, getImageTypes(pImageIndex), getWidth(pImageIndex), getHeight(pImageIndex)) : null; BufferedImage image = readBitmap(entry); // TODO: Handle AOI and subsampling inline, probably not of big importance... if (pParam != null) { image = fakeAOI(image, pParam); image = ImageUtil.toBuffered(fakeSubsampling(image, pParam)); } if (destination == null) { // This is okay, as long as the client did not request explicit destination image/type destination = image; } else { Graphics2D g = destination.createGraphics(); try { g.setComposite(AlphaComposite.Src); g.drawImage(image, 0, 0, null); } finally { g.dispose(); } } } processImageProgress(100); processImageComplete(); return destination; } private boolean isPNG(final DirectoryEntry pEntry) throws IOException { long magic; imageInput.seek(pEntry.getOffset()); imageInput.setByteOrder(ByteOrder.BIG_ENDIAN); try { magic = imageInput.readLong(); } finally { imageInput.setByteOrder(ByteOrder.LITTLE_ENDIAN); } return magic == DIB.PNG_MAGIC; } private BufferedImage readPNG(final DirectoryEntry pEntry, final ImageReadParam pParam) throws IOException { // TODO: Consider delegating listener calls return initPNGReader(pEntry).read(0, pParam); } private Iterator<ImageTypeSpecifier> getImageTypesPNG(final DirectoryEntry pEntry) throws IOException { return initPNGReader(pEntry).getImageTypes(0); } private ImageReader initPNGReader(final DirectoryEntry pEntry) throws IOException { ImageReader pngReader = getPNGReader(); imageInput.seek(pEntry.getOffset()); // InputStream inputStream = IIOUtil.createStreamAdapter(imageInput, pEntry.getSize()); // ImageInputStream stream = ImageIO.createImageInputStream(inputStream); ImageInputStream stream = new SubImageInputStream(imageInput, pEntry.getSize()); // NOTE: Will throw IOException on later reads if input is not PNG pngReader.setInput(stream); return pngReader; } private ImageReader getPNGReader() throws IIOException { // TODO: Prefer Sun's std JDK PNGImagerReader, because it has known behaviour? if (pngImageReader == null) { Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("PNG"); if (readers.hasNext()) { pngImageReader = readers.next(); } else { throw new IIOException("No PNGImageReader found using ImageIO, can't read PNG encoded ICO format."); } } else { pngImageReader.reset(); } return pngImageReader; } private DIBHeader getHeader(final DirectoryEntry pEntry) throws IOException { if (!headers.containsKey(pEntry)) { imageInput.seek(pEntry.getOffset()); DIBHeader header = DIBHeader.read(imageInput); headers.put(pEntry, header); } return headers.get(pEntry); } private BufferedImage readBitmap(final DirectoryEntry pEntry) throws IOException { // TODO: Get rid of the caching, as the images are mutable BitmapDescriptor descriptor = descriptors.get(pEntry); if (descriptor == null || !descriptors.containsKey(pEntry)) { DIBHeader header = getHeader(pEntry); int offset = pEntry.getOffset() + header.getSize(); if (offset != imageInput.getStreamPosition()) { imageInput.seek(offset); } // TODO: Support this, it's already in the BMP reader, spec allows RLE4 and RLE8 if (header.getCompression() != DIB.COMPRESSION_RGB) { descriptor = new BitmapUnsupported(pEntry, String.format("Unsupported compression: %d", header.getCompression())); } else { int bitCount = header.getBitCount(); switch (bitCount) { // Palette style case 1: case 4: case 8: // TODO: Gray! descriptor = new BitmapIndexed(pEntry, header); readBitmapIndexed((BitmapIndexed) descriptor); break; // RGB style case 16: descriptor = new BitmapRGB(pEntry, header); readBitmap16(descriptor); break; case 24: descriptor = new BitmapRGB(pEntry, header); readBitmap24(descriptor); break; case 32: descriptor = new BitmapRGB(pEntry, header); readBitmap32(descriptor); break; default: descriptor = new BitmapUnsupported(pEntry, String.format("Unsupported bit count %d", bitCount)); } } descriptors.put(pEntry, descriptor); } return descriptor.getImage(); } private void readBitmapIndexed(final BitmapIndexed pBitmap) throws IOException { readColorMap(pBitmap); switch (pBitmap.getBitCount()) { case 1: readBitmapIndexed1(pBitmap, false); break; case 4: readBitmapIndexed4(pBitmap); break; case 8: readBitmapIndexed8(pBitmap); break; } BitmapMask mask = new BitmapMask(pBitmap.entry, pBitmap.header); readBitmapIndexed1(mask.bitMask, true); pBitmap.setMask(mask); } private void readColorMap(final BitmapIndexed pBitmap) throws IOException { int colorCount = pBitmap.getColorCount(); for (int i = 0; i < colorCount; i++) { // aRGB (a is "Reserved") pBitmap.colors[i] = (imageInput.readInt() & 0xffffff) | 0xff000000; } } private void readBitmapIndexed1(final BitmapIndexed pBitmap, final boolean pAsMask) throws IOException { int width = adjustToPadding(pBitmap.getWidth() >> 3); byte[] row = new byte[width]; for (int y = 0; y < pBitmap.getHeight(); y++) { imageInput.readFully(row, 0, width); int rowPos = 0; int xOrVal = 0x80; int pos = (pBitmap.getHeight() - y - 1) * pBitmap.getWidth(); for (int x = 0; x < pBitmap.getWidth(); x++) { pBitmap.bits[pos++] = ((row[rowPos] & xOrVal) / xOrVal) & 0xFF; if (xOrVal == 1) { xOrVal = 0x80; rowPos++; } else { xOrVal >>= 1; } } // NOTE: If we are reading the mask, we don't abort or report progress if (!pAsMask) { if (abortRequested()) { processReadAborted(); break; } processImageProgress(100 * y / (float) pBitmap.getHeight()); } } } private void readBitmapIndexed4(final BitmapIndexed pBitmap) throws IOException { int width = adjustToPadding(pBitmap.getWidth() >> 1); byte[] row = new byte[width]; for (int y = 0; y < pBitmap.getHeight(); y++) { imageInput.readFully(row, 0, width); int rowPos = 0; boolean high4 = true; int pos = (pBitmap.getHeight() - y - 1) * pBitmap.getWidth(); for (int x = 0; x < pBitmap.getWidth(); x++) { int value; if (high4) { value = (row[rowPos] & 0xF0) >> 4; } else { value = row[rowPos] & 0x0F; rowPos++; } pBitmap.bits[pos++] = value & 0xFF; high4 = !high4; } if (abortRequested()) { processReadAborted(); break; } processImageProgress(100 * y / (float) pBitmap.getHeight()); } } private void readBitmapIndexed8(final BitmapIndexed pBitmap) throws IOException { int width = adjustToPadding(pBitmap.getWidth()); byte[] row = new byte[width]; for (int y = 0; y < pBitmap.getHeight(); y++) { imageInput.readFully(row, 0, width); int rowPos = 0; int pos = (pBitmap.getHeight() - y - 1) * pBitmap.getWidth(); for (int x = 0; x < pBitmap.getWidth(); x++) { pBitmap.bits[pos++] = row[rowPos++] & 0xFF; } if (abortRequested()) { processReadAborted(); break; } processImageProgress(100 * y / (float) pBitmap.getHeight()); } } /** * @param pWidth Bytes per scan line (i.e., 1BPP, width = 9 -> bytes = 1) * @return padded width */ private static int adjustToPadding(final int pWidth) { if ((pWidth & 0x03) != 0) { return (pWidth & ~0x03) + 4; } return pWidth; } private void readBitmap16(final BitmapDescriptor pBitmap) throws IOException { // TODO: No idea if this actually works.. short[] pixels = new short[pBitmap.getWidth() * pBitmap.getHeight()]; // TODO: Support TYPE_USHORT_565 and the RGB 444/ARGB 4444 layouts // Will create TYPE_USHORT_555 DirectColorModel cm = new DirectColorModel(16, 0x7C00, 0x03E0, 0x001F); DataBuffer buffer = new DataBufferShort(pixels, pixels.length); WritableRaster raster = Raster.createPackedRaster( buffer, pBitmap.getWidth(), pBitmap.getHeight(), pBitmap.getWidth(), cm.getMasks(), null ); pBitmap.image = new BufferedImage(cm, raster, cm.isAlphaPremultiplied(), null); for (int y = 0; y < pBitmap.getHeight(); y++) { int offset = (pBitmap.getHeight() - y - 1) * pBitmap.getWidth(); imageInput.readFully(pixels, offset, pBitmap.getWidth()); // Skip to 32 bit boundary if (pBitmap.getWidth() % 2 != 0) { imageInput.readShort(); } if (abortRequested()) { processReadAborted(); break; } processImageProgress(100 * y / (float) pBitmap.getHeight()); } // TODO: Might be mask!? } private void readBitmap24(final BitmapDescriptor pBitmap) throws IOException { byte[] pixels = new byte[pBitmap.getWidth() * pBitmap.getHeight() * 3]; // Create TYPE_3BYTE_BGR DataBuffer buffer = new DataBufferByte(pixels, pixels.length); ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); int[] nBits = {8, 8, 8}; int[] bOffs = {2, 1, 0}; ComponentColorModel cm = new ComponentColorModel( cs, nBits, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE ); int scanlineStride = pBitmap.getWidth() * 3; // BMP rows are padded to 4 byte boundary int rowSizeBytes = ((8 * scanlineStride + 31) / 32) * 4; WritableRaster raster = Raster.createInterleavedRaster( buffer, pBitmap.getWidth(), pBitmap.getHeight(), scanlineStride, 3, bOffs, null ); pBitmap.image = new BufferedImage(cm, raster, cm.isAlphaPremultiplied(), null); for (int y = 0; y < pBitmap.getHeight(); y++) { int offset = (pBitmap.getHeight() - y - 1) * scanlineStride; imageInput.readFully(pixels, offset, scanlineStride); imageInput.skipBytes(rowSizeBytes - scanlineStride); if (abortRequested()) { processReadAborted(); break; } processImageProgress(100 * y / (float) pBitmap.getHeight()); } // 24 bit icons usually have a bit mask if (pBitmap.hasMask()) { BitmapMask mask = new BitmapMask(pBitmap.entry, pBitmap.header); readBitmapIndexed1(mask.bitMask, true); pBitmap.setMask(mask); } } private void readBitmap32(final BitmapDescriptor pBitmap) throws IOException { int[] pixels = new int[pBitmap.getWidth() * pBitmap.getHeight()]; // Will create TYPE_INT_ARGB DirectColorModel cm = (DirectColorModel) ColorModel.getRGBdefault(); DataBuffer buffer = new DataBufferInt(pixels, pixels.length); WritableRaster raster = Raster.createPackedRaster( buffer, pBitmap.getWidth(), pBitmap.getHeight(), pBitmap.getWidth(), cm.getMasks(), null ); pBitmap.image = new BufferedImage(cm, raster, cm.isAlphaPremultiplied(), null); for (int y = 0; y < pBitmap.getHeight(); y++) { int offset = (pBitmap.getHeight() - y - 1) * pBitmap.getWidth(); imageInput.readFully(pixels, offset, pBitmap.getWidth()); if (abortRequested()) { processReadAborted(); break; } processImageProgress(100 * y / (float) pBitmap.getHeight()); } // There might be a mask here as well, but we'll ignore it, // and use the 8 bit alpha channel in the ARGB pixel data } private Directory getDirectory() throws IOException { assertInput(); if (directory == null) { readFileHeader(); } return directory; } private void readFileHeader() throws IOException { imageInput.setByteOrder(ByteOrder.LITTLE_ENDIAN); // Read file header imageInput.readUnsignedShort(); // Reserved // Should be same as type as the provider int type = imageInput.readUnsignedShort(); int imageCount = imageInput.readUnsignedShort(); // Read directory directory = Directory.read(type, imageCount, imageInput); } final DirectoryEntry getEntry(final int pImageIndex) throws IOException { Directory directory = getDirectory(); if (pImageIndex < 0 || pImageIndex >= directory.count()) { throw new IndexOutOfBoundsException(String.format("Index: %d, ImageCount: %d", pImageIndex, directory.count())); } return directory.getEntry(pImageIndex); } /// Test code below, ignore.. :-) public static void main(final String[] pArgs) throws IOException { if (pArgs.length == 0) { System.err.println("Please specify the icon file name"); System.exit(1); } try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { // Ignore } String title = new File(pArgs[0]).getName(); JFrame frame = createWindow(title); JPanel root = new JPanel(new FlowLayout()); JScrollPane scroll = new JScrollPane(root, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); scroll.setBorder(BorderFactory.createEmptyBorder()); frame.setContentPane(scroll); Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("ico"); if (!readers.hasNext()) { System.err.println("No reader for format 'ico' found"); System.exit(1); } ImageReader reader = readers.next(); for (String arg : pArgs) { JPanel panel = new JPanel(null); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); readImagesInFile(arg, reader, panel); root.add(panel); } frame.pack(); frame.setVisible(true); } private static void readImagesInFile(String pFileName, ImageReader pReader, final Container pContainer) throws IOException { File file = new File(pFileName); if (!file.isFile()) { System.err.println(pFileName + " not found, or is no file"); } pReader.setInput(ImageIO.createImageInputStream(file)); int imageCount = pReader.getNumImages(true); for (int i = 0; i < imageCount; i++) { try { addImage(pContainer, pReader, i); } catch (Exception e) { System.err.println("FileName: " + pFileName); System.err.println("Icon: " + i); e.printStackTrace(); } } } private static JFrame createWindow(final String pTitle) { JFrame frame = new JFrame(pTitle); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { public void windowClosed(WindowEvent e) { System.exit(0); } }); return frame; } private static void addImage(final Container pParent, final ImageReader pReader, final int pImageNo) throws IOException { final JButton button = new JButton(); BufferedImage image = pReader.read(pImageNo); button.setIcon(new ImageIcon(image) { TexturePaint texture; private void createTexture(final GraphicsConfiguration pGraphicsConfiguration) { BufferedImage pattern = pGraphicsConfiguration.createCompatibleImage(20, 20); Graphics2D g = pattern.createGraphics(); try { g.setColor(Color.LIGHT_GRAY); g.fillRect(0, 0, pattern.getWidth(), pattern.getHeight()); g.setColor(Color.GRAY); g.fillRect(0, 0, pattern.getWidth() / 2, pattern.getHeight() / 2); g.fillRect(pattern.getWidth() / 2, pattern.getHeight() / 2, pattern.getWidth() / 2, pattern.getHeight() / 2); } finally { g.dispose(); } texture = new TexturePaint(pattern, new Rectangle(pattern.getWidth(), pattern.getHeight())); } @Override public void paintIcon(Component c, Graphics g, int x, int y) { if (texture == null) { createTexture(c.getGraphicsConfiguration()); } Graphics2D gr = (Graphics2D) g; gr.setPaint(texture); gr.fillRect(x, y, getIconWidth(), getIconHeight()); super.paintIcon(c, g, x, y); } }); button.setText("" + image.getWidth() + "x" + image.getHeight() + ": " + ((image.getColorModel() instanceof IndexColorModel) ? "" + ((IndexColorModel) image.getColorModel()).getMapSize() : "TrueColor")); pParent.add(button); } }
package com.adaptris.core.management.config; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import com.adaptris.core.Adapter; import com.adaptris.core.CoreException; import lombok.NoArgsConstructor; @NoArgsConstructor public class JavaxValidationChecker extends AdapterConfigurationChecker { private static final String FRIENDLY_NAME = "javax.validation Checks"; private static final ValidatorFactory JAVAX_VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory(); @Override protected void validate(Adapter adapter, ConfigurationCheckReport report) { try { Validator validator = JAVAX_VALIDATOR_FACTORY.getValidator(); // There are no warnings; everything is a hard failure. report.setFailureExceptions((violationsToException(validator.validate(adapter)))); } catch (Exception ex) { report.getFailureExceptions().add(ex); } } @Override public String getFriendlyName() { return FRIENDLY_NAME; } private List<Exception> violationsToException(Set<ConstraintViolation<Adapter>> violations) { return violations.stream().map((v) -> new CoreException(String .format("Interlok Validation Error: [%1$s]=[%2$s]", v.getPropertyPath(), v.getMessage()))) .collect(Collectors.toList()); } }
package org.javarosa.reminders.util; import java.util.Date; import org.javarosa.core.JavaRosaServiceProvider; import org.javarosa.core.model.data.DateData; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.instance.TreeElement; import org.javarosa.core.model.utils.IPreloadHandler; import org.javarosa.patient.model.Patient; import org.javarosa.reminders.model.Reminder; import org.javarosa.reminders.storage.ReminderRMSUtility; public class ReminderPreloadHandler implements IPreloadHandler { Patient patient; public ReminderPreloadHandler(Patient currentPatient) { patient = currentPatient; } /* * (non-Javadoc) * @see org.javarosa.core.model.utils.IPreloadHandler#handlePostProcess(org.javarosa.core.model.IFormDataModel, org.javarosa.core.model.IDataReference, java.lang.String) */ public boolean handlePostProcess(TreeElement node, String params) { ReminderRMSUtility reminderRms = (ReminderRMSUtility)JavaRosaServiceProvider.instance().getStorageManager().getRMSStorageProvider().getUtility(ReminderRMSUtility.getUtilityName()); DateData dateData = (DateData)node.getValue(); if(dateData != null) { Date date = (Date)dateData.getValue(); String patientName = patient.getName(); int patientId = patient.getRecordId(); Reminder reminder = new Reminder(date,patientId,patientName, "Follow up with " + patientName, "Follow up"); reminderRms.writeToRMS(reminder); } return false; } /* * (non-Javadoc) * @see org.javarosa.core.model.utils.IPreloadHandler#handlePreload(java.lang.String) */ public IAnswerData handlePreload(String preloadParams) { //Null is our flag about whether we want a reminder for right now. We'll possibly //deal with this more robustly in the future return null; } /* * (non-Javadoc) * @see org.javarosa.core.model.utils.IPreloadHandler#preloadHandled() */ public String preloadHandled() { return "followup"; } }
package com.intellij.debugger.ui.breakpoints; import com.intellij.debugger.engine.DebuggerUtils; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Ref; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.PairFunction; import com.intellij.xdebugger.XDebuggerUtil; import com.intellij.xdebugger.breakpoints.XLineBreakpoint; import com.intellij.xdebugger.breakpoints.XLineBreakpointType; import com.intellij.xdebugger.breakpoints.ui.XBreakpointCustomPropertiesPanel; import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.java.debugger.JavaDebuggerEditorsProvider; import org.jetbrains.java.debugger.breakpoints.JavaBreakpointFiltersPanel; import org.jetbrains.java.debugger.breakpoints.properties.JavaBreakpointProperties; /** * Base class for java line-connected exceptions (line, method, field) * @author egor */ public abstract class JavaLineBreakpointTypeBase<P extends JavaBreakpointProperties> extends XLineBreakpointType<P> { public JavaLineBreakpointTypeBase(@NonNls @NotNull String id, @Nls @NotNull String title) { super(id, title); } @Override public final boolean isSuspendThreadSupported() { return true; } @NotNull @Override public final XBreakpointCustomPropertiesPanel<XLineBreakpoint<P>> createCustomRightPropertiesPanel(@NotNull Project project) { return new JavaBreakpointFiltersPanel<>(project); } @NotNull @Override public final XDebuggerEditorsProvider getEditorsProvider(@NotNull XLineBreakpoint<P> breakpoint, @NotNull Project project) { return new JavaDebuggerEditorsProvider(); } @Override public String getDisplayText(XLineBreakpoint<P> breakpoint) { BreakpointWithHighlighter javaBreakpoint = (BreakpointWithHighlighter)BreakpointManager.getJavaBreakpoint(breakpoint); if (javaBreakpoint != null) { return javaBreakpoint.getDescription(); } else { return super.getDisplayText(breakpoint); } } protected static boolean canPutAtElement(@NotNull final VirtualFile file, final int line, @NotNull Project project, @NotNull PairFunction<PsiElement, Document, Boolean> processor) { PsiFile psiFile = PsiManager.getInstance(project).findFile(file); // JSPX supports jvm debugging, but not in XHTML files if (psiFile == null || psiFile.getViewProvider().getFileType() == StdFileTypes.XHTML) { return false; } if (!StdFileTypes.CLASS.equals(psiFile.getFileType()) && !DebuggerUtils.isBreakpointAware(psiFile)) { return false; } // workaround for KT-23886, remove after it is fixed if ("kt".equals(psiFile.getFileType().getDefaultExtension())) { return false; } Document document = FileDocumentManager.getInstance().getDocument(file); if (document != null) { Ref<Boolean> res = Ref.create(false); XDebuggerUtil.getInstance().iterateLine(project, document, line, element -> { // avoid comments if ((element instanceof PsiWhiteSpace) || (PsiTreeUtil.getParentOfType(element, PsiComment.class, PsiImportStatementBase.class, PsiPackageStatement.class) != null)) { return true; } PsiElement parent = element; while (element != null) { // skip modifiers if (element instanceof PsiModifierList) { element = element.getParent(); continue; } final int offset = element.getTextOffset(); if (offset >= 0) { if (document.getLineNumber(offset) != line) { break; } } parent = element; element = element.getParent(); } if (processor.fun(parent, document)) { res.set(true); return false; } return true; }); return res.get(); } return false; } }
package com.intellij.java.propertyBased; import com.intellij.application.options.PathMacrosImpl; import com.intellij.codeInspection.ex.InspectionProfileImpl; import com.intellij.compiler.CompilerTestUtil; import com.intellij.ide.impl.ProjectUtil; import com.intellij.openapi.application.PathMacros; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.compiler.CompilerMessage; import com.intellij.openapi.compiler.CompilerMessageCategory; import com.intellij.openapi.diagnostic.DefaultLogger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.ProjectJdkTable; import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiJavaFile; import com.intellij.psi.PsiManager; import com.intellij.psi.search.FilenameIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.testFramework.CompilerTester; import com.intellij.testFramework.PlatformTestCase; import com.intellij.testFramework.PlatformTestUtil; import com.intellij.testFramework.TestDataProvider; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.jetCheck.Generator; import java.io.File; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public abstract class AbstractApplyAndRevertTestCase extends PlatformTestCase { protected CompilerTester myCompilerTester; protected Project myProject; private String oldMacroValue; @Override public Object getData(@NotNull String dataId) { return myProject == null ? null : new TestDataProvider(myProject).getData(dataId); } private Generator<VirtualFile> javaFiles() { GlobalSearchScope projectScope = GlobalSearchScope.projectScope(myProject); List<VirtualFile> allFiles = new ArrayList<>(FilenameIndex.getAllFilesByExt(myProject, "java", projectScope)); if (allFiles.isEmpty()) { throw new IllegalStateException("No java files in project???"); } ContainerUtil.sort(allFiles, Comparator.comparing(VirtualFile::getPath)); return Generator.sampledFrom(allFiles); } protected Generator<PsiJavaFile> psiJavaFiles() { return javaFiles().map(vf -> (PsiJavaFile)PsiManager.getInstance(myProject).findFile(vf)); } protected abstract String getTestDataPath(); @Override public void setUp() throws Exception { super.setUp(); PathMacros pathMacros = PathMacros.getInstance(); oldMacroValue = pathMacros.getValue(PathMacrosImpl.MAVEN_REPOSITORY); pathMacros.setMacro(PathMacrosImpl.MAVEN_REPOSITORY, getDefaultMavenRepositoryPath()); WriteAction.run(() -> ProjectJdkTable.getInstance().addJdk(JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk(), getTestRootDisposable())); CompilerTestUtil.saveApplicationSettings(); myProject = ProjectUtil.openOrImport(getTestDataPath(), null, false); WriteAction.run( () -> ProjectRootManager.getInstance(myProject).setProjectSdk(JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk())); InspectionProfileImpl.INIT_INSPECTIONS = true; DefaultLogger.disableStderrDumping(getTestRootDisposable()); } protected final void initCompiler() { try { Module module = ModuleManager.getInstance(myProject).getModules()[0]; myCompilerTester = new CompilerTester(module); } catch (Throwable e) { fail(e.getMessage()); } } protected String getDefaultMavenRepositoryPath() { final String root = System.getProperty("user.home", null); return (root != null ? new File(root, ".m2/repository") : new File(".m2/repository")).getAbsolutePath(); } @Override public void tearDown() throws Exception { try { if (myCompilerTester != null) { myCompilerTester.tearDown(); } PathMacros.getInstance().setMacro(PathMacrosImpl.MAVEN_REPOSITORY, oldMacroValue); Project project = myProject; myProject = null; PlatformTestUtil.forceCloseProjectWithoutSaving(project); InspectionProfileImpl.INIT_INSPECTIONS = false; } catch (Throwable e) { addSuppressedException(e); } finally { super.tearDown(); } } protected static void checkCompiles(List<CompilerMessage> messages) { List<CompilerMessage> compilerMessages = filterErrors(messages); if (!compilerMessages.isEmpty()) { fail(StringUtil.join(compilerMessages, mes -> mes.getMessage(), "\n")); } } protected static List<CompilerMessage> filterErrors(List<CompilerMessage> messages) { return ContainerUtil.filter(messages, message -> message.getCategory() == CompilerMessageCategory.ERROR); } }