diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/loci/visbio/data/ExportPane.java b/loci/visbio/data/ExportPane.java index 730db93f8..6f22a5ab7 100644 --- a/loci/visbio/data/ExportPane.java +++ b/loci/visbio/data/ExportPane.java @@ -1,512 +1,527 @@ // // ExportPane.java // /* VisBio application for visualization of multidimensional biological image data. Copyright (C) 2002-2004 Curtis Rueden. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.visbio.data; import com.jgoodies.forms.builder.PanelBuilder; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.io.IOException; import java.util.*; import javax.swing.*; import loci.visbio.VisBioFrame; import loci.visbio.util.*; import visad.*; /** * ExportPane provides a full-featured set of options for exporting a * multidimensional data series from VisBio to several different formats. */ public class ExportPane extends WizardPane { // -- GUI components, page 1 -- /** File pattern text field. */ private JTextField patternField; /** File format combo box. */ private BioComboBox formatBox; // -- GUI components, page 2 -- /** Panel for dynamic second page components. */ private JPanel second; /** Check box indicating whether file numbering should use leading zeroes. */ private JCheckBox leadingZeroes; /** Frames per second for movie formats. */ private JTextField fps; /** Combo boxes for mapping each star to corresponding dimensional axes. */ private BioComboBox[] letterBoxes; // -- GUI components, page 3 -- /** Panel for dynamic third page components. */ private JPanel third; /** Pane containing export summary. */ private JEditorPane summary; // -- Other fields -- /** Associated VisBio frame (for displaying export status). */ private VisBioFrame bio; /** File adapter for exporting VisAD data to disk. */ private ImageFamily saver; /** Data object from which exportable data will be derived. */ private ImageTransform trans; /** File pattern, divided into tokens. */ private String[] tokens; /** Number of "stars" in the file pattern. */ private int stars; /** Mapping from each star to corresponding dimensional axis. */ private int[] maps; /** Excluded index (not mapped to a star). */ private int excl; /** Number of total files to export. */ private int numFiles; // -- Constructor -- /** Creates a multidimensional data export dialog. */ public ExportPane(VisBioFrame bio) { super("Export data"); this.bio = bio; saver = new ImageFamily(); // -- Page 1 -- // pattern field patternField = new JTextField(); // format combo box String[] formats = saver.canSaveQT() ? new String[] {"TIFF", "PIC", "MOV"} : new String[] {"TIFF", "PIC"}; formatBox = new BioComboBox(formats); // lay out first page PanelBuilder builder = new PanelBuilder(new FormLayout( "pref, 3dlu, pref:grow, 3dlu, pref, 3dlu, pref", "pref")); CellConstraints cc = new CellConstraints(); builder.addLabel("File &pattern", cc.xy(1, 1)).setLabelFor(patternField); builder.add(patternField, cc.xy(3, 1)); builder.addLabel("&Format", cc.xy(5, 1)).setLabelFor(formatBox); builder.add(formatBox, cc.xy(7, 1)); JPanel first = builder.getPanel(); // -- Page 2 -- // pad file numbering with leading zeroes checkbox leadingZeroes = new JCheckBox("Pad file numbering with leading zeroes"); leadingZeroes.setMnemonic('p'); // frames per second text field fps = new JTextField(4); // lay out second page second = new JPanel(); second.setLayout(new BorderLayout()); // -- Page 3 -- // summary text area summary = new JEditorPane(); summary.setEditable(false); summary.setContentType("text/html"); JScrollPane summaryScroll = new JScrollPane(summary); SwingUtil.configureScrollPane(summaryScroll); // lay out third page third = new JPanel(); third.setLayout(new BorderLayout()); // lay out pages setPages(new JPanel[] {first, second, third}); } // -- New API methods -- /** Associates the given data object with the export pane. */ public void setData(ImageTransform trans) { this.trans = trans; if (trans == null) return; } /** Exports the data according to the current input parameters. */ public void export() { final int[] lengths = trans.getLengths(); final int numImages = excl < 0 ? 1 : lengths[excl]; final int numTotal = numFiles * numImages; final JProgressBar progress = bio.getProgressBar(); progress.setString("Exporting data"); progress.setValue(0); progress.setMaximum(numTotal + numFiles); Thread t = new Thread(new Runnable() { public void run() { try { boolean padZeroes = leadingZeroes.isSelected(); int[] plen = new int[stars]; for (int i=0; i<stars; i++) plen[i] = lengths[maps[i]]; RealType indexType = RealType.getRealType("index"); int[] lengths = trans.getLengths(); for (int i=0; i<numFiles; i++) { int[] pos = MathUtil.rasterToPosition(plen, i); int[] npos = new int[lengths.length]; for (int j=0; j<stars; j++) npos[maps[j]] = pos[j]; // construct data object FieldImpl data = null; if (excl < 0) { progress.setString("Reading image #" + (i + 1) + "/" + numTotal); data = (FlatField) trans.getData(npos, 2, null); progress.setValue(progress.getValue() + 1); } else { Integer1DSet fset = new Integer1DSet(indexType, lengths[excl]); for (int j=0; j<lengths[excl]; j++) { int img = numImages * i + j + 1; progress.setString("Reading image #" + img + "/" + numTotal); npos[excl] = j; FlatField image = (FlatField) trans.getData(npos, 2, null); if (data == null) { FunctionType imageType = (FunctionType) image.getType(); FunctionType ftype = new FunctionType(indexType, imageType); data = new FieldImpl(ftype, fset); } data.setSample(j, image, false); progress.setValue(progress.getValue() + 1); } } // construct filename StringBuffer sb = new StringBuffer(); for (int j=0; j<stars; j++) { sb.append(tokens[j]); if (padZeroes) { int len = ("" + lengths[maps[j]]).length() - ("" + (pos[j] + 1)).length(); for (int k=0; k<len; k++) sb.append("0"); } sb.append(pos[j] + 1); } sb.append(tokens[stars]); // save data to file String filename = sb.toString(); progress.setString("Exporting file " + filename); saver.save(filename, data, false); progress.setValue(progress.getValue() + 1); } bio.resetStatus(); } catch (VisADException exc) { bio.resetStatus(); exc.printStackTrace(); JOptionPane.showMessageDialog(dialog, "Error exporting data: " + exc.getMessage(), "VisBio", JOptionPane.ERROR_MESSAGE); } catch (IOException exc) { bio.resetStatus(); exc.printStackTrace(); JOptionPane.showMessageDialog(dialog, "Error exporting data: " + exc.getMessage(), "VisBio", JOptionPane.ERROR_MESSAGE); } } }); t.start(); } // -- DialogPane API methods -- /** Resets the wizard pane's components to their default states. */ public void resetComponents() { super.resetComponents(); patternField.setText(""); formatBox.setSelectedIndex(0); } // -- ActionListener API methods -- /** Handles button press events. */ public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals("next")) { if (page == 0) { // lay out page 2 // ensure file pattern ends with appropriate format extension // also determine visibility of "frames per second" text field String pattern = patternField.getText(); String format = (String) formatBox.getSelectedItem(); String plow = pattern.toLowerCase(); boolean doFPS = false; if (format.equals("PIC")) { if (!plow.endsWith(".pic")) pattern += ".pic"; } else if (format.equals("TIFF")) { if (!plow.endsWith(".tiff") && !plow.endsWith(".tif")) { pattern += ".tif"; } } else if (format.equals("MOV")) { if (!plow.endsWith(".mov")) pattern += ".mov"; doFPS = true; } // parse file pattern StringTokenizer st = new StringTokenizer("#" + pattern + "#", "*"); tokens = new String[st.countTokens()]; for (int i=0; i<tokens.length; i++) { String t = st.nextToken(); if (i == 0) t = t.substring(1); if (i == tokens.length - 1) t = t.substring(0, t.length() - 1); tokens[i] = t; } stars = tokens.length - 1; String[] dims = trans.getDimTypes(); int q = dims.length - stars; if (q < 0 || q > 1) { - JOptionPane.showMessageDialog(dialog, "Please use either " + - (dims.length - 1) + " or " + dims.length + " asterisks in the " + - "file pattern to\nindicate where the dimensional axes should be " + - "numbered.", "VisBio", JOptionPane.ERROR_MESSAGE); + String msg; + if (dims.length == 0) { + msg = "Please specify a single filename (no asterisks)."; + } + else if (dims.length == 1) { + msg = "Please specify either a single filename (no asterisks) " + + "or a file pattern with\none asterisk to indicate where the " + + "dimensional axes should be numbered."; + } + else { + msg = "Please specify either " + (dims.length - 1) + " or " + + dims.length + " asterisks in the file pattern to\nindicate " + + "where the dimensional axes should be numbered."; + } + JOptionPane.showMessageDialog(dialog, msg, "VisBio", + JOptionPane.ERROR_MESSAGE); return; } // determine visibility of "leading zeroes" checkbox boolean doZeroes = stars > 0; // build file pattern StringBuffer sb = new StringBuffer(); for (int i=0; i<stars; i++) { sb.append(tokens[i]); sb.append("<"); sb.append((char) ('A' + i)); sb.append(">"); } sb.append(tokens[stars]); String pat = sb.toString(); // build list of dimensional axes String[] dimChoices = new String[dims.length]; for (int i=0; i<dims.length; i++) { dimChoices[i] = "<" + (i + 1) + "> " + dims[i]; } // construct second page panel sb = new StringBuffer("pref"); if (doFPS) sb.append(", 3dlu, pref"); if (doZeroes) sb.append(", 3dlu, pref"); for (int i=0; i<stars; i++) { sb.append(", 3dlu, pref"); } PanelBuilder builder = new PanelBuilder(new FormLayout( "pref:grow, 3dlu, pref", sb.toString())); CellConstraints cc = new CellConstraints(); builder.addSeparator(pat, cc.xyw(1, 1, 3)); int row = 3; if (doFPS) { builder.addLabel("&Frames per second", cc.xy(1, row, "right,center")).setLabelFor(fps); builder.add(fps, cc.xy(3, row)); row += 2; } if (doZeroes) { builder.add(leadingZeroes, cc.xyw(1, row, 3, "right,center")); row += 2; } letterBoxes = new BioComboBox[stars]; for (int i=0; i<stars; i++) { char letter = (char) ('A' + i); builder.addLabel("<" + letter + "> =", cc.xy(1, row, "right,center")); letterBoxes[i] = new BioComboBox(dimChoices); letterBoxes[i].setSelectedIndex(i); builder.add(letterBoxes[i], cc.xy(3, row)); row += 2; } second.removeAll(); second.add(builder.getPanel()); } else if (page == 1) { // lay out page 3 String[] dims = trans.getDimTypes(); int[] lengths = trans.getLengths(); // file pattern StringBuffer sb = new StringBuffer("File pattern: "); for (int i=0; i<stars; i++) { sb.append(tokens[i]); char letter = (char) ('A' + i); sb.append("<"); sb.append(letter); sb.append(">"); } sb.append(tokens[stars]); // file format sb.append("\nFormat: "); String format = (String) formatBox.getSelectedItem(); - if (format.equals("PIC")) sb.append("Bio-Rad PIC"); - else if (format.equals("TIFF")) sb.append("Multi-page TIFF stack"); + if (format.equals("PIC")) sb.append("Bio-Rad PIC file"); + else if (format.equals("TIFF")) { + if (dims.length == stars) sb.append("TIFF image"); + else sb.append("Multi-page TIFF stack"); + } else if (format.equals("MOV")) sb.append("QuickTime movie"); else sb.append("Unknown"); sb.append("\n \n"); // dimensional mappings maps = new int[stars]; if (stars > 0) { for (int i=0; i<stars; i++) { char letter = (char) ('A' + i); sb.append("<"); sb.append(letter); sb.append("> numbered across dimension: "); maps[i] = letterBoxes[i].getSelectedIndex(); sb.append("<"); sb.append(maps[i] + 1); sb.append("> "); sb.append(dims[maps[i]]); sb.append("\n"); } } else sb.append(" \n"); // count dimensional axis exclusions excl = -1; boolean[] b = new boolean[dims.length]; for (int i=0; i<stars; i++) b[maps[i]] = true; int exclude = 0; for (int i=0; i<dims.length; i++) { if (!b[i]) { excl = i; exclude++; } } // file contents sb.append("Each file will contain "); int q = dims.length - stars; if (q == 0) sb.append("a single image.\n \n"); else { // q == 1 int len = lengths[excl]; sb.append(len); sb.append(" image"); if (len != 1) sb.append("s"); sb.append(" across dimension: <"); sb.append(excl + 1); sb.append("> "); sb.append(dims[excl]); sb.append("\n \n"); } // verify dimensional axis mappings are acceptable if (exclude != q) { JOptionPane.showMessageDialog(dialog, "Please map each letter to a different dimensional axis.", "VisBio", JOptionPane.ERROR_MESSAGE); return; } // verify number of range components is acceptable int rangeCount = trans.getRangeCount(); if (format.equals("PIC") && rangeCount != 1) { JOptionPane.showMessageDialog(dialog, "Bio-Rad PIC format requires a data object with a single " + "range component. Please subsample your data object accordingly.", "VisBio", JOptionPane.ERROR_MESSAGE); return; } else if (rangeCount != 1 && rangeCount != 3) { JOptionPane.showMessageDialog(dialog, format + " format requires a data object with either 1 or 3 " + "range components. Please subsample your data object accordingly.", "VisBio", JOptionPane.ERROR_MESSAGE); return; } // number of files boolean padZeroes = leadingZeroes.isSelected(); sb.append("\nFirst file: "); for (int i=0; i<stars; i++) { sb.append(tokens[i]); if (padZeroes) { int len = ("" + lengths[maps[i]]).length() - 1; for (int j=0; j<len; j++) sb.append("0"); } sb.append("1"); } sb.append(tokens[stars]); sb.append("\nLast file: "); numFiles = 1; for (int i=0; i<stars; i++) { sb.append(tokens[i]); sb.append(lengths[maps[i]]); numFiles *= lengths[maps[i]]; } sb.append(tokens[stars]); sb.append("\nTotal number of files: "); sb.append(numFiles); // construct third page panel StringTokenizer st = new StringTokenizer(sb.toString(), "\n"); int numLines = st.countTokens(); sb = new StringBuffer("pref, 3dlu"); for (int i=0; i<numLines; i++) sb.append(", pref"); sb.append(", 5dlu"); PanelBuilder builder = new PanelBuilder(new FormLayout( "pref:grow", sb.toString())); CellConstraints cc = new CellConstraints(); builder.addSeparator("Summary", cc.xy(1, 1)); for (int i=0; i<numLines; i++) { builder.addLabel(st.nextToken(), cc.xy(1, i + 3)); } third.removeAll(); third.add(builder.getPanel()); } super.actionPerformed(e); } else super.actionPerformed(e); } }
false
true
public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals("next")) { if (page == 0) { // lay out page 2 // ensure file pattern ends with appropriate format extension // also determine visibility of "frames per second" text field String pattern = patternField.getText(); String format = (String) formatBox.getSelectedItem(); String plow = pattern.toLowerCase(); boolean doFPS = false; if (format.equals("PIC")) { if (!plow.endsWith(".pic")) pattern += ".pic"; } else if (format.equals("TIFF")) { if (!plow.endsWith(".tiff") && !plow.endsWith(".tif")) { pattern += ".tif"; } } else if (format.equals("MOV")) { if (!plow.endsWith(".mov")) pattern += ".mov"; doFPS = true; } // parse file pattern StringTokenizer st = new StringTokenizer("#" + pattern + "#", "*"); tokens = new String[st.countTokens()]; for (int i=0; i<tokens.length; i++) { String t = st.nextToken(); if (i == 0) t = t.substring(1); if (i == tokens.length - 1) t = t.substring(0, t.length() - 1); tokens[i] = t; } stars = tokens.length - 1; String[] dims = trans.getDimTypes(); int q = dims.length - stars; if (q < 0 || q > 1) { JOptionPane.showMessageDialog(dialog, "Please use either " + (dims.length - 1) + " or " + dims.length + " asterisks in the " + "file pattern to\nindicate where the dimensional axes should be " + "numbered.", "VisBio", JOptionPane.ERROR_MESSAGE); return; } // determine visibility of "leading zeroes" checkbox boolean doZeroes = stars > 0; // build file pattern StringBuffer sb = new StringBuffer(); for (int i=0; i<stars; i++) { sb.append(tokens[i]); sb.append("<"); sb.append((char) ('A' + i)); sb.append(">"); } sb.append(tokens[stars]); String pat = sb.toString(); // build list of dimensional axes String[] dimChoices = new String[dims.length]; for (int i=0; i<dims.length; i++) { dimChoices[i] = "<" + (i + 1) + "> " + dims[i]; } // construct second page panel sb = new StringBuffer("pref"); if (doFPS) sb.append(", 3dlu, pref"); if (doZeroes) sb.append(", 3dlu, pref"); for (int i=0; i<stars; i++) { sb.append(", 3dlu, pref"); } PanelBuilder builder = new PanelBuilder(new FormLayout( "pref:grow, 3dlu, pref", sb.toString())); CellConstraints cc = new CellConstraints(); builder.addSeparator(pat, cc.xyw(1, 1, 3)); int row = 3; if (doFPS) { builder.addLabel("&Frames per second", cc.xy(1, row, "right,center")).setLabelFor(fps); builder.add(fps, cc.xy(3, row)); row += 2; } if (doZeroes) { builder.add(leadingZeroes, cc.xyw(1, row, 3, "right,center")); row += 2; } letterBoxes = new BioComboBox[stars]; for (int i=0; i<stars; i++) { char letter = (char) ('A' + i); builder.addLabel("<" + letter + "> =", cc.xy(1, row, "right,center")); letterBoxes[i] = new BioComboBox(dimChoices); letterBoxes[i].setSelectedIndex(i); builder.add(letterBoxes[i], cc.xy(3, row)); row += 2; } second.removeAll(); second.add(builder.getPanel()); } else if (page == 1) { // lay out page 3 String[] dims = trans.getDimTypes(); int[] lengths = trans.getLengths(); // file pattern StringBuffer sb = new StringBuffer("File pattern: "); for (int i=0; i<stars; i++) { sb.append(tokens[i]); char letter = (char) ('A' + i); sb.append("<"); sb.append(letter); sb.append(">"); } sb.append(tokens[stars]); // file format sb.append("\nFormat: "); String format = (String) formatBox.getSelectedItem(); if (format.equals("PIC")) sb.append("Bio-Rad PIC"); else if (format.equals("TIFF")) sb.append("Multi-page TIFF stack"); else if (format.equals("MOV")) sb.append("QuickTime movie"); else sb.append("Unknown"); sb.append("\n \n"); // dimensional mappings maps = new int[stars]; if (stars > 0) { for (int i=0; i<stars; i++) { char letter = (char) ('A' + i); sb.append("<"); sb.append(letter); sb.append("> numbered across dimension: "); maps[i] = letterBoxes[i].getSelectedIndex(); sb.append("<"); sb.append(maps[i] + 1); sb.append("> "); sb.append(dims[maps[i]]); sb.append("\n"); } } else sb.append(" \n"); // count dimensional axis exclusions excl = -1; boolean[] b = new boolean[dims.length]; for (int i=0; i<stars; i++) b[maps[i]] = true; int exclude = 0; for (int i=0; i<dims.length; i++) { if (!b[i]) { excl = i; exclude++; } } // file contents sb.append("Each file will contain "); int q = dims.length - stars; if (q == 0) sb.append("a single image.\n \n"); else { // q == 1 int len = lengths[excl]; sb.append(len); sb.append(" image"); if (len != 1) sb.append("s"); sb.append(" across dimension: <"); sb.append(excl + 1); sb.append("> "); sb.append(dims[excl]); sb.append("\n \n"); } // verify dimensional axis mappings are acceptable if (exclude != q) { JOptionPane.showMessageDialog(dialog, "Please map each letter to a different dimensional axis.", "VisBio", JOptionPane.ERROR_MESSAGE); return; } // verify number of range components is acceptable int rangeCount = trans.getRangeCount(); if (format.equals("PIC") && rangeCount != 1) { JOptionPane.showMessageDialog(dialog, "Bio-Rad PIC format requires a data object with a single " + "range component. Please subsample your data object accordingly.", "VisBio", JOptionPane.ERROR_MESSAGE); return; } else if (rangeCount != 1 && rangeCount != 3) { JOptionPane.showMessageDialog(dialog, format + " format requires a data object with either 1 or 3 " + "range components. Please subsample your data object accordingly.", "VisBio", JOptionPane.ERROR_MESSAGE); return; } // number of files boolean padZeroes = leadingZeroes.isSelected(); sb.append("\nFirst file: "); for (int i=0; i<stars; i++) { sb.append(tokens[i]); if (padZeroes) { int len = ("" + lengths[maps[i]]).length() - 1; for (int j=0; j<len; j++) sb.append("0"); } sb.append("1"); } sb.append(tokens[stars]); sb.append("\nLast file: "); numFiles = 1; for (int i=0; i<stars; i++) { sb.append(tokens[i]); sb.append(lengths[maps[i]]); numFiles *= lengths[maps[i]]; } sb.append(tokens[stars]); sb.append("\nTotal number of files: "); sb.append(numFiles); // construct third page panel StringTokenizer st = new StringTokenizer(sb.toString(), "\n"); int numLines = st.countTokens(); sb = new StringBuffer("pref, 3dlu"); for (int i=0; i<numLines; i++) sb.append(", pref"); sb.append(", 5dlu"); PanelBuilder builder = new PanelBuilder(new FormLayout( "pref:grow", sb.toString())); CellConstraints cc = new CellConstraints(); builder.addSeparator("Summary", cc.xy(1, 1)); for (int i=0; i<numLines; i++) { builder.addLabel(st.nextToken(), cc.xy(1, i + 3)); } third.removeAll(); third.add(builder.getPanel()); } super.actionPerformed(e); } else super.actionPerformed(e); }
public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals("next")) { if (page == 0) { // lay out page 2 // ensure file pattern ends with appropriate format extension // also determine visibility of "frames per second" text field String pattern = patternField.getText(); String format = (String) formatBox.getSelectedItem(); String plow = pattern.toLowerCase(); boolean doFPS = false; if (format.equals("PIC")) { if (!plow.endsWith(".pic")) pattern += ".pic"; } else if (format.equals("TIFF")) { if (!plow.endsWith(".tiff") && !plow.endsWith(".tif")) { pattern += ".tif"; } } else if (format.equals("MOV")) { if (!plow.endsWith(".mov")) pattern += ".mov"; doFPS = true; } // parse file pattern StringTokenizer st = new StringTokenizer("#" + pattern + "#", "*"); tokens = new String[st.countTokens()]; for (int i=0; i<tokens.length; i++) { String t = st.nextToken(); if (i == 0) t = t.substring(1); if (i == tokens.length - 1) t = t.substring(0, t.length() - 1); tokens[i] = t; } stars = tokens.length - 1; String[] dims = trans.getDimTypes(); int q = dims.length - stars; if (q < 0 || q > 1) { String msg; if (dims.length == 0) { msg = "Please specify a single filename (no asterisks)."; } else if (dims.length == 1) { msg = "Please specify either a single filename (no asterisks) " + "or a file pattern with\none asterisk to indicate where the " + "dimensional axes should be numbered."; } else { msg = "Please specify either " + (dims.length - 1) + " or " + dims.length + " asterisks in the file pattern to\nindicate " + "where the dimensional axes should be numbered."; } JOptionPane.showMessageDialog(dialog, msg, "VisBio", JOptionPane.ERROR_MESSAGE); return; } // determine visibility of "leading zeroes" checkbox boolean doZeroes = stars > 0; // build file pattern StringBuffer sb = new StringBuffer(); for (int i=0; i<stars; i++) { sb.append(tokens[i]); sb.append("<"); sb.append((char) ('A' + i)); sb.append(">"); } sb.append(tokens[stars]); String pat = sb.toString(); // build list of dimensional axes String[] dimChoices = new String[dims.length]; for (int i=0; i<dims.length; i++) { dimChoices[i] = "<" + (i + 1) + "> " + dims[i]; } // construct second page panel sb = new StringBuffer("pref"); if (doFPS) sb.append(", 3dlu, pref"); if (doZeroes) sb.append(", 3dlu, pref"); for (int i=0; i<stars; i++) { sb.append(", 3dlu, pref"); } PanelBuilder builder = new PanelBuilder(new FormLayout( "pref:grow, 3dlu, pref", sb.toString())); CellConstraints cc = new CellConstraints(); builder.addSeparator(pat, cc.xyw(1, 1, 3)); int row = 3; if (doFPS) { builder.addLabel("&Frames per second", cc.xy(1, row, "right,center")).setLabelFor(fps); builder.add(fps, cc.xy(3, row)); row += 2; } if (doZeroes) { builder.add(leadingZeroes, cc.xyw(1, row, 3, "right,center")); row += 2; } letterBoxes = new BioComboBox[stars]; for (int i=0; i<stars; i++) { char letter = (char) ('A' + i); builder.addLabel("<" + letter + "> =", cc.xy(1, row, "right,center")); letterBoxes[i] = new BioComboBox(dimChoices); letterBoxes[i].setSelectedIndex(i); builder.add(letterBoxes[i], cc.xy(3, row)); row += 2; } second.removeAll(); second.add(builder.getPanel()); } else if (page == 1) { // lay out page 3 String[] dims = trans.getDimTypes(); int[] lengths = trans.getLengths(); // file pattern StringBuffer sb = new StringBuffer("File pattern: "); for (int i=0; i<stars; i++) { sb.append(tokens[i]); char letter = (char) ('A' + i); sb.append("<"); sb.append(letter); sb.append(">"); } sb.append(tokens[stars]); // file format sb.append("\nFormat: "); String format = (String) formatBox.getSelectedItem(); if (format.equals("PIC")) sb.append("Bio-Rad PIC file"); else if (format.equals("TIFF")) { if (dims.length == stars) sb.append("TIFF image"); else sb.append("Multi-page TIFF stack"); } else if (format.equals("MOV")) sb.append("QuickTime movie"); else sb.append("Unknown"); sb.append("\n \n"); // dimensional mappings maps = new int[stars]; if (stars > 0) { for (int i=0; i<stars; i++) { char letter = (char) ('A' + i); sb.append("<"); sb.append(letter); sb.append("> numbered across dimension: "); maps[i] = letterBoxes[i].getSelectedIndex(); sb.append("<"); sb.append(maps[i] + 1); sb.append("> "); sb.append(dims[maps[i]]); sb.append("\n"); } } else sb.append(" \n"); // count dimensional axis exclusions excl = -1; boolean[] b = new boolean[dims.length]; for (int i=0; i<stars; i++) b[maps[i]] = true; int exclude = 0; for (int i=0; i<dims.length; i++) { if (!b[i]) { excl = i; exclude++; } } // file contents sb.append("Each file will contain "); int q = dims.length - stars; if (q == 0) sb.append("a single image.\n \n"); else { // q == 1 int len = lengths[excl]; sb.append(len); sb.append(" image"); if (len != 1) sb.append("s"); sb.append(" across dimension: <"); sb.append(excl + 1); sb.append("> "); sb.append(dims[excl]); sb.append("\n \n"); } // verify dimensional axis mappings are acceptable if (exclude != q) { JOptionPane.showMessageDialog(dialog, "Please map each letter to a different dimensional axis.", "VisBio", JOptionPane.ERROR_MESSAGE); return; } // verify number of range components is acceptable int rangeCount = trans.getRangeCount(); if (format.equals("PIC") && rangeCount != 1) { JOptionPane.showMessageDialog(dialog, "Bio-Rad PIC format requires a data object with a single " + "range component. Please subsample your data object accordingly.", "VisBio", JOptionPane.ERROR_MESSAGE); return; } else if (rangeCount != 1 && rangeCount != 3) { JOptionPane.showMessageDialog(dialog, format + " format requires a data object with either 1 or 3 " + "range components. Please subsample your data object accordingly.", "VisBio", JOptionPane.ERROR_MESSAGE); return; } // number of files boolean padZeroes = leadingZeroes.isSelected(); sb.append("\nFirst file: "); for (int i=0; i<stars; i++) { sb.append(tokens[i]); if (padZeroes) { int len = ("" + lengths[maps[i]]).length() - 1; for (int j=0; j<len; j++) sb.append("0"); } sb.append("1"); } sb.append(tokens[stars]); sb.append("\nLast file: "); numFiles = 1; for (int i=0; i<stars; i++) { sb.append(tokens[i]); sb.append(lengths[maps[i]]); numFiles *= lengths[maps[i]]; } sb.append(tokens[stars]); sb.append("\nTotal number of files: "); sb.append(numFiles); // construct third page panel StringTokenizer st = new StringTokenizer(sb.toString(), "\n"); int numLines = st.countTokens(); sb = new StringBuffer("pref, 3dlu"); for (int i=0; i<numLines; i++) sb.append(", pref"); sb.append(", 5dlu"); PanelBuilder builder = new PanelBuilder(new FormLayout( "pref:grow", sb.toString())); CellConstraints cc = new CellConstraints(); builder.addSeparator("Summary", cc.xy(1, 1)); for (int i=0; i<numLines; i++) { builder.addLabel(st.nextToken(), cc.xy(1, i + 3)); } third.removeAll(); third.add(builder.getPanel()); } super.actionPerformed(e); } else super.actionPerformed(e); }
diff --git a/test/java/org/jboss/mod_cluster/TestStickyForce.java b/test/java/org/jboss/mod_cluster/TestStickyForce.java index c4eedab3..55350ce3 100644 --- a/test/java/org/jboss/mod_cluster/TestStickyForce.java +++ b/test/java/org/jboss/mod_cluster/TestStickyForce.java @@ -1,176 +1,176 @@ /* * mod_cluster * * Copyright(c) 2008 Red Hat Middleware, LLC, * and individual contributors as indicated by the @authors tag. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library in the file COPYING.LIB; * if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA * * @author Jean-Frederic Clere * @version $Revision$ */ package org.jboss.mod_cluster; import java.io.IOException; import junit.framework.TestCase; import org.apache.catalina.Engine; import org.apache.catalina.ServerFactory; import org.apache.catalina.Service; import org.apache.catalina.LifecycleListener; import org.apache.catalina.LifecycleException; import org.apache.catalina.connector.Connector; import org.apache.catalina.core.StandardServer; public class TestStickyForce extends TestCase { StandardServer server = null; /* Test failover */ public void testStickyForce() { boolean clienterror = false; server = Maintest.getServer(); JBossWeb service = null; JBossWeb service2 = null; Connector connector = null; Connector connector2 = null; LifecycleListener cluster = null; System.out.println("TestStickyForce Started"); try { // server = (StandardServer) ServerFactory.getServer(); service = new JBossWeb("sticky3", "localhost"); connector = service.addConnector(8012); connector.setProperty("connectionTimeout", "3000"); server.addService(service); service2 = new JBossWeb("sticky4", "localhost"); connector2 = service2.addConnector(8011); connector2.setProperty("connectionTimeout", "3000"); server.addService(service2); cluster = Maintest.createClusterListener("224.0.1.105", 23364, false, null, true, false, true, "secret"); server.addLifecycleListener(cluster); // Maintest.listServices(); } catch(IOException ex) { ex.printStackTrace(); fail("can't start service"); } // start the server thread. ServerThread wait = new ServerThread(3000, server); wait.start(); // Wait until httpd as received the nodes information. String [] nodes = new String[2]; nodes[0] = "sticky3"; nodes[1] = "sticky4"; if (!Maintest.TestForNodes(cluster, nodes)) fail("can't start nodes"); // Start the client and wait for it. Client client = new Client(); // Wait for it. try { if (client.runit("/ROOT/MyCount", 10, false, true) != 0) clienterror = true; } catch (Exception ex) { ex.printStackTrace(); clienterror = true; } if (clienterror) fail("Client error"); // Stop the connector that has received the request... String node = client.getnode(); int port; if ("sticky4".equals(node)) { connector = connector2; node = "sticky3"; port = 8011; } else { node = "sticky4"; port = 8012; } if (connector != null) { try { connector.stop(); } catch (Exception ex) { ex.printStackTrace(); fail("can't stop connector"); } /* wait until the connector has stopped */ int countinfo = 0; while (Maintest.testPort(port) && countinfo < 20) { try { Thread.sleep(3000); } catch (InterruptedException ex) { ex.printStackTrace(); } countinfo++; } if (countinfo == 20) fail("can't stop connector"); } // Run a test on it. (it waits until httpd as received the nodes information). client.setnode(node); try { client.setdelay(30000); client.start(); client.join(); } catch (Exception ex) { ex.printStackTrace(); } if (client.getresultok()) System.out.println("Test DONE"); else { System.out.println("Test FAILED"); clienterror = true; } // Stop the server or services. try { wait.stopit(); wait.join(); server.removeService(service); server.removeService(service2); server.removeLifecycleListener(cluster); } catch (InterruptedException ex) { ex.printStackTrace(); } // Wait until httpd as received the stop messages. Maintest.testPort(8012); Maintest.testPort(8011); if (!Maintest.TestForNodes(cluster, null)) - fail("Can't stop..."); + fail("Can't stop nodes"); /* XXX: In fact it doesn't stop correctly ... Something needs to be fixed */ // Test client result. if ( !clienterror && client.httpResponseCode != 503 ) fail("Client test should have failed"); Maintest.waitn(); System.out.println("TestStickyForce Done"); } }
true
true
public void testStickyForce() { boolean clienterror = false; server = Maintest.getServer(); JBossWeb service = null; JBossWeb service2 = null; Connector connector = null; Connector connector2 = null; LifecycleListener cluster = null; System.out.println("TestStickyForce Started"); try { // server = (StandardServer) ServerFactory.getServer(); service = new JBossWeb("sticky3", "localhost"); connector = service.addConnector(8012); connector.setProperty("connectionTimeout", "3000"); server.addService(service); service2 = new JBossWeb("sticky4", "localhost"); connector2 = service2.addConnector(8011); connector2.setProperty("connectionTimeout", "3000"); server.addService(service2); cluster = Maintest.createClusterListener("224.0.1.105", 23364, false, null, true, false, true, "secret"); server.addLifecycleListener(cluster); // Maintest.listServices(); } catch(IOException ex) { ex.printStackTrace(); fail("can't start service"); } // start the server thread. ServerThread wait = new ServerThread(3000, server); wait.start(); // Wait until httpd as received the nodes information. String [] nodes = new String[2]; nodes[0] = "sticky3"; nodes[1] = "sticky4"; if (!Maintest.TestForNodes(cluster, nodes)) fail("can't start nodes"); // Start the client and wait for it. Client client = new Client(); // Wait for it. try { if (client.runit("/ROOT/MyCount", 10, false, true) != 0) clienterror = true; } catch (Exception ex) { ex.printStackTrace(); clienterror = true; } if (clienterror) fail("Client error"); // Stop the connector that has received the request... String node = client.getnode(); int port; if ("sticky4".equals(node)) { connector = connector2; node = "sticky3"; port = 8011; } else { node = "sticky4"; port = 8012; } if (connector != null) { try { connector.stop(); } catch (Exception ex) { ex.printStackTrace(); fail("can't stop connector"); } /* wait until the connector has stopped */ int countinfo = 0; while (Maintest.testPort(port) && countinfo < 20) { try { Thread.sleep(3000); } catch (InterruptedException ex) { ex.printStackTrace(); } countinfo++; } if (countinfo == 20) fail("can't stop connector"); } // Run a test on it. (it waits until httpd as received the nodes information). client.setnode(node); try { client.setdelay(30000); client.start(); client.join(); } catch (Exception ex) { ex.printStackTrace(); } if (client.getresultok()) System.out.println("Test DONE"); else { System.out.println("Test FAILED"); clienterror = true; } // Stop the server or services. try { wait.stopit(); wait.join(); server.removeService(service); server.removeService(service2); server.removeLifecycleListener(cluster); } catch (InterruptedException ex) { ex.printStackTrace(); } // Wait until httpd as received the stop messages. Maintest.testPort(8012); Maintest.testPort(8011); if (!Maintest.TestForNodes(cluster, null)) fail("Can't stop..."); /* XXX: In fact it doesn't stop correctly ... Something needs to be fixed */ // Test client result. if ( !clienterror && client.httpResponseCode != 503 ) fail("Client test should have failed"); Maintest.waitn(); System.out.println("TestStickyForce Done"); }
public void testStickyForce() { boolean clienterror = false; server = Maintest.getServer(); JBossWeb service = null; JBossWeb service2 = null; Connector connector = null; Connector connector2 = null; LifecycleListener cluster = null; System.out.println("TestStickyForce Started"); try { // server = (StandardServer) ServerFactory.getServer(); service = new JBossWeb("sticky3", "localhost"); connector = service.addConnector(8012); connector.setProperty("connectionTimeout", "3000"); server.addService(service); service2 = new JBossWeb("sticky4", "localhost"); connector2 = service2.addConnector(8011); connector2.setProperty("connectionTimeout", "3000"); server.addService(service2); cluster = Maintest.createClusterListener("224.0.1.105", 23364, false, null, true, false, true, "secret"); server.addLifecycleListener(cluster); // Maintest.listServices(); } catch(IOException ex) { ex.printStackTrace(); fail("can't start service"); } // start the server thread. ServerThread wait = new ServerThread(3000, server); wait.start(); // Wait until httpd as received the nodes information. String [] nodes = new String[2]; nodes[0] = "sticky3"; nodes[1] = "sticky4"; if (!Maintest.TestForNodes(cluster, nodes)) fail("can't start nodes"); // Start the client and wait for it. Client client = new Client(); // Wait for it. try { if (client.runit("/ROOT/MyCount", 10, false, true) != 0) clienterror = true; } catch (Exception ex) { ex.printStackTrace(); clienterror = true; } if (clienterror) fail("Client error"); // Stop the connector that has received the request... String node = client.getnode(); int port; if ("sticky4".equals(node)) { connector = connector2; node = "sticky3"; port = 8011; } else { node = "sticky4"; port = 8012; } if (connector != null) { try { connector.stop(); } catch (Exception ex) { ex.printStackTrace(); fail("can't stop connector"); } /* wait until the connector has stopped */ int countinfo = 0; while (Maintest.testPort(port) && countinfo < 20) { try { Thread.sleep(3000); } catch (InterruptedException ex) { ex.printStackTrace(); } countinfo++; } if (countinfo == 20) fail("can't stop connector"); } // Run a test on it. (it waits until httpd as received the nodes information). client.setnode(node); try { client.setdelay(30000); client.start(); client.join(); } catch (Exception ex) { ex.printStackTrace(); } if (client.getresultok()) System.out.println("Test DONE"); else { System.out.println("Test FAILED"); clienterror = true; } // Stop the server or services. try { wait.stopit(); wait.join(); server.removeService(service); server.removeService(service2); server.removeLifecycleListener(cluster); } catch (InterruptedException ex) { ex.printStackTrace(); } // Wait until httpd as received the stop messages. Maintest.testPort(8012); Maintest.testPort(8011); if (!Maintest.TestForNodes(cluster, null)) fail("Can't stop nodes"); /* XXX: In fact it doesn't stop correctly ... Something needs to be fixed */ // Test client result. if ( !clienterror && client.httpResponseCode != 503 ) fail("Client test should have failed"); Maintest.waitn(); System.out.println("TestStickyForce Done"); }
diff --git a/api/src/main/java/org/asynchttpclient/AsyncHttpClientConfig.java b/api/src/main/java/org/asynchttpclient/AsyncHttpClientConfig.java index 55717a02e..32d01ebd9 100644 --- a/api/src/main/java/org/asynchttpclient/AsyncHttpClientConfig.java +++ b/api/src/main/java/org/asynchttpclient/AsyncHttpClientConfig.java @@ -1,1348 +1,1347 @@ /* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.asynchttpclient; import org.asynchttpclient.filter.IOExceptionFilter; import org.asynchttpclient.filter.RequestFilter; import org.asynchttpclient.filter.ResponseFilter; import org.asynchttpclient.util.AllowAllHostnameVerifier; import org.asynchttpclient.util.ProxyUtils; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * Configuration class to use with a {@link AsyncHttpClient}. System property can be also used to configure this * object default behavior by doing: * <p/> * -Dorg.asynchttpclient.AsyncHttpClientConfig.nameOfTheProperty * ex: * <p/> * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultMaxTotalConnections * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultMaxTotalConnections * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultMaxConnectionsPerHost * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultConnectionTimeoutInMS * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultIdleConnectionInPoolTimeoutInMS * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultRequestTimeoutInMS * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultRedirectsEnabled * -Dorg.asynchttpclient.AsyncHttpClientConfig.defaultMaxRedirects */ public class AsyncHttpClientConfig { protected final static String ASYNC_CLIENT = AsyncHttpClientConfig.class.getName() + "."; public final static String AHC_VERSION; static { InputStream is = null; Properties prop = new Properties(); try { is = AsyncHttpClientConfig.class.getResourceAsStream("version.properties"); prop.load(is); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException ignored) { } } } AHC_VERSION = prop.getProperty("ahc.version", "UNKNOWN"); } protected int maxTotalConnections; protected int maxConnectionPerHost; protected int connectionTimeOutInMs; protected int webSocketIdleTimeoutInMs; protected int idleConnectionInPoolTimeoutInMs; protected int idleConnectionTimeoutInMs; protected int requestTimeoutInMs; protected boolean redirectEnabled; protected int maxDefaultRedirects; protected boolean compressionEnabled; protected String userAgent; protected boolean allowPoolingConnection; protected ScheduledExecutorService reaper; protected ExecutorService applicationThreadPool; protected ProxyServerSelector proxyServerSelector; protected SSLContext sslContext; protected SSLEngineFactory sslEngineFactory; protected AsyncHttpProviderConfig<?, ?> providerConfig; protected ConnectionsPool<?, ?> connectionsPool; protected Realm realm; protected List<RequestFilter> requestFilters; protected List<ResponseFilter> responseFilters; protected List<IOExceptionFilter> ioExceptionFilters; protected int requestCompressionLevel; protected int maxRequestRetry; protected boolean allowSslConnectionPool; protected boolean useRawUrl; protected boolean removeQueryParamOnRedirect; protected boolean managedApplicationThreadPool; protected HostnameVerifier hostnameVerifier; protected int ioThreadMultiplier; protected boolean strict302Handling; protected int maxConnectionLifeTimeInMs; protected boolean useRelativeURIsWithSSLProxies; protected boolean spdyEnabled; protected int spdyInitialWindowSize; protected int spdyMaxConcurrentStreams; protected boolean rfc6265CookieEncoding; protected boolean asyncConnectMode; protected AsyncHttpClientConfig() { } private AsyncHttpClientConfig(int maxTotalConnections, int maxConnectionPerHost, int connectionTimeOutInMs, int webSocketTimeoutInMs, int idleConnectionInPoolTimeoutInMs, int idleConnectionTimeoutInMs, int requestTimeoutInMs, int connectionMaxLifeTimeInMs, boolean redirectEnabled, int maxDefaultRedirects, boolean compressionEnabled, String userAgent, boolean keepAlive, ScheduledExecutorService reaper, ExecutorService applicationThreadPool, ProxyServerSelector proxyServerSelector, SSLContext sslContext, SSLEngineFactory sslEngineFactory, AsyncHttpProviderConfig<?, ?> providerConfig, ConnectionsPool<?, ?> connectionsPool, Realm realm, List<RequestFilter> requestFilters, List<ResponseFilter> responseFilters, List<IOExceptionFilter> ioExceptionFilters, int requestCompressionLevel, int maxRequestRetry, boolean allowSslConnectionCaching, boolean useRawUrl, boolean removeQueryParamOnRedirect, HostnameVerifier hostnameVerifier, int ioThreadMultiplier, boolean strict302Handling, boolean useRelativeURIsWithSSLProxies, boolean spdyEnabled, int spdyInitialWindowSize, int spdyMaxConcurrentStreams, boolean rfc6265CookieEncoding, boolean asyncConnectMode, boolean managedApplicationThreadPool) { this.maxTotalConnections = maxTotalConnections; this.maxConnectionPerHost = maxConnectionPerHost; this.connectionTimeOutInMs = connectionTimeOutInMs; this.webSocketIdleTimeoutInMs = webSocketTimeoutInMs; this.idleConnectionInPoolTimeoutInMs = idleConnectionInPoolTimeoutInMs; this.idleConnectionTimeoutInMs = idleConnectionTimeoutInMs; this.requestTimeoutInMs = requestTimeoutInMs; this.maxConnectionLifeTimeInMs = connectionMaxLifeTimeInMs; this.redirectEnabled = redirectEnabled; this.maxDefaultRedirects = maxDefaultRedirects; this.compressionEnabled = compressionEnabled; this.userAgent = userAgent; this.allowPoolingConnection = keepAlive; this.sslContext = sslContext; this.sslEngineFactory = sslEngineFactory; this.providerConfig = providerConfig; this.connectionsPool = connectionsPool; this.realm = realm; this.requestFilters = requestFilters; this.responseFilters = responseFilters; this.ioExceptionFilters = ioExceptionFilters; this.requestCompressionLevel = requestCompressionLevel; this.maxRequestRetry = maxRequestRetry; this.reaper = reaper; this.allowSslConnectionPool = allowSslConnectionCaching; this.removeQueryParamOnRedirect = removeQueryParamOnRedirect; this.hostnameVerifier = hostnameVerifier; this.ioThreadMultiplier = ioThreadMultiplier; this.strict302Handling = strict302Handling; this.useRelativeURIsWithSSLProxies = useRelativeURIsWithSSLProxies; this.managedApplicationThreadPool = managedApplicationThreadPool; this.applicationThreadPool = applicationThreadPool; this.proxyServerSelector = proxyServerSelector; this.useRawUrl = useRawUrl; this.spdyEnabled = spdyEnabled; this.spdyInitialWindowSize = spdyInitialWindowSize; this.spdyMaxConcurrentStreams = spdyMaxConcurrentStreams; this.rfc6265CookieEncoding = rfc6265CookieEncoding; this.asyncConnectMode = asyncConnectMode; } /** * A {@link ScheduledExecutorService} used to expire idle connections. * * @return {@link ScheduledExecutorService} */ public ScheduledExecutorService reaper() { return reaper; } /** * Return the maximum number of connections an {@link AsyncHttpClient} can handle. * * @return the maximum number of connections an {@link AsyncHttpClient} can handle. */ public int getMaxTotalConnections() { return maxTotalConnections; } /** * Return the maximum number of connections per hosts an {@link AsyncHttpClient} can handle. * * @return the maximum number of connections per host an {@link AsyncHttpClient} can handle. */ public int getMaxConnectionPerHost() { return maxConnectionPerHost; } /** * Return the maximum time in millisecond an {@link AsyncHttpClient} can wait when connecting to a remote host * * @return the maximum time in millisecond an {@link AsyncHttpClient} can wait when connecting to a remote host */ public int getConnectionTimeoutInMs() { return connectionTimeOutInMs; } /** * Return the maximum time, in milliseconds, a {@link org.asynchttpclient.websocket.WebSocket} may be idle before being timed out. * @return the maximum time, in milliseconds, a {@link org.asynchttpclient.websocket.WebSocket} may be idle before being timed out. */ public int getWebSocketIdleTimeoutInMs() { return webSocketIdleTimeoutInMs; } /** * Return the maximum time in millisecond an {@link AsyncHttpClient} can stay idle. * * @return the maximum time in millisecond an {@link AsyncHttpClient} can stay idle. */ public int getIdleConnectionTimeoutInMs() { return idleConnectionTimeoutInMs; } /** * Return the maximum time in millisecond an {@link AsyncHttpClient} will keep connection * in pool. * * @return the maximum time in millisecond an {@link AsyncHttpClient} will keep connection * in pool. */ public int getIdleConnectionInPoolTimeoutInMs() { return idleConnectionInPoolTimeoutInMs; } /** * Return the maximum time in millisecond an {@link AsyncHttpClient} wait for a response * * @return the maximum time in millisecond an {@link AsyncHttpClient} wait for a response */ public int getRequestTimeoutInMs() { return requestTimeoutInMs; } /** * Is HTTP redirect enabled * * @return true if enabled. */ public boolean isRedirectEnabled() { return redirectEnabled; } /** * Get the maximum number of HTTP redirect * * @return the maximum number of HTTP redirect */ public int getMaxRedirects() { return maxDefaultRedirects; } /** * Is the {@link ConnectionsPool} support enabled. * * @return true if keep-alive is enabled */ public boolean getAllowPoolingConnection() { return allowPoolingConnection; } /** * Is the {@link ConnectionsPool} support enabled. * * @return true if keep-alive is enabled * @deprecated - Use {@link AsyncHttpClientConfig#getAllowPoolingConnection()} */ public boolean getKeepAlive() { return allowPoolingConnection; } /** * Return the USER_AGENT header value * * @return the USER_AGENT header value */ public String getUserAgent() { return userAgent; } /** * Is HTTP compression enabled. * * @return true if compression is enabled */ public boolean isCompressionEnabled() { return compressionEnabled; } /** * Return the {@link java.util.concurrent.ExecutorService} an {@link AsyncHttpClient} use for handling * asynchronous response. * * @return the {@link java.util.concurrent.ExecutorService} an {@link AsyncHttpClient} use for handling * asynchronous response. */ public ExecutorService executorService() { return applicationThreadPool; } /** * @return <code>true</code> if this <code>AsyncHttpClientConfig</code> instance created the * {@link ExecutorService} returned by {@link #executorService()}, otherwise returns <code>false</code>. * The return from this method is typically used by the various provider implementations to determine * if it should shutdown the {@link ExecutorService} when the {@link AsyncHttpClient} is closed. Developers * should take care and not share managed {@link ExecutorService} instances between client instances. * * @since 2.2.0 */ public boolean isManagedExecutorService() { return managedApplicationThreadPool; } /** * An instance of {@link ProxyServer} used by an {@link AsyncHttpClient} * * @return instance of {@link ProxyServer} */ public ProxyServerSelector getProxyServerSelector() { return proxyServerSelector; } /** * Return an instance of {@link SSLContext} used for SSL connection. * * @return an instance of {@link SSLContext} used for SSL connection. */ public SSLContext getSSLContext() { return sslContext; } /** * Return an instance of {@link ConnectionsPool} * * @return an instance of {@link ConnectionsPool} */ public ConnectionsPool<?, ?> getConnectionsPool() { return connectionsPool; } /** * Return an instance of {@link SSLEngineFactory} used for SSL connection. * * @return an instance of {@link SSLEngineFactory} used for SSL connection. */ public SSLEngineFactory getSSLEngineFactory() { if (sslEngineFactory == null) { return new SSLEngineFactory() { public SSLEngine newSSLEngine() { if (sslContext != null) { SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setUseClientMode(true); return sslEngine; } else { return null; } } }; } return sslEngineFactory; } /** * Return the {@link AsyncHttpProviderConfig} * * @return the {@link AsyncHttpProviderConfig} */ public AsyncHttpProviderConfig<?, ?> getAsyncHttpProviderConfig() { return providerConfig; } /** * Return the current {@link Realm}} * * @return the current {@link Realm}} */ public Realm getRealm() { return realm; } /** * @return <code>true</code> if {@link RequestFilter}s have been defined. * * @since 2.0.0 */ public boolean hasRequestFilters() { return !requestFilters.isEmpty(); } /** * Return the list of {@link RequestFilter} * * @return Unmodifiable list of {@link ResponseFilter} */ public List<RequestFilter> getRequestFilters() { return Collections.unmodifiableList(requestFilters); } /** * @return <code>true</code> if {@link ResponseFilter}s have been defined. * @since 2.0.0 */ public boolean hasResponseFilters() { return !responseFilters.isEmpty(); } /** * Return the list of {@link ResponseFilter} * * @return Unmodifiable list of {@link ResponseFilter} */ public List<ResponseFilter> getResponseFilters() { return Collections.unmodifiableList(responseFilters); } /** * Return the list of {@link java.io.IOException} * * @return Unmodifiable list of {@link java.io.IOException} */ public List<IOExceptionFilter> getIOExceptionFilters() { return Collections.unmodifiableList(ioExceptionFilters); } /** * Return the compression level, or -1 if no compression is used. * * @return the compression level, or -1 if no compression is use */ public int getRequestCompressionLevel() { return requestCompressionLevel; } /** * Return the number of time the library will retry when an {@link java.io.IOException} is throw by the remote server * * @return the number of time the library will retry when an {@link java.io.IOException} is throw by the remote server */ public int getMaxRequestRetry() { return maxRequestRetry; } /** * Return true is SSL connection polling is enabled. Default is true. * * @return true is enabled. */ public boolean isSslConnectionPoolEnabled() { return allowSslConnectionPool; } /** * @return the useRawUrl */ public boolean isUseRawUrl() { return useRawUrl; } /** * @return whether or not SPDY is enabled. */ public boolean isSpdyEnabled() { return spdyEnabled; } /** * @return the windows size new SPDY sessions should be initialized to. */ public int getSpdyInitialWindowSize() { return spdyInitialWindowSize; } /** * @return the maximum number of concurrent streams over one SPDY session. */ public int getSpdyMaxConcurrentStreams() { return spdyMaxConcurrentStreams; } /** * Return true if the query parameters will be stripped from the request when a redirect is requested. * * @return true if the query parameters will be stripped from the request when a redirect is requested. */ public boolean isRemoveQueryParamOnRedirect() { return removeQueryParamOnRedirect; } /** * Return true if one of the {@link java.util.concurrent.ExecutorService} has been shutdown. * * @return true if one of the {@link java.util.concurrent.ExecutorService} has been shutdown. */ public boolean isClosed() { return applicationThreadPool.isShutdown() || reaper.isShutdown(); } /** * Return the {@link HostnameVerifier} * * @return the {@link HostnameVerifier} */ public HostnameVerifier getHostnameVerifier() { return hostnameVerifier; } /** * @return number to multiply by availableProcessors() that will determine # of NioWorkers to use */ public int getIoThreadMultiplier() { return ioThreadMultiplier; } /** * <p> * In the case of a POST/Redirect/Get scenario where the server uses a 302 * for the redirect, should AHC respond to the redirect with a GET or * whatever the original method was. Unless configured otherwise, * for a 302, AHC, will use a GET for this case. * </p> * * @return <code>true</code> if string 302 handling is to be used, * otherwise <code>false</code>. * * @since 1.7.2 */ public boolean isStrict302Handling() { return strict302Handling; } /** * @return<code>true</code> if AHC should use relative URIs instead of absolute ones when talking with a SSL proxy, * otherwise <code>false</code>. * * @since 1.7.12 */ public boolean isUseRelativeURIsWithSSLProxies() { return useRelativeURIsWithSSLProxies; } /** * Return the maximum time in millisecond an {@link AsyncHttpClient} will keep connection in the pool, or -1 to keep connection while possible. * * @return the maximum time in millisecond an {@link AsyncHttpClient} will keep connection in the pool, or -1 to keep connection while possible. */ public int getMaxConnectionLifeTimeInMs() { return maxConnectionLifeTimeInMs; } /** * @return<code>true</code> if AHC should use rfc6265 for encoding client side cookies, otherwise <code>false</code>. * * @since 1.7.18 */ public boolean isRfc6265CookieEncoding() { return rfc6265CookieEncoding; } /** * @return <code>true</code> if the underlying provider should make new connections asynchronously or not. By default * new connections are made synchronously. * * @since 2.0.0 */ public boolean isAsyncConnectMode() { return asyncConnectMode; } /** * Builder for an {@link AsyncHttpClient} */ public static class Builder { private int defaultMaxTotalConnections = Integer.getInteger(ASYNC_CLIENT + "defaultMaxTotalConnections", -1); private int defaultMaxConnectionPerHost = Integer.getInteger(ASYNC_CLIENT + "defaultMaxConnectionsPerHost", -1); private int defaultConnectionTimeOutInMs = Integer.getInteger(ASYNC_CLIENT + "defaultConnectionTimeoutInMS", 60 * 1000); private int defaultWebsocketIdleTimeoutInMs = Integer.getInteger(ASYNC_CLIENT + "defaultWebsocketTimoutInMS", 15 * 60 * 1000); private int defaultIdleConnectionInPoolTimeoutInMs = Integer.getInteger(ASYNC_CLIENT + "defaultIdleConnectionInPoolTimeoutInMS", 60 * 1000); private int defaultIdleConnectionTimeoutInMs = Integer.getInteger(ASYNC_CLIENT + "defaultIdleConnectionTimeoutInMS", 60 * 1000); private int defaultRequestTimeoutInMs = Integer.getInteger(ASYNC_CLIENT + "defaultRequestTimeoutInMS", 60 * 1000); private int defaultMaxConnectionLifeTimeInMs = Integer.getInteger(ASYNC_CLIENT + "defaultMaxConnectionLifeTimeInMs", -1); private boolean redirectEnabled = Boolean.getBoolean(ASYNC_CLIENT + "defaultRedirectsEnabled"); private int maxDefaultRedirects = Integer.getInteger(ASYNC_CLIENT + "defaultMaxRedirects", 5); private boolean compressionEnabled = Boolean.getBoolean(ASYNC_CLIENT + "compressionEnabled"); private String userAgent = System.getProperty(ASYNC_CLIENT + "userAgent", "AsyncHttpClient/" + AHC_VERSION); private boolean useProxyProperties = Boolean.getBoolean(ASYNC_CLIENT + "useProxyProperties"); private boolean useProxySelector = Boolean.getBoolean(ASYNC_CLIENT + "useProxySelector"); private boolean allowPoolingConnection = true; private boolean useRelativeURIsWithSSLProxies = Boolean.getBoolean(ASYNC_CLIENT + "useRelativeURIsWithSSLProxies"); private ScheduledExecutorService reaper; private ExecutorService applicationThreadPool; private boolean managedApplicationThreadPool; private ProxyServerSelector proxyServerSelector = null; private SSLContext sslContext; private SSLEngineFactory sslEngineFactory; private AsyncHttpProviderConfig<?, ?> providerConfig; private ConnectionsPool<?, ?> connectionsPool; private Realm realm; private int requestCompressionLevel = -1; private int maxRequestRetry = 5; private final List<RequestFilter> requestFilters = new LinkedList<RequestFilter>(); private final List<ResponseFilter> responseFilters = new LinkedList<ResponseFilter>(); private final List<IOExceptionFilter> ioExceptionFilters = new LinkedList<IOExceptionFilter>(); private boolean allowSslConnectionPool = true; private boolean useRawUrl = false; private boolean removeQueryParamOnRedirect = true; private HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier(); private int ioThreadMultiplier = 2; private boolean strict302Handling; private boolean spdyEnabled; private int spdyInitialWindowSize = 10 * 1024 * 1024; private int spdyMaxConcurrentStreams = 100; private boolean rfc6265CookieEncoding; private boolean asyncConnectMode; public Builder() { } /** * Set the maximum number of connections an {@link AsyncHttpClient} can handle. * * @param defaultMaxTotalConnections the maximum number of connections an {@link AsyncHttpClient} can handle. * @return a {@link Builder} */ public Builder setMaximumConnectionsTotal(int defaultMaxTotalConnections) { this.defaultMaxTotalConnections = defaultMaxTotalConnections; return this; } /** * Set the maximum number of connections per hosts an {@link AsyncHttpClient} can handle. * * @param defaultMaxConnectionPerHost the maximum number of connections per host an {@link AsyncHttpClient} can handle. * @return a {@link Builder} */ public Builder setMaximumConnectionsPerHost(int defaultMaxConnectionPerHost) { this.defaultMaxConnectionPerHost = defaultMaxConnectionPerHost; return this; } /** * Set the maximum time in millisecond an {@link AsyncHttpClient} can wait when connecting to a remote host * * @param defaultConnectionTimeOutInMs the maximum time in millisecond an {@link AsyncHttpClient} can wait when connecting to a remote host * @return a {@link Builder} */ public Builder setConnectionTimeoutInMs(int defaultConnectionTimeOutInMs) { this.defaultConnectionTimeOutInMs = defaultConnectionTimeOutInMs; return this; } /** * Set the maximum time in millisecond an {@link org.asynchttpclient.websocket.WebSocket} can stay idle. * * @param defaultWebSocketIdleTimeoutInMs * the maximum time in millisecond an {@link org.asynchttpclient.websocket.WebSocket} can stay idle. * @return a {@link Builder} */ public Builder setWebSocketIdleTimeoutInMs(int defaultWebSocketIdleTimeoutInMs) { this.defaultWebsocketIdleTimeoutInMs = defaultWebSocketIdleTimeoutInMs; return this; } /** * Set the maximum time in millisecond an {@link AsyncHttpClient} can stay idle. * * @param defaultIdleConnectionTimeoutInMs * the maximum time in millisecond an {@link AsyncHttpClient} can stay idle. * @return a {@link Builder} */ public Builder setIdleConnectionTimeoutInMs(int defaultIdleConnectionTimeoutInMs) { this.defaultIdleConnectionTimeoutInMs = defaultIdleConnectionTimeoutInMs; return this; } /** * Set the maximum time in millisecond an {@link AsyncHttpClient} will keep connection * idle in pool. * * @param defaultIdleConnectionInPoolTimeoutInMs * the maximum time in millisecond an {@link AsyncHttpClient} will keep connection * idle in pool. * @return a {@link Builder} */ public Builder setIdleConnectionInPoolTimeoutInMs(int defaultIdleConnectionInPoolTimeoutInMs) { this.defaultIdleConnectionInPoolTimeoutInMs = defaultIdleConnectionInPoolTimeoutInMs; return this; } /** * Set the maximum time in millisecond an {@link AsyncHttpClient} wait for a response * * @param defaultRequestTimeoutInMs the maximum time in millisecond an {@link AsyncHttpClient} wait for a response * @return a {@link Builder} */ public Builder setRequestTimeoutInMs(int defaultRequestTimeoutInMs) { this.defaultRequestTimeoutInMs = defaultRequestTimeoutInMs; return this; } /** * Set to true to enable HTTP redirect * * @param redirectEnabled true if enabled. * @return a {@link Builder} */ public Builder setFollowRedirects(boolean redirectEnabled) { this.redirectEnabled = redirectEnabled; return this; } /** * Set the maximum number of HTTP redirect * * @param maxDefaultRedirects the maximum number of HTTP redirect * @return a {@link Builder} */ public Builder setMaximumNumberOfRedirects(int maxDefaultRedirects) { this.maxDefaultRedirects = maxDefaultRedirects; return this; } /** * Enable HTTP compression. * * @param compressionEnabled true if compression is enabled * @return a {@link Builder} */ public Builder setCompressionEnabled(boolean compressionEnabled) { this.compressionEnabled = compressionEnabled; return this; } /** * Set the USER_AGENT header value * * @param userAgent the USER_AGENT header value * @return a {@link Builder} */ public Builder setUserAgent(String userAgent) { this.userAgent = userAgent; return this; } /** * Set true if connection can be pooled by a {@link ConnectionsPool}. Default is true. * * @param allowPoolingConnection true if connection can be pooled by a {@link ConnectionsPool} * @return a {@link Builder} */ public Builder setAllowPoolingConnection(boolean allowPoolingConnection) { this.allowPoolingConnection = allowPoolingConnection; return this; } /** * Set true if connection can be pooled by a {@link ConnectionsPool}. Default is true. * * @param allowPoolingConnection true if connection can be pooled by a {@link ConnectionsPool} * @return a {@link Builder} * @deprecated - Use {@link AsyncHttpClientConfig.Builder#setAllowPoolingConnection(boolean)} */ public Builder setKeepAlive(boolean allowPoolingConnection) { this.allowPoolingConnection = allowPoolingConnection; return this; } /** * Set the{@link ScheduledExecutorService} used to expire idle connections. * * @param reaper the{@link ScheduledExecutorService} used to expire idle connections. * @return a {@link Builder} */ public Builder setScheduledExecutorService(ScheduledExecutorService reaper) { this.reaper = reaper; return this; } /** * Set the {@link java.util.concurrent.ExecutorService} an {@link AsyncHttpClient} use for handling * asynchronous response. * * @param applicationThreadPool the {@link java.util.concurrent.ExecutorService} an {@link AsyncHttpClient} use for handling * asynchronous response. * @return a {@link Builder} */ public Builder setExecutorService(ExecutorService applicationThreadPool) { this.applicationThreadPool = applicationThreadPool; return this; } /** * Set an instance of {@link ProxyServerSelector} used by an {@link AsyncHttpClient} * * @param proxyServerSelector instance of {@link ProxyServerSelector} * @return a {@link Builder} */ public Builder setProxyServerSelector(ProxyServerSelector proxyServerSelector) { this.proxyServerSelector = proxyServerSelector; return this; } /** * Set an instance of {@link ProxyServer} used by an {@link AsyncHttpClient} * * @param proxyServer instance of {@link ProxyServer} * @return a {@link Builder} */ public Builder setProxyServer(ProxyServer proxyServer) { this.proxyServerSelector = ProxyUtils.createProxyServerSelector(proxyServer); return this; } /** * Set the {@link SSLEngineFactory} for secure connection. * * @param sslEngineFactory the {@link SSLEngineFactory} for secure connection * @return a {@link Builder} */ public Builder setSSLEngineFactory(SSLEngineFactory sslEngineFactory) { this.sslEngineFactory = sslEngineFactory; return this; } /** * Set the {@link SSLContext} for secure connection. * * @param sslContext the {@link SSLContext} for secure connection * @return a {@link Builder} */ public Builder setSSLContext(final SSLContext sslContext) { this.sslEngineFactory = new SSLEngineFactory() { public SSLEngine newSSLEngine() throws GeneralSecurityException { SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setUseClientMode(true); return sslEngine; } }; this.sslContext = sslContext; return this; } /** * Set the {@link AsyncHttpProviderConfig} * * @param providerConfig the {@link AsyncHttpProviderConfig} * @return a {@link Builder} */ public Builder setAsyncHttpClientProviderConfig(AsyncHttpProviderConfig<?, ?> providerConfig) { this.providerConfig = providerConfig; return this; } /** * Set the {@link ConnectionsPool} * * @param connectionsPool the {@link ConnectionsPool} * @return a {@link Builder} */ public Builder setConnectionsPool(ConnectionsPool<?, ?> connectionsPool) { this.connectionsPool = connectionsPool; return this; } /** * Set the {@link Realm} that will be used for all requests. * * @param realm the {@link Realm} * @return a {@link Builder} */ public Builder setRealm(Realm realm) { this.realm = realm; return this; } /** * Add an {@link org.asynchttpclient.filter.RequestFilter} that will be invoked before {@link AsyncHttpClient#executeRequest(Request)} * * @param requestFilter {@link org.asynchttpclient.filter.RequestFilter} * @return this */ public Builder addRequestFilter(RequestFilter requestFilter) { requestFilters.add(requestFilter); return this; } /** * Remove an {@link org.asynchttpclient.filter.RequestFilter} that will be invoked before {@link AsyncHttpClient#executeRequest(Request)} * * @param requestFilter {@link org.asynchttpclient.filter.RequestFilter} * @return this */ public Builder removeRequestFilter(RequestFilter requestFilter) { requestFilters.remove(requestFilter); return this; } /** * Add an {@link org.asynchttpclient.filter.ResponseFilter} that will be invoked as soon as the response is * received, and before {@link AsyncHandler#onStatusReceived(HttpResponseStatus)}. * * @param responseFilter an {@link org.asynchttpclient.filter.ResponseFilter} * @return this */ public Builder addResponseFilter(ResponseFilter responseFilter) { responseFilters.add(responseFilter); return this; } /** * Remove an {@link org.asynchttpclient.filter.ResponseFilter} that will be invoked as soon as the response is * received, and before {@link AsyncHandler#onStatusReceived(HttpResponseStatus)}. * * @param responseFilter an {@link org.asynchttpclient.filter.ResponseFilter} * @return this */ public Builder removeResponseFilter(ResponseFilter responseFilter) { responseFilters.remove(responseFilter); return this; } /** * Add an {@link org.asynchttpclient.filter.IOExceptionFilter} that will be invoked when an {@link java.io.IOException} * occurs during the download/upload operations. * * @param ioExceptionFilter an {@link org.asynchttpclient.filter.ResponseFilter} * @return this */ public Builder addIOExceptionFilter(IOExceptionFilter ioExceptionFilter) { ioExceptionFilters.add(ioExceptionFilter); return this; } /** * Remove an {@link org.asynchttpclient.filter.IOExceptionFilter} tthat will be invoked when an {@link java.io.IOException} * occurs during the download/upload operations. * * @param ioExceptionFilter an {@link org.asynchttpclient.filter.ResponseFilter} * @return this */ public Builder removeIOExceptionFilter(IOExceptionFilter ioExceptionFilter) { ioExceptionFilters.remove(ioExceptionFilter); return this; } /** * Return the compression level, or -1 if no compression is used. * * @return the compression level, or -1 if no compression is use */ public int getRequestCompressionLevel() { return requestCompressionLevel; } /** * Set the compression level, or -1 if no compression is used. * * @param requestCompressionLevel compression level, or -1 if no compression is use * @return this */ public Builder setRequestCompressionLevel(int requestCompressionLevel) { this.requestCompressionLevel = requestCompressionLevel; return this; } /** * Set the number of times a request will be retried when an {@link java.io.IOException} occurs because of a Network exception. * * @param maxRequestRetry the number of times a request will be retried * @return this */ public Builder setMaxRequestRetry(int maxRequestRetry) { this.maxRequestRetry = maxRequestRetry; return this; } /** * Return true is if connections pooling is enabled. * * @param allowSslConnectionPool true if enabled * @return this */ public Builder setAllowSslConnectionPool(boolean allowSslConnectionPool) { this.allowSslConnectionPool = allowSslConnectionPool; return this; } /** * Allows use unescaped URLs in requests * useful for retrieving data from broken sites * * @param useRawUrl * @return this */ public Builder setUseRawUrl(boolean useRawUrl) { this.useRawUrl = useRawUrl; return this; } /** * Set to false if you don't want the query parameters removed when a redirect occurs. * * @param removeQueryParamOnRedirect * @return this */ public Builder setRemoveQueryParamsOnRedirect(boolean removeQueryParamOnRedirect) { this.removeQueryParamOnRedirect = removeQueryParamOnRedirect; return this; } /** * Sets whether AHC should use the default JDK ProxySelector to select a proxy server. * <p/> * If useProxySelector is set to <code>true</code> but {@link #setProxyServer(ProxyServer)} * was used to explicitly set a proxy server, the latter is preferred. * <p/> * See http://docs.oracle.com/javase/7/docs/api/java/net/ProxySelector.html */ public Builder setUseProxySelector(boolean useProxySelector) { this.useProxySelector = useProxySelector; return this; } /** * Sets whether AHC should use the default http.proxy* system properties * to obtain proxy information. This differs from {@link #setUseProxySelector(boolean)} * in that AsyncHttpClient will use its own logic to handle the system properties, * potentially supporting other protocols that the the JDK ProxySelector doesn't. * <p/> * If useProxyProperties is set to <code>true</code> but {@link #setUseProxySelector(boolean)} * was also set to true, the latter is preferred. * <p/> * See http://download.oracle.com/javase/1.4.2/docs/guide/net/properties.html */ public Builder setUseProxyProperties(boolean useProxyProperties) { this.useProxyProperties = useProxyProperties; return this; } public Builder setIOThreadMultiplier(int multiplier) { this.ioThreadMultiplier = multiplier; return this; } /** * Set the {@link HostnameVerifier} * * @param hostnameVerifier {@link HostnameVerifier} * @return this */ public Builder setHostnameVerifier(HostnameVerifier hostnameVerifier) { this.hostnameVerifier = hostnameVerifier; return this; } /** * Configures this AHC instance to be strict in it's handling of 302 redirects * in a POST/Redirect/GET situation. * * @param strict302Handling strict handling * * @return this * * @since 1.7.2 */ public Builder setStrict302Handling(final boolean strict302Handling) { this.strict302Handling = strict302Handling; return this; } /** * Set the maximum time in millisecond connection can be added to the pool for further reuse * * @param maxConnectionLifeTimeInMs the maximum time in millisecond connection can be added to the pool for further reuse * @return a {@link Builder} */ public Builder setMaxConnectionLifeTimeInMs(int maxConnectionLifeTimeInMs) { this.defaultMaxConnectionLifeTimeInMs = maxConnectionLifeTimeInMs; return this; } /** * Configures this AHC instance to use relative URIs instead of absolute ones when talking with a SSL proxy. * * @param useRelativeURIsWithSSLProxies * @return this * * @since 1.7.2 */ public Builder setUseRelativeURIsWithSSLProxies(boolean useRelativeURIsWithSSLProxies) { this.useRelativeURIsWithSSLProxies = useRelativeURIsWithSSLProxies; return this; } /** * Enables SPDY support. Note that doing so, will currently disable WebSocket support * for this client instance. If not explicitly enabled, spdy will not be used. * * @param spdyEnabled configures spdy support. * * @return this * * @since 2.0 */ public Builder setSpdyEnabled(boolean spdyEnabled) { this.spdyEnabled = spdyEnabled; return this; } /** * Configures the initial window size for the SPDY session. * * @param spdyInitialWindowSize the initial window size. * * @return this * * @since 2.0 */ public Builder setSpdyInitialWindowSize(int spdyInitialWindowSize) { this.spdyInitialWindowSize = spdyInitialWindowSize; return this; } /** * Configures the maximum number of concurrent streams over a single * SPDY session. * * @param spdyMaxConcurrentStreams the maximum number of concurrent * streams over a single SPDY session. * * @return this * * @since 2.0 */ public Builder setSpdyMaxConcurrentStreams(int spdyMaxConcurrentStreams) { this.spdyMaxConcurrentStreams = spdyMaxConcurrentStreams; return this; } /** * Configures this AHC instance to use RFC 6265 cookie encoding style * * @param rfc6265CookieEncoding * @return this * * @since 1.7.18 */ public Builder setRfc6265CookieEncoding(boolean rfc6265CookieEncoding) { this.rfc6265CookieEncoding = rfc6265CookieEncoding; return this; } /** * Configures how the underlying providers make new connections. By default, * connections will be made synchronously. * * @param asyncConnectMode pass <code>true</code> to enable async connect mode. * * @return this * * @since 2.0.0 */ public Builder setAsyncConnectMode(boolean asyncConnectMode) { this.asyncConnectMode = asyncConnectMode; return this; } /** * Create a config builder with values taken from the given prototype configuration. * * @param prototype the configuration to use as a prototype. */ public Builder(AsyncHttpClientConfig prototype) { allowPoolingConnection = prototype.getAllowPoolingConnection(); providerConfig = prototype.getAsyncHttpProviderConfig(); connectionsPool = prototype.getConnectionsPool(); defaultConnectionTimeOutInMs = prototype.getConnectionTimeoutInMs(); defaultIdleConnectionInPoolTimeoutInMs = prototype.getIdleConnectionInPoolTimeoutInMs(); defaultIdleConnectionTimeoutInMs = prototype.getIdleConnectionTimeoutInMs(); defaultMaxConnectionPerHost = prototype.getMaxConnectionPerHost(); defaultMaxConnectionLifeTimeInMs = prototype.getMaxConnectionLifeTimeInMs(); maxDefaultRedirects = prototype.getMaxRedirects(); defaultMaxTotalConnections = prototype.getMaxTotalConnections(); proxyServerSelector = prototype.getProxyServerSelector(); realm = prototype.getRealm(); defaultRequestTimeoutInMs = prototype.getRequestTimeoutInMs(); sslContext = prototype.getSSLContext(); sslEngineFactory = prototype.getSSLEngineFactory(); userAgent = prototype.getUserAgent(); redirectEnabled = prototype.isRedirectEnabled(); compressionEnabled = prototype.isCompressionEnabled(); reaper = prototype.reaper(); applicationThreadPool = prototype.executorService(); requestFilters.clear(); responseFilters.clear(); ioExceptionFilters.clear(); requestFilters.addAll(prototype.getRequestFilters()); responseFilters.addAll(prototype.getResponseFilters()); ioExceptionFilters.addAll(prototype.getIOExceptionFilters()); requestCompressionLevel = prototype.getRequestCompressionLevel(); useRawUrl = prototype.isUseRawUrl(); ioThreadMultiplier = prototype.getIoThreadMultiplier(); maxRequestRetry = prototype.getMaxRequestRetry(); allowSslConnectionPool = prototype.getAllowPoolingConnection(); removeQueryParamOnRedirect = prototype.isRemoveQueryParamOnRedirect(); hostnameVerifier = prototype.getHostnameVerifier(); strict302Handling = prototype.isStrict302Handling(); useRelativeURIsWithSSLProxies = prototype.isUseRelativeURIsWithSSLProxies(); rfc6265CookieEncoding = prototype.isRfc6265CookieEncoding(); asyncConnectMode = prototype.isAsyncConnectMode(); } /** * Build an {@link AsyncHttpClientConfig} * * @return an {@link AsyncHttpClientConfig} */ public AsyncHttpClientConfig build() { if (reaper == null) { reaper = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors(), new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r, "AsyncHttpClient-Reaper"); t.setDaemon(true); return t; } }); } if (applicationThreadPool == null) { managedApplicationThreadPool = true; - int count = Runtime.getRuntime().availableProcessors(); applicationThreadPool = - Executors.newFixedThreadPool(count, new ThreadFactory() { + Executors.newCachedThreadPool(new ThreadFactory() { final AtomicInteger counter = new AtomicInteger(); public Thread newThread(Runnable r) { Thread t = new Thread(r, "AsyncHttpClient-Callback-" + counter.incrementAndGet()); t.setDaemon(true); return t; } }); } if (applicationThreadPool.isShutdown()) { throw new IllegalStateException("ExecutorServices closed"); } if (proxyServerSelector == null && useProxySelector) { proxyServerSelector = ProxyUtils.getJdkDefaultProxyServerSelector(); } if (proxyServerSelector == null && useProxyProperties) { proxyServerSelector = ProxyUtils.createProxyServerSelector(System.getProperties()); } if (proxyServerSelector == null) { proxyServerSelector = ProxyServerSelector.NO_PROXY_SELECTOR; } return new AsyncHttpClientConfig(defaultMaxTotalConnections, defaultMaxConnectionPerHost, defaultConnectionTimeOutInMs, defaultWebsocketIdleTimeoutInMs, defaultIdleConnectionInPoolTimeoutInMs, defaultIdleConnectionTimeoutInMs, defaultRequestTimeoutInMs, defaultMaxConnectionLifeTimeInMs, redirectEnabled, maxDefaultRedirects, compressionEnabled, userAgent, allowPoolingConnection, reaper, applicationThreadPool, proxyServerSelector, sslContext, sslEngineFactory, providerConfig, connectionsPool, realm, requestFilters, responseFilters, ioExceptionFilters, requestCompressionLevel, maxRequestRetry, allowSslConnectionPool, useRawUrl, removeQueryParamOnRedirect, hostnameVerifier, ioThreadMultiplier, strict302Handling, useRelativeURIsWithSSLProxies, spdyEnabled, spdyInitialWindowSize, spdyMaxConcurrentStreams, rfc6265CookieEncoding, asyncConnectMode, managedApplicationThreadPool); } } }
false
true
public AsyncHttpClientConfig build() { if (reaper == null) { reaper = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors(), new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r, "AsyncHttpClient-Reaper"); t.setDaemon(true); return t; } }); } if (applicationThreadPool == null) { managedApplicationThreadPool = true; int count = Runtime.getRuntime().availableProcessors(); applicationThreadPool = Executors.newFixedThreadPool(count, new ThreadFactory() { final AtomicInteger counter = new AtomicInteger(); public Thread newThread(Runnable r) { Thread t = new Thread(r, "AsyncHttpClient-Callback-" + counter.incrementAndGet()); t.setDaemon(true); return t; } }); } if (applicationThreadPool.isShutdown()) { throw new IllegalStateException("ExecutorServices closed"); } if (proxyServerSelector == null && useProxySelector) { proxyServerSelector = ProxyUtils.getJdkDefaultProxyServerSelector(); } if (proxyServerSelector == null && useProxyProperties) { proxyServerSelector = ProxyUtils.createProxyServerSelector(System.getProperties()); } if (proxyServerSelector == null) { proxyServerSelector = ProxyServerSelector.NO_PROXY_SELECTOR; } return new AsyncHttpClientConfig(defaultMaxTotalConnections, defaultMaxConnectionPerHost, defaultConnectionTimeOutInMs, defaultWebsocketIdleTimeoutInMs, defaultIdleConnectionInPoolTimeoutInMs, defaultIdleConnectionTimeoutInMs, defaultRequestTimeoutInMs, defaultMaxConnectionLifeTimeInMs, redirectEnabled, maxDefaultRedirects, compressionEnabled, userAgent, allowPoolingConnection, reaper, applicationThreadPool, proxyServerSelector, sslContext, sslEngineFactory, providerConfig, connectionsPool, realm, requestFilters, responseFilters, ioExceptionFilters, requestCompressionLevel, maxRequestRetry, allowSslConnectionPool, useRawUrl, removeQueryParamOnRedirect, hostnameVerifier, ioThreadMultiplier, strict302Handling, useRelativeURIsWithSSLProxies, spdyEnabled, spdyInitialWindowSize, spdyMaxConcurrentStreams, rfc6265CookieEncoding, asyncConnectMode, managedApplicationThreadPool); }
public AsyncHttpClientConfig build() { if (reaper == null) { reaper = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors(), new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r, "AsyncHttpClient-Reaper"); t.setDaemon(true); return t; } }); } if (applicationThreadPool == null) { managedApplicationThreadPool = true; applicationThreadPool = Executors.newCachedThreadPool(new ThreadFactory() { final AtomicInteger counter = new AtomicInteger(); public Thread newThread(Runnable r) { Thread t = new Thread(r, "AsyncHttpClient-Callback-" + counter.incrementAndGet()); t.setDaemon(true); return t; } }); } if (applicationThreadPool.isShutdown()) { throw new IllegalStateException("ExecutorServices closed"); } if (proxyServerSelector == null && useProxySelector) { proxyServerSelector = ProxyUtils.getJdkDefaultProxyServerSelector(); } if (proxyServerSelector == null && useProxyProperties) { proxyServerSelector = ProxyUtils.createProxyServerSelector(System.getProperties()); } if (proxyServerSelector == null) { proxyServerSelector = ProxyServerSelector.NO_PROXY_SELECTOR; } return new AsyncHttpClientConfig(defaultMaxTotalConnections, defaultMaxConnectionPerHost, defaultConnectionTimeOutInMs, defaultWebsocketIdleTimeoutInMs, defaultIdleConnectionInPoolTimeoutInMs, defaultIdleConnectionTimeoutInMs, defaultRequestTimeoutInMs, defaultMaxConnectionLifeTimeInMs, redirectEnabled, maxDefaultRedirects, compressionEnabled, userAgent, allowPoolingConnection, reaper, applicationThreadPool, proxyServerSelector, sslContext, sslEngineFactory, providerConfig, connectionsPool, realm, requestFilters, responseFilters, ioExceptionFilters, requestCompressionLevel, maxRequestRetry, allowSslConnectionPool, useRawUrl, removeQueryParamOnRedirect, hostnameVerifier, ioThreadMultiplier, strict302Handling, useRelativeURIsWithSSLProxies, spdyEnabled, spdyInitialWindowSize, spdyMaxConcurrentStreams, rfc6265CookieEncoding, asyncConnectMode, managedApplicationThreadPool); }
diff --git a/server/plugin/src/pt/webdetails/cdf/dd/render/RenderComponents.java b/server/plugin/src/pt/webdetails/cdf/dd/render/RenderComponents.java index 86b1991d..2b0cc0a0 100644 --- a/server/plugin/src/pt/webdetails/cdf/dd/render/RenderComponents.java +++ b/server/plugin/src/pt/webdetails/cdf/dd/render/RenderComponents.java @@ -1,122 +1,122 @@ package pt.webdetails.cdf.dd.render; import java.util.Iterator; import java.util.Map; import net.sf.json.JSONObject; import org.apache.commons.jxpath.JXPathContext; import org.apache.commons.jxpath.Pointer; import org.json.JSONArray; import pt.webdetails.cdf.dd.Widget; import pt.webdetails.cdf.dd.render.components.ComponentManager; import pt.webdetails.cdf.dd.render.components.BaseComponent; @SuppressWarnings("unchecked") public class RenderComponents extends Renderer { public static final String newLine = System.getProperty("line.separator"); Class<JXPathContext>[] rendererConstructorArgs = new Class[] { JXPathContext.class }; public RenderComponents() { super(); } public String render(JXPathContext doc) throws Exception { return render(doc, null); } public String render(JXPathContext doc, String alias) throws Exception { setDoc(doc); Map<String, Widget> widgets = getWidgets(alias); StringBuffer widgetContent = new StringBuffer(), result = new StringBuffer(newLine + "<script language=\"javascript\" type=\"text/javascript\">" + newLine); final JSONObject settings = (JSONObject) doc.getValue("/settings"); result.append("wcdfSettings = "); result.append(settings.toString(2)); result.append(';'); Iterator<Pointer> components = doc.iteratePointers("/components/rows"); String componentsIds = ""; ComponentManager engine = ComponentManager.getInstance(); while (components.hasNext()) { Pointer pointer = components.next(); JXPathContext context = doc.getRelativeContext(pointer); Object metaWidget = context.getValue("meta_widget"), htmlObject; /* If the htmlObject doesn't exist, looking for it will throw an exception. */ try { htmlObject = context.getValue("properties[name='htmlObject']/value"); } catch (Exception e) { htmlObject = null; } boolean isWidget = metaWidget != null && metaWidget.toString().equals("true"); String id = htmlObject != null ? htmlObject.toString().replaceAll("\\$\\{.*:(.*)\\}","$1") : ""; if (isWidget && widgets.containsKey(id)) { widgetContent.append(newLine); widgetContent.append(widgets.get(id).getComponents()); JSONArray params = new JSONArray(context.getValue("properties[name='xActionArrayParameter']/value").toString()); for (int i = 0; i < params.length(); i++) { JSONArray line = params.getJSONArray(i); String widgetAlias = getWidgetAlias(context, alias), widgetParam = line.getString(0), dashboardParam = line.getString(1); widgetParam = aliasName(widgetAlias,widgetParam); widgetContent.append(newLine + "<script language=\"javascript\" type=\"text/javascript\">" + newLine); widgetContent.append("Dashboards.parameterModel.on('change:" + widgetParam + "',function(model,value){Dashboards.fireChange('${p:" + dashboardParam + "}',value)});\n"); widgetContent.append("Dashboards.parameterModel.on('change:${p:" + dashboardParam + "}',function(model,value){Dashboards.fireChange('" + widgetParam + "',value)});\n"); - widgetContent.append("Dashboards.setParameter('"+widgetParam+"',Dashboards.getParameterValue('${p:"+dashboardParam+"}'));"); + widgetContent.append("Dashboards.fireChange('"+widgetParam+"',Dashboards.getParameterValue('${p:"+dashboardParam+"}'));"); widgetContent.append("</script>\n"); } } else { BaseComponent renderer = engine.getRenderer(context); if (renderer != null) { // Discard everything that's not an actual renderable component renderer.setAlias(alias); renderer.setNode(context); if (renderer.getId().startsWith("render_")) { componentsIds += renderer.getId().length() > 0 ? renderer.getId() + "," : ""; } result.append(newLine); result.append(renderer.render(context)); } } } if (componentsIds.length() > 0) { result.append(newLine + "Dashboards.addComponents([" + componentsIds.replaceAll(",$", "]") + ");"); } result.append(newLine); result.append("</script>"); result.append(newLine); result.append(widgetContent); return result.toString(); } @Override public String getRenderClassName(String type) { return "pt.webdetails.cdf.dd.render.components." + type.replace("Components", "") + "Render"; } }
true
true
public String render(JXPathContext doc, String alias) throws Exception { setDoc(doc); Map<String, Widget> widgets = getWidgets(alias); StringBuffer widgetContent = new StringBuffer(), result = new StringBuffer(newLine + "<script language=\"javascript\" type=\"text/javascript\">" + newLine); final JSONObject settings = (JSONObject) doc.getValue("/settings"); result.append("wcdfSettings = "); result.append(settings.toString(2)); result.append(';'); Iterator<Pointer> components = doc.iteratePointers("/components/rows"); String componentsIds = ""; ComponentManager engine = ComponentManager.getInstance(); while (components.hasNext()) { Pointer pointer = components.next(); JXPathContext context = doc.getRelativeContext(pointer); Object metaWidget = context.getValue("meta_widget"), htmlObject; /* If the htmlObject doesn't exist, looking for it will throw an exception. */ try { htmlObject = context.getValue("properties[name='htmlObject']/value"); } catch (Exception e) { htmlObject = null; } boolean isWidget = metaWidget != null && metaWidget.toString().equals("true"); String id = htmlObject != null ? htmlObject.toString().replaceAll("\\$\\{.*:(.*)\\}","$1") : ""; if (isWidget && widgets.containsKey(id)) { widgetContent.append(newLine); widgetContent.append(widgets.get(id).getComponents()); JSONArray params = new JSONArray(context.getValue("properties[name='xActionArrayParameter']/value").toString()); for (int i = 0; i < params.length(); i++) { JSONArray line = params.getJSONArray(i); String widgetAlias = getWidgetAlias(context, alias), widgetParam = line.getString(0), dashboardParam = line.getString(1); widgetParam = aliasName(widgetAlias,widgetParam); widgetContent.append(newLine + "<script language=\"javascript\" type=\"text/javascript\">" + newLine); widgetContent.append("Dashboards.parameterModel.on('change:" + widgetParam + "',function(model,value){Dashboards.fireChange('${p:" + dashboardParam + "}',value)});\n"); widgetContent.append("Dashboards.parameterModel.on('change:${p:" + dashboardParam + "}',function(model,value){Dashboards.fireChange('" + widgetParam + "',value)});\n"); widgetContent.append("Dashboards.setParameter('"+widgetParam+"',Dashboards.getParameterValue('${p:"+dashboardParam+"}'));"); widgetContent.append("</script>\n"); } } else { BaseComponent renderer = engine.getRenderer(context); if (renderer != null) { // Discard everything that's not an actual renderable component renderer.setAlias(alias); renderer.setNode(context); if (renderer.getId().startsWith("render_")) { componentsIds += renderer.getId().length() > 0 ? renderer.getId() + "," : ""; } result.append(newLine); result.append(renderer.render(context)); } } } if (componentsIds.length() > 0) { result.append(newLine + "Dashboards.addComponents([" + componentsIds.replaceAll(",$", "]") + ");"); } result.append(newLine); result.append("</script>"); result.append(newLine); result.append(widgetContent); return result.toString(); }
public String render(JXPathContext doc, String alias) throws Exception { setDoc(doc); Map<String, Widget> widgets = getWidgets(alias); StringBuffer widgetContent = new StringBuffer(), result = new StringBuffer(newLine + "<script language=\"javascript\" type=\"text/javascript\">" + newLine); final JSONObject settings = (JSONObject) doc.getValue("/settings"); result.append("wcdfSettings = "); result.append(settings.toString(2)); result.append(';'); Iterator<Pointer> components = doc.iteratePointers("/components/rows"); String componentsIds = ""; ComponentManager engine = ComponentManager.getInstance(); while (components.hasNext()) { Pointer pointer = components.next(); JXPathContext context = doc.getRelativeContext(pointer); Object metaWidget = context.getValue("meta_widget"), htmlObject; /* If the htmlObject doesn't exist, looking for it will throw an exception. */ try { htmlObject = context.getValue("properties[name='htmlObject']/value"); } catch (Exception e) { htmlObject = null; } boolean isWidget = metaWidget != null && metaWidget.toString().equals("true"); String id = htmlObject != null ? htmlObject.toString().replaceAll("\\$\\{.*:(.*)\\}","$1") : ""; if (isWidget && widgets.containsKey(id)) { widgetContent.append(newLine); widgetContent.append(widgets.get(id).getComponents()); JSONArray params = new JSONArray(context.getValue("properties[name='xActionArrayParameter']/value").toString()); for (int i = 0; i < params.length(); i++) { JSONArray line = params.getJSONArray(i); String widgetAlias = getWidgetAlias(context, alias), widgetParam = line.getString(0), dashboardParam = line.getString(1); widgetParam = aliasName(widgetAlias,widgetParam); widgetContent.append(newLine + "<script language=\"javascript\" type=\"text/javascript\">" + newLine); widgetContent.append("Dashboards.parameterModel.on('change:" + widgetParam + "',function(model,value){Dashboards.fireChange('${p:" + dashboardParam + "}',value)});\n"); widgetContent.append("Dashboards.parameterModel.on('change:${p:" + dashboardParam + "}',function(model,value){Dashboards.fireChange('" + widgetParam + "',value)});\n"); widgetContent.append("Dashboards.fireChange('"+widgetParam+"',Dashboards.getParameterValue('${p:"+dashboardParam+"}'));"); widgetContent.append("</script>\n"); } } else { BaseComponent renderer = engine.getRenderer(context); if (renderer != null) { // Discard everything that's not an actual renderable component renderer.setAlias(alias); renderer.setNode(context); if (renderer.getId().startsWith("render_")) { componentsIds += renderer.getId().length() > 0 ? renderer.getId() + "," : ""; } result.append(newLine); result.append(renderer.render(context)); } } } if (componentsIds.length() > 0) { result.append(newLine + "Dashboards.addComponents([" + componentsIds.replaceAll(",$", "]") + ");"); } result.append(newLine); result.append("</script>"); result.append(newLine); result.append(widgetContent); return result.toString(); }
diff --git a/annis-visualizers/src/main/java/annis/visualizers/component/grid/GridComponent.java b/annis-visualizers/src/main/java/annis/visualizers/component/grid/GridComponent.java index c0a098308..8dfdbfaf3 100644 --- a/annis-visualizers/src/main/java/annis/visualizers/component/grid/GridComponent.java +++ b/annis-visualizers/src/main/java/annis/visualizers/component/grid/GridComponent.java @@ -1,399 +1,400 @@ /* * Copyright 2014 SFB 632. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package annis.visualizers.component.grid; import annis.CommonHelper; import annis.gui.widgets.grid.AnnotationGrid; import annis.gui.widgets.grid.GridEvent; import annis.gui.widgets.grid.Row; import annis.libgui.media.MediaController; import annis.libgui.media.PDFController; import annis.libgui.visualizers.VisualizerInput; import annis.model.AnnisConstants; import annis.model.RelannisNodeFeature; import com.vaadin.ui.Panel; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.themes.ChameleonTheme; import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SDocumentGraph; import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SSpan; import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.STextualDS; import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SToken; import de.hu_berlin.german.korpling.saltnpepper.salt.saltCore.SAnnotation; import de.hu_berlin.german.korpling.saltnpepper.salt.saltCore.SNode; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Pattern; import org.eclipse.emf.common.util.EList; import org.slf4j.LoggerFactory; /** * * @author Thomas Krause <[email protected]> */ public class GridComponent extends Panel { private static final org.slf4j.Logger log = LoggerFactory.getLogger(GridComponent.class); public static final String MAPPING_ANNOS_KEY = "annos"; public static final String MAPPING_ANNO_REGEX_KEY = "anno_regex"; public static final String MAPPING_HIDE_TOK_KEY = "hide_tok"; public static final String MAPPING_TOK_ANNOS_KEY = "tok_anno"; public static final String MAPPING_ESCAPE_HTML = "escape_html"; private AnnotationGrid grid; private final transient VisualizerInput input; private final transient MediaController mediaController; private final transient PDFController pdfController; private final VerticalLayout layout; private Set<String> manuallySelectedTokenAnnos; private String segmentationName; private transient Map<SNode, Long> markedAndCovered = new HashMap<SNode, Long>(); private transient STextualDS enforcedText; public enum ElementType { begin, end, middle, single, noEvent } public GridComponent(VisualizerInput input, MediaController mediaController, PDFController pdfController, boolean forceToken, STextualDS enforcedText) { this.input = input; this.mediaController = mediaController; this.pdfController = pdfController; this.enforcedText = enforcedText; setWidth("100%"); setHeight("-1"); layout = new VerticalLayout(); setContent(layout); layout.setSizeUndefined(); addStyleName(ChameleonTheme.PANEL_BORDERLESS); if (input != null) { this.manuallySelectedTokenAnnos = input.getVisibleTokenAnnos(); this.segmentationName = forceToken ? null : input.getSegmentationName(); this.markedAndCovered = input.getMarkedAndCovered(); EList<STextualDS> texts = input.getDocument().getSDocumentGraph().getSTextualDSs(); if (texts != null && texts.size() > 0) { if (CommonHelper.containsRTLText(texts.get(0).getSText())) { addStyleName("rtl"); } } createAnnotationGrid(); } // end if input not null } private void createAnnotationGrid() { String resultID = input.getId(); grid = new AnnotationGrid(mediaController, pdfController, resultID); grid.addStyleName(getMainStyle()); grid.addStyleName("corpus-font-force"); grid.setEscapeHTML(Boolean.parseBoolean(input.getMappings(). getProperty(MAPPING_ESCAPE_HTML, "true"))); layout.addComponent(grid); SDocumentGraph graph = input.getDocument().getSDocumentGraph(); List<SNode> tokens = CommonHelper.getSortedSegmentationNodes(segmentationName, graph); RelannisNodeFeature featTokStart = (RelannisNodeFeature) tokens.get(0). getSFeature(AnnisConstants.ANNIS_NS, AnnisConstants.FEAT_RELANNIS_NODE). getValue(); long startIndex = featTokStart.getTokenIndex(); RelannisNodeFeature featTokEnd = (RelannisNodeFeature) tokens.get(tokens.size() - 1). getSFeature(AnnisConstants.ANNIS_NS, AnnisConstants.FEAT_RELANNIS_NODE). getValue(); long endIndex = featTokEnd.getTokenIndex(); LinkedHashMap<String, ArrayList<Row>> rowsByAnnotation = computeAnnotationRows(startIndex, endIndex); // add tokens as row AtomicInteger tokenOffsetForText = new AtomicInteger(-1); ArrayList<Row> tokenRowList = computeTokenRow(tokens, graph, rowsByAnnotation, startIndex, tokenOffsetForText); if (isHidingToken() == false) { if(isTokenFirst()) { // copy original list but add token row at the beginning LinkedHashMap<String, ArrayList<Row>> newList = new LinkedHashMap<String, ArrayList<Row>>(); newList.put("tok", tokenRowList); newList.putAll(rowsByAnnotation); rowsByAnnotation = newList; } else { // just add the token row to the end of the list rowsByAnnotation.put("tok", tokenRowList); } } EventExtractor.removeEmptySpace(rowsByAnnotation); grid.setRowsByAnnotation(rowsByAnnotation); grid.setTokenIndexOffset(tokenOffsetForText.get()); } private ArrayList<Row> computeTokenRow(List<SNode> tokens, SDocumentGraph graph, LinkedHashMap<String, ArrayList<Row>> rowsByAnnotation, long startIndex, AtomicInteger tokenOffsetForText) { /* we will only add tokens of one texts which is mentioned by any included annotation. */ Set<String> validTextIDs = new HashSet<String>(); if(enforcedText == null) { Iterator<ArrayList<Row>> itAllRows = rowsByAnnotation.values().iterator(); while (itAllRows.hasNext()) { ArrayList<Row> rowsForAnnotation = itAllRows.next(); for (Row r : rowsForAnnotation) { validTextIDs.addAll(r.getTextIDs()); } } /** * we want to show all token if no valid text was found and we have only one * text and the first one if there are more than one text. */ EList<STextualDS> allTexts = graph.getSTextualDSs(); if (validTextIDs.isEmpty() && allTexts != null && (allTexts.size() == 1 || allTexts.size() == 2)) { validTextIDs.add(allTexts.get(0).getSId()); } } else { validTextIDs.add(enforcedText.getSId()); } Row tokenRow = new Row(); for (SNode t : tokens) { // get the Salt ID of the STextualDS of this token STextualDS tokenText = CommonHelper.getTextualDSForNode(t, graph); // only add token if text ID matches the valid one if (tokenText != null && validTextIDs.contains(tokenText.getSId())) { RelannisNodeFeature feat = (RelannisNodeFeature) t.getSFeature(AnnisConstants.ANNIS_NS, AnnisConstants.FEAT_RELANNIS_NODE).getValue(); - long idx = feat.getLeftToken() - startIndex; + long idxLeft = feat.getLeftToken() - startIndex; + long idxRight = feat.getRightToken() - startIndex; if (tokenOffsetForText.get() < 0) { // set the token offset by assuming the first idx must be zero - tokenOffsetForText.set(Math.abs((int) idx)); + tokenOffsetForText.set(Math.abs((int) idxLeft)); } String text = extractTextForToken(t, segmentationName); GridEvent event - = new GridEvent(t.getSId(), (int) idx, (int) idx, text); + = new GridEvent(t.getSId(), (int) idxLeft, (int) idxRight, text); event.setTextID(tokenText.getSId()); // check if the token is a matched node Long match = markCoveredTokens(markedAndCovered, t); event.setMatch(match); tokenRow.addEvent(event); } } // end token row ArrayList<Row> tokenRowList = new ArrayList<Row>(); tokenRowList.add(tokenRow); return tokenRowList; } private String extractTextForToken(SNode t, String segmentation) { if(t instanceof SToken) { return CommonHelper.getSpannedText((SToken) t); } else if(segmentation != null) { for(SAnnotation anno : t.getSAnnotations()) { if(anno.getSName().equals(segmentation)) { return anno.getSValueSTEXT(); } } } return ""; } private LinkedHashMap<String, ArrayList<Row>> computeAnnotationRows( long startIndex, long endIndex) { List<String> annos = new LinkedList<String>(); boolean showSpanAnnotations = isShowingSpanAnnotations(); if(showSpanAnnotations) { annos.addAll(EventExtractor.computeDisplayAnnotations(input, SSpan.class)); } boolean showTokenAnnotations = isShowingTokenAnnotations(); if (showTokenAnnotations) { List<String> tokenAnnos = EventExtractor.computeDisplayAnnotations(input, SToken.class); if(manuallySelectedTokenAnnos != null) { tokenAnnos.retainAll(manuallySelectedTokenAnnos); } annos.addAll(tokenAnnos); } // search for media annotations Set<String> mediaAnnotations = null; if(isFilteringMediaLayer()) { mediaAnnotations = new HashSet<String>(); Pattern patternMedia = Pattern.compile("(annis::)?time"); for (String qname : annos) { if(patternMedia.matcher(qname).matches()) { mediaAnnotations.add(qname); } } } LinkedHashMap<String, ArrayList<Row>> rowsByAnnotation = EventExtractor.parseSalt(input, showSpanAnnotations, showTokenAnnotations, annos, mediaAnnotations, isUnsettingValueForMedia(), (int) startIndex, (int) endIndex, pdfController, enforcedText); return rowsByAnnotation; } public void setVisibleTokenAnnos(Set<String> annos) { this.manuallySelectedTokenAnnos = annos; // complete recreation of the grid layout.removeComponent(grid); createAnnotationGrid(); } public void setSegmentationLayer(String segmentationName, Map<SNode, Long> markedAndCovered) { this.segmentationName = segmentationName; this.markedAndCovered = markedAndCovered; // complete recreation of the grid layout.removeComponent(grid); createAnnotationGrid(); } protected boolean isShowingTokenAnnotations() { return Boolean.parseBoolean(input.getMappings(). getProperty(MAPPING_TOK_ANNOS_KEY)); } protected boolean isShowingSpanAnnotations() { return true; } protected boolean isHidingToken() { return Boolean.parseBoolean(input.getMappings(). getProperty(MAPPING_HIDE_TOK_KEY, "false")); } protected boolean isTokenFirst() { return false; } protected boolean isFilteringMediaLayer() { return false; } protected boolean isUnsettingValueForMedia() { return false; } protected String getMainStyle() { return "partitur_table"; } /** * Checks if a token is covered by a matched node but not a match by it self. * * @param markedAndCovered A mapping from node to a matched number. The node * must not matched directly, but covered by a matched node. * @param tok the checked token. * @return Returns null, if token is not covered neither marked. */ private Long markCoveredTokens(Map<SNode, Long> markedAndCovered, SNode tok) { RelannisNodeFeature f = RelannisNodeFeature.extract(tok); if (markedAndCovered.containsKey(tok) && f != null && f.getMatchedNode() == null) { return markedAndCovered.get(tok); } return f != null ? f.getMatchedNode() : null; } public VisualizerInput getInput() { return input; } public AnnotationGrid getGrid() { return grid; } } // end GridVisualizerComponent
false
true
private ArrayList<Row> computeTokenRow(List<SNode> tokens, SDocumentGraph graph, LinkedHashMap<String, ArrayList<Row>> rowsByAnnotation, long startIndex, AtomicInteger tokenOffsetForText) { /* we will only add tokens of one texts which is mentioned by any included annotation. */ Set<String> validTextIDs = new HashSet<String>(); if(enforcedText == null) { Iterator<ArrayList<Row>> itAllRows = rowsByAnnotation.values().iterator(); while (itAllRows.hasNext()) { ArrayList<Row> rowsForAnnotation = itAllRows.next(); for (Row r : rowsForAnnotation) { validTextIDs.addAll(r.getTextIDs()); } } /** * we want to show all token if no valid text was found and we have only one * text and the first one if there are more than one text. */ EList<STextualDS> allTexts = graph.getSTextualDSs(); if (validTextIDs.isEmpty() && allTexts != null && (allTexts.size() == 1 || allTexts.size() == 2)) { validTextIDs.add(allTexts.get(0).getSId()); } } else { validTextIDs.add(enforcedText.getSId()); } Row tokenRow = new Row(); for (SNode t : tokens) { // get the Salt ID of the STextualDS of this token STextualDS tokenText = CommonHelper.getTextualDSForNode(t, graph); // only add token if text ID matches the valid one if (tokenText != null && validTextIDs.contains(tokenText.getSId())) { RelannisNodeFeature feat = (RelannisNodeFeature) t.getSFeature(AnnisConstants.ANNIS_NS, AnnisConstants.FEAT_RELANNIS_NODE).getValue(); long idx = feat.getLeftToken() - startIndex; if (tokenOffsetForText.get() < 0) { // set the token offset by assuming the first idx must be zero tokenOffsetForText.set(Math.abs((int) idx)); } String text = extractTextForToken(t, segmentationName); GridEvent event = new GridEvent(t.getSId(), (int) idx, (int) idx, text); event.setTextID(tokenText.getSId()); // check if the token is a matched node Long match = markCoveredTokens(markedAndCovered, t); event.setMatch(match); tokenRow.addEvent(event); } } // end token row ArrayList<Row> tokenRowList = new ArrayList<Row>(); tokenRowList.add(tokenRow); return tokenRowList; }
private ArrayList<Row> computeTokenRow(List<SNode> tokens, SDocumentGraph graph, LinkedHashMap<String, ArrayList<Row>> rowsByAnnotation, long startIndex, AtomicInteger tokenOffsetForText) { /* we will only add tokens of one texts which is mentioned by any included annotation. */ Set<String> validTextIDs = new HashSet<String>(); if(enforcedText == null) { Iterator<ArrayList<Row>> itAllRows = rowsByAnnotation.values().iterator(); while (itAllRows.hasNext()) { ArrayList<Row> rowsForAnnotation = itAllRows.next(); for (Row r : rowsForAnnotation) { validTextIDs.addAll(r.getTextIDs()); } } /** * we want to show all token if no valid text was found and we have only one * text and the first one if there are more than one text. */ EList<STextualDS> allTexts = graph.getSTextualDSs(); if (validTextIDs.isEmpty() && allTexts != null && (allTexts.size() == 1 || allTexts.size() == 2)) { validTextIDs.add(allTexts.get(0).getSId()); } } else { validTextIDs.add(enforcedText.getSId()); } Row tokenRow = new Row(); for (SNode t : tokens) { // get the Salt ID of the STextualDS of this token STextualDS tokenText = CommonHelper.getTextualDSForNode(t, graph); // only add token if text ID matches the valid one if (tokenText != null && validTextIDs.contains(tokenText.getSId())) { RelannisNodeFeature feat = (RelannisNodeFeature) t.getSFeature(AnnisConstants.ANNIS_NS, AnnisConstants.FEAT_RELANNIS_NODE).getValue(); long idxLeft = feat.getLeftToken() - startIndex; long idxRight = feat.getRightToken() - startIndex; if (tokenOffsetForText.get() < 0) { // set the token offset by assuming the first idx must be zero tokenOffsetForText.set(Math.abs((int) idxLeft)); } String text = extractTextForToken(t, segmentationName); GridEvent event = new GridEvent(t.getSId(), (int) idxLeft, (int) idxRight, text); event.setTextID(tokenText.getSId()); // check if the token is a matched node Long match = markCoveredTokens(markedAndCovered, t); event.setMatch(match); tokenRow.addEvent(event); } } // end token row ArrayList<Row> tokenRowList = new ArrayList<Row>(); tokenRowList.add(tokenRow); return tokenRowList; }
diff --git a/common/com/github/soniex2/endermoney/trading/tileentity/TileEntityCreativeItemTrader.java b/common/com/github/soniex2/endermoney/trading/tileentity/TileEntityCreativeItemTrader.java index bd66af8..50f2876 100644 --- a/common/com/github/soniex2/endermoney/trading/tileentity/TileEntityCreativeItemTrader.java +++ b/common/com/github/soniex2/endermoney/trading/tileentity/TileEntityCreativeItemTrader.java @@ -1,240 +1,244 @@ package com.github.soniex2.endermoney.trading.tileentity; import java.math.BigInteger; import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; import java.util.Set; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import com.github.soniex2.endermoney.core.EnderCoin; import com.github.soniex2.endermoney.core.EnderMoney; import com.github.soniex2.endermoney.trading.TradeError; import com.github.soniex2.endermoney.trading.base.AbstractTraderTileEntity; import com.github.soniex2.endermoney.trading.helper.item.ItemStackMapKey; public class TileEntityCreativeItemTrader extends AbstractTraderTileEntity { public TileEntityCreativeItemTrader() { super(18); } public ItemStack[] getTradeInputs() { ItemStack[] tradeInputs = new ItemStack[9]; for (int i = 0; i < 9; i++) { tradeInputs[i] = ItemStack.copyItemStack(inv[i]); } return tradeInputs; } public ItemStack[] getTradeOutputs() { ItemStack[] tradeOutputs = new ItemStack[9]; for (int i = 0; i < 9; i++) { tradeOutputs[i] = ItemStack.copyItemStack(inv[i + 9]); } return tradeOutputs; } public boolean doTrade(IInventory fakeInv, int inputMinSlot, int inputMaxSlot, int outputMinSlot, int outputMaxSlot) throws TradeError { if (fakeInv == null) { throw new TradeError(1, "Invalid inventory", new NullPointerException()); } HashMap<ItemStackMapKey, Integer> tradeInputs = new HashMap<ItemStackMapKey, Integer>(); BigInteger moneyRequired = BigInteger.ZERO; for (ItemStack i : getTradeInputs()) { if (i == null) { continue; } if (i.getItem() == EnderMoney.coin) { moneyRequired = moneyRequired.add(BigInteger.valueOf( EnderCoin.getValueFromItemStack(i)).multiply( BigInteger.valueOf(i.stackSize))); continue; } ItemStackMapKey index = new ItemStackMapKey(i); if (tradeInputs.containsKey(index)) { tradeInputs.put(index, i.stackSize + tradeInputs.get(index)); } else { tradeInputs.put(index, i.stackSize); } } HashMap<ItemStackMapKey, Integer> tradeInput = new HashMap<ItemStackMapKey, Integer>(); BigInteger money = BigInteger.ZERO; for (int i = inputMinSlot; i <= inputMaxSlot; i++) { ItemStack is = fakeInv.getStackInSlot(i); if (is == null) { continue; } if (is.getItem() == EnderMoney.coin) { money = money.add(BigInteger.valueOf(EnderCoin.getValueFromItemStack(is)).multiply( BigInteger.valueOf(is.stackSize))); continue; } ItemStackMapKey index = new ItemStackMapKey(is); if (tradeInput.containsKey(index)) { tradeInput.put(index, is.stackSize + tradeInput.get(index)); } else { tradeInput.put(index, is.stackSize); } } if (money.compareTo(moneyRequired) < 0) { return false; } BigInteger newMoney = money.subtract(moneyRequired); Set<Entry<ItemStackMapKey, Integer>> itemsRequired = tradeInputs.entrySet(); Iterator<Entry<ItemStackMapKey, Integer>> i = itemsRequired.iterator(); HashMap<ItemStackMapKey, Integer> newInput = new HashMap<ItemStackMapKey, Integer>(); while (i.hasNext()) { Entry<ItemStackMapKey, Integer> entry = i.next(); ItemStackMapKey item = entry.getKey(); Integer amount = entry.getValue(); Integer available = tradeInput.get(item); if (available == null) { return false; } if (available < amount) { return false; } if (available - amount == 0) { continue; } newInput.put(item, available - amount); } if (newMoney.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) { BigInteger[] coinCount = newMoney .divideAndRemainder(BigInteger.valueOf(Long.MAX_VALUE)); int a = coinCount[0].intValue(); long b = coinCount[1].longValue(); ItemStack is1 = ((EnderCoin) EnderMoney.coin).getItemStack(Long.MAX_VALUE, 1); ItemStack is2 = ((EnderCoin) EnderMoney.coin).getItemStack(b, 1); ItemStackMapKey index1 = new ItemStackMapKey(is1); ItemStackMapKey index2 = new ItemStackMapKey(is2); newInput.put(index1, a); newInput.put(index2, 1); + } else if (!newMoney.equals(BigInteger.ZERO)) { + ItemStack is = ((EnderCoin) EnderMoney.coin).getItemStack(newMoney.longValue(), 1); + ItemStackMapKey index = new ItemStackMapKey(is); + newInput.put(index, 1); } ItemStack[] tradeOutputs = getTradeOutputs(); // TODO put commented out code below somewhere else /* * int[] something = new int[tradeOutputs.length]; * int[][] lookAt = new int[][] { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 }, * { -1, 0, 0 }, * { 0, -1, 0 }, { 0, 0, -1 } }; * for (int a = 0; a < lookAt.length; a++) { * TileEntity tileEntity = this.worldObj.getBlockTileEntity(this.xCoord * + lookAt[a][0], * this.yCoord + lookAt[a][1], this.zCoord + lookAt[a][2]); * if (tileEntity == null) continue; * if (tileEntity instanceof IInventory) { * IInventory iinv = (IInventory) tileEntity; * for (int b = 0; b < iinv.getSizeInventory(); b++) { * ItemStack is = iinv.getStackInSlot(b); * if (is == null) continue; * for (int c = 0; c < tradeOutputs.length; c++) { * if (tradeOutputs[c] == null) continue; * if (tradeOutputs[c].isItemEqual(is) && * ItemStack.areItemStackTagsEqual(tradeOutputs[c], is)) { * something[c] += is.stackSize; * } * } * } * } * } */ ItemStack[] oldOutInv = new ItemStack[outputMaxSlot - outputMinSlot + 1]; for (int a = outputMinSlot; a <= outputMaxSlot; a++) { oldOutInv[a - outputMinSlot] = ItemStack.copyItemStack(fakeInv.getStackInSlot(a)); } for (int a = outputMinSlot; a <= outputMaxSlot; a++) { ItemStack is = fakeInv.getStackInSlot(a); for (int b = 0; b < tradeOutputs.length; b++) { if (is != null && tradeOutputs[b] != null && is.isItemEqual(tradeOutputs[b]) && ItemStack.areItemStackTagsEqual(is, tradeOutputs[b])) { if (is.isStackable()) { if (is.stackSize < is.getMaxStackSize()) { if (is.stackSize + tradeOutputs[b].stackSize > is.getMaxStackSize()) { int newStackSize = tradeOutputs[b].stackSize + is.stackSize; if (newStackSize > is.getMaxStackSize()) { newStackSize = newStackSize - is.getMaxStackSize(); } tradeOutputs[b].stackSize = newStackSize; is.stackSize = is.getMaxStackSize(); } else { is.stackSize = is.stackSize + tradeOutputs[b].stackSize; tradeOutputs[b] = null; } } } } else if (is == null && tradeOutputs[b] != null) { fakeInv.setInventorySlotContents(a, tradeOutputs[b]); is = fakeInv.getStackInSlot(a); tradeOutputs[b] = null; } if (tradeOutputs[b] != null && tradeOutputs[b].stackSize <= 0) { tradeOutputs[b] = null; } } } for (int a = 0; a < tradeOutputs.length; a++) { if (tradeOutputs[a] != null) { for (int b = 0; b < oldOutInv.length; b++) { fakeInv.setInventorySlotContents(b + outputMinSlot, oldOutInv[b]); } throw new TradeError(0, "Couldn't complete trade: Out of inventory space"); } } for (int _i = inputMinSlot; _i < inputMaxSlot; _i++) { fakeInv.setInventorySlotContents(_i, null); } Set<Entry<ItemStackMapKey, Integer>> input = newInput.entrySet(); Iterator<Entry<ItemStackMapKey, Integer>> it = input.iterator(); int slot = inputMinSlot; while (it.hasNext()) { if (slot >= inputMaxSlot) { throw new TradeError(0, "Couldn't complete trade: Out of inventory space"); } if (fakeInv.getStackInSlot(slot) != null) { slot++; continue; } Entry<ItemStackMapKey, Integer> entry = it.next(); ItemStackMapKey itemData = entry.getKey(); ItemStack item = new ItemStack(itemData.itemID, 1, itemData.damage); item.stackTagCompound = (NBTTagCompound) itemData.getTag(); Integer amount = entry.getValue(); if (amount == 0) { // shouldn't happen but who knows... continue; } int stacks = amount / item.getMaxStackSize(); int extra = amount % item.getMaxStackSize(); ItemStack newItem = item.copy(); newItem.stackSize = item.getMaxStackSize(); for (int n = slot; n < slot + stacks; n++) { fakeInv.setInventorySlotContents(n, newItem); } slot += stacks; newItem = item.copy(); newItem.stackSize = extra; fakeInv.setInventorySlotContents(slot, newItem); slot++; } return true; } @Override public String getInvName() { return "endermoney.traders.item"; } @Override public boolean isInvNameLocalized() { return false; } @Override public void openChest() { } @Override public void closeChest() { } }
true
true
public boolean doTrade(IInventory fakeInv, int inputMinSlot, int inputMaxSlot, int outputMinSlot, int outputMaxSlot) throws TradeError { if (fakeInv == null) { throw new TradeError(1, "Invalid inventory", new NullPointerException()); } HashMap<ItemStackMapKey, Integer> tradeInputs = new HashMap<ItemStackMapKey, Integer>(); BigInteger moneyRequired = BigInteger.ZERO; for (ItemStack i : getTradeInputs()) { if (i == null) { continue; } if (i.getItem() == EnderMoney.coin) { moneyRequired = moneyRequired.add(BigInteger.valueOf( EnderCoin.getValueFromItemStack(i)).multiply( BigInteger.valueOf(i.stackSize))); continue; } ItemStackMapKey index = new ItemStackMapKey(i); if (tradeInputs.containsKey(index)) { tradeInputs.put(index, i.stackSize + tradeInputs.get(index)); } else { tradeInputs.put(index, i.stackSize); } } HashMap<ItemStackMapKey, Integer> tradeInput = new HashMap<ItemStackMapKey, Integer>(); BigInteger money = BigInteger.ZERO; for (int i = inputMinSlot; i <= inputMaxSlot; i++) { ItemStack is = fakeInv.getStackInSlot(i); if (is == null) { continue; } if (is.getItem() == EnderMoney.coin) { money = money.add(BigInteger.valueOf(EnderCoin.getValueFromItemStack(is)).multiply( BigInteger.valueOf(is.stackSize))); continue; } ItemStackMapKey index = new ItemStackMapKey(is); if (tradeInput.containsKey(index)) { tradeInput.put(index, is.stackSize + tradeInput.get(index)); } else { tradeInput.put(index, is.stackSize); } } if (money.compareTo(moneyRequired) < 0) { return false; } BigInteger newMoney = money.subtract(moneyRequired); Set<Entry<ItemStackMapKey, Integer>> itemsRequired = tradeInputs.entrySet(); Iterator<Entry<ItemStackMapKey, Integer>> i = itemsRequired.iterator(); HashMap<ItemStackMapKey, Integer> newInput = new HashMap<ItemStackMapKey, Integer>(); while (i.hasNext()) { Entry<ItemStackMapKey, Integer> entry = i.next(); ItemStackMapKey item = entry.getKey(); Integer amount = entry.getValue(); Integer available = tradeInput.get(item); if (available == null) { return false; } if (available < amount) { return false; } if (available - amount == 0) { continue; } newInput.put(item, available - amount); } if (newMoney.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) { BigInteger[] coinCount = newMoney .divideAndRemainder(BigInteger.valueOf(Long.MAX_VALUE)); int a = coinCount[0].intValue(); long b = coinCount[1].longValue(); ItemStack is1 = ((EnderCoin) EnderMoney.coin).getItemStack(Long.MAX_VALUE, 1); ItemStack is2 = ((EnderCoin) EnderMoney.coin).getItemStack(b, 1); ItemStackMapKey index1 = new ItemStackMapKey(is1); ItemStackMapKey index2 = new ItemStackMapKey(is2); newInput.put(index1, a); newInput.put(index2, 1); } ItemStack[] tradeOutputs = getTradeOutputs(); // TODO put commented out code below somewhere else /* * int[] something = new int[tradeOutputs.length]; * int[][] lookAt = new int[][] { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 }, * { -1, 0, 0 }, * { 0, -1, 0 }, { 0, 0, -1 } }; * for (int a = 0; a < lookAt.length; a++) { * TileEntity tileEntity = this.worldObj.getBlockTileEntity(this.xCoord * + lookAt[a][0], * this.yCoord + lookAt[a][1], this.zCoord + lookAt[a][2]); * if (tileEntity == null) continue; * if (tileEntity instanceof IInventory) { * IInventory iinv = (IInventory) tileEntity; * for (int b = 0; b < iinv.getSizeInventory(); b++) { * ItemStack is = iinv.getStackInSlot(b); * if (is == null) continue; * for (int c = 0; c < tradeOutputs.length; c++) { * if (tradeOutputs[c] == null) continue; * if (tradeOutputs[c].isItemEqual(is) && * ItemStack.areItemStackTagsEqual(tradeOutputs[c], is)) { * something[c] += is.stackSize; * } * } * } * } * } */ ItemStack[] oldOutInv = new ItemStack[outputMaxSlot - outputMinSlot + 1]; for (int a = outputMinSlot; a <= outputMaxSlot; a++) { oldOutInv[a - outputMinSlot] = ItemStack.copyItemStack(fakeInv.getStackInSlot(a)); } for (int a = outputMinSlot; a <= outputMaxSlot; a++) { ItemStack is = fakeInv.getStackInSlot(a); for (int b = 0; b < tradeOutputs.length; b++) { if (is != null && tradeOutputs[b] != null && is.isItemEqual(tradeOutputs[b]) && ItemStack.areItemStackTagsEqual(is, tradeOutputs[b])) { if (is.isStackable()) { if (is.stackSize < is.getMaxStackSize()) { if (is.stackSize + tradeOutputs[b].stackSize > is.getMaxStackSize()) { int newStackSize = tradeOutputs[b].stackSize + is.stackSize; if (newStackSize > is.getMaxStackSize()) { newStackSize = newStackSize - is.getMaxStackSize(); } tradeOutputs[b].stackSize = newStackSize; is.stackSize = is.getMaxStackSize(); } else { is.stackSize = is.stackSize + tradeOutputs[b].stackSize; tradeOutputs[b] = null; } } } } else if (is == null && tradeOutputs[b] != null) { fakeInv.setInventorySlotContents(a, tradeOutputs[b]); is = fakeInv.getStackInSlot(a); tradeOutputs[b] = null; } if (tradeOutputs[b] != null && tradeOutputs[b].stackSize <= 0) { tradeOutputs[b] = null; } } } for (int a = 0; a < tradeOutputs.length; a++) { if (tradeOutputs[a] != null) { for (int b = 0; b < oldOutInv.length; b++) { fakeInv.setInventorySlotContents(b + outputMinSlot, oldOutInv[b]); } throw new TradeError(0, "Couldn't complete trade: Out of inventory space"); } } for (int _i = inputMinSlot; _i < inputMaxSlot; _i++) { fakeInv.setInventorySlotContents(_i, null); } Set<Entry<ItemStackMapKey, Integer>> input = newInput.entrySet(); Iterator<Entry<ItemStackMapKey, Integer>> it = input.iterator(); int slot = inputMinSlot; while (it.hasNext()) { if (slot >= inputMaxSlot) { throw new TradeError(0, "Couldn't complete trade: Out of inventory space"); } if (fakeInv.getStackInSlot(slot) != null) { slot++; continue; } Entry<ItemStackMapKey, Integer> entry = it.next(); ItemStackMapKey itemData = entry.getKey(); ItemStack item = new ItemStack(itemData.itemID, 1, itemData.damage); item.stackTagCompound = (NBTTagCompound) itemData.getTag(); Integer amount = entry.getValue(); if (amount == 0) { // shouldn't happen but who knows... continue; } int stacks = amount / item.getMaxStackSize(); int extra = amount % item.getMaxStackSize(); ItemStack newItem = item.copy(); newItem.stackSize = item.getMaxStackSize(); for (int n = slot; n < slot + stacks; n++) { fakeInv.setInventorySlotContents(n, newItem); } slot += stacks; newItem = item.copy(); newItem.stackSize = extra; fakeInv.setInventorySlotContents(slot, newItem); slot++; } return true; }
public boolean doTrade(IInventory fakeInv, int inputMinSlot, int inputMaxSlot, int outputMinSlot, int outputMaxSlot) throws TradeError { if (fakeInv == null) { throw new TradeError(1, "Invalid inventory", new NullPointerException()); } HashMap<ItemStackMapKey, Integer> tradeInputs = new HashMap<ItemStackMapKey, Integer>(); BigInteger moneyRequired = BigInteger.ZERO; for (ItemStack i : getTradeInputs()) { if (i == null) { continue; } if (i.getItem() == EnderMoney.coin) { moneyRequired = moneyRequired.add(BigInteger.valueOf( EnderCoin.getValueFromItemStack(i)).multiply( BigInteger.valueOf(i.stackSize))); continue; } ItemStackMapKey index = new ItemStackMapKey(i); if (tradeInputs.containsKey(index)) { tradeInputs.put(index, i.stackSize + tradeInputs.get(index)); } else { tradeInputs.put(index, i.stackSize); } } HashMap<ItemStackMapKey, Integer> tradeInput = new HashMap<ItemStackMapKey, Integer>(); BigInteger money = BigInteger.ZERO; for (int i = inputMinSlot; i <= inputMaxSlot; i++) { ItemStack is = fakeInv.getStackInSlot(i); if (is == null) { continue; } if (is.getItem() == EnderMoney.coin) { money = money.add(BigInteger.valueOf(EnderCoin.getValueFromItemStack(is)).multiply( BigInteger.valueOf(is.stackSize))); continue; } ItemStackMapKey index = new ItemStackMapKey(is); if (tradeInput.containsKey(index)) { tradeInput.put(index, is.stackSize + tradeInput.get(index)); } else { tradeInput.put(index, is.stackSize); } } if (money.compareTo(moneyRequired) < 0) { return false; } BigInteger newMoney = money.subtract(moneyRequired); Set<Entry<ItemStackMapKey, Integer>> itemsRequired = tradeInputs.entrySet(); Iterator<Entry<ItemStackMapKey, Integer>> i = itemsRequired.iterator(); HashMap<ItemStackMapKey, Integer> newInput = new HashMap<ItemStackMapKey, Integer>(); while (i.hasNext()) { Entry<ItemStackMapKey, Integer> entry = i.next(); ItemStackMapKey item = entry.getKey(); Integer amount = entry.getValue(); Integer available = tradeInput.get(item); if (available == null) { return false; } if (available < amount) { return false; } if (available - amount == 0) { continue; } newInput.put(item, available - amount); } if (newMoney.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) { BigInteger[] coinCount = newMoney .divideAndRemainder(BigInteger.valueOf(Long.MAX_VALUE)); int a = coinCount[0].intValue(); long b = coinCount[1].longValue(); ItemStack is1 = ((EnderCoin) EnderMoney.coin).getItemStack(Long.MAX_VALUE, 1); ItemStack is2 = ((EnderCoin) EnderMoney.coin).getItemStack(b, 1); ItemStackMapKey index1 = new ItemStackMapKey(is1); ItemStackMapKey index2 = new ItemStackMapKey(is2); newInput.put(index1, a); newInput.put(index2, 1); } else if (!newMoney.equals(BigInteger.ZERO)) { ItemStack is = ((EnderCoin) EnderMoney.coin).getItemStack(newMoney.longValue(), 1); ItemStackMapKey index = new ItemStackMapKey(is); newInput.put(index, 1); } ItemStack[] tradeOutputs = getTradeOutputs(); // TODO put commented out code below somewhere else /* * int[] something = new int[tradeOutputs.length]; * int[][] lookAt = new int[][] { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 }, * { -1, 0, 0 }, * { 0, -1, 0 }, { 0, 0, -1 } }; * for (int a = 0; a < lookAt.length; a++) { * TileEntity tileEntity = this.worldObj.getBlockTileEntity(this.xCoord * + lookAt[a][0], * this.yCoord + lookAt[a][1], this.zCoord + lookAt[a][2]); * if (tileEntity == null) continue; * if (tileEntity instanceof IInventory) { * IInventory iinv = (IInventory) tileEntity; * for (int b = 0; b < iinv.getSizeInventory(); b++) { * ItemStack is = iinv.getStackInSlot(b); * if (is == null) continue; * for (int c = 0; c < tradeOutputs.length; c++) { * if (tradeOutputs[c] == null) continue; * if (tradeOutputs[c].isItemEqual(is) && * ItemStack.areItemStackTagsEqual(tradeOutputs[c], is)) { * something[c] += is.stackSize; * } * } * } * } * } */ ItemStack[] oldOutInv = new ItemStack[outputMaxSlot - outputMinSlot + 1]; for (int a = outputMinSlot; a <= outputMaxSlot; a++) { oldOutInv[a - outputMinSlot] = ItemStack.copyItemStack(fakeInv.getStackInSlot(a)); } for (int a = outputMinSlot; a <= outputMaxSlot; a++) { ItemStack is = fakeInv.getStackInSlot(a); for (int b = 0; b < tradeOutputs.length; b++) { if (is != null && tradeOutputs[b] != null && is.isItemEqual(tradeOutputs[b]) && ItemStack.areItemStackTagsEqual(is, tradeOutputs[b])) { if (is.isStackable()) { if (is.stackSize < is.getMaxStackSize()) { if (is.stackSize + tradeOutputs[b].stackSize > is.getMaxStackSize()) { int newStackSize = tradeOutputs[b].stackSize + is.stackSize; if (newStackSize > is.getMaxStackSize()) { newStackSize = newStackSize - is.getMaxStackSize(); } tradeOutputs[b].stackSize = newStackSize; is.stackSize = is.getMaxStackSize(); } else { is.stackSize = is.stackSize + tradeOutputs[b].stackSize; tradeOutputs[b] = null; } } } } else if (is == null && tradeOutputs[b] != null) { fakeInv.setInventorySlotContents(a, tradeOutputs[b]); is = fakeInv.getStackInSlot(a); tradeOutputs[b] = null; } if (tradeOutputs[b] != null && tradeOutputs[b].stackSize <= 0) { tradeOutputs[b] = null; } } } for (int a = 0; a < tradeOutputs.length; a++) { if (tradeOutputs[a] != null) { for (int b = 0; b < oldOutInv.length; b++) { fakeInv.setInventorySlotContents(b + outputMinSlot, oldOutInv[b]); } throw new TradeError(0, "Couldn't complete trade: Out of inventory space"); } } for (int _i = inputMinSlot; _i < inputMaxSlot; _i++) { fakeInv.setInventorySlotContents(_i, null); } Set<Entry<ItemStackMapKey, Integer>> input = newInput.entrySet(); Iterator<Entry<ItemStackMapKey, Integer>> it = input.iterator(); int slot = inputMinSlot; while (it.hasNext()) { if (slot >= inputMaxSlot) { throw new TradeError(0, "Couldn't complete trade: Out of inventory space"); } if (fakeInv.getStackInSlot(slot) != null) { slot++; continue; } Entry<ItemStackMapKey, Integer> entry = it.next(); ItemStackMapKey itemData = entry.getKey(); ItemStack item = new ItemStack(itemData.itemID, 1, itemData.damage); item.stackTagCompound = (NBTTagCompound) itemData.getTag(); Integer amount = entry.getValue(); if (amount == 0) { // shouldn't happen but who knows... continue; } int stacks = amount / item.getMaxStackSize(); int extra = amount % item.getMaxStackSize(); ItemStack newItem = item.copy(); newItem.stackSize = item.getMaxStackSize(); for (int n = slot; n < slot + stacks; n++) { fakeInv.setInventorySlotContents(n, newItem); } slot += stacks; newItem = item.copy(); newItem.stackSize = extra; fakeInv.setInventorySlotContents(slot, newItem); slot++; } return true; }
diff --git a/app/models/Code.java b/app/models/Code.java index e442ebe..29a4b38 100755 --- a/app/models/Code.java +++ b/app/models/Code.java @@ -1,114 +1,114 @@ package models; import com.google.gson.Gson; import com.greenlaw110.rythm.Rythm; import com.greenlaw110.rythm.RythmEngine; import com.greenlaw110.rythm.extension.ICodeType; import com.greenlaw110.rythm.sandbox.RythmSecurityManager; import com.greenlaw110.rythm.sandbox.SandboxThreadFactory; import com.greenlaw110.rythm.utils.JSONWrapper; import com.greenlaw110.rythm.utils.S; import play.mvc.Scope; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import static common.Helper.eq; /** * User: freewind * Date: 13-3-18 * Time: 下午6:07 */ public class Code { public String id; public String desc; public String params; public List<CodeFile> files; public boolean showInMenu; public boolean isNew() { return S.empty(id); } private static final Object lock = new Object(); private static final Map<String, RythmEngine> engines = new HashMap<String, RythmEngine>(); private static final String sandboxPassword = UUID.randomUUID().toString(); private static final RythmSecurityManager rsm = new RythmSecurityManager(null, sandboxPassword, null); private static final SandboxThreadFactory stf = new SandboxThreadFactory(rsm, sandboxPassword, null); private RythmEngine engine() { String sessId = Scope.Session.current().getId(); synchronized (lock) { RythmEngine e = engines.get(sessId); if (null == e) { Map<String, Object> conf = new HashMap<String, Object>(); conf.put("resource.loader", new InMemoryResourceLoader(sessId)); conf.put("default.code_type", ICodeType.DefImpl.HTML); conf.put("engine.mode", Rythm.Mode.dev); conf.put("sandbox.security_manager", rsm); conf.put("sandbox.thread_factory", stf); - conf.put("log.source.java.enabled", false); - conf.put("log.source.template.enabled", false); + //conf.put("log.source.java.enabled", false); + //conf.put("log.source.template.enabled", false); e = new RythmEngine(conf); engines.put(sessId, e); } return e; } } public String render() throws IOException { CodeFile main = getMainCodeFile(); // FIXME? Is it correct to use a file? (which will make rythm use FileTemplateResource) Map<String, Object> context = new HashMap(); context.put("session-id", Scope.Session.current().getId()); RythmEngine rythm = engine(); if (S.notEmpty(params)) { return rythm.sandbox(context).render(main.getKey(), JSONWrapper.wrap(params)); } else { return rythm.sandbox(context).render(main.getKey()); } } public String toJson() { return new Gson().toJson(this); } public CodeFile getMainCodeFile() { for (CodeFile file : files) { if (file.isMain) { return file; } } return files.get(0); } public CodeFile findCodeFile(String path) { // find by fullname first for (CodeFile file : files) { if (eq(file.filename, path)) { return file; } } // find by prefix for (CodeFile file : files) { if (file.filename.startsWith(path + ".")) { return file; } } return null; } public void save(String sessionId) { for (CodeFile file : files) { file.save(sessionId); } } }
true
true
private RythmEngine engine() { String sessId = Scope.Session.current().getId(); synchronized (lock) { RythmEngine e = engines.get(sessId); if (null == e) { Map<String, Object> conf = new HashMap<String, Object>(); conf.put("resource.loader", new InMemoryResourceLoader(sessId)); conf.put("default.code_type", ICodeType.DefImpl.HTML); conf.put("engine.mode", Rythm.Mode.dev); conf.put("sandbox.security_manager", rsm); conf.put("sandbox.thread_factory", stf); conf.put("log.source.java.enabled", false); conf.put("log.source.template.enabled", false); e = new RythmEngine(conf); engines.put(sessId, e); } return e; } }
private RythmEngine engine() { String sessId = Scope.Session.current().getId(); synchronized (lock) { RythmEngine e = engines.get(sessId); if (null == e) { Map<String, Object> conf = new HashMap<String, Object>(); conf.put("resource.loader", new InMemoryResourceLoader(sessId)); conf.put("default.code_type", ICodeType.DefImpl.HTML); conf.put("engine.mode", Rythm.Mode.dev); conf.put("sandbox.security_manager", rsm); conf.put("sandbox.thread_factory", stf); //conf.put("log.source.java.enabled", false); //conf.put("log.source.template.enabled", false); e = new RythmEngine(conf); engines.put(sessId, e); } return e; } }
diff --git a/Essentials/src/com/earth2me/essentials/UserData.java b/Essentials/src/com/earth2me/essentials/UserData.java index 8046102f..81b8eac6 100644 --- a/Essentials/src/com/earth2me/essentials/UserData.java +++ b/Essentials/src/com/earth2me/essentials/UserData.java @@ -1,709 +1,711 @@ package com.earth2me.essentials; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public abstract class UserData extends PlayerExtension implements IConf { private EssentialsConf config; private static final Logger logger = Logger.getLogger("Minecraft"); protected Essentials ess; protected UserData(Player base, Essentials ess) { super(base); this.ess = ess; File folder = new File(ess.getDataFolder(), "userdata"); if (!folder.exists()) { folder.mkdirs(); } config = new EssentialsConf(new File(folder, Util.sanitizeFileName(base.getName()) + ".yml")); reloadConfig(); } public final void reloadConfig() { config.load(); money = _getMoney(); unlimited = _getUnlimited(); powertools = getPowertools(); lastLocation = _getLastLocation(); lastTeleportTimestamp = _getLastTeleportTimestamp(); lastHealTimestamp = _getLastHealTimestamp(); jail = _getJail(); mails = _getMails(); savedInventory = _getSavedInventory(); teleportEnabled = getTeleportEnabled(); ignoredPlayers = getIgnoredPlayers(); godmode = getGodModeEnabled(); muted = getMuted(); muteTimeout = _getMuteTimeout(); jailed = getJailed(); jailTimeout = _getJailTimeout(); lastLogin = _getLastLogin(); lastLogout = _getLastLogout(); afk = getAfk(); + newplayer = getNew(); geolocation = _getGeoLocation(); isSocialSpyEnabled = _isSocialSpyEnabled(); + isNPC = _isNPC(); } double money; private double _getMoney() { if (config.hasProperty("money")) { return config.getDouble("money", ess.getSettings().getStartingBalance()); } else { return ess.getSettings().getStartingBalance(); } } public double getMoney() { return money; } public void setMoney(double value) { money = value; config.setProperty("money", value); config.save(); } public boolean hasHome() { if (config.hasProperty("home")) { return true; } return false; } public Location getHome() { if (!hasHome()) { return null; } World world = getLocation().getWorld(); String worldHome = "home.worlds." + world.getName().toLowerCase(); if (!config.hasProperty(worldHome)) { String defaultWorld = config.getString("home.default"); worldHome = "home.worlds." + defaultWorld; } Location loc = config.getLocation(worldHome, getServer()); return loc; } public void setHome(Location loc, boolean b) { String worldName = loc.getWorld().getName().toLowerCase(); if (worldName == null || worldName.isEmpty()) { logger.log(Level.WARNING, Util.i18n("emptyWorldName")); return; } if (b || !config.hasProperty("home.default")) { config.setProperty("home.default", worldName); } config.setProperty("home.worlds." + worldName, loc); config.save(); } public String getNickname() { return config.getString("nickname"); } public void setNickname(String nick) { config.setProperty("nickname", nick); config.save(); } private List<Integer> unlimited; private List<Integer> _getUnlimited() { return config.getIntList("unlimited", new ArrayList<Integer>()); } public List<Integer> getUnlimited() { return unlimited; } public boolean hasUnlimited(ItemStack stack) { return unlimited.contains(stack.getTypeId()); } public void setUnlimited(ItemStack stack, boolean state) { if (unlimited.contains(stack.getTypeId())) { unlimited.remove(Integer.valueOf(stack.getTypeId())); } if (state) { unlimited.add(stack.getTypeId()); } config.setProperty("unlimited", unlimited); config.save(); } private Map<Integer, String> powertools; @SuppressWarnings("unchecked") private Map<Integer, String> getPowertools() { Object o = config.getProperty("powertools"); if (o != null && o instanceof Map) { return (Map<Integer, String>)o; } else { return new HashMap<Integer, String>(); } } public String getPowertool(ItemStack stack) { return powertools.get(stack.getTypeId()); } public void setPowertool(ItemStack stack, String command) { if (command == null || command.isEmpty()) { powertools.remove(stack.getTypeId()); } else { powertools.put(stack.getTypeId(), command); } config.setProperty("powertools", powertools); config.save(); } private Location lastLocation; private Location _getLastLocation() { return config.getLocation("lastlocation", getServer()); } public Location getLastLocation() { return lastLocation; } public void setLastLocation(Location loc) { lastLocation = loc; config.setProperty("lastlocation", loc); config.save(); } private long lastTeleportTimestamp; private long _getLastTeleportTimestamp() { return config.getLong("timestamps.lastteleport", 0); } public long getLastTeleportTimestamp() { return lastTeleportTimestamp; } public void setLastTeleportTimestamp(long time) { lastTeleportTimestamp = time; config.setProperty("timestamps.lastteleport", time); config.save(); } private long lastHealTimestamp; private long _getLastHealTimestamp() { return config.getLong("timestamps.lastheal", 0); } public long getLastHealTimestamp() { return lastHealTimestamp; } public void setLastHealTimestamp(long time) { lastHealTimestamp = time; config.setProperty("timestamps.lastheal", time); config.save(); } private String jail; private String _getJail() { return config.getString("jail"); } public String getJail() { return jail; } public void setJail(String jail) { if (jail == null || jail.isEmpty()) { this.jail = null; config.removeProperty("jail"); } else { this.jail = jail; config.setProperty("jail", jail); } config.save(); } private List<String> mails; private List<String> _getMails() { return config.getStringList("mail", new ArrayList<String>()); } public List<String> getMails() { return mails; } public void setMails(List<String> mails) { if (mails == null) { config.removeProperty("mail"); mails = _getMails(); } else { config.setProperty("mail", mails); } this.mails = mails; config.save(); } public void addMail(String mail) { mails.add(mail); setMails(mails); } private ItemStack[] savedInventory; public ItemStack[] getSavedInventory() { return savedInventory; } private ItemStack[] _getSavedInventory() { int size = config.getInt("inventory.size", 0); if (size < 1 || size > getInventory().getSize()) { return null; } ItemStack[] is = new ItemStack[size]; for (int i = 0; i < size; i++) { is[i] = config.getItemStack("inventory." + i); } return is; } public void setSavedInventory(ItemStack[] is) { if (is == null || is.length == 0) { savedInventory = null; config.removeProperty("inventory"); } else { savedInventory = is; config.setProperty("inventory.size", is.length); for (int i = 0; i < is.length; i++) { if (is[i] == null || is[i].getType() == Material.AIR) { continue; } config.setProperty("inventory." + i, is[i]); } } config.save(); } private boolean teleportEnabled; private boolean getTeleportEnabled() { return config.getBoolean("teleportenabled", true); } public boolean isTeleportEnabled() { return teleportEnabled; } public void setTeleportEnabled(boolean set) { teleportEnabled = set; config.setProperty("teleportenabled", set); config.save(); } public boolean toggleTeleportEnabled() { boolean ret = !isTeleportEnabled(); setTeleportEnabled(ret); return ret; } public boolean toggleSocialSpy() { boolean ret = !isSocialSpyEnabled(); setSocialSpyEnabled(ret); return ret; } private List<String> ignoredPlayers; public List<String> getIgnoredPlayers() { return config.getStringList("ignore", new ArrayList<String>()); } public void setIgnoredPlayers(List<String> players) { if (players == null || players.isEmpty()) { ignoredPlayers = new ArrayList<String>(); config.removeProperty("ignore"); } else { ignoredPlayers = players; config.setProperty("ignore", players); } config.save(); } public boolean isIgnoredPlayer(String name) { return ignoredPlayers.contains(name); } public void setIgnoredPlayer(String name, boolean set) { if (set) { ignoredPlayers.add(name); } else { ignoredPlayers.remove(name); } setIgnoredPlayers(ignoredPlayers); } private boolean godmode; private boolean getGodModeEnabled() { return config.getBoolean("godmode", false); } public boolean isGodModeEnabled() { return godmode; } public void setGodModeEnabled(boolean set) { godmode = set; config.setProperty("godmode", set); config.save(); } public boolean toggleGodModeEnabled() { boolean ret = !isGodModeEnabled(); setGodModeEnabled(ret); return ret; } private boolean muted; private boolean getMuted() { return config.getBoolean("muted", false); } public boolean isMuted() { return muted; } public void setMuted(boolean set) { muted = set; config.setProperty("muted", set); config.save(); } public boolean toggleMuted() { boolean ret = !isMuted(); setMuted(ret); return ret; } private long muteTimeout; private long _getMuteTimeout() { return config.getLong("timestamps.mute", 0); } public long getMuteTimeout() { return muteTimeout; } public void setMuteTimeout(long time) { muteTimeout = time; config.setProperty("timestamps.mute", time); config.save(); } private boolean jailed; private boolean getJailed() { return config.getBoolean("jailed", false); } public boolean isJailed() { return jailed; } public void setJailed(boolean set) { jailed = set; config.setProperty("jailed", set); config.save(); } public boolean toggleJailed() { boolean ret = !isJailed(); setJailed(ret); return ret; } private long jailTimeout; private long _getJailTimeout() { return config.getLong("timestamps.jail", 0); } public long getJailTimeout() { return jailTimeout; } public void setJailTimeout(long time) { jailTimeout = time; config.setProperty("timestamps.jail", time); config.save(); } public String getBanReason() { return config.getString("ban.reason"); } public void setBanReason(String reason) { config.setProperty("ban.reason", reason); config.save(); } public long getBanTimeout() { return config.getLong("ban.timeout", 0); } public void setBanTimeout(long time) { config.setProperty("ban.timeout", time); config.save(); } private long lastLogin; private long _getLastLogin() { return config.getLong("timestamps.login", 0); } public long getLastLogin() { return lastLogin; } public void setLastLogin(long time) { lastLogin = time; config.setProperty("timestamps.login", time); config.save(); } private long lastLogout; private long _getLastLogout() { return config.getLong("timestamps.logout", 0); } public long getLastLogout() { return lastLogout; } public void setLastLogout(long time) { lastLogout = time; config.setProperty("timestamps.logout", time); config.save(); } private boolean afk; private boolean getAfk() { return config.getBoolean("afk", false); } public boolean isAfk() { return afk; } public void setAfk(boolean set) { afk = set; config.setProperty("afk", set); config.save(); } public boolean toggleAfk() { boolean ret = !isAfk(); setAfk(ret); return ret; } private boolean newplayer; private boolean getNew() { return config.getBoolean("newplayer", true); } public boolean isNew() { return newplayer; } public void setNew(boolean set) { newplayer = set; config.setProperty("newplayer", set); config.save(); } private String geolocation; private String _getGeoLocation() { return config.getString("geolocation"); } public String getGeoLocation() { return geolocation; } public void setGeoLocation(String geolocation) { if (geolocation == null || geolocation.isEmpty()) { this.geolocation = null; config.removeProperty("geolocation"); } else { this.geolocation = geolocation; config.setProperty("geolocation", geolocation); } config.save(); } private boolean isSocialSpyEnabled; private boolean _isSocialSpyEnabled() { return config.getBoolean("socialspy", false); } public boolean isSocialSpyEnabled() { return isSocialSpyEnabled; } public void setSocialSpyEnabled(boolean status) { isSocialSpyEnabled = status; config.setProperty("socialspy", status); config.save(); } private boolean isNPC; private boolean _isNPC() { return config.getBoolean("npc", false); } public boolean isNPC() { return isNPC; } void setNPC(boolean set) { isNPC = set; config.setProperty("npc", set); config.save(); } }
false
true
public final void reloadConfig() { config.load(); money = _getMoney(); unlimited = _getUnlimited(); powertools = getPowertools(); lastLocation = _getLastLocation(); lastTeleportTimestamp = _getLastTeleportTimestamp(); lastHealTimestamp = _getLastHealTimestamp(); jail = _getJail(); mails = _getMails(); savedInventory = _getSavedInventory(); teleportEnabled = getTeleportEnabled(); ignoredPlayers = getIgnoredPlayers(); godmode = getGodModeEnabled(); muted = getMuted(); muteTimeout = _getMuteTimeout(); jailed = getJailed(); jailTimeout = _getJailTimeout(); lastLogin = _getLastLogin(); lastLogout = _getLastLogout(); afk = getAfk(); geolocation = _getGeoLocation(); isSocialSpyEnabled = _isSocialSpyEnabled(); }
public final void reloadConfig() { config.load(); money = _getMoney(); unlimited = _getUnlimited(); powertools = getPowertools(); lastLocation = _getLastLocation(); lastTeleportTimestamp = _getLastTeleportTimestamp(); lastHealTimestamp = _getLastHealTimestamp(); jail = _getJail(); mails = _getMails(); savedInventory = _getSavedInventory(); teleportEnabled = getTeleportEnabled(); ignoredPlayers = getIgnoredPlayers(); godmode = getGodModeEnabled(); muted = getMuted(); muteTimeout = _getMuteTimeout(); jailed = getJailed(); jailTimeout = _getJailTimeout(); lastLogin = _getLastLogin(); lastLogout = _getLastLogout(); afk = getAfk(); newplayer = getNew(); geolocation = _getGeoLocation(); isSocialSpyEnabled = _isSocialSpyEnabled(); isNPC = _isNPC(); }
diff --git a/src/main/java/net/praqma/hudson/scm/PucmScm.java b/src/main/java/net/praqma/hudson/scm/PucmScm.java index fdb139f..f0a7a15 100644 --- a/src/main/java/net/praqma/hudson/scm/PucmScm.java +++ b/src/main/java/net/praqma/hudson/scm/PucmScm.java @@ -1,704 +1,705 @@ package net.praqma.hudson.scm; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.FilePath.FileCallable; import hudson.model.Build; import hudson.model.BuildListener; import hudson.model.FreeStyleBuild; import hudson.model.ParameterValue; import hudson.model.TaskListener; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Job; import hudson.remoting.VirtualChannel; import hudson.scm.ChangeLogParser; import hudson.scm.PollingResult; import hudson.scm.SCMDescriptor; import hudson.scm.SCMRevisionState; import hudson.scm.SCM; import hudson.util.FormValidation; import hudson.util.VariableResolver; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.praqma.clearcase.ucm.UCMException; import net.praqma.clearcase.ucm.entities.Project; import net.praqma.clearcase.ucm.entities.Baseline; import net.praqma.clearcase.ucm.entities.Activity; import net.praqma.clearcase.ucm.entities.Component; import net.praqma.clearcase.ucm.utils.BaselineList; import net.praqma.clearcase.ucm.entities.Stream; import net.praqma.clearcase.ucm.entities.UCMEntity; import net.praqma.clearcase.ucm.entities.Version; import net.praqma.clearcase.ucm.view.SnapshotView; import net.praqma.clearcase.ucm.view.SnapshotView.COMP; import net.praqma.clearcase.ucm.view.UCMView; import net.praqma.clearcase.ucm.utils.BaselineDiff; import net.praqma.hudson.Config; import net.praqma.hudson.exception.ScmException; import net.praqma.hudson.scm.PucmState.State; import net.praqma.util.debug.Logger; import net.sf.json.JSONObject; //import net.praqma.hudson.Version; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.export.Exported; /** * CC4HClass is responsible for everything regarding Hudsons connection to * ClearCase pre-build. This class defines all the files required by the user. * The information can be entered on the config page. * * @author Troels Selch S�rensen * @author Margit Bennetzen * */ public class PucmScm extends SCM { private String levelToPoll; private String loadModule; private String component; private String stream; private boolean newest; private Baseline bl; private List<String> levels = null; private List<String> loadModules = null; //private BaselineList baselines; private boolean compRevCalled; private StringBuffer pollMsgs = new StringBuffer(); private Stream integrationstream; private Component comp; private SnapshotView sv = null; private boolean doPostBuild = true; private String buildProject; private String jobName = ""; private Integer jobNumber; private String id = ""; protected static Logger logger = Logger.getLogger(); public static PucmState pucm = new PucmState(); /** * The constructor is used by Hudson to create the instance of the plugin * needed for a connection to ClearCase. It is annotated with * <code>@DataBoundConstructor</code> to tell Hudson where to put the * information retrieved from the configuration page in the WebUI. * * @param component * defines the component needed to find baselines. * @param levelToPoll * defines the level to poll ClearCase for. * @param loadModule * tells if we should load all modules or only the ones that are * modifiable. * @param stream * defines the stream needed to find baselines. * @param newest * tells whether we should build only the newest baseline. * @param newerThanRecommended * tells whether we should look at all baselines or only ones * newer than the recommended baseline */ @DataBoundConstructor public PucmScm( String component, String levelToPoll, String loadModule, String stream, boolean newest, boolean testing, String buildProject ) { logger.trace_function(); logger.debug( "PucmSCM constructor" ); this.component = component; this.levelToPoll = levelToPoll; this.loadModule = loadModule; this.stream = stream; this.newest = newest; this.buildProject = buildProject; } @Override public boolean checkout( AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile ) throws IOException, InterruptedException { logger.trace_function(); logger.debug( "PucmSCM checkout" ); boolean result = true; // consoleOutput Printstream is from Hudson, so it can only be accessed // here PrintStream consoleOutput = listener.getLogger(); consoleOutput.println( "[PUCM] Praqmatic UCM v." + net.praqma.hudson.Version.version + " - SCM section started" ); /* Recalculate the states */ int count = pucm.recalculate( build.getProject() ); logger.info( "Removed " + count + " from states." ); doPostBuild = true; jobName = build.getParent().getDisplayName(); jobNumber = build.getNumber(); /* If we polled, we should get the same object created at that point */ State state = pucm.getState( jobName, jobNumber ); logger.debug( id + "The initial state:\n" + state.stringify() ); this.id = "[" + jobName + "::" + jobNumber + "]"; if ( build.getBuildVariables().get( "include_classes" ) != null ) { String[] is = build.getBuildVariables().get( "include_classes" ).toString().split( "," ); for( String i : is ) { logger.includeClass( i.trim() ); } } if ( build.getBuildVariables().get( "pucm_baseline" ) != null ) { Stream integrationstream = null; String baselinename = (String) build.getBuildVariables().get( "pucm_baseline" ); try { state.setBaseline( UCMEntity.GetBaseline( baselinename ) ); integrationstream = bl.GetStream(); + state.setStream( state.getBaseline().GetStream() ); consoleOutput.println( "[PUCM] Starting parameterized build with a pucm_baseline.\nUsing baseline: " + baselinename + " from integrationstream " + integrationstream.GetShortname() ); } catch ( UCMException e ) { consoleOutput.println( "[PUCM] Could not find baseline from parameter." ); state.setPostBuild( false ); result = false; } } else { // compRevCalled tells whether we have polled for baselines to build // - // so if we haven't polled, we do it now if ( !compRevCalled ) { try { //baselinesToBuild( component, stream, build.getProject(), build.getParent().getDisplayName(), build.getNumber() ); baselinesToBuild( build.getProject(), state ); } catch ( ScmException e ) { pollMsgs.append( e.getMessage() ); result = false; } } compRevCalled = false; // pollMsgs are set in either compareRemoteRevisionWith() or // baselinesToBuild() consoleOutput.println( pollMsgs ); pollMsgs = new StringBuffer(); } if ( result ) { try { /* Force the Baseline to be loaded */ try { bl.Load(); } catch( UCMException e ) { logger.debug( id + "Could not load Baseline" ); consoleOutput.println( "[PUCM] Could not load Baseline." ); } /* Check parameters */ if( listener == null ) { consoleOutput.println( "[PUCM] Listener is null" ); } if( jobName == null ) { consoleOutput.println( "[PUCM] jobname is null" ); } if( build == null ) { consoleOutput.println( "[PUCM] BUILD is null" ); } if( stream == null ) { consoleOutput.println( "[PUCM] stream is null" ); } if( loadModule == null ) { consoleOutput.println( "[PUCM] loadModule is null" ); } if( buildProject == null ) { consoleOutput.println( "[PUCM] buildProject is null" ); } if( bl == null ) { consoleOutput.println( "[PUCM] bl is null" ); } CheckoutTask ct = new CheckoutTask( listener, jobName, build.getNumber(), stream, loadModule, bl.GetFQName(), buildProject ); String changelog = workspace.act( ct ); /* Write change log */ try { FileOutputStream fos = new FileOutputStream( changelogFile ); fos.write( changelog.getBytes() ); fos.close(); } catch( IOException e ) { logger.debug( id + "Could not write change log file" ); consoleOutput.println( "[PUCM] Could not write change log file" ); } //doPostBuild = changelog.length() > 0 ? true : false; } catch ( Exception e ) { consoleOutput.println( "[PUCM] An unknown error occured: " + e.getMessage() ); doPostBuild = false; result = false; } } //pucm.add( new PucmState( build.getParent().getDisplayName(), build.getNumber(), bl, null, comp, doPostBuild ) ); //state.save(); logger.debug( id + "The CO state:\n" + state.stringify() ); return result; } @Override public ChangeLogParser createChangeLogParser() { logger.trace_function(); return new ChangeLogParserImpl(); } @Override public PollingResult compareRemoteRevisionWith( AbstractProject<?, ?> project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState baseline ) throws IOException, InterruptedException { this.id = "[" + project.getDisplayName() + "::" + project.getNextBuildNumber() + "]"; logger.trace_function(); logger.debug( id + "PucmSCM Pollingresult" ); /* Make a state object, which is only temporary, only to determine if there's baselines to build this object will be stored in checkout */ jobName = project.getDisplayName(); jobNumber = project.getNextBuildNumber(); /* This number is not the final job number */ State state = pucm.getState( jobName, jobNumber ); PollingResult p; try { //baselinesToBuild( component, stream, project, project.getDisplayName(), project.getNextBuildNumber() ); baselinesToBuild( project, state ); compRevCalled = true; logger.info( id + "Polling result = BUILD NOW" ); p = PollingResult.BUILD_NOW; } catch ( ScmException e ) { logger.info( id + "Polling result = NO CHANGES" ); p = PollingResult.NO_CHANGES; PrintStream consoleOut = listener.getLogger(); consoleOut.println( pollMsgs + "\n" + e.getMessage() ); pollMsgs = new StringBuffer(); logger.debug( id + "Removed job " + state.getJobNumber() + " from list" ); state.remove(); } logger.debug( id + "FINAL Polling result = " + p.change.toString() ); return p; } @Override public SCMRevisionState calcRevisionsFromBuild( AbstractBuild<?, ?> build, Launcher launcher, TaskListener listener ) throws IOException, InterruptedException { logger.trace_function(); logger.debug( id + "PucmSCM calcRevisionsFromBuild" ); // PrintStream hudsonOut = listener.getLogger(); SCMRevisionStateImpl scmRS = null; if ( !( bl == null ) ) { scmRS = new SCMRevisionStateImpl(); } return scmRS; } private void baselinesToBuild( AbstractProject<?, ?> project, State state ) throws ScmException { logger.trace_function(); /* Store the component to the state */ try { state.setComponent( UCMEntity.GetComponent( component, false ) ); } catch ( UCMException e ) { throw new ScmException( "Could not get component. " + e.getMessage() ); } /* Store the stream to the state */ try { state.setStream( UCMEntity.GetStream( stream, false ) ); } catch ( UCMException e ) { throw new ScmException( "Could not get stream. " + e.getMessage() ); } state.setPlevel( Project.Plevel.valueOf( levelToPoll ) ); /* The baseline list */ BaselineList baselines = null; try { pollMsgs.append( "[PUCM] Getting all baselines for :\n[PUCM] * Stream: " ); pollMsgs.append( stream ); pollMsgs.append( "\n[PUCM] * Component: " ); pollMsgs.append( component ); pollMsgs.append( "\n[PUCM] * Promotionlevel: " ); pollMsgs.append( levelToPoll ); pollMsgs.append( "\n" ); baselines = state.getComponent().GetBaselines( state.getStream(), state.getPlevel() ); } catch ( UCMException e ) { throw new ScmException( "Could not retrieve baselines from repository. " + e.getMessage() ); } if ( baselines.size() > 0 ) { printBaselines( baselines ); logger.debug( id + "PUCM=" + pucm.stringify() ); try { List<Baseline> baselinelist = state.getStream().GetRecommendedBaselines(); pollMsgs.append( "\n[PUCM] Recommended baseline(s): \n" ); for ( Baseline b : baselinelist ) { pollMsgs.append( b.GetShortname() + "\n" ); } /* Determine the baseline to build */ bl = null; state.setBaseline( null ); /* For each baseline retrieved from ClearCase */ //for ( Baseline b : baselinelist ) int start = 0; int stop = baselines.size(); int increment = 1; if( newest ) { start = baselines.size() - 1; //stop = 0; increment = -1; } /* Find the Baseline to build */ for( int i = start ; i < stop && i >= 0 ; i += increment ) { /* The current baseline */ Baseline b = baselines.get( i ); State cstate = pucm.getStateByBaseline( jobName, b.GetFQName() ); /* The baseline is in progress, determine if the job is still running */ //if( thisJob.containsKey( b.GetFQName() ) ) if( cstate != null ) { //Integer bnum = thisJob.get( b.GetFQName() ); //State Integer bnum = cstate.getJobNumber(); Object o = project.getBuildByNumber( bnum ); Build bld = (Build)o; /* The job is not running */ if( !bld.isLogUpdated() ) { logger.debug( id + "Job " + bld.getNumber() + " is not building, using baseline: " + b ); bl = b; //thisJob.put( b.GetFQName(), state.getJobNumber() ); break; } else { logger.debug( id + "Job " + bld.getNumber() + " is building " + cstate.getBaseline().GetFQName() ); } } /* The baseline is available */ else { bl = b; //thisJob.put( b.GetFQName(), state.getJobNumber() ); logger.debug( id + "The baseline " + b + " is available" ); break; } } if( bl == null ) { logger.log( id + "No baselines available on chosen parameters." ); throw new ScmException( "No baselines available on chosen parameters." ); } pollMsgs.append( "\n[PUCM] Building baseline: " + bl + "\n" ); state.setBaseline( bl ); /* Store the baseline to build */ //thisJob.put( bl.GetFQName(), state.getJobNumber() ); } catch ( UCMException e ) { throw new ScmException( "Could not get recommended baselines. " + e.getMessage() ); } } else { throw new ScmException( "No baselines on chosen parameters." ); } //logger.debug( id + "PRINTING THIS JOB:" ); //logger.debug( net.praqma.util.structure.Printer.mapPrinterToString( thisJob ) ); } private void printBaselines( BaselineList baselines ) { pollMsgs.append( "[PUCM] Retrieved baselines:\n" ); if ( !( baselines.size() > 20 ) ) { for ( Baseline b : baselines ) { pollMsgs.append( b.GetShortname() ); pollMsgs.append( "\n" ); } } else { int i = baselines.size(); pollMsgs.append( "[PUCM] There are " + i + " baselines - only printing first and last three\n" ); pollMsgs.append( baselines.get( 0 ).GetShortname() + "\n" ); pollMsgs.append( baselines.get( 1 ).GetShortname() + "\n" ); pollMsgs.append( baselines.get( 2 ).GetShortname() + "\n" ); pollMsgs.append( "...\n" ); pollMsgs.append( baselines.get( i - 3 ).GetShortname() + "\n" ); pollMsgs.append( baselines.get( i - 2 ).GetShortname() + "\n" ); pollMsgs.append( baselines.get( i - 1 ).GetShortname() + "\n" ); } } /* * The following getters and booleans (six in all) are used to display saved * userdata in Hudsons gui */ public String getLevelToPoll() { logger.trace_function(); return levelToPoll; } public String getComponent() { logger.trace_function(); return component; } public String getStream() { logger.trace_function(); return stream; } public String getLoadModule() { logger.trace_function(); return loadModule; } public boolean isNewest() { logger.trace_function(); return newest; } /* * getStreamObject() and getBaseline() are used by PucmNotifier to get the * Baseline and Stream in use */ public Stream getStreamObject() { logger.trace_function(); return integrationstream; } @Exported public Baseline getBaseline() { logger.trace_function(); return bl; } @Exported public boolean doPostbuild() { logger.trace_function(); return doPostBuild; } public String getBuildProject() { logger.trace_function(); return buildProject; } /** * This class is used to describe the plugin to Hudson * * @author Troels Selch S�rensen * @author Margit Bennetzen * */ @Extension public static class PucmScmDescriptor extends SCMDescriptor<PucmScm> { private String cleartool; private List<String> loadModules; public PucmScmDescriptor() { super( PucmScm.class, null ); logger.trace_function(); loadModules = getLoadModules(); load(); Config.setContext(); } /** * This method is called, when the user saves the global Hudson * configuration. */ @Override public boolean configure( org.kohsuke.stapler.StaplerRequest req, JSONObject json ) throws FormException { logger.trace_function(); cleartool = req.getParameter( "PUCM.cleartool" ).trim(); save(); return true; } /** * This is called by Hudson to discover the plugin name */ @Override public String getDisplayName() { logger.trace_function(); return "Praqmatic UCM"; } /** * This method is called by the scm/Pucm/global.jelly to validate the * input without reloading the global configuration page * * @param value * @return */ public FormValidation doExecutableCheck( @QueryParameter String value ) { logger.trace_function(); return FormValidation.validateExecutable( value ); } /** * Called by Hudson. If the user does not input a command for Hudson to * use when polling, default value is returned * * @return */ public String getCleartool() { logger.trace_function(); if ( cleartool == null || cleartool.equals( "" ) ) { return "cleartool"; } return cleartool; } /** * Used by Hudson to display a list of valid promotion levels to build * from. The list of promotion levels is hard coded in * net.praqma.hudson.Config.java * * @return */ public List<String> getLevels() { logger.trace_function(); return Config.getLevels(); } /** * Used by Hudson to display a list of loadModules (whether to poll all * or only modifiable elements * * @return */ public List<String> getLoadModules() { logger.trace_function(); loadModules = new ArrayList<String>(); loadModules.add( "All" ); loadModules.add( "Modifiable" ); return loadModules; } } }
true
true
public boolean checkout( AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile ) throws IOException, InterruptedException { logger.trace_function(); logger.debug( "PucmSCM checkout" ); boolean result = true; // consoleOutput Printstream is from Hudson, so it can only be accessed // here PrintStream consoleOutput = listener.getLogger(); consoleOutput.println( "[PUCM] Praqmatic UCM v." + net.praqma.hudson.Version.version + " - SCM section started" ); /* Recalculate the states */ int count = pucm.recalculate( build.getProject() ); logger.info( "Removed " + count + " from states." ); doPostBuild = true; jobName = build.getParent().getDisplayName(); jobNumber = build.getNumber(); /* If we polled, we should get the same object created at that point */ State state = pucm.getState( jobName, jobNumber ); logger.debug( id + "The initial state:\n" + state.stringify() ); this.id = "[" + jobName + "::" + jobNumber + "]"; if ( build.getBuildVariables().get( "include_classes" ) != null ) { String[] is = build.getBuildVariables().get( "include_classes" ).toString().split( "," ); for( String i : is ) { logger.includeClass( i.trim() ); } } if ( build.getBuildVariables().get( "pucm_baseline" ) != null ) { Stream integrationstream = null; String baselinename = (String) build.getBuildVariables().get( "pucm_baseline" ); try { state.setBaseline( UCMEntity.GetBaseline( baselinename ) ); integrationstream = bl.GetStream(); consoleOutput.println( "[PUCM] Starting parameterized build with a pucm_baseline.\nUsing baseline: " + baselinename + " from integrationstream " + integrationstream.GetShortname() ); } catch ( UCMException e ) { consoleOutput.println( "[PUCM] Could not find baseline from parameter." ); state.setPostBuild( false ); result = false; } } else { // compRevCalled tells whether we have polled for baselines to build // - // so if we haven't polled, we do it now if ( !compRevCalled ) { try { //baselinesToBuild( component, stream, build.getProject(), build.getParent().getDisplayName(), build.getNumber() ); baselinesToBuild( build.getProject(), state ); } catch ( ScmException e ) { pollMsgs.append( e.getMessage() ); result = false; } } compRevCalled = false; // pollMsgs are set in either compareRemoteRevisionWith() or // baselinesToBuild() consoleOutput.println( pollMsgs ); pollMsgs = new StringBuffer(); } if ( result ) { try { /* Force the Baseline to be loaded */ try { bl.Load(); } catch( UCMException e ) { logger.debug( id + "Could not load Baseline" ); consoleOutput.println( "[PUCM] Could not load Baseline." ); } /* Check parameters */ if( listener == null ) { consoleOutput.println( "[PUCM] Listener is null" ); } if( jobName == null ) { consoleOutput.println( "[PUCM] jobname is null" ); } if( build == null ) { consoleOutput.println( "[PUCM] BUILD is null" ); } if( stream == null ) { consoleOutput.println( "[PUCM] stream is null" ); } if( loadModule == null ) { consoleOutput.println( "[PUCM] loadModule is null" ); } if( buildProject == null ) { consoleOutput.println( "[PUCM] buildProject is null" ); } if( bl == null ) { consoleOutput.println( "[PUCM] bl is null" ); } CheckoutTask ct = new CheckoutTask( listener, jobName, build.getNumber(), stream, loadModule, bl.GetFQName(), buildProject ); String changelog = workspace.act( ct ); /* Write change log */ try { FileOutputStream fos = new FileOutputStream( changelogFile ); fos.write( changelog.getBytes() ); fos.close(); } catch( IOException e ) { logger.debug( id + "Could not write change log file" ); consoleOutput.println( "[PUCM] Could not write change log file" ); } //doPostBuild = changelog.length() > 0 ? true : false; } catch ( Exception e ) { consoleOutput.println( "[PUCM] An unknown error occured: " + e.getMessage() ); doPostBuild = false; result = false; } } //pucm.add( new PucmState( build.getParent().getDisplayName(), build.getNumber(), bl, null, comp, doPostBuild ) ); //state.save(); logger.debug( id + "The CO state:\n" + state.stringify() ); return result; }
public boolean checkout( AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile ) throws IOException, InterruptedException { logger.trace_function(); logger.debug( "PucmSCM checkout" ); boolean result = true; // consoleOutput Printstream is from Hudson, so it can only be accessed // here PrintStream consoleOutput = listener.getLogger(); consoleOutput.println( "[PUCM] Praqmatic UCM v." + net.praqma.hudson.Version.version + " - SCM section started" ); /* Recalculate the states */ int count = pucm.recalculate( build.getProject() ); logger.info( "Removed " + count + " from states." ); doPostBuild = true; jobName = build.getParent().getDisplayName(); jobNumber = build.getNumber(); /* If we polled, we should get the same object created at that point */ State state = pucm.getState( jobName, jobNumber ); logger.debug( id + "The initial state:\n" + state.stringify() ); this.id = "[" + jobName + "::" + jobNumber + "]"; if ( build.getBuildVariables().get( "include_classes" ) != null ) { String[] is = build.getBuildVariables().get( "include_classes" ).toString().split( "," ); for( String i : is ) { logger.includeClass( i.trim() ); } } if ( build.getBuildVariables().get( "pucm_baseline" ) != null ) { Stream integrationstream = null; String baselinename = (String) build.getBuildVariables().get( "pucm_baseline" ); try { state.setBaseline( UCMEntity.GetBaseline( baselinename ) ); integrationstream = bl.GetStream(); state.setStream( state.getBaseline().GetStream() ); consoleOutput.println( "[PUCM] Starting parameterized build with a pucm_baseline.\nUsing baseline: " + baselinename + " from integrationstream " + integrationstream.GetShortname() ); } catch ( UCMException e ) { consoleOutput.println( "[PUCM] Could not find baseline from parameter." ); state.setPostBuild( false ); result = false; } } else { // compRevCalled tells whether we have polled for baselines to build // - // so if we haven't polled, we do it now if ( !compRevCalled ) { try { //baselinesToBuild( component, stream, build.getProject(), build.getParent().getDisplayName(), build.getNumber() ); baselinesToBuild( build.getProject(), state ); } catch ( ScmException e ) { pollMsgs.append( e.getMessage() ); result = false; } } compRevCalled = false; // pollMsgs are set in either compareRemoteRevisionWith() or // baselinesToBuild() consoleOutput.println( pollMsgs ); pollMsgs = new StringBuffer(); } if ( result ) { try { /* Force the Baseline to be loaded */ try { bl.Load(); } catch( UCMException e ) { logger.debug( id + "Could not load Baseline" ); consoleOutput.println( "[PUCM] Could not load Baseline." ); } /* Check parameters */ if( listener == null ) { consoleOutput.println( "[PUCM] Listener is null" ); } if( jobName == null ) { consoleOutput.println( "[PUCM] jobname is null" ); } if( build == null ) { consoleOutput.println( "[PUCM] BUILD is null" ); } if( stream == null ) { consoleOutput.println( "[PUCM] stream is null" ); } if( loadModule == null ) { consoleOutput.println( "[PUCM] loadModule is null" ); } if( buildProject == null ) { consoleOutput.println( "[PUCM] buildProject is null" ); } if( bl == null ) { consoleOutput.println( "[PUCM] bl is null" ); } CheckoutTask ct = new CheckoutTask( listener, jobName, build.getNumber(), stream, loadModule, bl.GetFQName(), buildProject ); String changelog = workspace.act( ct ); /* Write change log */ try { FileOutputStream fos = new FileOutputStream( changelogFile ); fos.write( changelog.getBytes() ); fos.close(); } catch( IOException e ) { logger.debug( id + "Could not write change log file" ); consoleOutput.println( "[PUCM] Could not write change log file" ); } //doPostBuild = changelog.length() > 0 ? true : false; } catch ( Exception e ) { consoleOutput.println( "[PUCM] An unknown error occured: " + e.getMessage() ); doPostBuild = false; result = false; } } //pucm.add( new PucmState( build.getParent().getDisplayName(), build.getNumber(), bl, null, comp, doPostBuild ) ); //state.save(); logger.debug( id + "The CO state:\n" + state.stringify() ); return result; }
diff --git a/src/com/vaadin/data/util/AbstractInMemoryContainer.java b/src/com/vaadin/data/util/AbstractInMemoryContainer.java index 61dbe7584..e9867c16a 100644 --- a/src/com/vaadin/data/util/AbstractInMemoryContainer.java +++ b/src/com/vaadin/data/util/AbstractInMemoryContainer.java @@ -1,787 +1,788 @@ package com.vaadin.data.util; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import com.vaadin.data.Container; import com.vaadin.data.Container.ItemSetChangeNotifier; import com.vaadin.data.Item; /** * Abstract {@link Container} class that handles common functionality for * in-memory containers. Concrete in-memory container classes can either inherit * this class, inherit {@link AbstractContainer}, or implement the * {@link Container} interface directly. * * Features: * <ul> * <li> {@link Container.Ordered} * <li> {@link Container.Indexed} * <li> {@link Filterable} (internal implementation, does not implement the * interface directly) * <li> {@link Sortable} (internal implementation, does not implement the * interface directly) * </ul> * * @param <ITEMIDTYPE> * the class of item identifiers in the container, use Object if can * be any class * @param <PROPERTYIDCLASS> * the class of property identifiers for the items in the container, * use Object if can be any class * @param <ITEMCLASS> * the (base) class of the Item instances in the container, use * {@link Item} if unknown * * @since 6.6 */ public abstract class AbstractInMemoryContainer<ITEMIDTYPE, PROPERTYIDCLASS, ITEMCLASS extends Item> extends AbstractContainer implements ItemSetChangeNotifier, Container.Indexed { /** * Filter interface for item filtering in in-memory containers, including * for implementing {@link Filterable}. * * An ItemFilter must implement {@link #equals(Object)} and * {@link #hashCode()} correctly to avoid duplicate filter registrations * etc. * * TODO this may change for 6.6 with the new filtering API * * @since 6.6 */ public interface ItemFilter extends Serializable { /** * Check if an item passes the filter. * * @param item * @return true if the item is accepted by this filter */ public boolean passesFilter(Item item); /** * Check if a change in the value of a property can affect the filtering * result. May always return true, at the cost of performance. * * @param propertyId * @return true if the filtering result may/does change based on changes * to the property identified by propertyId */ public boolean appliesToProperty(Object propertyId); } /** * An ordered {@link List} of all item identifiers in the container, * including those that have been filtered out. * * Must not be null. */ private List<ITEMIDTYPE> allItemIds; /** * An ordered {@link List} of item identifiers in the container after * filtering, excluding those that have been filtered out. * * This is what the external API of the {@link Container} interface and its * subinterfaces shows (e.g. {@link #size()}, {@link #nextItemId(Object)}). * * If null, the full item id list is used instead. */ private List<ITEMIDTYPE> filteredItemIds; /** * Filters that are applied to the container to limit the items visible in * it */ private Set<ItemFilter> filters = new HashSet<ItemFilter>(); /** * The item sorter which is used for sorting the container. */ private ItemSorter itemSorter = new DefaultItemSorter(); // Constructors /** * Constructor for an abstract in-memory container. */ protected AbstractInMemoryContainer() { setAllItemIds(new ListSet<ITEMIDTYPE>()); } // Container interface methods with more specific return class public abstract ITEMCLASS getItem(Object itemId); /** * Get an item even if filtered out. * * For internal use only. * * @param itemId * @return */ protected abstract ITEMCLASS getUnfilteredItem(Object itemId); // cannot override getContainerPropertyIds() and getItemIds(): if subclass // uses Object as ITEMIDCLASS or PROPERTYIDCLASS, Collection<Object> cannot // be cast to Collection<MyInterface> // public abstract Collection<PROPERTYIDCLASS> getContainerPropertyIds(); // public abstract Collection<ITEMIDCLASS> getItemIds(); // Container interface method implementations public int size() { return getVisibleItemIds().size(); } public boolean containsId(Object itemId) { // only look at visible items after filtering if (itemId == null) { return false; } else { return getVisibleItemIds().contains(itemId); } } public Collection<?> getItemIds() { return Collections.unmodifiableCollection(getVisibleItemIds()); } // Container.Ordered public ITEMIDTYPE nextItemId(Object itemId) { int index = indexOfId(itemId); if (index >= 0 && index < size() - 1) { return getIdByIndex(index + 1); } else { // out of bounds return null; } } public ITEMIDTYPE prevItemId(Object itemId) { int index = indexOfId(itemId); if (index > 0) { return getIdByIndex(index - 1); } else { // out of bounds return null; } } public ITEMIDTYPE firstItemId() { if (size() > 0) { return getIdByIndex(0); } else { return null; } } public ITEMIDTYPE lastItemId() { if (size() > 0) { return getIdByIndex(size() - 1); } else { return null; } } public boolean isFirstId(Object itemId) { if (itemId == null) { return false; } return itemId.equals(firstItemId()); } public boolean isLastId(Object itemId) { if (itemId == null) { return false; } return itemId.equals(lastItemId()); } // Container.Indexed public ITEMIDTYPE getIdByIndex(int index) { return getVisibleItemIds().get(index); } public int indexOfId(Object itemId) { return getVisibleItemIds().indexOf(itemId); } // ItemSetChangeNotifier @Override public void addListener(Container.ItemSetChangeListener listener) { super.addListener(listener); } @Override public void removeListener(Container.ItemSetChangeListener listener) { super.removeListener(listener); } // internal methods // Filtering support /** * Filter the view to recreate the visible item list from the unfiltered * items, and send a notification if the set of visible items changed in any * way. */ protected void filterAll() { if (doFilterContainer(!getFilters().isEmpty())) { fireItemSetChange(); } } /** * Filters the data in the container and updates internal data structures. * This method should reset any internal data structures and then repopulate * them so {@link #getItemIds()} and other methods only return the filtered * items. * * @param hasFilters * true if filters has been set for the container, false * otherwise * @return true if the item set has changed as a result of the filtering */ protected boolean doFilterContainer(boolean hasFilters) { if (!hasFilters) { boolean changed = getAllItemIds().size() != getVisibleItemIds() .size(); setFilteredItemIds(null); return changed; } // Reset filtered list List<ITEMIDTYPE> originalFilteredItemIds = getFilteredItemIds(); boolean wasUnfiltered = false; if (originalFilteredItemIds == null) { originalFilteredItemIds = Collections.emptyList(); wasUnfiltered = true; } setFilteredItemIds(new ListSet<ITEMIDTYPE>()); // Filter boolean equal = true; Iterator<ITEMIDTYPE> origIt = originalFilteredItemIds.iterator(); for (final Iterator<ITEMIDTYPE> i = getAllItemIds().iterator(); i .hasNext();) { final ITEMIDTYPE id = i.next(); if (passesFilters(id)) { // filtered list comes from the full list, can use == equal = equal && origIt.hasNext() && origIt.next() == id; getFilteredItemIds().add(id); } } - return wasUnfiltered || !equal || origIt.hasNext(); + return (wasUnfiltered && !getAllItemIds().isEmpty()) || !equal + || origIt.hasNext(); } /** * Checks if the given itemId passes the filters set for the container. The * caller should make sure the itemId exists in the container. For * non-existing itemIds the behavior is undefined. * * @param itemId * An itemId that exists in the container. * @return true if the itemId passes all filters or no filters are set, * false otherwise. */ protected boolean passesFilters(Object itemId) { ITEMCLASS item = getUnfilteredItem(itemId); if (getFilters().isEmpty()) { return true; } final Iterator<ItemFilter> i = getFilters().iterator(); while (i.hasNext()) { final ItemFilter f = i.next(); if (!f.passesFilter(item)) { return false; } } return true; } /** * Add a container filter and re-filter the view * * This can be used to implement * {@link Filterable#addContainerFilter(Object, String, boolean, boolean)}. */ protected void addFilter(ItemFilter filter) { getFilters().add(filter); filterAll(); } /** * Remove all container filters for all properties and re-filter the view. * * This can be used to implement * {@link Filterable#removeAllContainerFilters()}. */ protected void removeAllFilters() { if (getFilters().isEmpty()) { return; } getFilters().clear(); filterAll(); } /** * Checks if there is a filter that applies to a given property. * * @param propertyId * @return true if there is an active filter for the property */ protected boolean isPropertyFiltered(Object propertyId) { if (getFilters().isEmpty() || propertyId == null) { return false; } final Iterator<ItemFilter> i = getFilters().iterator(); while (i.hasNext()) { final ItemFilter f = i.next(); if (f.appliesToProperty(propertyId)) { return true; } } return false; } /** * Remove all container filters for a given property identifier and * re-filter the view. This also removes filters applying to multiple * properties including the one identified by propertyId. * * This can be used to implement * {@link Filterable#removeContainerFilters(Object)}. * * @param propertyId * @return Collection<Filter> removed filters */ protected Collection<ItemFilter> removeFilters(Object propertyId) { if (getFilters().isEmpty() || propertyId == null) { return Collections.emptyList(); } List<ItemFilter> removedFilters = new LinkedList<ItemFilter>(); for (Iterator<ItemFilter> iterator = getFilters().iterator(); iterator .hasNext();) { ItemFilter f = iterator.next(); if (f.appliesToProperty(propertyId)) { removedFilters.add(f); iterator.remove(); } } if (!removedFilters.isEmpty()) { filterAll(); return removedFilters; } return Collections.emptyList(); } // sorting /** * Returns the ItemSorter used for comparing items in a sort. See * {@link #setItemSorter(ItemSorter)} for more information. * * @return The ItemSorter used for comparing two items in a sort. */ protected ItemSorter getItemSorter() { return itemSorter; } /** * Sets the ItemSorter used for comparing items in a sort. The * {@link ItemSorter#compare(Object, Object)} method is called with item ids * to perform the sorting. A default ItemSorter is used if this is not * explicitly set. * * @param itemSorter * The ItemSorter used for comparing two items in a sort (not * null). */ protected void setItemSorter(ItemSorter itemSorter) { this.itemSorter = itemSorter; } /** * Sort base implementation to be used to implement {@link Sortable}. * * Subclasses should override this with a public * {@link #sort(Object[], boolean[])} method calling this superclass method * when implementing Sortable. * * @see com.vaadin.data.Container.Sortable#sort(java.lang.Object[], * boolean[]) */ protected void sort(Object[] propertyId, boolean[] ascending) { if (!(this instanceof Sortable)) { throw new UnsupportedOperationException( "Cannot sort a Container that does not implement Sortable"); } // Set up the item sorter for the sort operation getItemSorter().setSortProperties((Sortable) this, propertyId, ascending); // Perform the actual sort doSort(); // Post sort updates if (getFilteredItemIds() != null) { filterAll(); } else { fireItemSetChange(); } } /** * Perform the sorting of the data structures in the container. This is * invoked when the <code>itemSorter</code> has been prepared for the sort * operation. Typically this method calls * <code>Collections.sort(aCollection, getItemSorter())</code> on all arrays * (containing item ids) that need to be sorted. * */ protected void doSort() { Collections.sort(getAllItemIds(), getItemSorter()); } /** * Returns the sortable property identifiers for the container. Can be used * to implement {@link Sortable#getSortableContainerPropertyIds()}. */ protected Collection<?> getSortablePropertyIds() { LinkedList<Object> sortables = new LinkedList<Object>(); for (Object propertyId : getContainerPropertyIds()) { Class<?> propertyType = getType(propertyId); if (Comparable.class.isAssignableFrom(propertyType) || propertyType.isPrimitive()) { sortables.add(propertyId); } } return sortables; } // removing items /** * Removes all items from the internal data structures of this class. This * can be used to implement {@link #removeAllItems()} in subclasses. * * No notification is sent, the caller has to fire a suitable item set * change notification. */ protected void internalRemoveAllItems() { // Removes all Items getAllItemIds().clear(); if (getFilteredItemIds() != null) { getFilteredItemIds().clear(); } } /** * Removes a single item from the internal data structures of this class. * This can be used to implement {@link #removeItem(Object)} in subclasses. * * No notification is sent, the caller has to fire a suitable item set * change notification. * * @param itemId * the identifier of the item to remove * @return true if an item was successfully removed, false if failed to * remove or no such item */ protected boolean internalRemoveItem(Object itemId) { if (itemId == null) { return false; } boolean result = getAllItemIds().remove(itemId); if (result && getFilteredItemIds() != null) { getFilteredItemIds().remove(itemId); } return result; } // adding items /** * Adds the bean to all internal data structures at the given position. * Fails if an item with itemId is already in the container. Returns a the * item if it was added successfully, null otherwise. * * <p> * Caller should initiate filtering after calling this method. * </p> * * For internal use only - subclasses should use * {@link #internalAddItemAtEnd(Object, Item, boolean)}, * {@link #internalAddItemAt(int, Object, Item)} and * {@link #internalAddItemAfter(Object, Object, Item)} instead. * * @param position * The position at which the item should be inserted in the * unfiltered collection of items * @param itemId * The item identifier for the item to insert * @param item * The item to insert * * @return ITEMCLASS if the item was added successfully, null otherwise */ private ITEMCLASS internalAddAt(int position, ITEMIDTYPE itemId, ITEMCLASS item) { if (position < 0 || position > getAllItemIds().size() || itemId == null || item == null) { return null; } // Make sure that the item has not been added previously if (getAllItemIds().contains(itemId)) { return null; } // "filteredList" will be updated in filterAll() which should be invoked // by the caller after calling this method. getAllItemIds().add(position, itemId); registerNewItem(position, itemId, item); return item; } /** * Add an item at the end of the container, and perform filtering if * necessary. An event is fired if the filtered view changes. * * The new item is added at the beginning if previousItemId is null. * * @param newItemId * @param item * new item to add * @param filter * true to perform filtering and send event after adding the * item, false to skip them * @return item added or null if no item was added */ protected ITEMCLASS internalAddItemAtEnd(ITEMIDTYPE newItemId, ITEMCLASS item, boolean filter) { ITEMCLASS newItem = internalAddAt(getAllItemIds().size(), newItemId, item); if (newItem != null && filter) { // TODO filter only this item, use fireItemAdded() filterAll(); if (getFilteredItemIds() == null) { // TODO hack: does not detect change in filterAll() in this case fireItemAdded(indexOfId(newItemId), newItemId, item); } } return newItem; } /** * Add an item after a given (visible) item, and perform filtering. An event * is fired if the filtered view changes. * * The new item is added at the beginning if previousItemId is null. * * @param previousItemId * item id of a visible item after which to add the new item, or * null to add at the beginning * @param newItemId * @param item * new item to add * @return item added or null if no item was added */ protected ITEMCLASS internalAddItemAfter(ITEMIDTYPE previousItemId, ITEMIDTYPE newItemId, ITEMCLASS item) { // only add if the previous item is visible ITEMCLASS newItem = null; if (previousItemId == null) { newItem = internalAddAt(0, newItemId, item); } else if (containsId(previousItemId)) { newItem = internalAddAt( getAllItemIds().indexOf(previousItemId) + 1, newItemId, item); } if (newItem != null) { // TODO filter only this item, use fireItemAdded() filterAll(); if (getFilteredItemIds() == null) { // TODO hack: does not detect change in filterAll() in this case fireItemAdded(indexOfId(newItemId), newItemId, item); } } return newItem; } /** * Add an item at a given (visible) item index, and perform filtering. An * event is fired if the filtered view changes. * * @param index * position where to add the item (visible/view index) * @param newItemId * @return item added or null if no item was added * @return */ protected ITEMCLASS internalAddItemAt(int index, ITEMIDTYPE newItemId, ITEMCLASS item) { if (index < 0 || index > size()) { return null; } else if (index == 0) { // add before any item, visible or not return internalAddItemAfter(null, newItemId, item); } else { // if index==size(), adds immediately after last visible item return internalAddItemAfter(getIdByIndex(index - 1), newItemId, item); } } /** * Registers a new item as having been added to the container. This can * involve storing the item or any relevant information about it in internal * container-specific collections if necessary, as well as registering * listeners etc. * * The full identifier list in {@link AbstractInMemoryContainer} has already * been updated to reflect the new item when this method is called. * * @param position * @param itemId * @param item */ protected void registerNewItem(int position, ITEMIDTYPE itemId, ITEMCLASS item) { } // item set change notifications /** * Notify item set change listeners that an item has been added to the * container. * * Unless subclasses specify otherwise, the default notification indicates a * full refresh. * * @param postion * position of the added item in the view (if visible) * @param itemId * id of the added item * @param item * the added item */ protected void fireItemAdded(int position, ITEMIDTYPE itemId, ITEMCLASS item) { fireItemSetChange(); } /** * Notify item set change listeners that an item has been removed from the * container. * * Unless subclasses specify otherwise, the default notification indicates a * full refresh. * * @param postion * position of the removed item in the view prior to removal (if * was visible) * @param itemId * id of the removed item, of type {@link Object} to satisfy * {@link Container#removeItem(Object)} API */ protected void fireItemRemoved(int position, Object itemId) { fireItemSetChange(); } // visible and filtered item identifier lists /** * Returns the internal list of visible item identifiers after filtering. * * For internal use only. */ protected List<ITEMIDTYPE> getVisibleItemIds() { if (getFilteredItemIds() != null) { return getFilteredItemIds(); } else { return getAllItemIds(); } } /** * TODO Temporary internal helper method to set the internal list of * filtered item identifiers. * * @param filteredItemIds */ protected void setFilteredItemIds(List<ITEMIDTYPE> filteredItemIds) { this.filteredItemIds = filteredItemIds; } /** * TODO Temporary internal helper method to get the internal list of * filtered item identifiers. * * @return List<ITEMIDTYPE> */ protected List<ITEMIDTYPE> getFilteredItemIds() { return filteredItemIds; } /** * TODO Temporary internal helper method to set the internal list of all * item identifiers. Should not be used outside this class except for * implementing clone(), may disappear from future versions. * * @param allItemIds */ protected void setAllItemIds(List<ITEMIDTYPE> allItemIds) { this.allItemIds = allItemIds; } /** * TODO Temporary internal helper method to get the internal list of all * item identifiers. Should not be used outside this class without * exceptional justification, may disappear in future versions. * * @return List<ITEMIDTYPE> */ protected List<ITEMIDTYPE> getAllItemIds() { return allItemIds; } /** * TODO Temporary internal helper method to set the internal list of * filters. * * @param filters */ protected void setFilters(Set<ItemFilter> filters) { this.filters = filters; } /** * TODO Temporary internal helper method to get the internal list of * filters. * * @return Set<ItemFilter> */ protected Set<ItemFilter> getFilters() { return filters; } }
true
true
protected boolean doFilterContainer(boolean hasFilters) { if (!hasFilters) { boolean changed = getAllItemIds().size() != getVisibleItemIds() .size(); setFilteredItemIds(null); return changed; } // Reset filtered list List<ITEMIDTYPE> originalFilteredItemIds = getFilteredItemIds(); boolean wasUnfiltered = false; if (originalFilteredItemIds == null) { originalFilteredItemIds = Collections.emptyList(); wasUnfiltered = true; } setFilteredItemIds(new ListSet<ITEMIDTYPE>()); // Filter boolean equal = true; Iterator<ITEMIDTYPE> origIt = originalFilteredItemIds.iterator(); for (final Iterator<ITEMIDTYPE> i = getAllItemIds().iterator(); i .hasNext();) { final ITEMIDTYPE id = i.next(); if (passesFilters(id)) { // filtered list comes from the full list, can use == equal = equal && origIt.hasNext() && origIt.next() == id; getFilteredItemIds().add(id); } } return wasUnfiltered || !equal || origIt.hasNext(); }
protected boolean doFilterContainer(boolean hasFilters) { if (!hasFilters) { boolean changed = getAllItemIds().size() != getVisibleItemIds() .size(); setFilteredItemIds(null); return changed; } // Reset filtered list List<ITEMIDTYPE> originalFilteredItemIds = getFilteredItemIds(); boolean wasUnfiltered = false; if (originalFilteredItemIds == null) { originalFilteredItemIds = Collections.emptyList(); wasUnfiltered = true; } setFilteredItemIds(new ListSet<ITEMIDTYPE>()); // Filter boolean equal = true; Iterator<ITEMIDTYPE> origIt = originalFilteredItemIds.iterator(); for (final Iterator<ITEMIDTYPE> i = getAllItemIds().iterator(); i .hasNext();) { final ITEMIDTYPE id = i.next(); if (passesFilters(id)) { // filtered list comes from the full list, can use == equal = equal && origIt.hasNext() && origIt.next() == id; getFilteredItemIds().add(id); } } return (wasUnfiltered && !getAllItemIds().isEmpty()) || !equal || origIt.hasNext(); }
diff --git a/src/main/com/deftlabs/lock/mongo/DistributedLockSvcOptions.java b/src/main/com/deftlabs/lock/mongo/DistributedLockSvcOptions.java index 29d8e69..c64f20c 100644 --- a/src/main/com/deftlabs/lock/mongo/DistributedLockSvcOptions.java +++ b/src/main/com/deftlabs/lock/mongo/DistributedLockSvcOptions.java @@ -1,124 +1,124 @@ /** * Copyright 2011, Deft Labs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.deftlabs.lock.mongo; // Java import java.net.InetAddress; import java.net.UnknownHostException; /** * The global distributed lock service options/config. */ public class DistributedLockSvcOptions { /** * The basic constructor. This uses the following:<br /> * <ul> * <li>database name: mongo-distributed-lock * <li>collection name: locks * </ul> * */ public DistributedLockSvcOptions(final String pMongoUri) { this(pMongoUri, "mongo-distributed-lock", "locks", null); } /** * Constructor that allows the user to specify database and colleciton name. */ public DistributedLockSvcOptions( final String pMongoUri, final String pDbName, final String pCollectionName) { this(pMongoUri, pDbName, pCollectionName, null); } /** * Constructor that allows the user to specify database, colleciton and app name. * The app name should definetly be used if the db/collection names are shared by multiple * apps/systems (e.g., SomeCoolDataProcessor). */ public DistributedLockSvcOptions( final String pMongoUri, final String pDbName, final String pCollectionName, final String pAppName) { _mongoUri = pMongoUri; _dbName = pDbName; _collectionName = pCollectionName; _appName = pAppName; try { _hostAddress = InetAddress.getLocalHost().getHostAddress(); - } catch (final UnknownHostException e) { _hostname = null; } + } catch (final UnknownHostException e) { _hostAddress = null; } try { _hostname = InetAddress.getLocalHost().getHostName(); } catch (final UnknownHostException e) { _hostname = null; } } public String getMongoUri() { return _mongoUri; } public String getDbName() { return _dbName; } public String getCollectionName() { return _collectionName; } public String getAppName() { return _appName; } /** * True by default. Set to false to disable storing historical data. Lock data * is tracked when individual locks are locked, unlocked and (possibly) timed out. */ public void setEnableHistory(final boolean pV) { _enableHistory = pV; } public boolean getEnableHistory() { return _enableHistory; } /** * True by default. Set to fault to use a regular collection instead of a * capped collection for lock history. Entries will never be deleted if * this is not a capped collection. */ public void setHistoryIsCapped(final boolean pV) { _historyIsCapped = pV; } public boolean getHistoryIsCapped() { return _historyIsCapped; } /** * Set the size (in bytes) of the historical capped collection. The default * is 200MB. */ public void setHistorySize(final long pV) { _historySize = pV; } public long getHistorySize() { return _historySize; } public String getLibVersion() { return LIB_VERSION; } public String getHostname() { return _hostname; } public String getHostAddress() { return _hostAddress; } /** * The default collection name is: lockHistory. Override here. */ public void setHistoryCollectionName(final String pV) { _historyCollectionName = pV; } public String getHistoryCollectionName() { return _historyCollectionName; } private final String _mongoUri; private final String _dbName; private final String _collectionName; private String _historyCollectionName = "lockHistory"; private String _hostname; private String _hostAddress; private final String _appName; private static final String LIB_VERSION = "@LIB_VERSION@"; private boolean _enableHistory = true; private boolean _historyIsCapped = true; private long _historySize = 209715200; }
true
true
public DistributedLockSvcOptions( final String pMongoUri, final String pDbName, final String pCollectionName, final String pAppName) { _mongoUri = pMongoUri; _dbName = pDbName; _collectionName = pCollectionName; _appName = pAppName; try { _hostAddress = InetAddress.getLocalHost().getHostAddress(); } catch (final UnknownHostException e) { _hostname = null; } try { _hostname = InetAddress.getLocalHost().getHostName(); } catch (final UnknownHostException e) { _hostname = null; } }
public DistributedLockSvcOptions( final String pMongoUri, final String pDbName, final String pCollectionName, final String pAppName) { _mongoUri = pMongoUri; _dbName = pDbName; _collectionName = pCollectionName; _appName = pAppName; try { _hostAddress = InetAddress.getLocalHost().getHostAddress(); } catch (final UnknownHostException e) { _hostAddress = null; } try { _hostname = InetAddress.getLocalHost().getHostName(); } catch (final UnknownHostException e) { _hostname = null; } }
diff --git a/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/layout/LayoutUtil.java b/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/layout/LayoutUtil.java index 2ef8c7d46..3b8c6da8e 100644 --- a/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/layout/LayoutUtil.java +++ b/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/layout/LayoutUtil.java @@ -1,222 +1,222 @@ package org.eclipse.birt.report.engine.emitter.excel.layout; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.birt.report.engine.content.IContent; import org.eclipse.birt.report.engine.content.IForeignContent; import org.eclipse.birt.report.engine.content.IImageContent; import org.eclipse.birt.report.engine.content.IListContent; import org.eclipse.birt.report.engine.content.ITableContent; import org.eclipse.birt.report.engine.emitter.EmitterUtil; import org.eclipse.birt.report.engine.emitter.excel.ExcelUtil; import org.eclipse.birt.report.engine.ir.DimensionType; import org.eclipse.birt.report.engine.ir.ExtendedItemDesign; import org.eclipse.birt.report.engine.layout.emitter.Image; public class LayoutUtil { private static final Logger log = Logger.getLogger( LayoutUtil.class .getName( ) ); public static ColumnsInfo createTable( int col, int width ) { return new ColumnsInfo( col, width ); } public static ColumnsInfo createTable( IListContent list, int width ) { width = getElementWidth(list, width); int[] column = new int[] {width}; return new ColumnsInfo( column ); } public static ColumnsInfo createChart( IForeignContent content, int width ) { ExtendedItemDesign design = (ExtendedItemDesign) content .getGenerateBy( ); DimensionType value = design.getWidth( ); if ( value != null ) { width = getElementWidth( value, width ); } int[] column = new int[]{width}; return new ColumnsInfo( column ); } public static ColumnsInfo createImage( IImageContent image, int width ) { width = getImageWidth( image, width ); int[] column = new int[]{width}; return new ColumnsInfo( column ); } public static int getImageWidth( IImageContent image, int width ) { DimensionType value = image.getWidth( ); if ( value != null ) { width = getElementWidth( value, width ); } else { try { Image imageInfo = EmitterUtil.parseImage( image, image .getImageSource( ), image.getURI( ), image .getMIMEType( ), image.getExtension( ) ); width = (int) ( imageInfo.getWidth( ) * ExcelUtil.PX_PT ); } catch ( IOException e1 ) { log.log( Level.WARNING, e1.getLocalizedMessage( ) ); } } return width; } public static int getElementWidth( IContent content, int width ) { DimensionType value = content.getWidth( ); if ( value != null ) { return getElementWidth( value, width ); } return width; } private static int getElementWidth( DimensionType contentWdith, int width ) { try { width = Math.min( ExcelUtil.convertDimensionType( contentWdith, width ), width ); } catch ( Exception e ) { } return width; } public static int[] createFixedTable( ITableContent table, int tableWidth ) { int columnCount = table.getColumnCount( ); int[] columns = new int[columnCount]; int unassignedCount = 0; int totalAssigned = 0; for(int i = 0; i < columnCount; i++) { DimensionType value = table.getColumn( i ).getWidth( ); if( value == null) { columns[i] = -1; unassignedCount++; } else { columns[i] = ExcelUtil.convertDimensionType( value, tableWidth ); totalAssigned += columns[i]; } } if ( table.getWidth( ) == null && unassignedCount == 0 ) { return columns; } return EmitterUtil.resizeTableColumn( tableWidth, columns, unassignedCount, totalAssigned ); } public static ColumnsInfo createTable( ITableContent table, int width ) { int tableWidth = getElementWidth( table, width ); int columnCount = table.getColumnCount( ); if ( columnCount == 0 ) { return null; } int[] columns = new int[columnCount]; int unassignedCount = 0; int totalAssigned = 0; for ( int i = 0; i < columnCount; i++ ) { DimensionType value = table.getColumn( i ).getWidth( ); if ( value == null ) { columns[i] = -1; unassignedCount++; } else { if ( ExcelUtil.convertDimensionType( value, tableWidth ) > 576000 ) { System.out.println( "" ); } columns[i] = ExcelUtil.convertDimensionType( value, tableWidth ); totalAssigned += columns[i]; } } int leftWidth = tableWidth - totalAssigned; if ( leftWidth != 0 && unassignedCount == 0 ) { int totalResized = 0; for ( int i = 0; i < columnCount - 1; i++ ) { columns[i] = resize( columns[i], totalAssigned, leftWidth ); totalResized += columns[i]; } columns[columnCount - 1] = tableWidth - totalResized; } else if ( leftWidth < 0 && unassignedCount > 0 ) { int totalResized = 0; int lastAssignedIndex = 0; for ( int i = 0; i < columnCount; i++ ) { if ( columns[i] == -1 ) { - columns[1] = 0; + columns[i] = 0; } else { columns[i] = resize( columns[i], totalAssigned, leftWidth ); lastAssignedIndex = i; } totalResized += columns[i]; } columns[lastAssignedIndex] += tableWidth - totalResized; } else if ( leftWidth >= 0 && unassignedCount > 0 ) { int per = (int) leftWidth / unassignedCount; int index = 0; for ( int i = 0; i < columns.length; i++ ) { if ( columns[i] == -1 ) { columns[i] = per; index = i; } } columns[index] = leftWidth - per * ( unassignedCount - 1 ); } return new ColumnsInfo( columns ); } private static int resize( int width, int total, int left ) { return Math.round( width + (float) width / (float) total * left ); } }
true
true
public static ColumnsInfo createTable( ITableContent table, int width ) { int tableWidth = getElementWidth( table, width ); int columnCount = table.getColumnCount( ); if ( columnCount == 0 ) { return null; } int[] columns = new int[columnCount]; int unassignedCount = 0; int totalAssigned = 0; for ( int i = 0; i < columnCount; i++ ) { DimensionType value = table.getColumn( i ).getWidth( ); if ( value == null ) { columns[i] = -1; unassignedCount++; } else { if ( ExcelUtil.convertDimensionType( value, tableWidth ) > 576000 ) { System.out.println( "" ); } columns[i] = ExcelUtil.convertDimensionType( value, tableWidth ); totalAssigned += columns[i]; } } int leftWidth = tableWidth - totalAssigned; if ( leftWidth != 0 && unassignedCount == 0 ) { int totalResized = 0; for ( int i = 0; i < columnCount - 1; i++ ) { columns[i] = resize( columns[i], totalAssigned, leftWidth ); totalResized += columns[i]; } columns[columnCount - 1] = tableWidth - totalResized; } else if ( leftWidth < 0 && unassignedCount > 0 ) { int totalResized = 0; int lastAssignedIndex = 0; for ( int i = 0; i < columnCount; i++ ) { if ( columns[i] == -1 ) { columns[1] = 0; } else { columns[i] = resize( columns[i], totalAssigned, leftWidth ); lastAssignedIndex = i; } totalResized += columns[i]; } columns[lastAssignedIndex] += tableWidth - totalResized; } else if ( leftWidth >= 0 && unassignedCount > 0 ) { int per = (int) leftWidth / unassignedCount; int index = 0; for ( int i = 0; i < columns.length; i++ ) { if ( columns[i] == -1 ) { columns[i] = per; index = i; } } columns[index] = leftWidth - per * ( unassignedCount - 1 ); } return new ColumnsInfo( columns ); }
public static ColumnsInfo createTable( ITableContent table, int width ) { int tableWidth = getElementWidth( table, width ); int columnCount = table.getColumnCount( ); if ( columnCount == 0 ) { return null; } int[] columns = new int[columnCount]; int unassignedCount = 0; int totalAssigned = 0; for ( int i = 0; i < columnCount; i++ ) { DimensionType value = table.getColumn( i ).getWidth( ); if ( value == null ) { columns[i] = -1; unassignedCount++; } else { if ( ExcelUtil.convertDimensionType( value, tableWidth ) > 576000 ) { System.out.println( "" ); } columns[i] = ExcelUtil.convertDimensionType( value, tableWidth ); totalAssigned += columns[i]; } } int leftWidth = tableWidth - totalAssigned; if ( leftWidth != 0 && unassignedCount == 0 ) { int totalResized = 0; for ( int i = 0; i < columnCount - 1; i++ ) { columns[i] = resize( columns[i], totalAssigned, leftWidth ); totalResized += columns[i]; } columns[columnCount - 1] = tableWidth - totalResized; } else if ( leftWidth < 0 && unassignedCount > 0 ) { int totalResized = 0; int lastAssignedIndex = 0; for ( int i = 0; i < columnCount; i++ ) { if ( columns[i] == -1 ) { columns[i] = 0; } else { columns[i] = resize( columns[i], totalAssigned, leftWidth ); lastAssignedIndex = i; } totalResized += columns[i]; } columns[lastAssignedIndex] += tableWidth - totalResized; } else if ( leftWidth >= 0 && unassignedCount > 0 ) { int per = (int) leftWidth / unassignedCount; int index = 0; for ( int i = 0; i < columns.length; i++ ) { if ( columns[i] == -1 ) { columns[i] = per; index = i; } } columns[index] = leftWidth - per * ( unassignedCount - 1 ); } return new ColumnsInfo( columns ); }
diff --git a/org/xbill/DNS/ReverseMap.java b/org/xbill/DNS/ReverseMap.java index fb0aea9..8e83d10 100644 --- a/org/xbill/DNS/ReverseMap.java +++ b/org/xbill/DNS/ReverseMap.java @@ -1,122 +1,125 @@ // Copyright (c) 2003-2004 Brian Wellington ([email protected]) package org.xbill.DNS; import java.net.*; /** * A set functions designed to deal with DNS names used in reverse mappings. * For the IPv4 address a.b.c.d, the reverse map name is d.c.b.a.in-addr.arpa. * For an IPv6 address, the reverse map name is ...ip6.arpa. * * @author Brian Wellington */ public final class ReverseMap { private static Name inaddr4 = Name.fromConstantString("in-addr.arpa."); private static Name inaddr6 = Name.fromConstantString("ip6.arpa."); /* Otherwise the class could be instantiated */ private ReverseMap() {} /** * Creates a reverse map name corresponding to an address contained in * an array of 4 bytes (for an IPv4 address) or 16 bytes (for an IPv6 address). * @param addr The address from which to build a name. * @return The name corresponding to the address in the reverse map. */ public static Name fromAddress(byte [] addr) { if (addr.length != 4 && addr.length != 16) throw new IllegalArgumentException("array must contain " + "4 or 16 elements"); StringBuffer sb = new StringBuffer(); if (addr.length == 4) { for (int i = addr.length - 1; i >= 0; i--) { sb.append(addr[i] & 0xFF); if (i > 0) sb.append("."); } } else { int [] nibbles = new int[2]; for (int i = addr.length - 1; i >= 0; i--) { nibbles[0] = (addr[i] & 0xFF) >> 4; nibbles[1] = (addr[i] & 0xFF) & 0xF; for (int j = nibbles.length - 1; j >= 0; j--) { - sb.append(nibbles[j]); + sb.append(Integer.toHexString(nibbles[j])); if (i > 0 || j > 0) sb.append("."); } } } try { - return Name.fromString(sb.toString(), inaddr4); + if (addr.length == 4) + return Name.fromString(sb.toString(), inaddr4); + else + return Name.fromString(sb.toString(), inaddr6); } catch (TextParseException e) { throw new IllegalStateException("name cannot be invalid"); } } /** * Creates a reverse map name corresponding to an address contained in * an array of 4 integers between 0 and 255 (for an IPv4 address) or 16 * integers between 0 and 255 (for an IPv6 address). * @param addr The address from which to build a name. * @return The name corresponding to the address in the reverse map. */ public static Name fromAddress(int [] addr) { byte [] bytes = new byte[addr.length]; for (int i = 0; i < addr.length; i++) { if (addr[i] < 0 || addr[i] > 0xFF) throw new IllegalArgumentException("array must " + "contain values " + "between 0 and 255"); bytes[i] = (byte) addr[i]; } return fromAddress(bytes); } /** * Creates a reverse map name corresponding to an address contained in * an InetAddress. * @param addr The address from which to build a name. * @return The name corresponding to the address in the reverse map. */ public static Name fromAddress(InetAddress addr) { return fromAddress(addr.getAddress()); } /** * Creates a reverse map name corresponding to an address contained in * a String. * @param addr The address from which to build a name. * @return The name corresponding to the address in the reverse map. * @throws UnknownHostException The string does not contain a valid address. */ public static Name fromAddress(String addr, int family) throws UnknownHostException { byte [] array = Address.toByteArray(addr, family); if (array == null) throw new UnknownHostException("Invalid IP address"); return fromAddress(array); } /** * Creates a reverse map name corresponding to an address contained in * a String. * @param addr The address from which to build a name. * @return The name corresponding to the address in the reverse map. * @throws UnknownHostException The string does not contain a valid address. */ public static Name fromAddress(String addr) throws UnknownHostException { return fromAddress(addr, Address.IPv4); } }
false
true
public static Name fromAddress(byte [] addr) { if (addr.length != 4 && addr.length != 16) throw new IllegalArgumentException("array must contain " + "4 or 16 elements"); StringBuffer sb = new StringBuffer(); if (addr.length == 4) { for (int i = addr.length - 1; i >= 0; i--) { sb.append(addr[i] & 0xFF); if (i > 0) sb.append("."); } } else { int [] nibbles = new int[2]; for (int i = addr.length - 1; i >= 0; i--) { nibbles[0] = (addr[i] & 0xFF) >> 4; nibbles[1] = (addr[i] & 0xFF) & 0xF; for (int j = nibbles.length - 1; j >= 0; j--) { sb.append(nibbles[j]); if (i > 0 || j > 0) sb.append("."); } } } try { return Name.fromString(sb.toString(), inaddr4); } catch (TextParseException e) { throw new IllegalStateException("name cannot be invalid"); } }
public static Name fromAddress(byte [] addr) { if (addr.length != 4 && addr.length != 16) throw new IllegalArgumentException("array must contain " + "4 or 16 elements"); StringBuffer sb = new StringBuffer(); if (addr.length == 4) { for (int i = addr.length - 1; i >= 0; i--) { sb.append(addr[i] & 0xFF); if (i > 0) sb.append("."); } } else { int [] nibbles = new int[2]; for (int i = addr.length - 1; i >= 0; i--) { nibbles[0] = (addr[i] & 0xFF) >> 4; nibbles[1] = (addr[i] & 0xFF) & 0xF; for (int j = nibbles.length - 1; j >= 0; j--) { sb.append(Integer.toHexString(nibbles[j])); if (i > 0 || j > 0) sb.append("."); } } } try { if (addr.length == 4) return Name.fromString(sb.toString(), inaddr4); else return Name.fromString(sb.toString(), inaddr6); } catch (TextParseException e) { throw new IllegalStateException("name cannot be invalid"); } }
diff --git a/sitebricks-mail/src/main/java/com/google/sitebricks/mail/MailClientHandler.java b/sitebricks-mail/src/main/java/com/google/sitebricks/mail/MailClientHandler.java index a95af21..8e0f961 100644 --- a/sitebricks-mail/src/main/java/com/google/sitebricks/mail/MailClientHandler.java +++ b/sitebricks-mail/src/main/java/com/google/sitebricks/mail/MailClientHandler.java @@ -1,412 +1,414 @@ package com.google.sitebricks.mail; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.sitebricks.util.BoundedDiscardingList; import com.google.sitebricks.util.JmxUtil; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.softee.management.annotation.MBean; import org.softee.management.annotation.ManagedAttribute; import org.softee.management.annotation.ManagedOperation; import org.softee.management.helper.MBeanRegistration; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A command/response handler for a single mail connection/user. * * @author [email protected] (Dhanji R. Prasanna) */ @MBean class MailClientHandler extends SimpleChannelHandler { private static final Logger log = LoggerFactory.getLogger(MailClientHandler.class); private static final Set<String> logAllMessagesForUsers = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()); public static final String CAPABILITY_PREFIX = "* CAPABILITY"; static final Pattern AUTH_SUCCESS_REGEX = Pattern.compile("[.] OK .*@.* \\(Success\\)", Pattern.CASE_INSENSITIVE); static final Pattern COMMAND_FAILED_REGEX = Pattern.compile("^[.] (NO|BAD) (.*)", Pattern.CASE_INSENSITIVE); static final Pattern MESSAGE_COULDNT_BE_FETCHED_REGEX = Pattern.compile("^\\d+ no some messages could not be fetched \\(failure\\)\\s*", Pattern.CASE_INSENSITIVE); static final Pattern SYSTEM_ERROR_REGEX = Pattern.compile("[*]\\s*bye\\s*system\\s*error\\s*", Pattern.CASE_INSENSITIVE); static final Pattern IDLE_ENDED_REGEX = Pattern.compile(".* OK IDLE terminated \\(success\\)\\s*", Pattern.CASE_INSENSITIVE); static final Pattern IDLE_EXISTS_REGEX = Pattern.compile("\\* (\\d+) exists\\s*", Pattern.CASE_INSENSITIVE); static final Pattern IDLE_EXPUNGE_REGEX = Pattern.compile("\\* (\\d+) expunge\\s*", Pattern.CASE_INSENSITIVE); private final Idler idler; private final MailClientConfig config; private final CountDownLatch loginSuccess = new CountDownLatch(1); private volatile List<String> capabilities; private volatile FolderObserver observer; final AtomicBoolean idleRequested = new AtomicBoolean(); final AtomicBoolean idleAcknowledged = new AtomicBoolean(); private final Object idleMutex = new Object(); // Panic button. private volatile boolean halt = false; private final LinkedBlockingDeque<Error> errorStack = new LinkedBlockingDeque<Error>(); private final Queue<CommandCompletion> completions = new ConcurrentLinkedQueue<CommandCompletion>(); private volatile PushedData pushedData; private final BoundedDiscardingList<String> commandTrace = new BoundedDiscardingList<String>(10); private final BoundedDiscardingList<String> wireTrace = new BoundedDiscardingList<String>(25); private final MBeanRegistration mBeanRegistration; private final InputBuffer inputBuffer = new InputBuffer(); public MailClientHandler(Idler idler, MailClientConfig config) { this.idler = idler; this.config = config; mBeanRegistration = JmxUtil.registerMBean(this, "com.google.sitebricks", "MailClientHandler", config.getUsername()); } @ManagedOperation public void logAllMessages(boolean b) { log.info("logAllMessagesForUsers[" + config.getUsername() + "] = " + b); if (b) logAllMessagesForUsers.add(config.getUsername()); else logAllMessagesForUsers.remove(config.getUsername()); } @ManagedAttribute public Set<String> getLogAllMessagesFor() { return logAllMessagesForUsers; } @ManagedAttribute public List<String> getCommandTrace() { return commandTrace.list(); } public List<String> getWireTrace() { return wireTrace.list(); } @ManagedAttribute public boolean isLoggedIn() { return loginSuccess.getCount() == 0; } private static class PushedData { volatile boolean idleExitSent = false; // guarded by idleMutex. final SortedSet<Integer> pushAdds = Sets.<Integer>newTreeSet(); // guarded by idleMutex. final SortedSet<Integer> pushRemoves = Sets.<Integer>newTreeSet(); } // DO NOT synchronize! public void enqueue(CommandCompletion completion) { completions.add(completion); commandTrace.add(new Date().toString() + " " + completion.toString()); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { String message = e.getMessage().toString(); for (String input : inputBuffer.processMessage(message)) { processMessage(input); } } private void processMessage(String message) throws Exception { if (logAllMessagesForUsers.contains(config.getUsername())) { log.info("IMAP [{}]: {}", config.getUsername(), message); } wireTrace.add(message); log.trace(message); if (SYSTEM_ERROR_REGEX.matcher(message).matches() || ". NO [ALERT] Account exceeded command or bandwidth limits. (Failure)".equalsIgnoreCase( message.trim())) { log.warn("{} disconnected by IMAP Server due to system error: {}", config.getUsername(), message); disconnectAbnormally(message); return; } try { if (halt) { log.error("Mail client for {} is halted but continues to receive messages, ignoring!", config.getUsername()); return; } if (loginSuccess.getCount() > 0) { if (message.startsWith(CAPABILITY_PREFIX)) { this.capabilities = Arrays.asList( message.substring(CAPABILITY_PREFIX.length() + 1).split("[ ]+")); return; } else if (AUTH_SUCCESS_REGEX.matcher(message).matches()) { log.info("Authentication success for user {}", config.getUsername()); loginSuccess.countDown(); } else { Matcher matcher = COMMAND_FAILED_REGEX.matcher(message); if (matcher.find()) { // WARNING: DO NOT COUNTDOWN THE LOGIN LATCH ON FAILURE!!! log.warn("Authentication failed for {} due to: {}", config.getUsername(), message); errorStack.push(new Error(null /* logins have no completion */, extractError(matcher), wireTrace.list())); disconnectAbnormally(message); } } return; } // Copy to local var as the value can change underneath us. FolderObserver observer = this.observer; if (idleRequested.get() || idleAcknowledged.get()) { synchronized (idleMutex) { if (IDLE_ENDED_REGEX.matcher(message).matches()) { idleRequested.compareAndSet(true, false); idleAcknowledged.set(false); // Now fire the events. PushedData data = pushedData; pushedData = null; idler.idleEnd(); observer.changed(data.pushAdds.isEmpty() ? null : data.pushAdds, data.pushRemoves.isEmpty() ? null : data.pushRemoves); return; } // Queue up any push notifications to publish to the client in a second. Matcher existsMatcher = IDLE_EXISTS_REGEX.matcher(message); boolean matched = false; if (existsMatcher.matches()) { int number = Integer.parseInt(existsMatcher.group(1)); pushedData.pushAdds.add(number); pushedData.pushRemoves.remove(number); matched = true; } else { Matcher expungeMatcher = IDLE_EXPUNGE_REGEX.matcher(message); if (expungeMatcher.matches()) { int number = Integer.parseInt(expungeMatcher.group(1)); pushedData.pushRemoves.add(number); pushedData.pushAdds.remove(number); matched = true; } } // Stop idling, when we get the idle ended message (next cycle) we can publish what's been gathered. - if (matched && !pushedData.idleExitSent) { - idler.done(); - pushedData.idleExitSent = true; + if (matched) { + if(!pushedData.idleExitSent) { + idler.done(); + pushedData.idleExitSent = true; + } return; } } } complete(message); } catch (Exception ex) { CommandCompletion completion = completions.poll(); if (completion != null) completion.error(message, ex); else { log.error("Strange exception during mail processing (no completions available!): {}", message, ex); errorStack.push(new Error(null, "No completions available!", wireTrace.list())); } throw ex; } } private void disconnectAbnormally(String message) { try { halt(); // Disconnect abnormally. The user code should reconnect using the mail client. errorStack.push(new Error(completions.poll(), message, wireTrace.list())); idler.disconnect(); } finally { disconnected(); } } private String extractError(Matcher matcher) { return (matcher.groupCount()) > 1 ? matcher.group(2) : matcher.group(); } /** * This is synchronized to ensure that we process the queue serially. */ private synchronized void complete(String message) { // This is a weird problem with writing stuff while idling. Need to investigate it more, but // for now just ignore it. if (MESSAGE_COULDNT_BE_FETCHED_REGEX.matcher(message).matches()) { log.warn("Some messages in the batch could not be fetched for {}\n" + "---cmd---\n{}\n---wire---\n{}\n---end---\n", new Object[] { config.getUsername(), getCommandTrace(), getWireTrace() }); errorStack.push(new Error(completions.peek(), message, wireTrace.list())); throw new RuntimeException("Some messages in the batch could not be fetched for user " + config.getUsername()); } CommandCompletion completion = completions.peek(); if (completion == null) { if ("+ idling".equalsIgnoreCase(message)) { synchronized (idleMutex) { idler.idleStart(); log.trace("IDLE entered."); idleAcknowledged.set(true); } } else { log.error("Could not find the completion for message {} (Was it ever issued?)", message); errorStack.push(new Error(null, "No completion found!", wireTrace.list())); } return; } if (completion.complete(message)) { completions.poll(); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { log.error("Exception caught! Disconnecting...", e.getCause()); disconnectAbnormally(e.getCause().getMessage()); } public List<String> getCapabilities() { return capabilities; } boolean awaitLogin() { try { if (!loginSuccess.await(10L, TimeUnit.SECONDS)) { disconnectAbnormally("Timed out waiting for login response"); throw new RuntimeException("Timed out waiting for login response"); } return isLoggedIn(); } catch (InterruptedException e) { errorStack.push(new Error(null, e.getMessage(), wireTrace.list())); throw new RuntimeException("Interruption while awaiting server login", e); } } MailClient.WireError lastError() { return errorStack.peek() != null ? errorStack.pop() : null; } List<String> getLastTrace() { return wireTrace.list(); } /** * Registers a FolderObserver to receive events happening with a particular * folder. Typically an IMAP IDLE feature. If called multiple times, will * overwrite the currently set observer. */ void observe(FolderObserver observer) { synchronized (idleMutex) { this.observer = observer; pushedData = new PushedData(); idleAcknowledged.set(false); } } void halt() { halt = true; } public boolean isHalted() { return halt; } public void disconnected() { JmxUtil.unregister(mBeanRegistration); } static class Error implements MailClient.WireError { final CommandCompletion completion; final String error; final List<String> wireTrace; Error(CommandCompletion completion, String error, List<String> wireTrace) { this.completion = completion; this.error = error; this.wireTrace = wireTrace; } @Override public String message() { return error; } @Override public List<String> trace() { return wireTrace; } @Override public String expected() { return completion == null ? null : completion.toString(); } @Override public String toString() { StringBuilder sout = new StringBuilder(); sout.append("WireError: "); sout.append("Completion=").append(completion); sout.append(", Error: ").append(error); sout.append(", Trace:\n"); for (String s : wireTrace) { sout.append(" ").append(s).append("\n"); } return sout.toString(); } } @VisibleForTesting static class InputBuffer { volatile private StringBuilder buffer = new StringBuilder(); @VisibleForTesting List<String> processMessage(String message) { // Split leaves a trailing empty line if there's a terminating newline. ArrayList<String> split = Lists.newArrayList(message.split("\r?\n", -1)); Preconditions.checkArgument(split.size() > 0); synchronized (this) { buffer.append(split.get(0)); if (split.size() == 1) // no newlines. return ImmutableList.of(); split.set(0, buffer.toString()); buffer = new StringBuilder().append(split.remove(split.size() - 1)); } return split; } } }
true
true
private void processMessage(String message) throws Exception { if (logAllMessagesForUsers.contains(config.getUsername())) { log.info("IMAP [{}]: {}", config.getUsername(), message); } wireTrace.add(message); log.trace(message); if (SYSTEM_ERROR_REGEX.matcher(message).matches() || ". NO [ALERT] Account exceeded command or bandwidth limits. (Failure)".equalsIgnoreCase( message.trim())) { log.warn("{} disconnected by IMAP Server due to system error: {}", config.getUsername(), message); disconnectAbnormally(message); return; } try { if (halt) { log.error("Mail client for {} is halted but continues to receive messages, ignoring!", config.getUsername()); return; } if (loginSuccess.getCount() > 0) { if (message.startsWith(CAPABILITY_PREFIX)) { this.capabilities = Arrays.asList( message.substring(CAPABILITY_PREFIX.length() + 1).split("[ ]+")); return; } else if (AUTH_SUCCESS_REGEX.matcher(message).matches()) { log.info("Authentication success for user {}", config.getUsername()); loginSuccess.countDown(); } else { Matcher matcher = COMMAND_FAILED_REGEX.matcher(message); if (matcher.find()) { // WARNING: DO NOT COUNTDOWN THE LOGIN LATCH ON FAILURE!!! log.warn("Authentication failed for {} due to: {}", config.getUsername(), message); errorStack.push(new Error(null /* logins have no completion */, extractError(matcher), wireTrace.list())); disconnectAbnormally(message); } } return; } // Copy to local var as the value can change underneath us. FolderObserver observer = this.observer; if (idleRequested.get() || idleAcknowledged.get()) { synchronized (idleMutex) { if (IDLE_ENDED_REGEX.matcher(message).matches()) { idleRequested.compareAndSet(true, false); idleAcknowledged.set(false); // Now fire the events. PushedData data = pushedData; pushedData = null; idler.idleEnd(); observer.changed(data.pushAdds.isEmpty() ? null : data.pushAdds, data.pushRemoves.isEmpty() ? null : data.pushRemoves); return; } // Queue up any push notifications to publish to the client in a second. Matcher existsMatcher = IDLE_EXISTS_REGEX.matcher(message); boolean matched = false; if (existsMatcher.matches()) { int number = Integer.parseInt(existsMatcher.group(1)); pushedData.pushAdds.add(number); pushedData.pushRemoves.remove(number); matched = true; } else { Matcher expungeMatcher = IDLE_EXPUNGE_REGEX.matcher(message); if (expungeMatcher.matches()) { int number = Integer.parseInt(expungeMatcher.group(1)); pushedData.pushRemoves.add(number); pushedData.pushAdds.remove(number); matched = true; } } // Stop idling, when we get the idle ended message (next cycle) we can publish what's been gathered. if (matched && !pushedData.idleExitSent) { idler.done(); pushedData.idleExitSent = true; return; } } } complete(message); } catch (Exception ex) { CommandCompletion completion = completions.poll(); if (completion != null) completion.error(message, ex); else { log.error("Strange exception during mail processing (no completions available!): {}", message, ex); errorStack.push(new Error(null, "No completions available!", wireTrace.list())); } throw ex; } }
private void processMessage(String message) throws Exception { if (logAllMessagesForUsers.contains(config.getUsername())) { log.info("IMAP [{}]: {}", config.getUsername(), message); } wireTrace.add(message); log.trace(message); if (SYSTEM_ERROR_REGEX.matcher(message).matches() || ". NO [ALERT] Account exceeded command or bandwidth limits. (Failure)".equalsIgnoreCase( message.trim())) { log.warn("{} disconnected by IMAP Server due to system error: {}", config.getUsername(), message); disconnectAbnormally(message); return; } try { if (halt) { log.error("Mail client for {} is halted but continues to receive messages, ignoring!", config.getUsername()); return; } if (loginSuccess.getCount() > 0) { if (message.startsWith(CAPABILITY_PREFIX)) { this.capabilities = Arrays.asList( message.substring(CAPABILITY_PREFIX.length() + 1).split("[ ]+")); return; } else if (AUTH_SUCCESS_REGEX.matcher(message).matches()) { log.info("Authentication success for user {}", config.getUsername()); loginSuccess.countDown(); } else { Matcher matcher = COMMAND_FAILED_REGEX.matcher(message); if (matcher.find()) { // WARNING: DO NOT COUNTDOWN THE LOGIN LATCH ON FAILURE!!! log.warn("Authentication failed for {} due to: {}", config.getUsername(), message); errorStack.push(new Error(null /* logins have no completion */, extractError(matcher), wireTrace.list())); disconnectAbnormally(message); } } return; } // Copy to local var as the value can change underneath us. FolderObserver observer = this.observer; if (idleRequested.get() || idleAcknowledged.get()) { synchronized (idleMutex) { if (IDLE_ENDED_REGEX.matcher(message).matches()) { idleRequested.compareAndSet(true, false); idleAcknowledged.set(false); // Now fire the events. PushedData data = pushedData; pushedData = null; idler.idleEnd(); observer.changed(data.pushAdds.isEmpty() ? null : data.pushAdds, data.pushRemoves.isEmpty() ? null : data.pushRemoves); return; } // Queue up any push notifications to publish to the client in a second. Matcher existsMatcher = IDLE_EXISTS_REGEX.matcher(message); boolean matched = false; if (existsMatcher.matches()) { int number = Integer.parseInt(existsMatcher.group(1)); pushedData.pushAdds.add(number); pushedData.pushRemoves.remove(number); matched = true; } else { Matcher expungeMatcher = IDLE_EXPUNGE_REGEX.matcher(message); if (expungeMatcher.matches()) { int number = Integer.parseInt(expungeMatcher.group(1)); pushedData.pushRemoves.add(number); pushedData.pushAdds.remove(number); matched = true; } } // Stop idling, when we get the idle ended message (next cycle) we can publish what's been gathered. if (matched) { if(!pushedData.idleExitSent) { idler.done(); pushedData.idleExitSent = true; } return; } } } complete(message); } catch (Exception ex) { CommandCompletion completion = completions.poll(); if (completion != null) completion.error(message, ex); else { log.error("Strange exception during mail processing (no completions available!): {}", message, ex); errorStack.push(new Error(null, "No completions available!", wireTrace.list())); } throw ex; } }
diff --git a/src/com/fsck/k9/activity/MessageList.java b/src/com/fsck/k9/activity/MessageList.java index 4c1cf489f..3b73f3dee 100644 --- a/src/com/fsck/k9/activity/MessageList.java +++ b/src/com/fsck/k9/activity/MessageList.java @@ -1,1386 +1,1389 @@ package com.fsck.k9.activity; import java.util.Collection; import java.util.List; import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences.Editor; import android.content.res.Configuration; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentManager.OnBackStackChangedListener; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.fsck.k9.Account; import com.fsck.k9.Account.SortType; import com.fsck.k9.K9; import com.fsck.k9.Preferences; import com.fsck.k9.R; import com.fsck.k9.activity.misc.SwipeGestureDetector.OnSwipeGestureListener; import com.fsck.k9.activity.setup.AccountSettings; import com.fsck.k9.activity.setup.FolderSettings; import com.fsck.k9.activity.setup.Prefs; import com.fsck.k9.crypto.PgpData; import com.fsck.k9.fragment.MessageListFragment; import com.fsck.k9.fragment.MessageViewFragment; import com.fsck.k9.fragment.MessageListFragment.MessageListFragmentListener; import com.fsck.k9.fragment.MessageViewFragment.MessageViewFragmentListener; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.store.StorageManager; import com.fsck.k9.search.LocalSearch; import com.fsck.k9.search.SearchAccount; import com.fsck.k9.search.SearchSpecification; import com.fsck.k9.search.SearchSpecification.Attribute; import com.fsck.k9.search.SearchSpecification.Searchfield; import com.fsck.k9.search.SearchSpecification.SearchCondition; import com.fsck.k9.view.MessageHeader; import com.fsck.k9.view.MessageTitleView; import de.cketti.library.changelog.ChangeLog; /** * MessageList is the primary user interface for the program. This Activity * shows a list of messages. * From this Activity the user can perform all standard message operations. */ public class MessageList extends K9FragmentActivity implements MessageListFragmentListener, MessageViewFragmentListener, OnBackStackChangedListener, OnSwipeGestureListener { // for this activity private static final String EXTRA_SEARCH = "search"; private static final String EXTRA_NO_THREADING = "no_threading"; private static final String ACTION_SHORTCUT = "shortcut"; private static final String EXTRA_SPECIAL_FOLDER = "special_folder"; private static final String EXTRA_MESSAGE_REFERENCE = "message_reference"; // used for remote search public static final String EXTRA_SEARCH_ACCOUNT = "com.fsck.k9.search_account"; private static final String EXTRA_SEARCH_FOLDER = "com.fsck.k9.search_folder"; private static final String STATE_DISPLAY_MODE = "displayMode"; public static void actionDisplaySearch(Context context, SearchSpecification search, boolean noThreading, boolean newTask) { actionDisplaySearch(context, search, noThreading, newTask, true); } public static void actionDisplaySearch(Context context, SearchSpecification search, boolean noThreading, boolean newTask, boolean clearTop) { context.startActivity( intentDisplaySearch(context, search, noThreading, newTask, clearTop)); } public static Intent intentDisplaySearch(Context context, SearchSpecification search, boolean noThreading, boolean newTask, boolean clearTop) { Intent intent = new Intent(context, MessageList.class); intent.putExtra(EXTRA_SEARCH, search); intent.putExtra(EXTRA_NO_THREADING, noThreading); if (clearTop) { intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } if (newTask) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } return intent; } public static Intent shortcutIntent(Context context, String specialFolder) { Intent intent = new Intent(context, MessageList.class); intent.setAction(ACTION_SHORTCUT); intent.putExtra(EXTRA_SPECIAL_FOLDER, specialFolder); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } public static Intent actionDisplayMessageIntent(Context context, MessageReference messageReference) { Intent intent = new Intent(context, MessageList.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(EXTRA_MESSAGE_REFERENCE, messageReference); return intent; } public static Intent actionHandleNotificationIntent(Context context, MessageReference messageReference) { Intent intent = actionDisplayMessageIntent(context, messageReference); intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } private enum DisplayMode { MESSAGE_LIST, MESSAGE_VIEW, SPLIT_VIEW } private StorageManager.StorageListener mStorageListener = new StorageListenerImplementation(); private ActionBar mActionBar; private View mActionBarMessageList; private View mActionBarMessageView; private MessageTitleView mActionBarSubject; private TextView mActionBarTitle; private TextView mActionBarSubTitle; private TextView mActionBarUnread; private Menu mMenu; private ViewGroup mMessageListContainer; private ViewGroup mMessageViewContainer; private View mMessageViewPlaceHolder; private MessageListFragment mMessageListFragment; private MessageViewFragment mMessageViewFragment; private Account mAccount; private String mFolderName; private LocalSearch mSearch; private boolean mSingleFolderMode; private boolean mSingleAccountMode; private ProgressBar mActionBarProgress; private MenuItem mMenuButtonCheckMail; private View mActionButtonIndeterminateProgress; /** * {@code true} if the message list should be displayed as flat list (i.e. no threading) * regardless whether or not message threading was enabled in the settings. This is used for * filtered views, e.g. when only displaying the unread messages in a folder. */ private boolean mNoThreading; private DisplayMode mDisplayMode; private MessageReference mMessageReference; /** * {@code true} when the message list was displayed once. This is used in * {@link #onBackPressed()} to decide whether to go from the message view to the message list or * finish the activity. */ private boolean mMessageListWasDisplayed = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (UpgradeDatabases.actionUpgradeDatabases(this, getIntent())) { finish(); return; } setContentView(R.layout.split_message_list); initializeActionBar(); // Enable gesture detection for MessageLists setupGestureDetector(this); decodeExtras(getIntent()); findFragments(); initializeDisplayMode(savedInstanceState); initializeLayout(); initializeFragments(); displayViews(); ChangeLog cl = new ChangeLog(this); if (cl.isFirstRun()) { cl.getLogDialog().show(); } } @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); removeMessageListFragment(); removeMessageViewFragment(); decodeExtras(intent); initializeDisplayMode(null); initializeFragments(); displayViews(); } /** * Get references to existing fragments if the activity was restarted. */ private void findFragments() { FragmentManager fragmentManager = getSupportFragmentManager(); mMessageListFragment = (MessageListFragment) fragmentManager.findFragmentById( R.id.message_list_container); mMessageViewFragment = (MessageViewFragment) fragmentManager.findFragmentById( R.id.message_view_container); } /** * Create fragment instances if necessary. * * @see #findFragments() */ private void initializeFragments() { FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.addOnBackStackChangedListener(this); boolean hasMessageListFragment = (mMessageListFragment != null); if (!hasMessageListFragment) { FragmentTransaction ft = fragmentManager.beginTransaction(); mMessageListFragment = MessageListFragment.newInstance(mSearch, false, (K9.isThreadedViewEnabled() && !mNoThreading)); ft.add(R.id.message_list_container, mMessageListFragment); ft.commit(); } // Check if the fragment wasn't restarted and has a MessageReference in the arguments. If // so, open the referenced message. if (!hasMessageListFragment && mMessageViewFragment == null && mMessageReference != null) { openMessage(mMessageReference); } } /** * Set the initial display mode (message list, message view, or split view). * * <p><strong>Note:</strong> * This method has to be called after {@link #findFragments()} because the result depends on * the availability of a {@link MessageViewFragment} instance. * </p> * * @param savedInstanceState * The saved instance state that was passed to the activity as argument to * {@link #onCreate(Bundle)}. May be {@code null}. */ private void initializeDisplayMode(Bundle savedInstanceState) { if (savedInstanceState != null) { mDisplayMode = (DisplayMode) savedInstanceState.getSerializable(STATE_DISPLAY_MODE); } else { boolean displayMessage = (mMessageReference != null); mDisplayMode = (displayMessage) ? DisplayMode.MESSAGE_VIEW : DisplayMode.MESSAGE_LIST; } switch (K9.getSplitViewMode()) { case ALWAYS: { mDisplayMode = DisplayMode.SPLIT_VIEW; break; } case NEVER: { // Use the value set at the beginning of this method. break; } case WHEN_IN_LANDSCAPE: { int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_LANDSCAPE) { mDisplayMode = DisplayMode.SPLIT_VIEW; } else if (mMessageViewFragment != null || mDisplayMode == DisplayMode.MESSAGE_VIEW) { mDisplayMode = DisplayMode.MESSAGE_VIEW; } else { mDisplayMode = DisplayMode.MESSAGE_LIST; } break; } } } private void initializeLayout() { mMessageListContainer = (ViewGroup) findViewById(R.id.message_list_container); mMessageViewContainer = (ViewGroup) findViewById(R.id.message_view_container); mMessageViewPlaceHolder = getLayoutInflater().inflate(R.layout.empty_message_view, null); } private void displayViews() { switch (mDisplayMode) { case MESSAGE_LIST: { showMessageList(); break; } case MESSAGE_VIEW: { showMessageView(); break; } case SPLIT_VIEW: { mMessageListWasDisplayed = true; findViewById(R.id.message_list_divider).setVisibility(View.VISIBLE); if (mMessageViewFragment == null) { showMessageViewPlaceHolder(); } else { MessageReference activeMessage = mMessageViewFragment.getMessageReference(); if (activeMessage != null) { mMessageListFragment.setActiveMessage(activeMessage); } } break; } } } private void decodeExtras(Intent intent) { String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action)) { Uri uri = intent.getData(); List<String> segmentList = uri.getPathSegments(); String accountId = segmentList.get(0); Collection<Account> accounts = Preferences.getPreferences(this).getAvailableAccounts(); for (Account account : accounts) { if (String.valueOf(account.getAccountNumber()).equals(accountId)) { mMessageReference = new MessageReference(); mMessageReference.accountUuid = account.getUuid(); mMessageReference.folderName = segmentList.get(1); mMessageReference.uid = segmentList.get(2); break; } } } else if (ACTION_SHORTCUT.equals(action)) { // Handle shortcut intents String specialFolder = intent.getStringExtra(EXTRA_SPECIAL_FOLDER); if (SearchAccount.UNIFIED_INBOX.equals(specialFolder)) { mSearch = SearchAccount.createUnifiedInboxAccount(this).getRelatedSearch(); } else if (SearchAccount.ALL_MESSAGES.equals(specialFolder)) { mSearch = SearchAccount.createAllMessagesAccount(this).getRelatedSearch(); } } else if (intent.getStringExtra(SearchManager.QUERY) != null) { // check if this intent comes from the system search ( remote ) if (Intent.ACTION_SEARCH.equals(intent.getAction())) { //Query was received from Search Dialog String query = intent.getStringExtra(SearchManager.QUERY); mSearch = new LocalSearch(getString(R.string.search_results)); mSearch.setManualSearch(true); mNoThreading = true; mSearch.or(new SearchCondition(Searchfield.SENDER, Attribute.CONTAINS, query)); mSearch.or(new SearchCondition(Searchfield.SUBJECT, Attribute.CONTAINS, query)); mSearch.or(new SearchCondition(Searchfield.MESSAGE_CONTENTS, Attribute.CONTAINS, query)); Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA); if (appData != null) { mSearch.addAccountUuid(appData.getString(EXTRA_SEARCH_ACCOUNT)); // searches started from a folder list activity will provide an account, but no folder if (appData.getString(EXTRA_SEARCH_FOLDER) != null) { mSearch.addAllowedFolder(appData.getString(EXTRA_SEARCH_FOLDER)); } } else { mSearch.addAccountUuid(LocalSearch.ALL_ACCOUNTS); } } } else { // regular LocalSearch object was passed mSearch = intent.getParcelableExtra(EXTRA_SEARCH); mNoThreading = intent.getBooleanExtra(EXTRA_NO_THREADING, false); } if (mMessageReference == null) { mMessageReference = intent.getParcelableExtra(EXTRA_MESSAGE_REFERENCE); } if (mMessageReference != null) { mSearch = new LocalSearch(); mSearch.addAccountUuid(mMessageReference.accountUuid); mSearch.addAllowedFolder(mMessageReference.folderName); } String[] accountUuids = mSearch.getAccountUuids(); mSingleAccountMode = (accountUuids.length == 1 && !mSearch.searchAllAccounts()); mSingleFolderMode = mSingleAccountMode && (mSearch.getFolderNames().size() == 1); if (mSingleAccountMode) { Preferences prefs = Preferences.getPreferences(getApplicationContext()); mAccount = prefs.getAccount(accountUuids[0]); if (mAccount != null && !mAccount.isAvailable(this)) { Log.i(K9.LOG_TAG, "not opening MessageList of unavailable account"); onAccountUnavailable(); return; } } if (mSingleFolderMode) { mFolderName = mSearch.getFolderNames().get(0); } // now we know if we are in single account mode and need a subtitle mActionBarSubTitle.setVisibility((!mSingleFolderMode) ? View.GONE : View.VISIBLE); } @Override public void onPause() { super.onPause(); StorageManager.getInstance(getApplication()).removeListener(mStorageListener); } @Override public void onResume() { super.onResume(); if (!(this instanceof Search)) { //necessary b/c no guarantee Search.onStop will be called before MessageList.onResume //when returning from search results Search.setActive(false); } if (mAccount != null && !mAccount.isAvailable(this)) { onAccountUnavailable(); return; } StorageManager.getInstance(getApplication()).addListener(mStorageListener); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(STATE_DISPLAY_MODE, mDisplayMode); } private void initializeActionBar() { mActionBar = getSupportActionBar(); mActionBar.setDisplayShowCustomEnabled(true); mActionBar.setCustomView(R.layout.actionbar_custom); View customView = mActionBar.getCustomView(); mActionBarMessageList = customView.findViewById(R.id.actionbar_message_list); mActionBarMessageView = customView.findViewById(R.id.actionbar_message_view); mActionBarSubject = (MessageTitleView) customView.findViewById(R.id.message_title_view); mActionBarTitle = (TextView) customView.findViewById(R.id.actionbar_title_first); mActionBarSubTitle = (TextView) customView.findViewById(R.id.actionbar_title_sub); mActionBarUnread = (TextView) customView.findViewById(R.id.actionbar_unread_count); mActionBarProgress = (ProgressBar) customView.findViewById(R.id.actionbar_progress); mActionButtonIndeterminateProgress = getLayoutInflater().inflate(R.layout.actionbar_indeterminate_progress_actionview, null); mActionBar.setDisplayHomeAsUpEnabled(true); } @Override public boolean dispatchKeyEvent(KeyEvent event) { boolean ret = false; if (KeyEvent.ACTION_DOWN == event.getAction()) { ret = onCustomKeyDown(event.getKeyCode(), event); } if (!ret) { ret = super.dispatchKeyEvent(event); } return ret; } @Override public void onBackPressed() { if (mDisplayMode == DisplayMode.MESSAGE_VIEW && mMessageListWasDisplayed) { showMessageList(); } else { super.onBackPressed(); } } /** * Handle hotkeys * * <p> * This method is called by {@link #dispatchKeyEvent(KeyEvent)} before any view had the chance * to consume this key event. * </p> * * @param keyCode * The value in {@code event.getKeyCode()}. * @param event * Description of the key event. * * @return {@code true} if this event was consumed. */ public boolean onCustomKeyDown(final int keyCode, final KeyEvent event) { - // Shortcuts that work no matter what is selected switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: { if (mMessageViewFragment != null && mDisplayMode != DisplayMode.MESSAGE_LIST && K9.useVolumeKeysForNavigationEnabled()) { showPreviousMessage(); return true; } else if (mDisplayMode != DisplayMode.MESSAGE_VIEW && K9.useVolumeKeysForListNavigationEnabled()) { mMessageListFragment.onMoveUp(); return true; } break; } case KeyEvent.KEYCODE_VOLUME_DOWN: { if (mMessageViewFragment != null && mDisplayMode != DisplayMode.MESSAGE_LIST && K9.useVolumeKeysForNavigationEnabled()) { showNextMessage(); return true; } else if (mDisplayMode != DisplayMode.MESSAGE_VIEW && K9.useVolumeKeysForListNavigationEnabled()) { mMessageListFragment.onMoveDown(); return true; } break; } case KeyEvent.KEYCODE_C: { mMessageListFragment.onCompose(); return true; } case KeyEvent.KEYCODE_Q: { onShowFolderList(); return true; } case KeyEvent.KEYCODE_O: { mMessageListFragment.onCycleSort(); return true; } case KeyEvent.KEYCODE_I: { mMessageListFragment.onReverseSort(); return true; } case KeyEvent.KEYCODE_DEL: case KeyEvent.KEYCODE_D: { if (mDisplayMode == DisplayMode.MESSAGE_LIST) { mMessageListFragment.onDelete(); } else if (mMessageViewFragment != null) { mMessageViewFragment.onDelete(); } return true; } case KeyEvent.KEYCODE_S: { mMessageListFragment.toggleMessageSelect(); return true; } case KeyEvent.KEYCODE_G: { if (mDisplayMode == DisplayMode.MESSAGE_LIST) { mMessageListFragment.onToggleFlagged(); } else if (mMessageViewFragment != null) { mMessageViewFragment.onToggleFlagged(); } return true; } case KeyEvent.KEYCODE_M: { if (mDisplayMode == DisplayMode.MESSAGE_LIST) { mMessageListFragment.onMove(); } else if (mMessageViewFragment != null) { mMessageViewFragment.onMove(); } return true; } case KeyEvent.KEYCODE_V: { if (mDisplayMode == DisplayMode.MESSAGE_LIST) { mMessageListFragment.onArchive(); } else if (mMessageViewFragment != null) { mMessageViewFragment.onArchive(); } return true; } case KeyEvent.KEYCODE_Y: { if (mDisplayMode == DisplayMode.MESSAGE_LIST) { mMessageListFragment.onCopy(); } else if (mMessageViewFragment != null) { mMessageViewFragment.onCopy(); } return true; } case KeyEvent.KEYCODE_Z: { if (mDisplayMode == DisplayMode.MESSAGE_LIST) { mMessageListFragment.onToggleRead(); } else if (mMessageViewFragment != null) { mMessageViewFragment.onToggleRead(); } return true; } case KeyEvent.KEYCODE_F: { if (mMessageViewFragment != null) { mMessageViewFragment.onForward(); } return true; } case KeyEvent.KEYCODE_A: { if (mMessageViewFragment != null) { mMessageViewFragment.onReplyAll(); } return true; } case KeyEvent.KEYCODE_R: { if (mMessageViewFragment != null) { mMessageViewFragment.onReply(); } return true; } case KeyEvent.KEYCODE_J: case KeyEvent.KEYCODE_P: { - showPreviousMessage(); + if (mMessageViewFragment != null) { + showPreviousMessage(); + } return true; } case KeyEvent.KEYCODE_N: case KeyEvent.KEYCODE_K: { - showNextMessage(); + if (mMessageViewFragment != null) { + showNextMessage(); + } return true; } /* FIXME case KeyEvent.KEYCODE_Z: { mMessageViewFragment.zoom(event); return true; }*/ case KeyEvent.KEYCODE_H: { Toast toast = Toast.makeText(this, R.string.message_list_help_key, Toast.LENGTH_LONG); toast.show(); return true; } } return false; } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { // Swallow these events too to avoid the audible notification of a volume change if (K9.useVolumeKeysForListNavigationEnabled()) { if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Swallowed key up."); return true; } } return super.onKeyUp(keyCode, event); } private void onAccounts() { Accounts.listAccounts(this); finish(); } private void onShowFolderList() { FolderList.actionHandleAccount(this, mAccount); finish(); } private void onEditPrefs() { Prefs.actionPrefs(this); } private void onEditAccount() { AccountSettings.actionSettings(this, mAccount); } @Override public boolean onSearchRequested() { return mMessageListFragment.onSearchRequested(); } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); switch (itemId) { case android.R.id.home: { goBack(); return true; } case R.id.compose: { mMessageListFragment.onCompose(); return true; } case R.id.toggle_message_view_theme: { onToggleTheme(); return true; } // MessageList case R.id.check_mail: { mMessageListFragment.checkMail(); return true; } case R.id.set_sort_date: { mMessageListFragment.changeSort(SortType.SORT_DATE); return true; } case R.id.set_sort_arrival: { mMessageListFragment.changeSort(SortType.SORT_ARRIVAL); return true; } case R.id.set_sort_subject: { mMessageListFragment.changeSort(SortType.SORT_SUBJECT); return true; } // case R.id.set_sort_sender: { // mMessageListFragment.changeSort(SortType.SORT_SENDER); // return true; // } case R.id.set_sort_flag: { mMessageListFragment.changeSort(SortType.SORT_FLAGGED); return true; } case R.id.set_sort_unread: { mMessageListFragment.changeSort(SortType.SORT_UNREAD); return true; } case R.id.set_sort_attach: { mMessageListFragment.changeSort(SortType.SORT_ATTACHMENT); return true; } case R.id.select_all: { mMessageListFragment.selectAll(); return true; } case R.id.app_settings: { onEditPrefs(); return true; } case R.id.account_settings: { onEditAccount(); return true; } case R.id.search: { mMessageListFragment.onSearchRequested(); return true; } case R.id.search_remote: { mMessageListFragment.onRemoteSearch(); return true; } // MessageView case R.id.delete: { mMessageViewFragment.onDelete(); return true; } case R.id.reply: { mMessageViewFragment.onReply(); return true; } case R.id.reply_all: { mMessageViewFragment.onReplyAll(); return true; } case R.id.forward: { mMessageViewFragment.onForward(); return true; } case R.id.share: { mMessageViewFragment.onSendAlternate(); return true; } case R.id.toggle_unread: { mMessageViewFragment.onToggleRead(); return true; } case R.id.archive: { mMessageViewFragment.onArchive(); return true; } case R.id.spam: { mMessageViewFragment.onSpam(); return true; } case R.id.move: { mMessageViewFragment.onMove(); return true; } case R.id.copy: { mMessageViewFragment.onCopy(); return true; } case R.id.select_text: { mMessageViewFragment.onSelectText(); return true; } } if (!mSingleFolderMode) { // None of the options after this point are "safe" for search results //TODO: This is not true for "unread" and "starred" searches in regular folders return false; } switch (itemId) { case R.id.send_messages: { mMessageListFragment.onSendPendingMessages(); return true; } case R.id.folder_settings: { if (mFolderName != null) { FolderSettings.actionSettings(this, mAccount, mFolderName); } return true; } case R.id.expunge: { mMessageListFragment.onExpunge(); return true; } default: { return super.onOptionsItemSelected(item); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getSupportMenuInflater().inflate(R.menu.message_list_option, menu); mMenu = menu; mMenuButtonCheckMail= menu.findItem(R.id.check_mail); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { configureMenu(menu); return true; } /** * Hide menu items not appropriate for the current context. * * <p><strong>Note:</strong> * Please adjust the comments in {@code res/menu/message_list_option.xml} if you change the * visibility of a menu item in this method. * </p> * * @param menu * The {@link Menu} instance that should be modified. May be {@code null}; in that case * the method does nothing and immediately returns. */ private void configureMenu(Menu menu) { if (menu == null) { return; } // Set visibility of account/folder settings menu items if (mMessageListFragment == null) { menu.findItem(R.id.account_settings).setVisible(false); menu.findItem(R.id.folder_settings).setVisible(false); } else { menu.findItem(R.id.account_settings).setVisible( mMessageListFragment.isSingleAccountMode()); menu.findItem(R.id.folder_settings).setVisible( mMessageListFragment.isSingleFolderMode()); } /* * Set visibility of menu items related to the message view */ if (mMessageViewFragment == null) { menu.findItem(R.id.delete).setVisible(false); menu.findItem(R.id.single_message_options).setVisible(false); menu.findItem(R.id.archive).setVisible(false); menu.findItem(R.id.spam).setVisible(false); menu.findItem(R.id.move).setVisible(false); menu.findItem(R.id.copy).setVisible(false); menu.findItem(R.id.toggle_unread).setVisible(false); menu.findItem(R.id.select_text).setVisible(false); menu.findItem(R.id.toggle_message_view_theme).setVisible(false); } else { // Set title of menu item to switch to dark/light theme MenuItem toggleTheme = menu.findItem(R.id.toggle_message_view_theme); if (K9.getK9MessageViewTheme() == K9.THEME_DARK) { toggleTheme.setTitle(R.string.message_view_theme_action_light); } else { toggleTheme.setTitle(R.string.message_view_theme_action_dark); } toggleTheme.setVisible(true); // Set title of menu item to toggle the read state of the currently displayed message if (mMessageViewFragment.isMessageRead()) { menu.findItem(R.id.toggle_unread).setTitle(R.string.mark_as_unread_action); } else { menu.findItem(R.id.toggle_unread).setTitle(R.string.mark_as_read_action); } menu.findItem(R.id.copy).setVisible(mMessageViewFragment.isCopyCapable()); if (mMessageViewFragment.isMoveCapable()) { menu.findItem(R.id.move).setVisible(true); menu.findItem(R.id.archive).setVisible(mMessageViewFragment.canMessageBeArchived()); menu.findItem(R.id.spam).setVisible(mMessageViewFragment.canMessageBeMovedToSpam()); } else { menu.findItem(R.id.move).setVisible(false); menu.findItem(R.id.archive).setVisible(false); menu.findItem(R.id.spam).setVisible(false); } } /* * Set visibility of menu items related to the message list */ // Hide both search menu items by default and enable one when appropriate menu.findItem(R.id.search).setVisible(false); menu.findItem(R.id.search_remote).setVisible(false); if (mDisplayMode == DisplayMode.MESSAGE_VIEW || mMessageListFragment == null) { menu.findItem(R.id.check_mail).setVisible(false); menu.findItem(R.id.set_sort).setVisible(false); menu.findItem(R.id.select_all).setVisible(false); menu.findItem(R.id.send_messages).setVisible(false); menu.findItem(R.id.expunge).setVisible(false); } else { menu.findItem(R.id.set_sort).setVisible(true); menu.findItem(R.id.select_all).setVisible(true); if (!mMessageListFragment.isSingleAccountMode()) { menu.findItem(R.id.expunge).setVisible(false); menu.findItem(R.id.check_mail).setVisible(false); menu.findItem(R.id.send_messages).setVisible(false); } else { menu.findItem(R.id.send_messages).setVisible(mMessageListFragment.isOutbox()); if (mMessageListFragment.isRemoteFolder()) { menu.findItem(R.id.check_mail).setVisible(true); menu.findItem(R.id.expunge).setVisible( mMessageListFragment.isAccountExpungeCapable()); } else { menu.findItem(R.id.check_mail).setVisible(false); menu.findItem(R.id.expunge).setVisible(false); } } // If this is an explicit local search, show the option to search on the server if (!mMessageListFragment.isRemoteSearch() && mMessageListFragment.isRemoteSearchAllowed()) { menu.findItem(R.id.search_remote).setVisible(true); } else if (!mMessageListFragment.isManualSearch()) { menu.findItem(R.id.search).setVisible(true); } } } protected void onAccountUnavailable() { finish(); // TODO inform user about account unavailability using Toast Accounts.listAccounts(this); } public void setActionBarTitle(String title) { mActionBarTitle.setText(title); } public void setActionBarSubTitle(String subTitle) { mActionBarSubTitle.setText(subTitle); } public void setActionBarUnread(int unread) { if (unread == 0) { mActionBarUnread.setVisibility(View.GONE); } else { mActionBarUnread.setVisibility(View.VISIBLE); mActionBarUnread.setText(Integer.toString(unread)); } } @Override public void setMessageListTitle(String title) { setActionBarTitle(title); } @Override public void setMessageListSubTitle(String subTitle) { setActionBarSubTitle(subTitle); } @Override public void setUnreadCount(int unread) { setActionBarUnread(unread); } @Override public void setMessageListProgress(int progress) { setSupportProgress(progress); } @Override public void openMessage(MessageReference messageReference) { Preferences prefs = Preferences.getPreferences(getApplicationContext()); Account account = prefs.getAccount(messageReference.accountUuid); String folderName = messageReference.folderName; if (folderName.equals(account.getDraftsFolderName())) { MessageCompose.actionEditDraft(this, messageReference); } else { mMessageViewContainer.removeView(mMessageViewPlaceHolder); MessageViewFragment fragment = MessageViewFragment.newInstance(messageReference); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.message_view_container, fragment); mMessageViewFragment = fragment; ft.commit(); if (mDisplayMode == DisplayMode.SPLIT_VIEW) { mMessageListFragment.setActiveMessage(messageReference); } else { showMessageView(); } } } @Override public void onResendMessage(Message message) { MessageCompose.actionEditDraft(this, message.makeMessageReference()); } @Override public void onForward(Message message) { MessageCompose.actionForward(this, message.getFolder().getAccount(), message, null); } @Override public void onReply(Message message) { MessageCompose.actionReply(this, message.getFolder().getAccount(), message, false, null); } @Override public void onReplyAll(Message message) { MessageCompose.actionReply(this, message.getFolder().getAccount(), message, true, null); } @Override public void onCompose(Account account) { MessageCompose.actionCompose(this, account); } @Override public void showMoreFromSameSender(String senderAddress) { LocalSearch tmpSearch = new LocalSearch("From " + senderAddress); tmpSearch.addAccountUuids(mSearch.getAccountUuids()); tmpSearch.and(Searchfield.SENDER, senderAddress, Attribute.CONTAINS); MessageListFragment fragment = MessageListFragment.newInstance(tmpSearch, false, false); addMessageListFragment(fragment, true); } @Override public void onBackStackChanged() { FragmentManager fragmentManager = getSupportFragmentManager(); mMessageListFragment = (MessageListFragment) fragmentManager.findFragmentById( R.id.message_list_container); mMessageViewFragment = (MessageViewFragment) fragmentManager.findFragmentById( R.id.message_view_container); if (mDisplayMode == DisplayMode.SPLIT_VIEW) { showMessageViewPlaceHolder(); } configureMenu(mMenu); } @Override public void onSwipeRightToLeft(MotionEvent e1, MotionEvent e2) { if (mMessageListFragment != null && mDisplayMode != DisplayMode.MESSAGE_VIEW) { mMessageListFragment.onSwipeRightToLeft(e1, e2); } } @Override public void onSwipeLeftToRight(MotionEvent e1, MotionEvent e2) { if (mMessageListFragment != null && mDisplayMode != DisplayMode.MESSAGE_VIEW) { mMessageListFragment.onSwipeLeftToRight(e1, e2); } } private final class StorageListenerImplementation implements StorageManager.StorageListener { @Override public void onUnmount(String providerId) { if (mAccount != null && providerId.equals(mAccount.getLocalStorageProviderId())) { runOnUiThread(new Runnable() { @Override public void run() { onAccountUnavailable(); } }); } } @Override public void onMount(String providerId) { // no-op } } private void addMessageListFragment(MessageListFragment fragment, boolean addToBackStack) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.message_list_container, fragment); if (addToBackStack) ft.addToBackStack(null); mMessageListFragment = fragment; ft.commit(); } @Override public boolean startSearch(Account account, String folderName) { // If this search was started from a MessageList of a single folder, pass along that folder info // so that we can enable remote search. if (account != null && folderName != null) { final Bundle appData = new Bundle(); appData.putString(EXTRA_SEARCH_ACCOUNT, account.getUuid()); appData.putString(EXTRA_SEARCH_FOLDER, folderName); startSearch(null, false, appData, false); } else { // TODO Handle the case where we're searching from within a search result. startSearch(null, false, null, false); } return true; } @Override public void showThread(Account account, String folderName, long threadRootId) { showMessageViewPlaceHolder(); LocalSearch tmpSearch = new LocalSearch(); tmpSearch.addAccountUuid(account.getUuid()); tmpSearch.and(Searchfield.THREAD_ID, String.valueOf(threadRootId), Attribute.EQUALS); MessageListFragment fragment = MessageListFragment.newInstance(tmpSearch, true, false); addMessageListFragment(fragment, true); } private void showMessageViewPlaceHolder() { removeMessageViewFragment(); // Add placeholder view if necessary if (mMessageViewPlaceHolder.getParent() == null) { mMessageViewContainer.addView(mMessageViewPlaceHolder); } mMessageListFragment.setActiveMessage(null); } /** * Remove MessageViewFragment if necessary. */ private void removeMessageViewFragment() { if (mMessageViewFragment != null) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.remove(mMessageViewFragment); mMessageViewFragment = null; ft.commit(); showDefaultTitleView(); } } private void removeMessageListFragment() { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.remove(mMessageListFragment); mMessageListFragment = null; ft.commit(); } @Override public void remoteSearchStarted() { // Remove action button for remote search configureMenu(mMenu); } @Override public void goBack() { FragmentManager fragmentManager = getSupportFragmentManager(); if (mDisplayMode == DisplayMode.MESSAGE_VIEW) { showMessageList(); } else if (fragmentManager.getBackStackEntryCount() > 0) { fragmentManager.popBackStack(); } else if (mMessageListFragment.isManualSearch()) { finish(); } else if (!mSingleFolderMode) { onAccounts(); } else { onShowFolderList(); } } @Override public void enableActionBarProgress(boolean enable) { if (mMenuButtonCheckMail != null && mMenuButtonCheckMail.isVisible()) { mActionBarProgress.setVisibility(ProgressBar.GONE); if (enable) { mMenuButtonCheckMail .setActionView(mActionButtonIndeterminateProgress); } else { mMenuButtonCheckMail.setActionView(null); } } else { if (mMenuButtonCheckMail != null) mMenuButtonCheckMail.setActionView(null); if (enable) { mActionBarProgress.setVisibility(ProgressBar.VISIBLE); } else { mActionBarProgress.setVisibility(ProgressBar.GONE); } } } private void restartActivity() { // restart the current activity, so that the theme change can be applied if (Build.VERSION.SDK_INT < 11) { Intent intent = getIntent(); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); finish(); overridePendingTransition(0, 0); // disable animations to speed up the switch startActivity(intent); overridePendingTransition(0, 0); } else { recreate(); } } @Override public void displayMessageSubject(String subject) { if (mDisplayMode == DisplayMode.MESSAGE_VIEW) { mActionBarSubject.setText(subject); } } @Override public void onReply(Message message, PgpData pgpData) { MessageCompose.actionReply(this, mAccount, message, false, pgpData.getDecryptedData()); finish(); } @Override public void onReplyAll(Message message, PgpData pgpData) { MessageCompose.actionReply(this, mAccount, message, true, pgpData.getDecryptedData()); finish(); } @Override public void onForward(Message mMessage, PgpData mPgpData) { MessageCompose.actionForward(this, mAccount, mMessage, mPgpData.getDecryptedData()); finish(); } @Override public void showNextMessageOrReturn() { if (K9.messageViewReturnToList()) { if (mDisplayMode == DisplayMode.SPLIT_VIEW) { showMessageViewPlaceHolder(); } else { showMessageList(); } } else { showNextMessage(); } } @Override public void setProgress(boolean enable) { setSupportProgressBarIndeterminateVisibility(enable); } @Override public void messageHeaderViewAvailable(MessageHeader header) { mActionBarSubject.setMessageHeader(header); } private void showNextMessage() { MessageReference ref = mMessageViewFragment.getMessageReference(); if (ref != null) { mMessageListFragment.openNext(ref); } } private void showPreviousMessage() { MessageReference ref = mMessageViewFragment.getMessageReference(); if (ref != null) { mMessageListFragment.openPrevious(ref); } } private void showMessageList() { mMessageListWasDisplayed = true; mDisplayMode = DisplayMode.MESSAGE_LIST; mMessageViewContainer.setVisibility(View.GONE); mMessageListContainer.setVisibility(View.VISIBLE); removeMessageViewFragment(); mMessageListFragment.setActiveMessage(null); showDefaultTitleView(); } private void showMessageView() { mDisplayMode = DisplayMode.MESSAGE_VIEW; mMessageListContainer.setVisibility(View.GONE); mMessageViewContainer.setVisibility(View.VISIBLE); showMessageTitleView(); } @Override public void updateMenu() { configureMenu(mMenu); } @Override public void disableDeleteAction() { mMenu.findItem(R.id.delete).setEnabled(false); } private void onToggleTheme() { if (K9.getK9MessageViewTheme() == K9.THEME_DARK) { K9.setK9MessageViewTheme(K9.THEME_LIGHT); } else { K9.setK9MessageViewTheme(K9.THEME_DARK); } new Thread(new Runnable() { @Override public void run() { Context appContext = getApplicationContext(); Preferences prefs = Preferences.getPreferences(appContext); Editor editor = prefs.getPreferences().edit(); K9.save(editor); editor.commit(); } }).start(); restartActivity(); } private void showDefaultTitleView() { mActionBarMessageView.setVisibility(View.GONE); mActionBarMessageList.setVisibility(View.VISIBLE); if (mMessageListFragment != null) { mMessageListFragment.updateTitle(); } mActionBarSubject.setMessageHeader(null); } private void showMessageTitleView() { mActionBarMessageList.setVisibility(View.GONE); mActionBarMessageView.setVisibility(View.VISIBLE); if (mMessageViewFragment != null) { mMessageViewFragment.updateTitle(); } } }
false
true
public boolean onCustomKeyDown(final int keyCode, final KeyEvent event) { // Shortcuts that work no matter what is selected switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: { if (mMessageViewFragment != null && mDisplayMode != DisplayMode.MESSAGE_LIST && K9.useVolumeKeysForNavigationEnabled()) { showPreviousMessage(); return true; } else if (mDisplayMode != DisplayMode.MESSAGE_VIEW && K9.useVolumeKeysForListNavigationEnabled()) { mMessageListFragment.onMoveUp(); return true; } break; } case KeyEvent.KEYCODE_VOLUME_DOWN: { if (mMessageViewFragment != null && mDisplayMode != DisplayMode.MESSAGE_LIST && K9.useVolumeKeysForNavigationEnabled()) { showNextMessage(); return true; } else if (mDisplayMode != DisplayMode.MESSAGE_VIEW && K9.useVolumeKeysForListNavigationEnabled()) { mMessageListFragment.onMoveDown(); return true; } break; } case KeyEvent.KEYCODE_C: { mMessageListFragment.onCompose(); return true; } case KeyEvent.KEYCODE_Q: { onShowFolderList(); return true; } case KeyEvent.KEYCODE_O: { mMessageListFragment.onCycleSort(); return true; } case KeyEvent.KEYCODE_I: { mMessageListFragment.onReverseSort(); return true; } case KeyEvent.KEYCODE_DEL: case KeyEvent.KEYCODE_D: { if (mDisplayMode == DisplayMode.MESSAGE_LIST) { mMessageListFragment.onDelete(); } else if (mMessageViewFragment != null) { mMessageViewFragment.onDelete(); } return true; } case KeyEvent.KEYCODE_S: { mMessageListFragment.toggleMessageSelect(); return true; } case KeyEvent.KEYCODE_G: { if (mDisplayMode == DisplayMode.MESSAGE_LIST) { mMessageListFragment.onToggleFlagged(); } else if (mMessageViewFragment != null) { mMessageViewFragment.onToggleFlagged(); } return true; } case KeyEvent.KEYCODE_M: { if (mDisplayMode == DisplayMode.MESSAGE_LIST) { mMessageListFragment.onMove(); } else if (mMessageViewFragment != null) { mMessageViewFragment.onMove(); } return true; } case KeyEvent.KEYCODE_V: { if (mDisplayMode == DisplayMode.MESSAGE_LIST) { mMessageListFragment.onArchive(); } else if (mMessageViewFragment != null) { mMessageViewFragment.onArchive(); } return true; } case KeyEvent.KEYCODE_Y: { if (mDisplayMode == DisplayMode.MESSAGE_LIST) { mMessageListFragment.onCopy(); } else if (mMessageViewFragment != null) { mMessageViewFragment.onCopy(); } return true; } case KeyEvent.KEYCODE_Z: { if (mDisplayMode == DisplayMode.MESSAGE_LIST) { mMessageListFragment.onToggleRead(); } else if (mMessageViewFragment != null) { mMessageViewFragment.onToggleRead(); } return true; } case KeyEvent.KEYCODE_F: { if (mMessageViewFragment != null) { mMessageViewFragment.onForward(); } return true; } case KeyEvent.KEYCODE_A: { if (mMessageViewFragment != null) { mMessageViewFragment.onReplyAll(); } return true; } case KeyEvent.KEYCODE_R: { if (mMessageViewFragment != null) { mMessageViewFragment.onReply(); } return true; } case KeyEvent.KEYCODE_J: case KeyEvent.KEYCODE_P: { showPreviousMessage(); return true; } case KeyEvent.KEYCODE_N: case KeyEvent.KEYCODE_K: { showNextMessage(); return true; } /* FIXME case KeyEvent.KEYCODE_Z: { mMessageViewFragment.zoom(event); return true; }*/ case KeyEvent.KEYCODE_H: { Toast toast = Toast.makeText(this, R.string.message_list_help_key, Toast.LENGTH_LONG); toast.show(); return true; } } return false; }
public boolean onCustomKeyDown(final int keyCode, final KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: { if (mMessageViewFragment != null && mDisplayMode != DisplayMode.MESSAGE_LIST && K9.useVolumeKeysForNavigationEnabled()) { showPreviousMessage(); return true; } else if (mDisplayMode != DisplayMode.MESSAGE_VIEW && K9.useVolumeKeysForListNavigationEnabled()) { mMessageListFragment.onMoveUp(); return true; } break; } case KeyEvent.KEYCODE_VOLUME_DOWN: { if (mMessageViewFragment != null && mDisplayMode != DisplayMode.MESSAGE_LIST && K9.useVolumeKeysForNavigationEnabled()) { showNextMessage(); return true; } else if (mDisplayMode != DisplayMode.MESSAGE_VIEW && K9.useVolumeKeysForListNavigationEnabled()) { mMessageListFragment.onMoveDown(); return true; } break; } case KeyEvent.KEYCODE_C: { mMessageListFragment.onCompose(); return true; } case KeyEvent.KEYCODE_Q: { onShowFolderList(); return true; } case KeyEvent.KEYCODE_O: { mMessageListFragment.onCycleSort(); return true; } case KeyEvent.KEYCODE_I: { mMessageListFragment.onReverseSort(); return true; } case KeyEvent.KEYCODE_DEL: case KeyEvent.KEYCODE_D: { if (mDisplayMode == DisplayMode.MESSAGE_LIST) { mMessageListFragment.onDelete(); } else if (mMessageViewFragment != null) { mMessageViewFragment.onDelete(); } return true; } case KeyEvent.KEYCODE_S: { mMessageListFragment.toggleMessageSelect(); return true; } case KeyEvent.KEYCODE_G: { if (mDisplayMode == DisplayMode.MESSAGE_LIST) { mMessageListFragment.onToggleFlagged(); } else if (mMessageViewFragment != null) { mMessageViewFragment.onToggleFlagged(); } return true; } case KeyEvent.KEYCODE_M: { if (mDisplayMode == DisplayMode.MESSAGE_LIST) { mMessageListFragment.onMove(); } else if (mMessageViewFragment != null) { mMessageViewFragment.onMove(); } return true; } case KeyEvent.KEYCODE_V: { if (mDisplayMode == DisplayMode.MESSAGE_LIST) { mMessageListFragment.onArchive(); } else if (mMessageViewFragment != null) { mMessageViewFragment.onArchive(); } return true; } case KeyEvent.KEYCODE_Y: { if (mDisplayMode == DisplayMode.MESSAGE_LIST) { mMessageListFragment.onCopy(); } else if (mMessageViewFragment != null) { mMessageViewFragment.onCopy(); } return true; } case KeyEvent.KEYCODE_Z: { if (mDisplayMode == DisplayMode.MESSAGE_LIST) { mMessageListFragment.onToggleRead(); } else if (mMessageViewFragment != null) { mMessageViewFragment.onToggleRead(); } return true; } case KeyEvent.KEYCODE_F: { if (mMessageViewFragment != null) { mMessageViewFragment.onForward(); } return true; } case KeyEvent.KEYCODE_A: { if (mMessageViewFragment != null) { mMessageViewFragment.onReplyAll(); } return true; } case KeyEvent.KEYCODE_R: { if (mMessageViewFragment != null) { mMessageViewFragment.onReply(); } return true; } case KeyEvent.KEYCODE_J: case KeyEvent.KEYCODE_P: { if (mMessageViewFragment != null) { showPreviousMessage(); } return true; } case KeyEvent.KEYCODE_N: case KeyEvent.KEYCODE_K: { if (mMessageViewFragment != null) { showNextMessage(); } return true; } /* FIXME case KeyEvent.KEYCODE_Z: { mMessageViewFragment.zoom(event); return true; }*/ case KeyEvent.KEYCODE_H: { Toast toast = Toast.makeText(this, R.string.message_list_help_key, Toast.LENGTH_LONG); toast.show(); return true; } } return false; }
diff --git a/org.springframework.expression/src/main/java/org/springframework/expression/spel/ast/Projection.java b/org.springframework.expression/src/main/java/org/springframework/expression/spel/ast/Projection.java index 50ed7d94e..5a4f2d46f 100644 --- a/org.springframework.expression/src/main/java/org/springframework/expression/spel/ast/Projection.java +++ b/org.springframework.expression/src/main/java/org/springframework/expression/spel/ast/Projection.java @@ -1,105 +1,109 @@ /* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.expression.spel.ast; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import org.springframework.core.convert.TypeDescriptor; import org.springframework.expression.EvaluationException; import org.springframework.expression.TypedValue; import org.springframework.expression.spel.ExpressionState; import org.springframework.expression.spel.SpelEvaluationException; import org.springframework.expression.spel.SpelMessages; /** * Represents projection, where a given operation is performed on all elements in some input sequence, returning * a new sequence of the same size. For example: * "{1,2,3,4,5,6,7,8,9,10}.!{#isEven(#this)}" returns "[n, y, n, y, n, y, n, y, n, y]" * * @author Andy Clement * */ public class Projection extends SpelNodeImpl { private final boolean nullSafe; public Projection(boolean nullSafe, int pos,SpelNodeImpl expression) { super(pos,expression); this.nullSafe = nullSafe; } @SuppressWarnings("unchecked") @Override public TypedValue getValueInternal(ExpressionState state) throws EvaluationException { TypedValue op = state.getActiveContextObject(); Object operand = op.getValue(); // TypeDescriptor operandTypeDescriptor = op.getTypeDescriptor(); // When the input is a map, we push a special context object on the stack // before calling the specified operation. This special context object // has two fields 'key' and 'value' that refer to the map entries key // and value, and they can be referenced in the operation // eg. {'a':'y','b':'n'}.!{value=='y'?key:null}" == ['a', null] if (operand instanceof Map) { Map<?, ?> mapdata = (Map<?, ?>) operand; List<Object> result = new ArrayList<Object>(); for (Map.Entry entry : mapdata.entrySet()) { try { state.pushActiveContextObject(new TypedValue(entry,TypeDescriptor.valueOf(Map.Entry.class))); result.add(children[0].getValueInternal(state).getValue()); } finally { state.popActiveContextObject(); } } return new TypedValue(result,TypeDescriptor.valueOf(List.class)); // TODO unable to build correct type descriptor } else if (operand instanceof List) { List<Object> data = new ArrayList<Object>(); data.addAll((Collection<?>) operand); List<Object> result = new ArrayList<Object>(); int idx = 0; for (Object element : data) { try { state.pushActiveContextObject(new TypedValue(element,TypeDescriptor.valueOf(op.getTypeDescriptor().getType()))); state.enterScope("index", idx); result.add(children[0].getValueInternal(state).getValue()); } finally { state.exitScope(); state.popActiveContextObject(); } idx++; } return new TypedValue(result,op.getTypeDescriptor()); } else { - if (operand==null && nullSafe) { - return TypedValue.NULL_TYPED_VALUE; + if (operand==null) { + if (nullSafe) { + return TypedValue.NULL_TYPED_VALUE; + } else { + throw new SpelEvaluationException(getStartPosition(),SpelMessages.PROJECTION_NOT_SUPPORTED_ON_TYPE, "null"); + } } else { throw new SpelEvaluationException(getStartPosition(),SpelMessages.PROJECTION_NOT_SUPPORTED_ON_TYPE, operand.getClass().getName()); } } } @Override public String toStringAST() { StringBuilder sb = new StringBuilder(); return sb.append("![").append(getChild(0).toStringAST()).append("]").toString(); } }
true
true
public TypedValue getValueInternal(ExpressionState state) throws EvaluationException { TypedValue op = state.getActiveContextObject(); Object operand = op.getValue(); // TypeDescriptor operandTypeDescriptor = op.getTypeDescriptor(); // When the input is a map, we push a special context object on the stack // before calling the specified operation. This special context object // has two fields 'key' and 'value' that refer to the map entries key // and value, and they can be referenced in the operation // eg. {'a':'y','b':'n'}.!{value=='y'?key:null}" == ['a', null] if (operand instanceof Map) { Map<?, ?> mapdata = (Map<?, ?>) operand; List<Object> result = new ArrayList<Object>(); for (Map.Entry entry : mapdata.entrySet()) { try { state.pushActiveContextObject(new TypedValue(entry,TypeDescriptor.valueOf(Map.Entry.class))); result.add(children[0].getValueInternal(state).getValue()); } finally { state.popActiveContextObject(); } } return new TypedValue(result,TypeDescriptor.valueOf(List.class)); // TODO unable to build correct type descriptor } else if (operand instanceof List) { List<Object> data = new ArrayList<Object>(); data.addAll((Collection<?>) operand); List<Object> result = new ArrayList<Object>(); int idx = 0; for (Object element : data) { try { state.pushActiveContextObject(new TypedValue(element,TypeDescriptor.valueOf(op.getTypeDescriptor().getType()))); state.enterScope("index", idx); result.add(children[0].getValueInternal(state).getValue()); } finally { state.exitScope(); state.popActiveContextObject(); } idx++; } return new TypedValue(result,op.getTypeDescriptor()); } else { if (operand==null && nullSafe) { return TypedValue.NULL_TYPED_VALUE; } else { throw new SpelEvaluationException(getStartPosition(),SpelMessages.PROJECTION_NOT_SUPPORTED_ON_TYPE, operand.getClass().getName()); } } }
public TypedValue getValueInternal(ExpressionState state) throws EvaluationException { TypedValue op = state.getActiveContextObject(); Object operand = op.getValue(); // TypeDescriptor operandTypeDescriptor = op.getTypeDescriptor(); // When the input is a map, we push a special context object on the stack // before calling the specified operation. This special context object // has two fields 'key' and 'value' that refer to the map entries key // and value, and they can be referenced in the operation // eg. {'a':'y','b':'n'}.!{value=='y'?key:null}" == ['a', null] if (operand instanceof Map) { Map<?, ?> mapdata = (Map<?, ?>) operand; List<Object> result = new ArrayList<Object>(); for (Map.Entry entry : mapdata.entrySet()) { try { state.pushActiveContextObject(new TypedValue(entry,TypeDescriptor.valueOf(Map.Entry.class))); result.add(children[0].getValueInternal(state).getValue()); } finally { state.popActiveContextObject(); } } return new TypedValue(result,TypeDescriptor.valueOf(List.class)); // TODO unable to build correct type descriptor } else if (operand instanceof List) { List<Object> data = new ArrayList<Object>(); data.addAll((Collection<?>) operand); List<Object> result = new ArrayList<Object>(); int idx = 0; for (Object element : data) { try { state.pushActiveContextObject(new TypedValue(element,TypeDescriptor.valueOf(op.getTypeDescriptor().getType()))); state.enterScope("index", idx); result.add(children[0].getValueInternal(state).getValue()); } finally { state.exitScope(); state.popActiveContextObject(); } idx++; } return new TypedValue(result,op.getTypeDescriptor()); } else { if (operand==null) { if (nullSafe) { return TypedValue.NULL_TYPED_VALUE; } else { throw new SpelEvaluationException(getStartPosition(),SpelMessages.PROJECTION_NOT_SUPPORTED_ON_TYPE, "null"); } } else { throw new SpelEvaluationException(getStartPosition(),SpelMessages.PROJECTION_NOT_SUPPORTED_ON_TYPE, operand.getClass().getName()); } } }
diff --git a/src/persistence/org/codehaus/groovy/grails/orm/hibernate/metaclass/FindPersistentMethod.java b/src/persistence/org/codehaus/groovy/grails/orm/hibernate/metaclass/FindPersistentMethod.java index 94b6cd9c2..06bfabf28 100644 --- a/src/persistence/org/codehaus/groovy/grails/orm/hibernate/metaclass/FindPersistentMethod.java +++ b/src/persistence/org/codehaus/groovy/grails/orm/hibernate/metaclass/FindPersistentMethod.java @@ -1,136 +1,136 @@ /* Copyright 2004-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.orm.hibernate.metaclass; import groovy.lang.MissingMethodException; import groovy.lang.GString; import java.sql.SQLException; import java.util.List; import java.util.regex.Pattern; import org.codehaus.groovy.grails.commons.GrailsClassUtils; import org.codehaus.groovy.grails.orm.hibernate.exceptions.GrailsQueryException; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Example; import org.springframework.orm.hibernate3.HibernateCallback; /** * <p>The "find" persistent static method allows searching for instances using either an example instance or an HQL * query. This method returns the first result of the query. A GrailsQueryException is thrown if the query is not a valid query for the domain class. * * <p>Examples in Groovy: * <code> * // retrieve the first 10 accounts ordered by account number * def a = Account.find("from Account as a order by a.number asc", 10) * * // with query parameters * def a = Account.find("from Account as a where a.number = ? and a.branch = ?", [38479, "London"]) * * // query by example * def a = new Account() * a.number = 495749357 * def a = Account.find(a) * * </code> * * @author Graeme Rocher * @since 31-Aug-2005 * */ public class FindPersistentMethod extends AbstractStaticPersistentMethod { private static final String METHOD_PATTERN = "^find$"; public FindPersistentMethod(SessionFactory sessionFactory, ClassLoader classLoader) { super(sessionFactory, classLoader, Pattern.compile(METHOD_PATTERN)); } protected Object doInvokeInternal(final Class clazz, String methodName, final Object[] arguments) { if(arguments.length == 0) throw new MissingMethodException(methodName,clazz,arguments); final Object arg = arguments[0] instanceof GString ? arguments[0].toString() :arguments[0]; // if the arg is an instance of the class find by example if(arg instanceof String) { final String query = (String)arg; final String shortName = GrailsClassUtils.getShortName(clazz); if(!query.matches( "from ["+clazz.getName()+"|"+shortName+"].*" )) { throw new GrailsQueryException("Invalid query ["+query+"] for domain class ["+clazz+"]"); } return super.getHibernateTemplate().execute( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query q = session.createQuery(query); Object[] queryArgs = null; if(arguments.length > 1) { if(arguments[1] instanceof List) { queryArgs = ((List)arguments[1]).toArray(); } else if(arguments[1].getClass().isArray()) { queryArgs = (Object[])arguments[1]; } } if(queryArgs != null) { for (int i = 0; i < queryArgs.length; i++) { if(queryArgs[0] instanceof GString) { q.setParameter(i,queryArgs[i].toString()); } else { q.setParameter(i, queryArgs[i]); } } } // only want one result, could have used uniqueObject here // but it throws an exception if its not unique which is // undesirable q.setMaxResults(1); List results = q.list(); if(results.size() > 0) return results.get(0); return null; } }); } if(clazz.isAssignableFrom( arg.getClass() )) { - return super.getHibernateTemplate().executeFind( new HibernateCallback() { + return super.getHibernateTemplate().execute( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Example example = Example.create(arg) .ignoreCase(); Criteria crit = session.createCriteria(clazz); crit.add(example); List results = crit.list(); if(results.size() > 0) return results.get(0); return null; } }); } throw new MissingMethodException(methodName,clazz,arguments); } }
true
true
protected Object doInvokeInternal(final Class clazz, String methodName, final Object[] arguments) { if(arguments.length == 0) throw new MissingMethodException(methodName,clazz,arguments); final Object arg = arguments[0] instanceof GString ? arguments[0].toString() :arguments[0]; // if the arg is an instance of the class find by example if(arg instanceof String) { final String query = (String)arg; final String shortName = GrailsClassUtils.getShortName(clazz); if(!query.matches( "from ["+clazz.getName()+"|"+shortName+"].*" )) { throw new GrailsQueryException("Invalid query ["+query+"] for domain class ["+clazz+"]"); } return super.getHibernateTemplate().execute( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query q = session.createQuery(query); Object[] queryArgs = null; if(arguments.length > 1) { if(arguments[1] instanceof List) { queryArgs = ((List)arguments[1]).toArray(); } else if(arguments[1].getClass().isArray()) { queryArgs = (Object[])arguments[1]; } } if(queryArgs != null) { for (int i = 0; i < queryArgs.length; i++) { if(queryArgs[0] instanceof GString) { q.setParameter(i,queryArgs[i].toString()); } else { q.setParameter(i, queryArgs[i]); } } } // only want one result, could have used uniqueObject here // but it throws an exception if its not unique which is // undesirable q.setMaxResults(1); List results = q.list(); if(results.size() > 0) return results.get(0); return null; } }); } if(clazz.isAssignableFrom( arg.getClass() )) { return super.getHibernateTemplate().executeFind( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Example example = Example.create(arg) .ignoreCase(); Criteria crit = session.createCriteria(clazz); crit.add(example); List results = crit.list(); if(results.size() > 0) return results.get(0); return null; } }); } throw new MissingMethodException(methodName,clazz,arguments); }
protected Object doInvokeInternal(final Class clazz, String methodName, final Object[] arguments) { if(arguments.length == 0) throw new MissingMethodException(methodName,clazz,arguments); final Object arg = arguments[0] instanceof GString ? arguments[0].toString() :arguments[0]; // if the arg is an instance of the class find by example if(arg instanceof String) { final String query = (String)arg; final String shortName = GrailsClassUtils.getShortName(clazz); if(!query.matches( "from ["+clazz.getName()+"|"+shortName+"].*" )) { throw new GrailsQueryException("Invalid query ["+query+"] for domain class ["+clazz+"]"); } return super.getHibernateTemplate().execute( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query q = session.createQuery(query); Object[] queryArgs = null; if(arguments.length > 1) { if(arguments[1] instanceof List) { queryArgs = ((List)arguments[1]).toArray(); } else if(arguments[1].getClass().isArray()) { queryArgs = (Object[])arguments[1]; } } if(queryArgs != null) { for (int i = 0; i < queryArgs.length; i++) { if(queryArgs[0] instanceof GString) { q.setParameter(i,queryArgs[i].toString()); } else { q.setParameter(i, queryArgs[i]); } } } // only want one result, could have used uniqueObject here // but it throws an exception if its not unique which is // undesirable q.setMaxResults(1); List results = q.list(); if(results.size() > 0) return results.get(0); return null; } }); } if(clazz.isAssignableFrom( arg.getClass() )) { return super.getHibernateTemplate().execute( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Example example = Example.create(arg) .ignoreCase(); Criteria crit = session.createCriteria(clazz); crit.add(example); List results = crit.list(); if(results.size() > 0) return results.get(0); return null; } }); } throw new MissingMethodException(methodName,clazz,arguments); }
diff --git a/activiti-rest/src/main/java/org/activiti/rest/util/ActivitiWebScript.java b/activiti-rest/src/main/java/org/activiti/rest/util/ActivitiWebScript.java index 1bd3eb86f..19d94ade4 100644 --- a/activiti-rest/src/main/java/org/activiti/rest/util/ActivitiWebScript.java +++ b/activiti-rest/src/main/java/org/activiti/rest/util/ActivitiWebScript.java @@ -1,464 +1,470 @@ /* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.rest.util; import org.activiti.*; import org.activiti.identity.Group; import org.activiti.impl.json.JSONObject; import org.activiti.rest.Config; import org.springframework.extensions.surf.util.Base64; import org.springframework.extensions.webscripts.*; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Helper class for all activiti webscripts. * * @author Erik Winlöf */ public class ActivitiWebScript extends DeclarativeWebScript { /** * The activiti config bean */ protected Config config; /** * Setter for the activiti config bean * * @param config The activiti config bean */ public void setConfig(Config config) { this.config = config; } /** * The entry point for the webscript. * * Will create a model and call the executeWebScript() so extending activiti webscripts may implement custom logic. * * @param req The webscript request * @param status The webscripts status * @param cache The webscript cache * @return The webscript template model */ @Override protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) { // Prepare model with process engine info Map<String, Object> model = new HashMap<String, Object>(); // todo: set the current user context when the core api implements security checks // Let implementing webscript do something useful executeWebScript(req, status, cache, model); // Return model return model; } /** * Override this class to implement custom logic. * * @param req The webscript request * @param status The webscript * @param cache * @param model */ protected void executeWebScript(WebScriptRequest req, Status status, Cache cache, Map<String, Object> model){ // Override to make something useful } /** * Returns the process engine info. * * @return The process engine info */ protected ProcessEngineInfo getProcessEngineInfo() { return ProcessEngines.getProcessEngineInfo(config.getEngine()); } /** * Returns the process engine. * * @return The process engine */ protected ProcessEngine getProcessEngine() { return ProcessEngines.getProcessEngine(config.getEngine()); } /** * Returns the identity service. * * @return The identity service */ protected IdentityService getIdentityService() { return getProcessEngine().getIdentityService(); } /** * Returns the management service. * * @return The management service. */ protected ManagementService getManagementService() { return getProcessEngine().getManagementService(); } /** * Returns The process service. * * @return The process service */ protected ProcessService getProcessService() { return getProcessEngine().getProcessService(); } /** * Returns the task service. * * @return The task service */ protected TaskService getTaskService() { return getProcessEngine().getTaskService(); } /** * Returns the webscript request body in an abstracted form so multiple formats may be * implemented seamlessly in the future. * * @param req The webscript request * @return The webscript requests body */ protected ActivitiWebScriptBody getBody(WebScriptRequest req) { try { return new ActivitiWebScriptBody(req); } catch (IOException e) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Can't read body"); } } /** * Gets a path parameter value and throws an exception if its not present. * * @param req The webscript request * @param param The name of the path parameter * @return The value of the path parameter * @throws WebScriptException if parameter isn't present */ protected String getMandatoryPathParameter(WebScriptRequest req, String param) { return checkString(req.getServiceMatch().getTemplateVars().get(param), param, true); } /** * Gets a path parameter value. * * @param req The webscript request * @param param The name of the path parameter * @return The path parameter value or null if not present */ protected String getPathParameter(WebScriptRequest req, String param) { return checkString(req.getServiceMatch().getTemplateVars().get(param), param, false); } /** * Gets an int parameter value. * * @param req The webscript request * @param param The name of the int parameter * @return The int parameter value or Integer.MIN_VALUE if not present */ protected int getInt(WebScriptRequest req, String param) { String value = getString(req, param); return value != null ? Integer.parseInt(value) : Integer.MIN_VALUE; } /** * Gets a mandatory int parameter and throws an exception if its not present. * * @param req The webscript request * @param param The name of the path parameter * @return The int parameter value * @throws WebScriptException if parameter isn't present */ protected int getMandatoryInt(WebScriptRequest req, String param) { String value = getMandatoryString(req, param); return value != null ? Integer.parseInt(value) : Integer.MIN_VALUE; } /** * Gets an int parameter value * * @param req The webscript request * @param param The name of the int parameter * @param defaultValue THe value to return if the parameter isn't present * @return The int parameter value of defaultValue if the parameter isn't present */ protected int getInt(WebScriptRequest req, String param, int defaultValue) { String value = getString(req, param); return value != null ? Integer.parseInt(value) : defaultValue; } /** * Gets the string parameter value. * * @param req The webscript request * @param param The name of the string parameter * @return The string parameter value or null if the parameter isn't present */ protected String getString(WebScriptRequest req, String param) { return checkString(req.getParameter(param), param, false); } /** * Gets a mandatory string parameter value of throws an exception if the parameter isn't present. * * @param req The webscript request * @param param The name of the string parameter value * @return The string parameter value * @throws WebScriptException if the parameter isn't present */ protected String getMandatoryString(WebScriptRequest req, String param) { return checkString(req.getParameter(param), param, true); } /** * Gets the string parameter value. * * @param req The webscript request. * @param param The name of the string parameter value * @param defaultValue The value to return if the parameter isn't present * @return The value of the string parameter or the default value if parameter isn't present */ protected String getString(WebScriptRequest req, String param, String defaultValue) { String value = checkString(req.getParameter(param), param, false); return value != null ? value : defaultValue; } /** * Gets a string parameter from the body * @param body The activiti webscript request body * @param param The name of the string parameter * @return The value of the string body parameter * @throws WebScriptException if string body parameter isn't present */ protected String getMandatoryString(ActivitiWebScriptBody body, String param) { return checkString(body.getString(param), param, true); } /** * Gets a parameter as Map * @param body The activiti webscript request body * @return The value of the string body parameter * @throws WebScriptException if string body parameter isn't present */ protected Map<String, Object> getFormVariables(ActivitiWebScriptBody body) { return body.getFormVariables(); } /** * Throws and exception if the parameter value is null or empty and mandatory is true * * @param value The parameter value to test * @param param The name of the parameter * @param mandatory If true the value wil be tested * @return The parameter value * @throws WebScriptException if mandatory is true and value is null or empty */ protected String checkString(String value, String param, boolean mandatory) { if (value != null && value.isEmpty()) { value = null; } return (String) checkObject(value, param, mandatory); } /** * Throws and exception if the parameter value is null or empty and mandatory is true * * @param value The parameter value to test * @param param The name of the parameter * @param mandatory If true the value wil be tested * @return The parameter value * @throws WebScriptException if mandatory is true and value is null or empty */ protected Object checkObject(Object value, String param, boolean mandatory) { if (value == null) { if (mandatory) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Parameter '" + param + "' is missing"); } else { return null; } } return value; } /** * Returns the username for the current user. * * @param req The webscript request * @return THe username of the current user */ protected String getCurrentUserId(WebScriptRequest req) { String authorization = req.getHeader("Authorization"); if (authorization != null) { String [] parts = authorization.split(" "); if (parts.length == 2) { return new String(Base64.decode(parts[1])).split(":")[0]; } } return null; } /** * Tests if user is in group. * * @param req The webscript request * @param userId The id of the user to test * @param groupId The if of the group to test the user against * @return true of user is in group */ protected boolean isUserInGroup(WebScriptRequest req, String userId, String groupId) { if (userId != null) { List<Group> groups = getIdentityService().findGroupsByUser(userId); for (Group group : groups) { if (config.getAdminGroupId().equals(group.getId())) { return true; } } } return false; } /** * Tests if user has manager role. * * @param req The webscript request. * @return true if the user has manager role */ protected boolean isManager(WebScriptRequest req) { return isUserInGroup(req, getCurrentUserId(req), config.getManagerGroupId()); } /** * Tests if user has admin role. * * @param req The webscript request * @return true if the user has admin role */ protected boolean isAdmin(WebScriptRequest req) { return isUserInGroup(req, getCurrentUserId(req), config.getAdminGroupId()); } /** * A class that wraps the webscripts request body so multiple formats * such as XML may be supported in the future. */ public class ActivitiWebScriptBody { /** * The json body */ private JSONObject jsonBody = null; /** * Constructor * * @param req The webscript request * @throws IOException if body of correct format cannot be created */ ActivitiWebScriptBody(WebScriptRequest req) throws IOException { jsonBody = new JSONObject(req.getContent().getContent()); } /** * Gets a body parameter string value. * * @param param The name of the parameter * @return The string value of the parameter */ String getString(String param) { return jsonBody.getString(param); } /** * Gets a body parameter string value. * * @param param The name of the parameter * @return The string value of the parameter */ int getInt(String param) { return jsonBody.getInt(param); } /** * Gets the body as a map. * * @return The body as a map */ Map<String, Object> getFormVariables() { Map<String, Object> map = new HashMap<String, Object>(); Iterator keys = jsonBody.keys(); String key, typeKey, type; String[] keyPair; Object value; while (keys.hasNext()) { key = (String) keys.next(); keyPair = key.split("_"); if (keyPair.length == 1) { typeKey = keyPair[0] + "_type"; if (jsonBody.has(typeKey)) { type = jsonBody.getString(typeKey); if (type.equals("Integer")) { value = jsonBody.getInt(key); } else if (type.equals("Boolean")) { value = jsonBody.getBoolean(key); } + else if (type.equals("Date")) { + value = jsonBody.getString(key); + } + else if (type.equals("User")) { + value = jsonBody.getString(key); + } else { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Parameter '" + keyPair[0] + "' is of unknown type '" + type + "'"); } } else { value = jsonBody.get(key); } map.put(key, value); } else if (keyPair.length == 2) { if (keyPair[1].equals("required")) { if (!jsonBody.has(keyPair[0]) || jsonBody.get(keyPair[0]) == null) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Parameter '" + keyPair[0] + "' has no value"); } } } } return map; } } }
true
true
Map<String, Object> getFormVariables() { Map<String, Object> map = new HashMap<String, Object>(); Iterator keys = jsonBody.keys(); String key, typeKey, type; String[] keyPair; Object value; while (keys.hasNext()) { key = (String) keys.next(); keyPair = key.split("_"); if (keyPair.length == 1) { typeKey = keyPair[0] + "_type"; if (jsonBody.has(typeKey)) { type = jsonBody.getString(typeKey); if (type.equals("Integer")) { value = jsonBody.getInt(key); } else if (type.equals("Boolean")) { value = jsonBody.getBoolean(key); } else { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Parameter '" + keyPair[0] + "' is of unknown type '" + type + "'"); } } else { value = jsonBody.get(key); } map.put(key, value); } else if (keyPair.length == 2) { if (keyPair[1].equals("required")) { if (!jsonBody.has(keyPair[0]) || jsonBody.get(keyPair[0]) == null) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Parameter '" + keyPair[0] + "' has no value"); } } } } return map; }
Map<String, Object> getFormVariables() { Map<String, Object> map = new HashMap<String, Object>(); Iterator keys = jsonBody.keys(); String key, typeKey, type; String[] keyPair; Object value; while (keys.hasNext()) { key = (String) keys.next(); keyPair = key.split("_"); if (keyPair.length == 1) { typeKey = keyPair[0] + "_type"; if (jsonBody.has(typeKey)) { type = jsonBody.getString(typeKey); if (type.equals("Integer")) { value = jsonBody.getInt(key); } else if (type.equals("Boolean")) { value = jsonBody.getBoolean(key); } else if (type.equals("Date")) { value = jsonBody.getString(key); } else if (type.equals("User")) { value = jsonBody.getString(key); } else { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Parameter '" + keyPair[0] + "' is of unknown type '" + type + "'"); } } else { value = jsonBody.get(key); } map.put(key, value); } else if (keyPair.length == 2) { if (keyPair[1].equals("required")) { if (!jsonBody.has(keyPair[0]) || jsonBody.get(keyPair[0]) == null) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Parameter '" + keyPair[0] + "' has no value"); } } } } return map; }
diff --git a/core/src/visad/trunk/DataRenderer.java b/core/src/visad/trunk/DataRenderer.java index 8662fa56a..ba9d4760f 100644 --- a/core/src/visad/trunk/DataRenderer.java +++ b/core/src/visad/trunk/DataRenderer.java @@ -1,1828 +1,1826 @@ // // DataRenderer.java // /* VisAD system for interactive analysis and visualization of numerical data. Copyright (C) 1996 - 1999 Bill Hibbard, Curtis Rueden, Tom Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and Tommy Jasmin. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ package visad; import java.util.*; import java.rmi.*; /** DataRenderer is the VisAD abstract super-class for graphics rendering algorithms. These transform Data objects into 3-D (or 2-D) depictions in a Display window.<P> DataRenderer is not Serializable and should not be copied between JVMs.<P> */ public abstract class DataRenderer extends Object { private DisplayImpl display; /** used to insert output into scene graph */ private DisplayRenderer displayRenderer; /** links to Data to be renderer by this */ private transient DataDisplayLink[] Links; /** flag from DataDisplayLink.prepareData */ private boolean[] feasible; // it's a miracle if this is correct /** flag to indicate that DataDisplayLink.prepareData was invoked */ private boolean[] changed; private boolean any_changed; private boolean all_feasible; private boolean any_transform_control; /** a Vector of BadMappingException and UnimplementedException Strings generated during the last invocation of doAction */ private Vector exceptionVector = new Vector(); public DataRenderer() { Links = null; display = null; } public void clearExceptions() { exceptionVector.removeAllElements(); } /** add message from BadMappingException or UnimplementedException to exceptionVector */ public void addException(Exception error) { exceptionVector.addElement(error); // System.out.println(error.getMessage()); } /** this returns a Vector of Strings from the BadMappingExceptions and UnimplementedExceptions generated during the last invocation of this DataRenderer's doAction method; there is no need to over-ride this method, but it may be invoked by DisplayRenderer; gets a clone of exceptionVector to avoid concurrent access by Display thread */ public Vector getExceptionVector() { return (Vector) exceptionVector.clone(); } public boolean get_all_feasible() { return all_feasible; } public boolean get_any_changed() { return any_changed; } public boolean get_any_transform_control() { return any_transform_control; } public void set_all_feasible(boolean b) { all_feasible = b; } public abstract void setLinks(DataDisplayLink[] links, DisplayImpl d) throws VisADException; public synchronized void setLinks(DataDisplayLink[] links) { if (links == null || links.length == 0) return; Links = links; feasible = new boolean[Links.length]; changed = new boolean[Links.length]; for (int i=0; i<Links.length; i++) feasible[i] = false; } /** return an array of links to Data objects to be rendered; Data objects are accessed by DataDisplayLink.getData() */ public DataDisplayLink[] getLinks() { return Links; } public DisplayImpl getDisplay() { return display; } public void setDisplay(DisplayImpl d) { display = d; } public DisplayRenderer getDisplayRenderer() { return displayRenderer; } public void setDisplayRenderer(DisplayRenderer r) { displayRenderer = r; } public boolean checkAction() { for (int i=0; i<Links.length; i++) { if (Links[i].checkTicks() || !feasible[i]) { return true; } // check if this Data includes any changed Controls Enumeration maps = Links[i].getSelectedMapVector().elements(); while(maps.hasMoreElements()) { ScalarMap map = (ScalarMap) maps.nextElement(); if (map.checkTicks(this, Links[i])) { return true; } } } return false; } /** check if re-transform is needed; if initialize is true then compute ranges for RealType-s and Animation sampling */ public DataShadow prepareAction(boolean go, boolean initialize, DataShadow shadow) throws VisADException, RemoteException { any_changed = false; all_feasible = true; any_transform_control = false; for (int i=0; i<Links.length; i++) { changed[i] = false; DataReference ref = Links[i].getDataReference(); // test for changed Controls that require doTransform /* System.out.println(display.getName() + " Links[" + i + "].checkTicks() = " + Links[i].checkTicks() + " feasible[" + i + "] = " + feasible[i] + " go = " + go); MathType junk = Links[i].getType(); if (junk != null) System.out.println(junk.prettyString()); */ if (Links[i].checkTicks() || !feasible[i] || go) { /* boolean check = Links[i].checkTicks(); System.out.println("DataRenderer.prepareAction: check = " + check + " feasible = " + feasible[i] + " go = " + go + " " + Links[i].getThingReference().getName()); */ // data has changed - need to re-display changed[i] = true; any_changed = true; // create ShadowType for data, classify data for display feasible[i] = Links[i].prepareData(); if (!feasible[i]) { all_feasible = false; // WLH 31 March 99 clearBranch(); } if (initialize && feasible[i]) { // compute ranges of RealTypes and Animation sampling ShadowType type = Links[i].getShadow().getAdaptedShadowType(); if (shadow == null) { shadow = Links[i].getData().computeRanges(type, display.getScalarCount()); } else { shadow = Links[i].getData().computeRanges(type, shadow); } } } // end if (Links[i].checkTicks() || !feasible[i] || go) if (feasible[i]) { // check if this Data includes any changed Controls Enumeration maps = Links[i].getSelectedMapVector().elements(); while(maps.hasMoreElements()) { ScalarMap map = (ScalarMap) maps.nextElement(); if (map.checkTicks(this, Links[i])) { any_transform_control = true; } } } // end if (feasible[i]) } // end for (int i=0; i<Links.length; i++) return shadow; } /** clear scene graph component */ public abstract void clearBranch(); /** re-transform if needed; return false if not done */ /** transform linked Data objects into a display list, if any Data object values have changed or relevant Controls have changed; DataRenderers that assume the default implementation of DisplayImpl.doAction can determine whether re-transform is needed by: (get_all_feasible() && (get_any_changed() || get_any_transform_control())); these flags are computed by the default DataRenderer implementation of prepareAction; the return boolean is true if the transform was done successfully */ public abstract boolean doAction() throws VisADException, RemoteException; public boolean getBadScale() { boolean badScale = false; for (int i=0; i<Links.length; i++) { if (!feasible[i]) { /* try { System.out.println("getBadScale not feasible " + Links[i].getThingReference().getName()); } catch (VisADException e) {} catch (RemoteException e) {} */ return true; } Enumeration maps = Links[i].getSelectedMapVector().elements(); while(maps.hasMoreElements()) { ScalarMap map = (ScalarMap) maps.nextElement(); badScale |= map.badRange(); /* if (map.badRange()) { System.out.println("getBadScale: " + map.getScalar().getName() + " -> " + map.getDisplayScalar().getName()); } */ } } return badScale; } /** clear any display list created by the most recent doAction invocation */ public abstract void clearScene(); public void clearAVControls() { Enumeration controls = display.getControls(AVControl.class).elements(); while (controls.hasMoreElements()) { ((AVControl )controls.nextElement()).clearSwitches(this); } // a convenient place to throw this in ProjectionControl control = display.getProjectionControl(); control.clearSwitches(this); // a convenient place to throw this in lat_index = -1; lon_index = -1; } /** factory for constructing a subclass of ShadowType appropriate for the graphics API, that also adapts ShadowFunctionType; these factories are invoked by the buildShadowType methods of the MathType subclasses, which are invoked by DataDisplayLink.prepareData, which is invoked by DataRenderer.prepareAction */ public abstract ShadowType makeShadowFunctionType( FunctionType type, DataDisplayLink link, ShadowType parent) throws VisADException, RemoteException; /** factory for constructing a subclass of ShadowType appropriate for the graphics API, that also adapts ShadowRealTupleType */ public abstract ShadowType makeShadowRealTupleType( RealTupleType type, DataDisplayLink link, ShadowType parent) throws VisADException, RemoteException; /** factory for constructing a subclass of ShadowType appropriate for the graphics API, that also adapts ShadowRealType */ public abstract ShadowType makeShadowRealType( RealType type, DataDisplayLink link, ShadowType parent) throws VisADException, RemoteException; /** factory for constructing a subclass of ShadowType appropriate for the graphics API, that also adapts ShadowSetType */ public abstract ShadowType makeShadowSetType( SetType type, DataDisplayLink link, ShadowType parent) throws VisADException, RemoteException; /** factory for constructing a subclass of ShadowType appropriate for the graphics API, that also adapts ShadowTextType */ public abstract ShadowType makeShadowTextType( TextType type, DataDisplayLink link, ShadowType parent) throws VisADException, RemoteException; /** factory for constructing a subclass of ShadowType appropriate for the graphics API, that also adapts ShadowTupleType */ public abstract ShadowType makeShadowTupleType( TupleType type, DataDisplayLink link, ShadowType parent) throws VisADException, RemoteException; /** DataRenderer-specific decision about which Controls require re-transform; may be over-ridden by DataRenderer sub-classes; this decision may use some values computed by link.prepareData */ public boolean isTransformControl(Control control, DataDisplayLink link) { if (control instanceof ProjectionControl || control instanceof ToggleControl) { return false; } /* WLH 1 Nov 97 - temporary hack - RangeControl changes always require Transform ValueControl and AnimationControl never do if (control instanceof AnimationControl || control instanceof ValueControl || control instanceof RangeControl) { return link.isTransform[control.getIndex()]; */ if (control instanceof AnimationControl || control instanceof ValueControl) { return false; } return true; } /** used for transform time-out hack */ public DataDisplayLink getLink() { return null; } public boolean isLegalTextureMap() { return true; } /* ********************** */ /* flow rendering stuff */ /* ********************** */ // value array (display_values) indices // ((ScalarMap) MapVector.elementAt(valueToMap[index])) // can get these indices through shadow_data_out or shadow_data_in // true if lat and lon in data_in & shadow_data_in is allSpatial // or if lat and lon in data_in & lat_lon_in_by_coord boolean lat_lon_in = false; // true if lat_lon_in and shadow_data_out is allSpatial // i.e., map from lat, lon to display is through data CoordinateSystem boolean lat_lon_in_by_coord = false; // true if lat and lon in data_out & shadow_data_out is allSpatial boolean lat_lon_out = false; // true if lat_lon_out and shadow_data_in is allSpatial // i.e., map from lat, lon to display is inverse via data CoordinateSystem boolean lat_lon_out_by_coord = false; int lat_lon_dimension = -1; ShadowRealTupleType shadow_data_out = null; RealTupleType data_out = null; Unit[] data_units_out = null; // CoordinateSystem data_coord_out is always null ShadowRealTupleType shadow_data_in = null; RealTupleType data_in = null; Unit[] data_units_in = null; CoordinateSystem[] data_coord_in = null; // may be one per point // spatial ScalarMaps for allSpatial shadow_data_out ScalarMap[] sdo_maps = null; // spatial ScalarMaps for allSpatial shadow_data_in ScalarMap[] sdi_maps = null; int[] sdo_spatial_index = null; int[] sdi_spatial_index = null; // indices of RealType.Latitude and RealType.Longitude // if lat_lon_in then indices in data_in // if lat_lon_out then indices in data_out // if lat_lon_spatial then values indices int lat_index = -1; int lon_index = -1; // non-negative if lat & lon in a RealTupleType of length 3 int other_index = -1; // true if other_index Units convertable to meter boolean other_meters = false; // from doTransform RealVectorType[] rvts = {null, null}; public RealVectorType getRealVectorTypes(int index) { if (index == 0 || index == 1) return rvts[index]; else return null; } public int[] getLatLonIndices() { return new int[] {lat_index, lon_index}; } public void setLatLonIndices(int[] indices) { lat_index = indices[0]; lon_index = indices[1]; } public int getEarthDimension() { return lat_lon_dimension; } public Unit[] getEarthUnits() { Unit[] units = null; if (lat_lon_in) { units = data_units_in; } else if (lat_lon_out) { units = data_units_out; } else if (lat_lon_spatial) { units = new Unit[] {RealType.Latitude.getDefaultUnit(), RealType.Longitude.getDefaultUnit()}; } else { units = null; } int lat = lat_index; int lon = lon_index; int other = other_index; if (units == null) { return null; } else if (units.length == 2) { return new Unit[] {lat >= 0 ? units[lat] : null, lon >= 0 ? units[lon] : null}; } else if (units.length == 3) { return new Unit[] {lat >= 0 ? units[lat] : null, lon >= 0 ? units[lon] : null, other >= 0 ? units[other] : null}; } else { return null; } } public float getLatLonRange() { double[] rlat = null; double[] rlon = null; int lat = lat_index; int lon = lon_index; if ((lat_lon_out && !lat_lon_out_by_coord) || (lat_lon_in && lat_lon_in_by_coord)) { rlat = lat >= 0 ? sdo_maps[lat].getRange() : new double[] {Double.NaN, Double.NaN}; rlon = lon >= 0 ? sdo_maps[lon].getRange() : new double[] {Double.NaN, Double.NaN}; } else if ((lat_lon_in && !lat_lon_in_by_coord) || (lat_lon_out && lat_lon_out_by_coord)) { rlat = lat >= 0 ? sdi_maps[lat].getRange() : new double[] {Double.NaN, Double.NaN}; rlon = lon >= 0 ? sdi_maps[lon].getRange() : new double[] {Double.NaN, Double.NaN}; } else if (lat_lon_spatial) { rlat = lat_map.getRange(); rlon = lon_map.getRange(); } else { return 1.0f; } double dlat = Math.abs(rlat[1] - rlat[0]); double dlon = Math.abs(rlon[1] - rlon[0]); if (dlat != dlat) dlat = 1.0f; if (dlon != dlon) dlon = 1.0f; return (dlat > dlon) ? (float) dlat : (float) dlon; } /** convert (lat, lon) or (lat, lon, other) values to display (x, y, z) */ public float[][] earthToSpatial(float[][] locs, float[] vert) throws VisADException { return earthToSpatial(locs, vert, null); } public float[][] earthToSpatial(float[][] locs, float[] vert, float[][] base_spatial_locs) throws VisADException { int lat = lat_index; int lon = lon_index; int other = other_index; if (lat_index < 0 || lon_index < 0) return null; int size = locs[0].length; if (locs.length < lat_lon_dimension) { // extend locs to lat_lon_dimension with zero fill float[][] temp = locs; locs = new float[lat_lon_dimension][]; for (int i=0; i<locs.length; i++) { locs[i] = temp[i]; } float[] zero = new float[size]; for (int j=0; j<size; j++) zero[j] = 0.0f; for (int i=locs.length; i<lat_lon_dimension; i++) { locs[i] = zero; } } else if (locs.length > lat_lon_dimension) { // truncate locs to lat_lon_dimension float[][] temp = locs; locs = new float[lat_lon_dimension][]; for (int i=0; i<lat_lon_dimension; i++) { locs[i] = temp[i]; } } // permute (lat, lon, other) to data RealTupleType float[][] tuple_locs = new float[lat_lon_dimension][]; float[][] spatial_locs = new float[3][]; tuple_locs[lat] = locs[0]; tuple_locs[lon] = locs[1]; if (lat_lon_dimension == 3) tuple_locs[other] = locs[2]; int vert_index = -1; // non-lat/lon index for lat_lon_dimension = 2 if (lat_lon_in) { if (lat_lon_in_by_coord) { // transform 'RealTupleType data_in' to 'RealTupleType data_out' if (data_coord_in.length == 1) { // one data_coord_in applies to all data points tuple_locs = CoordinateSystem.transformCoordinates(data_out, null, data_units_out, null, data_in, data_coord_in[0], data_units_in, null, tuple_locs); } else { // one data_coord_in per data point float[][] temp = new float[lat_lon_dimension][1]; for (int j=0; j<size; j++) { for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j]; temp = CoordinateSystem.transformCoordinates(data_out, null, data_units_out, null, data_in, data_coord_in[j], data_units_in, null, temp); for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0]; } } // map data_out to spatial DisplayRealTypes for (int i=0; i<lat_lon_dimension; i++) { spatial_locs[sdo_spatial_index[i]] = sdo_maps[i].scaleValues(tuple_locs[i]); } if (lat_lon_dimension == 2) { vert_index = 3 - (sdo_spatial_index[0] + sdo_spatial_index[1]); } } else { // map data_in to spatial DisplayRealTypes for (int i=0; i<lat_lon_dimension; i++) { spatial_locs[sdi_spatial_index[i]] = sdi_maps[i].scaleValues(tuple_locs[i]); } if (lat_lon_dimension == 2) { vert_index = 3 - (sdi_spatial_index[0] + sdi_spatial_index[1]); } } } else if (lat_lon_out) { if (lat_lon_out_by_coord) { // transform 'RealTupleType data_out' to 'RealTupleType data_in' if (data_coord_in.length == 1) { // one data_coord_in applies to all data points tuple_locs = CoordinateSystem.transformCoordinates(data_in, data_coord_in[0], data_units_in, null, data_out, null, data_units_out, null, tuple_locs); } else { // one data_coord_in per data point float[][] temp = new float[lat_lon_dimension][1]; for (int j=0; j<size; j++) { for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j]; temp = CoordinateSystem.transformCoordinates(data_in, data_coord_in[j], data_units_in, null, data_out, null, data_units_out, null, temp); for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0]; } } // map data_in to spatial DisplayRealTypes for (int i=0; i<lat_lon_dimension; i++) { spatial_locs[sdi_spatial_index[i]] = sdi_maps[i].scaleValues(tuple_locs[i]); } if (lat_lon_dimension == 2) { vert_index = 3 - (sdi_spatial_index[0] + sdi_spatial_index[1]); } } else { // map data_out to spatial DisplayRealTypes for (int i=0; i<lat_lon_dimension; i++) { spatial_locs[sdo_spatial_index[i]] = sdo_maps[i].scaleValues(tuple_locs[i]); } if (lat_lon_dimension == 2) { vert_index = 3 - (sdo_spatial_index[0] + sdo_spatial_index[1]); } } } else if (lat_lon_spatial) { // map lat & lon, not in allSpatial RealTupleType, to // spatial DisplayRealTypes spatial_locs[lat_spatial_index] = lat_map.scaleValues(tuple_locs[lat]); spatial_locs[lon_spatial_index] = lon_map.scaleValues(tuple_locs[lon]); vert_index = 3 - (lat_spatial_index + lon_spatial_index); } else { // should never happen return null; } // WLH 9 Dec 99 // fill any empty spatial DisplayRealTypes with default values for (int i=0; i<3; i++) { if (spatial_locs[i] == null) { if (base_spatial_locs != null && base_spatial_locs[i] != null) { spatial_locs[i] = base_spatial_locs[i]; // copy not necessary } else { spatial_locs[i] = new float[size]; float def = default_spatial_in[i]; // may be non-Cartesian for (int j=0; j<size; j++) spatial_locs[i][j] = def; } } } // adjust non-lat/lon spatial_locs by vertical flow component /* WLH 28 July 99 if (vert != null && vert_index > -1) { for (int j=0; j<size; j++) spatial_locs[vert_index][j] += vert[j]; } */ - if (spatial_locs[vert_index] != null) { - if (vert != null && vert_index > -1) { - for (int j=0; j<size; j++) spatial_locs[vert_index][j] += vert[j]; - } + if (vert != null && vert_index > -1 && spatial_locs[vert_index] != null) { + for (int j=0; j<size; j++) spatial_locs[vert_index][j] += vert[j]; } if (display_coordinate_system != null) { // transform non-Cartesian spatial DisplayRealTypes to Cartesian spatial_locs = display_coordinate_system.toReference(spatial_locs); } return spatial_locs; } /** convert display (x, y, z) to (lat, lon) or (lat, lon, other) values */ public float[][] spatialToEarth(float[][] spatial_locs) throws VisADException { float[][] base_spatial_locs = new float[3][]; return spatialToEarth(spatial_locs, base_spatial_locs); } public float[][] spatialToEarth(float[][] spatial_locs, float[][] base_spatial_locs) throws VisADException { int lat = lat_index; int lon = lon_index; int other = other_index; if (lat_index < 0 || lon_index < 0) return null; if (spatial_locs.length != 3) return null; int size = 0; for (int i=0; i<3; i++) { if (spatial_locs[i] != null && spatial_locs[i].length > size) { size = spatial_locs[i].length; } } if (size == 0) return null; // fill any empty spatial DisplayRealTypes with default values for (int i=0; i<3; i++) { if (spatial_locs[i] == null) { spatial_locs[i] = new float[size]; // defaults for Cartesian spatial DisplayRealTypes = 0.0f for (int j=0; j<size; j++) spatial_locs[i][j] = 0.0f; } } if (display_coordinate_system != null) { // transform Cartesian spatial DisplayRealTypes to non-Cartesian spatial_locs = display_coordinate_system.fromReference(spatial_locs); } base_spatial_locs[0] = spatial_locs[0]; base_spatial_locs[1] = spatial_locs[1]; base_spatial_locs[2] = spatial_locs[2]; float[][] tuple_locs = new float[lat_lon_dimension][]; if (lat_lon_in) { if (lat_lon_in_by_coord) { // map spatial DisplayRealTypes to data_out for (int i=0; i<lat_lon_dimension; i++) { tuple_locs[i] = sdo_maps[i].inverseScaleValues(spatial_locs[sdo_spatial_index[i]]); } // transform 'RealTupleType data_out' to 'RealTupleType data_in' if (data_coord_in.length == 1) { // one data_coord_in applies to all data points tuple_locs = CoordinateSystem.transformCoordinates(data_in, data_coord_in[0], data_units_in, null, data_out, null, data_units_out, null, tuple_locs); } else { // one data_coord_in per data point float[][] temp = new float[lat_lon_dimension][1]; for (int j=0; j<size; j++) { for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j]; temp = CoordinateSystem.transformCoordinates(data_in, data_coord_in[j], data_units_in, null, data_out, null, data_units_out, null, temp); for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0]; } } } else { // map spatial DisplayRealTypes to data_in for (int i=0; i<lat_lon_dimension; i++) { tuple_locs[i] = sdi_maps[i].inverseScaleValues(spatial_locs[sdi_spatial_index[i]]); } } } else if (lat_lon_out) { if (lat_lon_out_by_coord) { // map spatial DisplayRealTypes to data_in for (int i=0; i<lat_lon_dimension; i++) { tuple_locs[i] = sdi_maps[i].inverseScaleValues(spatial_locs[sdi_spatial_index[i]]); } // transform 'RealTupleType data_in' to 'RealTupleType data_out' if (data_coord_in.length == 1) { // one data_coord_in applies to all data points tuple_locs = CoordinateSystem.transformCoordinates(data_out, null, data_units_out, null, data_in, data_coord_in[0], data_units_in, null, tuple_locs); } else { // one data_coord_in per data point float[][] temp = new float[lat_lon_dimension][1]; for (int j=0; j<size; j++) { for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j]; temp = CoordinateSystem.transformCoordinates(data_out, null, data_units_out, null, data_in, data_coord_in[j], data_units_in, null, temp); for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0]; } } } else { // map spatial DisplayRealTypes to data_out for (int i=0; i<lat_lon_dimension; i++) { tuple_locs[i] = sdo_maps[i].inverseScaleValues(spatial_locs[sdo_spatial_index[i]]); } } } else if (lat_lon_spatial) { // map spatial DisplayRealTypes to lat & lon, not in // allSpatial RealTupleType tuple_locs[lat] = lat_map.inverseScaleValues(spatial_locs[lat_spatial_index]); tuple_locs[lon] = lon_map.inverseScaleValues(spatial_locs[lon_spatial_index]); } else { // should never happen return null; } // permute data RealTupleType to (lat, lon, other) float[][] locs = new float[lat_lon_dimension][]; locs[0] = tuple_locs[lat]; locs[1] = tuple_locs[lon]; if (lat_lon_dimension == 3) locs[2] = tuple_locs[other]; return locs; } // information from doTransform public void setEarthSpatialData(ShadowRealTupleType s_d_i, ShadowRealTupleType s_d_o, RealTupleType d_o, Unit[] d_u_o, RealTupleType d_i, CoordinateSystem[] d_c_i, Unit[] d_u_i) throws VisADException { // first check for VectorRealType components mapped to flow // TO_DO: check here for flow mapped via CoordinateSystem if (d_o != null && d_o instanceof RealVectorType) { ScalarMap[] maps = new ScalarMap[3]; int k = getFlowMaps(s_d_o, maps); if (k > -1) rvts[k] = (RealVectorType) d_o; } if (d_i != null && d_i instanceof RealVectorType) { ScalarMap[] maps = new ScalarMap[3]; int k = getFlowMaps(s_d_i, maps); if (k > -1) rvts[k] = (RealVectorType) d_i; } int lat_index_local = -1; int lon_index_local = -1; other_index = -1; int n = 0; int m = 0; if (d_i != null) { n = d_i.getDimension(); for (int i=0; i<n; i++) { RealType real = (RealType) d_i.getComponent(i); if (RealType.Latitude.equals(real)) lat_index_local = i; if (RealType.Longitude.equals(real)) lon_index_local = i; } } if (lat_index_local > -1 && lon_index_local > -1 && (n == 2 || n == 3)) { if (s_d_i != null && s_d_i.getAllSpatial() && !s_d_i.getSpatialReference()) { lat_lon_in_by_coord = false; sdi_spatial_index = new int[s_d_i.getDimension()]; sdi_maps = getSpatialMaps(s_d_i, sdi_spatial_index); if (sdi_maps == null) { throw new DisplayException("sdi_maps null A"); } } else if (s_d_o != null && s_d_o.getAllSpatial() && !s_d_o.getSpatialReference()) { lat_lon_in_by_coord = true; sdo_spatial_index = new int[s_d_o.getDimension()]; sdo_maps = getSpatialMaps(s_d_o, sdo_spatial_index); if (sdo_maps == null) { throw new DisplayException("sdo_maps null A"); } } else { // do not update lat_index & lon_index return; } lat_lon_in = true; lat_lon_out = false; lat_lon_out_by_coord = false; lat_lon_spatial = false; lat_lon_dimension = n; if (n == 3) { other_index = 3 - (lat_index_local + lon_index_local); if (Unit.canConvert(d_u_i[other_index], CommonUnit.meter)) { other_meters = true; } } } else { // if( !(lat & lon in di, di dimension = 2 or 3) ) lat_index_local = -1; lon_index_local = -1; if (d_o != null) { m = d_o.getDimension(); for (int i=0; i<m; i++) { RealType real = (RealType) d_o.getComponent(i); if (RealType.Latitude.equals(real)) lat_index_local = i; if (RealType.Longitude.equals(real)) lon_index_local = i; } } if (lat_index_local < 0 || lon_index_local < 0 || !(m == 2 || m == 3)) { // do not update lat_index & lon_index return; } if (s_d_o != null && s_d_o.getAllSpatial() && !s_d_o.getSpatialReference()) { lat_lon_out_by_coord = false; sdo_spatial_index = new int[s_d_o.getDimension()]; sdo_maps = getSpatialMaps(s_d_o, sdo_spatial_index); if (sdo_maps == null) { throw new DisplayException("sdo_maps null B"); } } else if (s_d_i != null && s_d_i.getAllSpatial() && !s_d_i.getSpatialReference()) { lat_lon_out_by_coord = true; sdi_spatial_index = new int[s_d_i.getDimension()]; sdi_maps = getSpatialMaps(s_d_i, sdi_spatial_index); if (sdi_maps == null) { throw new DisplayException("sdi_maps null B"); } } else { // do not update lat_index & lon_index return; } lat_lon_out = true; lat_lon_in = false; lat_lon_in_by_coord = false; lat_lon_spatial = false; lat_lon_dimension = m; if (m == 3) { other_index = 3 - (lat_index_local + lon_index_local); if (Unit.canConvert(d_u_i[other_index], CommonUnit.meter)) { other_meters = true; } } } shadow_data_out = s_d_o; data_out = d_o; data_units_out = d_u_o; shadow_data_in = s_d_i; data_in = d_i; data_units_in = d_u_i; data_coord_in = d_c_i; // may be one per point lat_index = lat_index_local; lon_index = lon_index_local; return; } /** return array of spatial ScalarMap for srt, or null */ private ScalarMap[] getSpatialMaps(ShadowRealTupleType srt, int[] spatial_index) { int n = srt.getDimension(); ScalarMap[] maps = new ScalarMap[n]; for (int i=0; i<n; i++) { ShadowRealType real = (ShadowRealType) srt.getComponent(i); Enumeration ms = real.getSelectedMapVector().elements(); while (ms.hasMoreElements()) { ScalarMap map = (ScalarMap) ms.nextElement(); DisplayRealType dreal = map.getDisplayScalar(); DisplayTupleType tuple = dreal.getTuple(); if (tuple != null && (tuple.equals(Display.DisplaySpatialCartesianTuple) || (tuple.getCoordinateSystem() != null && tuple.getCoordinateSystem().getReference().equals( Display.DisplaySpatialCartesianTuple)))) { maps[i] = map; spatial_index[i] = dreal.getTupleIndex(); break; } } if (maps[i] == null) { return null; } } return maps; } /** return array of flow ScalarMap for srt, or null */ private int getFlowMaps(ShadowRealTupleType srt, ScalarMap[] maps) { int n = srt.getDimension(); maps[0] = null; maps[1] = null; maps[2] = null; DisplayTupleType ftuple = null; for (int i=0; i<n; i++) { ShadowRealType real = (ShadowRealType) srt.getComponent(i); Enumeration ms = real.getSelectedMapVector().elements(); while (ms.hasMoreElements()) { ScalarMap map = (ScalarMap) ms.nextElement(); DisplayRealType dreal = map.getDisplayScalar(); DisplayTupleType tuple = dreal.getTuple(); if (Display.DisplayFlow1Tuple.equals(tuple) || Display.DisplayFlow2Tuple.equals(tuple)) { if (ftuple != null && !ftuple.equals(tuple)) return -1; ftuple = tuple; maps[i] = map; break; } } if (maps[i] == null) return -1; } return Display.DisplayFlow1Tuple.equals(ftuple) ? 0 : 1; } // from assembleFlow ScalarMap[][] flow_maps = null; float[] flow_scale = null; public void setFlowDisplay(ScalarMap[][] maps, float[] fs) { flow_maps = maps; flow_scale = fs; } // if non-null, float[][] new_spatial_values = // display_coordinate_system.toReference(spatial_values); CoordinateSystem display_coordinate_system = null; // spatial_tuple and spatial_value_indices are set whether // display_coordinate_system is null or not DisplayTupleType spatial_tuple = null; // map from spatial_tuple tuple_index to value array indices int[] spatial_value_indices = {-1, -1, -1}; float[] default_spatial_in = {0.0f, 0.0f, 0.0f}; // true if lat and lon mapped directly to spatial boolean lat_lon_spatial = false; ScalarMap lat_map = null; ScalarMap lon_map = null; int lat_spatial_index = -1; int lon_spatial_index = -1; // spatial map getRange() results for flow adjustment double[] ranges = null; public double[] getRanges() { return ranges; } // WLH 4 March 2000 public CoordinateSystem getDisplayCoordinateSystem() { return display_coordinate_system ; } // information from assembleSpatial public void setEarthSpatialDisplay(CoordinateSystem coord, DisplayTupleType t, DisplayImpl display, int[] indices, float[] default_values, double[] r) throws VisADException { display_coordinate_system = coord; spatial_tuple = t; System.arraycopy(indices, 0, spatial_value_indices, 0, 3); /* WLH 5 Dec 99 spatial_value_indices = indices; */ ranges = r; for (int i=0; i<3; i++) { int default_index = display.getDisplayScalarIndex( ((DisplayRealType) t.getComponent(i)) ); default_spatial_in[i] = default_values[default_index]; } if (lat_index > -1 && lon_index > -1) return; lat_index = -1; lon_index = -1; other_index = -1; int valueArrayLength = display.getValueArrayLength(); int[] valueToScalar = display.getValueToScalar(); int[] valueToMap = display.getValueToMap(); Vector MapVector = display.getMapVector(); for (int i=0; i<valueArrayLength; i++) { ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]); ScalarType real = map.getScalar(); DisplayRealType dreal = map.getDisplayScalar(); DisplayTupleType tuple = dreal.getTuple(); if (tuple != null && (tuple.equals(Display.DisplaySpatialCartesianTuple) || (tuple.getCoordinateSystem() != null && tuple.getCoordinateSystem().getReference().equals( Display.DisplaySpatialCartesianTuple)))) { if (RealType.Latitude.equals(real)) { lat_index = 0; lat_map = map; lat_spatial_index = dreal.getTupleIndex(); } if (RealType.Longitude.equals(real)) { lon_index = 1; lon_map = map; lon_spatial_index = dreal.getTupleIndex(); } } } if (lat_index > -1 && lon_index > -1) { lat_lon_spatial = true; lat_lon_dimension = 2; lat_lon_out = false; lat_lon_in_by_coord = false; lat_lon_in = false; } else { lat_lon_spatial = false; lat_index = -1; lon_index = -1; } } /* *************************** */ /* direct manipulation stuff */ /* *************************** */ private float[][] spatialValues = null; /** if Function, last domain index and range values */ private int lastIndex = -1; double[] lastD = null; float[] lastX = new float[6]; /** index into spatialValues found by checkClose */ private int closeIndex = -1; /** for use in drag_direct */ private transient DataDisplayLink link = null; // private transient ShadowTypeJ3D type = null; private transient DataReference ref = null; private transient MathType type = null; private transient ShadowType shadow = null; /** point on direct manifold line or plane */ private float point_x, point_y, point_z; /** normalized direction of line or perpendicular to plane */ private float line_x, line_y, line_z; /** arrays of length one for inverseScaleValues */ private float[] f = new float[1]; private float[] d = new float[1]; private float[][] value = new float[1][1]; /** information calculated by checkDirect */ /** explanation for invalid use of DirectManipulationRenderer */ private String whyNotDirect = null; /** mapping from spatial axes to tuple component */ private int[] axisToComponent = {-1, -1, -1}; /** mapping from spatial axes to ScalarMaps */ private ScalarMap[] directMap = {null, null, null}; /** spatial axis for Function domain */ private int domainAxis = -1; /** dimension of direct manipulation (including any Function domain) */ private int directManifoldDimension = 0; /** spatial DisplayTupleType other than DisplaySpatialCartesianTuple */ DisplayTupleType tuple; /** possible values for whyNotDirect */ private final static String notRealFunction = "FunctionType must be Real"; private final static String notSimpleField = "not simple field"; private final static String notSimpleTuple = "not simple tuple"; private final static String multipleMapping = "RealType with multiple mappings"; private final static String multipleSpatialMapping = "RealType with multiple spatial mappings"; private final static String nonSpatial = "no spatial mapping"; private final static String viaReference = "spatial mapping through Reference"; private final static String domainDimension = "domain dimension must be 1"; private final static String domainNotSpatial = "domain must be mapped to spatial"; private final static String rangeType = "range must be RealType or RealTupleType"; private final static String rangeNotSpatial = "range must be mapped to spatial"; private final static String domainSet = "domain Set must be Gridded1DSet"; private final static String tooFewSpatial = "Function without spatial domain"; private final static String functionTooFew = "Function directManifoldDimension < 2"; private final static String badCoordSysManifoldDim = "bad directManifoldDimension with spatial CoordinateSystem"; public synchronized void realCheckDirect() throws VisADException, RemoteException { setIsDirectManipulation(false); link = getLinks()[0]; ref = link.getDataReference(); shadow = link.getShadow().getAdaptedShadowType(); type = link.getType(); tuple = null; if (type instanceof FunctionType) { ShadowRealTupleType domain = ((ShadowFunctionType) shadow).getDomain(); ShadowType range = ((ShadowFunctionType) shadow).getRange(); tuple = domain.getDisplaySpatialTuple(); // there is some redundancy among these conditions if (!((FunctionType) type).getReal()) { whyNotDirect = notRealFunction; return; } else if (shadow.getLevelOfDifficulty() != ShadowType.SIMPLE_FIELD) { whyNotDirect = notSimpleTuple; return; } else if (shadow.getMultipleSpatialDisplayScalar()) { whyNotDirect = multipleSpatialMapping; return; } else if (domain.getDimension() != 1) { whyNotDirect = domainDimension; return; } else if(!(Display.DisplaySpatialCartesianTuple.equals(tuple) || (tuple != null && tuple.getCoordinateSystem().getReference().equals( Display.DisplaySpatialCartesianTuple)) )) { whyNotDirect = domainNotSpatial; return; } else if (domain.getSpatialReference()) { whyNotDirect = viaReference; return; } DisplayTupleType rtuple = null; if (range instanceof ShadowRealTupleType) { rtuple = ((ShadowRealTupleType) range).getDisplaySpatialTuple(); } else if (range instanceof ShadowRealType) { rtuple = ((ShadowRealType) range).getDisplaySpatialTuple(); } else { whyNotDirect = rangeType; return; } if (!tuple.equals(rtuple)) { /* WLH 3 Aug 98 if (!Display.DisplaySpatialCartesianTuple.equals(rtuple)) { */ whyNotDirect = rangeNotSpatial; return; } else if (range instanceof ShadowRealTupleType && ((ShadowRealTupleType) range).getSpatialReference()) { whyNotDirect = viaReference; return; } else if (!(link.getData() instanceof Field) || !(((Field) link.getData()).getDomainSet() instanceof Gridded1DSet)) { whyNotDirect = domainSet; return; } if (Display.DisplaySpatialCartesianTuple.equals(tuple)) { tuple = null; } domainAxis = -1; for (int i=0; i<3; i++) { axisToComponent[i] = -1; directMap[i] = null; } directManifoldDimension = setDirectMap((ShadowRealType) domain.getComponent(0), -1, true); if (range instanceof ShadowRealType) { directManifoldDimension += setDirectMap((ShadowRealType) range, 0, false); } else if (range instanceof ShadowRealTupleType) { ShadowRealTupleType r = (ShadowRealTupleType) range; for (int i=0; i<r.getDimension(); i++) { directManifoldDimension += setDirectMap((ShadowRealType) r.getComponent(i), i, false); } } if (domainAxis == -1) { whyNotDirect = tooFewSpatial; return; } if (directManifoldDimension < 2) { whyNotDirect = functionTooFew; return; } boolean twod = displayRenderer.getMode2D(); if (tuple != null && (!twod && directManifoldDimension != 3 || twod && directManifoldDimension != 2) ) { whyNotDirect = badCoordSysManifoldDim; return; } setIsDirectManipulation(true); /* WLH 3 Aug 98 if (domainAxis == -1) { throw new DisplayException("DataRenderer.realCheckDirect:" + "too few spatial domain"); } if (directManifoldDimension < 2) { throw new DisplayException("DataRenderer.realCheckDirect:" + "directManifoldDimension < 2"); } */ } else if (type instanceof RealTupleType) { // // TO_DO // allow for any Flat ShadowTupleType // tuple = ((ShadowRealTupleType) shadow).getDisplaySpatialTuple(); if (shadow.getLevelOfDifficulty() != ShadowType.SIMPLE_TUPLE) { whyNotDirect = notSimpleTuple; return; } else if (shadow.getMultipleSpatialDisplayScalar()) { whyNotDirect = multipleSpatialMapping; return; } else if(!(Display.DisplaySpatialCartesianTuple.equals(tuple) || (tuple != null && tuple.getCoordinateSystem().getReference().equals( Display.DisplaySpatialCartesianTuple)) )) { /* WLH 3 Aug 98 else if (!Display.DisplaySpatialCartesianTuple.equals( ((ShadowRealTupleType) shadow).getDisplaySpatialTuple())) { */ whyNotDirect = nonSpatial; return; } else if (((ShadowRealTupleType) shadow).getSpatialReference()) { whyNotDirect = viaReference; return; } /* WLH 3 Aug 98 setIsDirectManipulation(true); */ if (Display.DisplaySpatialCartesianTuple.equals(tuple)) { tuple = null; } domainAxis = -1; for (int i=0; i<3; i++) { axisToComponent[i] = -1; directMap[i] = null; } directManifoldDimension = 0; for (int i=0; i<((ShadowRealTupleType) shadow).getDimension(); i++) { directManifoldDimension += setDirectMap((ShadowRealType) ((ShadowRealTupleType) shadow).getComponent(i), i, false); } boolean twod = displayRenderer.getMode2D(); if (tuple != null && (!twod && directManifoldDimension != 3 || twod && directManifoldDimension != 2) ) { whyNotDirect = badCoordSysManifoldDim; return; } setIsDirectManipulation(true); } else if (type instanceof RealType) { tuple = ((ShadowRealType) shadow).getDisplaySpatialTuple(); if (shadow.getLevelOfDifficulty() != ShadowType.SIMPLE_TUPLE) { whyNotDirect = notSimpleTuple; return; } else if (shadow.getMultipleSpatialDisplayScalar()) { whyNotDirect = multipleSpatialMapping; return; } else if(!(Display.DisplaySpatialCartesianTuple.equals(tuple) || (tuple != null && tuple.getCoordinateSystem().getReference().equals( Display.DisplaySpatialCartesianTuple)) )) { /* WLH 3 Aug 98 else if(!Display.DisplaySpatialCartesianTuple.equals( ((ShadowRealType) shadow).getDisplaySpatialTuple())) { */ whyNotDirect = nonSpatial; return; } /* WLH 3 Aug 98 setIsDirectManipulation(true); */ if (Display.DisplaySpatialCartesianTuple.equals(tuple)) { tuple = null; } domainAxis = -1; for (int i=0; i<3; i++) { axisToComponent[i] = -1; directMap[i] = null; } directManifoldDimension = setDirectMap((ShadowRealType) shadow, 0, false); boolean twod = displayRenderer.getMode2D(); if (tuple != null && (!twod && directManifoldDimension != 3 || twod && directManifoldDimension != 2) ) { whyNotDirect = badCoordSysManifoldDim; return; } setIsDirectManipulation(true); } // end else if (type instanceof RealType) } /** set directMap and axisToComponent (domain = false) or domainAxis (domain = true) from real; called by realCheckDirect */ synchronized int setDirectMap(ShadowRealType real, int component, boolean domain) { Enumeration maps = real.getSelectedMapVector().elements(); while (maps.hasMoreElements()) { ScalarMap map = (ScalarMap) maps.nextElement(); DisplayRealType dreal = map.getDisplayScalar(); DisplayTupleType tuple = dreal.getTuple(); if (Display.DisplaySpatialCartesianTuple.equals(tuple) || (tuple != null && tuple.getCoordinateSystem().getReference().equals( Display.DisplaySpatialCartesianTuple)) ) { int index = dreal.getTupleIndex(); if (domain) { domainAxis = index; } else { axisToComponent[index] = component; } directMap[index] = map; return 1; } } return 0; } private int getDirectManifoldDimension() { return directManifoldDimension; } public String getWhyNotDirect() { return whyNotDirect; } private int getAxisToComponent(int i) { return axisToComponent[i]; } private ScalarMap getDirectMap(int i) { return directMap[i]; } private int getDomainAxis() { return domainAxis; } /** set spatialValues from ShadowType.doTransform */ public synchronized void setSpatialValues(float[][] spatial_values) { // these are X, Y, Z values spatialValues = spatial_values; } /** find minimum distance from ray to spatialValues */ public synchronized float checkClose(double[] origin, double[] direction) { float distance = Float.MAX_VALUE; lastIndex = -1; if (spatialValues == null) return distance; float o_x = (float) origin[0]; float o_y = (float) origin[1]; float o_z = (float) origin[2]; float d_x = (float) direction[0]; float d_y = (float) direction[1]; float d_z = (float) direction[2]; /* System.out.println("origin = " + o_x + " " + o_y + " " + o_z); System.out.println("direction = " + d_x + " " + d_y + " " + d_z); */ for (int i=0; i<spatialValues[0].length; i++) { float x = spatialValues[0][i] - o_x; float y = spatialValues[1][i] - o_y; float z = spatialValues[2][i] - o_z; float dot = x * d_x + y * d_y + z * d_z; x = x - dot * d_x; y = y - dot * d_y; z = z - dot * d_z; float d = (float) Math.sqrt(x * x + y * y + z * z); if (d < distance) { distance = d; closeIndex = i; } /* System.out.println("spatialValues["+i+"] = " + spatialValues[0][i] + " " + spatialValues[1][i] + " " + spatialValues[2][i] + " d = " + d); */ } /* System.out.println("checkClose: distance = " + distance); */ return distance; } /** mouse button released, ending direct manipulation */ public synchronized void release_direct() { } public synchronized void drag_direct(VisADRay ray, boolean first, int mouseModifiers) { // System.out.println("drag_direct " + first + " " + type); if (spatialValues == null || ref == null || shadow == null) return; float o_x = (float) ray.position[0]; float o_y = (float) ray.position[1]; float o_z = (float) ray.position[2]; float d_x = (float) ray.vector[0]; float d_y = (float) ray.vector[1]; float d_z = (float) ray.vector[2]; if (first) { point_x = spatialValues[0][closeIndex]; point_y = spatialValues[1][closeIndex]; point_z = spatialValues[2][closeIndex]; int lineAxis = -1; if (getDirectManifoldDimension() == 3) { // coord sys ok line_x = d_x; line_y = d_y; line_z = d_z; } else { if (getDirectManifoldDimension() == 2) { if (displayRenderer.getMode2D()) { // coord sys ok lineAxis = 2; } else { for (int i=0; i<3; i++) { if (getAxisToComponent(i) < 0 && getDomainAxis() != i) { lineAxis = i; } } } } else if (getDirectManifoldDimension() == 1) { for (int i=0; i<3; i++) { if (getAxisToComponent(i) >= 0) { lineAxis = i; } } } line_x = (lineAxis == 0) ? 1.0f : 0.0f; line_y = (lineAxis == 1) ? 1.0f : 0.0f; line_z = (lineAxis == 2) ? 1.0f : 0.0f; } } // end if (first) float[] x = new float[3]; // x marks the spot if (getDirectManifoldDimension() == 1) { // find closest point on line to ray // logic from vis5d/cursor.c // line o_, d_ to line point_, line_ float ld = d_x * line_x + d_y * line_y + d_z * line_z; float od = o_x * d_x + o_y * d_y + o_z * d_z; float pd = point_x * d_x + point_y * d_y + point_z * d_z; float ol = o_x * line_x + o_y * line_y + o_z * line_z; float pl = point_x * line_x + point_y * line_y + point_z * line_z; if (ld * ld == 1.0f) return; float t = ((pl - ol) - (ld * (pd - od))) / (ld * ld - 1.0f); // x is closest point x[0] = point_x + t * line_x; x[1] = point_y + t * line_y; x[2] = point_z + t * line_z; } else { // getDirectManifoldDimension() = 2 or 3 // intersect ray with plane float dot = (point_x - o_x) * line_x + (point_y - o_y) * line_y + (point_z - o_z) * line_z; float dot2 = d_x * line_x + d_y * line_y + d_z * line_z; if (dot2 == 0.0) return; dot = dot / dot2; // x is intersection x[0] = o_x + dot * d_x; x[1] = o_y + dot * d_y; x[2] = o_z + dot * d_z; } // // TO_DO // might estimate errors from pixel resolution on screen // try { float[] xx = {x[0], x[1], x[2]}; if (tuple != null) { float[][] cursor = {{x[0]}, {x[1]}, {x[2]}}; float[][] new_cursor = tuple.getCoordinateSystem().fromReference(cursor); x[0] = new_cursor[0][0]; x[1] = new_cursor[1][0]; x[2] = new_cursor[2][0]; } Data newData = null; Data data = link.getData(); if (type instanceof RealType) { addPoint(xx); for (int i=0; i<3; i++) { if (getAxisToComponent(i) >= 0) { f[0] = x[i]; d = getDirectMap(i).inverseScaleValues(f); // RealType rtype = (RealType) data.getType(); RealType rtype = (RealType) type; newData = new Real(rtype, (double) d[0], rtype.getDefaultUnit(), null); // create location string Vector vect = new Vector(); /* WLH 26 July 99 float g = d[0]; vect.addElement(rtype.getName() + " = " + g); */ String valueString = new Real(rtype, d[0]).toValueString(); vect.addElement(rtype.getName() + " = " + valueString); getDisplayRenderer().setCursorStringVector(vect); break; } } ref.setData(newData); link.clearData(); // WLH 27 July 99 } else if (type instanceof RealTupleType) { addPoint(xx); int n = ((RealTuple) data).getDimension(); Real[] reals = new Real[n]; Vector vect = new Vector(); for (int i=0; i<3; i++) { int j = getAxisToComponent(i); if (j >= 0) { f[0] = x[i]; d = getDirectMap(i).inverseScaleValues(f); Real c = (Real) ((RealTuple) data).getComponent(j); RealType rtype = (RealType) c.getType(); reals[j] = new Real(rtype, (double) d[0], rtype.getDefaultUnit(), null); // create location string /* WLH 26 July 99 float g = d[0]; vect.addElement(rtype.getName() + " = " + g); */ String valueString = new Real(rtype, d[0]).toValueString(); vect.addElement(rtype.getName() + " = " + valueString); } } getDisplayRenderer().setCursorStringVector(vect); for (int j=0; j<n; j++) { if (reals[j] == null) { reals[j] = (Real) ((RealTuple) data).getComponent(j); } } newData = new RealTuple((RealTupleType) type, reals, ((RealTuple) data).getCoordinateSystem()); ref.setData(newData); link.clearData(); // WLH 27 July 99 } else if (type instanceof FunctionType) { Vector vect = new Vector(); if (first) lastIndex = -1; int k = getDomainAxis(); f[0] = x[k]; d = getDirectMap(k).inverseScaleValues(f); RealType rtype = (RealType) getDirectMap(k).getScalar(); // WLH 4 Jan 99 // convert d from default Unit to actual domain Unit of data Unit[] us = ((Field) data).getDomainUnits(); if (us != null && us[0] != null) { d[0] = (float) us[0].toThis((double) d[0], rtype.getDefaultUnit()); } // create location string float g = d[0]; vect.addElement(rtype.getName() + " = " + g); // convert domain value to domain index Gridded1DSet set = (Gridded1DSet) ((Field) data).getDomainSet(); value[0][0] = (float) d[0]; int[] indices = set.valueToIndex(value); int thisIndex = indices[0]; if (thisIndex < 0) { lastIndex = -1; return; } if (lastIndex < 0) { addPoint(xx); } else { lastX[3] = xx[0]; lastX[4] = xx[1]; lastX[5] = xx[2]; addPoint(lastX); } lastX[0] = xx[0]; lastX[1] = xx[1]; lastX[2] = xx[2]; int n; MathType range = ((FunctionType) type).getRange(); if (range instanceof RealType) { n = 1; } else { n = ((RealTupleType) range).getDimension(); } double[] thisD = new double[n]; boolean[] directComponent = new boolean[n]; for (int j=0; j<n; j++) { thisD[j] = Double.NaN; directComponent[j] = false; } for (int i=0; i<3; i++) { int j = getAxisToComponent(i); if (j >= 0) { f[0] = x[i]; d = getDirectMap(i).inverseScaleValues(f); // create location string rtype = (RealType) getDirectMap(i).getScalar(); /* WLH 26 July 99 g = (float) d[0]; vect.addElement(rtype.getName() + " = " + g); */ String valueString = new Real(rtype, d[0]).toValueString(); vect.addElement(rtype.getName() + " = " + valueString); thisD[j] = d[0]; directComponent[j] = true; } } getDisplayRenderer().setCursorStringVector(vect); if (lastIndex < 0) { lastIndex = thisIndex; lastD = new double[n]; for (int j=0; j<n; j++) { lastD[j] = thisD[j]; } } Real[] reals = new Real[n]; int m = Math.abs(lastIndex - thisIndex) + 1; indices = new int[m]; int index = thisIndex; int inc = (lastIndex >= thisIndex) ? 1 : -1; for (int i=0; i<m; i++) { indices[i] = index; index += inc; } float[][] values = set.indexToValue(indices); double coefDiv = values[0][m-1] - values[0][0]; for (int i=0; i<m; i++) { index = indices[i]; double coef = (i == 0 || coefDiv == 0.0) ? 0.0 : (values[0][i] - values[0][0]) / coefDiv; Data tuple = ((Field) data).getSample(index); if (tuple instanceof Real) { if (directComponent[0]) { rtype = (RealType) tuple.getType(); tuple = new Real(rtype, thisD[0] + coef * (lastD[0] - thisD[0]), rtype.getDefaultUnit(), null); } } else { for (int j=0; j<n; j++) { Real c = (Real) ((RealTuple) tuple).getComponent(j); if (directComponent[j]) { rtype = (RealType) c.getType(); reals[j] = new Real(rtype, thisD[j] + coef * (lastD[j] - thisD[j]), rtype.getDefaultUnit(), null); } else { reals[j] = c; } } tuple = new RealTuple(reals); } ((Field) data).setSample(index, tuple); } // end for (int i=0; i<m; i++) if (ref instanceof RemoteDataReference && !(data instanceof RemoteData)) { // ref is Remote and data is local, so we have only modified // a local copy and must send it back to ref ref.setData(data); link.clearData(); // WLH 27 July 99 } // set last index to this, and component values lastIndex = thisIndex; for (int j=0; j<n; j++) { lastD[j] = thisD[j]; } } // end else if (type instanceof FunctionType) } // end try catch (VisADException e) { // do nothing System.out.println("drag_direct " + e); e.printStackTrace(); } catch (RemoteException e) { // do nothing System.out.println("drag_direct " + e); e.printStackTrace(); } } public void addPoint(float[] x) throws VisADException { } /** flag indicating whether DirectManipulationRenderer is valid for this ShadowType */ private boolean isDirectManipulation; /** set isDirectManipulation = true if this DataRenderer supports direct manipulation for its linked Data */ public void checkDirect() throws VisADException, RemoteException { isDirectManipulation = false; } public void setIsDirectManipulation(boolean b) { isDirectManipulation = b; } public boolean getIsDirectManipulation() { return isDirectManipulation; } /* public void drag_direct(VisADRay ray, boolean first) { throw new VisADError("DataRenderer.drag_direct: not direct " + "manipulation renderer"); } */ }
true
true
public boolean isTransformControl(Control control, DataDisplayLink link) { if (control instanceof ProjectionControl || control instanceof ToggleControl) { return false; } /* WLH 1 Nov 97 - temporary hack - RangeControl changes always require Transform ValueControl and AnimationControl never do if (control instanceof AnimationControl || control instanceof ValueControl || control instanceof RangeControl) { return link.isTransform[control.getIndex()]; */ if (control instanceof AnimationControl || control instanceof ValueControl) { return false; } return true; } /** used for transform time-out hack */ public DataDisplayLink getLink() { return null; } public boolean isLegalTextureMap() { return true; } /* ********************** */ /* flow rendering stuff */ /* ********************** */ // value array (display_values) indices // ((ScalarMap) MapVector.elementAt(valueToMap[index])) // can get these indices through shadow_data_out or shadow_data_in // true if lat and lon in data_in & shadow_data_in is allSpatial // or if lat and lon in data_in & lat_lon_in_by_coord boolean lat_lon_in = false; // true if lat_lon_in and shadow_data_out is allSpatial // i.e., map from lat, lon to display is through data CoordinateSystem boolean lat_lon_in_by_coord = false; // true if lat and lon in data_out & shadow_data_out is allSpatial boolean lat_lon_out = false; // true if lat_lon_out and shadow_data_in is allSpatial // i.e., map from lat, lon to display is inverse via data CoordinateSystem boolean lat_lon_out_by_coord = false; int lat_lon_dimension = -1; ShadowRealTupleType shadow_data_out = null; RealTupleType data_out = null; Unit[] data_units_out = null; // CoordinateSystem data_coord_out is always null ShadowRealTupleType shadow_data_in = null; RealTupleType data_in = null; Unit[] data_units_in = null; CoordinateSystem[] data_coord_in = null; // may be one per point // spatial ScalarMaps for allSpatial shadow_data_out ScalarMap[] sdo_maps = null; // spatial ScalarMaps for allSpatial shadow_data_in ScalarMap[] sdi_maps = null; int[] sdo_spatial_index = null; int[] sdi_spatial_index = null; // indices of RealType.Latitude and RealType.Longitude // if lat_lon_in then indices in data_in // if lat_lon_out then indices in data_out // if lat_lon_spatial then values indices int lat_index = -1; int lon_index = -1; // non-negative if lat & lon in a RealTupleType of length 3 int other_index = -1; // true if other_index Units convertable to meter boolean other_meters = false; // from doTransform RealVectorType[] rvts = {null, null}; public RealVectorType getRealVectorTypes(int index) { if (index == 0 || index == 1) return rvts[index]; else return null; } public int[] getLatLonIndices() { return new int[] {lat_index, lon_index}; } public void setLatLonIndices(int[] indices) { lat_index = indices[0]; lon_index = indices[1]; } public int getEarthDimension() { return lat_lon_dimension; } public Unit[] getEarthUnits() { Unit[] units = null; if (lat_lon_in) { units = data_units_in; } else if (lat_lon_out) { units = data_units_out; } else if (lat_lon_spatial) { units = new Unit[] {RealType.Latitude.getDefaultUnit(), RealType.Longitude.getDefaultUnit()}; } else { units = null; } int lat = lat_index; int lon = lon_index; int other = other_index; if (units == null) { return null; } else if (units.length == 2) { return new Unit[] {lat >= 0 ? units[lat] : null, lon >= 0 ? units[lon] : null}; } else if (units.length == 3) { return new Unit[] {lat >= 0 ? units[lat] : null, lon >= 0 ? units[lon] : null, other >= 0 ? units[other] : null}; } else { return null; } } public float getLatLonRange() { double[] rlat = null; double[] rlon = null; int lat = lat_index; int lon = lon_index; if ((lat_lon_out && !lat_lon_out_by_coord) || (lat_lon_in && lat_lon_in_by_coord)) { rlat = lat >= 0 ? sdo_maps[lat].getRange() : new double[] {Double.NaN, Double.NaN}; rlon = lon >= 0 ? sdo_maps[lon].getRange() : new double[] {Double.NaN, Double.NaN}; } else if ((lat_lon_in && !lat_lon_in_by_coord) || (lat_lon_out && lat_lon_out_by_coord)) { rlat = lat >= 0 ? sdi_maps[lat].getRange() : new double[] {Double.NaN, Double.NaN}; rlon = lon >= 0 ? sdi_maps[lon].getRange() : new double[] {Double.NaN, Double.NaN}; } else if (lat_lon_spatial) { rlat = lat_map.getRange(); rlon = lon_map.getRange(); } else { return 1.0f; } double dlat = Math.abs(rlat[1] - rlat[0]); double dlon = Math.abs(rlon[1] - rlon[0]); if (dlat != dlat) dlat = 1.0f; if (dlon != dlon) dlon = 1.0f; return (dlat > dlon) ? (float) dlat : (float) dlon; } /** convert (lat, lon) or (lat, lon, other) values to display (x, y, z) */ public float[][] earthToSpatial(float[][] locs, float[] vert) throws VisADException { return earthToSpatial(locs, vert, null); } public float[][] earthToSpatial(float[][] locs, float[] vert, float[][] base_spatial_locs) throws VisADException { int lat = lat_index; int lon = lon_index; int other = other_index; if (lat_index < 0 || lon_index < 0) return null; int size = locs[0].length; if (locs.length < lat_lon_dimension) { // extend locs to lat_lon_dimension with zero fill float[][] temp = locs; locs = new float[lat_lon_dimension][]; for (int i=0; i<locs.length; i++) { locs[i] = temp[i]; } float[] zero = new float[size]; for (int j=0; j<size; j++) zero[j] = 0.0f; for (int i=locs.length; i<lat_lon_dimension; i++) { locs[i] = zero; } } else if (locs.length > lat_lon_dimension) { // truncate locs to lat_lon_dimension float[][] temp = locs; locs = new float[lat_lon_dimension][]; for (int i=0; i<lat_lon_dimension; i++) { locs[i] = temp[i]; } } // permute (lat, lon, other) to data RealTupleType float[][] tuple_locs = new float[lat_lon_dimension][]; float[][] spatial_locs = new float[3][]; tuple_locs[lat] = locs[0]; tuple_locs[lon] = locs[1]; if (lat_lon_dimension == 3) tuple_locs[other] = locs[2]; int vert_index = -1; // non-lat/lon index for lat_lon_dimension = 2 if (lat_lon_in) { if (lat_lon_in_by_coord) { // transform 'RealTupleType data_in' to 'RealTupleType data_out' if (data_coord_in.length == 1) { // one data_coord_in applies to all data points tuple_locs = CoordinateSystem.transformCoordinates(data_out, null, data_units_out, null, data_in, data_coord_in[0], data_units_in, null, tuple_locs); } else { // one data_coord_in per data point float[][] temp = new float[lat_lon_dimension][1]; for (int j=0; j<size; j++) { for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j]; temp = CoordinateSystem.transformCoordinates(data_out, null, data_units_out, null, data_in, data_coord_in[j], data_units_in, null, temp); for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0]; } } // map data_out to spatial DisplayRealTypes for (int i=0; i<lat_lon_dimension; i++) { spatial_locs[sdo_spatial_index[i]] = sdo_maps[i].scaleValues(tuple_locs[i]); } if (lat_lon_dimension == 2) { vert_index = 3 - (sdo_spatial_index[0] + sdo_spatial_index[1]); } } else { // map data_in to spatial DisplayRealTypes for (int i=0; i<lat_lon_dimension; i++) { spatial_locs[sdi_spatial_index[i]] = sdi_maps[i].scaleValues(tuple_locs[i]); } if (lat_lon_dimension == 2) { vert_index = 3 - (sdi_spatial_index[0] + sdi_spatial_index[1]); } } } else if (lat_lon_out) { if (lat_lon_out_by_coord) { // transform 'RealTupleType data_out' to 'RealTupleType data_in' if (data_coord_in.length == 1) { // one data_coord_in applies to all data points tuple_locs = CoordinateSystem.transformCoordinates(data_in, data_coord_in[0], data_units_in, null, data_out, null, data_units_out, null, tuple_locs); } else { // one data_coord_in per data point float[][] temp = new float[lat_lon_dimension][1]; for (int j=0; j<size; j++) { for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j]; temp = CoordinateSystem.transformCoordinates(data_in, data_coord_in[j], data_units_in, null, data_out, null, data_units_out, null, temp); for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0]; } } // map data_in to spatial DisplayRealTypes for (int i=0; i<lat_lon_dimension; i++) { spatial_locs[sdi_spatial_index[i]] = sdi_maps[i].scaleValues(tuple_locs[i]); } if (lat_lon_dimension == 2) { vert_index = 3 - (sdi_spatial_index[0] + sdi_spatial_index[1]); } } else { // map data_out to spatial DisplayRealTypes for (int i=0; i<lat_lon_dimension; i++) { spatial_locs[sdo_spatial_index[i]] = sdo_maps[i].scaleValues(tuple_locs[i]); } if (lat_lon_dimension == 2) { vert_index = 3 - (sdo_spatial_index[0] + sdo_spatial_index[1]); } } } else if (lat_lon_spatial) { // map lat & lon, not in allSpatial RealTupleType, to // spatial DisplayRealTypes spatial_locs[lat_spatial_index] = lat_map.scaleValues(tuple_locs[lat]); spatial_locs[lon_spatial_index] = lon_map.scaleValues(tuple_locs[lon]); vert_index = 3 - (lat_spatial_index + lon_spatial_index); } else { // should never happen return null; } // WLH 9 Dec 99 // fill any empty spatial DisplayRealTypes with default values for (int i=0; i<3; i++) { if (spatial_locs[i] == null) { if (base_spatial_locs != null && base_spatial_locs[i] != null) { spatial_locs[i] = base_spatial_locs[i]; // copy not necessary } else { spatial_locs[i] = new float[size]; float def = default_spatial_in[i]; // may be non-Cartesian for (int j=0; j<size; j++) spatial_locs[i][j] = def; } } } // adjust non-lat/lon spatial_locs by vertical flow component /* WLH 28 July 99 if (vert != null && vert_index > -1) { for (int j=0; j<size; j++) spatial_locs[vert_index][j] += vert[j]; } */ if (spatial_locs[vert_index] != null) { if (vert != null && vert_index > -1) { for (int j=0; j<size; j++) spatial_locs[vert_index][j] += vert[j]; } } if (display_coordinate_system != null) { // transform non-Cartesian spatial DisplayRealTypes to Cartesian spatial_locs = display_coordinate_system.toReference(spatial_locs); } return spatial_locs; } /** convert display (x, y, z) to (lat, lon) or (lat, lon, other) values */ public float[][] spatialToEarth(float[][] spatial_locs) throws VisADException { float[][] base_spatial_locs = new float[3][]; return spatialToEarth(spatial_locs, base_spatial_locs); } public float[][] spatialToEarth(float[][] spatial_locs, float[][] base_spatial_locs) throws VisADException { int lat = lat_index; int lon = lon_index; int other = other_index; if (lat_index < 0 || lon_index < 0) return null; if (spatial_locs.length != 3) return null; int size = 0; for (int i=0; i<3; i++) { if (spatial_locs[i] != null && spatial_locs[i].length > size) { size = spatial_locs[i].length; } } if (size == 0) return null; // fill any empty spatial DisplayRealTypes with default values for (int i=0; i<3; i++) { if (spatial_locs[i] == null) { spatial_locs[i] = new float[size]; // defaults for Cartesian spatial DisplayRealTypes = 0.0f for (int j=0; j<size; j++) spatial_locs[i][j] = 0.0f; } } if (display_coordinate_system != null) { // transform Cartesian spatial DisplayRealTypes to non-Cartesian spatial_locs = display_coordinate_system.fromReference(spatial_locs); } base_spatial_locs[0] = spatial_locs[0]; base_spatial_locs[1] = spatial_locs[1]; base_spatial_locs[2] = spatial_locs[2]; float[][] tuple_locs = new float[lat_lon_dimension][]; if (lat_lon_in) { if (lat_lon_in_by_coord) { // map spatial DisplayRealTypes to data_out for (int i=0; i<lat_lon_dimension; i++) { tuple_locs[i] = sdo_maps[i].inverseScaleValues(spatial_locs[sdo_spatial_index[i]]); } // transform 'RealTupleType data_out' to 'RealTupleType data_in' if (data_coord_in.length == 1) { // one data_coord_in applies to all data points tuple_locs = CoordinateSystem.transformCoordinates(data_in, data_coord_in[0], data_units_in, null, data_out, null, data_units_out, null, tuple_locs); } else { // one data_coord_in per data point float[][] temp = new float[lat_lon_dimension][1]; for (int j=0; j<size; j++) { for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j]; temp = CoordinateSystem.transformCoordinates(data_in, data_coord_in[j], data_units_in, null, data_out, null, data_units_out, null, temp); for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0]; } } } else { // map spatial DisplayRealTypes to data_in for (int i=0; i<lat_lon_dimension; i++) { tuple_locs[i] = sdi_maps[i].inverseScaleValues(spatial_locs[sdi_spatial_index[i]]); } } } else if (lat_lon_out) { if (lat_lon_out_by_coord) { // map spatial DisplayRealTypes to data_in for (int i=0; i<lat_lon_dimension; i++) { tuple_locs[i] = sdi_maps[i].inverseScaleValues(spatial_locs[sdi_spatial_index[i]]); } // transform 'RealTupleType data_in' to 'RealTupleType data_out' if (data_coord_in.length == 1) { // one data_coord_in applies to all data points tuple_locs = CoordinateSystem.transformCoordinates(data_out, null, data_units_out, null, data_in, data_coord_in[0], data_units_in, null, tuple_locs); } else { // one data_coord_in per data point float[][] temp = new float[lat_lon_dimension][1]; for (int j=0; j<size; j++) { for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j]; temp = CoordinateSystem.transformCoordinates(data_out, null, data_units_out, null, data_in, data_coord_in[j], data_units_in, null, temp); for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0]; } } } else { // map spatial DisplayRealTypes to data_out for (int i=0; i<lat_lon_dimension; i++) { tuple_locs[i] = sdo_maps[i].inverseScaleValues(spatial_locs[sdo_spatial_index[i]]); } } } else if (lat_lon_spatial) { // map spatial DisplayRealTypes to lat & lon, not in // allSpatial RealTupleType tuple_locs[lat] = lat_map.inverseScaleValues(spatial_locs[lat_spatial_index]); tuple_locs[lon] = lon_map.inverseScaleValues(spatial_locs[lon_spatial_index]); } else { // should never happen return null; } // permute data RealTupleType to (lat, lon, other) float[][] locs = new float[lat_lon_dimension][]; locs[0] = tuple_locs[lat]; locs[1] = tuple_locs[lon]; if (lat_lon_dimension == 3) locs[2] = tuple_locs[other]; return locs; } // information from doTransform public void setEarthSpatialData(ShadowRealTupleType s_d_i, ShadowRealTupleType s_d_o, RealTupleType d_o, Unit[] d_u_o, RealTupleType d_i, CoordinateSystem[] d_c_i, Unit[] d_u_i) throws VisADException { // first check for VectorRealType components mapped to flow // TO_DO: check here for flow mapped via CoordinateSystem if (d_o != null && d_o instanceof RealVectorType) { ScalarMap[] maps = new ScalarMap[3]; int k = getFlowMaps(s_d_o, maps); if (k > -1) rvts[k] = (RealVectorType) d_o; } if (d_i != null && d_i instanceof RealVectorType) { ScalarMap[] maps = new ScalarMap[3]; int k = getFlowMaps(s_d_i, maps); if (k > -1) rvts[k] = (RealVectorType) d_i; } int lat_index_local = -1; int lon_index_local = -1; other_index = -1; int n = 0; int m = 0; if (d_i != null) { n = d_i.getDimension(); for (int i=0; i<n; i++) { RealType real = (RealType) d_i.getComponent(i); if (RealType.Latitude.equals(real)) lat_index_local = i; if (RealType.Longitude.equals(real)) lon_index_local = i; } } if (lat_index_local > -1 && lon_index_local > -1 && (n == 2 || n == 3)) { if (s_d_i != null && s_d_i.getAllSpatial() && !s_d_i.getSpatialReference()) { lat_lon_in_by_coord = false; sdi_spatial_index = new int[s_d_i.getDimension()]; sdi_maps = getSpatialMaps(s_d_i, sdi_spatial_index); if (sdi_maps == null) { throw new DisplayException("sdi_maps null A"); } } else if (s_d_o != null && s_d_o.getAllSpatial() && !s_d_o.getSpatialReference()) { lat_lon_in_by_coord = true; sdo_spatial_index = new int[s_d_o.getDimension()]; sdo_maps = getSpatialMaps(s_d_o, sdo_spatial_index); if (sdo_maps == null) { throw new DisplayException("sdo_maps null A"); } } else { // do not update lat_index & lon_index return; } lat_lon_in = true; lat_lon_out = false; lat_lon_out_by_coord = false; lat_lon_spatial = false; lat_lon_dimension = n; if (n == 3) { other_index = 3 - (lat_index_local + lon_index_local); if (Unit.canConvert(d_u_i[other_index], CommonUnit.meter)) { other_meters = true; } } } else { // if( !(lat & lon in di, di dimension = 2 or 3) ) lat_index_local = -1; lon_index_local = -1; if (d_o != null) { m = d_o.getDimension(); for (int i=0; i<m; i++) { RealType real = (RealType) d_o.getComponent(i); if (RealType.Latitude.equals(real)) lat_index_local = i; if (RealType.Longitude.equals(real)) lon_index_local = i; } } if (lat_index_local < 0 || lon_index_local < 0 || !(m == 2 || m == 3)) { // do not update lat_index & lon_index return; } if (s_d_o != null && s_d_o.getAllSpatial() && !s_d_o.getSpatialReference()) { lat_lon_out_by_coord = false; sdo_spatial_index = new int[s_d_o.getDimension()]; sdo_maps = getSpatialMaps(s_d_o, sdo_spatial_index); if (sdo_maps == null) { throw new DisplayException("sdo_maps null B"); } } else if (s_d_i != null && s_d_i.getAllSpatial() && !s_d_i.getSpatialReference()) { lat_lon_out_by_coord = true; sdi_spatial_index = new int[s_d_i.getDimension()]; sdi_maps = getSpatialMaps(s_d_i, sdi_spatial_index); if (sdi_maps == null) { throw new DisplayException("sdi_maps null B"); } } else { // do not update lat_index & lon_index return; } lat_lon_out = true; lat_lon_in = false; lat_lon_in_by_coord = false; lat_lon_spatial = false; lat_lon_dimension = m; if (m == 3) { other_index = 3 - (lat_index_local + lon_index_local); if (Unit.canConvert(d_u_i[other_index], CommonUnit.meter)) { other_meters = true; } } } shadow_data_out = s_d_o; data_out = d_o; data_units_out = d_u_o; shadow_data_in = s_d_i; data_in = d_i; data_units_in = d_u_i; data_coord_in = d_c_i; // may be one per point lat_index = lat_index_local; lon_index = lon_index_local; return; } /** return array of spatial ScalarMap for srt, or null */ private ScalarMap[] getSpatialMaps(ShadowRealTupleType srt, int[] spatial_index) { int n = srt.getDimension(); ScalarMap[] maps = new ScalarMap[n]; for (int i=0; i<n; i++) { ShadowRealType real = (ShadowRealType) srt.getComponent(i); Enumeration ms = real.getSelectedMapVector().elements(); while (ms.hasMoreElements()) { ScalarMap map = (ScalarMap) ms.nextElement(); DisplayRealType dreal = map.getDisplayScalar(); DisplayTupleType tuple = dreal.getTuple(); if (tuple != null && (tuple.equals(Display.DisplaySpatialCartesianTuple) || (tuple.getCoordinateSystem() != null && tuple.getCoordinateSystem().getReference().equals( Display.DisplaySpatialCartesianTuple)))) { maps[i] = map; spatial_index[i] = dreal.getTupleIndex(); break; } } if (maps[i] == null) { return null; } } return maps; } /** return array of flow ScalarMap for srt, or null */ private int getFlowMaps(ShadowRealTupleType srt, ScalarMap[] maps) { int n = srt.getDimension(); maps[0] = null; maps[1] = null; maps[2] = null; DisplayTupleType ftuple = null; for (int i=0; i<n; i++) { ShadowRealType real = (ShadowRealType) srt.getComponent(i); Enumeration ms = real.getSelectedMapVector().elements(); while (ms.hasMoreElements()) { ScalarMap map = (ScalarMap) ms.nextElement(); DisplayRealType dreal = map.getDisplayScalar(); DisplayTupleType tuple = dreal.getTuple(); if (Display.DisplayFlow1Tuple.equals(tuple) || Display.DisplayFlow2Tuple.equals(tuple)) { if (ftuple != null && !ftuple.equals(tuple)) return -1; ftuple = tuple; maps[i] = map; break; } } if (maps[i] == null) return -1; } return Display.DisplayFlow1Tuple.equals(ftuple) ? 0 : 1; } // from assembleFlow ScalarMap[][] flow_maps = null; float[] flow_scale = null; public void setFlowDisplay(ScalarMap[][] maps, float[] fs) { flow_maps = maps; flow_scale = fs; } // if non-null, float[][] new_spatial_values = // display_coordinate_system.toReference(spatial_values); CoordinateSystem display_coordinate_system = null; // spatial_tuple and spatial_value_indices are set whether // display_coordinate_system is null or not DisplayTupleType spatial_tuple = null; // map from spatial_tuple tuple_index to value array indices int[] spatial_value_indices = {-1, -1, -1}; float[] default_spatial_in = {0.0f, 0.0f, 0.0f}; // true if lat and lon mapped directly to spatial boolean lat_lon_spatial = false; ScalarMap lat_map = null; ScalarMap lon_map = null; int lat_spatial_index = -1; int lon_spatial_index = -1; // spatial map getRange() results for flow adjustment double[] ranges = null; public double[] getRanges() { return ranges; } // WLH 4 March 2000 public CoordinateSystem getDisplayCoordinateSystem() { return display_coordinate_system ; } // information from assembleSpatial public void setEarthSpatialDisplay(CoordinateSystem coord, DisplayTupleType t, DisplayImpl display, int[] indices, float[] default_values, double[] r) throws VisADException { display_coordinate_system = coord; spatial_tuple = t; System.arraycopy(indices, 0, spatial_value_indices, 0, 3); /* WLH 5 Dec 99 spatial_value_indices = indices; */ ranges = r; for (int i=0; i<3; i++) { int default_index = display.getDisplayScalarIndex( ((DisplayRealType) t.getComponent(i)) ); default_spatial_in[i] = default_values[default_index]; } if (lat_index > -1 && lon_index > -1) return; lat_index = -1; lon_index = -1; other_index = -1; int valueArrayLength = display.getValueArrayLength(); int[] valueToScalar = display.getValueToScalar(); int[] valueToMap = display.getValueToMap(); Vector MapVector = display.getMapVector(); for (int i=0; i<valueArrayLength; i++) { ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]); ScalarType real = map.getScalar(); DisplayRealType dreal = map.getDisplayScalar(); DisplayTupleType tuple = dreal.getTuple(); if (tuple != null && (tuple.equals(Display.DisplaySpatialCartesianTuple) || (tuple.getCoordinateSystem() != null && tuple.getCoordinateSystem().getReference().equals( Display.DisplaySpatialCartesianTuple)))) { if (RealType.Latitude.equals(real)) { lat_index = 0; lat_map = map; lat_spatial_index = dreal.getTupleIndex(); } if (RealType.Longitude.equals(real)) { lon_index = 1; lon_map = map; lon_spatial_index = dreal.getTupleIndex(); } } } if (lat_index > -1 && lon_index > -1) { lat_lon_spatial = true; lat_lon_dimension = 2; lat_lon_out = false; lat_lon_in_by_coord = false; lat_lon_in = false; } else { lat_lon_spatial = false; lat_index = -1; lon_index = -1; } } /* *************************** */ /* direct manipulation stuff */ /* *************************** */ private float[][] spatialValues = null; /** if Function, last domain index and range values */ private int lastIndex = -1; double[] lastD = null; float[] lastX = new float[6]; /** index into spatialValues found by checkClose */ private int closeIndex = -1; /** for use in drag_direct */ private transient DataDisplayLink link = null; // private transient ShadowTypeJ3D type = null; private transient DataReference ref = null; private transient MathType type = null; private transient ShadowType shadow = null; /** point on direct manifold line or plane */ private float point_x, point_y, point_z; /** normalized direction of line or perpendicular to plane */ private float line_x, line_y, line_z; /** arrays of length one for inverseScaleValues */ private float[] f = new float[1]; private float[] d = new float[1]; private float[][] value = new float[1][1]; /** information calculated by checkDirect */ /** explanation for invalid use of DirectManipulationRenderer */ private String whyNotDirect = null; /** mapping from spatial axes to tuple component */ private int[] axisToComponent = {-1, -1, -1}; /** mapping from spatial axes to ScalarMaps */ private ScalarMap[] directMap = {null, null, null}; /** spatial axis for Function domain */ private int domainAxis = -1; /** dimension of direct manipulation (including any Function domain) */ private int directManifoldDimension = 0; /** spatial DisplayTupleType other than DisplaySpatialCartesianTuple */ DisplayTupleType tuple; /** possible values for whyNotDirect */ private final static String notRealFunction = "FunctionType must be Real"; private final static String notSimpleField = "not simple field"; private final static String notSimpleTuple = "not simple tuple"; private final static String multipleMapping = "RealType with multiple mappings"; private final static String multipleSpatialMapping = "RealType with multiple spatial mappings"; private final static String nonSpatial = "no spatial mapping"; private final static String viaReference = "spatial mapping through Reference"; private final static String domainDimension = "domain dimension must be 1"; private final static String domainNotSpatial = "domain must be mapped to spatial"; private final static String rangeType = "range must be RealType or RealTupleType"; private final static String rangeNotSpatial = "range must be mapped to spatial"; private final static String domainSet = "domain Set must be Gridded1DSet"; private final static String tooFewSpatial = "Function without spatial domain"; private final static String functionTooFew = "Function directManifoldDimension < 2"; private final static String badCoordSysManifoldDim = "bad directManifoldDimension with spatial CoordinateSystem"; public synchronized void realCheckDirect() throws VisADException, RemoteException { setIsDirectManipulation(false); link = getLinks()[0]; ref = link.getDataReference(); shadow = link.getShadow().getAdaptedShadowType(); type = link.getType(); tuple = null; if (type instanceof FunctionType) { ShadowRealTupleType domain = ((ShadowFunctionType) shadow).getDomain(); ShadowType range = ((ShadowFunctionType) shadow).getRange(); tuple = domain.getDisplaySpatialTuple(); // there is some redundancy among these conditions if (!((FunctionType) type).getReal()) { whyNotDirect = notRealFunction; return; } else if (shadow.getLevelOfDifficulty() != ShadowType.SIMPLE_FIELD) { whyNotDirect = notSimpleTuple; return; } else if (shadow.getMultipleSpatialDisplayScalar()) { whyNotDirect = multipleSpatialMapping; return; } else if (domain.getDimension() != 1) { whyNotDirect = domainDimension; return; } else if(!(Display.DisplaySpatialCartesianTuple.equals(tuple) || (tuple != null && tuple.getCoordinateSystem().getReference().equals( Display.DisplaySpatialCartesianTuple)) )) { whyNotDirect = domainNotSpatial; return; } else if (domain.getSpatialReference()) { whyNotDirect = viaReference; return; } DisplayTupleType rtuple = null; if (range instanceof ShadowRealTupleType) { rtuple = ((ShadowRealTupleType) range).getDisplaySpatialTuple(); } else if (range instanceof ShadowRealType) { rtuple = ((ShadowRealType) range).getDisplaySpatialTuple(); } else { whyNotDirect = rangeType; return; } if (!tuple.equals(rtuple)) { /* WLH 3 Aug 98 if (!Display.DisplaySpatialCartesianTuple.equals(rtuple)) { */ whyNotDirect = rangeNotSpatial; return; } else if (range instanceof ShadowRealTupleType && ((ShadowRealTupleType) range).getSpatialReference()) { whyNotDirect = viaReference; return; } else if (!(link.getData() instanceof Field) || !(((Field) link.getData()).getDomainSet() instanceof Gridded1DSet)) { whyNotDirect = domainSet; return; } if (Display.DisplaySpatialCartesianTuple.equals(tuple)) { tuple = null; } domainAxis = -1; for (int i=0; i<3; i++) { axisToComponent[i] = -1; directMap[i] = null; } directManifoldDimension = setDirectMap((ShadowRealType) domain.getComponent(0), -1, true); if (range instanceof ShadowRealType) { directManifoldDimension += setDirectMap((ShadowRealType) range, 0, false); } else if (range instanceof ShadowRealTupleType) { ShadowRealTupleType r = (ShadowRealTupleType) range; for (int i=0; i<r.getDimension(); i++) { directManifoldDimension += setDirectMap((ShadowRealType) r.getComponent(i), i, false); } } if (domainAxis == -1) { whyNotDirect = tooFewSpatial; return; } if (directManifoldDimension < 2) { whyNotDirect = functionTooFew; return; } boolean twod = displayRenderer.getMode2D(); if (tuple != null && (!twod && directManifoldDimension != 3 || twod && directManifoldDimension != 2) ) { whyNotDirect = badCoordSysManifoldDim; return; } setIsDirectManipulation(true); /* WLH 3 Aug 98 if (domainAxis == -1) { throw new DisplayException("DataRenderer.realCheckDirect:" + "too few spatial domain"); } if (directManifoldDimension < 2) { throw new DisplayException("DataRenderer.realCheckDirect:" + "directManifoldDimension < 2"); } */ } else if (type instanceof RealTupleType) { // // TO_DO // allow for any Flat ShadowTupleType // tuple = ((ShadowRealTupleType) shadow).getDisplaySpatialTuple(); if (shadow.getLevelOfDifficulty() != ShadowType.SIMPLE_TUPLE) { whyNotDirect = notSimpleTuple; return; } else if (shadow.getMultipleSpatialDisplayScalar()) { whyNotDirect = multipleSpatialMapping; return; } else if(!(Display.DisplaySpatialCartesianTuple.equals(tuple) || (tuple != null && tuple.getCoordinateSystem().getReference().equals( Display.DisplaySpatialCartesianTuple)) )) { /* WLH 3 Aug 98 else if (!Display.DisplaySpatialCartesianTuple.equals( ((ShadowRealTupleType) shadow).getDisplaySpatialTuple())) { */ whyNotDirect = nonSpatial; return; } else if (((ShadowRealTupleType) shadow).getSpatialReference()) { whyNotDirect = viaReference; return; } /* WLH 3 Aug 98 setIsDirectManipulation(true); */ if (Display.DisplaySpatialCartesianTuple.equals(tuple)) { tuple = null; } domainAxis = -1; for (int i=0; i<3; i++) { axisToComponent[i] = -1; directMap[i] = null; } directManifoldDimension = 0; for (int i=0; i<((ShadowRealTupleType) shadow).getDimension(); i++) { directManifoldDimension += setDirectMap((ShadowRealType) ((ShadowRealTupleType) shadow).getComponent(i), i, false); } boolean twod = displayRenderer.getMode2D(); if (tuple != null && (!twod && directManifoldDimension != 3 || twod && directManifoldDimension != 2) ) { whyNotDirect = badCoordSysManifoldDim; return; } setIsDirectManipulation(true); } else if (type instanceof RealType) { tuple = ((ShadowRealType) shadow).getDisplaySpatialTuple(); if (shadow.getLevelOfDifficulty() != ShadowType.SIMPLE_TUPLE) { whyNotDirect = notSimpleTuple; return; } else if (shadow.getMultipleSpatialDisplayScalar()) { whyNotDirect = multipleSpatialMapping; return; } else if(!(Display.DisplaySpatialCartesianTuple.equals(tuple) || (tuple != null && tuple.getCoordinateSystem().getReference().equals( Display.DisplaySpatialCartesianTuple)) )) { /* WLH 3 Aug 98 else if(!Display.DisplaySpatialCartesianTuple.equals( ((ShadowRealType) shadow).getDisplaySpatialTuple())) { */ whyNotDirect = nonSpatial; return; } /* WLH 3 Aug 98 setIsDirectManipulation(true); */ if (Display.DisplaySpatialCartesianTuple.equals(tuple)) { tuple = null; } domainAxis = -1; for (int i=0; i<3; i++) { axisToComponent[i] = -1; directMap[i] = null; } directManifoldDimension = setDirectMap((ShadowRealType) shadow, 0, false); boolean twod = displayRenderer.getMode2D(); if (tuple != null && (!twod && directManifoldDimension != 3 || twod && directManifoldDimension != 2) ) { whyNotDirect = badCoordSysManifoldDim; return; } setIsDirectManipulation(true); } // end else if (type instanceof RealType) } /** set directMap and axisToComponent (domain = false) or domainAxis (domain = true) from real; called by realCheckDirect */ synchronized int setDirectMap(ShadowRealType real, int component, boolean domain) { Enumeration maps = real.getSelectedMapVector().elements(); while (maps.hasMoreElements()) { ScalarMap map = (ScalarMap) maps.nextElement(); DisplayRealType dreal = map.getDisplayScalar(); DisplayTupleType tuple = dreal.getTuple(); if (Display.DisplaySpatialCartesianTuple.equals(tuple) || (tuple != null && tuple.getCoordinateSystem().getReference().equals( Display.DisplaySpatialCartesianTuple)) ) { int index = dreal.getTupleIndex(); if (domain) { domainAxis = index; } else { axisToComponent[index] = component; } directMap[index] = map; return 1; } } return 0; } private int getDirectManifoldDimension() { return directManifoldDimension; } public String getWhyNotDirect() { return whyNotDirect; } private int getAxisToComponent(int i) { return axisToComponent[i]; } private ScalarMap getDirectMap(int i) { return directMap[i]; } private int getDomainAxis() { return domainAxis; } /** set spatialValues from ShadowType.doTransform */ public synchronized void setSpatialValues(float[][] spatial_values) { // these are X, Y, Z values spatialValues = spatial_values; } /** find minimum distance from ray to spatialValues */ public synchronized float checkClose(double[] origin, double[] direction) { float distance = Float.MAX_VALUE; lastIndex = -1; if (spatialValues == null) return distance; float o_x = (float) origin[0]; float o_y = (float) origin[1]; float o_z = (float) origin[2]; float d_x = (float) direction[0]; float d_y = (float) direction[1]; float d_z = (float) direction[2]; /* System.out.println("origin = " + o_x + " " + o_y + " " + o_z); System.out.println("direction = " + d_x + " " + d_y + " " + d_z); */ for (int i=0; i<spatialValues[0].length; i++) { float x = spatialValues[0][i] - o_x; float y = spatialValues[1][i] - o_y; float z = spatialValues[2][i] - o_z; float dot = x * d_x + y * d_y + z * d_z; x = x - dot * d_x; y = y - dot * d_y; z = z - dot * d_z; float d = (float) Math.sqrt(x * x + y * y + z * z); if (d < distance) { distance = d; closeIndex = i; } /* System.out.println("spatialValues["+i+"] = " + spatialValues[0][i] + " " + spatialValues[1][i] + " " + spatialValues[2][i] + " d = " + d); */ } /* System.out.println("checkClose: distance = " + distance); */ return distance; } /** mouse button released, ending direct manipulation */ public synchronized void release_direct() { } public synchronized void drag_direct(VisADRay ray, boolean first, int mouseModifiers) { // System.out.println("drag_direct " + first + " " + type); if (spatialValues == null || ref == null || shadow == null) return; float o_x = (float) ray.position[0]; float o_y = (float) ray.position[1]; float o_z = (float) ray.position[2]; float d_x = (float) ray.vector[0]; float d_y = (float) ray.vector[1]; float d_z = (float) ray.vector[2]; if (first) { point_x = spatialValues[0][closeIndex]; point_y = spatialValues[1][closeIndex]; point_z = spatialValues[2][closeIndex]; int lineAxis = -1; if (getDirectManifoldDimension() == 3) { // coord sys ok line_x = d_x; line_y = d_y; line_z = d_z; } else { if (getDirectManifoldDimension() == 2) { if (displayRenderer.getMode2D()) { // coord sys ok lineAxis = 2; } else { for (int i=0; i<3; i++) { if (getAxisToComponent(i) < 0 && getDomainAxis() != i) { lineAxis = i; } } } } else if (getDirectManifoldDimension() == 1) { for (int i=0; i<3; i++) { if (getAxisToComponent(i) >= 0) { lineAxis = i; } } } line_x = (lineAxis == 0) ? 1.0f : 0.0f; line_y = (lineAxis == 1) ? 1.0f : 0.0f; line_z = (lineAxis == 2) ? 1.0f : 0.0f; } } // end if (first) float[] x = new float[3]; // x marks the spot if (getDirectManifoldDimension() == 1) { // find closest point on line to ray // logic from vis5d/cursor.c // line o_, d_ to line point_, line_ float ld = d_x * line_x + d_y * line_y + d_z * line_z; float od = o_x * d_x + o_y * d_y + o_z * d_z; float pd = point_x * d_x + point_y * d_y + point_z * d_z; float ol = o_x * line_x + o_y * line_y + o_z * line_z; float pl = point_x * line_x + point_y * line_y + point_z * line_z; if (ld * ld == 1.0f) return; float t = ((pl - ol) - (ld * (pd - od))) / (ld * ld - 1.0f); // x is closest point x[0] = point_x + t * line_x; x[1] = point_y + t * line_y; x[2] = point_z + t * line_z; } else { // getDirectManifoldDimension() = 2 or 3 // intersect ray with plane float dot = (point_x - o_x) * line_x + (point_y - o_y) * line_y + (point_z - o_z) * line_z; float dot2 = d_x * line_x + d_y * line_y + d_z * line_z; if (dot2 == 0.0) return; dot = dot / dot2; // x is intersection x[0] = o_x + dot * d_x; x[1] = o_y + dot * d_y; x[2] = o_z + dot * d_z; } // // TO_DO // might estimate errors from pixel resolution on screen // try { float[] xx = {x[0], x[1], x[2]}; if (tuple != null) { float[][] cursor = {{x[0]}, {x[1]}, {x[2]}}; float[][] new_cursor = tuple.getCoordinateSystem().fromReference(cursor); x[0] = new_cursor[0][0]; x[1] = new_cursor[1][0]; x[2] = new_cursor[2][0]; } Data newData = null; Data data = link.getData(); if (type instanceof RealType) { addPoint(xx); for (int i=0; i<3; i++) { if (getAxisToComponent(i) >= 0) { f[0] = x[i]; d = getDirectMap(i).inverseScaleValues(f); // RealType rtype = (RealType) data.getType(); RealType rtype = (RealType) type; newData = new Real(rtype, (double) d[0], rtype.getDefaultUnit(), null); // create location string Vector vect = new Vector(); /* WLH 26 July 99 float g = d[0]; vect.addElement(rtype.getName() + " = " + g); */ String valueString = new Real(rtype, d[0]).toValueString(); vect.addElement(rtype.getName() + " = " + valueString); getDisplayRenderer().setCursorStringVector(vect); break; } } ref.setData(newData); link.clearData(); // WLH 27 July 99 } else if (type instanceof RealTupleType) { addPoint(xx); int n = ((RealTuple) data).getDimension(); Real[] reals = new Real[n]; Vector vect = new Vector(); for (int i=0; i<3; i++) { int j = getAxisToComponent(i); if (j >= 0) { f[0] = x[i]; d = getDirectMap(i).inverseScaleValues(f); Real c = (Real) ((RealTuple) data).getComponent(j); RealType rtype = (RealType) c.getType(); reals[j] = new Real(rtype, (double) d[0], rtype.getDefaultUnit(), null); // create location string /* WLH 26 July 99 float g = d[0]; vect.addElement(rtype.getName() + " = " + g); */ String valueString = new Real(rtype, d[0]).toValueString(); vect.addElement(rtype.getName() + " = " + valueString); } } getDisplayRenderer().setCursorStringVector(vect); for (int j=0; j<n; j++) { if (reals[j] == null) { reals[j] = (Real) ((RealTuple) data).getComponent(j); } } newData = new RealTuple((RealTupleType) type, reals, ((RealTuple) data).getCoordinateSystem()); ref.setData(newData); link.clearData(); // WLH 27 July 99 } else if (type instanceof FunctionType) { Vector vect = new Vector(); if (first) lastIndex = -1; int k = getDomainAxis(); f[0] = x[k]; d = getDirectMap(k).inverseScaleValues(f); RealType rtype = (RealType) getDirectMap(k).getScalar(); // WLH 4 Jan 99 // convert d from default Unit to actual domain Unit of data Unit[] us = ((Field) data).getDomainUnits(); if (us != null && us[0] != null) { d[0] = (float) us[0].toThis((double) d[0], rtype.getDefaultUnit()); } // create location string float g = d[0]; vect.addElement(rtype.getName() + " = " + g); // convert domain value to domain index Gridded1DSet set = (Gridded1DSet) ((Field) data).getDomainSet(); value[0][0] = (float) d[0]; int[] indices = set.valueToIndex(value); int thisIndex = indices[0]; if (thisIndex < 0) { lastIndex = -1; return; } if (lastIndex < 0) { addPoint(xx); } else { lastX[3] = xx[0]; lastX[4] = xx[1]; lastX[5] = xx[2]; addPoint(lastX); } lastX[0] = xx[0]; lastX[1] = xx[1]; lastX[2] = xx[2]; int n; MathType range = ((FunctionType) type).getRange(); if (range instanceof RealType) { n = 1; } else { n = ((RealTupleType) range).getDimension(); } double[] thisD = new double[n]; boolean[] directComponent = new boolean[n]; for (int j=0; j<n; j++) { thisD[j] = Double.NaN; directComponent[j] = false; } for (int i=0; i<3; i++) { int j = getAxisToComponent(i); if (j >= 0) { f[0] = x[i]; d = getDirectMap(i).inverseScaleValues(f); // create location string rtype = (RealType) getDirectMap(i).getScalar(); /* WLH 26 July 99 g = (float) d[0]; vect.addElement(rtype.getName() + " = " + g); */ String valueString = new Real(rtype, d[0]).toValueString(); vect.addElement(rtype.getName() + " = " + valueString); thisD[j] = d[0]; directComponent[j] = true; } } getDisplayRenderer().setCursorStringVector(vect); if (lastIndex < 0) { lastIndex = thisIndex; lastD = new double[n]; for (int j=0; j<n; j++) { lastD[j] = thisD[j]; } } Real[] reals = new Real[n]; int m = Math.abs(lastIndex - thisIndex) + 1; indices = new int[m]; int index = thisIndex; int inc = (lastIndex >= thisIndex) ? 1 : -1; for (int i=0; i<m; i++) { indices[i] = index; index += inc; } float[][] values = set.indexToValue(indices); double coefDiv = values[0][m-1] - values[0][0]; for (int i=0; i<m; i++) { index = indices[i]; double coef = (i == 0 || coefDiv == 0.0) ? 0.0 : (values[0][i] - values[0][0]) / coefDiv; Data tuple = ((Field) data).getSample(index); if (tuple instanceof Real) { if (directComponent[0]) { rtype = (RealType) tuple.getType(); tuple = new Real(rtype, thisD[0] + coef * (lastD[0] - thisD[0]), rtype.getDefaultUnit(), null); } } else { for (int j=0; j<n; j++) { Real c = (Real) ((RealTuple) tuple).getComponent(j); if (directComponent[j]) { rtype = (RealType) c.getType(); reals[j] = new Real(rtype, thisD[j] + coef * (lastD[j] - thisD[j]), rtype.getDefaultUnit(), null); } else { reals[j] = c; } } tuple = new RealTuple(reals); } ((Field) data).setSample(index, tuple); } // end for (int i=0; i<m; i++) if (ref instanceof RemoteDataReference && !(data instanceof RemoteData)) { // ref is Remote and data is local, so we have only modified // a local copy and must send it back to ref ref.setData(data); link.clearData(); // WLH 27 July 99 } // set last index to this, and component values lastIndex = thisIndex; for (int j=0; j<n; j++) { lastD[j] = thisD[j]; } } // end else if (type instanceof FunctionType) } // end try catch (VisADException e) { // do nothing System.out.println("drag_direct " + e); e.printStackTrace(); } catch (RemoteException e) { // do nothing System.out.println("drag_direct " + e); e.printStackTrace(); } } public void addPoint(float[] x) throws VisADException { } /** flag indicating whether DirectManipulationRenderer is valid for this ShadowType */ private boolean isDirectManipulation; /** set isDirectManipulation = true if this DataRenderer supports direct manipulation for its linked Data */ public void checkDirect() throws VisADException, RemoteException { isDirectManipulation = false; } public void setIsDirectManipulation(boolean b) { isDirectManipulation = b; } public boolean getIsDirectManipulation() { return isDirectManipulation; } /* public void drag_direct(VisADRay ray, boolean first) { throw new VisADError("DataRenderer.drag_direct: not direct " + "manipulation renderer"); } */ }
public boolean isTransformControl(Control control, DataDisplayLink link) { if (control instanceof ProjectionControl || control instanceof ToggleControl) { return false; } /* WLH 1 Nov 97 - temporary hack - RangeControl changes always require Transform ValueControl and AnimationControl never do if (control instanceof AnimationControl || control instanceof ValueControl || control instanceof RangeControl) { return link.isTransform[control.getIndex()]; */ if (control instanceof AnimationControl || control instanceof ValueControl) { return false; } return true; } /** used for transform time-out hack */ public DataDisplayLink getLink() { return null; } public boolean isLegalTextureMap() { return true; } /* ********************** */ /* flow rendering stuff */ /* ********************** */ // value array (display_values) indices // ((ScalarMap) MapVector.elementAt(valueToMap[index])) // can get these indices through shadow_data_out or shadow_data_in // true if lat and lon in data_in & shadow_data_in is allSpatial // or if lat and lon in data_in & lat_lon_in_by_coord boolean lat_lon_in = false; // true if lat_lon_in and shadow_data_out is allSpatial // i.e., map from lat, lon to display is through data CoordinateSystem boolean lat_lon_in_by_coord = false; // true if lat and lon in data_out & shadow_data_out is allSpatial boolean lat_lon_out = false; // true if lat_lon_out and shadow_data_in is allSpatial // i.e., map from lat, lon to display is inverse via data CoordinateSystem boolean lat_lon_out_by_coord = false; int lat_lon_dimension = -1; ShadowRealTupleType shadow_data_out = null; RealTupleType data_out = null; Unit[] data_units_out = null; // CoordinateSystem data_coord_out is always null ShadowRealTupleType shadow_data_in = null; RealTupleType data_in = null; Unit[] data_units_in = null; CoordinateSystem[] data_coord_in = null; // may be one per point // spatial ScalarMaps for allSpatial shadow_data_out ScalarMap[] sdo_maps = null; // spatial ScalarMaps for allSpatial shadow_data_in ScalarMap[] sdi_maps = null; int[] sdo_spatial_index = null; int[] sdi_spatial_index = null; // indices of RealType.Latitude and RealType.Longitude // if lat_lon_in then indices in data_in // if lat_lon_out then indices in data_out // if lat_lon_spatial then values indices int lat_index = -1; int lon_index = -1; // non-negative if lat & lon in a RealTupleType of length 3 int other_index = -1; // true if other_index Units convertable to meter boolean other_meters = false; // from doTransform RealVectorType[] rvts = {null, null}; public RealVectorType getRealVectorTypes(int index) { if (index == 0 || index == 1) return rvts[index]; else return null; } public int[] getLatLonIndices() { return new int[] {lat_index, lon_index}; } public void setLatLonIndices(int[] indices) { lat_index = indices[0]; lon_index = indices[1]; } public int getEarthDimension() { return lat_lon_dimension; } public Unit[] getEarthUnits() { Unit[] units = null; if (lat_lon_in) { units = data_units_in; } else if (lat_lon_out) { units = data_units_out; } else if (lat_lon_spatial) { units = new Unit[] {RealType.Latitude.getDefaultUnit(), RealType.Longitude.getDefaultUnit()}; } else { units = null; } int lat = lat_index; int lon = lon_index; int other = other_index; if (units == null) { return null; } else if (units.length == 2) { return new Unit[] {lat >= 0 ? units[lat] : null, lon >= 0 ? units[lon] : null}; } else if (units.length == 3) { return new Unit[] {lat >= 0 ? units[lat] : null, lon >= 0 ? units[lon] : null, other >= 0 ? units[other] : null}; } else { return null; } } public float getLatLonRange() { double[] rlat = null; double[] rlon = null; int lat = lat_index; int lon = lon_index; if ((lat_lon_out && !lat_lon_out_by_coord) || (lat_lon_in && lat_lon_in_by_coord)) { rlat = lat >= 0 ? sdo_maps[lat].getRange() : new double[] {Double.NaN, Double.NaN}; rlon = lon >= 0 ? sdo_maps[lon].getRange() : new double[] {Double.NaN, Double.NaN}; } else if ((lat_lon_in && !lat_lon_in_by_coord) || (lat_lon_out && lat_lon_out_by_coord)) { rlat = lat >= 0 ? sdi_maps[lat].getRange() : new double[] {Double.NaN, Double.NaN}; rlon = lon >= 0 ? sdi_maps[lon].getRange() : new double[] {Double.NaN, Double.NaN}; } else if (lat_lon_spatial) { rlat = lat_map.getRange(); rlon = lon_map.getRange(); } else { return 1.0f; } double dlat = Math.abs(rlat[1] - rlat[0]); double dlon = Math.abs(rlon[1] - rlon[0]); if (dlat != dlat) dlat = 1.0f; if (dlon != dlon) dlon = 1.0f; return (dlat > dlon) ? (float) dlat : (float) dlon; } /** convert (lat, lon) or (lat, lon, other) values to display (x, y, z) */ public float[][] earthToSpatial(float[][] locs, float[] vert) throws VisADException { return earthToSpatial(locs, vert, null); } public float[][] earthToSpatial(float[][] locs, float[] vert, float[][] base_spatial_locs) throws VisADException { int lat = lat_index; int lon = lon_index; int other = other_index; if (lat_index < 0 || lon_index < 0) return null; int size = locs[0].length; if (locs.length < lat_lon_dimension) { // extend locs to lat_lon_dimension with zero fill float[][] temp = locs; locs = new float[lat_lon_dimension][]; for (int i=0; i<locs.length; i++) { locs[i] = temp[i]; } float[] zero = new float[size]; for (int j=0; j<size; j++) zero[j] = 0.0f; for (int i=locs.length; i<lat_lon_dimension; i++) { locs[i] = zero; } } else if (locs.length > lat_lon_dimension) { // truncate locs to lat_lon_dimension float[][] temp = locs; locs = new float[lat_lon_dimension][]; for (int i=0; i<lat_lon_dimension; i++) { locs[i] = temp[i]; } } // permute (lat, lon, other) to data RealTupleType float[][] tuple_locs = new float[lat_lon_dimension][]; float[][] spatial_locs = new float[3][]; tuple_locs[lat] = locs[0]; tuple_locs[lon] = locs[1]; if (lat_lon_dimension == 3) tuple_locs[other] = locs[2]; int vert_index = -1; // non-lat/lon index for lat_lon_dimension = 2 if (lat_lon_in) { if (lat_lon_in_by_coord) { // transform 'RealTupleType data_in' to 'RealTupleType data_out' if (data_coord_in.length == 1) { // one data_coord_in applies to all data points tuple_locs = CoordinateSystem.transformCoordinates(data_out, null, data_units_out, null, data_in, data_coord_in[0], data_units_in, null, tuple_locs); } else { // one data_coord_in per data point float[][] temp = new float[lat_lon_dimension][1]; for (int j=0; j<size; j++) { for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j]; temp = CoordinateSystem.transformCoordinates(data_out, null, data_units_out, null, data_in, data_coord_in[j], data_units_in, null, temp); for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0]; } } // map data_out to spatial DisplayRealTypes for (int i=0; i<lat_lon_dimension; i++) { spatial_locs[sdo_spatial_index[i]] = sdo_maps[i].scaleValues(tuple_locs[i]); } if (lat_lon_dimension == 2) { vert_index = 3 - (sdo_spatial_index[0] + sdo_spatial_index[1]); } } else { // map data_in to spatial DisplayRealTypes for (int i=0; i<lat_lon_dimension; i++) { spatial_locs[sdi_spatial_index[i]] = sdi_maps[i].scaleValues(tuple_locs[i]); } if (lat_lon_dimension == 2) { vert_index = 3 - (sdi_spatial_index[0] + sdi_spatial_index[1]); } } } else if (lat_lon_out) { if (lat_lon_out_by_coord) { // transform 'RealTupleType data_out' to 'RealTupleType data_in' if (data_coord_in.length == 1) { // one data_coord_in applies to all data points tuple_locs = CoordinateSystem.transformCoordinates(data_in, data_coord_in[0], data_units_in, null, data_out, null, data_units_out, null, tuple_locs); } else { // one data_coord_in per data point float[][] temp = new float[lat_lon_dimension][1]; for (int j=0; j<size; j++) { for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j]; temp = CoordinateSystem.transformCoordinates(data_in, data_coord_in[j], data_units_in, null, data_out, null, data_units_out, null, temp); for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0]; } } // map data_in to spatial DisplayRealTypes for (int i=0; i<lat_lon_dimension; i++) { spatial_locs[sdi_spatial_index[i]] = sdi_maps[i].scaleValues(tuple_locs[i]); } if (lat_lon_dimension == 2) { vert_index = 3 - (sdi_spatial_index[0] + sdi_spatial_index[1]); } } else { // map data_out to spatial DisplayRealTypes for (int i=0; i<lat_lon_dimension; i++) { spatial_locs[sdo_spatial_index[i]] = sdo_maps[i].scaleValues(tuple_locs[i]); } if (lat_lon_dimension == 2) { vert_index = 3 - (sdo_spatial_index[0] + sdo_spatial_index[1]); } } } else if (lat_lon_spatial) { // map lat & lon, not in allSpatial RealTupleType, to // spatial DisplayRealTypes spatial_locs[lat_spatial_index] = lat_map.scaleValues(tuple_locs[lat]); spatial_locs[lon_spatial_index] = lon_map.scaleValues(tuple_locs[lon]); vert_index = 3 - (lat_spatial_index + lon_spatial_index); } else { // should never happen return null; } // WLH 9 Dec 99 // fill any empty spatial DisplayRealTypes with default values for (int i=0; i<3; i++) { if (spatial_locs[i] == null) { if (base_spatial_locs != null && base_spatial_locs[i] != null) { spatial_locs[i] = base_spatial_locs[i]; // copy not necessary } else { spatial_locs[i] = new float[size]; float def = default_spatial_in[i]; // may be non-Cartesian for (int j=0; j<size; j++) spatial_locs[i][j] = def; } } } // adjust non-lat/lon spatial_locs by vertical flow component /* WLH 28 July 99 if (vert != null && vert_index > -1) { for (int j=0; j<size; j++) spatial_locs[vert_index][j] += vert[j]; } */ if (vert != null && vert_index > -1 && spatial_locs[vert_index] != null) { for (int j=0; j<size; j++) spatial_locs[vert_index][j] += vert[j]; } if (display_coordinate_system != null) { // transform non-Cartesian spatial DisplayRealTypes to Cartesian spatial_locs = display_coordinate_system.toReference(spatial_locs); } return spatial_locs; } /** convert display (x, y, z) to (lat, lon) or (lat, lon, other) values */ public float[][] spatialToEarth(float[][] spatial_locs) throws VisADException { float[][] base_spatial_locs = new float[3][]; return spatialToEarth(spatial_locs, base_spatial_locs); } public float[][] spatialToEarth(float[][] spatial_locs, float[][] base_spatial_locs) throws VisADException { int lat = lat_index; int lon = lon_index; int other = other_index; if (lat_index < 0 || lon_index < 0) return null; if (spatial_locs.length != 3) return null; int size = 0; for (int i=0; i<3; i++) { if (spatial_locs[i] != null && spatial_locs[i].length > size) { size = spatial_locs[i].length; } } if (size == 0) return null; // fill any empty spatial DisplayRealTypes with default values for (int i=0; i<3; i++) { if (spatial_locs[i] == null) { spatial_locs[i] = new float[size]; // defaults for Cartesian spatial DisplayRealTypes = 0.0f for (int j=0; j<size; j++) spatial_locs[i][j] = 0.0f; } } if (display_coordinate_system != null) { // transform Cartesian spatial DisplayRealTypes to non-Cartesian spatial_locs = display_coordinate_system.fromReference(spatial_locs); } base_spatial_locs[0] = spatial_locs[0]; base_spatial_locs[1] = spatial_locs[1]; base_spatial_locs[2] = spatial_locs[2]; float[][] tuple_locs = new float[lat_lon_dimension][]; if (lat_lon_in) { if (lat_lon_in_by_coord) { // map spatial DisplayRealTypes to data_out for (int i=0; i<lat_lon_dimension; i++) { tuple_locs[i] = sdo_maps[i].inverseScaleValues(spatial_locs[sdo_spatial_index[i]]); } // transform 'RealTupleType data_out' to 'RealTupleType data_in' if (data_coord_in.length == 1) { // one data_coord_in applies to all data points tuple_locs = CoordinateSystem.transformCoordinates(data_in, data_coord_in[0], data_units_in, null, data_out, null, data_units_out, null, tuple_locs); } else { // one data_coord_in per data point float[][] temp = new float[lat_lon_dimension][1]; for (int j=0; j<size; j++) { for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j]; temp = CoordinateSystem.transformCoordinates(data_in, data_coord_in[j], data_units_in, null, data_out, null, data_units_out, null, temp); for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0]; } } } else { // map spatial DisplayRealTypes to data_in for (int i=0; i<lat_lon_dimension; i++) { tuple_locs[i] = sdi_maps[i].inverseScaleValues(spatial_locs[sdi_spatial_index[i]]); } } } else if (lat_lon_out) { if (lat_lon_out_by_coord) { // map spatial DisplayRealTypes to data_in for (int i=0; i<lat_lon_dimension; i++) { tuple_locs[i] = sdi_maps[i].inverseScaleValues(spatial_locs[sdi_spatial_index[i]]); } // transform 'RealTupleType data_in' to 'RealTupleType data_out' if (data_coord_in.length == 1) { // one data_coord_in applies to all data points tuple_locs = CoordinateSystem.transformCoordinates(data_out, null, data_units_out, null, data_in, data_coord_in[0], data_units_in, null, tuple_locs); } else { // one data_coord_in per data point float[][] temp = new float[lat_lon_dimension][1]; for (int j=0; j<size; j++) { for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j]; temp = CoordinateSystem.transformCoordinates(data_out, null, data_units_out, null, data_in, data_coord_in[j], data_units_in, null, temp); for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0]; } } } else { // map spatial DisplayRealTypes to data_out for (int i=0; i<lat_lon_dimension; i++) { tuple_locs[i] = sdo_maps[i].inverseScaleValues(spatial_locs[sdo_spatial_index[i]]); } } } else if (lat_lon_spatial) { // map spatial DisplayRealTypes to lat & lon, not in // allSpatial RealTupleType tuple_locs[lat] = lat_map.inverseScaleValues(spatial_locs[lat_spatial_index]); tuple_locs[lon] = lon_map.inverseScaleValues(spatial_locs[lon_spatial_index]); } else { // should never happen return null; } // permute data RealTupleType to (lat, lon, other) float[][] locs = new float[lat_lon_dimension][]; locs[0] = tuple_locs[lat]; locs[1] = tuple_locs[lon]; if (lat_lon_dimension == 3) locs[2] = tuple_locs[other]; return locs; } // information from doTransform public void setEarthSpatialData(ShadowRealTupleType s_d_i, ShadowRealTupleType s_d_o, RealTupleType d_o, Unit[] d_u_o, RealTupleType d_i, CoordinateSystem[] d_c_i, Unit[] d_u_i) throws VisADException { // first check for VectorRealType components mapped to flow // TO_DO: check here for flow mapped via CoordinateSystem if (d_o != null && d_o instanceof RealVectorType) { ScalarMap[] maps = new ScalarMap[3]; int k = getFlowMaps(s_d_o, maps); if (k > -1) rvts[k] = (RealVectorType) d_o; } if (d_i != null && d_i instanceof RealVectorType) { ScalarMap[] maps = new ScalarMap[3]; int k = getFlowMaps(s_d_i, maps); if (k > -1) rvts[k] = (RealVectorType) d_i; } int lat_index_local = -1; int lon_index_local = -1; other_index = -1; int n = 0; int m = 0; if (d_i != null) { n = d_i.getDimension(); for (int i=0; i<n; i++) { RealType real = (RealType) d_i.getComponent(i); if (RealType.Latitude.equals(real)) lat_index_local = i; if (RealType.Longitude.equals(real)) lon_index_local = i; } } if (lat_index_local > -1 && lon_index_local > -1 && (n == 2 || n == 3)) { if (s_d_i != null && s_d_i.getAllSpatial() && !s_d_i.getSpatialReference()) { lat_lon_in_by_coord = false; sdi_spatial_index = new int[s_d_i.getDimension()]; sdi_maps = getSpatialMaps(s_d_i, sdi_spatial_index); if (sdi_maps == null) { throw new DisplayException("sdi_maps null A"); } } else if (s_d_o != null && s_d_o.getAllSpatial() && !s_d_o.getSpatialReference()) { lat_lon_in_by_coord = true; sdo_spatial_index = new int[s_d_o.getDimension()]; sdo_maps = getSpatialMaps(s_d_o, sdo_spatial_index); if (sdo_maps == null) { throw new DisplayException("sdo_maps null A"); } } else { // do not update lat_index & lon_index return; } lat_lon_in = true; lat_lon_out = false; lat_lon_out_by_coord = false; lat_lon_spatial = false; lat_lon_dimension = n; if (n == 3) { other_index = 3 - (lat_index_local + lon_index_local); if (Unit.canConvert(d_u_i[other_index], CommonUnit.meter)) { other_meters = true; } } } else { // if( !(lat & lon in di, di dimension = 2 or 3) ) lat_index_local = -1; lon_index_local = -1; if (d_o != null) { m = d_o.getDimension(); for (int i=0; i<m; i++) { RealType real = (RealType) d_o.getComponent(i); if (RealType.Latitude.equals(real)) lat_index_local = i; if (RealType.Longitude.equals(real)) lon_index_local = i; } } if (lat_index_local < 0 || lon_index_local < 0 || !(m == 2 || m == 3)) { // do not update lat_index & lon_index return; } if (s_d_o != null && s_d_o.getAllSpatial() && !s_d_o.getSpatialReference()) { lat_lon_out_by_coord = false; sdo_spatial_index = new int[s_d_o.getDimension()]; sdo_maps = getSpatialMaps(s_d_o, sdo_spatial_index); if (sdo_maps == null) { throw new DisplayException("sdo_maps null B"); } } else if (s_d_i != null && s_d_i.getAllSpatial() && !s_d_i.getSpatialReference()) { lat_lon_out_by_coord = true; sdi_spatial_index = new int[s_d_i.getDimension()]; sdi_maps = getSpatialMaps(s_d_i, sdi_spatial_index); if (sdi_maps == null) { throw new DisplayException("sdi_maps null B"); } } else { // do not update lat_index & lon_index return; } lat_lon_out = true; lat_lon_in = false; lat_lon_in_by_coord = false; lat_lon_spatial = false; lat_lon_dimension = m; if (m == 3) { other_index = 3 - (lat_index_local + lon_index_local); if (Unit.canConvert(d_u_i[other_index], CommonUnit.meter)) { other_meters = true; } } } shadow_data_out = s_d_o; data_out = d_o; data_units_out = d_u_o; shadow_data_in = s_d_i; data_in = d_i; data_units_in = d_u_i; data_coord_in = d_c_i; // may be one per point lat_index = lat_index_local; lon_index = lon_index_local; return; } /** return array of spatial ScalarMap for srt, or null */ private ScalarMap[] getSpatialMaps(ShadowRealTupleType srt, int[] spatial_index) { int n = srt.getDimension(); ScalarMap[] maps = new ScalarMap[n]; for (int i=0; i<n; i++) { ShadowRealType real = (ShadowRealType) srt.getComponent(i); Enumeration ms = real.getSelectedMapVector().elements(); while (ms.hasMoreElements()) { ScalarMap map = (ScalarMap) ms.nextElement(); DisplayRealType dreal = map.getDisplayScalar(); DisplayTupleType tuple = dreal.getTuple(); if (tuple != null && (tuple.equals(Display.DisplaySpatialCartesianTuple) || (tuple.getCoordinateSystem() != null && tuple.getCoordinateSystem().getReference().equals( Display.DisplaySpatialCartesianTuple)))) { maps[i] = map; spatial_index[i] = dreal.getTupleIndex(); break; } } if (maps[i] == null) { return null; } } return maps; } /** return array of flow ScalarMap for srt, or null */ private int getFlowMaps(ShadowRealTupleType srt, ScalarMap[] maps) { int n = srt.getDimension(); maps[0] = null; maps[1] = null; maps[2] = null; DisplayTupleType ftuple = null; for (int i=0; i<n; i++) { ShadowRealType real = (ShadowRealType) srt.getComponent(i); Enumeration ms = real.getSelectedMapVector().elements(); while (ms.hasMoreElements()) { ScalarMap map = (ScalarMap) ms.nextElement(); DisplayRealType dreal = map.getDisplayScalar(); DisplayTupleType tuple = dreal.getTuple(); if (Display.DisplayFlow1Tuple.equals(tuple) || Display.DisplayFlow2Tuple.equals(tuple)) { if (ftuple != null && !ftuple.equals(tuple)) return -1; ftuple = tuple; maps[i] = map; break; } } if (maps[i] == null) return -1; } return Display.DisplayFlow1Tuple.equals(ftuple) ? 0 : 1; } // from assembleFlow ScalarMap[][] flow_maps = null; float[] flow_scale = null; public void setFlowDisplay(ScalarMap[][] maps, float[] fs) { flow_maps = maps; flow_scale = fs; } // if non-null, float[][] new_spatial_values = // display_coordinate_system.toReference(spatial_values); CoordinateSystem display_coordinate_system = null; // spatial_tuple and spatial_value_indices are set whether // display_coordinate_system is null or not DisplayTupleType spatial_tuple = null; // map from spatial_tuple tuple_index to value array indices int[] spatial_value_indices = {-1, -1, -1}; float[] default_spatial_in = {0.0f, 0.0f, 0.0f}; // true if lat and lon mapped directly to spatial boolean lat_lon_spatial = false; ScalarMap lat_map = null; ScalarMap lon_map = null; int lat_spatial_index = -1; int lon_spatial_index = -1; // spatial map getRange() results for flow adjustment double[] ranges = null; public double[] getRanges() { return ranges; } // WLH 4 March 2000 public CoordinateSystem getDisplayCoordinateSystem() { return display_coordinate_system ; } // information from assembleSpatial public void setEarthSpatialDisplay(CoordinateSystem coord, DisplayTupleType t, DisplayImpl display, int[] indices, float[] default_values, double[] r) throws VisADException { display_coordinate_system = coord; spatial_tuple = t; System.arraycopy(indices, 0, spatial_value_indices, 0, 3); /* WLH 5 Dec 99 spatial_value_indices = indices; */ ranges = r; for (int i=0; i<3; i++) { int default_index = display.getDisplayScalarIndex( ((DisplayRealType) t.getComponent(i)) ); default_spatial_in[i] = default_values[default_index]; } if (lat_index > -1 && lon_index > -1) return; lat_index = -1; lon_index = -1; other_index = -1; int valueArrayLength = display.getValueArrayLength(); int[] valueToScalar = display.getValueToScalar(); int[] valueToMap = display.getValueToMap(); Vector MapVector = display.getMapVector(); for (int i=0; i<valueArrayLength; i++) { ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]); ScalarType real = map.getScalar(); DisplayRealType dreal = map.getDisplayScalar(); DisplayTupleType tuple = dreal.getTuple(); if (tuple != null && (tuple.equals(Display.DisplaySpatialCartesianTuple) || (tuple.getCoordinateSystem() != null && tuple.getCoordinateSystem().getReference().equals( Display.DisplaySpatialCartesianTuple)))) { if (RealType.Latitude.equals(real)) { lat_index = 0; lat_map = map; lat_spatial_index = dreal.getTupleIndex(); } if (RealType.Longitude.equals(real)) { lon_index = 1; lon_map = map; lon_spatial_index = dreal.getTupleIndex(); } } } if (lat_index > -1 && lon_index > -1) { lat_lon_spatial = true; lat_lon_dimension = 2; lat_lon_out = false; lat_lon_in_by_coord = false; lat_lon_in = false; } else { lat_lon_spatial = false; lat_index = -1; lon_index = -1; } } /* *************************** */ /* direct manipulation stuff */ /* *************************** */ private float[][] spatialValues = null; /** if Function, last domain index and range values */ private int lastIndex = -1; double[] lastD = null; float[] lastX = new float[6]; /** index into spatialValues found by checkClose */ private int closeIndex = -1; /** for use in drag_direct */ private transient DataDisplayLink link = null; // private transient ShadowTypeJ3D type = null; private transient DataReference ref = null; private transient MathType type = null; private transient ShadowType shadow = null; /** point on direct manifold line or plane */ private float point_x, point_y, point_z; /** normalized direction of line or perpendicular to plane */ private float line_x, line_y, line_z; /** arrays of length one for inverseScaleValues */ private float[] f = new float[1]; private float[] d = new float[1]; private float[][] value = new float[1][1]; /** information calculated by checkDirect */ /** explanation for invalid use of DirectManipulationRenderer */ private String whyNotDirect = null; /** mapping from spatial axes to tuple component */ private int[] axisToComponent = {-1, -1, -1}; /** mapping from spatial axes to ScalarMaps */ private ScalarMap[] directMap = {null, null, null}; /** spatial axis for Function domain */ private int domainAxis = -1; /** dimension of direct manipulation (including any Function domain) */ private int directManifoldDimension = 0; /** spatial DisplayTupleType other than DisplaySpatialCartesianTuple */ DisplayTupleType tuple; /** possible values for whyNotDirect */ private final static String notRealFunction = "FunctionType must be Real"; private final static String notSimpleField = "not simple field"; private final static String notSimpleTuple = "not simple tuple"; private final static String multipleMapping = "RealType with multiple mappings"; private final static String multipleSpatialMapping = "RealType with multiple spatial mappings"; private final static String nonSpatial = "no spatial mapping"; private final static String viaReference = "spatial mapping through Reference"; private final static String domainDimension = "domain dimension must be 1"; private final static String domainNotSpatial = "domain must be mapped to spatial"; private final static String rangeType = "range must be RealType or RealTupleType"; private final static String rangeNotSpatial = "range must be mapped to spatial"; private final static String domainSet = "domain Set must be Gridded1DSet"; private final static String tooFewSpatial = "Function without spatial domain"; private final static String functionTooFew = "Function directManifoldDimension < 2"; private final static String badCoordSysManifoldDim = "bad directManifoldDimension with spatial CoordinateSystem"; public synchronized void realCheckDirect() throws VisADException, RemoteException { setIsDirectManipulation(false); link = getLinks()[0]; ref = link.getDataReference(); shadow = link.getShadow().getAdaptedShadowType(); type = link.getType(); tuple = null; if (type instanceof FunctionType) { ShadowRealTupleType domain = ((ShadowFunctionType) shadow).getDomain(); ShadowType range = ((ShadowFunctionType) shadow).getRange(); tuple = domain.getDisplaySpatialTuple(); // there is some redundancy among these conditions if (!((FunctionType) type).getReal()) { whyNotDirect = notRealFunction; return; } else if (shadow.getLevelOfDifficulty() != ShadowType.SIMPLE_FIELD) { whyNotDirect = notSimpleTuple; return; } else if (shadow.getMultipleSpatialDisplayScalar()) { whyNotDirect = multipleSpatialMapping; return; } else if (domain.getDimension() != 1) { whyNotDirect = domainDimension; return; } else if(!(Display.DisplaySpatialCartesianTuple.equals(tuple) || (tuple != null && tuple.getCoordinateSystem().getReference().equals( Display.DisplaySpatialCartesianTuple)) )) { whyNotDirect = domainNotSpatial; return; } else if (domain.getSpatialReference()) { whyNotDirect = viaReference; return; } DisplayTupleType rtuple = null; if (range instanceof ShadowRealTupleType) { rtuple = ((ShadowRealTupleType) range).getDisplaySpatialTuple(); } else if (range instanceof ShadowRealType) { rtuple = ((ShadowRealType) range).getDisplaySpatialTuple(); } else { whyNotDirect = rangeType; return; } if (!tuple.equals(rtuple)) { /* WLH 3 Aug 98 if (!Display.DisplaySpatialCartesianTuple.equals(rtuple)) { */ whyNotDirect = rangeNotSpatial; return; } else if (range instanceof ShadowRealTupleType && ((ShadowRealTupleType) range).getSpatialReference()) { whyNotDirect = viaReference; return; } else if (!(link.getData() instanceof Field) || !(((Field) link.getData()).getDomainSet() instanceof Gridded1DSet)) { whyNotDirect = domainSet; return; } if (Display.DisplaySpatialCartesianTuple.equals(tuple)) { tuple = null; } domainAxis = -1; for (int i=0; i<3; i++) { axisToComponent[i] = -1; directMap[i] = null; } directManifoldDimension = setDirectMap((ShadowRealType) domain.getComponent(0), -1, true); if (range instanceof ShadowRealType) { directManifoldDimension += setDirectMap((ShadowRealType) range, 0, false); } else if (range instanceof ShadowRealTupleType) { ShadowRealTupleType r = (ShadowRealTupleType) range; for (int i=0; i<r.getDimension(); i++) { directManifoldDimension += setDirectMap((ShadowRealType) r.getComponent(i), i, false); } } if (domainAxis == -1) { whyNotDirect = tooFewSpatial; return; } if (directManifoldDimension < 2) { whyNotDirect = functionTooFew; return; } boolean twod = displayRenderer.getMode2D(); if (tuple != null && (!twod && directManifoldDimension != 3 || twod && directManifoldDimension != 2) ) { whyNotDirect = badCoordSysManifoldDim; return; } setIsDirectManipulation(true); /* WLH 3 Aug 98 if (domainAxis == -1) { throw new DisplayException("DataRenderer.realCheckDirect:" + "too few spatial domain"); } if (directManifoldDimension < 2) { throw new DisplayException("DataRenderer.realCheckDirect:" + "directManifoldDimension < 2"); } */ } else if (type instanceof RealTupleType) { // // TO_DO // allow for any Flat ShadowTupleType // tuple = ((ShadowRealTupleType) shadow).getDisplaySpatialTuple(); if (shadow.getLevelOfDifficulty() != ShadowType.SIMPLE_TUPLE) { whyNotDirect = notSimpleTuple; return; } else if (shadow.getMultipleSpatialDisplayScalar()) { whyNotDirect = multipleSpatialMapping; return; } else if(!(Display.DisplaySpatialCartesianTuple.equals(tuple) || (tuple != null && tuple.getCoordinateSystem().getReference().equals( Display.DisplaySpatialCartesianTuple)) )) { /* WLH 3 Aug 98 else if (!Display.DisplaySpatialCartesianTuple.equals( ((ShadowRealTupleType) shadow).getDisplaySpatialTuple())) { */ whyNotDirect = nonSpatial; return; } else if (((ShadowRealTupleType) shadow).getSpatialReference()) { whyNotDirect = viaReference; return; } /* WLH 3 Aug 98 setIsDirectManipulation(true); */ if (Display.DisplaySpatialCartesianTuple.equals(tuple)) { tuple = null; } domainAxis = -1; for (int i=0; i<3; i++) { axisToComponent[i] = -1; directMap[i] = null; } directManifoldDimension = 0; for (int i=0; i<((ShadowRealTupleType) shadow).getDimension(); i++) { directManifoldDimension += setDirectMap((ShadowRealType) ((ShadowRealTupleType) shadow).getComponent(i), i, false); } boolean twod = displayRenderer.getMode2D(); if (tuple != null && (!twod && directManifoldDimension != 3 || twod && directManifoldDimension != 2) ) { whyNotDirect = badCoordSysManifoldDim; return; } setIsDirectManipulation(true); } else if (type instanceof RealType) { tuple = ((ShadowRealType) shadow).getDisplaySpatialTuple(); if (shadow.getLevelOfDifficulty() != ShadowType.SIMPLE_TUPLE) { whyNotDirect = notSimpleTuple; return; } else if (shadow.getMultipleSpatialDisplayScalar()) { whyNotDirect = multipleSpatialMapping; return; } else if(!(Display.DisplaySpatialCartesianTuple.equals(tuple) || (tuple != null && tuple.getCoordinateSystem().getReference().equals( Display.DisplaySpatialCartesianTuple)) )) { /* WLH 3 Aug 98 else if(!Display.DisplaySpatialCartesianTuple.equals( ((ShadowRealType) shadow).getDisplaySpatialTuple())) { */ whyNotDirect = nonSpatial; return; } /* WLH 3 Aug 98 setIsDirectManipulation(true); */ if (Display.DisplaySpatialCartesianTuple.equals(tuple)) { tuple = null; } domainAxis = -1; for (int i=0; i<3; i++) { axisToComponent[i] = -1; directMap[i] = null; } directManifoldDimension = setDirectMap((ShadowRealType) shadow, 0, false); boolean twod = displayRenderer.getMode2D(); if (tuple != null && (!twod && directManifoldDimension != 3 || twod && directManifoldDimension != 2) ) { whyNotDirect = badCoordSysManifoldDim; return; } setIsDirectManipulation(true); } // end else if (type instanceof RealType) } /** set directMap and axisToComponent (domain = false) or domainAxis (domain = true) from real; called by realCheckDirect */ synchronized int setDirectMap(ShadowRealType real, int component, boolean domain) { Enumeration maps = real.getSelectedMapVector().elements(); while (maps.hasMoreElements()) { ScalarMap map = (ScalarMap) maps.nextElement(); DisplayRealType dreal = map.getDisplayScalar(); DisplayTupleType tuple = dreal.getTuple(); if (Display.DisplaySpatialCartesianTuple.equals(tuple) || (tuple != null && tuple.getCoordinateSystem().getReference().equals( Display.DisplaySpatialCartesianTuple)) ) { int index = dreal.getTupleIndex(); if (domain) { domainAxis = index; } else { axisToComponent[index] = component; } directMap[index] = map; return 1; } } return 0; } private int getDirectManifoldDimension() { return directManifoldDimension; } public String getWhyNotDirect() { return whyNotDirect; } private int getAxisToComponent(int i) { return axisToComponent[i]; } private ScalarMap getDirectMap(int i) { return directMap[i]; } private int getDomainAxis() { return domainAxis; } /** set spatialValues from ShadowType.doTransform */ public synchronized void setSpatialValues(float[][] spatial_values) { // these are X, Y, Z values spatialValues = spatial_values; } /** find minimum distance from ray to spatialValues */ public synchronized float checkClose(double[] origin, double[] direction) { float distance = Float.MAX_VALUE; lastIndex = -1; if (spatialValues == null) return distance; float o_x = (float) origin[0]; float o_y = (float) origin[1]; float o_z = (float) origin[2]; float d_x = (float) direction[0]; float d_y = (float) direction[1]; float d_z = (float) direction[2]; /* System.out.println("origin = " + o_x + " " + o_y + " " + o_z); System.out.println("direction = " + d_x + " " + d_y + " " + d_z); */ for (int i=0; i<spatialValues[0].length; i++) { float x = spatialValues[0][i] - o_x; float y = spatialValues[1][i] - o_y; float z = spatialValues[2][i] - o_z; float dot = x * d_x + y * d_y + z * d_z; x = x - dot * d_x; y = y - dot * d_y; z = z - dot * d_z; float d = (float) Math.sqrt(x * x + y * y + z * z); if (d < distance) { distance = d; closeIndex = i; } /* System.out.println("spatialValues["+i+"] = " + spatialValues[0][i] + " " + spatialValues[1][i] + " " + spatialValues[2][i] + " d = " + d); */ } /* System.out.println("checkClose: distance = " + distance); */ return distance; } /** mouse button released, ending direct manipulation */ public synchronized void release_direct() { } public synchronized void drag_direct(VisADRay ray, boolean first, int mouseModifiers) { // System.out.println("drag_direct " + first + " " + type); if (spatialValues == null || ref == null || shadow == null) return; float o_x = (float) ray.position[0]; float o_y = (float) ray.position[1]; float o_z = (float) ray.position[2]; float d_x = (float) ray.vector[0]; float d_y = (float) ray.vector[1]; float d_z = (float) ray.vector[2]; if (first) { point_x = spatialValues[0][closeIndex]; point_y = spatialValues[1][closeIndex]; point_z = spatialValues[2][closeIndex]; int lineAxis = -1; if (getDirectManifoldDimension() == 3) { // coord sys ok line_x = d_x; line_y = d_y; line_z = d_z; } else { if (getDirectManifoldDimension() == 2) { if (displayRenderer.getMode2D()) { // coord sys ok lineAxis = 2; } else { for (int i=0; i<3; i++) { if (getAxisToComponent(i) < 0 && getDomainAxis() != i) { lineAxis = i; } } } } else if (getDirectManifoldDimension() == 1) { for (int i=0; i<3; i++) { if (getAxisToComponent(i) >= 0) { lineAxis = i; } } } line_x = (lineAxis == 0) ? 1.0f : 0.0f; line_y = (lineAxis == 1) ? 1.0f : 0.0f; line_z = (lineAxis == 2) ? 1.0f : 0.0f; } } // end if (first) float[] x = new float[3]; // x marks the spot if (getDirectManifoldDimension() == 1) { // find closest point on line to ray // logic from vis5d/cursor.c // line o_, d_ to line point_, line_ float ld = d_x * line_x + d_y * line_y + d_z * line_z; float od = o_x * d_x + o_y * d_y + o_z * d_z; float pd = point_x * d_x + point_y * d_y + point_z * d_z; float ol = o_x * line_x + o_y * line_y + o_z * line_z; float pl = point_x * line_x + point_y * line_y + point_z * line_z; if (ld * ld == 1.0f) return; float t = ((pl - ol) - (ld * (pd - od))) / (ld * ld - 1.0f); // x is closest point x[0] = point_x + t * line_x; x[1] = point_y + t * line_y; x[2] = point_z + t * line_z; } else { // getDirectManifoldDimension() = 2 or 3 // intersect ray with plane float dot = (point_x - o_x) * line_x + (point_y - o_y) * line_y + (point_z - o_z) * line_z; float dot2 = d_x * line_x + d_y * line_y + d_z * line_z; if (dot2 == 0.0) return; dot = dot / dot2; // x is intersection x[0] = o_x + dot * d_x; x[1] = o_y + dot * d_y; x[2] = o_z + dot * d_z; } // // TO_DO // might estimate errors from pixel resolution on screen // try { float[] xx = {x[0], x[1], x[2]}; if (tuple != null) { float[][] cursor = {{x[0]}, {x[1]}, {x[2]}}; float[][] new_cursor = tuple.getCoordinateSystem().fromReference(cursor); x[0] = new_cursor[0][0]; x[1] = new_cursor[1][0]; x[2] = new_cursor[2][0]; } Data newData = null; Data data = link.getData(); if (type instanceof RealType) { addPoint(xx); for (int i=0; i<3; i++) { if (getAxisToComponent(i) >= 0) { f[0] = x[i]; d = getDirectMap(i).inverseScaleValues(f); // RealType rtype = (RealType) data.getType(); RealType rtype = (RealType) type; newData = new Real(rtype, (double) d[0], rtype.getDefaultUnit(), null); // create location string Vector vect = new Vector(); /* WLH 26 July 99 float g = d[0]; vect.addElement(rtype.getName() + " = " + g); */ String valueString = new Real(rtype, d[0]).toValueString(); vect.addElement(rtype.getName() + " = " + valueString); getDisplayRenderer().setCursorStringVector(vect); break; } } ref.setData(newData); link.clearData(); // WLH 27 July 99 } else if (type instanceof RealTupleType) { addPoint(xx); int n = ((RealTuple) data).getDimension(); Real[] reals = new Real[n]; Vector vect = new Vector(); for (int i=0; i<3; i++) { int j = getAxisToComponent(i); if (j >= 0) { f[0] = x[i]; d = getDirectMap(i).inverseScaleValues(f); Real c = (Real) ((RealTuple) data).getComponent(j); RealType rtype = (RealType) c.getType(); reals[j] = new Real(rtype, (double) d[0], rtype.getDefaultUnit(), null); // create location string /* WLH 26 July 99 float g = d[0]; vect.addElement(rtype.getName() + " = " + g); */ String valueString = new Real(rtype, d[0]).toValueString(); vect.addElement(rtype.getName() + " = " + valueString); } } getDisplayRenderer().setCursorStringVector(vect); for (int j=0; j<n; j++) { if (reals[j] == null) { reals[j] = (Real) ((RealTuple) data).getComponent(j); } } newData = new RealTuple((RealTupleType) type, reals, ((RealTuple) data).getCoordinateSystem()); ref.setData(newData); link.clearData(); // WLH 27 July 99 } else if (type instanceof FunctionType) { Vector vect = new Vector(); if (first) lastIndex = -1; int k = getDomainAxis(); f[0] = x[k]; d = getDirectMap(k).inverseScaleValues(f); RealType rtype = (RealType) getDirectMap(k).getScalar(); // WLH 4 Jan 99 // convert d from default Unit to actual domain Unit of data Unit[] us = ((Field) data).getDomainUnits(); if (us != null && us[0] != null) { d[0] = (float) us[0].toThis((double) d[0], rtype.getDefaultUnit()); } // create location string float g = d[0]; vect.addElement(rtype.getName() + " = " + g); // convert domain value to domain index Gridded1DSet set = (Gridded1DSet) ((Field) data).getDomainSet(); value[0][0] = (float) d[0]; int[] indices = set.valueToIndex(value); int thisIndex = indices[0]; if (thisIndex < 0) { lastIndex = -1; return; } if (lastIndex < 0) { addPoint(xx); } else { lastX[3] = xx[0]; lastX[4] = xx[1]; lastX[5] = xx[2]; addPoint(lastX); } lastX[0] = xx[0]; lastX[1] = xx[1]; lastX[2] = xx[2]; int n; MathType range = ((FunctionType) type).getRange(); if (range instanceof RealType) { n = 1; } else { n = ((RealTupleType) range).getDimension(); } double[] thisD = new double[n]; boolean[] directComponent = new boolean[n]; for (int j=0; j<n; j++) { thisD[j] = Double.NaN; directComponent[j] = false; } for (int i=0; i<3; i++) { int j = getAxisToComponent(i); if (j >= 0) { f[0] = x[i]; d = getDirectMap(i).inverseScaleValues(f); // create location string rtype = (RealType) getDirectMap(i).getScalar(); /* WLH 26 July 99 g = (float) d[0]; vect.addElement(rtype.getName() + " = " + g); */ String valueString = new Real(rtype, d[0]).toValueString(); vect.addElement(rtype.getName() + " = " + valueString); thisD[j] = d[0]; directComponent[j] = true; } } getDisplayRenderer().setCursorStringVector(vect); if (lastIndex < 0) { lastIndex = thisIndex; lastD = new double[n]; for (int j=0; j<n; j++) { lastD[j] = thisD[j]; } } Real[] reals = new Real[n]; int m = Math.abs(lastIndex - thisIndex) + 1; indices = new int[m]; int index = thisIndex; int inc = (lastIndex >= thisIndex) ? 1 : -1; for (int i=0; i<m; i++) { indices[i] = index; index += inc; } float[][] values = set.indexToValue(indices); double coefDiv = values[0][m-1] - values[0][0]; for (int i=0; i<m; i++) { index = indices[i]; double coef = (i == 0 || coefDiv == 0.0) ? 0.0 : (values[0][i] - values[0][0]) / coefDiv; Data tuple = ((Field) data).getSample(index); if (tuple instanceof Real) { if (directComponent[0]) { rtype = (RealType) tuple.getType(); tuple = new Real(rtype, thisD[0] + coef * (lastD[0] - thisD[0]), rtype.getDefaultUnit(), null); } } else { for (int j=0; j<n; j++) { Real c = (Real) ((RealTuple) tuple).getComponent(j); if (directComponent[j]) { rtype = (RealType) c.getType(); reals[j] = new Real(rtype, thisD[j] + coef * (lastD[j] - thisD[j]), rtype.getDefaultUnit(), null); } else { reals[j] = c; } } tuple = new RealTuple(reals); } ((Field) data).setSample(index, tuple); } // end for (int i=0; i<m; i++) if (ref instanceof RemoteDataReference && !(data instanceof RemoteData)) { // ref is Remote and data is local, so we have only modified // a local copy and must send it back to ref ref.setData(data); link.clearData(); // WLH 27 July 99 } // set last index to this, and component values lastIndex = thisIndex; for (int j=0; j<n; j++) { lastD[j] = thisD[j]; } } // end else if (type instanceof FunctionType) } // end try catch (VisADException e) { // do nothing System.out.println("drag_direct " + e); e.printStackTrace(); } catch (RemoteException e) { // do nothing System.out.println("drag_direct " + e); e.printStackTrace(); } } public void addPoint(float[] x) throws VisADException { } /** flag indicating whether DirectManipulationRenderer is valid for this ShadowType */ private boolean isDirectManipulation; /** set isDirectManipulation = true if this DataRenderer supports direct manipulation for its linked Data */ public void checkDirect() throws VisADException, RemoteException { isDirectManipulation = false; } public void setIsDirectManipulation(boolean b) { isDirectManipulation = b; } public boolean getIsDirectManipulation() { return isDirectManipulation; } /* public void drag_direct(VisADRay ray, boolean first) { throw new VisADError("DataRenderer.drag_direct: not direct " + "manipulation renderer"); } */ }
diff --git a/grails/src/java/org/codehaus/groovy/grails/context/annotation/ClosureClassIgnoringComponentScanBeanDefinitionParser.java b/grails/src/java/org/codehaus/groovy/grails/context/annotation/ClosureClassIgnoringComponentScanBeanDefinitionParser.java index 68969995d..2655d63a1 100644 --- a/grails/src/java/org/codehaus/groovy/grails/context/annotation/ClosureClassIgnoringComponentScanBeanDefinitionParser.java +++ b/grails/src/java/org/codehaus/groovy/grails/context/annotation/ClosureClassIgnoringComponentScanBeanDefinitionParser.java @@ -1,111 +1,113 @@ /* Copyright 2004-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.context.annotation; import grails.util.BuildSettings; import grails.util.BuildSettingsHolder; import grails.util.Metadata; import org.apache.commons.io.FilenameUtils; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; import org.springframework.context.annotation.ComponentScanBeanDefinitionParser; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.util.AntPathMatcher; import org.w3c.dom.Element; import java.io.IOException; import java.net.URL; import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.Set; /** * Extends Spring's default &lt;context:component-scan/&gt; element to ignore Groovy's * generated closure classes * * @author Graeme Rocher * @since 1.2 */ public class ClosureClassIgnoringComponentScanBeanDefinitionParser extends ComponentScanBeanDefinitionParser{ @Override protected ClassPathBeanDefinitionScanner configureScanner(ParserContext parserContext, Element element) { final ClassPathBeanDefinitionScanner scanner = super.configureScanner(parserContext, element); final PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(parserContext.getReaderContext().getResourceLoader()) { @Override protected Resource[] findAllClassPathResources(String location) throws IOException { Set<Resource> result = new LinkedHashSet<Resource>(16); URL classesDir = null; final boolean warDeployed = Metadata.getCurrent().isWarDeployed(); if(!warDeployed) { BuildSettings buildSettings = BuildSettingsHolder.getSettings(); - classesDir = buildSettings.getClassesDir().toURI().toURL(); + if(buildSettings != null && buildSettings.getClassesDir()!=null) { + classesDir = buildSettings.getClassesDir().toURI().toURL(); + } } // only scan classes from project classes directory String path = location; if (path.startsWith("/")) { path = path.substring(1); } Enumeration resourceUrls = getClassLoader().getResources(path); while (resourceUrls.hasMoreElements()) { URL url = (URL) resourceUrls.nextElement(); if(!warDeployed && classesDir!= null && url.equals(classesDir)) { result.add(convertClassLoaderURL(url)); } - else { + else if(warDeployed){ result.add(convertClassLoaderURL(url)); } } return result.toArray(new Resource[result.size()]); } }; resourceResolver.setPathMatcher(new AntPathMatcher(){ @Override public boolean match(String pattern, String path) { if(path.endsWith(".class")) { String filename = FilenameUtils.getBaseName(path); if(filename.indexOf("$")>-1) return false; } return super.match(pattern, path); } }); scanner.setResourceLoader(resourceResolver); return scanner; } class DelegatingResourceLoader implements ResourceLoader{ private ResourceLoader delegate; DelegatingResourceLoader(ResourceLoader loader) { this.delegate = loader; } public Resource getResource(String location) { System.out.println("location = " + location); return delegate.getResource(location); } public ClassLoader getClassLoader() { return delegate.getClassLoader(); } } }
false
true
protected ClassPathBeanDefinitionScanner configureScanner(ParserContext parserContext, Element element) { final ClassPathBeanDefinitionScanner scanner = super.configureScanner(parserContext, element); final PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(parserContext.getReaderContext().getResourceLoader()) { @Override protected Resource[] findAllClassPathResources(String location) throws IOException { Set<Resource> result = new LinkedHashSet<Resource>(16); URL classesDir = null; final boolean warDeployed = Metadata.getCurrent().isWarDeployed(); if(!warDeployed) { BuildSettings buildSettings = BuildSettingsHolder.getSettings(); classesDir = buildSettings.getClassesDir().toURI().toURL(); } // only scan classes from project classes directory String path = location; if (path.startsWith("/")) { path = path.substring(1); } Enumeration resourceUrls = getClassLoader().getResources(path); while (resourceUrls.hasMoreElements()) { URL url = (URL) resourceUrls.nextElement(); if(!warDeployed && classesDir!= null && url.equals(classesDir)) { result.add(convertClassLoaderURL(url)); } else { result.add(convertClassLoaderURL(url)); } } return result.toArray(new Resource[result.size()]); } }; resourceResolver.setPathMatcher(new AntPathMatcher(){ @Override public boolean match(String pattern, String path) { if(path.endsWith(".class")) { String filename = FilenameUtils.getBaseName(path); if(filename.indexOf("$")>-1) return false; } return super.match(pattern, path); } }); scanner.setResourceLoader(resourceResolver); return scanner; }
protected ClassPathBeanDefinitionScanner configureScanner(ParserContext parserContext, Element element) { final ClassPathBeanDefinitionScanner scanner = super.configureScanner(parserContext, element); final PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(parserContext.getReaderContext().getResourceLoader()) { @Override protected Resource[] findAllClassPathResources(String location) throws IOException { Set<Resource> result = new LinkedHashSet<Resource>(16); URL classesDir = null; final boolean warDeployed = Metadata.getCurrent().isWarDeployed(); if(!warDeployed) { BuildSettings buildSettings = BuildSettingsHolder.getSettings(); if(buildSettings != null && buildSettings.getClassesDir()!=null) { classesDir = buildSettings.getClassesDir().toURI().toURL(); } } // only scan classes from project classes directory String path = location; if (path.startsWith("/")) { path = path.substring(1); } Enumeration resourceUrls = getClassLoader().getResources(path); while (resourceUrls.hasMoreElements()) { URL url = (URL) resourceUrls.nextElement(); if(!warDeployed && classesDir!= null && url.equals(classesDir)) { result.add(convertClassLoaderURL(url)); } else if(warDeployed){ result.add(convertClassLoaderURL(url)); } } return result.toArray(new Resource[result.size()]); } }; resourceResolver.setPathMatcher(new AntPathMatcher(){ @Override public boolean match(String pattern, String path) { if(path.endsWith(".class")) { String filename = FilenameUtils.getBaseName(path); if(filename.indexOf("$")>-1) return false; } return super.match(pattern, path); } }); scanner.setResourceLoader(resourceResolver); return scanner; }
diff --git a/src/org/linphone/LinphoneService.java b/src/org/linphone/LinphoneService.java index b36b3a3..3b18b8b 100644 --- a/src/org/linphone/LinphoneService.java +++ b/src/org/linphone/LinphoneService.java @@ -1,482 +1,483 @@ /* LinphoneService.java Copyright (C) 2010 Belledonne Communications, Grenoble, France This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.linphone; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.linphone.LinphoneManager.NewOutgoingCallUiListener; import org.linphone.LinphoneSimpleListener.LinphoneServiceListener; import org.linphone.core.LinphoneCall; import org.linphone.core.LinphoneCore; import org.linphone.core.LinphoneProxyConfig; import org.linphone.core.Log; import org.linphone.core.OnlineStatus; import org.linphone.core.LinphoneCall.State; import org.linphone.core.LinphoneCore.GlobalState; import org.linphone.core.LinphoneCore.RegistrationState; import org.linphone.mediastream.Version; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.media.MediaPlayer; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.preference.PreferenceManager; /** * * Linphone service, reacting to Incoming calls, ...<br /> * * Roles include:<ul> * <li>Initializing LinphoneManager</li> * <li>Starting C libLinphone through LinphoneManager</li> * <li>Reacting to LinphoneManager state changes</li> * <li>Delegating GUI state change actions to GUI listener</li> * * * @author Guillaume Beraudo * */ public final class LinphoneService extends Service implements LinphoneServiceListener { /* Listener needs to be implemented in the Service as it calls * setLatestEventInfo and startActivity() which needs a context. */ private Handler mHandler = new Handler(); private static LinphoneService instance; // private boolean mTestDelayElapsed; // add a timer for testing private boolean mTestDelayElapsed = true; // no timer public static boolean isReady() { return instance!=null && instance.mTestDelayElapsed; } /** * @throws RuntimeException service not instantiated */ static LinphoneService instance() { if (isReady()) return instance; throw new RuntimeException("LinphoneService not instantiated yet"); } private final static int NOTIF_ID=1; private final static int INCALL_NOTIF_ID=2; private Notification mNotif; private Notification mIncallNotif; private PendingIntent mNotifContentIntent; private String mNotificationTitle; private static final int IC_LEVEL_ORANGE=0; /*private static final int IC_LEVEL_GREEN=1; private static final int IC_LEVEL_RED=2;*/ private static final int IC_LEVEL_OFFLINE=3; @Override public void onCreate() { super.onCreate(); // In case restart after a crash. Main in LinphoneActivity LinphonePreferenceManager.getInstance(this); // Set default preferences PreferenceManager.setDefaultValues(this, R.xml.preferences, true); mNotificationTitle = getString(R.string.app_name); // Dump some debugging information to the logs Log.i(START_LINPHONE_LOGS); dumpDeviceInformation(); dumpInstalledLinphoneInformation(); mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); + mNM.cancel(INCALL_NOTIF_ID); // in case of crash the icon is not removed mNotif = new Notification(R.drawable.status_level, "", System.currentTimeMillis()); mNotif.iconLevel=IC_LEVEL_ORANGE; mNotif.flags |= Notification.FLAG_ONGOING_EVENT; Intent notifIntent = new Intent(this, LinphoneActivity.class); mNotifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, 0); mNotif.setLatestEventInfo(this, mNotificationTitle,"", mNotifContentIntent); LinphoneManager.createAndStart(this, this); LinphoneManager.getLc().setPresenceInfo(0, null, OnlineStatus.Online); instance = this; // instance is ready once linphone manager has been created // Retrieve methods to publish notification and keep Android // from killing us and keep the audio quality high. if (Version.sdkStrictlyBelow(Version.API05_ECLAIR_20)) { try { mSetForeground = getClass().getMethod("setForeground", mSetFgSign); } catch (NoSuchMethodException e) { Log.e(e, "Couldn't find foreground method"); } } else { try { mStartForeground = getClass().getMethod("startForeground", mStartFgSign); mStopForeground = getClass().getMethod("stopForeground", mStopFgSign); } catch (NoSuchMethodException e) { Log.e(e, "Couldn't find startGoreground or stopForeground"); } } startForegroundCompat(NOTIF_ID, mNotif); if (!mTestDelayElapsed) { // Only used when testing. Simulates a 5 seconds delay for launching service mHandler.postDelayed(new Runnable() { @Override public void run() { mTestDelayElapsed = true; } }, 5000); } } private enum IncallIconState {INCALL, PAUSE, VIDEO, IDLE} private IncallIconState mCurrentIncallIconState = IncallIconState.IDLE; private synchronized void setIncallIcon(IncallIconState state) { if (state == mCurrentIncallIconState) return; mCurrentIncallIconState = state; if (mIncallNotif == null) mIncallNotif = new Notification(); int notificationTextId = 0; switch (state) { case IDLE: mNM.cancel(INCALL_NOTIF_ID); return; case INCALL: mIncallNotif.icon = R.drawable.conf_unhook; notificationTextId = R.string.incall_notif_active; break; case PAUSE: mIncallNotif.icon = R.drawable.conf_status_paused; notificationTextId = R.string.incall_notif_paused; break; case VIDEO: mIncallNotif.icon = R.drawable.conf_video; notificationTextId = R.string.incall_notif_video; break; default: throw new IllegalArgumentException("Unknown state " + state); } mIncallNotif.iconLevel = 0; mIncallNotif.when=System.currentTimeMillis(); mIncallNotif.flags &= Notification.FLAG_ONGOING_EVENT; mIncallNotif.setLatestEventInfo(this, mNotificationTitle, getString(notificationTextId), mNotifContentIntent); mNM.notify(INCALL_NOTIF_ID, mIncallNotif); } public void refreshIncallIcon(LinphoneCall currentCall) { LinphoneCore lc = LinphoneManager.getLc(); if (currentCall != null) { if (currentCall.getCurrentParamsCopy().getVideoEnabled() && currentCall.cameraEnabled()) { // checking first current params is mandatory setIncallIcon(IncallIconState.VIDEO); } else { setIncallIcon(IncallIconState.INCALL); } } else if (lc.getCallsNb() == 0) { setIncallIcon(IncallIconState.IDLE); } else if (lc.isInConference()) { setIncallIcon(IncallIconState.INCALL); } else { setIncallIcon(IncallIconState.PAUSE); } } private static final Class<?>[] mSetFgSign = new Class[] {boolean.class}; private static final Class<?>[] mStartFgSign = new Class[] { int.class, Notification.class}; private static final Class<?>[] mStopFgSign = new Class[] {boolean.class}; private NotificationManager mNM; private Method mSetForeground; private Method mStartForeground; private Method mStopForeground; private Object[] mSetForegroundArgs = new Object[1]; private Object[] mStartForegroundArgs = new Object[2]; private Object[] mStopForegroundArgs = new Object[1]; void invokeMethod(Method method, Object[] args) { try { method.invoke(this, args); } catch (InvocationTargetException e) { // Should not happen. Log.w(e, "Unable to invoke method"); } catch (IllegalAccessException e) { // Should not happen. Log.w(e, "Unable to invoke method"); } } /** * This is a wrapper around the new startForeground method, using the older * APIs if it is not available. */ void startForegroundCompat(int id, Notification notification) { // If we have the new startForeground API, then use it. if (mStartForeground != null) { mStartForegroundArgs[0] = Integer.valueOf(id); mStartForegroundArgs[1] = notification; invokeMethod(mStartForeground, mStartForegroundArgs); return; } // Fall back on the old API. if (mSetForeground != null) { mSetForegroundArgs[0] = Boolean.TRUE; invokeMethod(mSetForeground, mSetForegroundArgs); // continue } mNM.notify(id, notification); } /** * This is a wrapper around the new stopForeground method, using the older * APIs if it is not available. */ void stopForegroundCompat(int id) { // If we have the new stopForeground API, then use it. if (mStopForeground != null) { mStopForegroundArgs[0] = Boolean.TRUE; invokeMethod(mStopForeground, mStopForegroundArgs); return; } // Fall back on the old API. Note to cancel BEFORE changing the // foreground state, since we could be killed at that point. mNM.cancel(id); if (mSetForeground != null) { mSetForegroundArgs[0] = Boolean.FALSE; invokeMethod(mSetForeground, mSetForegroundArgs); } } public static final String START_LINPHONE_LOGS = " ==== Phone information dump ===="; private void dumpDeviceInformation() { StringBuilder sb = new StringBuilder(); sb.append("DEVICE=").append(Build.DEVICE).append("\n"); sb.append("MODEL=").append(Build.MODEL).append("\n"); //MANUFACTURER doesn't exist in android 1.5. //sb.append("MANUFACTURER=").append(Build.MANUFACTURER).append("\n"); sb.append("SDK=").append(Build.VERSION.SDK); Log.i(sb.toString()); } private void dumpInstalledLinphoneInformation() { PackageInfo info = null; try { info = getPackageManager().getPackageInfo(getPackageName(),0); } catch (NameNotFoundException nnfe) {} if (info != null) { Log.i("Linphone version is ", info.versionCode); } else { Log.i("Linphone version is unknown"); } } private void sendNotification(int level, int textId) { mNotif.iconLevel = level; mNotif.when=System.currentTimeMillis(); String text = getString(textId); if (text.contains("%s")) { LinphoneProxyConfig lpc = LinphoneManager.getLc().getDefaultProxyConfig(); String id = lpc != null ? lpc.getIdentity() : ""; text = String.format(text, id); } mNotif.setLatestEventInfo(this, mNotificationTitle, text, mNotifContentIntent); mNM.notify(NOTIF_ID, mNotif); } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onDestroy() { super.onDestroy(); // Make sure our notification is gone. stopForegroundCompat(NOTIF_ID); mNM.cancel(INCALL_NOTIF_ID); LinphoneManager.getLcIfManagerNotDestroyedOrNull().setPresenceInfo(0, null, OnlineStatus.Offline); LinphoneManager.destroy(); instance=null; } private static final LinphoneGuiListener guiListener() { return DialerActivity.instance(); } public void onDisplayStatus(final String message) { mHandler.post(new Runnable() { public void run() { if (guiListener() != null) guiListener().onDisplayStatus(message); } }); } public void onGlobalStateChanged(final GlobalState state, final String message) { if (state == GlobalState.GlobalOn) { sendNotification(IC_LEVEL_OFFLINE, R.string.notification_started); mHandler.post(new Runnable() { public void run() { if (guiListener() != null) guiListener().onGlobalStateChangedToOn(message); } }); } } public void onRegistrationStateChanged(final RegistrationState state, final String message) { if (state == RegistrationState.RegistrationOk && LinphoneManager.getLc().getDefaultProxyConfig().isRegistered()) { sendNotification(IC_LEVEL_ORANGE, R.string.notification_registered); } if (state == RegistrationState.RegistrationFailed) { sendNotification(IC_LEVEL_OFFLINE, R.string.notification_register_failure); } if (state == RegistrationState.RegistrationOk || state == RegistrationState.RegistrationFailed) { mHandler.post(new Runnable() { public void run() { if (LinphoneActivity.isInstanciated()) LinphoneActivity.instance().onRegistrationStateChanged(state, message); } }); } } public void onCallStateChanged(final LinphoneCall call, final State state, final String message) { if (state == LinphoneCall.State.IncomingReceived) { //wakeup linphone startActivity(new Intent() .setClass(this, LinphoneActivity.class) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } if (state == State.StreamsRunning) { // Workaround bug current call seems to be updated after state changed to streams running refreshIncallIcon(call); } else { refreshIncallIcon(LinphoneManager.getLc().getCurrentCall()); } mHandler.post(new Runnable() { public void run() { if (guiListener() != null) guiListener().onCallStateChanged(call, state, message); } }); } public interface LinphoneGuiListener extends NewOutgoingCallUiListener { void onDisplayStatus(String message); void onGlobalStateChangedToOn(String message); void onCallStateChanged(LinphoneCall call, State state, String message); } public void onRingerPlayerCreated(MediaPlayer mRingerPlayer) { final Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); try { mRingerPlayer.setDataSource(getApplicationContext(), ringtoneUri); } catch (IOException e) { Log.e(e, "cannot set ringtone"); } } public void tryingNewOutgoingCallButAlreadyInCall() { mHandler.post(new Runnable() { public void run() { if (guiListener() != null) guiListener().onAlreadyInCall(); } }); } public void tryingNewOutgoingCallButCannotGetCallParameters() { mHandler.post(new Runnable() { public void run() { if (guiListener() != null) guiListener().onCannotGetCallParameters(); } }); } public void tryingNewOutgoingCallButWrongDestinationAddress() { mHandler.post(new Runnable() { public void run() { if (guiListener() != null) guiListener().onWrongDestinationAddress(); } }); } public void onCallEncryptionChanged(final LinphoneCall call, final boolean encrypted, final String authenticationToken) { // IncallActivity registers itself to this event and handle it. } }
true
true
public void onCreate() { super.onCreate(); // In case restart after a crash. Main in LinphoneActivity LinphonePreferenceManager.getInstance(this); // Set default preferences PreferenceManager.setDefaultValues(this, R.xml.preferences, true); mNotificationTitle = getString(R.string.app_name); // Dump some debugging information to the logs Log.i(START_LINPHONE_LOGS); dumpDeviceInformation(); dumpInstalledLinphoneInformation(); mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); mNotif = new Notification(R.drawable.status_level, "", System.currentTimeMillis()); mNotif.iconLevel=IC_LEVEL_ORANGE; mNotif.flags |= Notification.FLAG_ONGOING_EVENT; Intent notifIntent = new Intent(this, LinphoneActivity.class); mNotifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, 0); mNotif.setLatestEventInfo(this, mNotificationTitle,"", mNotifContentIntent); LinphoneManager.createAndStart(this, this); LinphoneManager.getLc().setPresenceInfo(0, null, OnlineStatus.Online); instance = this; // instance is ready once linphone manager has been created // Retrieve methods to publish notification and keep Android // from killing us and keep the audio quality high. if (Version.sdkStrictlyBelow(Version.API05_ECLAIR_20)) { try { mSetForeground = getClass().getMethod("setForeground", mSetFgSign); } catch (NoSuchMethodException e) { Log.e(e, "Couldn't find foreground method"); } } else { try { mStartForeground = getClass().getMethod("startForeground", mStartFgSign); mStopForeground = getClass().getMethod("stopForeground", mStopFgSign); } catch (NoSuchMethodException e) { Log.e(e, "Couldn't find startGoreground or stopForeground"); } } startForegroundCompat(NOTIF_ID, mNotif); if (!mTestDelayElapsed) { // Only used when testing. Simulates a 5 seconds delay for launching service mHandler.postDelayed(new Runnable() { @Override public void run() { mTestDelayElapsed = true; } }, 5000); } }
public void onCreate() { super.onCreate(); // In case restart after a crash. Main in LinphoneActivity LinphonePreferenceManager.getInstance(this); // Set default preferences PreferenceManager.setDefaultValues(this, R.xml.preferences, true); mNotificationTitle = getString(R.string.app_name); // Dump some debugging information to the logs Log.i(START_LINPHONE_LOGS); dumpDeviceInformation(); dumpInstalledLinphoneInformation(); mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); mNM.cancel(INCALL_NOTIF_ID); // in case of crash the icon is not removed mNotif = new Notification(R.drawable.status_level, "", System.currentTimeMillis()); mNotif.iconLevel=IC_LEVEL_ORANGE; mNotif.flags |= Notification.FLAG_ONGOING_EVENT; Intent notifIntent = new Intent(this, LinphoneActivity.class); mNotifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, 0); mNotif.setLatestEventInfo(this, mNotificationTitle,"", mNotifContentIntent); LinphoneManager.createAndStart(this, this); LinphoneManager.getLc().setPresenceInfo(0, null, OnlineStatus.Online); instance = this; // instance is ready once linphone manager has been created // Retrieve methods to publish notification and keep Android // from killing us and keep the audio quality high. if (Version.sdkStrictlyBelow(Version.API05_ECLAIR_20)) { try { mSetForeground = getClass().getMethod("setForeground", mSetFgSign); } catch (NoSuchMethodException e) { Log.e(e, "Couldn't find foreground method"); } } else { try { mStartForeground = getClass().getMethod("startForeground", mStartFgSign); mStopForeground = getClass().getMethod("stopForeground", mStopFgSign); } catch (NoSuchMethodException e) { Log.e(e, "Couldn't find startGoreground or stopForeground"); } } startForegroundCompat(NOTIF_ID, mNotif); if (!mTestDelayElapsed) { // Only used when testing. Simulates a 5 seconds delay for launching service mHandler.postDelayed(new Runnable() { @Override public void run() { mTestDelayElapsed = true; } }, 5000); } }
diff --git a/orbisgis-core/src/main/java/org/orbisgis/core/ui/configurations/RenderingConfigurationPanel.java b/orbisgis-core/src/main/java/org/orbisgis/core/ui/configurations/RenderingConfigurationPanel.java index d14cc001a..453b927af 100644 --- a/orbisgis-core/src/main/java/org/orbisgis/core/ui/configurations/RenderingConfigurationPanel.java +++ b/orbisgis-core/src/main/java/org/orbisgis/core/ui/configurations/RenderingConfigurationPanel.java @@ -1,138 +1,139 @@ package org.orbisgis.core.ui.configurations; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.Vector; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JPanel; import org.orbisgis.sif.CRFlowLayout; import org.orbisgis.sif.CarriageReturn; public class RenderingConfigurationPanel extends JPanel implements ItemListener { private JCheckBox compositeCheck; private JComboBox compositeCb; private JCheckBox antialiasingCheck; String alpha = "1.0"; private ViewRenderingPanel view; private boolean antialiasing; private boolean composite; private String composite_value; public RenderingConfigurationPanel(boolean antialiasing, boolean composite, String composite_value) { this.antialiasing = antialiasing; this.composite = composite; this.composite_value = composite_value; } public void init() { this.setLayout(new BorderLayout()); this.add(getCheckPanel(), BorderLayout.WEST); this.add(new CarriageReturn()); view = new ViewRenderingPanel(composite_value); this.add(view, BorderLayout.CENTER); } public JPanel getCheckPanel() { CRFlowLayout crf = new CRFlowLayout(); crf.setAlignment(CRFlowLayout.LEFT); JPanel checkJPanel = new JPanel(crf); setAntialiasingCheck(new JCheckBox()); getAntialiasingCheck().setText("Activate antialiasing."); getAntialiasingCheck().setSelected(antialiasing); getAntialiasingCheck().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!getAntialiasingCheck().isSelected()) { getAntialiasingCheck().setSelected(false); } else { getAntialiasingCheck().setEnabled(true); view.changeAntialiasing(true); } } }); Vector<String> items = new Vector<String>(); items.add(RenderingConfiguration.items1); items.add(RenderingConfiguration.items2); items.add(RenderingConfiguration.items3); items.add(RenderingConfiguration.items4); - setCompositeCb(new JComboBox(items)); + compositeCb = new JComboBox(items); + if (composite_value!=null) compositeCb.setSelectedItem(composite_value); getCompositeCb().setEnabled(composite); getCompositeCb().addItemListener(this); setCompositeCheck(new JCheckBox()); getCompositeCheck().setText("Activate source-over alpha combination"); getCompositeCheck().setSelected(composite); getCompositeCheck().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (!getCompositeCheck().isSelected()) { getCompositeCheck().setSelected(false); getCompositeCb().setEnabled(false); } else { getCompositeCb().setEnabled(true); } } }); checkJPanel.add(getAntialiasingCheck()); checkJPanel.add(new CarriageReturn()); checkJPanel.add(getCompositeCheck()); checkJPanel.add(getCompositeCb()); return checkJPanel; } public void itemStateChanged(ItemEvent e) { if (e.getStateChange() != ItemEvent.SELECTED) { return; } Object choice = e.getSource(); if (choice == getCompositeCb()) { alpha = (String) getCompositeCb().getSelectedItem(); view.changeRule(alpha); } else { } } public void setAntialiasingCheck(JCheckBox antialiasingCheck) { this.antialiasingCheck = antialiasingCheck; } public JCheckBox getAntialiasingCheck() { return antialiasingCheck; } public void setCompositeCheck(JCheckBox compositeCheck) { this.compositeCheck = compositeCheck; } public JCheckBox getCompositeCheck() { return compositeCheck; } public void setCompositeCb(JComboBox compositeCb) { this.compositeCb = compositeCb; } public JComboBox getCompositeCb() { return compositeCb; } }
true
true
public JPanel getCheckPanel() { CRFlowLayout crf = new CRFlowLayout(); crf.setAlignment(CRFlowLayout.LEFT); JPanel checkJPanel = new JPanel(crf); setAntialiasingCheck(new JCheckBox()); getAntialiasingCheck().setText("Activate antialiasing."); getAntialiasingCheck().setSelected(antialiasing); getAntialiasingCheck().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!getAntialiasingCheck().isSelected()) { getAntialiasingCheck().setSelected(false); } else { getAntialiasingCheck().setEnabled(true); view.changeAntialiasing(true); } } }); Vector<String> items = new Vector<String>(); items.add(RenderingConfiguration.items1); items.add(RenderingConfiguration.items2); items.add(RenderingConfiguration.items3); items.add(RenderingConfiguration.items4); setCompositeCb(new JComboBox(items)); compositeCb.setSelectedItem(composite_value); getCompositeCb().setEnabled(composite); getCompositeCb().addItemListener(this); setCompositeCheck(new JCheckBox()); getCompositeCheck().setText("Activate source-over alpha combination"); getCompositeCheck().setSelected(composite); getCompositeCheck().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (!getCompositeCheck().isSelected()) { getCompositeCheck().setSelected(false); getCompositeCb().setEnabled(false); } else { getCompositeCb().setEnabled(true); } } }); checkJPanel.add(getAntialiasingCheck()); checkJPanel.add(new CarriageReturn()); checkJPanel.add(getCompositeCheck()); checkJPanel.add(getCompositeCb()); return checkJPanel; }
public JPanel getCheckPanel() { CRFlowLayout crf = new CRFlowLayout(); crf.setAlignment(CRFlowLayout.LEFT); JPanel checkJPanel = new JPanel(crf); setAntialiasingCheck(new JCheckBox()); getAntialiasingCheck().setText("Activate antialiasing."); getAntialiasingCheck().setSelected(antialiasing); getAntialiasingCheck().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!getAntialiasingCheck().isSelected()) { getAntialiasingCheck().setSelected(false); } else { getAntialiasingCheck().setEnabled(true); view.changeAntialiasing(true); } } }); Vector<String> items = new Vector<String>(); items.add(RenderingConfiguration.items1); items.add(RenderingConfiguration.items2); items.add(RenderingConfiguration.items3); items.add(RenderingConfiguration.items4); compositeCb = new JComboBox(items); if (composite_value!=null) compositeCb.setSelectedItem(composite_value); getCompositeCb().setEnabled(composite); getCompositeCb().addItemListener(this); setCompositeCheck(new JCheckBox()); getCompositeCheck().setText("Activate source-over alpha combination"); getCompositeCheck().setSelected(composite); getCompositeCheck().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (!getCompositeCheck().isSelected()) { getCompositeCheck().setSelected(false); getCompositeCb().setEnabled(false); } else { getCompositeCb().setEnabled(true); } } }); checkJPanel.add(getAntialiasingCheck()); checkJPanel.add(new CarriageReturn()); checkJPanel.add(getCompositeCheck()); checkJPanel.add(getCompositeCb()); return checkJPanel; }
diff --git a/BetterBatteryStats/src/com/asksven/betterbatterystats/data/StatsProvider.java b/BetterBatteryStats/src/com/asksven/betterbatterystats/data/StatsProvider.java index a37e25bf..2ec39ae3 100644 --- a/BetterBatteryStats/src/com/asksven/betterbatterystats/data/StatsProvider.java +++ b/BetterBatteryStats/src/com/asksven/betterbatterystats/data/StatsProvider.java @@ -1,3305 +1,3314 @@ /* * Copyright (C) 2011-2012<Re asksven * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asksven.betterbatterystats.data; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import android.Manifest; import android.annotation.SuppressLint; import android.app.ActivityManager; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ReceiverCallNotAllowedException; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PermissionInfo; import android.content.pm.ServiceInfo; import android.os.BatteryManager; import android.os.Build; import android.os.Environment; import android.os.SystemClock; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; import com.asksven.andoid.common.contrib.Util; import com.asksven.android.common.CommonLogSettings; import com.asksven.android.common.kernelutils.AlarmsDumpsys; import com.asksven.android.common.kernelutils.CpuStates; import com.asksven.android.common.kernelutils.NativeKernelWakelock; import com.asksven.android.common.kernelutils.Netstats; import com.asksven.android.common.kernelutils.RootDetection; import com.asksven.android.common.kernelutils.State; import com.asksven.android.common.kernelutils.Wakelocks; import com.asksven.android.common.kernelutils.WakeupSources; import com.asksven.android.common.privateapiproxies.Alarm; import com.asksven.android.common.privateapiproxies.BatteryInfoUnavailableException; import com.asksven.android.common.privateapiproxies.BatteryStatsProxy; import com.asksven.android.common.privateapiproxies.BatteryStatsTypes; import com.asksven.android.common.privateapiproxies.Misc; import com.asksven.android.common.privateapiproxies.NetworkUsage; import com.asksven.android.common.privateapiproxies.Process; import com.asksven.android.common.privateapiproxies.StatElement; import com.asksven.android.common.privateapiproxies.Wakelock; import com.asksven.android.common.utils.DataStorage; import com.asksven.android.common.utils.DateUtils; import com.asksven.android.common.utils.GenericLogger; import com.asksven.android.common.utils.StringUtils; import com.asksven.betterbatterystats.ActiveMonAlarmReceiver; import com.asksven.betterbatterystats.LogSettings; import com.asksven.betterbatterystats.R; /** * Singleton provider for all the statistics * * @author sven * */ public class StatsProvider { /** the singleton instance */ static StatsProvider m_statsProvider = null; /** the application context */ static Context m_context = null; /** constant for custom stats */ // dependent on arrays.xml public final static int STATS_CHARGED = 0; public final static int STATS_UNPLUGGED = 3; public final static int STATS_CUSTOM = 4; public final static int STATS_SCREEN_OFF = 5; public final static int STATS_BOOT = 6; /** the logger tag */ static String TAG = "StatsProvider"; /** * The constructor (hidden) */ private StatsProvider() { } /** * returns a singleton instance * * @param ctx * the application context * @return the singleton StatsProvider */ public static StatsProvider getInstance(Context ctx) { if (m_statsProvider == null) { m_statsProvider = new StatsProvider(); m_context = ctx; } return m_statsProvider; } /** * Get the Stat to be displayed * * @return a List of StatElements sorted (descending) */ public ArrayList<StatElement> getStatList(int iStat, String refFromName, int iSort, String refToName) throws Exception { SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(m_context); boolean bFilterStats = sharedPrefs.getBoolean("filter_data", true); boolean developerMode = sharedPrefs.getBoolean("developer", false); Reference refFrom = ReferenceStore.getReferenceByName(refFromName, m_context); Reference refTo = ReferenceStore.getReferenceByName(refToName, m_context); if ((refFrom == null) || (refTo == null) || (refFromName == null) || (refToName == null) || (refFromName.equals("")) || (refToName.equals(""))) { Log.e(TAG, "Reference from or to are empty: (" + refFromName + ", " + refToName +")"); return null; } if (refFrom.equals(refToName)) { Toast.makeText(m_context, "An error occured. Both stats are identical (" + refFromName + ")", Toast.LENGTH_LONG).show(); } int iPctType = Integer.valueOf(sharedPrefs.getString("default_wl_ref", "0")); if ((!developerMode) && (this.getIsCharging())) { ArrayList<StatElement> myRet = new ArrayList<StatElement>(); myRet.add(new Misc(Reference.NO_STATS_WHEN_CHARGING, 0, 0)); return myRet; } // try // { // constants are related to arrays.xml string-array name="stats" switch (iStat) { case 0: return getOtherUsageStatList(bFilterStats, refFrom, true, false, refTo); case 1: return getNativeKernelWakelockStatList(bFilterStats, refFrom, iPctType, iSort, refTo); case 2: return getWakelockStatList(bFilterStats, refFrom, iPctType, iSort, refTo); case 3: return getAlarmsStatList(bFilterStats, refFrom, refTo); case 4: return getNativeNetworkUsageStatList(bFilterStats, refFrom, refTo); case 5: return getCpuStateList(refFrom, refTo, bFilterStats); case 6: return getProcessStatList(bFilterStats, refFrom, iSort, refTo); } // } // catch (BatteryInfoUnavailableException e) // { // // } // catch (Exception e) // { // Log.e(TAG, "Exception: " + e.getMessage()); // Log.e(TAG, "Callstack: " + e.fillInStackTrace()); // throw new Exception(); // // } return new ArrayList<StatElement>(); } /** * Return the timespan between two references * @param refFrom * @param refTo * @return */ public long getSince(Reference refFrom, Reference refTo) { long ret = 0; if ((refFrom != null) && (refTo != null)) { ret = refTo.m_refBatteryRealtime - refFrom.m_refBatteryRealtime; long since = refTo.m_creationTime - refFrom.m_creationTime; if (LogSettings.DEBUG) { Log.d(TAG, "Since (battery realtime): " + DateUtils.formatDuration(ret)); Log.d(TAG, "Since (creating time, not displayed): " + DateUtils.formatDuration(since)); } } else { ret = -1; } return ret; } // public static Reference getReferenceByName(String refName) // { // if (m_refStore.containsKey(refName)) // { // return m_refStore.get(refName); // } // else // { // Log.e(TAG, "getReference was called with an unknown name " // + refName + ". No reference found"); // return null; // } // } /** * Get the Alarm Stat to be displayed * * @param bFilter * defines if zero-values should be filtered out * @return a List of Other usages sorted by duration (descending) * @throws Exception * if the API call failed */ public ArrayList<StatElement> getAlarmsStatList(boolean bFilter, Reference refFrom, Reference refTo) throws Exception { ArrayList<StatElement> myStats = new ArrayList<StatElement>(); // stop straight away of root features are disabled SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(m_context); boolean rootEnabled = sharedPrefs.getBoolean("root_features", false); if (!rootEnabled) { return myStats; } if ((refFrom == null) || (refTo == null)) { myStats.add(new Misc(Reference.GENERIC_REF_ERR, 1, 1)); return myStats; } ArrayList<StatElement> myAlarms = null; // // get the current value if ((refTo != null) && (refTo.m_refAlarms != null)) { myAlarms = refTo.m_refAlarms; } else { return null; } //Collections.sort(myAlarms); ArrayList<Alarm> myRetAlarms = new ArrayList<Alarm>(); // if we are using custom ref. always retrieve "stats current" // sort @see // com.asksven.android.common.privateapiproxies.Walkelock.compareTo String strCurrent = myAlarms.toString(); String strRef = ""; String strRefDescr = ""; if (LogSettings.DEBUG) { if (refFrom != null) { strRefDescr = refFrom.whoAmI(); if (refFrom.m_refAlarms != null) { strRef = refFrom.m_refAlarms.toString(); } else { strRef = "Alarms is null"; } } else { strRefDescr = "Reference is null"; } Log.d(TAG, "Processing alarms from " + refFrom.m_fileName + " to " + refTo.m_fileName); Log.d(TAG, "Reference used: " + strRefDescr); Log.d(TAG, "It is now " + DateUtils.now()); Log.d(TAG, "Substracting " + strRef); Log.d(TAG, "from " + strCurrent); } for (int i = 0; i < myAlarms.size(); i++) { Alarm alarm = ((Alarm) myAlarms.get(i)).clone(); if ((!bFilter) || ((alarm.getWakeups()) > 0)) { if ((refFrom != null) && (refFrom.m_refAlarms != null)) { alarm.substractFromRef(refFrom.m_refAlarms); // we must recheck if the delta process is still above // threshold if ((!bFilter) || ((alarm.getWakeups()) > 0)) { myRetAlarms.add(alarm); } } else { myRetAlarms.clear(); if (refFrom != null) { myRetAlarms.add(new Alarm(refFrom .getMissingRefError())); } else { myRetAlarms.add(new Alarm( Reference.GENERIC_REF_ERR)); } } } } Collections.sort(myRetAlarms); for (int i = 0; i < myRetAlarms.size(); i++) { myStats.add((StatElement) myRetAlarms.get(i)); } if (LogSettings.DEBUG) { Log.d(TAG, "Result " + myStats.toString()); } return myStats; } public ArrayList<StatElement> getCurrentAlarmsStatList(boolean bFilter) throws Exception { ArrayList<StatElement> myStats = new ArrayList<StatElement>(); // stop straight away of root features are disabled SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(m_context); boolean rootEnabled = sharedPrefs.getBoolean("root_features", false); if (!rootEnabled) { return myStats; } ArrayList<StatElement> myAlarms = null; // get the current value myAlarms = AlarmsDumpsys.getAlarms(); //Collections.sort(myAlarms); ArrayList<Alarm> myRetAlarms = new ArrayList<Alarm>(); // if we are using custom ref. always retrieve "stats current" // sort @see // com.asksven.android.common.privateapiproxies.Walkelock.compareTo for (int i = 0; i < myAlarms.size(); i++) { Alarm alarm = (Alarm) myAlarms.get(i); if ((!bFilter) || ((alarm.getWakeups()) > 0)) { myRetAlarms.add(alarm); } } Collections.sort(myRetAlarms); for (int i = 0; i < myRetAlarms.size(); i++) { myStats.add((StatElement) myRetAlarms.get(i)); } if (LogSettings.DEBUG) { Log.d(TAG, "Result " + myStats.toString()); } return myStats; } /** * Get the Process Stat to be displayed * * @param bFilter * defines if zero-values should be filtered out * @return a List of Wakelocks sorted by duration (descending) * @throws Exception * if the API call failed */ public ArrayList<StatElement> getProcessStatList(boolean bFilter, Reference refFrom, int iSort, Reference refTo) throws Exception { ArrayList<StatElement> myStats = new ArrayList<StatElement>(); if ((refFrom == null) || (refTo == null)) { myStats.add(new Misc(Reference.GENERIC_REF_ERR, 1, 1)); return myStats; } ArrayList<StatElement> myProcesses = null; ArrayList<Process> myRetProcesses = new ArrayList<Process>(); if ((refTo != null) && (refTo.m_refProcesses != null)) { myProcesses = refTo.m_refProcesses; } else { return null; } String strCurrent = myProcesses.toString(); String strRef = ""; String strRefDescr = ""; if (LogSettings.DEBUG) { if (refFrom != null) { strRefDescr = refFrom.whoAmI(); if (refFrom.m_refProcesses != null) { strRef = refFrom.m_refProcesses.toString(); } else { strRef = "Process is null"; } } else { strRefDescr = "Reference is null"; } Log.d(TAG, "Processing processes from " + refFrom.m_fileName + " to " + refTo.m_fileName); Log.d(TAG, "Reference used: " + strRefDescr); Log.d(TAG, "It is now " + DateUtils.now()); Log.d(TAG, "Substracting " + strRef); Log.d(TAG, "from " + strCurrent); } for (int i = 0; i < myProcesses.size(); i++) { Process ps = ((Process) myProcesses.get(i)).clone(); if ((!bFilter) || ((ps.getSystemTime() + ps.getUserTime()) > 0)) { // we must distinguish two situations // a) we use custom stat type // b) we use regular stat type if ((refFrom != null) && (refFrom.m_refProcesses != null)) { ps.substractFromRef(refFrom.m_refProcesses); // we must recheck if the delta process is still above // threshold if ((!bFilter) || ((ps.getSystemTime() + ps.getUserTime()) > 0)) { myRetProcesses.add(ps); } } else { myRetProcesses.clear(); if (refFrom != null) { myRetProcesses.add(new Process(refFrom .getMissingRefError(), 1, 1, 1)); } else { myRetProcesses.add(new Process( Reference.GENERIC_REF_ERR, 1, 1, 1)); } } } } // sort @see // com.asksven.android.common.privateapiproxies.Walkelock.compareTo switch (iSort) { case 0: // by Duration Comparator<Process> myCompTime = new Process.ProcessTimeComparator(); Collections.sort(myRetProcesses, myCompTime); break; case 1: // by Count Comparator<Process> myCompCount = new Process.ProcessCountComparator(); Collections.sort(myRetProcesses, myCompCount); break; } for (int i = 0; i < myRetProcesses.size(); i++) { myStats.add((StatElement) myRetProcesses.get(i)); } if (LogSettings.DEBUG) { Log.d(TAG, "Result " + myStats.toString()); } return myStats; } public ArrayList<StatElement> getCurrentProcessStatList(boolean bFilter, int iSort) throws Exception { BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(m_context); ArrayList<StatElement> myStats = new ArrayList<StatElement>(); ArrayList<StatElement> myProcesses = null; ArrayList<Process> myRetProcesses = new ArrayList<Process>(); myProcesses = mStats.getProcessStats(m_context, BatteryStatsTypes.STATS_CURRENT); for (int i = 0; i < myProcesses.size(); i++) { Process ps = (Process) myProcesses.get(i); if ((!bFilter) || ((ps.getSystemTime() + ps.getUserTime()) > 0)) { myRetProcesses.add(ps); } } // sort @see // com.asksven.android.common.privateapiproxies.Walkelock.compareTo switch (iSort) { case 0: // by Duration Comparator<Process> myCompTime = new Process.ProcessTimeComparator(); Collections.sort(myRetProcesses, myCompTime); break; case 1: // by Count Comparator<Process> myCompCount = new Process.ProcessCountComparator(); Collections.sort(myRetProcesses, myCompCount); break; } for (int i = 0; i < myRetProcesses.size(); i++) { myStats.add((StatElement) myRetProcesses.get(i)); } if (LogSettings.DEBUG) { Log.d(TAG, "Result " + myStats.toString()); } return myStats; } /** * Get the Wakelock Stat to be displayed * * @param bFilter * defines if zero-values should be filtered out * @return a List of Wakelocks sorted by duration (descending) * @throws Exception * if the API call failed */ public ArrayList<StatElement> getWakelockStatList(boolean bFilter, Reference refFrom, int iPctType, int iSort, Reference refTo) throws Exception { ArrayList<StatElement> myStats = new ArrayList<StatElement>(); if ((refFrom == null) || (refTo == null)) { myStats.add(new Misc(Reference.GENERIC_REF_ERR, 1, 1)); return myStats; } ArrayList<StatElement> myWakelocks = null; if ((refTo != null) && (refTo.m_refWakelocks != null)) { myWakelocks = refTo.m_refWakelocks; } else { return null; } ArrayList<Wakelock> myRetWakelocks = new ArrayList<Wakelock>(); String strCurrent = myWakelocks.toString(); String strRef = ""; String strRefDescr = ""; if (LogSettings.DEBUG) { if (refFrom != null) { strRefDescr = refFrom.whoAmI(); if (refFrom.m_refWakelocks != null) { strRef = refFrom.m_refWakelocks.toString(); } else { strRef = "Wakelocks is null"; } } else { strRefDescr = "Reference is null"; } Log.d(TAG, "Processing wakelocks since " + refFrom.m_fileName); Log.d(TAG, "Reference used: " + strRefDescr); Log.d(TAG, "It is now " + DateUtils.now()); Log.d(TAG, "Substracting " + strRef); Log.d(TAG, "from " + strCurrent); } // sort @see // com.asksven.android.common.privateapiproxies.Walkelock.compareTo // Collections.sort(myWakelocks); for (int i = 0; i < myWakelocks.size(); i++) { Wakelock wl = ((Wakelock) myWakelocks.get(i)).clone(); if ((!bFilter) || ((wl.getDuration() / 1000) > 0)) { // we must distinguish two situations // a) we use custom stat type // b) we use regular stat type if ((refFrom != null) && (refFrom.m_refWakelocks != null)) { wl.substractFromRef(refFrom.m_refWakelocks); // we must recheck if the delta process is still above // threshold if ((!bFilter) || ((wl.getDuration() / 1000) > 0)) { // if (LogSettings.DEBUG) // { // Log.i(TAG, "Adding " + wl.toString()); // } myRetWakelocks.add(wl); } else { if (LogSettings.DEBUG) { Log.i(TAG, "Skipped " + wl.toString() + " because duration < 1s"); } } } else { myRetWakelocks.clear(); if (refFrom != null) { myRetWakelocks.add(new Wakelock(1, refFrom .getMissingRefError(), 1, 1, 1)); } else { myRetWakelocks.add(new Wakelock(1, Reference.GENERIC_REF_ERR, 1, 1, 1)); } } } } if (LogSettings.DEBUG) { Log.i(TAG, "Result has " + myRetWakelocks.size() + " entries"); } // sort @see // com.asksven.android.common.privateapiproxies.Walkelock.compareTo switch (iSort) { case 0: // by Duration Comparator<Wakelock> myCompTime = new Wakelock.WakelockTimeComparator(); Collections.sort(myRetWakelocks, myCompTime); break; case 1: // by Count Comparator<Wakelock> myCompCount = new Wakelock.WakelockCountComparator(); Collections.sort(myRetWakelocks, myCompCount); break; } for (int i = 0; i < myRetWakelocks.size(); i++) { myStats.add((StatElement) myRetWakelocks.get(i)); } if (LogSettings.DEBUG) { Log.d(TAG, "Result " + myStats.toString()); } return myStats; } public ArrayList<StatElement> getCurrentWakelockStatList(boolean bFilter, int iPctType, int iSort) throws Exception { ArrayList<StatElement> myStats = new ArrayList<StatElement>(); BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(m_context); ArrayList<StatElement> myWakelocks = null; myWakelocks = mStats.getWakelockStats(m_context, BatteryStatsTypes.WAKE_TYPE_PARTIAL, BatteryStatsTypes.STATS_CURRENT, iPctType); ArrayList<Wakelock> myRetWakelocks = new ArrayList<Wakelock>(); // sort @see // com.asksven.android.common.privateapiproxies.Walkelock.compareTo // Collections.sort(myWakelocks); for (int i = 0; i < myWakelocks.size(); i++) { Wakelock wl = (Wakelock) myWakelocks.get(i); if ((!bFilter) || ((wl.getDuration() / 1000) > 0)) { myRetWakelocks.add(wl); } } if (LogSettings.DEBUG) { Log.i(TAG, "Result has " + myRetWakelocks.size() + " entries"); } // sort @see // com.asksven.android.common.privateapiproxies.Walkelock.compareTo switch (iSort) { case 0: // by Duration Comparator<Wakelock> myCompTime = new Wakelock.WakelockTimeComparator(); Collections.sort(myRetWakelocks, myCompTime); break; case 1: // by Count Comparator<Wakelock> myCompCount = new Wakelock.WakelockCountComparator(); Collections.sort(myRetWakelocks, myCompCount); break; } for (int i = 0; i < myRetWakelocks.size(); i++) { myStats.add((StatElement) myRetWakelocks.get(i)); } if (LogSettings.DEBUG) { Log.d(TAG, "Result " + myStats.toString()); } return myStats; } /** * Get the Kernel Wakelock Stat to be displayed * * @param bFilter * defines if zero-values should be filtered out * @return a List of Wakelocks sorted by duration (descending) * @throws Exception * if the API call failed */ public ArrayList<StatElement> getNativeKernelWakelockStatList( boolean bFilter, Reference refFrom, int iPctType, int iSort, Reference refTo) throws Exception { ArrayList<StatElement> myStats = new ArrayList<StatElement>(); if ((refFrom == null) || (refTo == null)) { myStats.add(new Misc(Reference.GENERIC_REF_ERR, 1, 1)); return myStats; } ArrayList<StatElement> myKernelWakelocks = null; if ((refTo != null) && (refTo.m_refKernelWakelocks != null)) { myKernelWakelocks = refTo.m_refKernelWakelocks; } else { return null; } ArrayList<NativeKernelWakelock> myRetKernelWakelocks = new ArrayList<NativeKernelWakelock>(); // if we are using custom ref. always retrieve "stats current" // sort @see // com.asksven.android.common.privateapiproxies.Walkelock.compareTo // Collections.sort(myKernelWakelocks); String strCurrent = myKernelWakelocks.toString(); String strRef = ""; String strRefDescr = ""; if (LogSettings.DEBUG) { if (refFrom != null) { strRefDescr = refFrom.whoAmI(); if (refFrom.m_refKernelWakelocks != null) { strRef = refFrom.m_refKernelWakelocks.toString(); } else { strRef = "kernel wakelocks is null"; } } else { strRefDescr = "Reference is null"; } Log.d(TAG, "Processing kernel wakelocks from " + refFrom.m_fileName + " to " + refTo.m_fileName); Log.d(TAG, "Reference used: " + strRefDescr); Log.d(TAG, "It is now " + DateUtils.now()); Log.d(TAG, "Substracting " + strRef); Log.d(TAG, "from " + strCurrent); } for (int i = 0; i < myKernelWakelocks.size(); i++) { NativeKernelWakelock wl = ((NativeKernelWakelock) myKernelWakelocks.get(i)).clone(); if ((!bFilter) || ((wl.getDuration()) > 0)) { if ((refFrom != null) && (refFrom.m_refKernelWakelocks != null)) { wl.substractFromRef(refFrom.m_refKernelWakelocks); // we must recheck if the delta process is still above // threshold if ((!bFilter) || ((wl.getDuration()) > 0)) { myRetKernelWakelocks.add(wl); } } else { myRetKernelWakelocks.clear(); if (refFrom != null) { myRetKernelWakelocks.add(new NativeKernelWakelock( refFrom.getMissingRefError(), "", 1, 1, 1, 1, 1, 1, 1, 1, 1)); } else { myRetKernelWakelocks.add(new NativeKernelWakelock( Reference.GENERIC_REF_ERR, "", 1, 1, 1, 1, 1, 1, 1, 1, 1)); } } } } // sort @see // com.asksven.android.common.privateapiproxies.Walkelock.compareTo switch (iSort) { case 0: // by Duration Comparator<NativeKernelWakelock> myCompTime = new NativeKernelWakelock.TimeComparator(); Collections.sort(myRetKernelWakelocks, myCompTime); break; case 1: // by Count Comparator<NativeKernelWakelock> myCompCount = new NativeKernelWakelock.CountComparator(); Collections.sort(myRetKernelWakelocks, myCompCount); break; } for (int i = 0; i < myRetKernelWakelocks.size(); i++) { myStats.add((StatElement) myRetKernelWakelocks.get(i)); } if (LogSettings.DEBUG) { Log.d(TAG, "Result " + myStats.toString()); } return myStats; } public ArrayList<StatElement> getCurrentNativeKernelWakelockStatList(boolean bFilter, int iPctType, int iSort) throws Exception { ArrayList<StatElement> myStats = new ArrayList<StatElement>(); ArrayList<StatElement> myKernelWakelocks = null; // we must support both "old" (/proc/wakelocks) and "new formats if (Wakelocks.fileExists()) { myKernelWakelocks = Wakelocks.parseProcWakelocks(m_context); } else { myKernelWakelocks = WakeupSources.parseWakeupSources(m_context); } ArrayList<NativeKernelWakelock> myRetKernelWakelocks = new ArrayList<NativeKernelWakelock>(); // if we are using custom ref. always retrieve "stats current" // sort @see // com.asksven.android.common.privateapiproxies.Walkelock.compareTo // Collections.sort(myKernelWakelocks); for (int i = 0; i < myKernelWakelocks.size(); i++) { NativeKernelWakelock wl = (NativeKernelWakelock) myKernelWakelocks.get(i); if ((!bFilter) || ((wl.getDuration()) > 0)) { myRetKernelWakelocks.add(wl); } } // sort @see // com.asksven.android.common.privateapiproxies.Walkelock.compareTo switch (iSort) { case 0: // by Duration Comparator<NativeKernelWakelock> myCompTime = new NativeKernelWakelock.TimeComparator(); Collections.sort(myRetKernelWakelocks, myCompTime); break; case 1: // by Count Comparator<NativeKernelWakelock> myCompCount = new NativeKernelWakelock.CountComparator(); Collections.sort(myRetKernelWakelocks, myCompCount); break; } for (int i = 0; i < myRetKernelWakelocks.size(); i++) { myStats.add((StatElement) myRetKernelWakelocks.get(i)); } if (LogSettings.DEBUG) { Log.d(TAG, "Result " + myStats.toString()); } return myStats; } /** * Get the Kernel Wakelock Stat to be displayed * * @param bFilter * defines if zero-values should be filtered out * @return a List of Wakelocks sorted by duration (descending) * @throws Exception * if the API call failed */ public ArrayList<StatElement> getNativeNetworkUsageStatList( boolean bFilter, Reference refFrom, Reference refTo) throws Exception { ArrayList<StatElement> myStats = new ArrayList<StatElement>(); if ((refFrom == null) || (refTo == null)) { myStats.add(new Misc(Reference.GENERIC_REF_ERR, 1, 1)); return myStats; } // stop straight away of root features are disabled SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(m_context); boolean rootEnabled = sharedPrefs.getBoolean("root_features", false); if (!rootEnabled) { return myStats; } ArrayList<StatElement> myNetworkStats = null; if ((refTo != null) && (refTo.m_refNetworkStats != null)) { myNetworkStats = refTo.m_refNetworkStats; } else { myNetworkStats = Netstats.parseNetstats(); } ArrayList<NetworkUsage> myRetNetworkStats = new ArrayList<NetworkUsage>(); // if we are using custom ref. always retrieve "stats current" // sort @see // com.asksven.android.common.privateapiproxies.Walkelock.compareTo // Collections.sort(myNetworkStats); String strCurrent = ""; String strRef = ""; String strRefDescr = ""; if (LogSettings.DEBUG) { if (refFrom != null) { strRefDescr = refFrom.whoAmI(); if (refFrom.m_refNetworkStats != null) { strRef = refFrom.m_refNetworkStats.toString(); } else { strRef = "Network stats is null"; } } else { strRefDescr = "Reference is null"; } Log.d(TAG, "Processing network stats from " + refFrom.m_fileName + " to " + refTo.m_fileName); Log.d(TAG, "Reference used: " + strRefDescr); Log.d(TAG, "It is now " + DateUtils.now()); Log.d(TAG, "Substracting " + strRef); Log.d(TAG, "from " + strCurrent); } for (int i = 0; i < myNetworkStats.size(); i++) { NetworkUsage netStat = ((NetworkUsage) myNetworkStats.get(i)).clone(); if ((!bFilter) || ((netStat.getTotalBytes()) > 0)) { if ((refFrom != null) && (refFrom.m_refNetworkStats != null)) { netStat.substractFromRef(refFrom.m_refNetworkStats); // we must recheck if the delta process is still above // threshold if ((!bFilter) || ((netStat.getTotalBytes()) > 0)) { myRetNetworkStats.add(netStat); } } else { myRetNetworkStats.clear(); if (refFrom != null) { myRetNetworkStats.add(new NetworkUsage(refFrom .getMissingRefError(), -1, 1, 0)); } else { myRetNetworkStats.add(new NetworkUsage( Reference.GENERIC_REF_ERR, -1, 1, 0)); } } } } // recalculate the total long total = 0; for (int i = 0; i < myRetNetworkStats.size(); i++) { total += myRetNetworkStats.get(i).getTotalBytes(); } Collections.sort(myRetNetworkStats); for (int i = 0; i < myRetNetworkStats.size(); i++) { myRetNetworkStats.get(i).setTotal(total); myStats.add((StatElement) myRetNetworkStats.get(i)); } if (LogSettings.DEBUG) { Log.d(TAG, "Result " + myStats.toString()); } return myStats; } public ArrayList<StatElement> getCurrentNativeNetworkUsageStatList(boolean bFilter) throws Exception { ArrayList<StatElement> myStats = new ArrayList<StatElement>(); // stop straight away of root features are disabled SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(m_context); boolean rootEnabled = sharedPrefs.getBoolean("root_features", false); if (!rootEnabled) { return myStats; } ArrayList<StatElement> myNetworkStats = null; myNetworkStats = Netstats.parseNetstats(); ArrayList<NetworkUsage> myRetNetworkStats = new ArrayList<NetworkUsage>(); // if we are using custom ref. always retrieve "stats current" // sort @see // com.asksven.android.common.privateapiproxies.Walkelock.compareTo // Collections.sort(myNetworkStats); for (int i = 0; i < myNetworkStats.size(); i++) { NetworkUsage netStat = (NetworkUsage) myNetworkStats.get(i); if ((!bFilter) || ((netStat.getTotalBytes()) > 0)) { myRetNetworkStats.add(netStat); } } // recalculate the total long total = 0; for (int i = 0; i < myRetNetworkStats.size(); i++) { total += myRetNetworkStats.get(i).getTotalBytes(); } Collections.sort(myRetNetworkStats); for (int i = 0; i < myRetNetworkStats.size(); i++) { myRetNetworkStats.get(i).setTotal(total); myStats.add((StatElement) myRetNetworkStats.get(i)); } if (LogSettings.DEBUG) { Log.d(TAG, "Result " + myStats.toString()); } return myStats; } /** * Get the CPU states to be displayed * * @param bFilter * defines if zero-values should be filtered out * @return a List of Other usages sorted by duration (descending) * @throws Exception * if the API call failed */ public ArrayList<StatElement> getCpuStateList(Reference refFrom, Reference refTo, boolean bFilter) throws Exception { // List to store the other usages to ArrayList<StatElement> myStates = refTo.m_refCpuStates; ArrayList<StatElement> myStats = new ArrayList<StatElement>(); if ((refFrom == null) || (refTo == null)) { myStats.add(new Misc(Reference.GENERIC_REF_ERR, 1, 1)); return myStats; } if (myStates == null) { return myStats; } String strCurrent = myStates.toString(); String strRef = ""; String strRefDescr = ""; if (LogSettings.DEBUG) { if (refFrom != null) { strRefDescr = refFrom.whoAmI(); if (refFrom.m_refCpuStates != null) { strRef = refFrom.m_refCpuStates.toString(); } else { strRef = "CPU States is null"; } } Log.d(TAG, "Processing CPU States from " + refFrom.m_fileName + " to " + refTo.m_fileName); Log.d(TAG, "Reference used: " + strRefDescr); Log.d(TAG, "It is now " + DateUtils.now()); Log.d(TAG, "Substracting " + strRef); Log.d(TAG, "from " + strCurrent); } for (int i = 0; i < myStates.size(); i++) { State state = ((State) myStates.get(i)).clone(); if ((refFrom != null) && (refFrom.m_refCpuStates != null)) { state.substractFromRef(refFrom.m_refCpuStates); if ((!bFilter) || ((state.m_duration) > 0)) { myStats.add(state); } } else { myStats.clear(); myStats.add(new State(1, 1)); } } return myStats; } public ArrayList<StatElement> getCurrentCpuStateList(boolean bFilter) throws Exception { // List to store the other usages to ArrayList<State> myStates = CpuStates.getTimesInStates(); ArrayList<StatElement> myStats = new ArrayList<StatElement>(); if (myStates == null) { return myStats; } String strCurrent = myStates.toString(); String strRef = ""; String strRefDescr = ""; for (int i = 0; i < myStates.size(); i++) { State state = myStates.get(i); if ((!bFilter) || ((state.m_duration) > 0)) { myStats.add(state); } } return myStats; } /** * Get the permissions * * @return a List of permissions */ public Map<String, Permission> getPermissionMap(Context context) { Map<String, Permission> myStats = new Hashtable<String, Permission>(); Class<Manifest.permission> perms = Manifest.permission.class; Field[] fields = perms.getFields(); int size = fields.length; PackageManager pm = context.getPackageManager(); for (int i = 0; i < size; i++) { try { Field field = fields[i]; PermissionInfo info = pm.getPermissionInfo( field.get(field.getName()).toString(), PackageManager.GET_PERMISSIONS); Permission perm = new Permission(); perm.name = info.name; final CharSequence chars = info.loadDescription(context .getPackageManager()); perm.description = chars == null ? "no description" : chars .toString(); perm.level = info.protectionLevel; myStats.put(perm.name, perm); } catch (Exception e) { Log.e(TAG, e.getMessage()); } } return myStats; } /** * Returns the permissions <uses-permissions> requested by a package in its manifest * @param context * @param packageName * @return the list of permissions */ public ArrayList<String> getRequestedPermissionListForPackage(Context context, String packageName) { ArrayList<String> myStats = new ArrayList<String>(); try { PackageInfo pkgInfo = context.getPackageManager().getPackageInfo( packageName, PackageManager.GET_PERMISSIONS ); String[] requestedPermissions = pkgInfo.requestedPermissions; if (requestedPermissions == null) { myStats.add("No requested permissions"); } else { for (int i = 0; i < requestedPermissions.length; i++) { myStats.add(requestedPermissions[i]); } } } catch (Exception e) { Log.e(TAG, e.getMessage()); } return myStats; } /** * Returns the permissions <uses-permissions> requested by a package in its manifest * @param context * @param packageName * @return the list of permissions */ public ArrayList<String> getReceiverListForPackage(Context context, String packageName) { ArrayList<String> myStats = new ArrayList<String>(); try { PackageInfo pkgInfo = context.getPackageManager().getPackageInfo( packageName, PackageManager.GET_RECEIVERS ); ActivityInfo[] receivers = pkgInfo.receivers; if (receivers == null) { myStats.add("No receivers"); } else { for (int i = 0; i < receivers.length; i++) { myStats.add(receivers[i].name); } } } catch (Exception e) { Log.e(TAG, e.getMessage()); } return myStats; } /** * Returns the services <service> defined by a package in its manifest * @param context * @param packageName * @return the list of services */ public ArrayList<String> getServiceListForPackage(Context context, String packageName) { ArrayList<String> myStats = new ArrayList<String>(); try { PackageInfo pkgInfo = context.getPackageManager().getPackageInfo( packageName, PackageManager.GET_SERVICES ); ServiceInfo[] services = pkgInfo.services; if (services == null) { myStats.add("None"); } else { for (int i = 0; i < services.length; i++) { myStats.add(services[i].name); } } } catch (Exception e) { Log.e(TAG, e.getMessage()); } return myStats; } /** * Get the Other Usage Stat to be displayed * * @param bFilter * defines if zero-values should be filtered out * @return a List of Other usages sorted by duration (descending) * @throws Exception * if the API call failed */ public ArrayList<StatElement> getOtherUsageStatList(boolean bFilter, Reference refFrom, boolean bFilterView, boolean bWidget, Reference refTo) throws Exception { ArrayList<StatElement> myStats = new ArrayList<StatElement>(); // if on of the refs is null return if ((refFrom == null) || (refTo == null)) { myStats.add(new Misc(Reference.GENERIC_REF_ERR, 1, 1)); return myStats; } // List to store the other usages to ArrayList<StatElement> myUsages = new ArrayList<StatElement>(); if ((refTo != null) && (refTo.m_refOther != null)) { myUsages = refTo.m_refOther; } else { return null; } String strRefFrom = ""; String strRefTo = ""; String strRefFromDescr = ""; String strRefToDescr = ""; if (LogSettings.DEBUG) { if (refFrom != null) { strRefFromDescr = refFrom.whoAmI(); if (refFrom.m_refOther != null) { strRefFrom = refFrom.m_refOther.toString(); } else { strRefFrom = "Other is null"; } } if (refTo != null) { strRefToDescr = refTo.whoAmI(); if (refTo.m_refOther != null) { strRefTo = refTo.m_refOther.toString(); } else { strRefTo = "Other is null"; } } Log.d(TAG, "Processing Other from " + refFrom.m_fileName + " to " + refTo.m_fileName); Log.d(TAG, "Reference from: " + strRefFromDescr); Log.d(TAG, "Reference to: " + strRefToDescr); Log.d(TAG, "It is now " + DateUtils.now()); Log.d(TAG, "Substracting " + strRefFrom); Log.d(TAG, "from " + strRefTo); } for (int i = 0; i < myUsages.size(); i++) { Misc usage = ((Misc)myUsages.get(i)).clone(); if (LogSettings.DEBUG) { Log.d(TAG, "Current value: " + usage.getName() + " " + usage.getData()); } if ((!bFilter) || (usage.getTimeOn() > 0)) { if ((refFrom != null) && (refFrom.m_refOther != null)) { usage.substractFromRef(refFrom.m_refOther); if ((!bFilter) || (usage.getTimeOn() > 0)) { if (LogSettings.DEBUG) { Log.d(TAG, "Result value: " + usage.getName() + " " + usage.getData()); } myStats.add((StatElement) usage); } } else { myStats.clear(); if (refFrom != null) { myStats.add(new Misc(refFrom.getMissingRefError(), 1, 1)); } else { myStats.add(new Misc(Reference.GENERIC_REF_ERR, 1, 1)); } } } } return myStats; } public ArrayList<StatElement> getCurrentOtherUsageStatList(boolean bFilter, boolean bFilterView, boolean bWidget) throws Exception { BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(m_context); SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(m_context); ArrayList<StatElement> myStats = new ArrayList<StatElement>(); // List to store the other usages to ArrayList<StatElement> myUsages = new ArrayList<StatElement>(); long rawRealtime = SystemClock.elapsedRealtime() * 1000; - long batteryRealtime = mStats.getBatteryRealtime(rawRealtime); + long batteryRealtime = 0; + try + { + batteryRealtime = mStats.getBatteryRealtime(rawRealtime); + } + catch (Exception e) + { + Log.e(TAG, "An exception occured processing battery realtime. Message: " + e.getMessage()); + Log.e(TAG, "Exception: " + Log.getStackTraceString(e)); + } long whichRealtime = mStats.computeBatteryRealtime(rawRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; long timeBatteryUp = mStats.computeBatteryUptime( SystemClock.uptimeMillis() * 1000, BatteryStatsTypes.STATS_CURRENT) / 1000; if (CommonLogSettings.DEBUG) { Log.i(TAG, "whichRealtime = " + whichRealtime + " batteryRealtime = " + batteryRealtime + " timeBatteryUp=" + timeBatteryUp); } long timeScreenOn = mStats.getScreenOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; long timePhoneOn = mStats.getPhoneOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; long timeWifiOn = 0; long timeWifiRunning = 0; if (sharedPrefs.getBoolean("show_other_wifi", true) && !bWidget) { try { timeWifiOn = mStats.getWifiOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeWifiRunning = mStats.getGlobalWifiRunningTime( batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; // long timeWifiMulticast = // mStats.getWifiMulticastTime(m_context, batteryRealtime, // BatteryStatsTypes.STATS_CURRENT) / 1000; // long timeWifiLocked = mStats.getFullWifiLockTime(m_context, // batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; // long timeWifiScan = mStats.getScanWifiLockTime(m_context, // batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; } catch (BatteryInfoUnavailableException e) { timeWifiOn = 0; timeWifiRunning = 0; Log.e(TAG, "A batteryinfo error occured while retrieving Wifi data"); } } // long timeAudioOn = mStats.getAudioTurnedOnTime(m_context, // batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; // long timeVideoOn = mStats.getVideoTurnedOnTime(m_context, // batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; long timeBluetoothOn = 0; if (sharedPrefs.getBoolean("show_other_bt", true) && !bWidget) { try { timeBluetoothOn = mStats.getBluetoothOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; } catch (BatteryInfoUnavailableException e) { timeBluetoothOn = 0; Log.e(TAG, "A batteryinfo error occured while retrieving BT data"); } } long timeNoDataConnection = 0; long timeSignalNone = 0; long timeSignalPoor = 0; long timeSignalModerate = 0; long timeSignalGood = 0; long timeSignalGreat = 0; if (sharedPrefs.getBoolean("show_other_signal", true)) { try { timeNoDataConnection = mStats.getPhoneDataConnectionTime( BatteryStatsTypes.DATA_CONNECTION_NONE, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeSignalNone = mStats.getPhoneSignalStrengthTime( BatteryStatsTypes.SIGNAL_STRENGTH_NONE_OR_UNKNOWN, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeSignalPoor = mStats.getPhoneSignalStrengthTime( BatteryStatsTypes.SIGNAL_STRENGTH_POOR, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeSignalModerate = mStats.getPhoneSignalStrengthTime( BatteryStatsTypes.SIGNAL_STRENGTH_MODERATE, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeSignalGood = mStats.getPhoneSignalStrengthTime( BatteryStatsTypes.SIGNAL_STRENGTH_GOOD, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeSignalGreat = mStats.getPhoneSignalStrengthTime( BatteryStatsTypes.SIGNAL_STRENGTH_GREAT, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; } catch (BatteryInfoUnavailableException e) { timeNoDataConnection = 0; timeSignalNone = 0; timeSignalPoor = 0; timeSignalModerate = 0; timeSignalGood = 0; timeSignalGreat = 0; Log.e(TAG, "A batteryinfo error occured while retrieving Signal data"); } } long timeScreenDark = 0; long timeScreenDim = 0; long timeScreenMedium = 0; long timeScreenLight = 0; long timeScreenBright = 0; if (sharedPrefs.getBoolean("show_other_screen_brightness", true)) { try { timeScreenDark = mStats.getScreenBrightnessTime( BatteryStatsTypes.SCREEN_BRIGHTNESS_DARK, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeScreenDim = mStats.getScreenBrightnessTime( BatteryStatsTypes.SCREEN_BRIGHTNESS_DIM, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeScreenMedium = mStats.getScreenBrightnessTime( BatteryStatsTypes.SCREEN_BRIGHTNESS_MEDIUM, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeScreenLight = mStats.getScreenBrightnessTime( BatteryStatsTypes.SCREEN_BRIGHTNESS_LIGHT, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeScreenBright = mStats.getScreenBrightnessTime( BatteryStatsTypes.SCREEN_BRIGHTNESS_BRIGHT, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; } catch (BatteryInfoUnavailableException e) { timeScreenDark = 0; timeScreenDim = 0; timeScreenMedium = 0; timeScreenLight = 0; timeScreenBright = 0; Log.e(TAG, "A batteryinfo error occured while retrieving Screen brightness data"); } } // deep sleep times are independent of stat type long timeDeepSleep = (SystemClock.elapsedRealtime() - SystemClock .uptimeMillis()); // long whichRealtime = SystemClock.elapsedRealtime(); // long timeElapsed = mStats.computeBatteryRealtime(rawRealtime, // BatteryStatsTypes.STATS_CURRENT) / 1000; // SystemClock.elapsedRealtime(); Misc deepSleepUsage = new Misc("Deep Sleep", timeDeepSleep, whichRealtime); Log.d(TAG, "Added Deep sleep:" + deepSleepUsage.getData()); if ((!bFilter) || (deepSleepUsage.getTimeOn() > 0)) { myUsages.add(deepSleepUsage); } if (timeBatteryUp > 0) { myUsages.add(new Misc("Awake", timeBatteryUp, whichRealtime)); } if (timeScreenOn > 0) { myUsages.add(new Misc("Screen On", timeScreenOn, whichRealtime)); } if (timePhoneOn > 0) { myUsages.add(new Misc("Phone On", timePhoneOn, whichRealtime)); } if ((timeWifiOn > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_wifi", true))) { myUsages.add(new Misc("Wifi On", timeWifiOn, whichRealtime)); } if ((timeWifiRunning > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_wifi", true))) { myUsages.add(new Misc("Wifi Running", timeWifiRunning, whichRealtime)); } if ((timeBluetoothOn > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_bt", true))) { myUsages.add(new Misc("Bluetooth On", timeBluetoothOn, whichRealtime)); } if ((timeNoDataConnection > 0) && (!bFilterView || sharedPrefs.getBoolean( "show_other_connection", true))) { myUsages.add(new Misc("No Data Connection", timeNoDataConnection, whichRealtime)); } if ((timeSignalNone > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_signal", true))) { myUsages.add(new Misc("No or Unknown Signal", timeSignalNone, whichRealtime)); } if ((timeSignalPoor > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_signal", true))) { myUsages.add(new Misc("Poor Signal", timeSignalPoor, whichRealtime)); } if ((timeSignalModerate > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_signal", true))) { myUsages.add(new Misc("Moderate Signal", timeSignalModerate, whichRealtime)); } if ((timeSignalGood > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_signal", true))) { myUsages.add(new Misc("Good Signal", timeSignalGood, whichRealtime)); } if ((timeSignalGreat > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_signal", true))) { myUsages.add(new Misc("Great Signal", timeSignalGreat, whichRealtime)); } if ((timeScreenDark > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_screen_brightness", true))) { myUsages.add(new Misc("Screen dark", timeScreenDark, whichRealtime)); } if ((timeScreenDim > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_screen_brightness", true))) { myUsages.add(new Misc("Screen dimmed", timeScreenDim, whichRealtime)); } if ((timeScreenMedium > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_screen_brightness", true))) { myUsages.add(new Misc("Screen medium", timeScreenMedium, whichRealtime)); } if ((timeScreenLight > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_screen_brightness", true))) { myUsages.add(new Misc("Screen light", timeScreenLight, whichRealtime)); } if ((timeScreenBright > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_screen_brightness", true))) { myUsages.add(new Misc("Screen bright", timeScreenBright, whichRealtime)); } // if ( (timeWifiMulticast > 0) && (!bFilterView || // sharedPrefs.getBoolean("show_other_wifi", true)) ) // { // myUsages.add(new Misc("Wifi Multicast On", timeWifiMulticast, // whichRealtime)); // } // // if ( (timeWifiLocked > 0) && (!bFilterView ||(!bFilterView || // sharedPrefs.getBoolean("show_other_wifi", true)) ) // { // myUsages.add(new Misc("Wifi Locked", timeWifiLocked, whichRealtime)); // } // // if ( (timeWifiScan > 0) && (!bFilterView || // sharedPrefs.getBoolean("show_other_wifi", true)) ) // { // myUsages.add(new Misc("Wifi Scan", timeWifiScan, whichRealtime)); // } // // if (timeAudioOn > 0) // { // myUsages.add(new Misc("Video On", timeAudioOn, whichRealtime)); // } // // if (timeVideoOn > 0) // { // myUsages.add(new Misc("Video On", timeVideoOn, whichRealtime)); // } // sort @see // com.asksven.android.common.privateapiproxies.Walkelock.compareTo // Collections.sort(myUsages); for (int i = 0; i < myUsages.size(); i++) { Misc usage = (Misc)myUsages.get(i); if (LogSettings.DEBUG) { Log.d(TAG, "Current value: " + usage.getName() + " " + usage.getData()); } if ((!bFilter) || (usage.getTimeOn() > 0)) { myStats.add((StatElement) usage); } } return myStats; } /** * Get the battery level lost since a given ref * * @param iStatType * the reference * @return the lost battery level */ public int getBatteryLevelStat(Reference myReference) { // deep sleep times are independent of stat type int level = getBatteryLevel(); if (myReference != null) { level = myReference.m_refBatteryLevel - level; } if (LogSettings.DEBUG) { Log.d(TAG, "Current Battery Level:" + level); Log.d(TAG, "Battery Level since " + myReference.getLabel() + ":" + level); } return level; } /** * Get the battery level lost since a given ref * * @param iStatType * the reference * @return the lost battery level */ public String getBatteryLevelFromTo(Reference refFrom, Reference refTo) { // deep sleep times are independent of stat type long lLevelTo = 0; long lLevelFrom = 0; long sinceH = -1; String levelTo = "-"; String levelFrom = "-"; if (refFrom != null) { lLevelFrom = refFrom.m_refBatteryLevel; levelFrom = String.valueOf(lLevelFrom); } if (refTo != null) { lLevelTo = refTo.m_refBatteryLevel; levelTo = String.valueOf(lLevelTo); } if (LogSettings.DEBUG) { Log.d(TAG, "Current Battery Level:" + levelTo); Log.d(TAG, "Battery Level between " + refFrom.m_fileName + " and " + refTo.m_fileName + ":" + levelFrom); } String drop_per_hour = ""; try { sinceH = getSince(refFrom, refTo); // since is in ms but x 100 in order to respect proportions of formatRatio (we call it with % and it normally calculates % so there is a factor 100 sinceH = sinceH / 10 / 60 / 60; drop_per_hour = StringUtils.formatRatio(lLevelFrom - lLevelTo, sinceH) + "/h"; } catch (Exception e) { drop_per_hour = ""; Log.e(TAG, "Error retrieving since"); } return "Bat.: " + getBatteryLevelStat(refFrom) + "% (" + levelFrom + "% to " + levelTo + "%)" + " [" + drop_per_hour + "]"; } /** * Get the battery voltage lost since a given ref * * @param iStatType * the reference * @return the lost battery level */ public int getBatteryVoltageStat(Reference myReference) { // deep sleep times are independent of stat type int voltage = getBatteryVoltage(); if (myReference != null) { voltage = myReference.m_refBatteryVoltage - voltage; } if (LogSettings.DEBUG) { Log.d(TAG, "Current Battery Voltage:" + voltage); Log.d(TAG, "Battery Voltage since " + myReference.getLabel() + ":" + voltage); } return voltage; } /** * Get the battery voltage lost since a given ref * * @param iStatType * the reference * @return the lost battery level */ public String getBatteryVoltageFromTo(Reference refFrom, Reference refTo) { // deep sleep times are independent of stat type int voltageTo = getBatteryVoltage(); int voltageFrom = -1; long sinceH = -1; if (refFrom != null) { voltageFrom = refFrom.m_refBatteryVoltage; } if (LogSettings.DEBUG) { Log.d(TAG, "Current Battery Voltage:" + voltageTo); Log.d(TAG, "Battery Voltage between " + refFrom.m_fileName + " and " + refTo.m_fileName + ":" + voltageFrom); } String drop_per_hour = ""; try { sinceH = getSince(refFrom, refTo); // since is in ms but x 100 in order to respect proportions of formatRatio (we call it with % and it normally calculates % so there is a factor 100 sinceH = sinceH / 10 / 60 / 60; drop_per_hour = StringUtils.formatRatio(voltageFrom - voltageTo, sinceH) + "/h"; } catch (Exception e) { drop_per_hour = ""; Log.e(TAG, "Error retrieving since"); } return "(" + voltageFrom + "-" + voltageTo + ")" + " [" + drop_per_hour + "]"; } public StatElement getElementByKey(ArrayList<StatElement> myList, String key) { StatElement ret = null; if (myList == null) { Log.e(TAG, "getElementByKey failed: null list"); return null; } for (int i = 0; i < myList.size(); i++) { StatElement item = myList.get(i); if (item.getName().equals(key)) { ret = item; break; } } if (ret == null) { Log.e(TAG, "getElementByKey failed: " + key + " was not found"); } return ret; } public long sum(ArrayList<StatElement> myList) { long ret = 0; if (myList == null) { Log.d(TAG, "sum was called with a null list"); return 0; } if (myList.size() == 0) { Log.d(TAG, "sum was called with an empty list"); return 0; } for (int i = 0; i < myList.size(); i++) { // make sure nothing goes wrong try { StatElement item = myList.get(i); ret += item.getValues()[0]; } catch (Exception e) { Log.e(TAG, "An error occcured " + e.getMessage()); GenericLogger.stackTrace(TAG, e.getStackTrace()); } } return ret; } /** * Returns true if a ref "since screen off" was stored * * @return true is a custom ref exists */ public boolean hasScreenOffRef() { Reference thisRef = ReferenceStore.getReferenceByName(Reference.SCREEN_OFF_REF_FILENAME, m_context); return ((thisRef != null) && (thisRef.m_refOther != null)); } /** * Returns true if a custom ref was stored * * @return true is a custom ref exists */ public boolean hasCustomRef() { Reference thisRef = ReferenceStore.getReferenceByName(Reference.CUSTOM_REF_FILENAME, m_context); return ((thisRef != null) && (thisRef.m_refOther != null)); } /** * Returns true if a since charged ref was stored * * @return true is a since charged ref exists */ public boolean hasSinceChargedRef() { Reference thisRef = ReferenceStore.getReferenceByName(Reference.CHARGED_REF_FILENAME, m_context); return ((thisRef != null) && (thisRef.m_refKernelWakelocks != null)); } /** * Returns true if a since unplugged ref was stored * * @return true is a since unplugged ref exists */ public boolean hasSinceUnpluggedRef() { Reference thisRef = ReferenceStore.getReferenceByName(Reference.UNPLUGGED_REF_FILENAME, m_context); return ((thisRef != null) && (thisRef.m_refKernelWakelocks != null)); } /** * Returns true if a since boot ref was stored * * @return true is a since unplugged ref exists */ public boolean hasSinceBootRef() { Reference thisRef = ReferenceStore.getReferenceByName(Reference.BOOT_REF_FILENAME, m_context); return ((thisRef != null) && (thisRef.m_refKernelWakelocks != null)); } /** * Saves all data to a point in time defined by user This data will be used * in a custom "since..." stat type */ public void setCustomReference(int iSort) { Reference thisRef = new Reference(Reference.CUSTOM_REF_FILENAME, Reference.TYPE_CUSTOM); ReferenceStore.put(Reference.CUSTOM_REF_FILENAME, populateReference(iSort, thisRef), m_context); } /** * Saves all data at the current point in time */ public void setCurrentReference(int iSort) { Reference thisRef = new Reference(Reference.CURRENT_REF_FILENAME, Reference.TYPE_CURRENT); ReferenceStore.put(Reference.CURRENT_REF_FILENAME, populateReference(iSort, thisRef), m_context); } /** * Saves all data at the current point in time */ public synchronized String setTimedReference(int iSort) { String fileName = Reference.TIMER_REF_FILENAME + DateUtils.format(System.currentTimeMillis(), DateUtils.DATE_FORMAT_NOW); Reference thisRef = new Reference(fileName, Reference.TYPE_TIMER); ReferenceStore.put(fileName, populateReference(iSort, thisRef), m_context); return fileName; } /** * Returns a n uncached current references with only "other", "wakelocks" and "kernel wakelocks" stats (for use in widgets) */ public Reference getUncachedPartialReference(int iSort) { Reference thisRef = new Reference(Reference.CURRENT_REF_FILENAME, Reference.TYPE_CURRENT); partiallyPopulateReference(iSort, thisRef); return thisRef; } /** * Saves all data to a point in time when the screen goes off This data will * be used in a custom "since..." stat type */ public void setReferenceSinceScreenOff(int iSort) { Reference thisRef = new Reference(Reference.SCREEN_OFF_REF_FILENAME, Reference.TYPE_EVENT); ReferenceStore.put(Reference.SCREEN_OFF_REF_FILENAME, populateReference(iSort, thisRef), m_context); // clean "current from cache" // ReferenceStore.invalidate(Reference.CURRENT_REF_FILENAME, m_context); } /** * Saves all data to a point in time when the screen goes in * be used in a custom "since..." stat type */ public void setReferenceScreenOn(int iSort) { Reference thisRef = new Reference(Reference.SCREEN_ON_REF_FILENAME, Reference.TYPE_EVENT); ReferenceStore.put(Reference.SCREEN_ON_REF_FILENAME, populateReference(iSort, thisRef), m_context); // clean "current from cache" ReferenceStore.invalidate(Reference.CURRENT_REF_FILENAME, m_context); } /** * Saves data when battery is fully charged This data will be used in the * "since charged" stat type */ public void setReferenceSinceCharged(int iSort) { Reference thisRef = new Reference(Reference.CHARGED_REF_FILENAME, Reference.TYPE_EVENT); ReferenceStore.put(Reference.CHARGED_REF_FILENAME, populateReference(iSort, thisRef), m_context); // clean "current from cache" ReferenceStore.invalidate(Reference.CURRENT_REF_FILENAME, m_context); } /** * Saves data when the phone is unplugged This data will be used in the * "since unplugged" stat type */ public void setReferenceSinceUnplugged(int iSort) { Reference thisRef = new Reference(Reference.UNPLUGGED_REF_FILENAME, Reference.TYPE_EVENT); ReferenceStore.put(Reference.UNPLUGGED_REF_FILENAME, populateReference(iSort, thisRef), m_context); // clean "current from cache" ReferenceStore.invalidate(Reference.CURRENT_REF_FILENAME, m_context); } /** * Saves data when the phone is booted This data will be used in the * "since unplugged" stat type */ public void setReferenceSinceBoot(int iSort) { Reference thisRef = new Reference(Reference.BOOT_REF_FILENAME, Reference.TYPE_EVENT); ReferenceStore.put(Reference.BOOT_REF_FILENAME, populateReference(iSort, thisRef), m_context); } /** * Saves a reference to cache and persists it */ private Reference populateReference(int iSort, Reference refs) { // we are going to retrieve a reference: make sure data does not come from the cache BatteryStatsProxy.getInstance(m_context).invalidate(); SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(m_context); boolean bFilterStats = sharedPrefs.getBoolean("filter_data", true); int iPctType = Integer.valueOf(sharedPrefs.getString("default_wl_ref", "0")); try { refs.m_refOther = null; refs.m_refWakelocks = null; refs.m_refKernelWakelocks = null; refs.m_refNetworkStats = null; refs.m_refAlarms = null; refs.m_refProcesses = null; refs.m_refCpuStates = null; try { refs.m_refKernelWakelocks = getCurrentNativeKernelWakelockStatList(bFilterStats, iPctType, iSort); } catch (Exception e) { Log.e(TAG, "An exception occured processing kernel wakelocks. Message: " + e.getMessage()); Log.e(TAG, "Exception: " + Log.getStackTraceString(e)); } try { refs.m_refWakelocks = getCurrentWakelockStatList(bFilterStats, iPctType, iSort); } catch (Exception e) { Log.e(TAG, "An exception occured processing partial wakelocks. Message: " + e.getMessage()); Log.e(TAG, "Exception: " + Log.getStackTraceString(e)); } try { refs.m_refOther = getCurrentOtherUsageStatList(bFilterStats, false, false); } catch (Exception e) { Log.e(TAG, "An exception occured processing other. Message: " + e.getMessage()); Log.e(TAG, "Exception: " + Log.getStackTraceString(e)); } try { refs.m_refCpuStates = getCurrentCpuStateList(bFilterStats); } catch (Exception e) { Log.e(TAG, "An exception occured processing CPU states. Message: " + e.getMessage()); Log.e(TAG, "Exception: " + Log.getStackTraceString(e)); } try { refs.m_refProcesses = getCurrentProcessStatList(bFilterStats, iSort); } catch (Exception e) { Log.e(TAG, "An exception occured processing processes. Message: " + e.getMessage()); Log.e(TAG, "Exception: " + Log.getStackTraceString(e)); } try { refs.m_refBatteryRealtime = getBatteryRealtime(BatteryStatsTypes.STATS_CURRENT); } catch (Exception e) { Log.e(TAG, "An exception occured processing battery realtime. Message: " + e.getMessage()); Log.e(TAG, "Exception: " + Log.getStackTraceString(e)); } try { refs.m_refBatteryLevel = getBatteryLevel(); refs.m_refBatteryVoltage = getBatteryVoltage(); } catch (ReceiverCallNotAllowedException e) { Log.e(TAG, "An exception occured. Message: " + e.getMessage()); Log.e(TAG, "Exception: " + Log.getStackTraceString(e)); refs.m_refBatteryLevel = 0; refs.m_refBatteryVoltage = 0; } // only root features active boolean rootEnabled = sharedPrefs .getBoolean("root_features", false); if (rootEnabled) { // After that we go on and try to write the rest. If this part // fails at least there will be a partial ref saved Log.i(TAG, "Trace: Calling root operations" + DateUtils.now()); try { refs.m_refNetworkStats = getCurrentNativeNetworkUsageStatList(bFilterStats); } catch (Exception e) { Log.e(TAG, "An exception occured processing network. Message: " + e.getMessage()); Log.e(TAG, "Exception: " + Log.getStackTraceString(e)); } try { refs.m_refAlarms = getCurrentAlarmsStatList(bFilterStats); } catch (Exception e) { Log.e(TAG, "An exception occured processing alarms. Message: " + e.getMessage()); Log.e(TAG, "Exception: " + Log.getStackTraceString(e)); } Log.i(TAG, "Trace: Finished root operations" + DateUtils.now()); } } catch (Exception e) { Log.e(TAG, "An exception occured. Message: " + e.getMessage()); // Log.e(TAG, "Callstack", e.fillInStackTrace()); Log.e(TAG, "Exception: " + Log.getStackTraceString(e)); refs.m_refOther = null; refs.m_refWakelocks = null; refs.m_refKernelWakelocks = null; refs.m_refNetworkStats = null; refs.m_refAlarms = null; refs.m_refProcesses = null; refs.m_refCpuStates = null; refs.m_refBatteryRealtime = 0; refs.m_refBatteryLevel = 0; refs.m_refBatteryVoltage = 0; } // update timestamp refs.setTimestamp(); return refs; } /** * Saves a reference to cache and persists it */ private Reference partiallyPopulateReference(int iSort, Reference refs) { // we are going to retrieve a reference: make sure data does not come from the cache BatteryStatsProxy.getInstance(m_context).invalidate(); SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(m_context); boolean bFilterStats = sharedPrefs.getBoolean("filter_data", true); int iPctType = Integer.valueOf(sharedPrefs.getString("default_wl_ref", "0")); try { refs.m_refOther = null; refs.m_refWakelocks = null; refs.m_refKernelWakelocks = null; refs.m_refAlarms = null; refs.m_refProcesses = null; refs.m_refCpuStates = null; refs.m_refKernelWakelocks = getCurrentNativeKernelWakelockStatList(bFilterStats, iPctType, iSort); refs.m_refWakelocks = getCurrentWakelockStatList(bFilterStats, iPctType, iSort); refs.m_refOther = getCurrentOtherUsageStatList(bFilterStats, false, false); refs.m_refBatteryRealtime = getBatteryRealtime(BatteryStatsTypes.STATS_CURRENT); try { refs.m_refBatteryLevel = getBatteryLevel(); refs.m_refBatteryVoltage = getBatteryVoltage(); } catch (ReceiverCallNotAllowedException e) { Log.e(TAG, "An exception occured. Message: " + e.getMessage()); Log.e(TAG, "Exception: " + Log.getStackTraceString(e)); refs.m_refBatteryLevel = 0; refs.m_refBatteryVoltage = 0; } } catch (Exception e) { Log.e(TAG, "An exception occured. Message: " + e.getMessage()); } // update timestamp refs.setTimestamp(); return refs; } /** * Returns the battery realtime since a given reference * * @param iStatType * the reference * @return the battery realtime */ public long getBatteryRealtime(int iStatType) throws BatteryInfoUnavailableException { BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(m_context); if (mStats == null) { // an error has occured return -1; } long whichRealtime = 0; long rawRealtime = SystemClock.elapsedRealtime() * 1000; if ((iStatType == StatsProvider.STATS_CUSTOM) && (ReferenceStore.getReferenceByName(Reference.CUSTOM_REF_FILENAME, m_context) != null)) { whichRealtime = mStats.computeBatteryRealtime(rawRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; whichRealtime -= ReferenceStore.getReferenceByName(Reference.CUSTOM_REF_FILENAME, m_context).m_refBatteryRealtime; } else if ((iStatType == StatsProvider.STATS_SCREEN_OFF) && (ReferenceStore.getReferenceByName(Reference.SCREEN_OFF_REF_FILENAME, m_context) != null)) { whichRealtime = mStats.computeBatteryRealtime(rawRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; whichRealtime -= ReferenceStore.getReferenceByName(Reference.SCREEN_OFF_REF_FILENAME, m_context).m_refBatteryRealtime; } else if ((iStatType == StatsProvider.STATS_BOOT) && (ReferenceStore.getReferenceByName(Reference.BOOT_REF_FILENAME, m_context) != null)) { whichRealtime = mStats.computeBatteryRealtime(rawRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; whichRealtime -= ReferenceStore.getReferenceByName(Reference.BOOT_REF_FILENAME, m_context).m_refBatteryRealtime; } else { whichRealtime = mStats.computeBatteryRealtime(rawRealtime, iStatType) / 1000; } return whichRealtime; } /** * Returns the battery realtime since a given reference * * @param iStatType * the reference * @return the battery realtime */ public boolean getIsCharging() throws BatteryInfoUnavailableException { BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(m_context); if (mStats == null) { // an error has occured return false; } return !mStats.getIsOnBattery(m_context); } /** * Dumps relevant data to an output file * */ @SuppressLint("NewApi") public void writeDumpToFile(Reference refFrom, int iSort, Reference refTo) { SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(m_context); boolean bFilterStats = sharedPrefs.getBoolean("filter_data", true); int iPctType = Integer.valueOf(sharedPrefs.getString("default_wl_ref", "0")); if (!DataStorage.isExternalStorageWritable()) { Log.e(TAG, "External storage can not be written"); Toast.makeText(m_context, "External Storage can not be written", Toast.LENGTH_SHORT).show(); } try { // open file for writing File root; boolean bSaveToPrivateStorage = sharedPrefs.getBoolean("files_to_private_storage", false); if (bSaveToPrivateStorage) { try { root = m_context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); } catch (Exception e) { root = Environment.getExternalStorageDirectory(); } } else { root = Environment.getExternalStorageDirectory(); } // check if file can be written if (root.canWrite()) { String strFilename = "BetterBatteryStats-" + DateUtils.now("yyyy-MM-dd_HHmmssSSS") + ".txt"; File dumpFile = new File(root, strFilename); FileWriter fw = new FileWriter(dumpFile); BufferedWriter out = new BufferedWriter(fw); // write header out.write("===================\n"); out.write("General Information\n"); out.write("===================\n"); PackageInfo pinfo = m_context.getPackageManager() .getPackageInfo(m_context.getPackageName(), 0); out.write("BetterBatteryStats version: " + pinfo.versionName + "\n"); out.write("Creation Date: " + DateUtils.now() + "\n"); out.write("Statistic Type: " + refFrom.getLabel() + " to "+ refTo.getLabel() + "\n"); out.write("Since " + DateUtils.formatDuration(getSince(refFrom, refTo)) + "\n"); out.write("VERSION.RELEASE: " + Build.VERSION.RELEASE + "\n"); out.write("BRAND: " + Build.BRAND + "\n"); out.write("DEVICE: " + Build.DEVICE + "\n"); out.write("MANUFACTURER: " + Build.MANUFACTURER + "\n"); out.write("MODEL: " + Build.MODEL + "\n"); out.write("OS.VERSION: " + System.getProperty("os.version") + "\n"); if (Build.VERSION.SDK_INT >= 8) { out.write("BOOTLOADER: " + Build.BOOTLOADER + "\n"); out.write("HARDWARE: " + Build.HARDWARE + "\n"); } out.write("FINGERPRINT: " + Build.FINGERPRINT + "\n"); out.write("ID: " + Build.ID + "\n"); out.write("TAGS: " + Build.TAGS + "\n"); out.write("USER: " + Build.USER + "\n"); out.write("PRODUCT: " + Build.PRODUCT + "\n"); String radio = ""; // from API14 if (Build.VERSION.SDK_INT >= 14) { radio = Build.getRadioVersion(); } else if (Build.VERSION.SDK_INT >= 8) { radio = Build.RADIO; } out.write("RADIO: " + radio + "\n"); out.write("Rooted: " + RootDetection.hasSuRights("dumpsys alarm") + "\n"); out.write("============\n"); out.write("Battery Info\n"); out.write("============\n"); out.write("Level lost [%]: " + getBatteryLevelStat(refFrom) + " " + getBatteryLevelFromTo(refFrom, refTo) + "\n"); out.write("Voltage lost [mV]: " + getBatteryVoltageStat(refFrom) + " " + getBatteryVoltageFromTo(refFrom, refTo) + "\n"); // write timing info boolean bDumpChapter = sharedPrefs.getBoolean("show_other", true); if (bDumpChapter) { out.write("===========\n"); out.write("Other Usage\n"); out.write("===========\n"); dumpList( getOtherUsageStatList(bFilterStats, refFrom, false, false, refTo), out); } bDumpChapter = sharedPrefs.getBoolean("show_pwl", true); if (bDumpChapter) { // write wakelock info out.write("=========\n"); out.write("Wakelocks\n"); out.write("=========\n"); dumpList( getWakelockStatList(bFilterStats, refFrom, iPctType, iSort, refTo), out); } bDumpChapter = sharedPrefs.getBoolean("show_kwl", true); if (bDumpChapter) { String addendum = ""; if (Wakelocks.isDiscreteKwlPatch()) { addendum = "!!! Discrete !!!"; } if (!Wakelocks.fileExists()) { addendum = " !!! wakeup_sources !!!"; } // write kernel wakelock info out.write("================\n"); out.write("Kernel Wakelocks " + addendum + "\n"); out.write("================\n"); dumpList( getNativeKernelWakelockStatList(bFilterStats, refFrom, iPctType, iSort, refTo), out); } bDumpChapter = sharedPrefs.getBoolean("show_proc", false); if (bDumpChapter) { // write process info out.write("=========\n"); out.write("Processes\n"); out.write("=========\n"); dumpList( getProcessStatList(bFilterStats, refFrom, iSort, refTo), out); } bDumpChapter = sharedPrefs.getBoolean("show_alarm", true); if (bDumpChapter) { // write alarms info out.write("======================\n"); out.write("Alarms (requires root)\n"); out.write("======================\n"); dumpList(getAlarmsStatList(bFilterStats, refFrom, refTo), out); } bDumpChapter = sharedPrefs.getBoolean("show_network", true); if (bDumpChapter) { // write alarms info out.write("======================\n"); out.write("Network (requires root)\n"); out.write("======================\n"); dumpList( getNativeNetworkUsageStatList(bFilterStats, refFrom, refTo), out); } bDumpChapter = sharedPrefs.getBoolean("show_cpustates", true); if (bDumpChapter) { // write alarms info out.write("==========\n"); out.write("CPU States\n"); out.write("==========\n"); dumpList(getCpuStateList(refFrom, refTo, bFilterStats), out); } bDumpChapter = sharedPrefs.getBoolean("show_serv", false); if (bDumpChapter) { out.write("========\n"); out.write("Services\n"); out.write("========\n"); out.write("Active since: The time when the service was first made active, either by someone starting or binding to it.\n"); out.write("Last activity: The time when there was last activity in the service (either explicit requests to start it or clients binding to it)\n"); out.write("See http://developer.android.com/reference/android/app/ActivityManager.RunningServiceInfo.html\n"); ActivityManager am = (ActivityManager) m_context .getSystemService(m_context.ACTIVITY_SERVICE); List<ActivityManager.RunningServiceInfo> rs = am .getRunningServices(50); for (int i = 0; i < rs.size(); i++) { ActivityManager.RunningServiceInfo rsi = rs.get(i); out.write(rsi.process + " (" + rsi.service.getClassName() + ")\n"); out.write(" Active since: " + DateUtils.formatDuration(rsi.activeSince) + "\n"); out.write(" Last activity: " + DateUtils .formatDuration(rsi.lastActivityTime) + "\n"); out.write(" Crash count:" + rsi.crashCount + "\n"); } } // add chapter for reference info out.write("==================\n"); out.write("Reference overview\n"); out.write("==================\n"); if (ReferenceStore.getReferenceByName(Reference.CUSTOM_REF_FILENAME, m_context) != null) { out.write("Custom: " + ReferenceStore.getReferenceByName(Reference.CUSTOM_REF_FILENAME, m_context).whoAmI() + "\n"); } else { out.write("Custom: " + "null" + "\n"); } if (ReferenceStore.getReferenceByName(Reference.CHARGED_REF_FILENAME, m_context) != null) { out.write("Since charged: " + ReferenceStore.getReferenceByName(Reference.CHARGED_REF_FILENAME, m_context).whoAmI() + "\n"); } else { out.write("Since charged: " + "null" + "\n"); } if (ReferenceStore.getReferenceByName(Reference.SCREEN_OFF_REF_FILENAME, m_context) != null) { out.write("Since screen off: " + ReferenceStore.getReferenceByName(Reference.SCREEN_OFF_REF_FILENAME, m_context).whoAmI() + "\n"); } else { out.write("Since screen off: " + "null" + "\n"); } if (ReferenceStore.getReferenceByName(Reference.UNPLUGGED_REF_FILENAME, m_context) != null) { out.write("Since unplugged: " + ReferenceStore.getReferenceByName(Reference.UNPLUGGED_REF_FILENAME, m_context).whoAmI() + "\n"); } else { out.write("Since unplugged: " + "null" + "\n"); } if (ReferenceStore.getReferenceByName(Reference.BOOT_REF_FILENAME, m_context) != null) { out.write("Since boot: " + ReferenceStore.getReferenceByName(Reference.BOOT_REF_FILENAME, m_context).whoAmI() + "\n"); } else { out.write("Since boot: " + "null" + "\n"); } // close file out.close(); // Toast.makeText(m_context, "Dump witten: " + strFilename, Toast.LENGTH_SHORT).show(); } else { Log.i(TAG, "Write error. " + Environment.getExternalStorageDirectory() + " couldn't be written"); } } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } } @SuppressLint("NewApi") public void writeLogcatToFile() { SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(m_context); if (!DataStorage.isExternalStorageWritable()) { Log.e(TAG, "External storage can not be written"); Toast.makeText(m_context, "External Storage can not be written", Toast.LENGTH_SHORT).show(); } try { // open file for writing // open file for writing File root; boolean bSaveToPrivateStorage = sharedPrefs.getBoolean("files_to_private_storage", false); if (bSaveToPrivateStorage) { try { root = m_context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); } catch (Exception e) { root = Environment.getExternalStorageDirectory(); } } else { root = Environment.getExternalStorageDirectory(); } String path = root.getAbsolutePath(); // check if file can be written if (root.canWrite()) { String filename = "logcat-" + DateUtils.now("yyyy-MM-dd_HHmmssSSS") + ".txt"; Util.run("logcat -d > " + path + "/" + filename); // Toast.makeText(m_context, "Dump witten: " + path + "/" + filename, Toast.LENGTH_SHORT).show(); } else { Log.i(TAG, "Write error. " + Environment.getExternalStorageDirectory() + " couldn't be written"); } } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } } @SuppressLint("NewApi") public void writeDmesgToFile() { SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(m_context); if (!DataStorage.isExternalStorageWritable()) { Log.e(TAG, "External storage can not be written"); Toast.makeText(m_context, "External Storage can not be written", Toast.LENGTH_SHORT).show(); } try { // open file for writing File root; boolean bSaveToPrivateStorage = sharedPrefs.getBoolean("files_to_private_storage", false); if (bSaveToPrivateStorage) { try { root = m_context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); } catch (Exception e) { root = Environment.getExternalStorageDirectory(); } } else { root = Environment.getExternalStorageDirectory(); } String path = root.getAbsolutePath(); // check if file can be written if (root.canWrite()) { String filename = "dmesg-" + DateUtils.now("yyyy-MM-dd_HHmmssSSS") + ".txt"; Util.run("dmesg > " + path + "/" + filename); // Toast.makeText(m_context, "Dump witten: " + path + "/" + filename, Toast.LENGTH_SHORT).show(); } else { Log.i(TAG, "Write error. " + Environment.getExternalStorageDirectory() + " couldn't be written"); } } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } } /** * Dump the elements on one list * * @param myList * a list of StatElement */ private void dumpList(List<StatElement> myList, BufferedWriter out) throws IOException { if (myList != null) { for (int i = 0; i < myList.size(); i++) { out.write(myList.get(i).getDumpData(m_context) + "\n"); } } } /** * translate the stat type (see arrays.xml) to the corresponding label * * @param position * the spinner position * @return the stat type */ public static String statTypeToLabel(int statType) { String strRet = ""; switch (statType) { case 0: strRet = "Since Charged"; break; case 3: strRet = "Since Unplugged"; break; case 4: strRet = "Custom Reference"; break; case 5: strRet = "Since Screen off"; break; case 6: strRet = "Since Boot"; break; default: Log.e(TAG, "No label was found for stat type " + statType); break; } return strRet; } /** * translate the stat type (see arrays.xml) to the corresponding short label * * @param position * the spinner position * @return the stat type */ public static String statTypeToLabelShort(int statType) { String strRet = ""; switch (statType) { case 0: strRet = "Charged"; break; case 3: strRet = "Unpl."; break; case 4: strRet = "Custom"; break; case 5: strRet = "Scr. off"; break; case 6: strRet = "Boot"; break; default: Log.e(TAG, "No label was found for stat type " + statType); break; } return strRet; } /** * translate the stat type (see arrays.xml) to the corresponding label * * @param position * the spinner position * @return the stat type */ public String statTypeToUrl(int statType) { String strRet = statTypeToLabel(statType); // remove spaces StringTokenizer st = new StringTokenizer(strRet, " ", false); String strCleaned = ""; while (st.hasMoreElements()) { strCleaned += st.nextElement(); } return strCleaned; } /** * translate the stat (see arrays.xml) to the corresponding label * * @param position * the spinner position * @return the stat */ private String statToLabel(int iStat) { String strRet = ""; String[] statsArray = m_context.getResources().getStringArray( R.array.stats); strRet = statsArray[iStat]; return strRet; } /** * translate the stat (see arrays.xml) to the corresponding label * * @param position * the spinner position * @return the stat */ public String statToUrl(int stat) { String strRet = statToLabel(stat); // remove spaces StringTokenizer st = new StringTokenizer(strRet, " ", false); String strCleaned = ""; while (st.hasMoreElements()) { strCleaned += st.nextElement(); } return strCleaned; } /** * translate the spinner position (see arrays.xml) to the stat type * * @param position * the spinner position * @return the stat type */ public static int statTypeFromPosition(int position) { int iRet = 0; switch (position) { case 0: iRet = STATS_CHARGED; break; case 1: iRet = STATS_UNPLUGGED; break; case 2: iRet = STATS_CUSTOM; break; case 3: iRet = STATS_SCREEN_OFF; break; case 4: iRet = STATS_BOOT; break; default: Log.e(TAG, "No stat type was found for position " + position); break; } return iRet; } /** * translate the stat type to the spinner position (see arrays.xml) * * @param iStatType * the stat type * @return the spinner position */ public int positionFromStatType(int iStatType) { int iRet = 0; switch (iStatType) { case STATS_CHARGED: iRet = 0; break; case STATS_UNPLUGGED: iRet = 1; break; case STATS_CUSTOM: iRet = 2; break; case STATS_SCREEN_OFF: iRet = 3; break; case STATS_BOOT: iRet = 4; break; default: Log.e(TAG, "No position was found for stat type " + iStatType); break; } return iRet; } /** * Returns the current battery level as an int [0..100] or -1 if invalid */ int getBatteryLevel() { // check the battery level and if 100% the store "since charged" ref Intent batteryIntent = m_context.getApplicationContext() .registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); int rawlevel = batteryIntent .getIntExtra(BatteryManager.EXTRA_LEVEL, -1); double scale = batteryIntent .getIntExtra(BatteryManager.EXTRA_SCALE, -1); double level = -1; if (rawlevel >= 0 && scale > 0) { // normalize level to [0..1] level = rawlevel / scale; } return (int) (level * 100); } /** * Returns the current battery voltage as a double [0..1] or -1 if invalid */ int getBatteryVoltage() { // check the battery level and if 100% the store "since charged" ref Intent batteryIntent = m_context.getApplicationContext() .registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); int voltage = batteryIntent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1); return voltage; } /** * Adds an alarm to schedule a wakeup to save a reference */ public static boolean scheduleActiveMonAlarm(Context ctx) { Log.i(TAG, "active_mon_enabled called"); // create a new one starting to count NOW SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx); int iInterval = prefs.getInt("active_mon_freq", 60); long fireAt = System.currentTimeMillis() + (iInterval * 60 * 1000); Intent intent = new Intent(ctx, ActiveMonAlarmReceiver.class); PendingIntent sender = PendingIntent.getBroadcast(ctx, ActiveMonAlarmReceiver.ACTIVE_MON_ALARM, intent, PendingIntent.FLAG_UPDATE_CURRENT); // Get the AlarmManager service AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE); am.set(AlarmManager.RTC_WAKEUP, fireAt, sender); return true; } /** * Cancels the current alarm (if existing) */ public static void cancelActiveMonAlarm(Context ctx) { // check if there is an intent pending Intent intent = new Intent(ctx, ActiveMonAlarmReceiver.class); PendingIntent sender = PendingIntent.getBroadcast(ctx, ActiveMonAlarmReceiver.ACTIVE_MON_ALARM, intent, PendingIntent.FLAG_UPDATE_CURRENT); if (sender != null) { // Get the AlarmManager service AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE); am.cancel(sender); } } public static boolean isActiveMonAlarmScheduled(Context ctx) { Intent intent = new Intent(ctx, ActiveMonAlarmReceiver.class); boolean alarmUp = (PendingIntent.getBroadcast(ctx, ActiveMonAlarmReceiver.ACTIVE_MON_ALARM, intent, PendingIntent.FLAG_NO_CREATE) != null); if (alarmUp) { Log.i("myTag", "Alarm is already active"); } return alarmUp; } }
true
true
public ArrayList<StatElement> getCurrentOtherUsageStatList(boolean bFilter, boolean bFilterView, boolean bWidget) throws Exception { BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(m_context); SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(m_context); ArrayList<StatElement> myStats = new ArrayList<StatElement>(); // List to store the other usages to ArrayList<StatElement> myUsages = new ArrayList<StatElement>(); long rawRealtime = SystemClock.elapsedRealtime() * 1000; long batteryRealtime = mStats.getBatteryRealtime(rawRealtime); long whichRealtime = mStats.computeBatteryRealtime(rawRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; long timeBatteryUp = mStats.computeBatteryUptime( SystemClock.uptimeMillis() * 1000, BatteryStatsTypes.STATS_CURRENT) / 1000; if (CommonLogSettings.DEBUG) { Log.i(TAG, "whichRealtime = " + whichRealtime + " batteryRealtime = " + batteryRealtime + " timeBatteryUp=" + timeBatteryUp); } long timeScreenOn = mStats.getScreenOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; long timePhoneOn = mStats.getPhoneOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; long timeWifiOn = 0; long timeWifiRunning = 0; if (sharedPrefs.getBoolean("show_other_wifi", true) && !bWidget) { try { timeWifiOn = mStats.getWifiOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeWifiRunning = mStats.getGlobalWifiRunningTime( batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; // long timeWifiMulticast = // mStats.getWifiMulticastTime(m_context, batteryRealtime, // BatteryStatsTypes.STATS_CURRENT) / 1000; // long timeWifiLocked = mStats.getFullWifiLockTime(m_context, // batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; // long timeWifiScan = mStats.getScanWifiLockTime(m_context, // batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; } catch (BatteryInfoUnavailableException e) { timeWifiOn = 0; timeWifiRunning = 0; Log.e(TAG, "A batteryinfo error occured while retrieving Wifi data"); } } // long timeAudioOn = mStats.getAudioTurnedOnTime(m_context, // batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; // long timeVideoOn = mStats.getVideoTurnedOnTime(m_context, // batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; long timeBluetoothOn = 0; if (sharedPrefs.getBoolean("show_other_bt", true) && !bWidget) { try { timeBluetoothOn = mStats.getBluetoothOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; } catch (BatteryInfoUnavailableException e) { timeBluetoothOn = 0; Log.e(TAG, "A batteryinfo error occured while retrieving BT data"); } } long timeNoDataConnection = 0; long timeSignalNone = 0; long timeSignalPoor = 0; long timeSignalModerate = 0; long timeSignalGood = 0; long timeSignalGreat = 0; if (sharedPrefs.getBoolean("show_other_signal", true)) { try { timeNoDataConnection = mStats.getPhoneDataConnectionTime( BatteryStatsTypes.DATA_CONNECTION_NONE, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeSignalNone = mStats.getPhoneSignalStrengthTime( BatteryStatsTypes.SIGNAL_STRENGTH_NONE_OR_UNKNOWN, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeSignalPoor = mStats.getPhoneSignalStrengthTime( BatteryStatsTypes.SIGNAL_STRENGTH_POOR, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeSignalModerate = mStats.getPhoneSignalStrengthTime( BatteryStatsTypes.SIGNAL_STRENGTH_MODERATE, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeSignalGood = mStats.getPhoneSignalStrengthTime( BatteryStatsTypes.SIGNAL_STRENGTH_GOOD, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeSignalGreat = mStats.getPhoneSignalStrengthTime( BatteryStatsTypes.SIGNAL_STRENGTH_GREAT, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; } catch (BatteryInfoUnavailableException e) { timeNoDataConnection = 0; timeSignalNone = 0; timeSignalPoor = 0; timeSignalModerate = 0; timeSignalGood = 0; timeSignalGreat = 0; Log.e(TAG, "A batteryinfo error occured while retrieving Signal data"); } } long timeScreenDark = 0; long timeScreenDim = 0; long timeScreenMedium = 0; long timeScreenLight = 0; long timeScreenBright = 0; if (sharedPrefs.getBoolean("show_other_screen_brightness", true)) { try { timeScreenDark = mStats.getScreenBrightnessTime( BatteryStatsTypes.SCREEN_BRIGHTNESS_DARK, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeScreenDim = mStats.getScreenBrightnessTime( BatteryStatsTypes.SCREEN_BRIGHTNESS_DIM, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeScreenMedium = mStats.getScreenBrightnessTime( BatteryStatsTypes.SCREEN_BRIGHTNESS_MEDIUM, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeScreenLight = mStats.getScreenBrightnessTime( BatteryStatsTypes.SCREEN_BRIGHTNESS_LIGHT, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeScreenBright = mStats.getScreenBrightnessTime( BatteryStatsTypes.SCREEN_BRIGHTNESS_BRIGHT, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; } catch (BatteryInfoUnavailableException e) { timeScreenDark = 0; timeScreenDim = 0; timeScreenMedium = 0; timeScreenLight = 0; timeScreenBright = 0; Log.e(TAG, "A batteryinfo error occured while retrieving Screen brightness data"); } } // deep sleep times are independent of stat type long timeDeepSleep = (SystemClock.elapsedRealtime() - SystemClock .uptimeMillis()); // long whichRealtime = SystemClock.elapsedRealtime(); // long timeElapsed = mStats.computeBatteryRealtime(rawRealtime, // BatteryStatsTypes.STATS_CURRENT) / 1000; // SystemClock.elapsedRealtime(); Misc deepSleepUsage = new Misc("Deep Sleep", timeDeepSleep, whichRealtime); Log.d(TAG, "Added Deep sleep:" + deepSleepUsage.getData()); if ((!bFilter) || (deepSleepUsage.getTimeOn() > 0)) { myUsages.add(deepSleepUsage); } if (timeBatteryUp > 0) { myUsages.add(new Misc("Awake", timeBatteryUp, whichRealtime)); } if (timeScreenOn > 0) { myUsages.add(new Misc("Screen On", timeScreenOn, whichRealtime)); } if (timePhoneOn > 0) { myUsages.add(new Misc("Phone On", timePhoneOn, whichRealtime)); } if ((timeWifiOn > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_wifi", true))) { myUsages.add(new Misc("Wifi On", timeWifiOn, whichRealtime)); } if ((timeWifiRunning > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_wifi", true))) { myUsages.add(new Misc("Wifi Running", timeWifiRunning, whichRealtime)); } if ((timeBluetoothOn > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_bt", true))) { myUsages.add(new Misc("Bluetooth On", timeBluetoothOn, whichRealtime)); } if ((timeNoDataConnection > 0) && (!bFilterView || sharedPrefs.getBoolean( "show_other_connection", true))) { myUsages.add(new Misc("No Data Connection", timeNoDataConnection, whichRealtime)); } if ((timeSignalNone > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_signal", true))) { myUsages.add(new Misc("No or Unknown Signal", timeSignalNone, whichRealtime)); } if ((timeSignalPoor > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_signal", true))) { myUsages.add(new Misc("Poor Signal", timeSignalPoor, whichRealtime)); } if ((timeSignalModerate > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_signal", true))) { myUsages.add(new Misc("Moderate Signal", timeSignalModerate, whichRealtime)); } if ((timeSignalGood > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_signal", true))) { myUsages.add(new Misc("Good Signal", timeSignalGood, whichRealtime)); } if ((timeSignalGreat > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_signal", true))) { myUsages.add(new Misc("Great Signal", timeSignalGreat, whichRealtime)); } if ((timeScreenDark > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_screen_brightness", true))) { myUsages.add(new Misc("Screen dark", timeScreenDark, whichRealtime)); } if ((timeScreenDim > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_screen_brightness", true))) { myUsages.add(new Misc("Screen dimmed", timeScreenDim, whichRealtime)); } if ((timeScreenMedium > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_screen_brightness", true))) { myUsages.add(new Misc("Screen medium", timeScreenMedium, whichRealtime)); } if ((timeScreenLight > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_screen_brightness", true))) { myUsages.add(new Misc("Screen light", timeScreenLight, whichRealtime)); } if ((timeScreenBright > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_screen_brightness", true))) { myUsages.add(new Misc("Screen bright", timeScreenBright, whichRealtime)); } // if ( (timeWifiMulticast > 0) && (!bFilterView || // sharedPrefs.getBoolean("show_other_wifi", true)) ) // { // myUsages.add(new Misc("Wifi Multicast On", timeWifiMulticast, // whichRealtime)); // } // // if ( (timeWifiLocked > 0) && (!bFilterView ||(!bFilterView || // sharedPrefs.getBoolean("show_other_wifi", true)) ) // { // myUsages.add(new Misc("Wifi Locked", timeWifiLocked, whichRealtime)); // } // // if ( (timeWifiScan > 0) && (!bFilterView || // sharedPrefs.getBoolean("show_other_wifi", true)) ) // { // myUsages.add(new Misc("Wifi Scan", timeWifiScan, whichRealtime)); // } // // if (timeAudioOn > 0) // { // myUsages.add(new Misc("Video On", timeAudioOn, whichRealtime)); // } // // if (timeVideoOn > 0) // { // myUsages.add(new Misc("Video On", timeVideoOn, whichRealtime)); // } // sort @see // com.asksven.android.common.privateapiproxies.Walkelock.compareTo // Collections.sort(myUsages); for (int i = 0; i < myUsages.size(); i++) { Misc usage = (Misc)myUsages.get(i); if (LogSettings.DEBUG) { Log.d(TAG, "Current value: " + usage.getName() + " " + usage.getData()); } if ((!bFilter) || (usage.getTimeOn() > 0)) { myStats.add((StatElement) usage); } } return myStats; }
public ArrayList<StatElement> getCurrentOtherUsageStatList(boolean bFilter, boolean bFilterView, boolean bWidget) throws Exception { BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(m_context); SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(m_context); ArrayList<StatElement> myStats = new ArrayList<StatElement>(); // List to store the other usages to ArrayList<StatElement> myUsages = new ArrayList<StatElement>(); long rawRealtime = SystemClock.elapsedRealtime() * 1000; long batteryRealtime = 0; try { batteryRealtime = mStats.getBatteryRealtime(rawRealtime); } catch (Exception e) { Log.e(TAG, "An exception occured processing battery realtime. Message: " + e.getMessage()); Log.e(TAG, "Exception: " + Log.getStackTraceString(e)); } long whichRealtime = mStats.computeBatteryRealtime(rawRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; long timeBatteryUp = mStats.computeBatteryUptime( SystemClock.uptimeMillis() * 1000, BatteryStatsTypes.STATS_CURRENT) / 1000; if (CommonLogSettings.DEBUG) { Log.i(TAG, "whichRealtime = " + whichRealtime + " batteryRealtime = " + batteryRealtime + " timeBatteryUp=" + timeBatteryUp); } long timeScreenOn = mStats.getScreenOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; long timePhoneOn = mStats.getPhoneOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; long timeWifiOn = 0; long timeWifiRunning = 0; if (sharedPrefs.getBoolean("show_other_wifi", true) && !bWidget) { try { timeWifiOn = mStats.getWifiOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeWifiRunning = mStats.getGlobalWifiRunningTime( batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; // long timeWifiMulticast = // mStats.getWifiMulticastTime(m_context, batteryRealtime, // BatteryStatsTypes.STATS_CURRENT) / 1000; // long timeWifiLocked = mStats.getFullWifiLockTime(m_context, // batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; // long timeWifiScan = mStats.getScanWifiLockTime(m_context, // batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; } catch (BatteryInfoUnavailableException e) { timeWifiOn = 0; timeWifiRunning = 0; Log.e(TAG, "A batteryinfo error occured while retrieving Wifi data"); } } // long timeAudioOn = mStats.getAudioTurnedOnTime(m_context, // batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; // long timeVideoOn = mStats.getVideoTurnedOnTime(m_context, // batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; long timeBluetoothOn = 0; if (sharedPrefs.getBoolean("show_other_bt", true) && !bWidget) { try { timeBluetoothOn = mStats.getBluetoothOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; } catch (BatteryInfoUnavailableException e) { timeBluetoothOn = 0; Log.e(TAG, "A batteryinfo error occured while retrieving BT data"); } } long timeNoDataConnection = 0; long timeSignalNone = 0; long timeSignalPoor = 0; long timeSignalModerate = 0; long timeSignalGood = 0; long timeSignalGreat = 0; if (sharedPrefs.getBoolean("show_other_signal", true)) { try { timeNoDataConnection = mStats.getPhoneDataConnectionTime( BatteryStatsTypes.DATA_CONNECTION_NONE, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeSignalNone = mStats.getPhoneSignalStrengthTime( BatteryStatsTypes.SIGNAL_STRENGTH_NONE_OR_UNKNOWN, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeSignalPoor = mStats.getPhoneSignalStrengthTime( BatteryStatsTypes.SIGNAL_STRENGTH_POOR, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeSignalModerate = mStats.getPhoneSignalStrengthTime( BatteryStatsTypes.SIGNAL_STRENGTH_MODERATE, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeSignalGood = mStats.getPhoneSignalStrengthTime( BatteryStatsTypes.SIGNAL_STRENGTH_GOOD, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeSignalGreat = mStats.getPhoneSignalStrengthTime( BatteryStatsTypes.SIGNAL_STRENGTH_GREAT, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; } catch (BatteryInfoUnavailableException e) { timeNoDataConnection = 0; timeSignalNone = 0; timeSignalPoor = 0; timeSignalModerate = 0; timeSignalGood = 0; timeSignalGreat = 0; Log.e(TAG, "A batteryinfo error occured while retrieving Signal data"); } } long timeScreenDark = 0; long timeScreenDim = 0; long timeScreenMedium = 0; long timeScreenLight = 0; long timeScreenBright = 0; if (sharedPrefs.getBoolean("show_other_screen_brightness", true)) { try { timeScreenDark = mStats.getScreenBrightnessTime( BatteryStatsTypes.SCREEN_BRIGHTNESS_DARK, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeScreenDim = mStats.getScreenBrightnessTime( BatteryStatsTypes.SCREEN_BRIGHTNESS_DIM, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeScreenMedium = mStats.getScreenBrightnessTime( BatteryStatsTypes.SCREEN_BRIGHTNESS_MEDIUM, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeScreenLight = mStats.getScreenBrightnessTime( BatteryStatsTypes.SCREEN_BRIGHTNESS_LIGHT, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; timeScreenBright = mStats.getScreenBrightnessTime( BatteryStatsTypes.SCREEN_BRIGHTNESS_BRIGHT, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000; } catch (BatteryInfoUnavailableException e) { timeScreenDark = 0; timeScreenDim = 0; timeScreenMedium = 0; timeScreenLight = 0; timeScreenBright = 0; Log.e(TAG, "A batteryinfo error occured while retrieving Screen brightness data"); } } // deep sleep times are independent of stat type long timeDeepSleep = (SystemClock.elapsedRealtime() - SystemClock .uptimeMillis()); // long whichRealtime = SystemClock.elapsedRealtime(); // long timeElapsed = mStats.computeBatteryRealtime(rawRealtime, // BatteryStatsTypes.STATS_CURRENT) / 1000; // SystemClock.elapsedRealtime(); Misc deepSleepUsage = new Misc("Deep Sleep", timeDeepSleep, whichRealtime); Log.d(TAG, "Added Deep sleep:" + deepSleepUsage.getData()); if ((!bFilter) || (deepSleepUsage.getTimeOn() > 0)) { myUsages.add(deepSleepUsage); } if (timeBatteryUp > 0) { myUsages.add(new Misc("Awake", timeBatteryUp, whichRealtime)); } if (timeScreenOn > 0) { myUsages.add(new Misc("Screen On", timeScreenOn, whichRealtime)); } if (timePhoneOn > 0) { myUsages.add(new Misc("Phone On", timePhoneOn, whichRealtime)); } if ((timeWifiOn > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_wifi", true))) { myUsages.add(new Misc("Wifi On", timeWifiOn, whichRealtime)); } if ((timeWifiRunning > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_wifi", true))) { myUsages.add(new Misc("Wifi Running", timeWifiRunning, whichRealtime)); } if ((timeBluetoothOn > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_bt", true))) { myUsages.add(new Misc("Bluetooth On", timeBluetoothOn, whichRealtime)); } if ((timeNoDataConnection > 0) && (!bFilterView || sharedPrefs.getBoolean( "show_other_connection", true))) { myUsages.add(new Misc("No Data Connection", timeNoDataConnection, whichRealtime)); } if ((timeSignalNone > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_signal", true))) { myUsages.add(new Misc("No or Unknown Signal", timeSignalNone, whichRealtime)); } if ((timeSignalPoor > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_signal", true))) { myUsages.add(new Misc("Poor Signal", timeSignalPoor, whichRealtime)); } if ((timeSignalModerate > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_signal", true))) { myUsages.add(new Misc("Moderate Signal", timeSignalModerate, whichRealtime)); } if ((timeSignalGood > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_signal", true))) { myUsages.add(new Misc("Good Signal", timeSignalGood, whichRealtime)); } if ((timeSignalGreat > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_signal", true))) { myUsages.add(new Misc("Great Signal", timeSignalGreat, whichRealtime)); } if ((timeScreenDark > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_screen_brightness", true))) { myUsages.add(new Misc("Screen dark", timeScreenDark, whichRealtime)); } if ((timeScreenDim > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_screen_brightness", true))) { myUsages.add(new Misc("Screen dimmed", timeScreenDim, whichRealtime)); } if ((timeScreenMedium > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_screen_brightness", true))) { myUsages.add(new Misc("Screen medium", timeScreenMedium, whichRealtime)); } if ((timeScreenLight > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_screen_brightness", true))) { myUsages.add(new Misc("Screen light", timeScreenLight, whichRealtime)); } if ((timeScreenBright > 0) && (!bFilterView || sharedPrefs.getBoolean("show_other_screen_brightness", true))) { myUsages.add(new Misc("Screen bright", timeScreenBright, whichRealtime)); } // if ( (timeWifiMulticast > 0) && (!bFilterView || // sharedPrefs.getBoolean("show_other_wifi", true)) ) // { // myUsages.add(new Misc("Wifi Multicast On", timeWifiMulticast, // whichRealtime)); // } // // if ( (timeWifiLocked > 0) && (!bFilterView ||(!bFilterView || // sharedPrefs.getBoolean("show_other_wifi", true)) ) // { // myUsages.add(new Misc("Wifi Locked", timeWifiLocked, whichRealtime)); // } // // if ( (timeWifiScan > 0) && (!bFilterView || // sharedPrefs.getBoolean("show_other_wifi", true)) ) // { // myUsages.add(new Misc("Wifi Scan", timeWifiScan, whichRealtime)); // } // // if (timeAudioOn > 0) // { // myUsages.add(new Misc("Video On", timeAudioOn, whichRealtime)); // } // // if (timeVideoOn > 0) // { // myUsages.add(new Misc("Video On", timeVideoOn, whichRealtime)); // } // sort @see // com.asksven.android.common.privateapiproxies.Walkelock.compareTo // Collections.sort(myUsages); for (int i = 0; i < myUsages.size(); i++) { Misc usage = (Misc)myUsages.get(i); if (LogSettings.DEBUG) { Log.d(TAG, "Current value: " + usage.getName() + " " + usage.getData()); } if ((!bFilter) || (usage.getTimeOn() > 0)) { myStats.add((StatElement) usage); } } return myStats; }
diff --git a/globe/es/igosoftware/globe/layers/hud/GHUDIcon.java b/globe/es/igosoftware/globe/layers/hud/GHUDIcon.java index a422382..298c644 100644 --- a/globe/es/igosoftware/globe/layers/hud/GHUDIcon.java +++ b/globe/es/igosoftware/globe/layers/hud/GHUDIcon.java @@ -1,387 +1,387 @@ /* IGO Software SL - [email protected] http://www.glob3.org ------------------------------------------------------------------------------- Copyright (c) 2010, IGO Software SL All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the IGO Software SL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL IGO Software SL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- */ package es.igosoftware.globe.layers.hud; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; import javax.media.opengl.GL; import com.sun.opengl.util.texture.Texture; import com.sun.opengl.util.texture.TextureCoords; import com.sun.opengl.util.texture.TextureIO; import es.igosoftware.util.GAssert; import es.igosoftware.util.GMath; import gov.nasa.worldwind.geom.Vec4; import gov.nasa.worldwind.render.DrawContext; public class GHUDIcon implements IHUDElement { public static enum Position { NORTHWEST, SOUTHWEST, NORTHEAST, SOUTHEAST; } private BufferedImage _image; private Texture _texture; private int _textureWidth; private int _textureHeight; private final GHUDIcon.Position _position; private int _borderWidth = 20; private int _borderHeight = 20; private float _opacity = 0.65f; private boolean _isEnable = true; private double _distanceFromEye = 0; private Rectangle _lastScreenBounds; private boolean _highlighted; private List<ActionListener> _actionListeners; public GHUDIcon(final BufferedImage image, final GHUDIcon.Position position) { GAssert.notNull(image, "image"); GAssert.notNull(position, "position"); _image = image; _position = position; } @Override public double getDistanceFromEye() { return _distanceFromEye; } @Override public void pick(final DrawContext dc, final Point pickPoint) { // drawIcon(dc); } @Override public void render(final DrawContext dc) { drawIcon(dc); } private void drawIcon(final DrawContext dc) { if (_texture == null) { _texture = TextureIO.newTexture(_image, true); if (_texture == null) { return; } _textureWidth = _texture.getWidth(); _textureHeight = _texture.getHeight(); } final GL gl = dc.getGL(); boolean attribsPushed = false; boolean modelviewPushed = false; boolean projectionPushed = false; try { gl.glPushAttrib(GL.GL_DEPTH_BUFFER_BIT | GL.GL_COLOR_BUFFER_BIT | GL.GL_ENABLE_BIT | GL.GL_TEXTURE_BIT | GL.GL_TRANSFORM_BIT | GL.GL_VIEWPORT_BIT | GL.GL_CURRENT_BIT); attribsPushed = true; // // Initialize texture if not done yet // Texture iconTexture = dc.getTextureCache().get(_iconFileName); // if (iconTexture == null) { // initializeTexture(dc); // iconTexture = dc.getTextureCache().get(_iconFileName); // if (iconTexture == null) { // logger.warning("Can't load icon \"" + _iconFileName + "\""); // return; // } // } gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); gl.glDisable(GL.GL_DEPTH_TEST); // Load a parallel projection with xy dimensions (viewportWidth, viewportHeight) // into the GL projection matrix. final Rectangle viewport = dc.getView().getViewport(); gl.glMatrixMode(GL.GL_PROJECTION); gl.glPushMatrix(); projectionPushed = true; gl.glLoadIdentity(); final double maxwh = (_textureWidth > _textureHeight) ? _textureWidth : _textureHeight; gl.glOrtho(0d, viewport.width, 0d, viewport.height, -0.6 * maxwh, 0.6 * maxwh); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glPushMatrix(); modelviewPushed = true; gl.glLoadIdentity(); // Translate and scale final float scale = computeScale(viewport); final Vec4 locationSW = computeLocation(viewport, scale); gl.glTranslated(locationSW.x(), locationSW.y(), locationSW.z()); // Scale to 0..1 space gl.glScalef(scale, scale, 1f); gl.glScaled(_textureWidth, _textureHeight, 1d); _lastScreenBounds = calculateScreenBounds(viewport, locationSW, scale); if (!dc.isPickingMode()) { gl.glEnable(GL.GL_TEXTURE_2D); _texture.bind(); - gl.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_DECAL); + gl.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_MODULATE); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR_MIPMAP_LINEAR); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE); gl.glColor4f(1, 1, 1, calculateOpacity()); final TextureCoords texCoords = _texture.getImageTexCoords(); dc.drawUnitQuad(texCoords); } } finally { if (projectionPushed) { gl.glMatrixMode(GL.GL_PROJECTION); gl.glPopMatrix(); } if (modelviewPushed) { gl.glMatrixMode(GL.GL_MODELVIEW); gl.glPopMatrix(); } if (attribsPushed) { gl.glPopAttrib(); } } } private float computeScale(final Rectangle viewport) { return Math.min(1, (float) viewport.width / _textureWidth) * (_highlighted ? 1.15f : 1f); } private Rectangle calculateScreenBounds(final Rectangle viewport, final Vec4 position, final float scale) { final int iWidth = toInt(_textureWidth * scale); final int iHeight = toInt(_textureHeight * scale); final int iX = toInt(position.x); final int iY = viewport.height - iHeight - toInt(position.y); return new Rectangle(iX, iY, iWidth, iHeight); } private static int toInt(final double value) { return GMath.toInt(Math.round(value)); } private Vec4 computeLocation(final Rectangle viewport, final float scale) { final double width = _textureWidth; final double height = _textureHeight; final double scaledWidth = scale * width; final double scaledHeight = scale * height; double x = 0; double y = 0; switch (_position) { case NORTHEAST: x = viewport.getWidth() - scaledWidth - _borderWidth; y = viewport.getHeight() - scaledHeight - _borderHeight; break; case SOUTHEAST: x = viewport.getWidth() - scaledWidth - _borderWidth; y = 0d + _borderHeight; break; case NORTHWEST: x = 0d + _borderWidth; y = viewport.getHeight() - scaledHeight - _borderHeight; break; case SOUTHWEST: x = 0d + _borderWidth; y = 0d + _borderHeight; break; } return new Vec4(x, y, 0); } public float getOpacity() { return _opacity; } private float calculateOpacity() { if (_highlighted) { return 1.0f; } return _opacity; } public void setOpacity(final float opacity) { _opacity = opacity; } public int getBorderWidth() { return _borderWidth; } public void setBorderWidth(final int borderWidth) { _borderWidth = borderWidth; } public int getBorderHeight() { return _borderHeight; } public void setBorderHeight(final int borderHeight) { _borderHeight = borderHeight; } @Override public boolean isEnable() { return _isEnable; } public void setEnable(final boolean isEnable) { _isEnable = isEnable; } public void setDistanceFromEye(final double distanceFromEye) { _distanceFromEye = distanceFromEye; } @Override public String toString() { return "GHUDIcon [texture=" + _texture + ", position=" + _position + "]"; } @Override public Rectangle getLastScreenBounds() { return _lastScreenBounds; } @Override public void setHighlighted(final boolean highlighted) { _highlighted = highlighted; } @Override public boolean hasActionListeners() { return (_actionListeners != null) && !_actionListeners.isEmpty(); } @Override public void mouseClicked(final MouseEvent evt) { if (_actionListeners != null) { for (final ActionListener listener : _actionListeners) { final ActionEvent actionEvent = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null, evt.getWhen(), 0); listener.actionPerformed(actionEvent); } } } public void removeActionListener(final ActionListener listener) { if (_actionListeners == null) { return; } _actionListeners.remove(listener); if (_actionListeners.isEmpty()) { _actionListeners = null; } } public void addActionListener(final ActionListener listener) { if (_actionListeners == null) { _actionListeners = new ArrayList<ActionListener>(2); } _actionListeners.add(listener); } public void setImage(final BufferedImage image) { _image = image; _texture = null; } }
true
true
private void drawIcon(final DrawContext dc) { if (_texture == null) { _texture = TextureIO.newTexture(_image, true); if (_texture == null) { return; } _textureWidth = _texture.getWidth(); _textureHeight = _texture.getHeight(); } final GL gl = dc.getGL(); boolean attribsPushed = false; boolean modelviewPushed = false; boolean projectionPushed = false; try { gl.glPushAttrib(GL.GL_DEPTH_BUFFER_BIT | GL.GL_COLOR_BUFFER_BIT | GL.GL_ENABLE_BIT | GL.GL_TEXTURE_BIT | GL.GL_TRANSFORM_BIT | GL.GL_VIEWPORT_BIT | GL.GL_CURRENT_BIT); attribsPushed = true; // // Initialize texture if not done yet // Texture iconTexture = dc.getTextureCache().get(_iconFileName); // if (iconTexture == null) { // initializeTexture(dc); // iconTexture = dc.getTextureCache().get(_iconFileName); // if (iconTexture == null) { // logger.warning("Can't load icon \"" + _iconFileName + "\""); // return; // } // } gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); gl.glDisable(GL.GL_DEPTH_TEST); // Load a parallel projection with xy dimensions (viewportWidth, viewportHeight) // into the GL projection matrix. final Rectangle viewport = dc.getView().getViewport(); gl.glMatrixMode(GL.GL_PROJECTION); gl.glPushMatrix(); projectionPushed = true; gl.glLoadIdentity(); final double maxwh = (_textureWidth > _textureHeight) ? _textureWidth : _textureHeight; gl.glOrtho(0d, viewport.width, 0d, viewport.height, -0.6 * maxwh, 0.6 * maxwh); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glPushMatrix(); modelviewPushed = true; gl.glLoadIdentity(); // Translate and scale final float scale = computeScale(viewport); final Vec4 locationSW = computeLocation(viewport, scale); gl.glTranslated(locationSW.x(), locationSW.y(), locationSW.z()); // Scale to 0..1 space gl.glScalef(scale, scale, 1f); gl.glScaled(_textureWidth, _textureHeight, 1d); _lastScreenBounds = calculateScreenBounds(viewport, locationSW, scale); if (!dc.isPickingMode()) { gl.glEnable(GL.GL_TEXTURE_2D); _texture.bind(); gl.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_DECAL); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR_MIPMAP_LINEAR); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE); gl.glColor4f(1, 1, 1, calculateOpacity()); final TextureCoords texCoords = _texture.getImageTexCoords(); dc.drawUnitQuad(texCoords); } } finally { if (projectionPushed) { gl.glMatrixMode(GL.GL_PROJECTION); gl.glPopMatrix(); } if (modelviewPushed) { gl.glMatrixMode(GL.GL_MODELVIEW); gl.glPopMatrix(); } if (attribsPushed) { gl.glPopAttrib(); } } }
private void drawIcon(final DrawContext dc) { if (_texture == null) { _texture = TextureIO.newTexture(_image, true); if (_texture == null) { return; } _textureWidth = _texture.getWidth(); _textureHeight = _texture.getHeight(); } final GL gl = dc.getGL(); boolean attribsPushed = false; boolean modelviewPushed = false; boolean projectionPushed = false; try { gl.glPushAttrib(GL.GL_DEPTH_BUFFER_BIT | GL.GL_COLOR_BUFFER_BIT | GL.GL_ENABLE_BIT | GL.GL_TEXTURE_BIT | GL.GL_TRANSFORM_BIT | GL.GL_VIEWPORT_BIT | GL.GL_CURRENT_BIT); attribsPushed = true; // // Initialize texture if not done yet // Texture iconTexture = dc.getTextureCache().get(_iconFileName); // if (iconTexture == null) { // initializeTexture(dc); // iconTexture = dc.getTextureCache().get(_iconFileName); // if (iconTexture == null) { // logger.warning("Can't load icon \"" + _iconFileName + "\""); // return; // } // } gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); gl.glDisable(GL.GL_DEPTH_TEST); // Load a parallel projection with xy dimensions (viewportWidth, viewportHeight) // into the GL projection matrix. final Rectangle viewport = dc.getView().getViewport(); gl.glMatrixMode(GL.GL_PROJECTION); gl.glPushMatrix(); projectionPushed = true; gl.glLoadIdentity(); final double maxwh = (_textureWidth > _textureHeight) ? _textureWidth : _textureHeight; gl.glOrtho(0d, viewport.width, 0d, viewport.height, -0.6 * maxwh, 0.6 * maxwh); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glPushMatrix(); modelviewPushed = true; gl.glLoadIdentity(); // Translate and scale final float scale = computeScale(viewport); final Vec4 locationSW = computeLocation(viewport, scale); gl.glTranslated(locationSW.x(), locationSW.y(), locationSW.z()); // Scale to 0..1 space gl.glScalef(scale, scale, 1f); gl.glScaled(_textureWidth, _textureHeight, 1d); _lastScreenBounds = calculateScreenBounds(viewport, locationSW, scale); if (!dc.isPickingMode()) { gl.glEnable(GL.GL_TEXTURE_2D); _texture.bind(); gl.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_MODULATE); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR_MIPMAP_LINEAR); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE); gl.glColor4f(1, 1, 1, calculateOpacity()); final TextureCoords texCoords = _texture.getImageTexCoords(); dc.drawUnitQuad(texCoords); } } finally { if (projectionPushed) { gl.glMatrixMode(GL.GL_PROJECTION); gl.glPopMatrix(); } if (modelviewPushed) { gl.glMatrixMode(GL.GL_MODELVIEW); gl.glPopMatrix(); } if (attribsPushed) { gl.glPopAttrib(); } } }
diff --git a/test/src/org/bouncycastle/asn1/test/EqualsAndHashCodeTest.java b/test/src/org/bouncycastle/asn1/test/EqualsAndHashCodeTest.java index 1a3ff3d9..5fc751b3 100644 --- a/test/src/org/bouncycastle/asn1/test/EqualsAndHashCodeTest.java +++ b/test/src/org/bouncycastle/asn1/test/EqualsAndHashCodeTest.java @@ -1,130 +1,130 @@ package org.bouncycastle.asn1.test; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1OutputStream; import org.bouncycastle.asn1.BERConstructedOctetString; import org.bouncycastle.asn1.BERSequence; import org.bouncycastle.asn1.BERSet; import org.bouncycastle.asn1.BERTaggedObject; import org.bouncycastle.asn1.DERApplicationSpecific; import org.bouncycastle.asn1.DERBMPString; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.DERBoolean; import org.bouncycastle.asn1.DEREnumerated; import org.bouncycastle.asn1.DERGeneralString; import org.bouncycastle.asn1.DERGeneralizedTime; import org.bouncycastle.asn1.DERIA5String; import org.bouncycastle.asn1.DERInteger; import org.bouncycastle.asn1.DERNull; import org.bouncycastle.asn1.DERNumericString; import org.bouncycastle.asn1.DERObject; import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERPrintableString; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.DERSet; import org.bouncycastle.asn1.DERT61String; import org.bouncycastle.asn1.DERTaggedObject; import org.bouncycastle.asn1.DERTags; import org.bouncycastle.asn1.DERUTCTime; import org.bouncycastle.asn1.DERUTF8String; import org.bouncycastle.asn1.DERUniversalString; import org.bouncycastle.asn1.DERUnknownTag; import org.bouncycastle.asn1.DERVisibleString; import org.bouncycastle.util.test.SimpleTestResult; import org.bouncycastle.util.test.Test; import org.bouncycastle.util.test.TestResult; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.Date; public class EqualsAndHashCodeTest implements Test { public TestResult perform() { byte[] data = { 0, 1, 0, 1, 0, 0, 1 }; DERObject values[] = { new BERConstructedOctetString(data), new BERSequence(new DERPrintableString("hello world")), new BERSet(new DERPrintableString("hello world")), new BERTaggedObject(0, new DERPrintableString("hello world")), new DERApplicationSpecific(0, data), new DERBitString(data), new DERBMPString("hello world"), new DERBoolean(true), new DERBoolean(false), new DEREnumerated(100), new DERGeneralizedTime("20070315173729Z"), new DERGeneralString("hello world"), new DERIA5String("hello"), new DERInteger(1000), new DERNull(), new DERNumericString("123456"), new DERObjectIdentifier("1.1.1.10000.1"), new DEROctetString(data), new DERPrintableString("hello world"), new DERSequence(new DERPrintableString("hello world")), new DERSet(new DERPrintableString("hello world")), new DERT61String("hello world"), new DERTaggedObject(0, new DERPrintableString("hello world")), new DERUniversalString(data), new DERUnknownTag(0xff & (~(DERTags.TAGGED | DERTags.APPLICATION)), data), new DERUTCTime(new Date()), new DERUTF8String("hello world"), new DERVisibleString("hello world") }; try { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream aOut = new ASN1OutputStream(bOut); for (int i = 0; i != values.length; i++) { aOut.writeObject(values[i]); } DERObject[] readValues = new DERObject[values.length]; ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); ASN1InputStream aIn = new ASN1InputStream(bIn); for (int i = 0; i != values.length; i++) { DERObject o = aIn.readObject(); if (!o.equals(values[i])) { - return new SimpleTestResult(false, getName() + ": Failed equality test for " + o); + return new SimpleTestResult(false, getName() + ": Failed equality test for " + o.getClass()); } if (o.hashCode() != values[i].hashCode()) { - return new SimpleTestResult(false, getName() + ": Failed hashCode test for " + o); + return new SimpleTestResult(false, getName() + ": Failed hashCode test for " + o.getClass()); } } } catch (Exception e) { return new SimpleTestResult(false, getName() + ": Failed - exception " + e.toString(), e); } return new SimpleTestResult(true, getName() + ": Okay"); } public String getName() { return "EqualsAndHashCode"; } public static void main( String[] args) { EqualsAndHashCodeTest test = new EqualsAndHashCodeTest(); TestResult result = test.perform(); System.out.println(result); } }
false
true
public TestResult perform() { byte[] data = { 0, 1, 0, 1, 0, 0, 1 }; DERObject values[] = { new BERConstructedOctetString(data), new BERSequence(new DERPrintableString("hello world")), new BERSet(new DERPrintableString("hello world")), new BERTaggedObject(0, new DERPrintableString("hello world")), new DERApplicationSpecific(0, data), new DERBitString(data), new DERBMPString("hello world"), new DERBoolean(true), new DERBoolean(false), new DEREnumerated(100), new DERGeneralizedTime("20070315173729Z"), new DERGeneralString("hello world"), new DERIA5String("hello"), new DERInteger(1000), new DERNull(), new DERNumericString("123456"), new DERObjectIdentifier("1.1.1.10000.1"), new DEROctetString(data), new DERPrintableString("hello world"), new DERSequence(new DERPrintableString("hello world")), new DERSet(new DERPrintableString("hello world")), new DERT61String("hello world"), new DERTaggedObject(0, new DERPrintableString("hello world")), new DERUniversalString(data), new DERUnknownTag(0xff & (~(DERTags.TAGGED | DERTags.APPLICATION)), data), new DERUTCTime(new Date()), new DERUTF8String("hello world"), new DERVisibleString("hello world") }; try { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream aOut = new ASN1OutputStream(bOut); for (int i = 0; i != values.length; i++) { aOut.writeObject(values[i]); } DERObject[] readValues = new DERObject[values.length]; ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); ASN1InputStream aIn = new ASN1InputStream(bIn); for (int i = 0; i != values.length; i++) { DERObject o = aIn.readObject(); if (!o.equals(values[i])) { return new SimpleTestResult(false, getName() + ": Failed equality test for " + o); } if (o.hashCode() != values[i].hashCode()) { return new SimpleTestResult(false, getName() + ": Failed hashCode test for " + o); } } } catch (Exception e) { return new SimpleTestResult(false, getName() + ": Failed - exception " + e.toString(), e); } return new SimpleTestResult(true, getName() + ": Okay"); }
public TestResult perform() { byte[] data = { 0, 1, 0, 1, 0, 0, 1 }; DERObject values[] = { new BERConstructedOctetString(data), new BERSequence(new DERPrintableString("hello world")), new BERSet(new DERPrintableString("hello world")), new BERTaggedObject(0, new DERPrintableString("hello world")), new DERApplicationSpecific(0, data), new DERBitString(data), new DERBMPString("hello world"), new DERBoolean(true), new DERBoolean(false), new DEREnumerated(100), new DERGeneralizedTime("20070315173729Z"), new DERGeneralString("hello world"), new DERIA5String("hello"), new DERInteger(1000), new DERNull(), new DERNumericString("123456"), new DERObjectIdentifier("1.1.1.10000.1"), new DEROctetString(data), new DERPrintableString("hello world"), new DERSequence(new DERPrintableString("hello world")), new DERSet(new DERPrintableString("hello world")), new DERT61String("hello world"), new DERTaggedObject(0, new DERPrintableString("hello world")), new DERUniversalString(data), new DERUnknownTag(0xff & (~(DERTags.TAGGED | DERTags.APPLICATION)), data), new DERUTCTime(new Date()), new DERUTF8String("hello world"), new DERVisibleString("hello world") }; try { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream aOut = new ASN1OutputStream(bOut); for (int i = 0; i != values.length; i++) { aOut.writeObject(values[i]); } DERObject[] readValues = new DERObject[values.length]; ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); ASN1InputStream aIn = new ASN1InputStream(bIn); for (int i = 0; i != values.length; i++) { DERObject o = aIn.readObject(); if (!o.equals(values[i])) { return new SimpleTestResult(false, getName() + ": Failed equality test for " + o.getClass()); } if (o.hashCode() != values[i].hashCode()) { return new SimpleTestResult(false, getName() + ": Failed hashCode test for " + o.getClass()); } } } catch (Exception e) { return new SimpleTestResult(false, getName() + ": Failed - exception " + e.toString(), e); } return new SimpleTestResult(true, getName() + ": Okay"); }
diff --git a/src/main/java/org/glom/web/server/ConfiguredDocument.java b/src/main/java/org/glom/web/server/ConfiguredDocument.java index 37de086..562a030 100644 --- a/src/main/java/org/glom/web/server/ConfiguredDocument.java +++ b/src/main/java/org/glom/web/server/ConfiguredDocument.java @@ -1,687 +1,687 @@ /* * Copyright (C) 2011 Openismus GmbH * * This file is part of GWT-Glom. * * GWT-Glom is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * GWT-Glom is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with GWT-Glom. If not, see <http://www.gnu.org/licenses/>. */ package org.glom.web.server; import java.beans.PropertyVetoException; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import org.glom.libglom.Document; import org.glom.libglom.Field; import org.glom.libglom.FieldFormatting; import org.glom.libglom.FieldVector; import org.glom.libglom.Glom; import org.glom.libglom.LayoutGroupVector; import org.glom.libglom.LayoutItemVector; import org.glom.libglom.LayoutItem_Field; import org.glom.libglom.LayoutItem_Notebook; import org.glom.libglom.LayoutItem_Portal; import org.glom.libglom.NumericFormat; import org.glom.libglom.Relationship; import org.glom.libglom.StringVector; import org.glom.web.server.database.DetailsDBAccess; import org.glom.web.server.database.ListViewDBAccess; import org.glom.web.server.database.RelatedListDBAccess; import org.glom.web.server.database.RelatedListNavigation; import org.glom.web.shared.DataItem; import org.glom.web.shared.DocumentInfo; import org.glom.web.shared.GlomNumericFormat; import org.glom.web.shared.NavigationRecord; import org.glom.web.shared.layout.Formatting; import org.glom.web.shared.layout.LayoutGroup; import org.glom.web.shared.layout.LayoutItem; import org.glom.web.shared.layout.LayoutItemField; import org.glom.web.shared.layout.LayoutItemNotebook; import org.glom.web.shared.layout.LayoutItemPortal; import com.mchange.v2.c3p0.ComboPooledDataSource; /** * A class to hold configuration information for a given Glom document. This class is used to retrieve layout * information from libglom and data from the underlying PostgreSQL database. * * @author Ben Konrath <[email protected]> * */ final class ConfiguredDocument { private Document document; private ComboPooledDataSource cpds; private boolean authenticated = false; private String documentID; @SuppressWarnings("unused") private ConfiguredDocument() { // disable default constructor } ConfiguredDocument(Document document) throws PropertyVetoException { // load the jdbc driver cpds = new ComboPooledDataSource(); // We don't support sqlite or self-hosting yet. if (document.get_hosting_mode() != Document.HostingMode.HOSTING_MODE_POSTGRES_CENTRAL) { Log.fatal("Error configuring the database connection." + " Only central PostgreSQL hosting is supported."); // FIXME: Throw exception? } try { cpds.setDriverClass("org.postgresql.Driver"); } catch (PropertyVetoException e) { Log.fatal("Error loading the PostgreSQL JDBC driver." + " Is the PostgreSQL JDBC jar available to the servlet?", e); throw e; } // setup the JDBC driver for the current glom document cpds.setJdbcUrl("jdbc:postgresql://" + document.get_connection_server() + ":" + document.get_connection_port() + "/" + document.get_connection_database()); this.document = document; } /** * Sets the username and password for the database associated with the Glom document. * * @return true if the username and password works, false otherwise */ boolean setUsernameAndPassword(String username, String password) throws SQLException { cpds.setUser(username); cpds.setPassword(password); int acquireRetryAttempts = cpds.getAcquireRetryAttempts(); cpds.setAcquireRetryAttempts(1); Connection conn = null; try { // FIXME find a better way to check authentication // it's possible that the connection could be failing for another reason conn = cpds.getConnection(); authenticated = true; } catch (SQLException e) { Log.info(Utils.getFileName(document.get_file_uri()), e.getMessage()); Log.info(Utils.getFileName(document.get_file_uri()), "Connection Failed. Maybe the username or password is not correct."); authenticated = false; } finally { if (conn != null) conn.close(); cpds.setAcquireRetryAttempts(acquireRetryAttempts); } return authenticated; } Document getDocument() { return document; } ComboPooledDataSource getCpds() { return cpds; } boolean isAuthenticated() { return authenticated; } String getDocumentID() { return documentID; } void setDocumentID(String documentID) { this.documentID = documentID; } /** * @return */ DocumentInfo getDocumentInfo() { DocumentInfo documentInfo = new DocumentInfo(); // get arrays of table names and titles, and find the default table index StringVector tablesVec = document.get_table_names(); int numTables = Utils.safeLongToInt(tablesVec.size()); // we don't know how many tables will be hidden so we'll use half of the number of tables for the default size // of the ArrayList ArrayList<String> tableNames = new ArrayList<String>(numTables / 2); ArrayList<String> tableTitles = new ArrayList<String>(numTables / 2); boolean foundDefaultTable = false; int visibleIndex = 0; for (int i = 0; i < numTables; i++) { String tableName = tablesVec.get(i); if (!document.get_table_is_hidden(tableName)) { tableNames.add(tableName); // JNI is "expensive", the comparison will only be called if we haven't already found the default table if (!foundDefaultTable && tableName.equals(document.get_default_table())) { documentInfo.setDefaultTableIndex(visibleIndex); foundDefaultTable = true; } tableTitles.add(document.get_table_title(tableName)); visibleIndex++; } } // set everything we need documentInfo.setTableNames(tableNames); documentInfo.setTableTitles(tableTitles); documentInfo.setTitle(document.get_database_title()); return documentInfo; } /* * Gets the layout group for the list view using the defined layout list in the document or the table fields if * there's no defined layout group for the list view. */ private org.glom.libglom.LayoutGroup getValidListViewLayoutGroup(String tableName) { LayoutGroupVector layoutGroupVec = document.get_data_layout_groups("list", tableName); int listViewLayoutGroupSize = Utils.safeLongToInt(layoutGroupVec.size()); org.glom.libglom.LayoutGroup libglomLayoutGroup = null; if (listViewLayoutGroupSize > 0) { // a list layout group is defined; we can use the first group as the list if (listViewLayoutGroupSize > 1) Log.warn(documentID, tableName, "The size of the list layout group is greater than 1. " + "Attempting to use the first item for the layout list view."); libglomLayoutGroup = layoutGroupVec.get(0); } else { // a list layout group is *not* defined; we are going make a libglom layout group from the list of fields Log.info(documentID, tableName, "A list layout is not defined for this table. Displaying a list layout based on the field list."); FieldVector fieldsVec = document.get_table_fields(tableName); libglomLayoutGroup = new org.glom.libglom.LayoutGroup(); for (int i = 0; i < fieldsVec.size(); i++) { Field field = fieldsVec.get(i); LayoutItem_Field layoutItemField = new LayoutItem_Field(); layoutItemField.set_full_field_details(field); libglomLayoutGroup.add_item(layoutItemField); } } return libglomLayoutGroup; } ArrayList<DataItem[]> getListViewData(String tableName, int start, int length, boolean useSortClause, int sortColumnIndex, boolean isAscending) { // Validate the table name. tableName = getTableNameToUse(tableName); // Get the libglom LayoutGroup that represents the list view. org.glom.libglom.LayoutGroup libglomLayoutGroup = getValidListViewLayoutGroup(tableName); // Create a database access object for the list view. ListViewDBAccess listViewDBAccess = new ListViewDBAccess(document, documentID, cpds, tableName, libglomLayoutGroup); // Return the data. return listViewDBAccess.getData(start, length, useSortClause, sortColumnIndex, isAscending); } DataItem[] getDetailsData(String tableName, String primaryKeyValue) { // Validate the table name. tableName = getTableNameToUse(tableName); DetailsDBAccess detailsDBAccess = new DetailsDBAccess(document, documentID, cpds, tableName); return detailsDBAccess.getData(primaryKeyValue); } ArrayList<DataItem[]> getRelatedListData(String tableName, String relationshipName, String foreignKeyValue, int start, int length, boolean useSortClause, int sortColumnIndex, boolean isAscending) { // Validate the table name. tableName = getTableNameToUse(tableName); // Create a database access object for the related list RelatedListDBAccess relatedListDBAccess = new RelatedListDBAccess(document, documentID, cpds, tableName, relationshipName); // Return the data return relatedListDBAccess.getData(start, length, foreignKeyValue, useSortClause, sortColumnIndex, isAscending); } ArrayList<LayoutGroup> getDetailsLayoutGroup(String tableName) { // Validate the table name. tableName = getTableNameToUse(tableName); // Get the details layout group information for each LayoutGroup in the LayoutGroupVector LayoutGroupVector layoutGroupVec = document.get_data_layout_groups("details", tableName); ArrayList<LayoutGroup> layoutGroups = new ArrayList<LayoutGroup>(); for (int i = 0; i < layoutGroupVec.size(); i++) { org.glom.libglom.LayoutGroup libglomLayoutGroup = layoutGroupVec.get(i); // satisfy the precondition of getDetailsLayoutGroup(String, org.glom.libglom.LayoutGroup) if (libglomLayoutGroup == null) continue; layoutGroups.add(getDetailsLayoutGroup(tableName, libglomLayoutGroup)); } return layoutGroups; } LayoutGroup getListViewLayoutGroup(String tableName) { // Validate the table name. tableName = getTableNameToUse(tableName); org.glom.libglom.LayoutGroup libglomLayoutGroup = getValidListViewLayoutGroup(tableName); return getListLayoutGroup(tableName, libglomLayoutGroup); } /* * Gets the expected row count for a related list. */ int getRelatedListRowCount(String tableName, String relationshipName, String foreignKeyValue) { // Validate the table name. tableName = getTableNameToUse(tableName); // Create a database access object for the related list RelatedListDBAccess relatedListDBAccess = new RelatedListDBAccess(document, documentID, cpds, tableName, relationshipName); // Return the row count return relatedListDBAccess.getExpectedResultSize(foreignKeyValue); } NavigationRecord getSuitableRecordToViewDetails(String tableName, String relationshipName, String primaryKeyValue) { // Validate the table name. tableName = getTableNameToUse(tableName); RelatedListNavigation relatedListNavigation = new RelatedListNavigation(document, documentID, cpds, tableName, relationshipName); return relatedListNavigation.getNavigationRecord(primaryKeyValue); } /* * Gets a LayoutGroup DTO for the given table name and libglom LayoutGroup. This method can be used for the main * list view table and for the related list table. */ private LayoutGroup getListLayoutGroup(String tableName, org.glom.libglom.LayoutGroup libglomLayoutGroup) { LayoutGroup layoutGroup = new LayoutGroup(); int primaryKeyIndex = -1; // look at each child item LayoutItemVector layoutItemsVec = libglomLayoutGroup.get_items(); int numItems = Utils.safeLongToInt(layoutItemsVec.size()); for (int i = 0; i < numItems; i++) { org.glom.libglom.LayoutItem libglomLayoutItem = layoutItemsVec.get(i); // TODO add support for other LayoutItems (Text, Image, Button etc.) LayoutItem_Field libglomLayoutItemField = LayoutItem_Field.cast_dynamic(libglomLayoutItem); if (libglomLayoutItemField != null) { layoutGroup.addItem(convertToGWTGlomLayoutItemField(libglomLayoutItemField, true)); Field field = libglomLayoutItemField.get_full_field_details(); if (field.get_primary_key()) primaryKeyIndex = i; } else { Log.info(documentID, tableName, "Ignoring unknown list LayoutItem of type " + libglomLayoutItem.get_part_type_name() + "."); continue; } } // set the expected result size for list view tables LayoutItem_Portal libglomLayoutItemPortal = LayoutItem_Portal.cast_dynamic(libglomLayoutGroup); if (libglomLayoutItemPortal == null) { // libglomLayoutGroup is a list view ListViewDBAccess listViewDBAccess = new ListViewDBAccess(document, documentID, cpds, tableName, libglomLayoutGroup); layoutGroup.setExpectedResultSize(listViewDBAccess.getExpectedResultSize()); } // Set the primary key index for the table if (primaryKeyIndex < 0) { // Add a LayoutItemField for the primary key to the end of the item list in the LayoutGroup because it // doesn't already contain a primary key. Field primaryKey = null; FieldVector fieldsVec = document.get_table_fields(tableName); for (int i = 0; i < Utils.safeLongToInt(fieldsVec.size()); i++) { Field field = fieldsVec.get(i); if (field.get_primary_key()) { primaryKey = field; break; } } if (primaryKey != null) { LayoutItem_Field libglomLayoutItemField = new LayoutItem_Field(); libglomLayoutItemField.set_full_field_details(primaryKey); layoutGroup.addItem(convertToGWTGlomLayoutItemField(libglomLayoutItemField, false)); layoutGroup.setPrimaryKeyIndex(layoutGroup.getItems().size() - 1); layoutGroup.setHiddenPrimaryKey(true); } else { Log.error(document.get_database_title(), tableName, "A primary key was not found in the FieldVector for this table. Navigation buttons will not work."); } } else { layoutGroup.setPrimaryKeyIndex(primaryKeyIndex); } layoutGroup.setTableName(tableName); return layoutGroup; } /* * Gets a recursively defined Details LayoutGroup DTO for the specified libglom LayoutGroup object. This is used for * getting layout information for the details view. * * @param documentID Glom document identifier * * @param tableName table name in the specified Glom document * * @param libglomLayoutGroup libglom LayoutGroup to convert * * @precondition libglomLayoutGroup must not be null * * @return {@link LayoutGroup} object that represents the layout for the specified {@link * org.glom.libglom.LayoutGroup} */ private LayoutGroup getDetailsLayoutGroup(String tableName, org.glom.libglom.LayoutGroup libglomLayoutGroup) { LayoutGroup layoutGroup = new LayoutGroup(); layoutGroup.setColumnCount(Utils.safeLongToInt(libglomLayoutGroup.get_columns_count())); - layoutGroup.setTitle(libglomLayoutGroup.get_title()); + layoutGroup.setTitle(libglomLayoutGroup.get_title_or_name()); // look at each child item LayoutItemVector layoutItemsVec = libglomLayoutGroup.get_items(); for (int i = 0; i < layoutItemsVec.size(); i++) { org.glom.libglom.LayoutItem libglomLayoutItem = layoutItemsVec.get(i); // just a safety check if (libglomLayoutItem == null) continue; org.glom.web.shared.layout.LayoutItem layoutItem = null; org.glom.libglom.LayoutGroup group = org.glom.libglom.LayoutGroup.cast_dynamic(libglomLayoutItem); if (group != null) { // libglomLayoutItem is a LayoutGroup LayoutItem_Portal libglomLayoutItemPortal = LayoutItem_Portal.cast_dynamic(group); if (libglomLayoutItemPortal != null) { // group is a LayoutItem_Portal LayoutItemPortal layoutItemPortal = new LayoutItemPortal(); Relationship relationship = libglomLayoutItemPortal.get_relationship(); if (relationship != null) { layoutItemPortal.setNavigationType(convertToGWTGlomNavigationType(libglomLayoutItemPortal .get_navigation_type())); layoutItemPortal.setTitle(libglomLayoutItemPortal.get_title_used("")); // parent title not // relevant LayoutGroup tempLayoutGroup = getListLayoutGroup(tableName, libglomLayoutItemPortal); for (org.glom.web.shared.layout.LayoutItem item : tempLayoutGroup.getItems()) { // TODO EDITING If the relationship does not allow editing, then mark all these fields as // non-editable. Check relationship.get_allow_edit() to see if it's editable. layoutItemPortal.addItem(item); } layoutItemPortal.setPrimaryKeyIndex(tempLayoutGroup.getPrimaryKeyIndex()); layoutItemPortal.setHiddenPrimaryKey(tempLayoutGroup.hasHiddenPrimaryKey()); layoutItemPortal.setName(libglomLayoutItemPortal.get_relationship_name_used()); layoutItemPortal.setTableName(relationship.get_from_table()); layoutItemPortal.setFromField(relationship.get_from_field()); // Set whether or not the related list will need to show the navigation buttons. // This was ported from Glom: Box_Data_Portal::get_has_suitable_record_to_view_details() StringBuffer navigationTableName = new StringBuffer(); LayoutItem_Field navigationRelationship = new LayoutItem_Field(); // Ignored. libglomLayoutItemPortal.get_suitable_table_to_view_details(navigationTableName, navigationRelationship, document); layoutItemPortal.setAddNavigation(!(navigationTableName.toString().isEmpty())); } // Note: empty layoutItemPortal used if relationship is null layoutItem = layoutItemPortal; } else { // libglomLayoutItem is a LayoutGroup LayoutItem_Notebook libglomLayoutItemNotebook = LayoutItem_Notebook.cast_dynamic(group); if (libglomLayoutItemNotebook != null) { // group is a LayoutItem_Notebook LayoutGroup tempLayoutGroup = getDetailsLayoutGroup(tableName, libglomLayoutItemNotebook); LayoutItemNotebook layoutItemNotebook = new LayoutItemNotebook(); for (LayoutItem item : tempLayoutGroup.getItems()) { layoutItemNotebook.addItem(item); } layoutItemNotebook.setName(tableName); layoutItem = layoutItemNotebook; } else { // group is *not* a LayoutItem_Portal or a LayoutItem_Notebook // recurse into child groups layoutItem = getDetailsLayoutGroup(tableName, group); } } } else { // libglomLayoutItem is *not* a LayoutGroup // create LayoutItem DTOs based on the the libglom type // TODO add support for other LayoutItems (Text, Image, Button etc.) LayoutItem_Field libglomLayoutItemField = LayoutItem_Field.cast_dynamic(libglomLayoutItem); if (libglomLayoutItemField != null) { LayoutItemField layoutItemField = convertToGWTGlomLayoutItemField(libglomLayoutItemField, true); // Set the full field details with updated field details from the document. libglomLayoutItemField.set_full_field_details(document.get_field( libglomLayoutItemField.get_table_used(tableName), libglomLayoutItemField.get_name())); // Determine if the field should have a navigation button and set this in the DTO. Relationship fieldUsedInRelationshipToOne = new Relationship(); boolean addNavigation = Glom.layout_field_should_have_navigation(tableName, libglomLayoutItemField, document, fieldUsedInRelationshipToOne); layoutItemField.setAddNavigation(addNavigation); // Set the the name of the table to navigate to if navigation should be enabled. if (addNavigation) { // It's not possible to directly check if fieldUsedInRelationshipToOne is // null because of the way that the glom_sharedptr macro works. This workaround accomplishes the // same task. String tableNameUsed; try { Relationship temp = new Relationship(); temp.equals(fieldUsedInRelationshipToOne); // this will throw an NPE if // fieldUsedInRelationshipToOne is null // fieldUsedInRelationshipToOne is *not* null tableNameUsed = fieldUsedInRelationshipToOne.get_to_table(); } catch (NullPointerException e) { // fieldUsedInRelationshipToOne is null tableNameUsed = libglomLayoutItemField.get_table_used(tableName); } // Set the navigation table name only if it's not different than the current table name. if (!tableName.equals(tableNameUsed)) { layoutItemField.setNavigationTableName(tableNameUsed); } } layoutItem = layoutItemField; } else { Log.info(documentID, tableName, "Ignoring unknown details LayoutItem of type " + libglomLayoutItem.get_part_type_name() + "."); continue; } } layoutGroup.addItem(layoutItem); } return layoutGroup; } private GlomNumericFormat convertNumbericFormat(NumericFormat libglomNumericFormat) { GlomNumericFormat gnf = new GlomNumericFormat(); gnf.setUseAltForegroundColourForNegatives(libglomNumericFormat.getM_alt_foreground_color_for_negatives()); gnf.setCurrencyCode(libglomNumericFormat.getM_currency_symbol()); gnf.setDecimalPlaces(Utils.safeLongToInt(libglomNumericFormat.getM_decimal_places())); gnf.setDecimalPlacesRestricted(libglomNumericFormat.getM_decimal_places_restricted()); gnf.setUseThousandsSeparator(libglomNumericFormat.getM_use_thousands_separator()); return gnf; } private Formatting convertFormatting(FieldFormatting libglomFormatting) { Formatting formatting = new Formatting(); // horizontal alignment Formatting.HorizontalAlignment horizontalAlignment; switch (libglomFormatting.get_horizontal_alignment()) { case HORIZONTAL_ALIGNMENT_LEFT: horizontalAlignment = Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_LEFT; case HORIZONTAL_ALIGNMENT_RIGHT: horizontalAlignment = Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT; case HORIZONTAL_ALIGNMENT_AUTO: default: horizontalAlignment = Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_AUTO; } formatting.setHorizontalAlignment(horizontalAlignment); // text colour String foregroundColour = libglomFormatting.get_text_format_color_foreground(); if (foregroundColour != null && !foregroundColour.isEmpty()) formatting.setTextFormatColourForeground(convertGdkColorToHtmlColour(foregroundColour)); String backgroundColour = libglomFormatting.get_text_format_color_background(); if (backgroundColour != null && !backgroundColour.isEmpty()) formatting.setTextFormatColourBackground(convertGdkColorToHtmlColour(backgroundColour)); // multiline if (libglomFormatting.get_text_format_multiline()) { formatting.setTextFormatMultilineHeightLines(Utils.safeLongToInt(libglomFormatting .get_text_format_multiline_height_lines())); } return formatting; } private LayoutItemField convertToGWTGlomLayoutItemField(LayoutItem_Field libglomLayoutItemField, boolean includeFormatting) { LayoutItemField layoutItemField = new LayoutItemField(); // set type layoutItemField.setType(convertToGWTGlomFieldType(libglomLayoutItemField.get_glom_type())); // set title and name layoutItemField.setTitle(libglomLayoutItemField.get_title_or_name()); layoutItemField.setName(libglomLayoutItemField.get_name()); if (includeFormatting) { FieldFormatting glomFormatting = libglomLayoutItemField.get_formatting_used(); Formatting formatting = convertFormatting(glomFormatting); // create a GlomNumericFormat DTO for numeric values if (libglomLayoutItemField.get_glom_type() == org.glom.libglom.Field.glom_field_type.TYPE_NUMERIC) { formatting.setGlomNumericFormat(convertNumbericFormat(glomFormatting.getM_numeric_format())); } layoutItemField.setFormatting(formatting); } return layoutItemField; } /* * This method converts a Field.glom_field_type to the equivalent ColumnInfo.FieldType. The need for this comes from * the fact that the GWT FieldType classes can't be used with RPC and there's no easy way to use the java-libglom * Field.glom_field_type enum with RPC. An enum identical to FieldFormatting.glom_field_type is included in the * ColumnInfo class. */ private LayoutItemField.GlomFieldType convertToGWTGlomFieldType(Field.glom_field_type type) { switch (type) { case TYPE_BOOLEAN: return LayoutItemField.GlomFieldType.TYPE_BOOLEAN; case TYPE_DATE: return LayoutItemField.GlomFieldType.TYPE_DATE; case TYPE_IMAGE: return LayoutItemField.GlomFieldType.TYPE_IMAGE; case TYPE_NUMERIC: return LayoutItemField.GlomFieldType.TYPE_NUMERIC; case TYPE_TEXT: return LayoutItemField.GlomFieldType.TYPE_TEXT; case TYPE_TIME: return LayoutItemField.GlomFieldType.TYPE_TIME; case TYPE_INVALID: Log.info("Returning TYPE_INVALID."); return LayoutItemField.GlomFieldType.TYPE_INVALID; default: Log.error("Recieved a type that I don't know about: " + Field.glom_field_type.class.getName() + "." + type.toString() + ". Returning " + LayoutItemField.GlomFieldType.TYPE_INVALID.toString() + "."); return LayoutItemField.GlomFieldType.TYPE_INVALID; } } /* * Converts a Gdk::Color (16-bits per channel) to an HTML colour (8-bits per channel) by discarding the least * significant 8-bits in each channel. */ private String convertGdkColorToHtmlColour(String gdkColor) { if (gdkColor.length() == 13) return gdkColor.substring(0, 3) + gdkColor.substring(5, 7) + gdkColor.substring(9, 11); else if (gdkColor.length() == 7) { // This shouldn't happen but let's deal with it if it does. Log.warn(documentID, "Expected a 13 character string but received a 7 character string. Returning received string."); return gdkColor; } else { Log.error("Did not receive a 13 or 7 character string. Returning black HTML colour code."); return "#000000"; } } /* * This method converts a LayoutItem_Portal.navigation_type from java-libglom to the equivalent * LayoutItemPortal.NavigationType from Online Glom. This conversion is required because the LayoutItem_Portal class * from java-libglom can't be used with GWT-RPC. An enum identical to LayoutItem_Portal.navigation_type from * java-libglom is included in the LayoutItemPortal data transfer object. */ private LayoutItemPortal.NavigationType convertToGWTGlomNavigationType( LayoutItem_Portal.navigation_type navigationType) { switch (navigationType) { case NAVIGATION_NONE: return LayoutItemPortal.NavigationType.NAVIGATION_NONE; case NAVIGATION_AUTOMATIC: return LayoutItemPortal.NavigationType.NAVIGATION_AUTOMATIC; case NAVIGATION_SPECIFIC: return LayoutItemPortal.NavigationType.NAVIGATION_SPECIFIC; default: Log.error("Recieved an unknown NavigationType: " + LayoutItem_Portal.navigation_type.class.getName() + "." + navigationType.toString() + ". Returning " + LayoutItemPortal.NavigationType.NAVIGATION_AUTOMATIC + "."); return LayoutItemPortal.NavigationType.NAVIGATION_AUTOMATIC; } } /** * Gets the table name to use when accessing the database and the document. This method guards against SQL injection * attacks by returning the default table if the requested table is not in the database or if the table name has not * been set. * * @param tableName * The table name to validate. * @return The table name to use. */ private String getTableNameToUse(String tableName) { if (tableName == null || tableName.isEmpty() || !document.get_table_is_known(tableName)) { return document.get_default_table(); } return tableName; } }
true
true
private LayoutGroup getDetailsLayoutGroup(String tableName, org.glom.libglom.LayoutGroup libglomLayoutGroup) { LayoutGroup layoutGroup = new LayoutGroup(); layoutGroup.setColumnCount(Utils.safeLongToInt(libglomLayoutGroup.get_columns_count())); layoutGroup.setTitle(libglomLayoutGroup.get_title()); // look at each child item LayoutItemVector layoutItemsVec = libglomLayoutGroup.get_items(); for (int i = 0; i < layoutItemsVec.size(); i++) { org.glom.libglom.LayoutItem libglomLayoutItem = layoutItemsVec.get(i); // just a safety check if (libglomLayoutItem == null) continue; org.glom.web.shared.layout.LayoutItem layoutItem = null; org.glom.libglom.LayoutGroup group = org.glom.libglom.LayoutGroup.cast_dynamic(libglomLayoutItem); if (group != null) { // libglomLayoutItem is a LayoutGroup LayoutItem_Portal libglomLayoutItemPortal = LayoutItem_Portal.cast_dynamic(group); if (libglomLayoutItemPortal != null) { // group is a LayoutItem_Portal LayoutItemPortal layoutItemPortal = new LayoutItemPortal(); Relationship relationship = libglomLayoutItemPortal.get_relationship(); if (relationship != null) { layoutItemPortal.setNavigationType(convertToGWTGlomNavigationType(libglomLayoutItemPortal .get_navigation_type())); layoutItemPortal.setTitle(libglomLayoutItemPortal.get_title_used("")); // parent title not // relevant LayoutGroup tempLayoutGroup = getListLayoutGroup(tableName, libglomLayoutItemPortal); for (org.glom.web.shared.layout.LayoutItem item : tempLayoutGroup.getItems()) { // TODO EDITING If the relationship does not allow editing, then mark all these fields as // non-editable. Check relationship.get_allow_edit() to see if it's editable. layoutItemPortal.addItem(item); } layoutItemPortal.setPrimaryKeyIndex(tempLayoutGroup.getPrimaryKeyIndex()); layoutItemPortal.setHiddenPrimaryKey(tempLayoutGroup.hasHiddenPrimaryKey()); layoutItemPortal.setName(libglomLayoutItemPortal.get_relationship_name_used()); layoutItemPortal.setTableName(relationship.get_from_table()); layoutItemPortal.setFromField(relationship.get_from_field()); // Set whether or not the related list will need to show the navigation buttons. // This was ported from Glom: Box_Data_Portal::get_has_suitable_record_to_view_details() StringBuffer navigationTableName = new StringBuffer(); LayoutItem_Field navigationRelationship = new LayoutItem_Field(); // Ignored. libglomLayoutItemPortal.get_suitable_table_to_view_details(navigationTableName, navigationRelationship, document); layoutItemPortal.setAddNavigation(!(navigationTableName.toString().isEmpty())); } // Note: empty layoutItemPortal used if relationship is null layoutItem = layoutItemPortal; } else { // libglomLayoutItem is a LayoutGroup LayoutItem_Notebook libglomLayoutItemNotebook = LayoutItem_Notebook.cast_dynamic(group); if (libglomLayoutItemNotebook != null) { // group is a LayoutItem_Notebook LayoutGroup tempLayoutGroup = getDetailsLayoutGroup(tableName, libglomLayoutItemNotebook); LayoutItemNotebook layoutItemNotebook = new LayoutItemNotebook(); for (LayoutItem item : tempLayoutGroup.getItems()) { layoutItemNotebook.addItem(item); } layoutItemNotebook.setName(tableName); layoutItem = layoutItemNotebook; } else { // group is *not* a LayoutItem_Portal or a LayoutItem_Notebook // recurse into child groups layoutItem = getDetailsLayoutGroup(tableName, group); } } } else { // libglomLayoutItem is *not* a LayoutGroup // create LayoutItem DTOs based on the the libglom type // TODO add support for other LayoutItems (Text, Image, Button etc.) LayoutItem_Field libglomLayoutItemField = LayoutItem_Field.cast_dynamic(libglomLayoutItem); if (libglomLayoutItemField != null) { LayoutItemField layoutItemField = convertToGWTGlomLayoutItemField(libglomLayoutItemField, true); // Set the full field details with updated field details from the document. libglomLayoutItemField.set_full_field_details(document.get_field( libglomLayoutItemField.get_table_used(tableName), libglomLayoutItemField.get_name())); // Determine if the field should have a navigation button and set this in the DTO. Relationship fieldUsedInRelationshipToOne = new Relationship(); boolean addNavigation = Glom.layout_field_should_have_navigation(tableName, libglomLayoutItemField, document, fieldUsedInRelationshipToOne); layoutItemField.setAddNavigation(addNavigation); // Set the the name of the table to navigate to if navigation should be enabled. if (addNavigation) { // It's not possible to directly check if fieldUsedInRelationshipToOne is // null because of the way that the glom_sharedptr macro works. This workaround accomplishes the // same task. String tableNameUsed; try { Relationship temp = new Relationship(); temp.equals(fieldUsedInRelationshipToOne); // this will throw an NPE if // fieldUsedInRelationshipToOne is null // fieldUsedInRelationshipToOne is *not* null tableNameUsed = fieldUsedInRelationshipToOne.get_to_table(); } catch (NullPointerException e) { // fieldUsedInRelationshipToOne is null tableNameUsed = libglomLayoutItemField.get_table_used(tableName); } // Set the navigation table name only if it's not different than the current table name. if (!tableName.equals(tableNameUsed)) { layoutItemField.setNavigationTableName(tableNameUsed); } } layoutItem = layoutItemField; } else { Log.info(documentID, tableName, "Ignoring unknown details LayoutItem of type " + libglomLayoutItem.get_part_type_name() + "."); continue; } } layoutGroup.addItem(layoutItem); } return layoutGroup; }
private LayoutGroup getDetailsLayoutGroup(String tableName, org.glom.libglom.LayoutGroup libglomLayoutGroup) { LayoutGroup layoutGroup = new LayoutGroup(); layoutGroup.setColumnCount(Utils.safeLongToInt(libglomLayoutGroup.get_columns_count())); layoutGroup.setTitle(libglomLayoutGroup.get_title_or_name()); // look at each child item LayoutItemVector layoutItemsVec = libglomLayoutGroup.get_items(); for (int i = 0; i < layoutItemsVec.size(); i++) { org.glom.libglom.LayoutItem libglomLayoutItem = layoutItemsVec.get(i); // just a safety check if (libglomLayoutItem == null) continue; org.glom.web.shared.layout.LayoutItem layoutItem = null; org.glom.libglom.LayoutGroup group = org.glom.libglom.LayoutGroup.cast_dynamic(libglomLayoutItem); if (group != null) { // libglomLayoutItem is a LayoutGroup LayoutItem_Portal libglomLayoutItemPortal = LayoutItem_Portal.cast_dynamic(group); if (libglomLayoutItemPortal != null) { // group is a LayoutItem_Portal LayoutItemPortal layoutItemPortal = new LayoutItemPortal(); Relationship relationship = libglomLayoutItemPortal.get_relationship(); if (relationship != null) { layoutItemPortal.setNavigationType(convertToGWTGlomNavigationType(libglomLayoutItemPortal .get_navigation_type())); layoutItemPortal.setTitle(libglomLayoutItemPortal.get_title_used("")); // parent title not // relevant LayoutGroup tempLayoutGroup = getListLayoutGroup(tableName, libglomLayoutItemPortal); for (org.glom.web.shared.layout.LayoutItem item : tempLayoutGroup.getItems()) { // TODO EDITING If the relationship does not allow editing, then mark all these fields as // non-editable. Check relationship.get_allow_edit() to see if it's editable. layoutItemPortal.addItem(item); } layoutItemPortal.setPrimaryKeyIndex(tempLayoutGroup.getPrimaryKeyIndex()); layoutItemPortal.setHiddenPrimaryKey(tempLayoutGroup.hasHiddenPrimaryKey()); layoutItemPortal.setName(libglomLayoutItemPortal.get_relationship_name_used()); layoutItemPortal.setTableName(relationship.get_from_table()); layoutItemPortal.setFromField(relationship.get_from_field()); // Set whether or not the related list will need to show the navigation buttons. // This was ported from Glom: Box_Data_Portal::get_has_suitable_record_to_view_details() StringBuffer navigationTableName = new StringBuffer(); LayoutItem_Field navigationRelationship = new LayoutItem_Field(); // Ignored. libglomLayoutItemPortal.get_suitable_table_to_view_details(navigationTableName, navigationRelationship, document); layoutItemPortal.setAddNavigation(!(navigationTableName.toString().isEmpty())); } // Note: empty layoutItemPortal used if relationship is null layoutItem = layoutItemPortal; } else { // libglomLayoutItem is a LayoutGroup LayoutItem_Notebook libglomLayoutItemNotebook = LayoutItem_Notebook.cast_dynamic(group); if (libglomLayoutItemNotebook != null) { // group is a LayoutItem_Notebook LayoutGroup tempLayoutGroup = getDetailsLayoutGroup(tableName, libglomLayoutItemNotebook); LayoutItemNotebook layoutItemNotebook = new LayoutItemNotebook(); for (LayoutItem item : tempLayoutGroup.getItems()) { layoutItemNotebook.addItem(item); } layoutItemNotebook.setName(tableName); layoutItem = layoutItemNotebook; } else { // group is *not* a LayoutItem_Portal or a LayoutItem_Notebook // recurse into child groups layoutItem = getDetailsLayoutGroup(tableName, group); } } } else { // libglomLayoutItem is *not* a LayoutGroup // create LayoutItem DTOs based on the the libglom type // TODO add support for other LayoutItems (Text, Image, Button etc.) LayoutItem_Field libglomLayoutItemField = LayoutItem_Field.cast_dynamic(libglomLayoutItem); if (libglomLayoutItemField != null) { LayoutItemField layoutItemField = convertToGWTGlomLayoutItemField(libglomLayoutItemField, true); // Set the full field details with updated field details from the document. libglomLayoutItemField.set_full_field_details(document.get_field( libglomLayoutItemField.get_table_used(tableName), libglomLayoutItemField.get_name())); // Determine if the field should have a navigation button and set this in the DTO. Relationship fieldUsedInRelationshipToOne = new Relationship(); boolean addNavigation = Glom.layout_field_should_have_navigation(tableName, libglomLayoutItemField, document, fieldUsedInRelationshipToOne); layoutItemField.setAddNavigation(addNavigation); // Set the the name of the table to navigate to if navigation should be enabled. if (addNavigation) { // It's not possible to directly check if fieldUsedInRelationshipToOne is // null because of the way that the glom_sharedptr macro works. This workaround accomplishes the // same task. String tableNameUsed; try { Relationship temp = new Relationship(); temp.equals(fieldUsedInRelationshipToOne); // this will throw an NPE if // fieldUsedInRelationshipToOne is null // fieldUsedInRelationshipToOne is *not* null tableNameUsed = fieldUsedInRelationshipToOne.get_to_table(); } catch (NullPointerException e) { // fieldUsedInRelationshipToOne is null tableNameUsed = libglomLayoutItemField.get_table_used(tableName); } // Set the navigation table name only if it's not different than the current table name. if (!tableName.equals(tableNameUsed)) { layoutItemField.setNavigationTableName(tableNameUsed); } } layoutItem = layoutItemField; } else { Log.info(documentID, tableName, "Ignoring unknown details LayoutItem of type " + libglomLayoutItem.get_part_type_name() + "."); continue; } } layoutGroup.addItem(layoutItem); } return layoutGroup; }
diff --git a/src/main/java/tconstruct/client/ToolCoreRenderer.java b/src/main/java/tconstruct/client/ToolCoreRenderer.java index e7a344abe..7c22332e5 100644 --- a/src/main/java/tconstruct/client/ToolCoreRenderer.java +++ b/src/main/java/tconstruct/client/ToolCoreRenderer.java @@ -1,318 +1,319 @@ package tconstruct.client; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ItemRenderer; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.TextureUtil; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.*; import tconstruct.TConstruct; import tconstruct.library.tools.ToolCore; public class ToolCoreRenderer implements IItemRenderer { private final boolean isEntity; private final boolean noEntityTranslation; public ToolCoreRenderer() { this(false, false); } public ToolCoreRenderer(boolean isEntity) { this(isEntity, false); } public ToolCoreRenderer(boolean isEntity, boolean noEntityTranslation) { this.isEntity = isEntity; this.noEntityTranslation = noEntityTranslation; } @Override public boolean handleRenderType (ItemStack item, ItemRenderType type) { if (!item.hasTagCompound()) return false; switch (type) { case ENTITY: return true; case EQUIPPED: GL11.glTranslatef(0.03f, 0F, -0.09375F); case EQUIPPED_FIRST_PERSON: return !isEntity; case INVENTORY: return true; default: TConstruct.logger.warn("[TCon] Unhandled render case!"); case FIRST_PERSON_MAP: return false; } } @Override public boolean shouldUseRenderHelper (ItemRenderType type, ItemStack item, ItemRendererHelper helper) { return handleRenderType(item, type) & helper.ordinal() < ItemRendererHelper.EQUIPPED_BLOCK.ordinal(); } private static final int toolIcons = 10; @Override public void renderItem (ItemRenderType type, ItemStack item, Object... data) { ToolCore tool = (ToolCore) item.getItem(); boolean isInventory = type == ItemRenderType.INVENTORY; Entity ent = null; if (data.length > 1) ent = (Entity) data[1]; int iconParts = toolIcons;//tool.getRenderPasses(item.getItemDamage()); // TODO: have the tools define how many render passes they have // (requires more logic rewrite than it sounds like) IIcon[] tempParts = new IIcon[iconParts]; label: { if (!isInventory && ent instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) ent; ItemStack itemInUse = player.getItemInUse(); if (itemInUse != null) { int useCount = player.getItemInUseCount(); for (int i = iconParts; i-- > 0;) tempParts[i] = tool.getIcon(item, i, player, itemInUse, useCount); break label; } } for (int i = iconParts; i-- > 0;) tempParts[i] = tool.getIcon(item, i); } int count = 0; IIcon[] parts = new IIcon[iconParts]; for (int i = 0; i < iconParts; ++i) { IIcon part = tempParts[i]; if (part == null || part == ToolCore.blankSprite || part == ToolCore.emptyIcon) ++count; else parts[i - count] = part; } iconParts -= count; if (iconParts <= 0) { iconParts = 1; // TODO: assign default sprite // parts = new Icon[]{ defaultSprite }; } Tessellator tess = Tessellator.instance; float[] xMax = new float[iconParts]; float[] yMin = new float[iconParts]; float[] xMin = new float[iconParts]; float[] yMax = new float[iconParts]; float depth = 1f / 16f; float[] width = new float[iconParts]; float[] height = new float[iconParts]; float[] xDiff = new float[iconParts]; float[] yDiff = new float[iconParts]; float[] xSub = new float[iconParts]; float[] ySub = new float[iconParts]; for (int i = 0; i < iconParts; ++i) { IIcon icon = parts[i]; xMin[i] = icon.getMinU(); xMax[i] = icon.getMaxU(); yMin[i] = icon.getMinV(); yMax[i] = icon.getMaxV(); width[i] = icon.getIconWidth(); height[i] = icon.getIconHeight(); xDiff[i] = xMin[i] - xMax[i]; yDiff[i] = yMin[i] - yMax[i]; xSub[i] = 0.5f * (xMax[i] - xMin[i]) / width[i]; ySub[i] = 0.5f * (yMax[i] - yMin[i]) / height[i]; } GL11.glPushMatrix(); // color int[] color = new int[iconParts]; for(int i = 0; i < iconParts; i++) color[i] = item.getItem().getColorFromItemStack(item, i); GL11.glEnable(GL12.GL_RESCALE_NORMAL); if (type == ItemRenderType.INVENTORY) { - TextureManager texturemanager = Minecraft.getMinecraft().getTextureManager(); - texturemanager.getResourceLocation(item.getItemSpriteNumber()); - TextureUtil.func_152777_a(false, false, 1.0F); + //TextureManager texturemanager = Minecraft.getMinecraft().getTextureManager(); + //texturemanager.getResourceLocation(item.getItemSpriteNumber()); + //TextureUtil.func_152777_a(false, false, 1.0F); GL11.glDisable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glAlphaFunc(GL11.GL_GREATER, 0.5F); GL11.glDisable(GL11.GL_BLEND); tess.startDrawingQuads(); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); tess.addVertexWithUV(0, 16, 0, xMin[i], yMax[i]); tess.addVertexWithUV(16, 16, 0, xMax[i], yMax[i]); tess.addVertexWithUV(16, 0, 0, xMax[i], yMin[i]); tess.addVertexWithUV(0, 0, 0, xMin[i], yMin[i]); } tess.draw(); GL11.glEnable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_ALPHA_TEST); + GL11.glEnable(GL11.GL_BLEND); //GL11.glDisable(GL12.GL_RESCALE_NORMAL); - texturemanager.bindTexture(texturemanager.getResourceLocation(item.getItemSpriteNumber())); - TextureUtil.func_147945_b(); + //texturemanager.bindTexture(texturemanager.getResourceLocation(item.getItemSpriteNumber())); + //TextureUtil.func_147945_b(); } else { switch (type) { case EQUIPPED_FIRST_PERSON: break; case EQUIPPED: GL11.glTranslatef(0, -4 / 16f, 0); break; case ENTITY: if (!noEntityTranslation) GL11.glTranslatef(-0.5f, 0f, depth); // correction of the rotation point when items lie on the ground break; default: } // one side tess.startDrawingQuads(); tess.setNormal(0, 0, 1); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); tess.addVertexWithUV(0, 0, 0, xMax[i], yMax[i]); tess.addVertexWithUV(1, 0, 0, xMin[i], yMax[i]); tess.addVertexWithUV(1, 1, 0, xMin[i], yMin[i]); tess.addVertexWithUV(0, 1, 0, xMax[i], yMin[i]); } tess.draw(); // other side tess.startDrawingQuads(); tess.setNormal(0, 0, -1); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); tess.addVertexWithUV(0, 1, -depth, xMax[i], yMin[i]); tess.addVertexWithUV(1, 1, -depth, xMin[i], yMin[i]); tess.addVertexWithUV(1, 0, -depth, xMin[i], yMax[i]); tess.addVertexWithUV(0, 0, -depth, xMax[i], yMax[i]); } tess.draw(); // make it have "depth" tess.startDrawingQuads(); tess.setNormal(-1, 0, 0); float pos; float iconPos; for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float w = width[i], m = xMax[i], d = xDiff[i], s = xSub[i]; for (int k = 0, e = (int) w; k < e; ++k) { pos = k / w; iconPos = m + d * pos - s; tess.addVertexWithUV(pos, 0, -depth, iconPos, yMax[i]); tess.addVertexWithUV(pos, 0, 0, iconPos, yMax[i]); tess.addVertexWithUV(pos, 1, 0, iconPos, yMin[i]); tess.addVertexWithUV(pos, 1, -depth, iconPos, yMin[i]); } } tess.draw(); tess.startDrawingQuads(); tess.setNormal(1, 0, 0); float posEnd; for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float w = width[i], m = xMax[i], d = xDiff[i], s = xSub[i]; float d2 = 1f / w; for (int k = 0, e = (int) w; k < e; ++k) { pos = k / w; iconPos = m + d * pos - s; posEnd = pos + d2; tess.addVertexWithUV(posEnd, 1, -depth, iconPos, yMin[i]); tess.addVertexWithUV(posEnd, 1, 0, iconPos, yMin[i]); tess.addVertexWithUV(posEnd, 0, 0, iconPos, yMax[i]); tess.addVertexWithUV(posEnd, 0, -depth, iconPos, yMax[i]); } } tess.draw(); tess.startDrawingQuads(); tess.setNormal(0, 1, 0); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float h = height[i], m = yMax[i], d = yDiff[i], s = ySub[i]; float d2 = 1f / h; for (int k = 0, e = (int) h; k < e; ++k) { pos = k / h; iconPos = m + d * pos - s; posEnd = pos + d2; tess.addVertexWithUV(0, posEnd, 0, xMax[i], iconPos); tess.addVertexWithUV(1, posEnd, 0, xMin[i], iconPos); tess.addVertexWithUV(1, posEnd, -depth, xMin[i], iconPos); tess.addVertexWithUV(0, posEnd, -depth, xMax[i], iconPos); } } tess.draw(); tess.startDrawingQuads(); tess.setNormal(0, -1, 0); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float h = height[i], m = yMax[i], d = yDiff[i], s = ySub[i]; for (int k = 0, e = (int) h; k < e; ++k) { pos = k / h; iconPos = m + d * pos - s; tess.addVertexWithUV(1, pos, 0, xMin[i], iconPos); tess.addVertexWithUV(0, pos, 0, xMax[i], iconPos); tess.addVertexWithUV(0, pos, -depth, xMax[i], iconPos); tess.addVertexWithUV(1, pos, -depth, xMin[i], iconPos); } } tess.draw(); GL11.glDisable(GL12.GL_RESCALE_NORMAL); } GL11.glPopMatrix(); } }
false
true
public void renderItem (ItemRenderType type, ItemStack item, Object... data) { ToolCore tool = (ToolCore) item.getItem(); boolean isInventory = type == ItemRenderType.INVENTORY; Entity ent = null; if (data.length > 1) ent = (Entity) data[1]; int iconParts = toolIcons;//tool.getRenderPasses(item.getItemDamage()); // TODO: have the tools define how many render passes they have // (requires more logic rewrite than it sounds like) IIcon[] tempParts = new IIcon[iconParts]; label: { if (!isInventory && ent instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) ent; ItemStack itemInUse = player.getItemInUse(); if (itemInUse != null) { int useCount = player.getItemInUseCount(); for (int i = iconParts; i-- > 0;) tempParts[i] = tool.getIcon(item, i, player, itemInUse, useCount); break label; } } for (int i = iconParts; i-- > 0;) tempParts[i] = tool.getIcon(item, i); } int count = 0; IIcon[] parts = new IIcon[iconParts]; for (int i = 0; i < iconParts; ++i) { IIcon part = tempParts[i]; if (part == null || part == ToolCore.blankSprite || part == ToolCore.emptyIcon) ++count; else parts[i - count] = part; } iconParts -= count; if (iconParts <= 0) { iconParts = 1; // TODO: assign default sprite // parts = new Icon[]{ defaultSprite }; } Tessellator tess = Tessellator.instance; float[] xMax = new float[iconParts]; float[] yMin = new float[iconParts]; float[] xMin = new float[iconParts]; float[] yMax = new float[iconParts]; float depth = 1f / 16f; float[] width = new float[iconParts]; float[] height = new float[iconParts]; float[] xDiff = new float[iconParts]; float[] yDiff = new float[iconParts]; float[] xSub = new float[iconParts]; float[] ySub = new float[iconParts]; for (int i = 0; i < iconParts; ++i) { IIcon icon = parts[i]; xMin[i] = icon.getMinU(); xMax[i] = icon.getMaxU(); yMin[i] = icon.getMinV(); yMax[i] = icon.getMaxV(); width[i] = icon.getIconWidth(); height[i] = icon.getIconHeight(); xDiff[i] = xMin[i] - xMax[i]; yDiff[i] = yMin[i] - yMax[i]; xSub[i] = 0.5f * (xMax[i] - xMin[i]) / width[i]; ySub[i] = 0.5f * (yMax[i] - yMin[i]) / height[i]; } GL11.glPushMatrix(); // color int[] color = new int[iconParts]; for(int i = 0; i < iconParts; i++) color[i] = item.getItem().getColorFromItemStack(item, i); GL11.glEnable(GL12.GL_RESCALE_NORMAL); if (type == ItemRenderType.INVENTORY) { TextureManager texturemanager = Minecraft.getMinecraft().getTextureManager(); texturemanager.getResourceLocation(item.getItemSpriteNumber()); TextureUtil.func_152777_a(false, false, 1.0F); GL11.glDisable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glAlphaFunc(GL11.GL_GREATER, 0.5F); GL11.glDisable(GL11.GL_BLEND); tess.startDrawingQuads(); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); tess.addVertexWithUV(0, 16, 0, xMin[i], yMax[i]); tess.addVertexWithUV(16, 16, 0, xMax[i], yMax[i]); tess.addVertexWithUV(16, 0, 0, xMax[i], yMin[i]); tess.addVertexWithUV(0, 0, 0, xMin[i], yMin[i]); } tess.draw(); GL11.glEnable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_ALPHA_TEST); //GL11.glDisable(GL12.GL_RESCALE_NORMAL); texturemanager.bindTexture(texturemanager.getResourceLocation(item.getItemSpriteNumber())); TextureUtil.func_147945_b(); } else { switch (type) { case EQUIPPED_FIRST_PERSON: break; case EQUIPPED: GL11.glTranslatef(0, -4 / 16f, 0); break; case ENTITY: if (!noEntityTranslation) GL11.glTranslatef(-0.5f, 0f, depth); // correction of the rotation point when items lie on the ground break; default: } // one side tess.startDrawingQuads(); tess.setNormal(0, 0, 1); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); tess.addVertexWithUV(0, 0, 0, xMax[i], yMax[i]); tess.addVertexWithUV(1, 0, 0, xMin[i], yMax[i]); tess.addVertexWithUV(1, 1, 0, xMin[i], yMin[i]); tess.addVertexWithUV(0, 1, 0, xMax[i], yMin[i]); } tess.draw(); // other side tess.startDrawingQuads(); tess.setNormal(0, 0, -1); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); tess.addVertexWithUV(0, 1, -depth, xMax[i], yMin[i]); tess.addVertexWithUV(1, 1, -depth, xMin[i], yMin[i]); tess.addVertexWithUV(1, 0, -depth, xMin[i], yMax[i]); tess.addVertexWithUV(0, 0, -depth, xMax[i], yMax[i]); } tess.draw(); // make it have "depth" tess.startDrawingQuads(); tess.setNormal(-1, 0, 0); float pos; float iconPos; for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float w = width[i], m = xMax[i], d = xDiff[i], s = xSub[i]; for (int k = 0, e = (int) w; k < e; ++k) { pos = k / w; iconPos = m + d * pos - s; tess.addVertexWithUV(pos, 0, -depth, iconPos, yMax[i]); tess.addVertexWithUV(pos, 0, 0, iconPos, yMax[i]); tess.addVertexWithUV(pos, 1, 0, iconPos, yMin[i]); tess.addVertexWithUV(pos, 1, -depth, iconPos, yMin[i]); } } tess.draw(); tess.startDrawingQuads(); tess.setNormal(1, 0, 0); float posEnd; for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float w = width[i], m = xMax[i], d = xDiff[i], s = xSub[i]; float d2 = 1f / w; for (int k = 0, e = (int) w; k < e; ++k) { pos = k / w; iconPos = m + d * pos - s; posEnd = pos + d2; tess.addVertexWithUV(posEnd, 1, -depth, iconPos, yMin[i]); tess.addVertexWithUV(posEnd, 1, 0, iconPos, yMin[i]); tess.addVertexWithUV(posEnd, 0, 0, iconPos, yMax[i]); tess.addVertexWithUV(posEnd, 0, -depth, iconPos, yMax[i]); } } tess.draw(); tess.startDrawingQuads(); tess.setNormal(0, 1, 0); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float h = height[i], m = yMax[i], d = yDiff[i], s = ySub[i]; float d2 = 1f / h; for (int k = 0, e = (int) h; k < e; ++k) { pos = k / h; iconPos = m + d * pos - s; posEnd = pos + d2; tess.addVertexWithUV(0, posEnd, 0, xMax[i], iconPos); tess.addVertexWithUV(1, posEnd, 0, xMin[i], iconPos); tess.addVertexWithUV(1, posEnd, -depth, xMin[i], iconPos); tess.addVertexWithUV(0, posEnd, -depth, xMax[i], iconPos); } } tess.draw(); tess.startDrawingQuads(); tess.setNormal(0, -1, 0); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float h = height[i], m = yMax[i], d = yDiff[i], s = ySub[i]; for (int k = 0, e = (int) h; k < e; ++k) { pos = k / h; iconPos = m + d * pos - s; tess.addVertexWithUV(1, pos, 0, xMin[i], iconPos); tess.addVertexWithUV(0, pos, 0, xMax[i], iconPos); tess.addVertexWithUV(0, pos, -depth, xMax[i], iconPos); tess.addVertexWithUV(1, pos, -depth, xMin[i], iconPos); } } tess.draw(); GL11.glDisable(GL12.GL_RESCALE_NORMAL); } GL11.glPopMatrix(); }
public void renderItem (ItemRenderType type, ItemStack item, Object... data) { ToolCore tool = (ToolCore) item.getItem(); boolean isInventory = type == ItemRenderType.INVENTORY; Entity ent = null; if (data.length > 1) ent = (Entity) data[1]; int iconParts = toolIcons;//tool.getRenderPasses(item.getItemDamage()); // TODO: have the tools define how many render passes they have // (requires more logic rewrite than it sounds like) IIcon[] tempParts = new IIcon[iconParts]; label: { if (!isInventory && ent instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) ent; ItemStack itemInUse = player.getItemInUse(); if (itemInUse != null) { int useCount = player.getItemInUseCount(); for (int i = iconParts; i-- > 0;) tempParts[i] = tool.getIcon(item, i, player, itemInUse, useCount); break label; } } for (int i = iconParts; i-- > 0;) tempParts[i] = tool.getIcon(item, i); } int count = 0; IIcon[] parts = new IIcon[iconParts]; for (int i = 0; i < iconParts; ++i) { IIcon part = tempParts[i]; if (part == null || part == ToolCore.blankSprite || part == ToolCore.emptyIcon) ++count; else parts[i - count] = part; } iconParts -= count; if (iconParts <= 0) { iconParts = 1; // TODO: assign default sprite // parts = new Icon[]{ defaultSprite }; } Tessellator tess = Tessellator.instance; float[] xMax = new float[iconParts]; float[] yMin = new float[iconParts]; float[] xMin = new float[iconParts]; float[] yMax = new float[iconParts]; float depth = 1f / 16f; float[] width = new float[iconParts]; float[] height = new float[iconParts]; float[] xDiff = new float[iconParts]; float[] yDiff = new float[iconParts]; float[] xSub = new float[iconParts]; float[] ySub = new float[iconParts]; for (int i = 0; i < iconParts; ++i) { IIcon icon = parts[i]; xMin[i] = icon.getMinU(); xMax[i] = icon.getMaxU(); yMin[i] = icon.getMinV(); yMax[i] = icon.getMaxV(); width[i] = icon.getIconWidth(); height[i] = icon.getIconHeight(); xDiff[i] = xMin[i] - xMax[i]; yDiff[i] = yMin[i] - yMax[i]; xSub[i] = 0.5f * (xMax[i] - xMin[i]) / width[i]; ySub[i] = 0.5f * (yMax[i] - yMin[i]) / height[i]; } GL11.glPushMatrix(); // color int[] color = new int[iconParts]; for(int i = 0; i < iconParts; i++) color[i] = item.getItem().getColorFromItemStack(item, i); GL11.glEnable(GL12.GL_RESCALE_NORMAL); if (type == ItemRenderType.INVENTORY) { //TextureManager texturemanager = Minecraft.getMinecraft().getTextureManager(); //texturemanager.getResourceLocation(item.getItemSpriteNumber()); //TextureUtil.func_152777_a(false, false, 1.0F); GL11.glDisable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glAlphaFunc(GL11.GL_GREATER, 0.5F); GL11.glDisable(GL11.GL_BLEND); tess.startDrawingQuads(); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); tess.addVertexWithUV(0, 16, 0, xMin[i], yMax[i]); tess.addVertexWithUV(16, 16, 0, xMax[i], yMax[i]); tess.addVertexWithUV(16, 0, 0, xMax[i], yMin[i]); tess.addVertexWithUV(0, 0, 0, xMin[i], yMin[i]); } tess.draw(); GL11.glEnable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_ALPHA_TEST); GL11.glEnable(GL11.GL_BLEND); //GL11.glDisable(GL12.GL_RESCALE_NORMAL); //texturemanager.bindTexture(texturemanager.getResourceLocation(item.getItemSpriteNumber())); //TextureUtil.func_147945_b(); } else { switch (type) { case EQUIPPED_FIRST_PERSON: break; case EQUIPPED: GL11.glTranslatef(0, -4 / 16f, 0); break; case ENTITY: if (!noEntityTranslation) GL11.glTranslatef(-0.5f, 0f, depth); // correction of the rotation point when items lie on the ground break; default: } // one side tess.startDrawingQuads(); tess.setNormal(0, 0, 1); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); tess.addVertexWithUV(0, 0, 0, xMax[i], yMax[i]); tess.addVertexWithUV(1, 0, 0, xMin[i], yMax[i]); tess.addVertexWithUV(1, 1, 0, xMin[i], yMin[i]); tess.addVertexWithUV(0, 1, 0, xMax[i], yMin[i]); } tess.draw(); // other side tess.startDrawingQuads(); tess.setNormal(0, 0, -1); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); tess.addVertexWithUV(0, 1, -depth, xMax[i], yMin[i]); tess.addVertexWithUV(1, 1, -depth, xMin[i], yMin[i]); tess.addVertexWithUV(1, 0, -depth, xMin[i], yMax[i]); tess.addVertexWithUV(0, 0, -depth, xMax[i], yMax[i]); } tess.draw(); // make it have "depth" tess.startDrawingQuads(); tess.setNormal(-1, 0, 0); float pos; float iconPos; for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float w = width[i], m = xMax[i], d = xDiff[i], s = xSub[i]; for (int k = 0, e = (int) w; k < e; ++k) { pos = k / w; iconPos = m + d * pos - s; tess.addVertexWithUV(pos, 0, -depth, iconPos, yMax[i]); tess.addVertexWithUV(pos, 0, 0, iconPos, yMax[i]); tess.addVertexWithUV(pos, 1, 0, iconPos, yMin[i]); tess.addVertexWithUV(pos, 1, -depth, iconPos, yMin[i]); } } tess.draw(); tess.startDrawingQuads(); tess.setNormal(1, 0, 0); float posEnd; for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float w = width[i], m = xMax[i], d = xDiff[i], s = xSub[i]; float d2 = 1f / w; for (int k = 0, e = (int) w; k < e; ++k) { pos = k / w; iconPos = m + d * pos - s; posEnd = pos + d2; tess.addVertexWithUV(posEnd, 1, -depth, iconPos, yMin[i]); tess.addVertexWithUV(posEnd, 1, 0, iconPos, yMin[i]); tess.addVertexWithUV(posEnd, 0, 0, iconPos, yMax[i]); tess.addVertexWithUV(posEnd, 0, -depth, iconPos, yMax[i]); } } tess.draw(); tess.startDrawingQuads(); tess.setNormal(0, 1, 0); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float h = height[i], m = yMax[i], d = yDiff[i], s = ySub[i]; float d2 = 1f / h; for (int k = 0, e = (int) h; k < e; ++k) { pos = k / h; iconPos = m + d * pos - s; posEnd = pos + d2; tess.addVertexWithUV(0, posEnd, 0, xMax[i], iconPos); tess.addVertexWithUV(1, posEnd, 0, xMin[i], iconPos); tess.addVertexWithUV(1, posEnd, -depth, xMin[i], iconPos); tess.addVertexWithUV(0, posEnd, -depth, xMax[i], iconPos); } } tess.draw(); tess.startDrawingQuads(); tess.setNormal(0, -1, 0); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float h = height[i], m = yMax[i], d = yDiff[i], s = ySub[i]; for (int k = 0, e = (int) h; k < e; ++k) { pos = k / h; iconPos = m + d * pos - s; tess.addVertexWithUV(1, pos, 0, xMin[i], iconPos); tess.addVertexWithUV(0, pos, 0, xMax[i], iconPos); tess.addVertexWithUV(0, pos, -depth, xMax[i], iconPos); tess.addVertexWithUV(1, pos, -depth, xMin[i], iconPos); } } tess.draw(); GL11.glDisable(GL12.GL_RESCALE_NORMAL); } GL11.glPopMatrix(); }
diff --git a/harri-manager/src/main/java/gov/usgs/cida/harri/HarriManagerService.java b/harri-manager/src/main/java/gov/usgs/cida/harri/HarriManagerService.java index edc3739..4b1a8f3 100644 --- a/harri-manager/src/main/java/gov/usgs/cida/harri/HarriManagerService.java +++ b/harri-manager/src/main/java/gov/usgs/cida/harri/HarriManagerService.java @@ -1,125 +1,126 @@ package gov.usgs.cida.harri; import org.teleal.cling.UpnpService; import org.teleal.cling.UpnpServiceImpl; import org.teleal.cling.controlpoint.*; import org.teleal.cling.model.action.*; import org.teleal.cling.model.message.*; import org.teleal.cling.model.message.header.*; import org.teleal.cling.model.meta.*; import org.teleal.cling.model.types.*; import org.teleal.cling.registry.*; public class HarriManagerService implements Runnable { public static final String DEVICE_PREFIX = "HARRI_Device"; public static final String DEVICE_MANUFACTURER = "CIDA"; public static void main(String[] args) throws Exception { // Start a user thread that runs the UPnP stack Thread clientThread = new Thread(new HarriManagerService()); clientThread.setDaemon(false); clientThread.start(); } public void run() { try { UpnpService upnpService = new UpnpServiceImpl(); // Add a listener for device registration events upnpService.getRegistry().addListener( createRegistryListener(upnpService) ); // Broadcast a search message for all devices upnpService.getControlPoint().search( new STAllHeader() ); } catch (Exception ex) { System.err.println("Exception occured: " + ex); System.exit(1); } } private RegistryListener createRegistryListener(final UpnpService upnpService) { return new DefaultRegistryListener() { private boolean isHarriDevice(final RemoteDevice device) { - return device.getDetails().getManufacturerDetails().equals(DEVICE_MANUFACTURER) && + return device.getDetails().getManufacturerDetails()!=null && + device.getDetails().getManufacturerDetails().getManufacturer().equals(DEVICE_MANUFACTURER) && device.getDetails().getModelDetails().getModelName().contains(DEVICE_PREFIX); } @Override public void remoteDeviceAdded(Registry registry, RemoteDevice device) { if(!isHarriDevice(device)){ return; } //if not a HARRI device, do nothing System.out.println("HARRI Device has been added: " + device.getDetails().getModelDetails().getModelName()); doExampleServiceCall(upnpService, device); //TODO delete when not needed } @Override public void remoteDeviceRemoved(Registry registry, RemoteDevice device) { if(!isHarriDevice(device)){ return; } System.out.println("HARRI Device " + device.getDetails().getModelDetails().getModelName() + " has been removed!"); } }; } //TODO remove example private void doExampleServiceCall(final UpnpService upnpService, final RemoteDevice device){ ServiceId serviceId = new UDAServiceId("ExampleHarriService"); //NOTE: a service on the device is annotated with this value Service exampleHarriAction; if ((exampleHarriAction = device.findService(serviceId)) != null) { System.out.println("HARRI Service discovered on device " + device.getDetails().getModelDetails().getModelName() + ": " + exampleHarriAction); executeAction(upnpService, exampleHarriAction); } } //TODO remove example private void executeAction(UpnpService upnpService, Service exampleHarriActionService) { ActionInvocation setTargetInvocation = new ExampleHarriActionInvocation(exampleHarriActionService); // Executes asynchronous in the background upnpService.getControlPoint().execute( new ActionCallback(setTargetInvocation) { @Override public void success(ActionInvocation invocation) { assert invocation.getOutput().length == 0; System.out.println("Successfully called remote action on HARRI device!"); } @Override public void failure(ActionInvocation invocation, UpnpResponse operation, String defaultMsg) { System.err.println(defaultMsg); } } ); } //TODO remove example private class ExampleHarriActionInvocation extends ActionInvocation { ExampleHarriActionInvocation(Service service) { super(service.getAction("DoExampleAction")); //NOTE: this string is a method in the service try { // Throws InvalidValueException if the value is of wrong type setInput("HarriManagerId", "EXAMPLE_HARRI_MANAGER_ID"); //TODO get this example harri manager id from somewhere useful } catch (InvalidValueException ex) { System.err.println(ex.getMessage()); System.exit(1); } } } }
true
true
private RegistryListener createRegistryListener(final UpnpService upnpService) { return new DefaultRegistryListener() { private boolean isHarriDevice(final RemoteDevice device) { return device.getDetails().getManufacturerDetails().equals(DEVICE_MANUFACTURER) && device.getDetails().getModelDetails().getModelName().contains(DEVICE_PREFIX); } @Override public void remoteDeviceAdded(Registry registry, RemoteDevice device) { if(!isHarriDevice(device)){ return; } //if not a HARRI device, do nothing System.out.println("HARRI Device has been added: " + device.getDetails().getModelDetails().getModelName()); doExampleServiceCall(upnpService, device); //TODO delete when not needed } @Override public void remoteDeviceRemoved(Registry registry, RemoteDevice device) { if(!isHarriDevice(device)){ return; } System.out.println("HARRI Device " + device.getDetails().getModelDetails().getModelName() + " has been removed!"); } }; }
private RegistryListener createRegistryListener(final UpnpService upnpService) { return new DefaultRegistryListener() { private boolean isHarriDevice(final RemoteDevice device) { return device.getDetails().getManufacturerDetails()!=null && device.getDetails().getManufacturerDetails().getManufacturer().equals(DEVICE_MANUFACTURER) && device.getDetails().getModelDetails().getModelName().contains(DEVICE_PREFIX); } @Override public void remoteDeviceAdded(Registry registry, RemoteDevice device) { if(!isHarriDevice(device)){ return; } //if not a HARRI device, do nothing System.out.println("HARRI Device has been added: " + device.getDetails().getModelDetails().getModelName()); doExampleServiceCall(upnpService, device); //TODO delete when not needed } @Override public void remoteDeviceRemoved(Registry registry, RemoteDevice device) { if(!isHarriDevice(device)){ return; } System.out.println("HARRI Device " + device.getDetails().getModelDetails().getModelName() + " has been removed!"); } }; }
diff --git a/jamwiki-core/src/main/java/org/jamwiki/parser/jflex/TemplateTag.java b/jamwiki-core/src/main/java/org/jamwiki/parser/jflex/TemplateTag.java index 1c50c1ab..64cb3c6e 100644 --- a/jamwiki-core/src/main/java/org/jamwiki/parser/jflex/TemplateTag.java +++ b/jamwiki-core/src/main/java/org/jamwiki/parser/jflex/TemplateTag.java @@ -1,427 +1,429 @@ /** * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999. * * This program is free software; you can redistribute it and/or modify * it under the terms of the latest version of the GNU Lesser General * Public License as published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program (LICENSE.txt); if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.jamwiki.parser.jflex; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.jamwiki.DataAccessException; import org.jamwiki.Environment; import org.jamwiki.WikiBase; import org.jamwiki.model.Namespace; import org.jamwiki.model.Topic; import org.jamwiki.model.TopicType; import org.jamwiki.parser.ExcessiveNestingException; import org.jamwiki.parser.ParserException; import org.jamwiki.parser.ParserInput; import org.jamwiki.parser.ParserOutput; import org.jamwiki.utils.LinkUtil; import org.jamwiki.utils.Utilities; import org.jamwiki.utils.WikiLink; import org.jamwiki.utils.WikiLogger; import org.jamwiki.utils.WikiUtil; /** * <code>TemplateTag</code> parses Mediawiki template syntax, which allows * programmatic structures to be embedded in wiki syntax. */ public class TemplateTag implements JFlexParserTag { private static final WikiLogger logger = WikiLogger.getLogger(TemplateTag.class.getName()); protected static final String TEMPLATE_INCLUSION = "template-inclusion"; protected static final String TEMPLATE_ONLYINCLUDE = "template-onlyinclude"; private static final Pattern PARAM_NAME_VALUE_PATTERN = Pattern.compile("[\\s]*([A-Za-z0-9_\\ \\-]+)[\\s]*\\=([\\s\\S]*)"); /** * Once the template call has been parsed and the template values have been * determined, parse the template body and apply those template values. * Parameters may be embedded or have default values, so there is some * voodoo magic that happens here to first parse any embedded values, and * to apply default values when no template value has been set. */ private String applyParameter(ParserInput parserInput, ParserOutput parserOutput, String param, Map<String, String> parameterValues) throws ParserException { String content = param.substring("{{{".length(), param.length() - "}}}".length()); // re-parse in case of embedded templates or params content = this.parseTemplateBody(parserInput, parserOutput, content, parameterValues); String name = this.parseParamName(content); String defaultValue = this.parseParamDefaultValue(parserInput, parserOutput, content); String value = parameterValues.get(name); if (value == null && defaultValue == null) { return param; } return (value == null) ? defaultValue : value; } /** * Determine if the template text is of the form "subst:XXX". */ private boolean isSubstitution(String templateContent) { // is it a substitution? templateContent = templateContent.trim(); return (templateContent.startsWith("subst:") && templateContent.length() > "subst:".length()); } /** * Parse a call to a Mediawiki template of the form "{{template|param1|param2}}" * and return the resulting template output. */ public String parse(JFlexLexer lexer, String raw, Object... args) throws ParserException { // validate and extract the template content if (StringUtils.isBlank(raw)) { throw new ParserException("Empty template text"); } if (!raw.startsWith("{{") || !raw.endsWith("}}")) { throw new ParserException ("Invalid template text: " + raw); } String templateContent = raw.substring("{{".length(), raw.length() - "}}".length()); if ((!this.isSubstitution(templateContent) && lexer.getMode() < JFlexParser.MODE_TEMPLATE) || lexer.getMode() < JFlexParser.MODE_MINIMAL) { return raw; } try { return this.parseTemplateOutput(lexer.getParserInput(), lexer.getParserOutput(), lexer.getMode(), raw, true); } catch (ExcessiveNestingException e) { logger.warn("Excessive template nesting in topic " + lexer.getParserInput().getTopicName()); // convert to a link so that the user can fix the template WikiLink wikiLink = this.parseTemplateName(lexer.getParserInput().getVirtualWiki(), templateContent); String templateName = wikiLink.getDestination(); if (!wikiLink.getColon() && !wikiLink.getNamespace().equals(Namespace.namespace(Namespace.TEMPLATE_ID))) { templateName = Namespace.namespace(Namespace.TEMPLATE_ID).getLabel(lexer.getParserInput().getVirtualWiki()) + Namespace.SEPARATOR + StringUtils.capitalize(templateName); } return "[[" + templateName + "]]"; } catch (DataAccessException e) { throw new ParserException("Data access exception while parsing: " + raw, e); } } /** * Parses the template content and returns the parsed output. If there is no result (such * as when a template does not exist) this method will either return an edit link to the * template topic page, or if allowTemplateEdit is <code>false</code> it will return * <code>null</code> (used with substitutions, where an edit link should not be shown). */ private String parseTemplateOutput(ParserInput parserInput, ParserOutput parserOutput, int mode, String raw, boolean allowTemplateEdit) throws DataAccessException, ParserException { String templateContent = raw.substring("{{".length(), raw.length() - "}}".length()); parserInput.incrementTemplateDepth(); if (parserInput.getTemplateDepth() > Environment.getIntValue(Environment.PROP_PARSER_MAX_TEMPLATE_DEPTH)) { parserInput.decrementTemplateDepth(); throw new ExcessiveNestingException("Potentially infinite parsing loop - over " + parserInput.getTemplateDepth() + " template inclusions while parsing topic " + parserInput.getTopicName()); } // check for magic word or parser function String[] parserFunctionInfo = ParserFunctionUtil.parseParserFunctionInfo(parserInput, mode, templateContent); String result = null; if (MagicWordUtil.isMagicWord(templateContent) || parserFunctionInfo != null) { if (mode <= JFlexParser.MODE_MINIMAL) { result = raw; } else if (MagicWordUtil.isMagicWord(templateContent)) { result = MagicWordUtil.processMagicWord(parserInput, templateContent); } else { result = ParserFunctionUtil.processParserFunction(parserInput, parserOutput, mode, parserFunctionInfo[0], parserFunctionInfo[1]); } parserInput.decrementTemplateDepth(); return result; } // update the raw value to handle cases such as a signature in the template content raw = "{{" + templateContent + "}}"; // check for substitution ("{{subst:Template}}") String subst = this.parseSubstitution(parserInput, parserOutput, raw, templateContent); if (subst != null) { parserInput.decrementTemplateDepth(); return subst; } // extract the template name WikiLink wikiLink = this.parseTemplateName(parserInput.getVirtualWiki(), templateContent); String name = wikiLink.getDestination(); + // parse in case of something like "{{PAGENAME}}/template" + name = JFlexParserUtil.parseFragment(parserInput, parserOutput, name, JFlexParser.MODE_TEMPLATE); // now see if a template with that name exists or if this is an inclusion Topic templateTopic = null; boolean inclusion = wikiLink.getColon(); String templateName = name; if (!wikiLink.getColon()) { if (!wikiLink.getNamespace().equals(Namespace.namespace(Namespace.TEMPLATE_ID))) { templateName = Namespace.namespace(Namespace.TEMPLATE_ID).getLabel(parserInput.getVirtualWiki()) + Namespace.SEPARATOR + StringUtils.capitalize(name); } templateTopic = WikiBase.getDataHandler().lookupTopic(parserInput.getVirtualWiki(), templateName, false, null); } if (templateTopic != null) { name = templateName; } else { // otherwise see if it's an inclusion templateTopic = WikiBase.getDataHandler().lookupTopic(parserInput.getVirtualWiki(), name, false, null); name = ((templateTopic == null && !wikiLink.getColon()) ? templateName : name); inclusion = (templateTopic != null || wikiLink.getColon()); } // get the parsed template body this.processTemplateMetadata(parserOutput, templateTopic, name); if (mode <= JFlexParser.MODE_MINIMAL) { result = raw; } else { // make sure template was not redirected if (templateTopic != null && templateTopic.getTopicType() == TopicType.REDIRECT) { templateTopic = WikiUtil.findRedirectedTopic(templateTopic, 0); name = templateTopic.getName(); } if (templateTopic != null && templateTopic.getTopicType() == TopicType.REDIRECT) { // redirection target does not exist templateTopic = null; } if (inclusion) { result = this.processTemplateInclusion(parserInput, parserOutput, templateTopic, templateContent, name); } else if (templateTopic == null) { result = ((allowTemplateEdit) ? "[[" + name + "]]" : null); } else { result = this.processTemplateContent(parserInput, parserOutput, templateTopic, templateContent); } } parserInput.decrementTemplateDepth(); return result; } /** * Given template parameter content of the form "name" or "name|default", * return the default value if it exists. */ private String parseParamDefaultValue(ParserInput parserInput, ParserOutput parserOutput, String raw) throws ParserException { List<String> tokens = JFlexParserUtil.tokenizeParamString(raw); if (tokens.size() < 2) { return null; } // table elements mess up default processing, so just return anything after // the first parameter to avoid having to implement special table logic String param1 = tokens.get(0); String value = raw.substring(param1.length() + 1); return JFlexParserUtil.parseFragment(parserInput, parserOutput, value, JFlexParser.MODE_TEMPLATE); } /** * Given template parameter content of the form "name" or "name|default", * return the parameter name. */ private String parseParamName(String raw) throws ParserException { int pos = raw.indexOf('|'); String name = ((pos != -1) ? raw.substring(0, pos) : raw).trim(); if (StringUtils.isBlank(name)) { // FIXME - no need for an exception throw new ParserException("No parameter name specified"); } return name; } /** * Determine if template content is of the form "subst:XXX". If it is, * process it, otherwise return <code>null</code>. */ private String parseSubstitution(ParserInput parserInput, ParserOutput parserOutput, String raw, String templateContent) throws DataAccessException, ParserException { // is it a substitution? templateContent = templateContent.trim(); if (!this.isSubstitution(templateContent)) { return null; } // get the substitution content String substContent = templateContent.trim().substring("subst:".length()).trim(); if (substContent.length() == 0) { return null; } // re-parse the substitution value. make sure it is parsed in at least MODE_TEMPLATE // so that values are properly replaced prior to saving. String output = this.parseTemplateOutput(parserInput, parserOutput, JFlexParser.MODE_TEMPLATE, "{{" + substContent + "}}", false); return (output == null) ? raw : output; } /** * After template parameter values have been set, process the template body * and replace parameters with parameter values or defaults, processing any * embedded parameters or templates. */ private String parseTemplateBody(ParserInput parserInput, ParserOutput parserOutput, String content, Map<String, String> parameterValues) throws ParserException { StringBuilder output = new StringBuilder(); char current; // find template parameters of the form {{{0}}} for (int pos = 0; pos < content.length(); pos++) { current = content.charAt(pos); String substring = content.substring(pos); if (!substring.startsWith("{{{")) { // not a template parameter, move to the next character output.append(current); continue; } // this may be a template parameter, but check for various sub-patterns to be sure int endPos = Utilities.findMatchingEndTag(content, pos, "{{{", "}}}"); if (endPos == -1) { // no matching end tag output.append(current); continue; } // there are several sub-patterns that need to be analyzed: // 1. {{{1|{{PAGENAME}}}}} // 2. {{{{{1}}}}} // 3. {{{template}} x {{template}}} // 4. {{{1|{{{2}}}}}} int case1EndPos = Utilities.findMatchingEndTag(content, pos, "{", "}"); if (endPos < case1EndPos && content.substring(case1EndPos - 3, case1EndPos).equals("}}}")) { // case #1 endPos = case1EndPos; } if (substring.startsWith("{{{{{") && content.substring(endPos - 5, endPos).equals("}}}}}")) { // case #2 (note: endPos updated in the previous step) output.append("{{"); pos++; continue; } int case3EndPos = Utilities.findMatchingEndTag(content, pos + 1, "{{", "}}"); if (case3EndPos != (endPos - 1)) { // either case #3 or case #4 char case4Char = content.charAt(case3EndPos + 1); if (case4Char != '}') { // case #3 output.append(current); continue; } } String param = content.substring(pos, endPos); output.append(this.applyParameter(parserInput, parserOutput, param, parameterValues)); pos = endPos - 1; } String result = JFlexParserUtil.parseFragment(parserInput, parserOutput, output.toString().trim(), JFlexParser.MODE_TEMPLATE); return result; } /** * Given a template call of the form "template|param|param", return * the template name. */ private WikiLink parseTemplateName(String virtualWiki, String raw) throws ParserException { String name = raw; int pos = raw.indexOf('|'); if (pos != -1) { name = name.substring(0, pos); } name = Utilities.decodeTopicName(name.trim(), true); if (StringUtils.isBlank(name)) { // FIXME - no need for an exception throw new ParserException("No template name specified"); } boolean inclusion = false; if (name.startsWith(Namespace.SEPARATOR)) { if (name.length() == 1) { // FIXME - no need for an exception throw new ParserException("No template name specified"); } inclusion = true; name = name.substring(1).trim(); } WikiLink wikiLink = LinkUtil.parseWikiLink(virtualWiki, name); wikiLink.setColon(inclusion); return wikiLink; } /** * Given a template call of the form "{{name|param=value|param=value}}" * parse the parameter names and values. */ private Map<String, String> parseTemplateParameterValues(String templateContent) throws ParserException { Map<String, String> parameterValues = new HashMap<String, String>(); List<String> tokens = JFlexParserUtil.tokenizeParamString(templateContent); if (tokens.isEmpty()) { throw new ParserException("No template name found in " + templateContent); } int count = -1; for (String token : tokens) { count++; if (count == 0) { // first token is template name continue; } String[] nameValue = this.tokenizeNameValue(token); String value = (nameValue[1] == null) ? null : nameValue[1].trim(); // the user can specify params of the form "2=first|1=second", so check to make // sure an index value hasn't already been used. if (!parameterValues.containsKey(Integer.toString(count))) { parameterValues.put(Integer.toString(count), value); } // if there is a named parameter store it as well as a count-based parameter, just in // case the template specifies both if (!StringUtils.isBlank(nameValue[0])) { parameterValues.put(nameValue[0].trim(), value); } } return parameterValues; } /** * Given a template call of the form "{{name|param|param}}" return the * parsed output. */ private String processTemplateContent(ParserInput parserInput, ParserOutput parserOutput, Topic templateTopic, String templateContent) throws ParserException { // set template parameter values Map<String, String> parameterValues = this.parseTemplateParameterValues(templateContent); // parse the template content for noinclude, onlyinclude and includeonly tags String templateBody = JFlexParserUtil.parseFragment(parserInput, parserOutput, templateTopic.getTopicContent().trim(), JFlexParser.MODE_TEMPLATE_BODY); if (parserInput.getTempParams().get(TEMPLATE_ONLYINCLUDE) != null) { // HACK! If an onlyinclude tag is encountered in the previous fragment parse // then that tag's parsed output is stored in the TEMPLATE_ONLYINCLUDE param. // This hack is necessary because onlyinclude indicates that ONLY the // onlyinclude content is relevant, and anything parsed before or after that // tag must be ignored. templateBody = (String)parserInput.getTempParams().get(TEMPLATE_ONLYINCLUDE); parserInput.getTempParams().remove(TEMPLATE_ONLYINCLUDE); } return this.parseTemplateBody(parserInput, parserOutput, templateBody, parameterValues); } /** * Given a template call of the form "{{:name}}" parse the template * inclusion. */ private String processTemplateInclusion(ParserInput parserInput, ParserOutput parserOutput, Topic templateTopic, String templateContent, String name) throws ParserException { if (templateTopic == null) { return "[[" + name + "]]"; } // FIXME - disable section editing int inclusion = (parserInput.getTempParams().get(TEMPLATE_INCLUSION) == null) ? 1 : (Integer)parserInput.getTempParams().get(TEMPLATE_INCLUSION) + 1; if (inclusion > Environment.getIntValue(Environment.PROP_PARSER_MAX_INCLUSIONS)) { throw new ExcessiveNestingException("Potentially infinite inclusions - over " + inclusion + " template inclusions while parsing topic " + parserInput.getTopicName()); } parserInput.getTempParams().put(TEMPLATE_INCLUSION, inclusion); return this.processTemplateContent(parserInput, parserOutput, templateTopic, templateContent); } /** * Process template values, setting link and other metadata output values. */ private void processTemplateMetadata(ParserOutput parserOutput, Topic templateTopic, String name) { name = (templateTopic != null) ? templateTopic.getName() : name; parserOutput.addLink(name); parserOutput.addTemplate(name); } /** * */ private String[] tokenizeNameValue(String content) { String[] results = new String[2]; results[0] = null; results[1] = content; Matcher m = PARAM_NAME_VALUE_PATTERN.matcher(content); if (m.matches()) { results[0] = m.group(1); results[1] = m.group(2); } return results; } }
true
true
private String parseTemplateOutput(ParserInput parserInput, ParserOutput parserOutput, int mode, String raw, boolean allowTemplateEdit) throws DataAccessException, ParserException { String templateContent = raw.substring("{{".length(), raw.length() - "}}".length()); parserInput.incrementTemplateDepth(); if (parserInput.getTemplateDepth() > Environment.getIntValue(Environment.PROP_PARSER_MAX_TEMPLATE_DEPTH)) { parserInput.decrementTemplateDepth(); throw new ExcessiveNestingException("Potentially infinite parsing loop - over " + parserInput.getTemplateDepth() + " template inclusions while parsing topic " + parserInput.getTopicName()); } // check for magic word or parser function String[] parserFunctionInfo = ParserFunctionUtil.parseParserFunctionInfo(parserInput, mode, templateContent); String result = null; if (MagicWordUtil.isMagicWord(templateContent) || parserFunctionInfo != null) { if (mode <= JFlexParser.MODE_MINIMAL) { result = raw; } else if (MagicWordUtil.isMagicWord(templateContent)) { result = MagicWordUtil.processMagicWord(parserInput, templateContent); } else { result = ParserFunctionUtil.processParserFunction(parserInput, parserOutput, mode, parserFunctionInfo[0], parserFunctionInfo[1]); } parserInput.decrementTemplateDepth(); return result; } // update the raw value to handle cases such as a signature in the template content raw = "{{" + templateContent + "}}"; // check for substitution ("{{subst:Template}}") String subst = this.parseSubstitution(parserInput, parserOutput, raw, templateContent); if (subst != null) { parserInput.decrementTemplateDepth(); return subst; } // extract the template name WikiLink wikiLink = this.parseTemplateName(parserInput.getVirtualWiki(), templateContent); String name = wikiLink.getDestination(); // now see if a template with that name exists or if this is an inclusion Topic templateTopic = null; boolean inclusion = wikiLink.getColon(); String templateName = name; if (!wikiLink.getColon()) { if (!wikiLink.getNamespace().equals(Namespace.namespace(Namespace.TEMPLATE_ID))) { templateName = Namespace.namespace(Namespace.TEMPLATE_ID).getLabel(parserInput.getVirtualWiki()) + Namespace.SEPARATOR + StringUtils.capitalize(name); } templateTopic = WikiBase.getDataHandler().lookupTopic(parserInput.getVirtualWiki(), templateName, false, null); } if (templateTopic != null) { name = templateName; } else { // otherwise see if it's an inclusion templateTopic = WikiBase.getDataHandler().lookupTopic(parserInput.getVirtualWiki(), name, false, null); name = ((templateTopic == null && !wikiLink.getColon()) ? templateName : name); inclusion = (templateTopic != null || wikiLink.getColon()); } // get the parsed template body this.processTemplateMetadata(parserOutput, templateTopic, name); if (mode <= JFlexParser.MODE_MINIMAL) { result = raw; } else { // make sure template was not redirected if (templateTopic != null && templateTopic.getTopicType() == TopicType.REDIRECT) { templateTopic = WikiUtil.findRedirectedTopic(templateTopic, 0); name = templateTopic.getName(); } if (templateTopic != null && templateTopic.getTopicType() == TopicType.REDIRECT) { // redirection target does not exist templateTopic = null; } if (inclusion) { result = this.processTemplateInclusion(parserInput, parserOutput, templateTopic, templateContent, name); } else if (templateTopic == null) { result = ((allowTemplateEdit) ? "[[" + name + "]]" : null); } else { result = this.processTemplateContent(parserInput, parserOutput, templateTopic, templateContent); } } parserInput.decrementTemplateDepth(); return result; }
private String parseTemplateOutput(ParserInput parserInput, ParserOutput parserOutput, int mode, String raw, boolean allowTemplateEdit) throws DataAccessException, ParserException { String templateContent = raw.substring("{{".length(), raw.length() - "}}".length()); parserInput.incrementTemplateDepth(); if (parserInput.getTemplateDepth() > Environment.getIntValue(Environment.PROP_PARSER_MAX_TEMPLATE_DEPTH)) { parserInput.decrementTemplateDepth(); throw new ExcessiveNestingException("Potentially infinite parsing loop - over " + parserInput.getTemplateDepth() + " template inclusions while parsing topic " + parserInput.getTopicName()); } // check for magic word or parser function String[] parserFunctionInfo = ParserFunctionUtil.parseParserFunctionInfo(parserInput, mode, templateContent); String result = null; if (MagicWordUtil.isMagicWord(templateContent) || parserFunctionInfo != null) { if (mode <= JFlexParser.MODE_MINIMAL) { result = raw; } else if (MagicWordUtil.isMagicWord(templateContent)) { result = MagicWordUtil.processMagicWord(parserInput, templateContent); } else { result = ParserFunctionUtil.processParserFunction(parserInput, parserOutput, mode, parserFunctionInfo[0], parserFunctionInfo[1]); } parserInput.decrementTemplateDepth(); return result; } // update the raw value to handle cases such as a signature in the template content raw = "{{" + templateContent + "}}"; // check for substitution ("{{subst:Template}}") String subst = this.parseSubstitution(parserInput, parserOutput, raw, templateContent); if (subst != null) { parserInput.decrementTemplateDepth(); return subst; } // extract the template name WikiLink wikiLink = this.parseTemplateName(parserInput.getVirtualWiki(), templateContent); String name = wikiLink.getDestination(); // parse in case of something like "{{PAGENAME}}/template" name = JFlexParserUtil.parseFragment(parserInput, parserOutput, name, JFlexParser.MODE_TEMPLATE); // now see if a template with that name exists or if this is an inclusion Topic templateTopic = null; boolean inclusion = wikiLink.getColon(); String templateName = name; if (!wikiLink.getColon()) { if (!wikiLink.getNamespace().equals(Namespace.namespace(Namespace.TEMPLATE_ID))) { templateName = Namespace.namespace(Namespace.TEMPLATE_ID).getLabel(parserInput.getVirtualWiki()) + Namespace.SEPARATOR + StringUtils.capitalize(name); } templateTopic = WikiBase.getDataHandler().lookupTopic(parserInput.getVirtualWiki(), templateName, false, null); } if (templateTopic != null) { name = templateName; } else { // otherwise see if it's an inclusion templateTopic = WikiBase.getDataHandler().lookupTopic(parserInput.getVirtualWiki(), name, false, null); name = ((templateTopic == null && !wikiLink.getColon()) ? templateName : name); inclusion = (templateTopic != null || wikiLink.getColon()); } // get the parsed template body this.processTemplateMetadata(parserOutput, templateTopic, name); if (mode <= JFlexParser.MODE_MINIMAL) { result = raw; } else { // make sure template was not redirected if (templateTopic != null && templateTopic.getTopicType() == TopicType.REDIRECT) { templateTopic = WikiUtil.findRedirectedTopic(templateTopic, 0); name = templateTopic.getName(); } if (templateTopic != null && templateTopic.getTopicType() == TopicType.REDIRECT) { // redirection target does not exist templateTopic = null; } if (inclusion) { result = this.processTemplateInclusion(parserInput, parserOutput, templateTopic, templateContent, name); } else if (templateTopic == null) { result = ((allowTemplateEdit) ? "[[" + name + "]]" : null); } else { result = this.processTemplateContent(parserInput, parserOutput, templateTopic, templateContent); } } parserInput.decrementTemplateDepth(); return result; }
diff --git a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/submission/Submissions.java b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/submission/Submissions.java index f72f4fee7..e80ca69d7 100644 --- a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/submission/Submissions.java +++ b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/submission/Submissions.java @@ -1,430 +1,431 @@ /** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.submission; import java.io.IOException; import java.sql.SQLException; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.utils.UIException; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Cell; import org.dspace.app.xmlui.wing.element.CheckBox; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Para; import org.dspace.app.xmlui.wing.element.Row; import org.dspace.app.xmlui.wing.element.Table; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Collection; import org.dspace.content.DCValue; import org.dspace.content.Item; import org.dspace.content.ItemIterator; import org.dspace.content.SupervisedItem; import org.dspace.content.WorkspaceItem; import org.dspace.core.Constants; import org.dspace.eperson.EPerson; import org.xml.sax.SAXException; /** * @author Scott Phillips */ public class Submissions extends AbstractDSpaceTransformer { /** General Language Strings */ protected static final Message T_title = message("xmlui.Submission.Submissions.title"); protected static final Message T_dspace_home = message("xmlui.general.dspace_home"); protected static final Message T_trail = message("xmlui.Submission.Submissions.trail"); protected static final Message T_head = message("xmlui.Submission.Submissions.head"); protected static final Message T_untitled = message("xmlui.Submission.Submissions.untitled"); protected static final Message T_email = message("xmlui.Submission.Submissions.email"); // used by the unfinished submissions section protected static final Message T_s_head1 = message("xmlui.Submission.Submissions.submit_head1"); protected static final Message T_s_info1a = message("xmlui.Submission.Submissions.submit_info1a"); protected static final Message T_s_info1b = message("xmlui.Submission.Submissions.submit_info1b"); protected static final Message T_s_info1c = message("xmlui.Submission.Submissions.submit_info1c"); protected static final Message T_s_head2 = message("xmlui.Submission.Submissions.submit_head2"); protected static final Message T_s_info2a = message("xmlui.Submission.Submissions.submit_info2a"); protected static final Message T_s_info2b = message("xmlui.Submission.Submissions.submit_info2b"); protected static final Message T_s_info2c = message("xmlui.Submission.Submissions.submit_info2c"); protected static final Message T_s_column1 = message("xmlui.Submission.Submissions.submit_column1"); protected static final Message T_s_column2 = message("xmlui.Submission.Submissions.submit_column2"); protected static final Message T_s_column3 = message("xmlui.Submission.Submissions.submit_column3"); protected static final Message T_s_column4 = message("xmlui.Submission.Submissions.submit_column4"); protected static final Message T_s_head3 = message("xmlui.Submission.Submissions.submit_head3"); protected static final Message T_s_info3 = message("xmlui.Submission.Submissions.submit_info3"); protected static final Message T_s_head4 = message("xmlui.Submission.Submissions.submit_head4"); protected static final Message T_s_submit_remove = message("xmlui.Submission.Submissions.submit_submit_remove"); // Used in the completed submissions section protected static final Message T_c_head = message("xmlui.Submission.Submissions.completed.head"); protected static final Message T_c_info = message("xmlui.Submission.Submissions.completed.info"); protected static final Message T_c_column1 = message("xmlui.Submission.Submissions.completed.column1"); protected static final Message T_c_column2 = message("xmlui.Submission.Submissions.completed.column2"); protected static final Message T_c_column3 = message("xmlui.Submission.Submissions.completed.column3"); protected static final Message T_c_limit = message("xmlui.Submission.Submissions.completed.limit"); protected static final Message T_c_displayall = message("xmlui.Submission.Submissions.completed.displayall"); @Override public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/",T_dspace_home); pageMeta.addTrailLink(null,T_trail); } @Override public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { Request request = ObjectModelHelper.getRequest(objectModel); boolean displayAll = false; //This param decides whether we display all of the user's previous // submissions, or just a portion of them if (request.getParameter("all") != null) { displayAll=true; } Division div = body.addInteractiveDivision("submissions", contextPath+"/submissions", Division.METHOD_POST,"primary"); div.setHead(T_head); // this.addWorkflowTasksDiv(div); this.addUnfinishedSubmissions(div); // this.addSubmissionsInWorkflowDiv(div); this.addPreviousSubmissions(div, displayAll); } /** * If the user has any workflow tasks, either assigned to them or in an * available pool of tasks, then build two tables listing each of these queues. * * If the user doesn't have any workflows then don't do anything. * * @param division The division to add the two queues too. */ private void addWorkflowTasksDiv(Division division) throws SQLException, WingException, AuthorizeException, IOException { division.addDivision("workflow-tasks"); } /** * There are two options: the user has some unfinished submissions * or the user does not. * * If the user does not, then we just display a simple paragraph * explaining that the user may submit new items to dspace. * * If the user does have unfinished submissions then a table is * presented listing all the unfinished submissions that this user has. * */ private void addUnfinishedSubmissions(Division division) throws SQLException, WingException { // User's WorkflowItems WorkspaceItem[] unfinishedItems = WorkspaceItem.findByEPerson(context,context.getCurrentUser()); SupervisedItem[] supervisedItems = SupervisedItem.findbyEPerson(context, context.getCurrentUser()); if (unfinishedItems.length <= 0 && supervisedItems.length <= 0) { Collection[] collections = Collection.findAuthorized(context, null, Constants.ADD); if (collections.length > 0) { Division start = division.addDivision("start-submision"); start.setHead(T_s_head1); Para p = start.addPara(); p.addContent(T_s_info1a); p.addXref(contextPath+"/submit",T_s_info1b); - p.addContent(T_s_info1c); + Para secondP = start.addPara(); + secondP.addContent(T_s_info1c); return; } } Division unfinished = division.addDivision("unfinished-submisions"); unfinished.setHead(T_s_head2); Para p = unfinished.addPara(); p.addContent(T_s_info2a); p.addHighlight("bold").addXref(contextPath+"/submit",T_s_info2b); p.addContent(T_s_info2c); // Calculate the number of rows. // Each list pluss the top header and bottom row for the button. int rows = unfinishedItems.length + supervisedItems.length + 2; if (supervisedItems.length > 0 && unfinishedItems.length > 0) { rows++; // Authoring heading row } if (supervisedItems.length > 0) { rows++; // Supervising heading row } Table table = unfinished.addTable("unfinished-submissions",rows,5); Row header = table.addRow(Row.ROLE_HEADER); header.addCellContent(T_s_column1); header.addCellContent(T_s_column2); header.addCellContent(T_s_column3); header.addCellContent(T_s_column4); if (supervisedItems.length > 0 && unfinishedItems.length > 0) { header = table.addRow(); header.addCell(null,Cell.ROLE_HEADER,0,5,null).addContent(T_s_head3); } if (unfinishedItems.length > 0) { for (WorkspaceItem workspaceItem : unfinishedItems) { DCValue[] titles = workspaceItem.getItem().getDC("title", null, Item.ANY); EPerson submitterEPerson = workspaceItem.getItem().getSubmitter(); int workspaceItemID = workspaceItem.getID(); String url = contextPath+"/submit?workspaceID="+workspaceItemID; String submitterName = submitterEPerson.getFullName(); String submitterEmail = submitterEPerson.getEmail(); String collectionName = workspaceItem.getCollection().getMetadata("name"); Row row = table.addRow(Row.ROLE_DATA); CheckBox remove = row.addCell().addCheckBox("workspaceID"); remove.setLabel("remove"); remove.addOption(workspaceItemID); if (titles.length > 0) { String displayTitle = titles[0].value; if (displayTitle.length() > 50) displayTitle = displayTitle.substring(0, 50) + " ..."; row.addCell().addXref(url,displayTitle); } else row.addCell().addXref(url,T_untitled); row.addCell().addXref(url,collectionName); Cell cell = row.addCell(); cell.addContent(T_email); cell.addXref("mailto:"+submitterEmail,submitterName); } } else { header = table.addRow(); header.addCell(0,5).addHighlight("italic").addContent(T_s_info3); } if (supervisedItems.length > 0) { header = table.addRow(); header.addCell(null,Cell.ROLE_HEADER,0,5,null).addContent(T_s_head4); } for (WorkspaceItem workspaceItem : supervisedItems) { DCValue[] titles = workspaceItem.getItem().getDC("title", null, Item.ANY); EPerson submitterEPerson = workspaceItem.getItem().getSubmitter(); int workspaceItemID = workspaceItem.getID(); String url = contextPath+"/submit?workspaceID="+workspaceItemID; String submitterName = submitterEPerson.getFullName(); String submitterEmail = submitterEPerson.getEmail(); String collectionName = workspaceItem.getCollection().getMetadata("name"); Row row = table.addRow(Row.ROLE_DATA); CheckBox selected = row.addCell().addCheckBox("workspaceID"); selected.setLabel("select"); selected.addOption(workspaceItemID); if (titles.length > 0) { String displayTitle = titles[0].value; if (displayTitle.length() > 50) { displayTitle = displayTitle.substring(0, 50) + " ..."; } row.addCell().addXref(url,displayTitle); } else { row.addCell().addXref(url, T_untitled); } row.addCell().addXref(url,collectionName); Cell cell = row.addCell(); cell.addContent(T_email); cell.addXref("mailto:"+submitterEmail,submitterName); } header = table.addRow(); Cell lastCell = header.addCell(0,5); if (unfinishedItems.length > 0 || supervisedItems.length > 0) { lastCell.addButton("submit_submissions_remove").setValue(T_s_submit_remove); } } /** * This section lists all the submissions that this user has submitted which are currently under review. * * If the user has none, this nothing is displayed. */ private void addSubmissionsInWorkflowDiv(Division division) throws SQLException, WingException, AuthorizeException, IOException { division.addDivision("submissions-inprogress"); } /** * Show the user's completed submissions. * * If the user has no completed submissions, display nothing. * If 'displayAll' is true, then display all user's archived submissions. * Otherwise, default to only displaying 50 archived submissions. * * @param division div to put archived submissions in * @param displayAll whether to display all or just a limited number. */ private void addPreviousSubmissions(Division division, boolean displayAll) throws SQLException,WingException { // Turn the iterator into a list (to get size info, in order to put in a table) List subList = new LinkedList(); ItemIterator subs = Item.findBySubmitter(context, context.getCurrentUser()); //NOTE: notice we are adding each item to this list in *reverse* order... // this is a very basic attempt at making more recent submissions float // up to the top of the list (findBySubmitter() doesn't guarrantee // chronological order, but tends to return older items near top of the list) try { while (subs.hasNext()) { subList.add(0, subs.next()); } } finally { if (subs != null) subs.close(); } // No tasks, so don't show the table. if (!(subList.size() > 0)) return; Division completedSubmissions = division.addDivision("completed-submissions"); completedSubmissions.setHead(T_c_head); completedSubmissions.addPara(T_c_info); // Create table, headers Table table = completedSubmissions.addTable("completed-submissions",subList.size() + 2,3); Row header = table.addRow(Row.ROLE_HEADER); header.addCellContent(T_c_column1); // ISSUE DATE header.addCellContent(T_c_column2); // ITEM TITLE (LINKED) header.addCellContent(T_c_column3); // COLLECTION NAME (LINKED) //Limit to showing just 50 archived submissions, unless overridden //(This is a saftey measure for Admins who may have submitted // thousands of items under their account via bulk ingest tools, etc.) int limit = 50; int count = 0; // Populate table Iterator i = subList.iterator(); while(i.hasNext()) { count++; //exit loop if we've gone over our limit of submissions to display if(count>limit && !displayAll) break; Item published = (Item) i.next(); String collUrl = contextPath+"/handle/"+published.getOwningCollection().getHandle(); String itemUrl = contextPath+"/handle/"+published.getHandle(); DCValue[] titles = published.getMetadata("dc", "title", null, Item.ANY); String collectionName = published.getOwningCollection().getMetadata("name"); DCValue[] ingestDate = published.getMetadata("dc", "date", "accessioned", Item.ANY); Row row = table.addRow(); // Item accession date if (ingestDate != null && ingestDate.length > 0 && ingestDate[0].value != null) { String displayDate = ingestDate[0].value.substring(0,10); Cell cellDate = row.addCell(); cellDate.addContent(displayDate); } else //if no accession date add an empty cell (shouldn't happen, but just in case) row.addCell().addContent(""); // The item description if (titles != null && titles.length > 0 && titles[0].value != null) { String displayTitle = titles[0].value; if (displayTitle.length() > 50) displayTitle = displayTitle.substring(0,50)+ " ..."; row.addCell().addXref(itemUrl,displayTitle); } else row.addCell().addXref(itemUrl,T_untitled); // Owning Collection row.addCell().addXref(collUrl,collectionName); }//end while //Display limit text & link to allow user to override this default limit if(!displayAll && count>limit) { Para limitedList = completedSubmissions.addPara(); limitedList.addContent(T_c_limit); limitedList.addXref(contextPath + "/submissions?all", T_c_displayall); } } }
true
true
private void addUnfinishedSubmissions(Division division) throws SQLException, WingException { // User's WorkflowItems WorkspaceItem[] unfinishedItems = WorkspaceItem.findByEPerson(context,context.getCurrentUser()); SupervisedItem[] supervisedItems = SupervisedItem.findbyEPerson(context, context.getCurrentUser()); if (unfinishedItems.length <= 0 && supervisedItems.length <= 0) { Collection[] collections = Collection.findAuthorized(context, null, Constants.ADD); if (collections.length > 0) { Division start = division.addDivision("start-submision"); start.setHead(T_s_head1); Para p = start.addPara(); p.addContent(T_s_info1a); p.addXref(contextPath+"/submit",T_s_info1b); p.addContent(T_s_info1c); return; } } Division unfinished = division.addDivision("unfinished-submisions"); unfinished.setHead(T_s_head2); Para p = unfinished.addPara(); p.addContent(T_s_info2a); p.addHighlight("bold").addXref(contextPath+"/submit",T_s_info2b); p.addContent(T_s_info2c); // Calculate the number of rows. // Each list pluss the top header and bottom row for the button. int rows = unfinishedItems.length + supervisedItems.length + 2; if (supervisedItems.length > 0 && unfinishedItems.length > 0) { rows++; // Authoring heading row } if (supervisedItems.length > 0) { rows++; // Supervising heading row } Table table = unfinished.addTable("unfinished-submissions",rows,5); Row header = table.addRow(Row.ROLE_HEADER); header.addCellContent(T_s_column1); header.addCellContent(T_s_column2); header.addCellContent(T_s_column3); header.addCellContent(T_s_column4); if (supervisedItems.length > 0 && unfinishedItems.length > 0) { header = table.addRow(); header.addCell(null,Cell.ROLE_HEADER,0,5,null).addContent(T_s_head3); } if (unfinishedItems.length > 0) { for (WorkspaceItem workspaceItem : unfinishedItems) { DCValue[] titles = workspaceItem.getItem().getDC("title", null, Item.ANY); EPerson submitterEPerson = workspaceItem.getItem().getSubmitter(); int workspaceItemID = workspaceItem.getID(); String url = contextPath+"/submit?workspaceID="+workspaceItemID; String submitterName = submitterEPerson.getFullName(); String submitterEmail = submitterEPerson.getEmail(); String collectionName = workspaceItem.getCollection().getMetadata("name"); Row row = table.addRow(Row.ROLE_DATA); CheckBox remove = row.addCell().addCheckBox("workspaceID"); remove.setLabel("remove"); remove.addOption(workspaceItemID); if (titles.length > 0) { String displayTitle = titles[0].value; if (displayTitle.length() > 50) displayTitle = displayTitle.substring(0, 50) + " ..."; row.addCell().addXref(url,displayTitle); } else row.addCell().addXref(url,T_untitled); row.addCell().addXref(url,collectionName); Cell cell = row.addCell(); cell.addContent(T_email); cell.addXref("mailto:"+submitterEmail,submitterName); } } else { header = table.addRow(); header.addCell(0,5).addHighlight("italic").addContent(T_s_info3); } if (supervisedItems.length > 0) { header = table.addRow(); header.addCell(null,Cell.ROLE_HEADER,0,5,null).addContent(T_s_head4); } for (WorkspaceItem workspaceItem : supervisedItems) { DCValue[] titles = workspaceItem.getItem().getDC("title", null, Item.ANY); EPerson submitterEPerson = workspaceItem.getItem().getSubmitter(); int workspaceItemID = workspaceItem.getID(); String url = contextPath+"/submit?workspaceID="+workspaceItemID; String submitterName = submitterEPerson.getFullName(); String submitterEmail = submitterEPerson.getEmail(); String collectionName = workspaceItem.getCollection().getMetadata("name"); Row row = table.addRow(Row.ROLE_DATA); CheckBox selected = row.addCell().addCheckBox("workspaceID"); selected.setLabel("select"); selected.addOption(workspaceItemID); if (titles.length > 0) { String displayTitle = titles[0].value; if (displayTitle.length() > 50) { displayTitle = displayTitle.substring(0, 50) + " ..."; } row.addCell().addXref(url,displayTitle); } else { row.addCell().addXref(url, T_untitled); } row.addCell().addXref(url,collectionName); Cell cell = row.addCell(); cell.addContent(T_email); cell.addXref("mailto:"+submitterEmail,submitterName); } header = table.addRow(); Cell lastCell = header.addCell(0,5); if (unfinishedItems.length > 0 || supervisedItems.length > 0) { lastCell.addButton("submit_submissions_remove").setValue(T_s_submit_remove); } }
private void addUnfinishedSubmissions(Division division) throws SQLException, WingException { // User's WorkflowItems WorkspaceItem[] unfinishedItems = WorkspaceItem.findByEPerson(context,context.getCurrentUser()); SupervisedItem[] supervisedItems = SupervisedItem.findbyEPerson(context, context.getCurrentUser()); if (unfinishedItems.length <= 0 && supervisedItems.length <= 0) { Collection[] collections = Collection.findAuthorized(context, null, Constants.ADD); if (collections.length > 0) { Division start = division.addDivision("start-submision"); start.setHead(T_s_head1); Para p = start.addPara(); p.addContent(T_s_info1a); p.addXref(contextPath+"/submit",T_s_info1b); Para secondP = start.addPara(); secondP.addContent(T_s_info1c); return; } } Division unfinished = division.addDivision("unfinished-submisions"); unfinished.setHead(T_s_head2); Para p = unfinished.addPara(); p.addContent(T_s_info2a); p.addHighlight("bold").addXref(contextPath+"/submit",T_s_info2b); p.addContent(T_s_info2c); // Calculate the number of rows. // Each list pluss the top header and bottom row for the button. int rows = unfinishedItems.length + supervisedItems.length + 2; if (supervisedItems.length > 0 && unfinishedItems.length > 0) { rows++; // Authoring heading row } if (supervisedItems.length > 0) { rows++; // Supervising heading row } Table table = unfinished.addTable("unfinished-submissions",rows,5); Row header = table.addRow(Row.ROLE_HEADER); header.addCellContent(T_s_column1); header.addCellContent(T_s_column2); header.addCellContent(T_s_column3); header.addCellContent(T_s_column4); if (supervisedItems.length > 0 && unfinishedItems.length > 0) { header = table.addRow(); header.addCell(null,Cell.ROLE_HEADER,0,5,null).addContent(T_s_head3); } if (unfinishedItems.length > 0) { for (WorkspaceItem workspaceItem : unfinishedItems) { DCValue[] titles = workspaceItem.getItem().getDC("title", null, Item.ANY); EPerson submitterEPerson = workspaceItem.getItem().getSubmitter(); int workspaceItemID = workspaceItem.getID(); String url = contextPath+"/submit?workspaceID="+workspaceItemID; String submitterName = submitterEPerson.getFullName(); String submitterEmail = submitterEPerson.getEmail(); String collectionName = workspaceItem.getCollection().getMetadata("name"); Row row = table.addRow(Row.ROLE_DATA); CheckBox remove = row.addCell().addCheckBox("workspaceID"); remove.setLabel("remove"); remove.addOption(workspaceItemID); if (titles.length > 0) { String displayTitle = titles[0].value; if (displayTitle.length() > 50) displayTitle = displayTitle.substring(0, 50) + " ..."; row.addCell().addXref(url,displayTitle); } else row.addCell().addXref(url,T_untitled); row.addCell().addXref(url,collectionName); Cell cell = row.addCell(); cell.addContent(T_email); cell.addXref("mailto:"+submitterEmail,submitterName); } } else { header = table.addRow(); header.addCell(0,5).addHighlight("italic").addContent(T_s_info3); } if (supervisedItems.length > 0) { header = table.addRow(); header.addCell(null,Cell.ROLE_HEADER,0,5,null).addContent(T_s_head4); } for (WorkspaceItem workspaceItem : supervisedItems) { DCValue[] titles = workspaceItem.getItem().getDC("title", null, Item.ANY); EPerson submitterEPerson = workspaceItem.getItem().getSubmitter(); int workspaceItemID = workspaceItem.getID(); String url = contextPath+"/submit?workspaceID="+workspaceItemID; String submitterName = submitterEPerson.getFullName(); String submitterEmail = submitterEPerson.getEmail(); String collectionName = workspaceItem.getCollection().getMetadata("name"); Row row = table.addRow(Row.ROLE_DATA); CheckBox selected = row.addCell().addCheckBox("workspaceID"); selected.setLabel("select"); selected.addOption(workspaceItemID); if (titles.length > 0) { String displayTitle = titles[0].value; if (displayTitle.length() > 50) { displayTitle = displayTitle.substring(0, 50) + " ..."; } row.addCell().addXref(url,displayTitle); } else { row.addCell().addXref(url, T_untitled); } row.addCell().addXref(url,collectionName); Cell cell = row.addCell(); cell.addContent(T_email); cell.addXref("mailto:"+submitterEmail,submitterName); } header = table.addRow(); Cell lastCell = header.addCell(0,5); if (unfinishedItems.length > 0 || supervisedItems.length > 0) { lastCell.addButton("submit_submissions_remove").setValue(T_s_submit_remove); } }
diff --git a/src/uk/org/ponder/rsf/renderer/html/HeadCollectingSCR.java b/src/uk/org/ponder/rsf/renderer/html/HeadCollectingSCR.java index 326518a..6b7d344 100644 --- a/src/uk/org/ponder/rsf/renderer/html/HeadCollectingSCR.java +++ b/src/uk/org/ponder/rsf/renderer/html/HeadCollectingSCR.java @@ -1,71 +1,72 @@ /* * Created on 18 Sep 2006 */ package uk.org.ponder.rsf.renderer.html; import java.util.HashSet; import java.util.Set; import uk.org.ponder.rsf.renderer.ComponentRenderer; import uk.org.ponder.rsf.renderer.RenderUtil; import uk.org.ponder.rsf.renderer.scr.CollectingSCR; import uk.org.ponder.rsf.template.XMLLump; import uk.org.ponder.rsf.template.XMLLumpList; import uk.org.ponder.streamutil.write.PrintOutputStream; import uk.org.ponder.xml.XMLWriter; /** * A basic collector of &lt;head&gt; material for HTML pages. Will emit all * collected &lt;style&gt; and &lt;script&gt; tags, and leave the tag in an open * condition. * * @author Antranig Basman ([email protected]) * */ public class HeadCollectingSCR implements CollectingSCR { public static final String NAME = "head-collect"; private URLRewriteSCR urlRewriteSCR; public String getName() { return NAME; } public String[] getCollectingNames() { return new String[] { "style", "script" }; } public void setURLRewriteSCR(URLRewriteSCR urlRewriteSCR) { this.urlRewriteSCR = urlRewriteSCR; } public int render(XMLLump lump, XMLLumpList collected, XMLWriter xmlw) { PrintOutputStream pos = xmlw.getInternalWriter(); RenderUtil.dumpTillLump(lump.parent.lumps, lump.lumpindex, lump.open_end.lumpindex + 1, pos); Set used = new HashSet(); for (int i = 0; i < collected.size(); ++i) { XMLLump collump = collected.lumpAt(i); String attr = URLRewriteSCR.getLinkAttribute(collump); if (attr != null) { String attrval = (String) collump.attributemap.get(attr); if (attrval != null) { String rewritten = urlRewriteSCR.resolveURL(collump.parent, attrval); + if (rewritten == null) rewritten = attrval; int qpos = rewritten.indexOf('?'); if (qpos != -1) rewritten = rewritten.substring(0, qpos); if (used.contains(rewritten)) continue; else used.add(rewritten); } } // TODO: equivalent of TagRenderContext for SCRs urlRewriteSCR.render(collump, xmlw); RenderUtil.dumpTillLump(collump.parent.lumps, collump.open_end.lumpindex + 1, collump.close_tag.lumpindex + 1, pos); } return ComponentRenderer.NESTING_TAG; } }
true
true
public int render(XMLLump lump, XMLLumpList collected, XMLWriter xmlw) { PrintOutputStream pos = xmlw.getInternalWriter(); RenderUtil.dumpTillLump(lump.parent.lumps, lump.lumpindex, lump.open_end.lumpindex + 1, pos); Set used = new HashSet(); for (int i = 0; i < collected.size(); ++i) { XMLLump collump = collected.lumpAt(i); String attr = URLRewriteSCR.getLinkAttribute(collump); if (attr != null) { String attrval = (String) collump.attributemap.get(attr); if (attrval != null) { String rewritten = urlRewriteSCR.resolveURL(collump.parent, attrval); int qpos = rewritten.indexOf('?'); if (qpos != -1) rewritten = rewritten.substring(0, qpos); if (used.contains(rewritten)) continue; else used.add(rewritten); } } // TODO: equivalent of TagRenderContext for SCRs urlRewriteSCR.render(collump, xmlw); RenderUtil.dumpTillLump(collump.parent.lumps, collump.open_end.lumpindex + 1, collump.close_tag.lumpindex + 1, pos); } return ComponentRenderer.NESTING_TAG; }
public int render(XMLLump lump, XMLLumpList collected, XMLWriter xmlw) { PrintOutputStream pos = xmlw.getInternalWriter(); RenderUtil.dumpTillLump(lump.parent.lumps, lump.lumpindex, lump.open_end.lumpindex + 1, pos); Set used = new HashSet(); for (int i = 0; i < collected.size(); ++i) { XMLLump collump = collected.lumpAt(i); String attr = URLRewriteSCR.getLinkAttribute(collump); if (attr != null) { String attrval = (String) collump.attributemap.get(attr); if (attrval != null) { String rewritten = urlRewriteSCR.resolveURL(collump.parent, attrval); if (rewritten == null) rewritten = attrval; int qpos = rewritten.indexOf('?'); if (qpos != -1) rewritten = rewritten.substring(0, qpos); if (used.contains(rewritten)) continue; else used.add(rewritten); } } // TODO: equivalent of TagRenderContext for SCRs urlRewriteSCR.render(collump, xmlw); RenderUtil.dumpTillLump(collump.parent.lumps, collump.open_end.lumpindex + 1, collump.close_tag.lumpindex + 1, pos); } return ComponentRenderer.NESTING_TAG; }
diff --git a/htroot/yacysearch.java b/htroot/yacysearch.java index 91348be4b..e441c40a5 100644 --- a/htroot/yacysearch.java +++ b/htroot/yacysearch.java @@ -1,565 +1,565 @@ // yacysearch.java // ----------------------- // part of the AnomicHTTPD caching proxy // (C) by Michael Peter Christen; [email protected] // first published on http://www.anomic.de // Frankfurt, Germany, 2004 // // $LastChangedDate$ // $LastChangedRevision$ // $LastChangedBy$ // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // You must compile this file with // javac -classpath .:../classes yacysearch.java // if the shell's current path is HTROOT import java.io.IOException; import java.util.HashMap; import java.util.TreeSet; import de.anomic.http.httpRequestHeader; import de.anomic.kelondro.order.Bitfield; import de.anomic.kelondro.text.metadataPrototype.URLMetadataRow; import de.anomic.kelondro.util.MemoryControl; import de.anomic.kelondro.util.SetTools; import de.anomic.kelondro.util.Log; import de.anomic.plasma.plasmaParserDocument; import de.anomic.plasma.plasmaProfiling; import de.anomic.plasma.plasmaSearchEvent; import de.anomic.plasma.plasmaSearchQuery; import de.anomic.plasma.plasmaSearchRankingProfile; import de.anomic.plasma.plasmaSnippetCache; import de.anomic.plasma.plasmaSwitchboard; import de.anomic.plasma.plasmaSwitchboardConstants; import de.anomic.plasma.parser.Word; import de.anomic.plasma.parser.Condenser; import de.anomic.server.serverCore; import de.anomic.server.serverDomains; import de.anomic.server.serverObjects; import de.anomic.server.serverProfiling; import de.anomic.server.serverSwitch; import de.anomic.tools.iso639; import de.anomic.tools.Formatter; import de.anomic.xml.RSSFeed; import de.anomic.xml.RSSMessage; import de.anomic.yacy.yacyNewsPool; import de.anomic.yacy.yacyNewsRecord; import de.anomic.yacy.yacyURL; public class yacysearch { public static serverObjects respond(final httpRequestHeader header, final serverObjects post, final serverSwitch<?> env) { final plasmaSwitchboard sb = (plasmaSwitchboard) env; sb.localSearchLastAccess = System.currentTimeMillis(); final boolean searchAllowed = sb.getConfigBool("publicSearchpage", true) || sb.verifyAuthentication(header, false); final boolean authenticated = sb.adminAuthenticated(header) >= 2; int display = (post == null) ? 0 : post.getInt("display", 0); if ((display == 1) && (!authenticated)) display = 0; final boolean browserPopUpTrigger = sb.getConfig(plasmaSwitchboardConstants.BROWSER_POP_UP_TRIGGER, "true").equals("true"); if (browserPopUpTrigger) { final String browserPopUpPage = sb.getConfig(plasmaSwitchboardConstants.BROWSER_POP_UP_PAGE, "ConfigBasic.html"); if (browserPopUpPage.startsWith("index") || browserPopUpPage.startsWith("yacysearch")) display = 2; } String promoteSearchPageGreeting = env.getConfig(plasmaSwitchboardConstants.GREETING, ""); if (env.getConfigBool(plasmaSwitchboardConstants.GREETING_NETWORK_NAME, false)) promoteSearchPageGreeting = env.getConfig("network.unit.description", ""); final String client = header.get(httpRequestHeader.CONNECTION_PROP_CLIENTIP); // the search client who initiated the search // get query String originalquerystring = (post == null) ? "" : post.get("query", post.get("search", "")).trim(); // SRU compliance String querystring = originalquerystring; boolean fetchSnippets = (post != null && post.get("verify", "false").equals("true")); final serverObjects prop = new serverObjects(); //final boolean rss = (post == null) ? false : post.get("rss", "false").equals("true"); prop.put("promoteSearchPageGreeting", promoteSearchPageGreeting); prop.put("promoteSearchPageGreeting.homepage", sb.getConfig(plasmaSwitchboardConstants.GREETING_HOMEPAGE, "")); prop.put("promoteSearchPageGreeting.smallImage", sb.getConfig(plasmaSwitchboardConstants.GREETING_SMALL_IMAGE, "")); if ((post == null) || (env == null) || (!searchAllowed)) { // we create empty entries for template strings prop.put("searchagain", "0"); prop.put("display", display); prop.put("display", display); prop.put("former", ""); prop.put("count", "10"); prop.put("offset", "0"); prop.put("resource", "global"); prop.put("urlmaskfilter", (post == null) ? ".*" : post.get("urlmaskfilter", ".*")); prop.put("prefermaskfilter", (post == null) ? "" : post.get("prefermaskfilter", "")); prop.put("tenant", (post == null) ? "" : post.get("tenant", "")); prop.put("indexof", "off"); prop.put("constraint", ""); prop.put("cat", "href"); prop.put("depth", "0"); prop.put("verify", (post == null) ? "true" : post.get("verify", "true")); prop.put("contentdom", "text"); prop.put("contentdomCheckText", "1"); prop.put("contentdomCheckAudio", "0"); prop.put("contentdomCheckVideo", "0"); prop.put("contentdomCheckImage", "0"); prop.put("contentdomCheckApp", "0"); prop.put("excluded", "0"); prop.put("results", ""); prop.put("resultTable", "0"); prop.put("num-results", searchAllowed ? "0" : "4"); prop.put("num-results_totalcount", 0); prop.put("num-results_offset", 0); prop.put("num-results_itemsPerPage", 10); prop.put("rss_queryenc", ""); return prop; } // check for JSONP if (post.containsKey("callback")) { final String jsonp = post.get("callback")+ "(["; prop.put("jsonp-start", jsonp); prop.put("jsonp-end", "])"); } else { prop.put("jsonp-start", ""); prop.put("jsonp-end", ""); } // collect search attributes boolean newsearch = post.hasValue("query") && post.hasValue("former") && !post.get("query","").equalsIgnoreCase(post.get("former","")); //new search term int itemsPerPage = Math.min((authenticated) ? 1000 : 10, post.getInt("maximumRecords", post.getInt("count", 10))); // SRU syntax with old property as alternative int offset = (newsearch) ? 0 : post.getInt("startRecord", post.getInt("offset", 0)); boolean global = (post == null) ? true : post.get("resource", "global").equals("global"); final boolean indexof = (post != null && post.get("indexof","").equals("on")); String urlmask = null; String originalUrlMask = null; if (post.containsKey("urlmask") && post.get("urlmask").equals("no")) { // option search all originalUrlMask = ".*"; } else if (!newsearch && post.containsKey("urlmaskfilter")) { originalUrlMask = post.get("urlmaskfilter", ".*"); } else { originalUrlMask = ".*"; } String prefermask = (post == null ? "" : post.get("prefermaskfilter", "")); if ((prefermask.length() > 0) && (prefermask.indexOf(".*") < 0)) prefermask = ".*" + prefermask + ".*"; Bitfield constraint = (post != null && post.containsKey("constraint") && post.get("constraint", "").length() > 0) ? new Bitfield(4, post.get("constraint", "______")) : null; if (indexof) { constraint = new Bitfield(4); constraint.set(Condenser.flag_cat_indexof, true); } // SEARCH final boolean indexReceiveGranted = sb.getConfigBool(plasmaSwitchboardConstants.INDEX_RECEIVE_ALLOW, true); global = global && indexReceiveGranted; // if the user does not want indexes from remote peers, it cannot be a global search //final boolean offline = yacyCore.seedDB.mySeed().isVirgin(); final boolean clustersearch = sb.isRobinsonMode() && (sb.getConfig("cluster.mode", "").equals("privatecluster") || sb.getConfig("cluster.mode", "").equals("publiccluster")); //if (offline || !indexDistributeGranted || !indexReceiveGranted) { global = false; } if (clustersearch) global = true; // switches search on, but search target is limited to cluster nodes // find search domain final int contentdomCode = plasmaSearchQuery.contentdomParser((post == null ? "text" : post.get("contentdom", "text"))); // patch until better search profiles are available if ((contentdomCode != plasmaSearchQuery.CONTENTDOM_TEXT) && (itemsPerPage <= 32)) itemsPerPage = 32; // check the search tracker TreeSet<Long> trackerHandles = sb.localSearchTracker.get(client); if (trackerHandles == null) trackerHandles = new TreeSet<Long>(); boolean block = false; if (serverDomains.matchesList(client, sb.networkBlacklist)) { global = false; fetchSnippets = false; block = true; Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: BLACKLISTED CLIENT FROM " + client + " gets no permission to search"); } else if (serverDomains.matchesList(client, sb.networkWhitelist)) { Log.logInfo("LOCAL_SEARCH", "ACCECC CONTROL: WHITELISTED CLIENT FROM " + client + " gets no search restrictions"); } else if (global || fetchSnippets) { // in case that we do a global search or we want to fetch snippets, we check for DoS cases int accInOneSecond = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 1000)).size(); int accInThreeSeconds = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 3000)).size(); int accInOneMinute = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 60000)).size(); int accInTenMinutes = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 600000)).size(); if (accInTenMinutes > 600) { global = false; fetchSnippets = false; block = true; Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: CLIENT FROM " + client + ": " + accInTenMinutes + " searches in ten minutes, fully blocked (no results generated)"); } else if (accInOneMinute > 200) { global = false; fetchSnippets = false; block = true; Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: CLIENT FROM " + client + ": " + accInOneMinute + " searches in one minute, fully blocked (no results generated)"); } else if (accInThreeSeconds > 1) { global = false; fetchSnippets = false; Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: CLIENT FROM " + client + ": " + accInThreeSeconds + " searches in three seconds, blocked global search and snippets"); } else if (accInOneSecond > 2) { global = false; fetchSnippets = false; Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: CLIENT FROM " + client + ": " + accInOneSecond + " searches in one second, blocked global search and snippets"); } } if ((!block) && (post == null || post.get("cat", "href").equals("href"))) { // check available memory and clean up if necessary if (!MemoryControl.request(8000000L, false)) { sb.webIndex.metadata().clearCache(); plasmaSearchEvent.cleanupEvents(true); } final plasmaSearchRankingProfile ranking = sb.getRanking(); if (querystring.indexOf("NEAR") >= 0) { querystring = querystring.replace("NEAR", ""); ranking.coeff_worddistance = plasmaSearchRankingProfile.COEFF_MAX; } if (querystring.indexOf("RECENT") >= 0) { querystring = querystring.replace("RECENT", ""); ranking.coeff_date = plasmaSearchRankingProfile.COEFF_MAX; } int lrp = querystring.indexOf("LANGUAGE:"); String lr = ""; if (lrp >= 0) { if (querystring.length() >= (lrp + 11)) lr = querystring.substring(lrp + 9, lrp + 11); querystring = querystring.replace("LANGUAGE:" + lr, ""); - lr.toLowerCase(); + lr = lr.toLowerCase(); } int inurl = querystring.indexOf("inurl:"); if (inurl >= 0) { int ftb = querystring.indexOf(' ', inurl); if (ftb == -1) ftb = querystring.length(); String urlstr = querystring.substring(inurl + 6, ftb); querystring = querystring.replace("inurl:" + urlstr, ""); if(urlstr.length() > 0) urlmask = ".*" + urlstr + ".*"; } int filetype = querystring.indexOf("filetype:"); if (filetype >= 0) { int ftb = querystring.indexOf(' ', filetype); if (ftb == -1) ftb = querystring.length(); String ft = querystring.substring(filetype + 9, ftb); querystring = querystring.replace("filetype:" + ft, ""); while(ft.startsWith(".")) ft = ft.substring(1); if(ft.length() > 0) { if (urlmask == null) { urlmask = ".*\\." + ft; } else { urlmask = urlmask + ".*\\." + ft; } } } if (post.containsKey("tenant")) { final String tenant = post.get("tenant"); if (urlmask == null) urlmask = ".*" + tenant + ".*"; else urlmask = ".*" + tenant + urlmask; } int site = querystring.indexOf("site:"); String sitehash = null; if (site >= 0) { int ftb = querystring.indexOf(' ', site); if (ftb == -1) ftb = querystring.length(); String domain = querystring.substring(site + 5, ftb); querystring = querystring.replace("site:" + domain, ""); while(domain.startsWith(".")) domain = domain.substring(1); while(domain.endsWith(".")) domain = domain.substring(0, domain.length() - 1); sitehash = yacyURL.domhash(domain); } int tld = querystring.indexOf("tld:"); if (tld >= 0) { int ftb = querystring.indexOf(' ', tld); if (ftb == -1) ftb = querystring.length(); String domain = querystring.substring(tld + 4, ftb); querystring = querystring.replace("tld:" + domain, ""); while(domain.startsWith(".")) domain = domain.substring(1); if (domain.indexOf(".") < 0) domain = "\\." + domain; // is tld if (domain.length() > 0) { if (urlmask == null) { urlmask = "[a-zA-Z]*://[^/]*" + domain + "/.*"; } else { urlmask = "[a-zA-Z]*://[^/]*" + domain + "/.*" + urlmask; } } } if (urlmask == null || urlmask.length() == 0) urlmask = originalUrlMask; //if no urlmask was given // read the language from the language-restrict option 'lr' // if no one is given, use the user agent or the system language as default String language = (post == null) ? lr : post.get("lr", lr); if (language.startsWith("lang_")) language = language.substring(5); if (!iso639.exists(language)) { // find out language of the user by reading of the user-agent string String agent = header.get(httpRequestHeader.ACCEPT_LANGUAGE); if (agent == null) agent = System.getProperty("user.language"); language = (agent == null) ? "en" : iso639.userAgentLanguageDetection(agent); if (language == null) language = "en"; } final TreeSet<String>[] query = plasmaSearchQuery.cleanQuery(querystring.trim()); // converts also umlaute int maxDistance = (querystring.indexOf('"') >= 0) ? maxDistance = query.length - 1 : Integer.MAX_VALUE; // filter out stopwords final TreeSet<String> filtered = SetTools.joinConstructive(query[0], plasmaSwitchboard.stopwords); if (filtered.size() > 0) { SetTools.excludeDestructive(query[0], plasmaSwitchboard.stopwords); } // if a minus-button was hit, remove a special reference first if (post != null && post.containsKey("deleteref")) try { if (!sb.verifyAuthentication(header, true)) { prop.put("AUTHENTICATE", "admin log-in"); // force log-in return prop; } // delete the index entry locally final String delHash = post.get("deleteref", ""); // urlhash sb.webIndex.index().remove(Word.words2hashes(query[0]), delHash); // make new news message with negative voting final HashMap<String, String> map = new HashMap<String, String>(); map.put("urlhash", delHash); map.put("vote", "negative"); map.put("refid", ""); sb.webIndex.peers().newsPool.publishMyNews(yacyNewsRecord.newRecord(sb.webIndex.peers().mySeed(), yacyNewsPool.CATEGORY_SURFTIPP_VOTE_ADD, map)); } catch (IOException e) { e.printStackTrace(); } // if a plus-button was hit, create new voting message if (post != null && post.containsKey("recommendref")) { if (!sb.verifyAuthentication(header, true)) { prop.put("AUTHENTICATE", "admin log-in"); // force log-in return prop; } final String recommendHash = post.get("recommendref", ""); // urlhash final URLMetadataRow urlentry = sb.webIndex.metadata().load(recommendHash, null, 0); if (urlentry != null) { final URLMetadataRow.Components metadata = urlentry.metadata(); plasmaParserDocument document; document = plasmaSnippetCache.retrieveDocument(metadata.url(), true, 5000, true, false); if (document != null) { // create a news message final HashMap<String, String> map = new HashMap<String, String>(); map.put("url", metadata.url().toNormalform(false, true).replace(',', '|')); map.put("title", metadata.dc_title().replace(',', ' ')); map.put("description", document.dc_title().replace(',', ' ')); map.put("author", document.dc_creator()); map.put("tags", document.dc_subject(' ')); sb.webIndex.peers().newsPool.publishMyNews(yacyNewsRecord.newRecord(sb.webIndex.peers().mySeed(), yacyNewsPool.CATEGORY_SURFTIPP_ADD, map)); document.close(); } } } // prepare search properties //final boolean yacyonline = ((sb.webIndex.seedDB != null) && (sb.webIndex.seedDB.mySeed() != null) && (sb.webIndex.seedDB.mySeed().getPublicAddress() != null)); final boolean globalsearch = (global) /* && (yacyonline)*/ && (sb.getConfigBool(plasmaSwitchboardConstants.INDEX_RECEIVE_ALLOW, false)); // do the search final TreeSet<byte[]> queryHashes = Word.words2hashes(query[0]); final plasmaSearchQuery theQuery = new plasmaSearchQuery( originalquerystring, queryHashes, Word.words2hashes(query[1]), Word.words2hashes(query[2]), ranking, maxDistance, prefermask, contentdomCode, language, fetchSnippets, itemsPerPage, offset, urlmask, (clustersearch && globalsearch) ? plasmaSearchQuery.SEARCHDOM_CLUSTERALL : ((globalsearch) ? plasmaSearchQuery.SEARCHDOM_GLOBALDHT : plasmaSearchQuery.SEARCHDOM_LOCAL), "", 20, constraint, true, sitehash, yacyURL.TLD_any_zone_filter, client, authenticated); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(theQuery.id(true), plasmaSearchEvent.INITIALIZATION, 0, 0), false); // tell all threads to do nothing for a specific time sb.intermissionAllThreads(10000); // filter out words that appear in bluelist theQuery.filterOut(plasmaSwitchboard.blueList); // log Log.logInfo("LOCAL_SEARCH", "INIT WORD SEARCH: " + theQuery.queryString + ":" + plasmaSearchQuery.hashSet2hashString(theQuery.queryHashes) + " - " + theQuery.neededResults() + " links to be computed, " + theQuery.displayResults() + " lines to be displayed"); RSSFeed.channels(RSSFeed.LOCALSEARCH).addMessage(new RSSMessage("Local Search Request", theQuery.queryString, "")); final long timestamp = System.currentTimeMillis(); // create a new search event if (plasmaSearchEvent.getEvent(theQuery.id(false)) == null) { theQuery.setOffset(0); // in case that this is a new search, always start without a offset offset = 0; } final plasmaSearchEvent theSearch = plasmaSearchEvent.getEvent(theQuery, ranking, sb.webIndex, sb.crawlResults, (sb.isRobinsonMode()) ? sb.clusterhashes : null, false); // generate result object //serverLog.logFine("LOCAL_SEARCH", "SEARCH TIME AFTER ORDERING OF SEARCH RESULTS: " + (System.currentTimeMillis() - timestamp) + " ms"); //serverLog.logFine("LOCAL_SEARCH", "SEARCH TIME AFTER RESULT PREPARATION: " + (System.currentTimeMillis() - timestamp) + " ms"); // calc some more cross-reference //serverLog.logFine("LOCAL_SEARCH", "SEARCH TIME AFTER XREF PREPARATION: " + (System.currentTimeMillis() - timestamp) + " ms"); // log Log.logInfo("LOCAL_SEARCH", "EXIT WORD SEARCH: " + theQuery.queryString + " - " + (theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize()) + " links found, " + (System.currentTimeMillis() - timestamp) + " ms"); // prepare search statistics theQuery.resultcount = theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize(); theQuery.searchtime = System.currentTimeMillis() - timestamp; theQuery.urlretrievaltime = theSearch.getURLRetrievalTime(); theQuery.snippetcomputationtime = theSearch.getSnippetComputationTime(); sb.localSearches.add(theQuery); // update the search tracker trackerHandles.add(theQuery.handle); sb.localSearchTracker.put(client, trackerHandles); final int totalcount = theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize(); prop.put("num-results_offset", offset); prop.put("num-results_itemscount", "0"); prop.put("num-results_itemsPerPage", itemsPerPage); prop.put("num-results_totalcount", Formatter.number(totalcount, true)); prop.put("num-results_globalresults", (globalsearch) ? "1" : "0"); prop.put("num-results_globalresults_localResourceSize", Formatter.number(theSearch.getRankingResult().getLocalResourceSize(), true)); prop.put("num-results_globalresults_remoteResourceSize", Formatter.number(theSearch.getRankingResult().getRemoteResourceSize(), true)); prop.put("num-results_globalresults_remoteIndexCount", Formatter.number(theSearch.getRankingResult().getRemoteIndexCount(), true)); prop.put("num-results_globalresults_remotePeerCount", Formatter.number(theSearch.getRankingResult().getRemotePeerCount(), true)); // compose page navigation final StringBuilder resnav = new StringBuilder(); final int thispage = offset / theQuery.displayResults(); if (thispage == 0) resnav.append("&lt;&nbsp;"); else { resnav.append(navurla(thispage - 1, display, theQuery, originalUrlMask)); resnav.append("<strong>&lt;</strong></a>&nbsp;"); } final int numberofpages = Math.min(10, Math.max(thispage + 2, totalcount / theQuery.displayResults())); for (int i = 0; i < numberofpages; i++) { if (i == thispage) { resnav.append("<strong>"); resnav.append(i + 1); resnav.append("</strong>&nbsp;"); } else { resnav.append(navurla(i, display, theQuery, originalUrlMask)); resnav.append(i + 1); resnav.append("</a>&nbsp;"); } } if (thispage >= numberofpages) resnav.append("&gt;"); else { resnav.append(navurla(thispage + 1, display, theQuery, originalUrlMask)); resnav.append("<strong>&gt;</strong></a>"); } prop.put("num-results_resnav", resnav.toString()); // generate the search result lines; they will be produced by another servlet for (int i = 0; i < theQuery.displayResults(); i++) { prop.put("results_" + i + "_item", offset + i); prop.put("results_" + i + "_eventID", theQuery.id(false)); prop.put("results_" + i + "_display", display); } prop.put("results", theQuery.displayResults()); prop.put("resultTable", (contentdomCode <= 1) ? "0" : "1"); prop.put("eventID", theQuery.id(false)); // for bottomline // process result of search if (filtered.size() > 0) { prop.put("excluded", "1"); prop.putHTML("excluded_stopwords", filtered.toString()); } else { prop.put("excluded", "0"); } if (prop == null || prop.size() == 0) { if (post == null || post.get("query", post.get("search", "")).length() < 3) { prop.put("num-results", "2"); // no results - at least 3 chars } else { prop.put("num-results", "1"); // no results } } else { prop.put("num-results", "3"); } prop.put("cat", "href"); prop.put("depth", "0"); // adding some additional properties needed for the rss feed String hostName = (String) header.get("Host", "localhost"); if (hostName.indexOf(":") == -1) hostName += ":" + serverCore.getPortNr(env.getConfig("port", "8080")); prop.put("searchBaseURL", "http://" + hostName + "/yacysearch.html"); prop.put("rssYacyImageURL", "http://" + hostName + "/env/grafics/yacy.gif"); } prop.put("searchagain", global ? "1" : "0"); prop.put("display", display); prop.put("display", display); prop.putHTML("former", originalquerystring); prop.put("count", itemsPerPage); prop.put("offset", offset); prop.put("resource", global ? "global" : "local"); prop.putHTML("urlmaskfilter", originalUrlMask); prop.putHTML("prefermaskfilter", prefermask); prop.put("indexof", (indexof) ? "on" : "off"); prop.put("constraint", (constraint == null) ? "" : constraint.exportB64()); prop.put("verify", (fetchSnippets) ? "true" : "false"); prop.put("contentdom", (post == null ? "text" : post.get("contentdom", "text"))); prop.put("contentdomCheckText", (contentdomCode == plasmaSearchQuery.CONTENTDOM_TEXT) ? "1" : "0"); prop.put("contentdomCheckAudio", (contentdomCode == plasmaSearchQuery.CONTENTDOM_AUDIO) ? "1" : "0"); prop.put("contentdomCheckVideo", (contentdomCode == plasmaSearchQuery.CONTENTDOM_VIDEO) ? "1" : "0"); prop.put("contentdomCheckImage", (contentdomCode == plasmaSearchQuery.CONTENTDOM_IMAGE) ? "1" : "0"); prop.put("contentdomCheckApp", (contentdomCode == plasmaSearchQuery.CONTENTDOM_APP) ? "1" : "0"); // for RSS: don't HTML encode some elements prop.putXML("rss_query", originalquerystring); prop.put("rss_queryenc", originalquerystring.replace(' ', '+')); sb.localSearchLastAccess = System.currentTimeMillis(); // return rewrite properties return prop; } /** * generates the page navigation bar */ private static String navurla(final int page, final int display, final plasmaSearchQuery theQuery, final String originalUrlMask) { return "<a href=\"yacysearch.html?display=" + display + "&amp;search=" + theQuery.queryString(true) + "&amp;maximumRecords="+ theQuery.displayResults() + "&amp;startRecord=" + (page * theQuery.displayResults()) + "&amp;resource=" + ((theQuery.isLocal()) ? "local" : "global") + "&amp;verify=" + ((theQuery.onlineSnippetFetch) ? "true" : "false") + "&amp;urlmaskfilter=" + originalUrlMask + "&amp;prefermaskfilter=" + theQuery.prefer + "&amp;cat=href&amp;constraint=" + ((theQuery.constraint == null) ? "" : theQuery.constraint.exportB64()) + "&amp;contentdom=" + theQuery.contentdom() + "&amp;former=" + theQuery.queryString(true) + "\">"; } }
true
true
public static serverObjects respond(final httpRequestHeader header, final serverObjects post, final serverSwitch<?> env) { final plasmaSwitchboard sb = (plasmaSwitchboard) env; sb.localSearchLastAccess = System.currentTimeMillis(); final boolean searchAllowed = sb.getConfigBool("publicSearchpage", true) || sb.verifyAuthentication(header, false); final boolean authenticated = sb.adminAuthenticated(header) >= 2; int display = (post == null) ? 0 : post.getInt("display", 0); if ((display == 1) && (!authenticated)) display = 0; final boolean browserPopUpTrigger = sb.getConfig(plasmaSwitchboardConstants.BROWSER_POP_UP_TRIGGER, "true").equals("true"); if (browserPopUpTrigger) { final String browserPopUpPage = sb.getConfig(plasmaSwitchboardConstants.BROWSER_POP_UP_PAGE, "ConfigBasic.html"); if (browserPopUpPage.startsWith("index") || browserPopUpPage.startsWith("yacysearch")) display = 2; } String promoteSearchPageGreeting = env.getConfig(plasmaSwitchboardConstants.GREETING, ""); if (env.getConfigBool(plasmaSwitchboardConstants.GREETING_NETWORK_NAME, false)) promoteSearchPageGreeting = env.getConfig("network.unit.description", ""); final String client = header.get(httpRequestHeader.CONNECTION_PROP_CLIENTIP); // the search client who initiated the search // get query String originalquerystring = (post == null) ? "" : post.get("query", post.get("search", "")).trim(); // SRU compliance String querystring = originalquerystring; boolean fetchSnippets = (post != null && post.get("verify", "false").equals("true")); final serverObjects prop = new serverObjects(); //final boolean rss = (post == null) ? false : post.get("rss", "false").equals("true"); prop.put("promoteSearchPageGreeting", promoteSearchPageGreeting); prop.put("promoteSearchPageGreeting.homepage", sb.getConfig(plasmaSwitchboardConstants.GREETING_HOMEPAGE, "")); prop.put("promoteSearchPageGreeting.smallImage", sb.getConfig(plasmaSwitchboardConstants.GREETING_SMALL_IMAGE, "")); if ((post == null) || (env == null) || (!searchAllowed)) { // we create empty entries for template strings prop.put("searchagain", "0"); prop.put("display", display); prop.put("display", display); prop.put("former", ""); prop.put("count", "10"); prop.put("offset", "0"); prop.put("resource", "global"); prop.put("urlmaskfilter", (post == null) ? ".*" : post.get("urlmaskfilter", ".*")); prop.put("prefermaskfilter", (post == null) ? "" : post.get("prefermaskfilter", "")); prop.put("tenant", (post == null) ? "" : post.get("tenant", "")); prop.put("indexof", "off"); prop.put("constraint", ""); prop.put("cat", "href"); prop.put("depth", "0"); prop.put("verify", (post == null) ? "true" : post.get("verify", "true")); prop.put("contentdom", "text"); prop.put("contentdomCheckText", "1"); prop.put("contentdomCheckAudio", "0"); prop.put("contentdomCheckVideo", "0"); prop.put("contentdomCheckImage", "0"); prop.put("contentdomCheckApp", "0"); prop.put("excluded", "0"); prop.put("results", ""); prop.put("resultTable", "0"); prop.put("num-results", searchAllowed ? "0" : "4"); prop.put("num-results_totalcount", 0); prop.put("num-results_offset", 0); prop.put("num-results_itemsPerPage", 10); prop.put("rss_queryenc", ""); return prop; } // check for JSONP if (post.containsKey("callback")) { final String jsonp = post.get("callback")+ "(["; prop.put("jsonp-start", jsonp); prop.put("jsonp-end", "])"); } else { prop.put("jsonp-start", ""); prop.put("jsonp-end", ""); } // collect search attributes boolean newsearch = post.hasValue("query") && post.hasValue("former") && !post.get("query","").equalsIgnoreCase(post.get("former","")); //new search term int itemsPerPage = Math.min((authenticated) ? 1000 : 10, post.getInt("maximumRecords", post.getInt("count", 10))); // SRU syntax with old property as alternative int offset = (newsearch) ? 0 : post.getInt("startRecord", post.getInt("offset", 0)); boolean global = (post == null) ? true : post.get("resource", "global").equals("global"); final boolean indexof = (post != null && post.get("indexof","").equals("on")); String urlmask = null; String originalUrlMask = null; if (post.containsKey("urlmask") && post.get("urlmask").equals("no")) { // option search all originalUrlMask = ".*"; } else if (!newsearch && post.containsKey("urlmaskfilter")) { originalUrlMask = post.get("urlmaskfilter", ".*"); } else { originalUrlMask = ".*"; } String prefermask = (post == null ? "" : post.get("prefermaskfilter", "")); if ((prefermask.length() > 0) && (prefermask.indexOf(".*") < 0)) prefermask = ".*" + prefermask + ".*"; Bitfield constraint = (post != null && post.containsKey("constraint") && post.get("constraint", "").length() > 0) ? new Bitfield(4, post.get("constraint", "______")) : null; if (indexof) { constraint = new Bitfield(4); constraint.set(Condenser.flag_cat_indexof, true); } // SEARCH final boolean indexReceiveGranted = sb.getConfigBool(plasmaSwitchboardConstants.INDEX_RECEIVE_ALLOW, true); global = global && indexReceiveGranted; // if the user does not want indexes from remote peers, it cannot be a global search //final boolean offline = yacyCore.seedDB.mySeed().isVirgin(); final boolean clustersearch = sb.isRobinsonMode() && (sb.getConfig("cluster.mode", "").equals("privatecluster") || sb.getConfig("cluster.mode", "").equals("publiccluster")); //if (offline || !indexDistributeGranted || !indexReceiveGranted) { global = false; } if (clustersearch) global = true; // switches search on, but search target is limited to cluster nodes // find search domain final int contentdomCode = plasmaSearchQuery.contentdomParser((post == null ? "text" : post.get("contentdom", "text"))); // patch until better search profiles are available if ((contentdomCode != plasmaSearchQuery.CONTENTDOM_TEXT) && (itemsPerPage <= 32)) itemsPerPage = 32; // check the search tracker TreeSet<Long> trackerHandles = sb.localSearchTracker.get(client); if (trackerHandles == null) trackerHandles = new TreeSet<Long>(); boolean block = false; if (serverDomains.matchesList(client, sb.networkBlacklist)) { global = false; fetchSnippets = false; block = true; Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: BLACKLISTED CLIENT FROM " + client + " gets no permission to search"); } else if (serverDomains.matchesList(client, sb.networkWhitelist)) { Log.logInfo("LOCAL_SEARCH", "ACCECC CONTROL: WHITELISTED CLIENT FROM " + client + " gets no search restrictions"); } else if (global || fetchSnippets) { // in case that we do a global search or we want to fetch snippets, we check for DoS cases int accInOneSecond = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 1000)).size(); int accInThreeSeconds = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 3000)).size(); int accInOneMinute = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 60000)).size(); int accInTenMinutes = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 600000)).size(); if (accInTenMinutes > 600) { global = false; fetchSnippets = false; block = true; Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: CLIENT FROM " + client + ": " + accInTenMinutes + " searches in ten minutes, fully blocked (no results generated)"); } else if (accInOneMinute > 200) { global = false; fetchSnippets = false; block = true; Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: CLIENT FROM " + client + ": " + accInOneMinute + " searches in one minute, fully blocked (no results generated)"); } else if (accInThreeSeconds > 1) { global = false; fetchSnippets = false; Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: CLIENT FROM " + client + ": " + accInThreeSeconds + " searches in three seconds, blocked global search and snippets"); } else if (accInOneSecond > 2) { global = false; fetchSnippets = false; Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: CLIENT FROM " + client + ": " + accInOneSecond + " searches in one second, blocked global search and snippets"); } } if ((!block) && (post == null || post.get("cat", "href").equals("href"))) { // check available memory and clean up if necessary if (!MemoryControl.request(8000000L, false)) { sb.webIndex.metadata().clearCache(); plasmaSearchEvent.cleanupEvents(true); } final plasmaSearchRankingProfile ranking = sb.getRanking(); if (querystring.indexOf("NEAR") >= 0) { querystring = querystring.replace("NEAR", ""); ranking.coeff_worddistance = plasmaSearchRankingProfile.COEFF_MAX; } if (querystring.indexOf("RECENT") >= 0) { querystring = querystring.replace("RECENT", ""); ranking.coeff_date = plasmaSearchRankingProfile.COEFF_MAX; } int lrp = querystring.indexOf("LANGUAGE:"); String lr = ""; if (lrp >= 0) { if (querystring.length() >= (lrp + 11)) lr = querystring.substring(lrp + 9, lrp + 11); querystring = querystring.replace("LANGUAGE:" + lr, ""); lr.toLowerCase(); } int inurl = querystring.indexOf("inurl:"); if (inurl >= 0) { int ftb = querystring.indexOf(' ', inurl); if (ftb == -1) ftb = querystring.length(); String urlstr = querystring.substring(inurl + 6, ftb); querystring = querystring.replace("inurl:" + urlstr, ""); if(urlstr.length() > 0) urlmask = ".*" + urlstr + ".*"; } int filetype = querystring.indexOf("filetype:"); if (filetype >= 0) { int ftb = querystring.indexOf(' ', filetype); if (ftb == -1) ftb = querystring.length(); String ft = querystring.substring(filetype + 9, ftb); querystring = querystring.replace("filetype:" + ft, ""); while(ft.startsWith(".")) ft = ft.substring(1); if(ft.length() > 0) { if (urlmask == null) { urlmask = ".*\\." + ft; } else { urlmask = urlmask + ".*\\." + ft; } } } if (post.containsKey("tenant")) { final String tenant = post.get("tenant"); if (urlmask == null) urlmask = ".*" + tenant + ".*"; else urlmask = ".*" + tenant + urlmask; } int site = querystring.indexOf("site:"); String sitehash = null; if (site >= 0) { int ftb = querystring.indexOf(' ', site); if (ftb == -1) ftb = querystring.length(); String domain = querystring.substring(site + 5, ftb); querystring = querystring.replace("site:" + domain, ""); while(domain.startsWith(".")) domain = domain.substring(1); while(domain.endsWith(".")) domain = domain.substring(0, domain.length() - 1); sitehash = yacyURL.domhash(domain); } int tld = querystring.indexOf("tld:"); if (tld >= 0) { int ftb = querystring.indexOf(' ', tld); if (ftb == -1) ftb = querystring.length(); String domain = querystring.substring(tld + 4, ftb); querystring = querystring.replace("tld:" + domain, ""); while(domain.startsWith(".")) domain = domain.substring(1); if (domain.indexOf(".") < 0) domain = "\\." + domain; // is tld if (domain.length() > 0) { if (urlmask == null) { urlmask = "[a-zA-Z]*://[^/]*" + domain + "/.*"; } else { urlmask = "[a-zA-Z]*://[^/]*" + domain + "/.*" + urlmask; } } } if (urlmask == null || urlmask.length() == 0) urlmask = originalUrlMask; //if no urlmask was given // read the language from the language-restrict option 'lr' // if no one is given, use the user agent or the system language as default String language = (post == null) ? lr : post.get("lr", lr); if (language.startsWith("lang_")) language = language.substring(5); if (!iso639.exists(language)) { // find out language of the user by reading of the user-agent string String agent = header.get(httpRequestHeader.ACCEPT_LANGUAGE); if (agent == null) agent = System.getProperty("user.language"); language = (agent == null) ? "en" : iso639.userAgentLanguageDetection(agent); if (language == null) language = "en"; } final TreeSet<String>[] query = plasmaSearchQuery.cleanQuery(querystring.trim()); // converts also umlaute int maxDistance = (querystring.indexOf('"') >= 0) ? maxDistance = query.length - 1 : Integer.MAX_VALUE; // filter out stopwords final TreeSet<String> filtered = SetTools.joinConstructive(query[0], plasmaSwitchboard.stopwords); if (filtered.size() > 0) { SetTools.excludeDestructive(query[0], plasmaSwitchboard.stopwords); } // if a minus-button was hit, remove a special reference first if (post != null && post.containsKey("deleteref")) try { if (!sb.verifyAuthentication(header, true)) { prop.put("AUTHENTICATE", "admin log-in"); // force log-in return prop; } // delete the index entry locally final String delHash = post.get("deleteref", ""); // urlhash sb.webIndex.index().remove(Word.words2hashes(query[0]), delHash); // make new news message with negative voting final HashMap<String, String> map = new HashMap<String, String>(); map.put("urlhash", delHash); map.put("vote", "negative"); map.put("refid", ""); sb.webIndex.peers().newsPool.publishMyNews(yacyNewsRecord.newRecord(sb.webIndex.peers().mySeed(), yacyNewsPool.CATEGORY_SURFTIPP_VOTE_ADD, map)); } catch (IOException e) { e.printStackTrace(); } // if a plus-button was hit, create new voting message if (post != null && post.containsKey("recommendref")) { if (!sb.verifyAuthentication(header, true)) { prop.put("AUTHENTICATE", "admin log-in"); // force log-in return prop; } final String recommendHash = post.get("recommendref", ""); // urlhash final URLMetadataRow urlentry = sb.webIndex.metadata().load(recommendHash, null, 0); if (urlentry != null) { final URLMetadataRow.Components metadata = urlentry.metadata(); plasmaParserDocument document; document = plasmaSnippetCache.retrieveDocument(metadata.url(), true, 5000, true, false); if (document != null) { // create a news message final HashMap<String, String> map = new HashMap<String, String>(); map.put("url", metadata.url().toNormalform(false, true).replace(',', '|')); map.put("title", metadata.dc_title().replace(',', ' ')); map.put("description", document.dc_title().replace(',', ' ')); map.put("author", document.dc_creator()); map.put("tags", document.dc_subject(' ')); sb.webIndex.peers().newsPool.publishMyNews(yacyNewsRecord.newRecord(sb.webIndex.peers().mySeed(), yacyNewsPool.CATEGORY_SURFTIPP_ADD, map)); document.close(); } } } // prepare search properties //final boolean yacyonline = ((sb.webIndex.seedDB != null) && (sb.webIndex.seedDB.mySeed() != null) && (sb.webIndex.seedDB.mySeed().getPublicAddress() != null)); final boolean globalsearch = (global) /* && (yacyonline)*/ && (sb.getConfigBool(plasmaSwitchboardConstants.INDEX_RECEIVE_ALLOW, false)); // do the search final TreeSet<byte[]> queryHashes = Word.words2hashes(query[0]); final plasmaSearchQuery theQuery = new plasmaSearchQuery( originalquerystring, queryHashes, Word.words2hashes(query[1]), Word.words2hashes(query[2]), ranking, maxDistance, prefermask, contentdomCode, language, fetchSnippets, itemsPerPage, offset, urlmask, (clustersearch && globalsearch) ? plasmaSearchQuery.SEARCHDOM_CLUSTERALL : ((globalsearch) ? plasmaSearchQuery.SEARCHDOM_GLOBALDHT : plasmaSearchQuery.SEARCHDOM_LOCAL), "", 20, constraint, true, sitehash, yacyURL.TLD_any_zone_filter, client, authenticated); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(theQuery.id(true), plasmaSearchEvent.INITIALIZATION, 0, 0), false); // tell all threads to do nothing for a specific time sb.intermissionAllThreads(10000); // filter out words that appear in bluelist theQuery.filterOut(plasmaSwitchboard.blueList); // log Log.logInfo("LOCAL_SEARCH", "INIT WORD SEARCH: " + theQuery.queryString + ":" + plasmaSearchQuery.hashSet2hashString(theQuery.queryHashes) + " - " + theQuery.neededResults() + " links to be computed, " + theQuery.displayResults() + " lines to be displayed"); RSSFeed.channels(RSSFeed.LOCALSEARCH).addMessage(new RSSMessage("Local Search Request", theQuery.queryString, "")); final long timestamp = System.currentTimeMillis(); // create a new search event if (plasmaSearchEvent.getEvent(theQuery.id(false)) == null) { theQuery.setOffset(0); // in case that this is a new search, always start without a offset offset = 0; } final plasmaSearchEvent theSearch = plasmaSearchEvent.getEvent(theQuery, ranking, sb.webIndex, sb.crawlResults, (sb.isRobinsonMode()) ? sb.clusterhashes : null, false); // generate result object //serverLog.logFine("LOCAL_SEARCH", "SEARCH TIME AFTER ORDERING OF SEARCH RESULTS: " + (System.currentTimeMillis() - timestamp) + " ms"); //serverLog.logFine("LOCAL_SEARCH", "SEARCH TIME AFTER RESULT PREPARATION: " + (System.currentTimeMillis() - timestamp) + " ms"); // calc some more cross-reference //serverLog.logFine("LOCAL_SEARCH", "SEARCH TIME AFTER XREF PREPARATION: " + (System.currentTimeMillis() - timestamp) + " ms"); // log Log.logInfo("LOCAL_SEARCH", "EXIT WORD SEARCH: " + theQuery.queryString + " - " + (theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize()) + " links found, " + (System.currentTimeMillis() - timestamp) + " ms"); // prepare search statistics theQuery.resultcount = theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize(); theQuery.searchtime = System.currentTimeMillis() - timestamp; theQuery.urlretrievaltime = theSearch.getURLRetrievalTime(); theQuery.snippetcomputationtime = theSearch.getSnippetComputationTime(); sb.localSearches.add(theQuery); // update the search tracker trackerHandles.add(theQuery.handle); sb.localSearchTracker.put(client, trackerHandles); final int totalcount = theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize(); prop.put("num-results_offset", offset); prop.put("num-results_itemscount", "0"); prop.put("num-results_itemsPerPage", itemsPerPage); prop.put("num-results_totalcount", Formatter.number(totalcount, true)); prop.put("num-results_globalresults", (globalsearch) ? "1" : "0"); prop.put("num-results_globalresults_localResourceSize", Formatter.number(theSearch.getRankingResult().getLocalResourceSize(), true)); prop.put("num-results_globalresults_remoteResourceSize", Formatter.number(theSearch.getRankingResult().getRemoteResourceSize(), true)); prop.put("num-results_globalresults_remoteIndexCount", Formatter.number(theSearch.getRankingResult().getRemoteIndexCount(), true)); prop.put("num-results_globalresults_remotePeerCount", Formatter.number(theSearch.getRankingResult().getRemotePeerCount(), true)); // compose page navigation final StringBuilder resnav = new StringBuilder(); final int thispage = offset / theQuery.displayResults(); if (thispage == 0) resnav.append("&lt;&nbsp;"); else { resnav.append(navurla(thispage - 1, display, theQuery, originalUrlMask)); resnav.append("<strong>&lt;</strong></a>&nbsp;"); } final int numberofpages = Math.min(10, Math.max(thispage + 2, totalcount / theQuery.displayResults())); for (int i = 0; i < numberofpages; i++) { if (i == thispage) { resnav.append("<strong>"); resnav.append(i + 1); resnav.append("</strong>&nbsp;"); } else { resnav.append(navurla(i, display, theQuery, originalUrlMask)); resnav.append(i + 1); resnav.append("</a>&nbsp;"); } } if (thispage >= numberofpages) resnav.append("&gt;"); else { resnav.append(navurla(thispage + 1, display, theQuery, originalUrlMask)); resnav.append("<strong>&gt;</strong></a>"); } prop.put("num-results_resnav", resnav.toString()); // generate the search result lines; they will be produced by another servlet for (int i = 0; i < theQuery.displayResults(); i++) { prop.put("results_" + i + "_item", offset + i); prop.put("results_" + i + "_eventID", theQuery.id(false)); prop.put("results_" + i + "_display", display); } prop.put("results", theQuery.displayResults()); prop.put("resultTable", (contentdomCode <= 1) ? "0" : "1"); prop.put("eventID", theQuery.id(false)); // for bottomline // process result of search if (filtered.size() > 0) { prop.put("excluded", "1"); prop.putHTML("excluded_stopwords", filtered.toString()); } else { prop.put("excluded", "0"); } if (prop == null || prop.size() == 0) { if (post == null || post.get("query", post.get("search", "")).length() < 3) { prop.put("num-results", "2"); // no results - at least 3 chars } else { prop.put("num-results", "1"); // no results } } else { prop.put("num-results", "3"); } prop.put("cat", "href"); prop.put("depth", "0"); // adding some additional properties needed for the rss feed String hostName = (String) header.get("Host", "localhost"); if (hostName.indexOf(":") == -1) hostName += ":" + serverCore.getPortNr(env.getConfig("port", "8080")); prop.put("searchBaseURL", "http://" + hostName + "/yacysearch.html"); prop.put("rssYacyImageURL", "http://" + hostName + "/env/grafics/yacy.gif"); } prop.put("searchagain", global ? "1" : "0"); prop.put("display", display); prop.put("display", display); prop.putHTML("former", originalquerystring); prop.put("count", itemsPerPage); prop.put("offset", offset); prop.put("resource", global ? "global" : "local"); prop.putHTML("urlmaskfilter", originalUrlMask); prop.putHTML("prefermaskfilter", prefermask); prop.put("indexof", (indexof) ? "on" : "off"); prop.put("constraint", (constraint == null) ? "" : constraint.exportB64()); prop.put("verify", (fetchSnippets) ? "true" : "false"); prop.put("contentdom", (post == null ? "text" : post.get("contentdom", "text"))); prop.put("contentdomCheckText", (contentdomCode == plasmaSearchQuery.CONTENTDOM_TEXT) ? "1" : "0"); prop.put("contentdomCheckAudio", (contentdomCode == plasmaSearchQuery.CONTENTDOM_AUDIO) ? "1" : "0"); prop.put("contentdomCheckVideo", (contentdomCode == plasmaSearchQuery.CONTENTDOM_VIDEO) ? "1" : "0"); prop.put("contentdomCheckImage", (contentdomCode == plasmaSearchQuery.CONTENTDOM_IMAGE) ? "1" : "0"); prop.put("contentdomCheckApp", (contentdomCode == plasmaSearchQuery.CONTENTDOM_APP) ? "1" : "0"); // for RSS: don't HTML encode some elements prop.putXML("rss_query", originalquerystring); prop.put("rss_queryenc", originalquerystring.replace(' ', '+')); sb.localSearchLastAccess = System.currentTimeMillis(); // return rewrite properties return prop; }
public static serverObjects respond(final httpRequestHeader header, final serverObjects post, final serverSwitch<?> env) { final plasmaSwitchboard sb = (plasmaSwitchboard) env; sb.localSearchLastAccess = System.currentTimeMillis(); final boolean searchAllowed = sb.getConfigBool("publicSearchpage", true) || sb.verifyAuthentication(header, false); final boolean authenticated = sb.adminAuthenticated(header) >= 2; int display = (post == null) ? 0 : post.getInt("display", 0); if ((display == 1) && (!authenticated)) display = 0; final boolean browserPopUpTrigger = sb.getConfig(plasmaSwitchboardConstants.BROWSER_POP_UP_TRIGGER, "true").equals("true"); if (browserPopUpTrigger) { final String browserPopUpPage = sb.getConfig(plasmaSwitchboardConstants.BROWSER_POP_UP_PAGE, "ConfigBasic.html"); if (browserPopUpPage.startsWith("index") || browserPopUpPage.startsWith("yacysearch")) display = 2; } String promoteSearchPageGreeting = env.getConfig(plasmaSwitchboardConstants.GREETING, ""); if (env.getConfigBool(plasmaSwitchboardConstants.GREETING_NETWORK_NAME, false)) promoteSearchPageGreeting = env.getConfig("network.unit.description", ""); final String client = header.get(httpRequestHeader.CONNECTION_PROP_CLIENTIP); // the search client who initiated the search // get query String originalquerystring = (post == null) ? "" : post.get("query", post.get("search", "")).trim(); // SRU compliance String querystring = originalquerystring; boolean fetchSnippets = (post != null && post.get("verify", "false").equals("true")); final serverObjects prop = new serverObjects(); //final boolean rss = (post == null) ? false : post.get("rss", "false").equals("true"); prop.put("promoteSearchPageGreeting", promoteSearchPageGreeting); prop.put("promoteSearchPageGreeting.homepage", sb.getConfig(plasmaSwitchboardConstants.GREETING_HOMEPAGE, "")); prop.put("promoteSearchPageGreeting.smallImage", sb.getConfig(plasmaSwitchboardConstants.GREETING_SMALL_IMAGE, "")); if ((post == null) || (env == null) || (!searchAllowed)) { // we create empty entries for template strings prop.put("searchagain", "0"); prop.put("display", display); prop.put("display", display); prop.put("former", ""); prop.put("count", "10"); prop.put("offset", "0"); prop.put("resource", "global"); prop.put("urlmaskfilter", (post == null) ? ".*" : post.get("urlmaskfilter", ".*")); prop.put("prefermaskfilter", (post == null) ? "" : post.get("prefermaskfilter", "")); prop.put("tenant", (post == null) ? "" : post.get("tenant", "")); prop.put("indexof", "off"); prop.put("constraint", ""); prop.put("cat", "href"); prop.put("depth", "0"); prop.put("verify", (post == null) ? "true" : post.get("verify", "true")); prop.put("contentdom", "text"); prop.put("contentdomCheckText", "1"); prop.put("contentdomCheckAudio", "0"); prop.put("contentdomCheckVideo", "0"); prop.put("contentdomCheckImage", "0"); prop.put("contentdomCheckApp", "0"); prop.put("excluded", "0"); prop.put("results", ""); prop.put("resultTable", "0"); prop.put("num-results", searchAllowed ? "0" : "4"); prop.put("num-results_totalcount", 0); prop.put("num-results_offset", 0); prop.put("num-results_itemsPerPage", 10); prop.put("rss_queryenc", ""); return prop; } // check for JSONP if (post.containsKey("callback")) { final String jsonp = post.get("callback")+ "(["; prop.put("jsonp-start", jsonp); prop.put("jsonp-end", "])"); } else { prop.put("jsonp-start", ""); prop.put("jsonp-end", ""); } // collect search attributes boolean newsearch = post.hasValue("query") && post.hasValue("former") && !post.get("query","").equalsIgnoreCase(post.get("former","")); //new search term int itemsPerPage = Math.min((authenticated) ? 1000 : 10, post.getInt("maximumRecords", post.getInt("count", 10))); // SRU syntax with old property as alternative int offset = (newsearch) ? 0 : post.getInt("startRecord", post.getInt("offset", 0)); boolean global = (post == null) ? true : post.get("resource", "global").equals("global"); final boolean indexof = (post != null && post.get("indexof","").equals("on")); String urlmask = null; String originalUrlMask = null; if (post.containsKey("urlmask") && post.get("urlmask").equals("no")) { // option search all originalUrlMask = ".*"; } else if (!newsearch && post.containsKey("urlmaskfilter")) { originalUrlMask = post.get("urlmaskfilter", ".*"); } else { originalUrlMask = ".*"; } String prefermask = (post == null ? "" : post.get("prefermaskfilter", "")); if ((prefermask.length() > 0) && (prefermask.indexOf(".*") < 0)) prefermask = ".*" + prefermask + ".*"; Bitfield constraint = (post != null && post.containsKey("constraint") && post.get("constraint", "").length() > 0) ? new Bitfield(4, post.get("constraint", "______")) : null; if (indexof) { constraint = new Bitfield(4); constraint.set(Condenser.flag_cat_indexof, true); } // SEARCH final boolean indexReceiveGranted = sb.getConfigBool(plasmaSwitchboardConstants.INDEX_RECEIVE_ALLOW, true); global = global && indexReceiveGranted; // if the user does not want indexes from remote peers, it cannot be a global search //final boolean offline = yacyCore.seedDB.mySeed().isVirgin(); final boolean clustersearch = sb.isRobinsonMode() && (sb.getConfig("cluster.mode", "").equals("privatecluster") || sb.getConfig("cluster.mode", "").equals("publiccluster")); //if (offline || !indexDistributeGranted || !indexReceiveGranted) { global = false; } if (clustersearch) global = true; // switches search on, but search target is limited to cluster nodes // find search domain final int contentdomCode = plasmaSearchQuery.contentdomParser((post == null ? "text" : post.get("contentdom", "text"))); // patch until better search profiles are available if ((contentdomCode != plasmaSearchQuery.CONTENTDOM_TEXT) && (itemsPerPage <= 32)) itemsPerPage = 32; // check the search tracker TreeSet<Long> trackerHandles = sb.localSearchTracker.get(client); if (trackerHandles == null) trackerHandles = new TreeSet<Long>(); boolean block = false; if (serverDomains.matchesList(client, sb.networkBlacklist)) { global = false; fetchSnippets = false; block = true; Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: BLACKLISTED CLIENT FROM " + client + " gets no permission to search"); } else if (serverDomains.matchesList(client, sb.networkWhitelist)) { Log.logInfo("LOCAL_SEARCH", "ACCECC CONTROL: WHITELISTED CLIENT FROM " + client + " gets no search restrictions"); } else if (global || fetchSnippets) { // in case that we do a global search or we want to fetch snippets, we check for DoS cases int accInOneSecond = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 1000)).size(); int accInThreeSeconds = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 3000)).size(); int accInOneMinute = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 60000)).size(); int accInTenMinutes = trackerHandles.tailSet(Long.valueOf(System.currentTimeMillis() - 600000)).size(); if (accInTenMinutes > 600) { global = false; fetchSnippets = false; block = true; Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: CLIENT FROM " + client + ": " + accInTenMinutes + " searches in ten minutes, fully blocked (no results generated)"); } else if (accInOneMinute > 200) { global = false; fetchSnippets = false; block = true; Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: CLIENT FROM " + client + ": " + accInOneMinute + " searches in one minute, fully blocked (no results generated)"); } else if (accInThreeSeconds > 1) { global = false; fetchSnippets = false; Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: CLIENT FROM " + client + ": " + accInThreeSeconds + " searches in three seconds, blocked global search and snippets"); } else if (accInOneSecond > 2) { global = false; fetchSnippets = false; Log.logWarning("LOCAL_SEARCH", "ACCECC CONTROL: CLIENT FROM " + client + ": " + accInOneSecond + " searches in one second, blocked global search and snippets"); } } if ((!block) && (post == null || post.get("cat", "href").equals("href"))) { // check available memory and clean up if necessary if (!MemoryControl.request(8000000L, false)) { sb.webIndex.metadata().clearCache(); plasmaSearchEvent.cleanupEvents(true); } final plasmaSearchRankingProfile ranking = sb.getRanking(); if (querystring.indexOf("NEAR") >= 0) { querystring = querystring.replace("NEAR", ""); ranking.coeff_worddistance = plasmaSearchRankingProfile.COEFF_MAX; } if (querystring.indexOf("RECENT") >= 0) { querystring = querystring.replace("RECENT", ""); ranking.coeff_date = plasmaSearchRankingProfile.COEFF_MAX; } int lrp = querystring.indexOf("LANGUAGE:"); String lr = ""; if (lrp >= 0) { if (querystring.length() >= (lrp + 11)) lr = querystring.substring(lrp + 9, lrp + 11); querystring = querystring.replace("LANGUAGE:" + lr, ""); lr = lr.toLowerCase(); } int inurl = querystring.indexOf("inurl:"); if (inurl >= 0) { int ftb = querystring.indexOf(' ', inurl); if (ftb == -1) ftb = querystring.length(); String urlstr = querystring.substring(inurl + 6, ftb); querystring = querystring.replace("inurl:" + urlstr, ""); if(urlstr.length() > 0) urlmask = ".*" + urlstr + ".*"; } int filetype = querystring.indexOf("filetype:"); if (filetype >= 0) { int ftb = querystring.indexOf(' ', filetype); if (ftb == -1) ftb = querystring.length(); String ft = querystring.substring(filetype + 9, ftb); querystring = querystring.replace("filetype:" + ft, ""); while(ft.startsWith(".")) ft = ft.substring(1); if(ft.length() > 0) { if (urlmask == null) { urlmask = ".*\\." + ft; } else { urlmask = urlmask + ".*\\." + ft; } } } if (post.containsKey("tenant")) { final String tenant = post.get("tenant"); if (urlmask == null) urlmask = ".*" + tenant + ".*"; else urlmask = ".*" + tenant + urlmask; } int site = querystring.indexOf("site:"); String sitehash = null; if (site >= 0) { int ftb = querystring.indexOf(' ', site); if (ftb == -1) ftb = querystring.length(); String domain = querystring.substring(site + 5, ftb); querystring = querystring.replace("site:" + domain, ""); while(domain.startsWith(".")) domain = domain.substring(1); while(domain.endsWith(".")) domain = domain.substring(0, domain.length() - 1); sitehash = yacyURL.domhash(domain); } int tld = querystring.indexOf("tld:"); if (tld >= 0) { int ftb = querystring.indexOf(' ', tld); if (ftb == -1) ftb = querystring.length(); String domain = querystring.substring(tld + 4, ftb); querystring = querystring.replace("tld:" + domain, ""); while(domain.startsWith(".")) domain = domain.substring(1); if (domain.indexOf(".") < 0) domain = "\\." + domain; // is tld if (domain.length() > 0) { if (urlmask == null) { urlmask = "[a-zA-Z]*://[^/]*" + domain + "/.*"; } else { urlmask = "[a-zA-Z]*://[^/]*" + domain + "/.*" + urlmask; } } } if (urlmask == null || urlmask.length() == 0) urlmask = originalUrlMask; //if no urlmask was given // read the language from the language-restrict option 'lr' // if no one is given, use the user agent or the system language as default String language = (post == null) ? lr : post.get("lr", lr); if (language.startsWith("lang_")) language = language.substring(5); if (!iso639.exists(language)) { // find out language of the user by reading of the user-agent string String agent = header.get(httpRequestHeader.ACCEPT_LANGUAGE); if (agent == null) agent = System.getProperty("user.language"); language = (agent == null) ? "en" : iso639.userAgentLanguageDetection(agent); if (language == null) language = "en"; } final TreeSet<String>[] query = plasmaSearchQuery.cleanQuery(querystring.trim()); // converts also umlaute int maxDistance = (querystring.indexOf('"') >= 0) ? maxDistance = query.length - 1 : Integer.MAX_VALUE; // filter out stopwords final TreeSet<String> filtered = SetTools.joinConstructive(query[0], plasmaSwitchboard.stopwords); if (filtered.size() > 0) { SetTools.excludeDestructive(query[0], plasmaSwitchboard.stopwords); } // if a minus-button was hit, remove a special reference first if (post != null && post.containsKey("deleteref")) try { if (!sb.verifyAuthentication(header, true)) { prop.put("AUTHENTICATE", "admin log-in"); // force log-in return prop; } // delete the index entry locally final String delHash = post.get("deleteref", ""); // urlhash sb.webIndex.index().remove(Word.words2hashes(query[0]), delHash); // make new news message with negative voting final HashMap<String, String> map = new HashMap<String, String>(); map.put("urlhash", delHash); map.put("vote", "negative"); map.put("refid", ""); sb.webIndex.peers().newsPool.publishMyNews(yacyNewsRecord.newRecord(sb.webIndex.peers().mySeed(), yacyNewsPool.CATEGORY_SURFTIPP_VOTE_ADD, map)); } catch (IOException e) { e.printStackTrace(); } // if a plus-button was hit, create new voting message if (post != null && post.containsKey("recommendref")) { if (!sb.verifyAuthentication(header, true)) { prop.put("AUTHENTICATE", "admin log-in"); // force log-in return prop; } final String recommendHash = post.get("recommendref", ""); // urlhash final URLMetadataRow urlentry = sb.webIndex.metadata().load(recommendHash, null, 0); if (urlentry != null) { final URLMetadataRow.Components metadata = urlentry.metadata(); plasmaParserDocument document; document = plasmaSnippetCache.retrieveDocument(metadata.url(), true, 5000, true, false); if (document != null) { // create a news message final HashMap<String, String> map = new HashMap<String, String>(); map.put("url", metadata.url().toNormalform(false, true).replace(',', '|')); map.put("title", metadata.dc_title().replace(',', ' ')); map.put("description", document.dc_title().replace(',', ' ')); map.put("author", document.dc_creator()); map.put("tags", document.dc_subject(' ')); sb.webIndex.peers().newsPool.publishMyNews(yacyNewsRecord.newRecord(sb.webIndex.peers().mySeed(), yacyNewsPool.CATEGORY_SURFTIPP_ADD, map)); document.close(); } } } // prepare search properties //final boolean yacyonline = ((sb.webIndex.seedDB != null) && (sb.webIndex.seedDB.mySeed() != null) && (sb.webIndex.seedDB.mySeed().getPublicAddress() != null)); final boolean globalsearch = (global) /* && (yacyonline)*/ && (sb.getConfigBool(plasmaSwitchboardConstants.INDEX_RECEIVE_ALLOW, false)); // do the search final TreeSet<byte[]> queryHashes = Word.words2hashes(query[0]); final plasmaSearchQuery theQuery = new plasmaSearchQuery( originalquerystring, queryHashes, Word.words2hashes(query[1]), Word.words2hashes(query[2]), ranking, maxDistance, prefermask, contentdomCode, language, fetchSnippets, itemsPerPage, offset, urlmask, (clustersearch && globalsearch) ? plasmaSearchQuery.SEARCHDOM_CLUSTERALL : ((globalsearch) ? plasmaSearchQuery.SEARCHDOM_GLOBALDHT : plasmaSearchQuery.SEARCHDOM_LOCAL), "", 20, constraint, true, sitehash, yacyURL.TLD_any_zone_filter, client, authenticated); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(theQuery.id(true), plasmaSearchEvent.INITIALIZATION, 0, 0), false); // tell all threads to do nothing for a specific time sb.intermissionAllThreads(10000); // filter out words that appear in bluelist theQuery.filterOut(plasmaSwitchboard.blueList); // log Log.logInfo("LOCAL_SEARCH", "INIT WORD SEARCH: " + theQuery.queryString + ":" + plasmaSearchQuery.hashSet2hashString(theQuery.queryHashes) + " - " + theQuery.neededResults() + " links to be computed, " + theQuery.displayResults() + " lines to be displayed"); RSSFeed.channels(RSSFeed.LOCALSEARCH).addMessage(new RSSMessage("Local Search Request", theQuery.queryString, "")); final long timestamp = System.currentTimeMillis(); // create a new search event if (plasmaSearchEvent.getEvent(theQuery.id(false)) == null) { theQuery.setOffset(0); // in case that this is a new search, always start without a offset offset = 0; } final plasmaSearchEvent theSearch = plasmaSearchEvent.getEvent(theQuery, ranking, sb.webIndex, sb.crawlResults, (sb.isRobinsonMode()) ? sb.clusterhashes : null, false); // generate result object //serverLog.logFine("LOCAL_SEARCH", "SEARCH TIME AFTER ORDERING OF SEARCH RESULTS: " + (System.currentTimeMillis() - timestamp) + " ms"); //serverLog.logFine("LOCAL_SEARCH", "SEARCH TIME AFTER RESULT PREPARATION: " + (System.currentTimeMillis() - timestamp) + " ms"); // calc some more cross-reference //serverLog.logFine("LOCAL_SEARCH", "SEARCH TIME AFTER XREF PREPARATION: " + (System.currentTimeMillis() - timestamp) + " ms"); // log Log.logInfo("LOCAL_SEARCH", "EXIT WORD SEARCH: " + theQuery.queryString + " - " + (theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize()) + " links found, " + (System.currentTimeMillis() - timestamp) + " ms"); // prepare search statistics theQuery.resultcount = theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize(); theQuery.searchtime = System.currentTimeMillis() - timestamp; theQuery.urlretrievaltime = theSearch.getURLRetrievalTime(); theQuery.snippetcomputationtime = theSearch.getSnippetComputationTime(); sb.localSearches.add(theQuery); // update the search tracker trackerHandles.add(theQuery.handle); sb.localSearchTracker.put(client, trackerHandles); final int totalcount = theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize(); prop.put("num-results_offset", offset); prop.put("num-results_itemscount", "0"); prop.put("num-results_itemsPerPage", itemsPerPage); prop.put("num-results_totalcount", Formatter.number(totalcount, true)); prop.put("num-results_globalresults", (globalsearch) ? "1" : "0"); prop.put("num-results_globalresults_localResourceSize", Formatter.number(theSearch.getRankingResult().getLocalResourceSize(), true)); prop.put("num-results_globalresults_remoteResourceSize", Formatter.number(theSearch.getRankingResult().getRemoteResourceSize(), true)); prop.put("num-results_globalresults_remoteIndexCount", Formatter.number(theSearch.getRankingResult().getRemoteIndexCount(), true)); prop.put("num-results_globalresults_remotePeerCount", Formatter.number(theSearch.getRankingResult().getRemotePeerCount(), true)); // compose page navigation final StringBuilder resnav = new StringBuilder(); final int thispage = offset / theQuery.displayResults(); if (thispage == 0) resnav.append("&lt;&nbsp;"); else { resnav.append(navurla(thispage - 1, display, theQuery, originalUrlMask)); resnav.append("<strong>&lt;</strong></a>&nbsp;"); } final int numberofpages = Math.min(10, Math.max(thispage + 2, totalcount / theQuery.displayResults())); for (int i = 0; i < numberofpages; i++) { if (i == thispage) { resnav.append("<strong>"); resnav.append(i + 1); resnav.append("</strong>&nbsp;"); } else { resnav.append(navurla(i, display, theQuery, originalUrlMask)); resnav.append(i + 1); resnav.append("</a>&nbsp;"); } } if (thispage >= numberofpages) resnav.append("&gt;"); else { resnav.append(navurla(thispage + 1, display, theQuery, originalUrlMask)); resnav.append("<strong>&gt;</strong></a>"); } prop.put("num-results_resnav", resnav.toString()); // generate the search result lines; they will be produced by another servlet for (int i = 0; i < theQuery.displayResults(); i++) { prop.put("results_" + i + "_item", offset + i); prop.put("results_" + i + "_eventID", theQuery.id(false)); prop.put("results_" + i + "_display", display); } prop.put("results", theQuery.displayResults()); prop.put("resultTable", (contentdomCode <= 1) ? "0" : "1"); prop.put("eventID", theQuery.id(false)); // for bottomline // process result of search if (filtered.size() > 0) { prop.put("excluded", "1"); prop.putHTML("excluded_stopwords", filtered.toString()); } else { prop.put("excluded", "0"); } if (prop == null || prop.size() == 0) { if (post == null || post.get("query", post.get("search", "")).length() < 3) { prop.put("num-results", "2"); // no results - at least 3 chars } else { prop.put("num-results", "1"); // no results } } else { prop.put("num-results", "3"); } prop.put("cat", "href"); prop.put("depth", "0"); // adding some additional properties needed for the rss feed String hostName = (String) header.get("Host", "localhost"); if (hostName.indexOf(":") == -1) hostName += ":" + serverCore.getPortNr(env.getConfig("port", "8080")); prop.put("searchBaseURL", "http://" + hostName + "/yacysearch.html"); prop.put("rssYacyImageURL", "http://" + hostName + "/env/grafics/yacy.gif"); } prop.put("searchagain", global ? "1" : "0"); prop.put("display", display); prop.put("display", display); prop.putHTML("former", originalquerystring); prop.put("count", itemsPerPage); prop.put("offset", offset); prop.put("resource", global ? "global" : "local"); prop.putHTML("urlmaskfilter", originalUrlMask); prop.putHTML("prefermaskfilter", prefermask); prop.put("indexof", (indexof) ? "on" : "off"); prop.put("constraint", (constraint == null) ? "" : constraint.exportB64()); prop.put("verify", (fetchSnippets) ? "true" : "false"); prop.put("contentdom", (post == null ? "text" : post.get("contentdom", "text"))); prop.put("contentdomCheckText", (contentdomCode == plasmaSearchQuery.CONTENTDOM_TEXT) ? "1" : "0"); prop.put("contentdomCheckAudio", (contentdomCode == plasmaSearchQuery.CONTENTDOM_AUDIO) ? "1" : "0"); prop.put("contentdomCheckVideo", (contentdomCode == plasmaSearchQuery.CONTENTDOM_VIDEO) ? "1" : "0"); prop.put("contentdomCheckImage", (contentdomCode == plasmaSearchQuery.CONTENTDOM_IMAGE) ? "1" : "0"); prop.put("contentdomCheckApp", (contentdomCode == plasmaSearchQuery.CONTENTDOM_APP) ? "1" : "0"); // for RSS: don't HTML encode some elements prop.putXML("rss_query", originalquerystring); prop.put("rss_queryenc", originalquerystring.replace(' ', '+')); sb.localSearchLastAccess = System.currentTimeMillis(); // return rewrite properties return prop; }
diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/CVSFolderElement.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/CVSFolderElement.java index 6ba3cb64a..cd079708b 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/CVSFolderElement.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/CVSFolderElement.java @@ -1,88 +1,89 @@ package org.eclipse.team.internal.ccvs.ui.model; /* * (c) Copyright IBM Corp. 2000, 2002. * All Rights Reserved. */ import java.lang.reflect.InvocationTargetException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.team.core.TeamException; import org.eclipse.team.internal.ccvs.core.ICVSFile; import org.eclipse.team.internal.ccvs.core.ICVSFolder; import org.eclipse.team.internal.ccvs.core.ICVSResource; import org.eclipse.team.internal.ccvs.ui.CVSUIPlugin; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; public class CVSFolderElement extends CVSResourceElement { private ICVSFolder folder; private boolean includeUnmanaged; public CVSFolderElement(ICVSFolder folder, boolean includeUnmanaged) { this.folder = folder; this.includeUnmanaged = includeUnmanaged; } /** * Returns CVSResourceElement instances */ - public Object[] getChildren(final Object o) { + public Object[] getChildren(Object o) { final Object[][] result = new Object[1][]; try { CVSUIPlugin.runWithProgress(null, true /*cancelable*/, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { ICVSResource[] children = folder.fetchChildren(monitor); CVSResourceElement[] elements = new CVSResourceElement[children.length]; for (int i = 0; i < children.length; i++) { ICVSResource resource = children[i]; if(resource.isFolder()) { elements[i] = new CVSFolderElement((ICVSFolder)resource, includeUnmanaged); } else { elements[i] = new CVSFileElement((ICVSFile)resource); } } result[0] = elements; } catch (TeamException e) { throw new InvocationTargetException(e); } } }); } catch (InterruptedException e) { return new Object[0]; } catch (InvocationTargetException e) { handle(e.getTargetException()); + return new Object[0]; } return result[0]; } /** * Overridden to append the version name to remote folders which * have version tags and are top-level folders. */ public String getLabel(Object o) { return folder.getName(); } public ImageDescriptor getImageDescriptor(Object object) { return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_FOLDER); } /** * @see IWorkbenchAdapter#getParent(Object) */ public Object getParent(Object o) { return new CVSFolderElement(folder.getParent(), includeUnmanaged); } /** * @see CVSResourceElement#getCVSResource() */ public ICVSResource getCVSResource() { return folder ; } }
false
true
public Object[] getChildren(final Object o) { final Object[][] result = new Object[1][]; try { CVSUIPlugin.runWithProgress(null, true /*cancelable*/, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { ICVSResource[] children = folder.fetchChildren(monitor); CVSResourceElement[] elements = new CVSResourceElement[children.length]; for (int i = 0; i < children.length; i++) { ICVSResource resource = children[i]; if(resource.isFolder()) { elements[i] = new CVSFolderElement((ICVSFolder)resource, includeUnmanaged); } else { elements[i] = new CVSFileElement((ICVSFile)resource); } } result[0] = elements; } catch (TeamException e) { throw new InvocationTargetException(e); } } }); } catch (InterruptedException e) { return new Object[0]; } catch (InvocationTargetException e) { handle(e.getTargetException()); } return result[0]; }
public Object[] getChildren(Object o) { final Object[][] result = new Object[1][]; try { CVSUIPlugin.runWithProgress(null, true /*cancelable*/, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { ICVSResource[] children = folder.fetchChildren(monitor); CVSResourceElement[] elements = new CVSResourceElement[children.length]; for (int i = 0; i < children.length; i++) { ICVSResource resource = children[i]; if(resource.isFolder()) { elements[i] = new CVSFolderElement((ICVSFolder)resource, includeUnmanaged); } else { elements[i] = new CVSFileElement((ICVSFile)resource); } } result[0] = elements; } catch (TeamException e) { throw new InvocationTargetException(e); } } }); } catch (InterruptedException e) { return new Object[0]; } catch (InvocationTargetException e) { handle(e.getTargetException()); return new Object[0]; } return result[0]; }
diff --git a/src/Java/domderrien/i18n/LabelExtractor.java b/src/Java/domderrien/i18n/LabelExtractor.java index cc23386..921e991 100644 --- a/src/Java/domderrien/i18n/LabelExtractor.java +++ b/src/Java/domderrien/i18n/LabelExtractor.java @@ -1,260 +1,267 @@ package domderrien.i18n; import java.util.HashMap; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; public class LabelExtractor { static public final String ERROR_MESSAGE_PREFIX = "errMsg_"; public enum ResourceFileId { master, second, third, fourth } /** * Return the message associated to the given error code, extracted from the master resource file. * * @param errorCode Error code * @param locale Optional locale instance, use to determine in which * resource files the label should be found. If the * reference is <code>null</code>, the root resource * bundle is used (written in English). * @return A localized label associated to the given error code. If no * association is found, the message identifier is returned. */ public static String get(int errorCode, Locale locale) { return get(ResourceFileId.master, errorCode, locale); } /** * Return the message associated to the given error code, extracted from the identifier resource file. * * @param errorCode Error code * @param resId Identifier of the resource file where the localized data should be extracted from * @param locale Optional locale instance, use to determine in which * resource files the label should be found. If the * reference is <code>null</code>, the root resource * bundle is used (written in English). * @return A localized label associated to the given error code. If no * association is found, the message identifier is returned. */ public static String get(ResourceFileId resId, int errorCode, Locale locale) { return get(ResourceFileId.master, errorCode, null, locale); } /** * Return the message associated to the given error code. * * @param errorCode Error code * @param parameters Array of parameters, each one used to replace a * pattern made of a number between curly braces. * @param locale Optional locale instance, use to determine in which * resource files the label should be found. If the * reference is <code>null</code>, the root resource * bundle is used (written in English). * @return A localized label associated to the given error code. If no * association is found, the message identifier is returned. */ public static String get(int errorCode, Object[] parameters, Locale locale) { return get(ResourceFileId.master, errorCode, parameters, locale); } /** * Return the message associated to the given error code. * * @param errorCode Error code * @param resId Identifier of the resource file where the localized data should be extracted from * @param parameters Array of parameters, each one used to replace a * pattern made of a number between curly braces. * @param locale Optional locale instance, use to determine in which * resource files the label should be found. If the * reference is <code>null</code>, the root resource * bundle is used (written in English). * @return A localized label associated to the given error code. If no * association is found, the message identifier is returned. */ public static String get(ResourceFileId resId, int errorCode, Object[] parameters, Locale locale) { String prefix = ERROR_MESSAGE_PREFIX; String label = get(resId, prefix + errorCode, parameters, locale); if (label.startsWith(prefix)) { return String.valueOf(errorCode); } return label; } /** * Return the message associated to the given identifier. * * @param messageId Identifier used to retrieve the localized label. * @param locale Optional locale instance, use to determine in which * resource files the label should be found. If the * reference is <code>null</code>, the root resource * bundle is used (written in English). * @return A localized label associated to the given error code. If no * association is found, the message identifier is returned. */ public static String get(String messageId, Locale locale) { return get(ResourceFileId.master, messageId, locale); } /** * Return the message associated to the given identifier. * * @param messageId Identifier used to retrieve the localized label. * @param resId Identifier of the resource file where the localized data should be extracted from * @param locale Optional locale instance, use to determine in which * resource files the label should be found. If the * reference is <code>null</code>, the root resource * bundle is used (written in English). * @return A localized label associated to the given error code. If no * association is found, the message identifier is returned. */ public static String get(ResourceFileId resId, String messageId, Locale locale) { return get(resId, messageId, null, locale); } /** * Return the message associated to the given identifier. * * @param messageId Identifier used to retrieve the localized label. * @param parameters Array of parameters, each one used to replace a * pattern made of a number between curly braces. * @param locale Optional locale instance, use to determine in which * resource files the label should be found. If the * reference is <code>null</code>, the root resource * bundle is used (written in English). * @return A localized label associated to the given error code. If no * association is found, the message identifier is returned. */ public static String get(String messageId, Object[] parameters, Locale locale) { return get(ResourceFileId.master, messageId, parameters, locale); } /** * Return the message associated to the given identifier. * * @param messageId Identifier used to retrieve the localized label. * @param resId Identifier of the resource file where the localized data should be extracted from * @param parameters Array of parameters, each one used to replace a * pattern made of a number between curly braces. * @param locale Optional locale instance, use to determine in which * resource files the label should be found. If the * reference is <code>null</code>, the root resource * bundle is used (written in English). * @return A localized label associated to the given error code. If no * association is found, the message identifier is returned. */ public static String get(ResourceFileId resId, String messageId, Object[] parameters, Locale locale) { String label = messageId; if (messageId != null && 0 < messageId.length()) { try { ResourceBundle labels = getResourceBundle(resId, locale); label = labels.getString(messageId); } catch (MissingResourceException ex) { // nothing } } return insertParameters(label, parameters); } /** * Utility method inserting the parameters into the given string * * @param label Text to process * @param parameters Array of parameters, each one used to replace a * pattern made of a number between curly braces. * @return Text where the place holders have been replaced by the * toString() of the objects passed in the array. * * @see java.text.MessageFormat#format(String, Object[]) */ public static String insertParameters(String label, Object[] parameters) { if (label != null && parameters != null) { // Note Message.format(label, parameters) does NOT work. int paramNb = parameters.length; for (int i=0; i<paramNb; ++i) { String pattern = "\\{" + i + "\\}"; //$NON-NLS-1$ //$NON-NLS-2$ label = label.replaceAll(pattern, parameters[i].toString()); } } return label; } /*------------------------------------------------------------------*/ /*------------------------------------------------------------------*/ protected static HashMap<String, ResourceBundle> masterResourceBundleSet = new HashMap<String, ResourceBundle>(); protected static HashMap<String, ResourceBundle> secondResourceBundleSet = new HashMap<String, ResourceBundle>(); protected static HashMap<String, ResourceBundle> thirdResourceBundleSet = new HashMap<String, ResourceBundle>(); protected static HashMap<String, ResourceBundle> fourthResourceBundleSet = new HashMap<String, ResourceBundle>(); /** * Provides a reset mechanism for the unit test suite * @param resId Identifier of the resource file set to manipulate */ protected static void resetResourceBundleList(ResourceFileId resId) { masterResourceBundleSet.clear(); } /** * Gives the string representing the locale or fall-back on the default one. * Made protected to be available for unit testing. * * @param locale locale to use * @return String identifying the locale */ protected static String getResourceBundleId(Locale locale) { return locale == null ? "root" : //$NON-NLS-1$ locale.toString(); // Composes language + country (if country available) } /** * Protected setter made available for the unit testing * * @param resId Identifier of the resource file set to manipulate * @param rb Mock resource bundle * @param locale Locale associated to the mock resource bundle */ protected static ResourceBundle setResourceBundle(ResourceFileId resId, ResourceBundle rb, Locale locale) { String rbId = getResourceBundleId(locale); ResourceBundle previousRB = masterResourceBundleSet.get(rbId); masterResourceBundleSet.put(rbId, rb); return previousRB; } /** * Retrieve the application resource bundle with the list of supported languages. * Specified protected only to ease the unit testing (IOP). * * @param resId Identifier of the resource file where the localized data should be extracted from * @param locale locale to use when getting the resource bundle * * @return The already resolved/set resource bundle or the one expected at runtime * @throws MissingResourceException */ protected static ResourceBundle getResourceBundle(ResourceFileId resId, Locale locale) throws MissingResourceException { String rbId = getResourceBundleId(locale); - ResourceBundle rb = (ResourceBundle) masterResourceBundleSet.get(rbId); + ResourceBundle rb; if (ResourceFileId.second.equals(resId)) { rb = (ResourceBundle) secondResourceBundleSet.get(rbId); } else if (ResourceFileId.third.equals(resId)) { rb = (ResourceBundle) thirdResourceBundleSet.get(rbId); } else if (ResourceFileId.fourth.equals(resId)) { rb = (ResourceBundle) fourthResourceBundleSet.get(rbId); } + else { rb = (ResourceBundle) masterResourceBundleSet.get(rbId); } if (rb == null) { // Get the resource bundle filename from the application settings and return the identified file ResourceBundle applicationSettings = ResourceBundle.getBundle(ResourceNameDefinitions.CONFIG_PROPERTIES_FILENAME, locale); - String keyForLookup = ResourceNameDefinitions.MASTER_TMX_FILENAME_KEY; + String keyForLookup; if (ResourceFileId.second.equals(resId)) { keyForLookup = ResourceNameDefinitions.SECOND_TMX_FILENAME_KEY; } else if (ResourceFileId.third.equals(resId)) { keyForLookup = ResourceNameDefinitions.THIRD_TMX_FILENAME_KEY; } else if (ResourceFileId.fourth.equals(resId)) { keyForLookup = ResourceNameDefinitions.FOURTH_TMX_FILENAME_KEY; } + else { keyForLookup = ResourceNameDefinitions.MASTER_TMX_FILENAME_KEY; } + // Get the resource bundle rb = ResourceBundle.getBundle(applicationSettings.getString(keyForLookup), locale); - masterResourceBundleSet.put(rbId, rb); + // Save the resource bundle reference + if (ResourceFileId.second.equals(resId)) { secondResourceBundleSet.put(rbId, rb); } + else if (ResourceFileId.third.equals(resId)) { thirdResourceBundleSet.put(rbId, rb); } + else if (ResourceFileId.fourth.equals(resId)) { fourthResourceBundleSet.put(rbId, rb); } + else { masterResourceBundleSet.put(rbId, rb); } } return rb; } }
false
true
protected static ResourceBundle getResourceBundle(ResourceFileId resId, Locale locale) throws MissingResourceException { String rbId = getResourceBundleId(locale); ResourceBundle rb = (ResourceBundle) masterResourceBundleSet.get(rbId); if (ResourceFileId.second.equals(resId)) { rb = (ResourceBundle) secondResourceBundleSet.get(rbId); } else if (ResourceFileId.third.equals(resId)) { rb = (ResourceBundle) thirdResourceBundleSet.get(rbId); } else if (ResourceFileId.fourth.equals(resId)) { rb = (ResourceBundle) fourthResourceBundleSet.get(rbId); } if (rb == null) { // Get the resource bundle filename from the application settings and return the identified file ResourceBundle applicationSettings = ResourceBundle.getBundle(ResourceNameDefinitions.CONFIG_PROPERTIES_FILENAME, locale); String keyForLookup = ResourceNameDefinitions.MASTER_TMX_FILENAME_KEY; if (ResourceFileId.second.equals(resId)) { keyForLookup = ResourceNameDefinitions.SECOND_TMX_FILENAME_KEY; } else if (ResourceFileId.third.equals(resId)) { keyForLookup = ResourceNameDefinitions.THIRD_TMX_FILENAME_KEY; } else if (ResourceFileId.fourth.equals(resId)) { keyForLookup = ResourceNameDefinitions.FOURTH_TMX_FILENAME_KEY; } rb = ResourceBundle.getBundle(applicationSettings.getString(keyForLookup), locale); masterResourceBundleSet.put(rbId, rb); } return rb; }
protected static ResourceBundle getResourceBundle(ResourceFileId resId, Locale locale) throws MissingResourceException { String rbId = getResourceBundleId(locale); ResourceBundle rb; if (ResourceFileId.second.equals(resId)) { rb = (ResourceBundle) secondResourceBundleSet.get(rbId); } else if (ResourceFileId.third.equals(resId)) { rb = (ResourceBundle) thirdResourceBundleSet.get(rbId); } else if (ResourceFileId.fourth.equals(resId)) { rb = (ResourceBundle) fourthResourceBundleSet.get(rbId); } else { rb = (ResourceBundle) masterResourceBundleSet.get(rbId); } if (rb == null) { // Get the resource bundle filename from the application settings and return the identified file ResourceBundle applicationSettings = ResourceBundle.getBundle(ResourceNameDefinitions.CONFIG_PROPERTIES_FILENAME, locale); String keyForLookup; if (ResourceFileId.second.equals(resId)) { keyForLookup = ResourceNameDefinitions.SECOND_TMX_FILENAME_KEY; } else if (ResourceFileId.third.equals(resId)) { keyForLookup = ResourceNameDefinitions.THIRD_TMX_FILENAME_KEY; } else if (ResourceFileId.fourth.equals(resId)) { keyForLookup = ResourceNameDefinitions.FOURTH_TMX_FILENAME_KEY; } else { keyForLookup = ResourceNameDefinitions.MASTER_TMX_FILENAME_KEY; } // Get the resource bundle rb = ResourceBundle.getBundle(applicationSettings.getString(keyForLookup), locale); // Save the resource bundle reference if (ResourceFileId.second.equals(resId)) { secondResourceBundleSet.put(rbId, rb); } else if (ResourceFileId.third.equals(resId)) { thirdResourceBundleSet.put(rbId, rb); } else if (ResourceFileId.fourth.equals(resId)) { fourthResourceBundleSet.put(rbId, rb); } else { masterResourceBundleSet.put(rbId, rb); } } return rb; }
diff --git a/src/main/java/org/nnsoft/t2t/Runner.java b/src/main/java/org/nnsoft/t2t/Runner.java index 2f894fd..d703c3f 100644 --- a/src/main/java/org/nnsoft/t2t/Runner.java +++ b/src/main/java/org/nnsoft/t2t/Runner.java @@ -1,165 +1,165 @@ /* * Copyright 2011 The 99 Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.nnsoft.t2t; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Properties; import org.nnsoft.t2t.configuration.ConfigurationManager; import org.nnsoft.t2t.configuration.MigratorConfiguration; import org.nnsoft.t2t.core.DefaultMigrator; import org.nnsoft.t2t.core.Migrator; import org.nnsoft.t2t.core.MigratorException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.beust.jcommander.JCommander; /** * @author Davide Palmisano ( [email protected] ) */ public class Runner { public static void main(String[] args) { final Logger logger = LoggerFactory.getLogger(Runner.class); RunnerOptions options = new RunnerOptions(); JCommander jCommander = new JCommander(options); jCommander.setProgramName("t2t"); jCommander.parseWithoutValidation(args); if (options.isPrintHelp()) { jCommander.usage(); System.exit(-1); } if (options.isPrintVersion()) { Properties properties = new Properties(); InputStream input = Runner.class.getClassLoader().getResourceAsStream("META-INF/maven/org.99soft/t2t/pom.properties"); if (input != null) { try { properties.load(input); } catch (IOException e) { // ignore, just don't load the properties } finally { try { input.close(); } catch (IOException e) { // close quietly } } } System.out.printf("99soft T2T %s (%s)%n", properties.getProperty("version"), properties.getProperty("build")); System.out.printf("Java version: %s, vendor: %s%n", System.getProperty("java.version"), System.getProperty("java.vendor")); System.out.printf("Java home: %s%n", System.getProperty("java.home")); System.out.printf("Default locale: %s_%s, platform encoding: %s%n", System.getProperty("user.language"), System.getProperty("user.country"), System.getProperty("sun.jnu.encoding")); System.out.printf("OS name: \"%s\", version: \"%s\", arch: \"%s\", family: \"%s\"%n", System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch"), getOsFamily()); System.exit(-1); } if (!options.getConfigurationFile().exists() || options.getConfigurationFile().isDirectory()) { System.out.println(String.format("Non-readable XML Configuration file: %s (No such file).", options.getConfigurationFile())); System.exit(-1); } if (options.getEntryPoint() == null) { System.out.println("No URL entrypoint has been specified for this migration."); System.exit(-1); } logger.info("Loading configuration from: '{}'", options.getConfigurationFile()); MigratorConfiguration configuration = ConfigurationManager.getInstance(options.getConfigurationFile()).getConfiguration(); final Migrator migrator = new DefaultMigrator(configuration); logger.info("Configuration load, starting migration..."); long start = System.currentTimeMillis(); int exit = 0; try { migrator.run(options.getEntryPoint()); } catch (MigratorException e) { logger.error("An error occurred during the migration process", e); exit = -1; } finally { logger.info("------------------------------------------------------------------------"); logger.info("T2T MIGRATION {}", (exit < 0) ? "FAILURE" : "SUCCESS"); logger.info("Total time: {}s", ((System.currentTimeMillis() - start) / 1000)); logger.info("Finished at: {}", new Date()); Runtime runtime = Runtime.getRuntime(); logger.info("Final Memory: {}M/{}M", - (runtime.totalMemory() - runtime.freeMemory()) / 1024, - runtime.totalMemory() / 1024); + (runtime.totalMemory() - runtime.freeMemory()) / (1024 * 1024), + runtime.totalMemory() / (1024 * 1024)); logger.info("------------------------------------------------------------------------"); System.exit(exit); } } private static final String getOsFamily() { String osName = System.getProperty("os.name").toLowerCase(); String pathSep = System.getProperty("path.separator"); if (osName.indexOf("windows") != -1) { return "windows"; } else if (osName.indexOf("os/2") != -1) { return "os/2"; } else if (osName.indexOf("z/os") != -1 || osName.indexOf("os/390") != -1) { return "z/os"; } else if (osName.indexOf("os/400") != -1) { return "os/400"; } else if (pathSep.equals(";")) { return "dos"; } else if (osName.indexOf("mac") != -1) { if (osName.endsWith("x")) { return "mac"; // MACOSX } return "unix"; } else if (osName.indexOf("nonstop_kernel") != -1) { return "tandem"; } else if (osName.indexOf("openvms") != -1) { return "openvms"; } else if (pathSep.equals(":")) { return "unix"; } return "undefined"; } }
true
true
public static void main(String[] args) { final Logger logger = LoggerFactory.getLogger(Runner.class); RunnerOptions options = new RunnerOptions(); JCommander jCommander = new JCommander(options); jCommander.setProgramName("t2t"); jCommander.parseWithoutValidation(args); if (options.isPrintHelp()) { jCommander.usage(); System.exit(-1); } if (options.isPrintVersion()) { Properties properties = new Properties(); InputStream input = Runner.class.getClassLoader().getResourceAsStream("META-INF/maven/org.99soft/t2t/pom.properties"); if (input != null) { try { properties.load(input); } catch (IOException e) { // ignore, just don't load the properties } finally { try { input.close(); } catch (IOException e) { // close quietly } } } System.out.printf("99soft T2T %s (%s)%n", properties.getProperty("version"), properties.getProperty("build")); System.out.printf("Java version: %s, vendor: %s%n", System.getProperty("java.version"), System.getProperty("java.vendor")); System.out.printf("Java home: %s%n", System.getProperty("java.home")); System.out.printf("Default locale: %s_%s, platform encoding: %s%n", System.getProperty("user.language"), System.getProperty("user.country"), System.getProperty("sun.jnu.encoding")); System.out.printf("OS name: \"%s\", version: \"%s\", arch: \"%s\", family: \"%s\"%n", System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch"), getOsFamily()); System.exit(-1); } if (!options.getConfigurationFile().exists() || options.getConfigurationFile().isDirectory()) { System.out.println(String.format("Non-readable XML Configuration file: %s (No such file).", options.getConfigurationFile())); System.exit(-1); } if (options.getEntryPoint() == null) { System.out.println("No URL entrypoint has been specified for this migration."); System.exit(-1); } logger.info("Loading configuration from: '{}'", options.getConfigurationFile()); MigratorConfiguration configuration = ConfigurationManager.getInstance(options.getConfigurationFile()).getConfiguration(); final Migrator migrator = new DefaultMigrator(configuration); logger.info("Configuration load, starting migration..."); long start = System.currentTimeMillis(); int exit = 0; try { migrator.run(options.getEntryPoint()); } catch (MigratorException e) { logger.error("An error occurred during the migration process", e); exit = -1; } finally { logger.info("------------------------------------------------------------------------"); logger.info("T2T MIGRATION {}", (exit < 0) ? "FAILURE" : "SUCCESS"); logger.info("Total time: {}s", ((System.currentTimeMillis() - start) / 1000)); logger.info("Finished at: {}", new Date()); Runtime runtime = Runtime.getRuntime(); logger.info("Final Memory: {}M/{}M", (runtime.totalMemory() - runtime.freeMemory()) / 1024, runtime.totalMemory() / 1024); logger.info("------------------------------------------------------------------------"); System.exit(exit); } }
public static void main(String[] args) { final Logger logger = LoggerFactory.getLogger(Runner.class); RunnerOptions options = new RunnerOptions(); JCommander jCommander = new JCommander(options); jCommander.setProgramName("t2t"); jCommander.parseWithoutValidation(args); if (options.isPrintHelp()) { jCommander.usage(); System.exit(-1); } if (options.isPrintVersion()) { Properties properties = new Properties(); InputStream input = Runner.class.getClassLoader().getResourceAsStream("META-INF/maven/org.99soft/t2t/pom.properties"); if (input != null) { try { properties.load(input); } catch (IOException e) { // ignore, just don't load the properties } finally { try { input.close(); } catch (IOException e) { // close quietly } } } System.out.printf("99soft T2T %s (%s)%n", properties.getProperty("version"), properties.getProperty("build")); System.out.printf("Java version: %s, vendor: %s%n", System.getProperty("java.version"), System.getProperty("java.vendor")); System.out.printf("Java home: %s%n", System.getProperty("java.home")); System.out.printf("Default locale: %s_%s, platform encoding: %s%n", System.getProperty("user.language"), System.getProperty("user.country"), System.getProperty("sun.jnu.encoding")); System.out.printf("OS name: \"%s\", version: \"%s\", arch: \"%s\", family: \"%s\"%n", System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch"), getOsFamily()); System.exit(-1); } if (!options.getConfigurationFile().exists() || options.getConfigurationFile().isDirectory()) { System.out.println(String.format("Non-readable XML Configuration file: %s (No such file).", options.getConfigurationFile())); System.exit(-1); } if (options.getEntryPoint() == null) { System.out.println("No URL entrypoint has been specified for this migration."); System.exit(-1); } logger.info("Loading configuration from: '{}'", options.getConfigurationFile()); MigratorConfiguration configuration = ConfigurationManager.getInstance(options.getConfigurationFile()).getConfiguration(); final Migrator migrator = new DefaultMigrator(configuration); logger.info("Configuration load, starting migration..."); long start = System.currentTimeMillis(); int exit = 0; try { migrator.run(options.getEntryPoint()); } catch (MigratorException e) { logger.error("An error occurred during the migration process", e); exit = -1; } finally { logger.info("------------------------------------------------------------------------"); logger.info("T2T MIGRATION {}", (exit < 0) ? "FAILURE" : "SUCCESS"); logger.info("Total time: {}s", ((System.currentTimeMillis() - start) / 1000)); logger.info("Finished at: {}", new Date()); Runtime runtime = Runtime.getRuntime(); logger.info("Final Memory: {}M/{}M", (runtime.totalMemory() - runtime.freeMemory()) / (1024 * 1024), runtime.totalMemory() / (1024 * 1024)); logger.info("------------------------------------------------------------------------"); System.exit(exit); } }
diff --git a/src/org/bonsaimind/easyminelauncher/Main.java b/src/org/bonsaimind/easyminelauncher/Main.java index 86926c6..49c6840 100644 --- a/src/org/bonsaimind/easyminelauncher/Main.java +++ b/src/org/bonsaimind/easyminelauncher/Main.java @@ -1,362 +1,363 @@ /* * Copyright 2012 Robert 'Bobby' Zenz. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY Robert 'Bobby' Zenz ''AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of Robert 'Bobby' Zenz. */ package org.bonsaimind.easyminelauncher; import java.awt.Dimension; import java.awt.Frame; import java.awt.Toolkit; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Main { private static String name = "EasyMineLauncher"; private static String version = "0.10"; public static void main(String[] args) { String jarDir = ""; String jar = ""; String lwjglDir = ""; String mppass = ""; String nativeDir = ""; List<String> additionalJars = new ArrayList<String>(); boolean noFrame = false; List<String> options = new ArrayList<String>(); boolean demo = false; String parentDir = ""; String port = null; String server = null; String sessionId = "0"; String username = "Username"; String texturepack = ""; String title = "Minecraft (" + name + ")"; boolean maximized = false; int width = 800; int height = 600; int x = -1; int y = -1; boolean alwaysOnTop = false; boolean fullscreen = false; // Parse arguments for (String arg : args) { if (arg.startsWith("--jar-dir=")) { jarDir = arg.substring(10); } else if (arg.startsWith("--jar=")) { jar = arg.substring(6); } else if (arg.startsWith("--lwjgl-dir=")) { lwjglDir = arg.substring(12); } else if (arg.startsWith("--mppass=")) { mppass = arg.substring(9); } else if (arg.startsWith("--native-dir=")) { nativeDir = arg.substring(13); } else if (arg.startsWith("--additional-jar=")) { String param = arg.substring(17); additionalJars.addAll(Arrays.asList(param.split(","))); } else if (arg.equals("--no-frame")) { noFrame = true; } else if (arg.startsWith("--parent-dir=")) { parentDir = arg.substring(13); } else if (arg.startsWith("--port=")) { port = arg.substring(7); } else if (arg.startsWith("--server=")) { server = arg.substring(9); } else if (arg.startsWith("--session-id=")) { sessionId = arg.substring(13); } else if (arg.startsWith("--set-option=")) { options.add(arg.substring(13)); } else if (arg.startsWith("--texturepack=")) { texturepack = arg.substring(14); } else if (arg.startsWith("--title=")) { title = arg.substring(8); } else if (arg.startsWith("--username=")) { username = arg.substring(11); } else if (arg.equals("--demo")) { demo = true; } else if (arg.equals("--version")) { printVersion(); return; } else if (arg.startsWith("--width=")) { width = Integer.parseInt(arg.substring(8)); } else if (arg.startsWith("--height=")) { height = Integer.parseInt(arg.substring(9)); } else if (arg.startsWith("--x=")) { x = Integer.parseInt(arg.substring(4)); } else if (arg.startsWith("--y=")) { y = Integer.parseInt(arg.substring(4)); } else if (arg.equals("--maximized")) { maximized = true; } else if (arg.equals("--always-on-top")) { alwaysOnTop = true; } else if (arg.equals("--fullscreen")) { fullscreen = true; } else if (arg.equals("--help")) { printHelp(); return; } else { System.err.println("Unknown parameter: " + arg); printHelp(); return; } } // Check the arguments if (jarDir.isEmpty() && jar.isEmpty()) { jarDir = new File(new File(System.getProperty("user.home"), ".minecraft").toString(), "bin").toString(); } if (jarDir.isEmpty()) { jarDir = new File(jar).getParent(); } else { jarDir = new File(jarDir).getAbsolutePath(); jar = jarDir; } if (lwjglDir.isEmpty()) { lwjglDir = jarDir; } if (nativeDir.isEmpty()) { nativeDir = new File(jarDir, "natives").getAbsolutePath(); } if (!parentDir.isEmpty()) { System.setProperty("user.home", parentDir); + System.setProperty("minecraft.applet.TargetDirectory", parentDir); } else { parentDir = System.getProperty("user.home"); } parentDir = new File(parentDir, ".minecraft").toString(); if (!texturepack.isEmpty()) { OptionsFile optionsFile = new OptionsFile(parentDir); if (optionsFile.exists() && optionsFile.read()) { optionsFile.setTexturePack(texturepack); // Set the options. for (String option : options) { int splitIdx = option.indexOf(":"); if (splitIdx > 0) { // we don't want not-named options either. optionsFile.setOption(option.substring(0, splitIdx), option.substring(splitIdx + 1)); } } if (!optionsFile.write()) { System.out.println("Failed to write options.txt!"); } } else { System.out.println("Failed to read options.txt or it does not exist!"); } } if (height <= 0) { height = 600; } if (width <= 0) { width = 800; } // Load the launcher if (!additionalJars.isEmpty()) { try { // This might fix issues for Mods which assume that they // are loaded via the real launcher...not sure, thought adding // it would be a good idea. List<URL> urls = new ArrayList<URL>(); for (String item : additionalJars) { urls.add(new File(item).toURI().toURL()); } if (!extendClassLoaders(urls.toArray(new URL[urls.size() - 1]))) { System.err.println("Failed to inject additional jars!"); return; } } catch (MalformedURLException ex) { System.err.println("Failed to load additional jars!"); System.err.println(ex); return; } } // Let's tell the Forge ModLoader (and others) that it is supposed // to load our applet and not that of the official launcher. System.setProperty("minecraft.applet.WrapperClass", "org.bonsaimind.easyminelauncher.ContainerApplet"); // Create the applet. ContainerApplet container = new ContainerApplet(); // Pass arguments to the applet. container.setDemo(demo); container.setUsername(username); if (server != null) { container.setServer(server, port != null ? port : "25565"); } container.setMpPass(mppass); container.setSessionId(sessionId); // Create and set up the frame. ContainerFrame frame = new ContainerFrame(title); if (fullscreen) { Dimension dimensions = Toolkit.getDefaultToolkit().getScreenSize(); frame.setAlwaysOnTop(true); frame.setUndecorated(true); frame.setSize(dimensions.width, dimensions.height); frame.setLocation(0, 0); } else { frame.setAlwaysOnTop(alwaysOnTop); frame.setUndecorated(noFrame); frame.setSize(width, height); // It is more likely that no location is set...I think. frame.setLocation( x == -1 ? frame.getX() : x, y == -1 ? frame.getY() : y); if (maximized) { frame.setExtendedState(Frame.MAXIMIZED_BOTH); } } frame.setContainerApplet(container); frame.setVisible(true); // Load container.loadNatives(nativeDir); if (container.loadJarsAndApplet(jar, lwjglDir)) { container.init(); container.start(); } else { System.err.println("Failed to load Minecraft! Exiting."); // Exit just to be sure. System.exit(0); } } /** * This is mostly from here: http://stackoverflow.com/questions/252893/how-do-you-change-the-classpath-within-java * @param url * @return */ private static boolean extendClassLoaders(URL[] urls) { // Extend the ClassLoader of the current thread. URLClassLoader loader = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader()); Thread.currentThread().setContextClassLoader(loader); // Extend the SystemClassLoader...this is needed for mods which will // use the WhatEver.getClass().getClassLoader() method to retrieve // a ClassLoader. URLClassLoader systemLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); try { Method addURLMethod = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class}); addURLMethod.setAccessible(true); for (URL url : urls) { addURLMethod.invoke(systemLoader, url); } return true; } catch (NoSuchMethodException ex) { System.err.println(ex); } catch (SecurityException ex) { System.err.println(ex); } catch (IllegalAccessException ex) { System.err.println(ex); } catch (InvocationTargetException ex) { System.err.println(ex); } return false; } private static void printVersion() { System.out.println(name + " " + version); System.out.println("Copyright 2012 Robert 'Bobby' Zenz. All rights reserved."); System.out.println("Licensed under 2-clause-BSD."); } private static void printHelp() { System.out.println("Usage: " + name + ".jar [OPTION]"); System.out.println("Launch Minecraft directly."); System.out.println(""); System.out.println(" --help Prints this help."); System.out.println(" --version Prints the version."); System.out.println(""); System.out.println(" --jar-dir=DIRECTORY Set the directory for the jar files."); System.out.println(" --jar=MINECRAFT.JAR Set the path to the minecraft.jar."); System.out.println(" Either specify jar-dir or this."); System.out.println(" --lwjgl-dir=DIRECTORY Set the directory for the jar files"); System.out.println(" of lwjgl (lwjgl.jar, lwjgl_util.jar,"); System.out.println(" and jinput.jar)"); System.out.println(" --mppass=MPPASS Set the mppass variable."); System.out.println(" --native-dir=DIRECTORY Set the directory for the native files"); System.out.println(" of lwjgl."); System.out.println(" --additional-jar=JAR Load the specified jars."); System.out.println(" This might be needed by some mods."); System.out.println(" Specify multiple times or list separated"); System.out.println(" with ','."); System.out.println(" --parent-dir=DIRECTORY Set the parent directory. This effectively"); System.out.println(" changes the location of the .minecraft folder."); System.out.println(" --port=PORT Set the port of the server, if not set"); System.out.println(" it will revert to 25565."); System.out.println(" --texturepack=FILE Set the texturepack to use, this takes"); System.out.println(" only the filename (including extension)."); System.out.println(" Use 'Default' for default."); System.out.println(" --server=SERVER Set the address of the server which"); System.out.println(" directly to connect to."); System.out.println(" --session-id=SESSIONID Set the session id."); System.out.println(" --set-option=NAME:VALUE Set this option in the options.txt file."); System.out.println(" --username=USERNAME Set the username to user."); System.out.println(" --demo Trigger Demo-Mode. This might break"); System.out.println(" other stuff (no Multiplayer f.e.)."); System.out.println(""); System.out.println(" --title=TITLE Replace the window title."); System.out.println(" --height=HEIGHT The width of the window."); System.out.println(" --width=WIDTH The height of the window."); System.out.println(" --x=X The x-location of the window."); System.out.println(" --y=Y The y-location of the window."); System.out.println(" --maximized Maximize the window."); System.out.println(" --no-frame Remove the border of the window."); System.out.println(" --always-on-top Make the window stay above all others."); System.out.println(" --fullscreen Makes the window the same size as"); System.out.println(" the whole desktop."); System.out.println(" This is basically shorthand for"); System.out.println(" --width=SCREENWIDTH"); System.out.println(" --height=SCREENHEIGHT"); System.out.println(" --x=0"); System.out.println(" --y=0"); System.out.println(" --no-frame"); System.out.println(" --always-on-top"); System.out.println(" This might yield odd results in multi-"); System.out.println(" monitor environments."); } }
true
true
public static void main(String[] args) { String jarDir = ""; String jar = ""; String lwjglDir = ""; String mppass = ""; String nativeDir = ""; List<String> additionalJars = new ArrayList<String>(); boolean noFrame = false; List<String> options = new ArrayList<String>(); boolean demo = false; String parentDir = ""; String port = null; String server = null; String sessionId = "0"; String username = "Username"; String texturepack = ""; String title = "Minecraft (" + name + ")"; boolean maximized = false; int width = 800; int height = 600; int x = -1; int y = -1; boolean alwaysOnTop = false; boolean fullscreen = false; // Parse arguments for (String arg : args) { if (arg.startsWith("--jar-dir=")) { jarDir = arg.substring(10); } else if (arg.startsWith("--jar=")) { jar = arg.substring(6); } else if (arg.startsWith("--lwjgl-dir=")) { lwjglDir = arg.substring(12); } else if (arg.startsWith("--mppass=")) { mppass = arg.substring(9); } else if (arg.startsWith("--native-dir=")) { nativeDir = arg.substring(13); } else if (arg.startsWith("--additional-jar=")) { String param = arg.substring(17); additionalJars.addAll(Arrays.asList(param.split(","))); } else if (arg.equals("--no-frame")) { noFrame = true; } else if (arg.startsWith("--parent-dir=")) { parentDir = arg.substring(13); } else if (arg.startsWith("--port=")) { port = arg.substring(7); } else if (arg.startsWith("--server=")) { server = arg.substring(9); } else if (arg.startsWith("--session-id=")) { sessionId = arg.substring(13); } else if (arg.startsWith("--set-option=")) { options.add(arg.substring(13)); } else if (arg.startsWith("--texturepack=")) { texturepack = arg.substring(14); } else if (arg.startsWith("--title=")) { title = arg.substring(8); } else if (arg.startsWith("--username=")) { username = arg.substring(11); } else if (arg.equals("--demo")) { demo = true; } else if (arg.equals("--version")) { printVersion(); return; } else if (arg.startsWith("--width=")) { width = Integer.parseInt(arg.substring(8)); } else if (arg.startsWith("--height=")) { height = Integer.parseInt(arg.substring(9)); } else if (arg.startsWith("--x=")) { x = Integer.parseInt(arg.substring(4)); } else if (arg.startsWith("--y=")) { y = Integer.parseInt(arg.substring(4)); } else if (arg.equals("--maximized")) { maximized = true; } else if (arg.equals("--always-on-top")) { alwaysOnTop = true; } else if (arg.equals("--fullscreen")) { fullscreen = true; } else if (arg.equals("--help")) { printHelp(); return; } else { System.err.println("Unknown parameter: " + arg); printHelp(); return; } } // Check the arguments if (jarDir.isEmpty() && jar.isEmpty()) { jarDir = new File(new File(System.getProperty("user.home"), ".minecraft").toString(), "bin").toString(); } if (jarDir.isEmpty()) { jarDir = new File(jar).getParent(); } else { jarDir = new File(jarDir).getAbsolutePath(); jar = jarDir; } if (lwjglDir.isEmpty()) { lwjglDir = jarDir; } if (nativeDir.isEmpty()) { nativeDir = new File(jarDir, "natives").getAbsolutePath(); } if (!parentDir.isEmpty()) { System.setProperty("user.home", parentDir); } else { parentDir = System.getProperty("user.home"); } parentDir = new File(parentDir, ".minecraft").toString(); if (!texturepack.isEmpty()) { OptionsFile optionsFile = new OptionsFile(parentDir); if (optionsFile.exists() && optionsFile.read()) { optionsFile.setTexturePack(texturepack); // Set the options. for (String option : options) { int splitIdx = option.indexOf(":"); if (splitIdx > 0) { // we don't want not-named options either. optionsFile.setOption(option.substring(0, splitIdx), option.substring(splitIdx + 1)); } } if (!optionsFile.write()) { System.out.println("Failed to write options.txt!"); } } else { System.out.println("Failed to read options.txt or it does not exist!"); } } if (height <= 0) { height = 600; } if (width <= 0) { width = 800; } // Load the launcher if (!additionalJars.isEmpty()) { try { // This might fix issues for Mods which assume that they // are loaded via the real launcher...not sure, thought adding // it would be a good idea. List<URL> urls = new ArrayList<URL>(); for (String item : additionalJars) { urls.add(new File(item).toURI().toURL()); } if (!extendClassLoaders(urls.toArray(new URL[urls.size() - 1]))) { System.err.println("Failed to inject additional jars!"); return; } } catch (MalformedURLException ex) { System.err.println("Failed to load additional jars!"); System.err.println(ex); return; } } // Let's tell the Forge ModLoader (and others) that it is supposed // to load our applet and not that of the official launcher. System.setProperty("minecraft.applet.WrapperClass", "org.bonsaimind.easyminelauncher.ContainerApplet"); // Create the applet. ContainerApplet container = new ContainerApplet(); // Pass arguments to the applet. container.setDemo(demo); container.setUsername(username); if (server != null) { container.setServer(server, port != null ? port : "25565"); } container.setMpPass(mppass); container.setSessionId(sessionId); // Create and set up the frame. ContainerFrame frame = new ContainerFrame(title); if (fullscreen) { Dimension dimensions = Toolkit.getDefaultToolkit().getScreenSize(); frame.setAlwaysOnTop(true); frame.setUndecorated(true); frame.setSize(dimensions.width, dimensions.height); frame.setLocation(0, 0); } else { frame.setAlwaysOnTop(alwaysOnTop); frame.setUndecorated(noFrame); frame.setSize(width, height); // It is more likely that no location is set...I think. frame.setLocation( x == -1 ? frame.getX() : x, y == -1 ? frame.getY() : y); if (maximized) { frame.setExtendedState(Frame.MAXIMIZED_BOTH); } } frame.setContainerApplet(container); frame.setVisible(true); // Load container.loadNatives(nativeDir); if (container.loadJarsAndApplet(jar, lwjglDir)) { container.init(); container.start(); } else { System.err.println("Failed to load Minecraft! Exiting."); // Exit just to be sure. System.exit(0); } }
public static void main(String[] args) { String jarDir = ""; String jar = ""; String lwjglDir = ""; String mppass = ""; String nativeDir = ""; List<String> additionalJars = new ArrayList<String>(); boolean noFrame = false; List<String> options = new ArrayList<String>(); boolean demo = false; String parentDir = ""; String port = null; String server = null; String sessionId = "0"; String username = "Username"; String texturepack = ""; String title = "Minecraft (" + name + ")"; boolean maximized = false; int width = 800; int height = 600; int x = -1; int y = -1; boolean alwaysOnTop = false; boolean fullscreen = false; // Parse arguments for (String arg : args) { if (arg.startsWith("--jar-dir=")) { jarDir = arg.substring(10); } else if (arg.startsWith("--jar=")) { jar = arg.substring(6); } else if (arg.startsWith("--lwjgl-dir=")) { lwjglDir = arg.substring(12); } else if (arg.startsWith("--mppass=")) { mppass = arg.substring(9); } else if (arg.startsWith("--native-dir=")) { nativeDir = arg.substring(13); } else if (arg.startsWith("--additional-jar=")) { String param = arg.substring(17); additionalJars.addAll(Arrays.asList(param.split(","))); } else if (arg.equals("--no-frame")) { noFrame = true; } else if (arg.startsWith("--parent-dir=")) { parentDir = arg.substring(13); } else if (arg.startsWith("--port=")) { port = arg.substring(7); } else if (arg.startsWith("--server=")) { server = arg.substring(9); } else if (arg.startsWith("--session-id=")) { sessionId = arg.substring(13); } else if (arg.startsWith("--set-option=")) { options.add(arg.substring(13)); } else if (arg.startsWith("--texturepack=")) { texturepack = arg.substring(14); } else if (arg.startsWith("--title=")) { title = arg.substring(8); } else if (arg.startsWith("--username=")) { username = arg.substring(11); } else if (arg.equals("--demo")) { demo = true; } else if (arg.equals("--version")) { printVersion(); return; } else if (arg.startsWith("--width=")) { width = Integer.parseInt(arg.substring(8)); } else if (arg.startsWith("--height=")) { height = Integer.parseInt(arg.substring(9)); } else if (arg.startsWith("--x=")) { x = Integer.parseInt(arg.substring(4)); } else if (arg.startsWith("--y=")) { y = Integer.parseInt(arg.substring(4)); } else if (arg.equals("--maximized")) { maximized = true; } else if (arg.equals("--always-on-top")) { alwaysOnTop = true; } else if (arg.equals("--fullscreen")) { fullscreen = true; } else if (arg.equals("--help")) { printHelp(); return; } else { System.err.println("Unknown parameter: " + arg); printHelp(); return; } } // Check the arguments if (jarDir.isEmpty() && jar.isEmpty()) { jarDir = new File(new File(System.getProperty("user.home"), ".minecraft").toString(), "bin").toString(); } if (jarDir.isEmpty()) { jarDir = new File(jar).getParent(); } else { jarDir = new File(jarDir).getAbsolutePath(); jar = jarDir; } if (lwjglDir.isEmpty()) { lwjglDir = jarDir; } if (nativeDir.isEmpty()) { nativeDir = new File(jarDir, "natives").getAbsolutePath(); } if (!parentDir.isEmpty()) { System.setProperty("user.home", parentDir); System.setProperty("minecraft.applet.TargetDirectory", parentDir); } else { parentDir = System.getProperty("user.home"); } parentDir = new File(parentDir, ".minecraft").toString(); if (!texturepack.isEmpty()) { OptionsFile optionsFile = new OptionsFile(parentDir); if (optionsFile.exists() && optionsFile.read()) { optionsFile.setTexturePack(texturepack); // Set the options. for (String option : options) { int splitIdx = option.indexOf(":"); if (splitIdx > 0) { // we don't want not-named options either. optionsFile.setOption(option.substring(0, splitIdx), option.substring(splitIdx + 1)); } } if (!optionsFile.write()) { System.out.println("Failed to write options.txt!"); } } else { System.out.println("Failed to read options.txt or it does not exist!"); } } if (height <= 0) { height = 600; } if (width <= 0) { width = 800; } // Load the launcher if (!additionalJars.isEmpty()) { try { // This might fix issues for Mods which assume that they // are loaded via the real launcher...not sure, thought adding // it would be a good idea. List<URL> urls = new ArrayList<URL>(); for (String item : additionalJars) { urls.add(new File(item).toURI().toURL()); } if (!extendClassLoaders(urls.toArray(new URL[urls.size() - 1]))) { System.err.println("Failed to inject additional jars!"); return; } } catch (MalformedURLException ex) { System.err.println("Failed to load additional jars!"); System.err.println(ex); return; } } // Let's tell the Forge ModLoader (and others) that it is supposed // to load our applet and not that of the official launcher. System.setProperty("minecraft.applet.WrapperClass", "org.bonsaimind.easyminelauncher.ContainerApplet"); // Create the applet. ContainerApplet container = new ContainerApplet(); // Pass arguments to the applet. container.setDemo(demo); container.setUsername(username); if (server != null) { container.setServer(server, port != null ? port : "25565"); } container.setMpPass(mppass); container.setSessionId(sessionId); // Create and set up the frame. ContainerFrame frame = new ContainerFrame(title); if (fullscreen) { Dimension dimensions = Toolkit.getDefaultToolkit().getScreenSize(); frame.setAlwaysOnTop(true); frame.setUndecorated(true); frame.setSize(dimensions.width, dimensions.height); frame.setLocation(0, 0); } else { frame.setAlwaysOnTop(alwaysOnTop); frame.setUndecorated(noFrame); frame.setSize(width, height); // It is more likely that no location is set...I think. frame.setLocation( x == -1 ? frame.getX() : x, y == -1 ? frame.getY() : y); if (maximized) { frame.setExtendedState(Frame.MAXIMIZED_BOTH); } } frame.setContainerApplet(container); frame.setVisible(true); // Load container.loadNatives(nativeDir); if (container.loadJarsAndApplet(jar, lwjglDir)) { container.init(); container.start(); } else { System.err.println("Failed to load Minecraft! Exiting."); // Exit just to be sure. System.exit(0); } }
diff --git a/maven-mercury/src/main/java/org/apache/maven/mercury/MavenDomainModel.java b/maven-mercury/src/main/java/org/apache/maven/mercury/MavenDomainModel.java index 98f268cbf..229875e3c 100644 --- a/maven-mercury/src/main/java/org/apache/maven/mercury/MavenDomainModel.java +++ b/maven-mercury/src/main/java/org/apache/maven/mercury/MavenDomainModel.java @@ -1,125 +1,125 @@ package org.apache.maven.mercury; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.maven.mercury.artifact.ArtifactMetadata; import org.apache.maven.model.Dependency; import org.apache.maven.model.Exclusion; import org.apache.maven.model.Parent; import org.apache.maven.model.PomClassicDomainModel; public final class MavenDomainModel extends PomClassicDomainModel { private ArtifactMetadata parentMetadata; /** * Constructor * * @throws IOException if there is a problem constructing the model */ public MavenDomainModel( byte[] bytes ) throws IOException { super( new ByteArrayInputStream( bytes ) ); } public MavenDomainModel(PomClassicDomainModel model) throws IOException { super(model.getModel()); } public boolean hasParent() { return getParentMetadata() != null; } public List<ArtifactMetadata> getDependencyMetadata() { List<ArtifactMetadata> metadatas = new ArrayList<ArtifactMetadata>(); for(Dependency d: model.getDependencies()) { ArtifactMetadata metadata = new ArtifactMetadata(); metadata.setArtifactId(d.getArtifactId()); metadata.setClassifier(d.getClassifier()); metadata.setGroupId(d.getGroupId()); - metadata.setScope( (d.getScope() == null) ? "runtime" : d.getScope()); + metadata.setScope( (d.getScope() == null) ? "compile" : d.getScope()); metadata.setVersion(d.getVersion()); metadata.setOptional(d.isOptional()); if( "test-jar".equals( d.getType() ) ) { metadata.setType( "jar" ); metadata.setClassifier( "tests" ); } else { metadata.setType( d.getType() ); } List<ArtifactMetadata> exclusions = new ArrayList<ArtifactMetadata>(); for( Exclusion e : d.getExclusions() ) { ArtifactMetadata md = new ArtifactMetadata(); md.setArtifactId(e.getArtifactId()); md.setGroupId(e.getGroupId()); exclusions.add(md); } metadata.setExclusions(exclusions); metadatas.add(metadata); } return metadatas; } public ArtifactMetadata getParentMetadata() { if(parentMetadata == null) { Parent parent = model.getParent(); if(parent != null) { parentMetadata = new ArtifactMetadata(); parentMetadata.setArtifactId( parent.getArtifactId() ); parentMetadata.setVersion( parent.getVersion() ); parentMetadata.setGroupId( parent.getGroupId() ); } } return (parentMetadata != null) ? copyArtifactBasicMetadata( parentMetadata ) : null; } private ArtifactMetadata copyArtifactBasicMetadata( ArtifactMetadata metadata ) { ArtifactMetadata amd = new ArtifactMetadata(); amd.setArtifactId( metadata.getArtifactId() ); amd.setGroupId( metadata.getGroupId() ); amd.setVersion( metadata.getVersion() ); return amd; } }
true
true
public List<ArtifactMetadata> getDependencyMetadata() { List<ArtifactMetadata> metadatas = new ArrayList<ArtifactMetadata>(); for(Dependency d: model.getDependencies()) { ArtifactMetadata metadata = new ArtifactMetadata(); metadata.setArtifactId(d.getArtifactId()); metadata.setClassifier(d.getClassifier()); metadata.setGroupId(d.getGroupId()); metadata.setScope( (d.getScope() == null) ? "runtime" : d.getScope()); metadata.setVersion(d.getVersion()); metadata.setOptional(d.isOptional()); if( "test-jar".equals( d.getType() ) ) { metadata.setType( "jar" ); metadata.setClassifier( "tests" ); } else { metadata.setType( d.getType() ); } List<ArtifactMetadata> exclusions = new ArrayList<ArtifactMetadata>(); for( Exclusion e : d.getExclusions() ) { ArtifactMetadata md = new ArtifactMetadata(); md.setArtifactId(e.getArtifactId()); md.setGroupId(e.getGroupId()); exclusions.add(md); } metadata.setExclusions(exclusions); metadatas.add(metadata); } return metadatas; }
public List<ArtifactMetadata> getDependencyMetadata() { List<ArtifactMetadata> metadatas = new ArrayList<ArtifactMetadata>(); for(Dependency d: model.getDependencies()) { ArtifactMetadata metadata = new ArtifactMetadata(); metadata.setArtifactId(d.getArtifactId()); metadata.setClassifier(d.getClassifier()); metadata.setGroupId(d.getGroupId()); metadata.setScope( (d.getScope() == null) ? "compile" : d.getScope()); metadata.setVersion(d.getVersion()); metadata.setOptional(d.isOptional()); if( "test-jar".equals( d.getType() ) ) { metadata.setType( "jar" ); metadata.setClassifier( "tests" ); } else { metadata.setType( d.getType() ); } List<ArtifactMetadata> exclusions = new ArrayList<ArtifactMetadata>(); for( Exclusion e : d.getExclusions() ) { ArtifactMetadata md = new ArtifactMetadata(); md.setArtifactId(e.getArtifactId()); md.setGroupId(e.getGroupId()); exclusions.add(md); } metadata.setExclusions(exclusions); metadatas.add(metadata); } return metadatas; }
diff --git a/src/main/java/org/basex/core/CommandParser.java b/src/main/java/org/basex/core/CommandParser.java index 9739afc34..ca584264b 100644 --- a/src/main/java/org/basex/core/CommandParser.java +++ b/src/main/java/org/basex/core/CommandParser.java @@ -1,529 +1,529 @@ package org.basex.core; import static org.basex.core.Text.*; import static org.basex.util.Token.*; import org.basex.core.Commands.Cmd; import org.basex.core.Commands.CmdAlter; import org.basex.core.Commands.CmdAttach; import org.basex.core.Commands.CmdCreate; import org.basex.core.Commands.CmdDetach; import org.basex.core.Commands.CmdDrop; import org.basex.core.Commands.CmdIndex; import org.basex.core.Commands.CmdIndexInfo; import org.basex.core.Commands.CmdInfo; import org.basex.core.Commands.CmdPerm; import org.basex.core.Commands.CmdShow; import org.basex.core.cmd.Add; import org.basex.core.cmd.AlterDB; import org.basex.core.cmd.AlterUser; import org.basex.core.cmd.AttachTrigger; import org.basex.core.cmd.Backup; import org.basex.core.cmd.Check; import org.basex.core.cmd.Close; import org.basex.core.cmd.CreateDB; import org.basex.core.cmd.CreateFS; import org.basex.core.cmd.CreateIndex; import org.basex.core.cmd.CreateMAB; import org.basex.core.cmd.CreateTrigger; import org.basex.core.cmd.CreateUser; import org.basex.core.cmd.Cs; import org.basex.core.cmd.Delete; import org.basex.core.cmd.DetachTrigger; import org.basex.core.cmd.DropBackup; import org.basex.core.cmd.DropDB; import org.basex.core.cmd.DropIndex; import org.basex.core.cmd.DropTrigger; import org.basex.core.cmd.DropUser; import org.basex.core.cmd.Exit; import org.basex.core.cmd.Export; import org.basex.core.cmd.Find; import org.basex.core.cmd.Get; import org.basex.core.cmd.Grant; import org.basex.core.cmd.Help; import org.basex.core.cmd.Info; import org.basex.core.cmd.InfoDB; import org.basex.core.cmd.InfoIndex; import org.basex.core.cmd.InfoStorage; import org.basex.core.cmd.Kill; import org.basex.core.cmd.List; import org.basex.core.cmd.ListDB; import org.basex.core.cmd.Open; import org.basex.core.cmd.Optimize; import org.basex.core.cmd.Password; import org.basex.core.cmd.Restore; import org.basex.core.cmd.Run; import org.basex.core.cmd.Set; import org.basex.core.cmd.ShowBackups; import org.basex.core.cmd.ShowDatabases; import org.basex.core.cmd.ShowSessions; import org.basex.core.cmd.ShowTriggers; import org.basex.core.cmd.ShowUsers; import org.basex.core.cmd.XQuery; import org.basex.query.QueryContext; import org.basex.query.QueryException; import org.basex.query.QueryParser; import org.basex.util.Array; import org.basex.util.InputParser; import org.basex.util.Levenshtein; import org.basex.util.StringList; import org.basex.util.TokenBuilder; /** * This is a parser for command strings, creating {@link Command} instances. * Several commands can be formulated in one string and separated by semicolons. * * @author BaseX Team 2005-11, BSD License * @author Christian Gruen */ public final class CommandParser extends InputParser { /** Context. */ private final Context ctx; /** Flag for gui command. */ private boolean gui; /** * Constructor, parsing the input queries. * @param in query input * @param c context */ public CommandParser(final String in, final Context c) { super(in); ctx = c; } /** * Parses the input as single command and returns the result. * @return command * @throws QueryException query exception */ public Command parseSingle() throws QueryException { final Cmd cmd = consume(Cmd.class, null); final Command command = parse(cmd, true); consumeWS(); if(more()) help(null, cmd); return command; } /** * Parses the input and returns a command list. * @return commands * @throws QueryException query exception */ public Command[] parse() throws QueryException { Command[] list = new Command[0]; while(true) { final Cmd cmd = consume(Cmd.class, null); list = Array.add(list, parse(cmd, false)); consumeWS(); if(!more()) return list; if(!consume(';')) help(null, cmd); } } /** * Parses the input and returns a command list. * @param g gui flag * @return commands * @throws QueryException query exception */ public Command[] parse(final boolean g) throws QueryException { gui = g; return parse(); } /** * Parses a single command. * @param cmd command definition * @param s single command expected * @return resulting command * @throws QueryException query exception */ private Command parse(final Cmd cmd, final boolean s) throws QueryException { switch(cmd) { case CREATE: switch(consume(CmdCreate.class, cmd)) { case DATABASE: case DB: return new CreateDB(name(cmd), s ? remaining(null) : string(null)); case INDEX: return new CreateIndex(consume(CmdIndex.class, cmd)); case FS: return new CreateFS(name(cmd), string(cmd)); case MAB: return new CreateMAB(string(cmd), name(null)); case USER: return new CreateUser(name(cmd), string(null)); case TRIGGER: return new CreateTrigger(name(cmd)); } break; case ALTER: switch(consume(CmdAlter.class, cmd)) { case DATABASE: case DB: return new AlterDB(name(cmd), name(cmd)); case USER: return new AlterUser(name(cmd), string(null)); } break; case OPEN: - return new Open(name(cmd)); + return new Open(string(cmd)); case ATTACH: switch (consume(CmdAttach.class, cmd)) { case TRIGGER: return new AttachTrigger(name(cmd)); } break; case DETACH: switch (consume(CmdDetach.class, cmd)) { case TRIGGER: return new DetachTrigger(name(cmd)); } break; case CHECK: return new Check(string(cmd)); case ADD: String arg1 = key(AS, null) ? string(cmd) : null; String arg2 = key(TO, null) ? string(cmd) : null; return new Add(s ? remaining(cmd) : string(cmd), arg1, arg2); case DELETE: return new Delete(string(cmd)); case INFO: switch(consume(CmdInfo.class, cmd)) { case NULL: return new Info(); case DATABASE: case DB: return new InfoDB(); case INDEX: return new InfoIndex(consume(CmdIndexInfo.class, null)); case STORAGE: arg1 = number(null); arg2 = arg1 != null ? number(null) : null; if(arg1 == null) arg1 = xquery(null); return new InfoStorage(arg1, arg2); } break; case CLOSE: return new Close(); case LIST: final String input = string(null); return input == null ? new List() : new ListDB(input); case DROP: switch(consume(CmdDrop.class, cmd)) { case DATABASE: case DB: return new DropDB(name(cmd)); case INDEX: return new DropIndex(consume(CmdIndex.class, cmd)); case USER: return new DropUser(name(cmd), key(ON, null) ? name(cmd) : null); case BACKUP: return new DropBackup(name(cmd)); case TRIGGER: return new DropTrigger(name(cmd)); } break; case OPTIMIZE: return new Optimize(); case EXPORT: return new Export(string(cmd)); case XQUERY: return new XQuery(xquery(cmd)); case RUN: return new Run(string(cmd)); case FIND: return new Find(string(cmd)); case CS: return new Cs(xquery(cmd)); case GET: return new Get(name(cmd)); case SET: return new Set(name(cmd), string(null)); case PASSWORD: return new Password(string(null)); case HELP: String hc = name(null); String form = null; if(hc != null) { if(hc.equalsIgnoreCase("wiki")) { form = hc; hc = null; } else { qp = qm; hc = consume(Cmd.class, cmd).toString(); form = name(null); } } return new Help(hc, form); case EXIT: case QUIT: return new Exit(); case KILL: return new Kill(name(cmd)); case BACKUP: return new Backup(name(cmd)); case RESTORE: return new Restore(name(cmd)); case SHOW: switch(consume(CmdShow.class, cmd)) { case DATABASES: return new ShowDatabases(); case SESSIONS: return new ShowSessions(); case USERS: return new ShowUsers(key(ON, null) ? name(cmd) : null); case BACKUPS: return new ShowBackups(); case TRIGGERS: return new ShowTriggers(); default: } break; case GRANT: final CmdPerm perm = consume(CmdPerm.class, cmd); if(perm == null) help(null, cmd); final String db = key(ON, null) ? name(cmd) : null; key(TO, cmd); return db == null ? new Grant(perm, name(cmd)) : new Grant(perm, name(cmd), db); default: } return null; } /** * Parses and returns a string, delimited by a space or semicolon. * Quotes can be used to include spaces. * @param cmd referring command; if specified, the result must not be empty * @return string * @throws QueryException query exception */ private String string(final Cmd cmd) throws QueryException { final TokenBuilder tb = new TokenBuilder(); consumeWS(); boolean q = false; while(more()) { final char c = curr(); if(!q && (c <= ' ' || c == ';')) break; if(c == '"') q ^= true; else tb.add(c); consume(); } return finish(cmd, tb); } /** * Parses and returns the remaining string. Quotes at the beginning and end * of the argument will be stripped. * @param cmd referring command; if specified, the result must not be empty * @return remaining string * @throws QueryException query exception */ private String remaining(final Cmd cmd) throws QueryException { final TokenBuilder tb = new TokenBuilder(); consumeWS(); while(more()) tb.add(consume()); String arg = finish(cmd, tb); if(arg != null) { // chop quotes; substrings are faster than replaces... if(arg.startsWith("\"")) arg = arg.substring(1); if(arg.endsWith("\"")) arg = arg.substring(0, arg.length() - 1); } return arg; } /** * Parses and returns an xquery expression. * @param cmd referring command; if specified, the result must not be empty * @return path * @throws QueryException query exception */ private String xquery(final Cmd cmd) throws QueryException { consumeWS(); final TokenBuilder tb = new TokenBuilder(); if(more() && !curr(';')) { final QueryParser p = new QueryParser(query, new QueryContext(ctx)); p.qp = qp; p.parse(null, false); tb.add(query.substring(qp, p.qp)); qp = p.qp; } return finish(cmd, tb); } /** * Parses and returns a name. A name is limited to letters, digits, * underscores, dashes, and periods: {@code [A-Za-z0-9_-]+}. * @param cmd referring command; if specified, the result must not be empty * @return name * @throws QueryException query exception */ private String name(final Cmd cmd) throws QueryException { consumeWS(); final TokenBuilder tb = new TokenBuilder(); while(letterOrDigit(curr()) || curr('-')) tb.add(consume()); return finish(cmd, !more() || curr(';') || ws(curr()) ? tb : null); } /** * Parses and returns the specified keyword. * @param key token to be parsed * @param cmd referring command; if specified, the keyword is mandatory * @return result of check * @throws QueryException query exception */ private boolean key(final String key, final Cmd cmd) throws QueryException { consumeWS(); final int p = qp; final boolean ok = (consume(key) || consume(key.toLowerCase())) && (curr(0) || ws(curr())); if(!ok) { qp = p; if(cmd != null) help(null, cmd); } return ok; } /** * Parses and returns a string result. * @param cmd referring command; if specified, the result must not be empty * @param s input string, or {@code null} if invalid * @return string result, or {@code null} * @throws QueryException query exception */ private String finish(final Cmd cmd, final TokenBuilder s) throws QueryException { if(s != null && s.size() != 0) return s.toString(); if(cmd != null) help(null, cmd); return null; } /** * Parses and returns a number. * @param cmd referring command; if specified, the result must not be empty * @return name * @throws QueryException query exception */ private String number(final Cmd cmd) throws QueryException { consumeWS(); final TokenBuilder tb = new TokenBuilder(); if(curr() == '-') tb.add(consume()); while(digit(curr())) tb.add(consume()); return finish(cmd, !more() || curr(';') || ws(curr()) ? tb : null); } /** * Consumes all whitespace characters from the beginning of the remaining * query. */ private void consumeWS() { while(qp < ql && query.charAt(qp) <= ' ') ++qp; qm = qp - 1; } /** * Returns the index of the found string or throws an error. * @param cmp possible completions * @param par parent command * @param <E> token type * @return index * @throws QueryException query exception */ private <E extends Enum<E>> E consume(final Class<E> cmp, final Cmd par) throws QueryException { final String token = name(null); if(!(gui && token != null && token.length() <= 1)) { try { // return command reference; allow empty strings as input ("NULL") final String t = token == null ? "NULL" : token.toUpperCase(); return Enum.valueOf(cmp, t); } catch(final IllegalArgumentException ex) { /* will not happen. */ } } final Enum<?>[] alt = list(cmp, token); if(token == null) { // no command found if(par == null) error(list(alt), CMDNO); // show available command extensions help(list(alt), par); } // output error for similar commands final byte[] name = lc(token(token)); final Levenshtein ls = new Levenshtein(); for(final Enum<?> s : list(cmp, null)) { final byte[] sm = lc(token(s.name().toLowerCase())); if(ls.similar(name, sm, 0) && Cmd.class.isInstance(s)) error(list(alt), CMDSIMILAR, name, sm); } // unknown command if(par == null) error(list(alt), CMDWHICH, token); // show available command extensions help(list(alt), par); return null; } /** * Prints some command info. * @param alt input alternatives * @param cmd input completions * @throws QueryException query exception */ private void help(final StringList alt, final Cmd cmd) throws QueryException { error(alt, PROCSYNTAX, cmd.help(true, false)); } /** * Returns the command list. * @param <T> token type * @param en enumeration * @param i user input * @return completions */ private <T extends Enum<T>> Enum<?>[] list(final Class<T> en, final String i) { Enum<?>[] list = new Enum<?>[0]; final String t = i == null ? "" : i.toUpperCase(); for(final Enum<?> e : en.getEnumConstants()) { // ignore hidden commands if(Cmd.class.isInstance(e) && Cmd.class.cast(e).hidden()) continue; if(e.name().startsWith(t)) { final int s = list.length; final Enum<?>[] tmp = new Enum<?>[s + 1]; System.arraycopy(list, 0, tmp, 0, s); tmp[s] = e; list = tmp; } } return list; } /** * Throws an error. * @param comp input completions * @param m message * @param e extension * @throws QueryException query exception */ private void error(final StringList comp, final String m, final Object... e) throws QueryException { final QueryException qe = new QueryException(input(), "", null, m, e); qe.complete(this, comp); throw qe; } /** * Converts the specified commands into a string list. * @param comp input completions * @return string list */ private StringList list(final Enum<?>[] comp) { final StringList list = new StringList(); for(final Enum<?> c : comp) list.add(c.name().toLowerCase()); return list; } }
true
true
private Command parse(final Cmd cmd, final boolean s) throws QueryException { switch(cmd) { case CREATE: switch(consume(CmdCreate.class, cmd)) { case DATABASE: case DB: return new CreateDB(name(cmd), s ? remaining(null) : string(null)); case INDEX: return new CreateIndex(consume(CmdIndex.class, cmd)); case FS: return new CreateFS(name(cmd), string(cmd)); case MAB: return new CreateMAB(string(cmd), name(null)); case USER: return new CreateUser(name(cmd), string(null)); case TRIGGER: return new CreateTrigger(name(cmd)); } break; case ALTER: switch(consume(CmdAlter.class, cmd)) { case DATABASE: case DB: return new AlterDB(name(cmd), name(cmd)); case USER: return new AlterUser(name(cmd), string(null)); } break; case OPEN: return new Open(name(cmd)); case ATTACH: switch (consume(CmdAttach.class, cmd)) { case TRIGGER: return new AttachTrigger(name(cmd)); } break; case DETACH: switch (consume(CmdDetach.class, cmd)) { case TRIGGER: return new DetachTrigger(name(cmd)); } break; case CHECK: return new Check(string(cmd)); case ADD: String arg1 = key(AS, null) ? string(cmd) : null; String arg2 = key(TO, null) ? string(cmd) : null; return new Add(s ? remaining(cmd) : string(cmd), arg1, arg2); case DELETE: return new Delete(string(cmd)); case INFO: switch(consume(CmdInfo.class, cmd)) { case NULL: return new Info(); case DATABASE: case DB: return new InfoDB(); case INDEX: return new InfoIndex(consume(CmdIndexInfo.class, null)); case STORAGE: arg1 = number(null); arg2 = arg1 != null ? number(null) : null; if(arg1 == null) arg1 = xquery(null); return new InfoStorage(arg1, arg2); } break; case CLOSE: return new Close(); case LIST: final String input = string(null); return input == null ? new List() : new ListDB(input); case DROP: switch(consume(CmdDrop.class, cmd)) { case DATABASE: case DB: return new DropDB(name(cmd)); case INDEX: return new DropIndex(consume(CmdIndex.class, cmd)); case USER: return new DropUser(name(cmd), key(ON, null) ? name(cmd) : null); case BACKUP: return new DropBackup(name(cmd)); case TRIGGER: return new DropTrigger(name(cmd)); } break; case OPTIMIZE: return new Optimize(); case EXPORT: return new Export(string(cmd)); case XQUERY: return new XQuery(xquery(cmd)); case RUN: return new Run(string(cmd)); case FIND: return new Find(string(cmd)); case CS: return new Cs(xquery(cmd)); case GET: return new Get(name(cmd)); case SET: return new Set(name(cmd), string(null)); case PASSWORD: return new Password(string(null)); case HELP: String hc = name(null); String form = null; if(hc != null) { if(hc.equalsIgnoreCase("wiki")) { form = hc; hc = null; } else { qp = qm; hc = consume(Cmd.class, cmd).toString(); form = name(null); } } return new Help(hc, form); case EXIT: case QUIT: return new Exit(); case KILL: return new Kill(name(cmd)); case BACKUP: return new Backup(name(cmd)); case RESTORE: return new Restore(name(cmd)); case SHOW: switch(consume(CmdShow.class, cmd)) { case DATABASES: return new ShowDatabases(); case SESSIONS: return new ShowSessions(); case USERS: return new ShowUsers(key(ON, null) ? name(cmd) : null); case BACKUPS: return new ShowBackups(); case TRIGGERS: return new ShowTriggers(); default: } break; case GRANT: final CmdPerm perm = consume(CmdPerm.class, cmd); if(perm == null) help(null, cmd); final String db = key(ON, null) ? name(cmd) : null; key(TO, cmd); return db == null ? new Grant(perm, name(cmd)) : new Grant(perm, name(cmd), db); default: } return null; }
private Command parse(final Cmd cmd, final boolean s) throws QueryException { switch(cmd) { case CREATE: switch(consume(CmdCreate.class, cmd)) { case DATABASE: case DB: return new CreateDB(name(cmd), s ? remaining(null) : string(null)); case INDEX: return new CreateIndex(consume(CmdIndex.class, cmd)); case FS: return new CreateFS(name(cmd), string(cmd)); case MAB: return new CreateMAB(string(cmd), name(null)); case USER: return new CreateUser(name(cmd), string(null)); case TRIGGER: return new CreateTrigger(name(cmd)); } break; case ALTER: switch(consume(CmdAlter.class, cmd)) { case DATABASE: case DB: return new AlterDB(name(cmd), name(cmd)); case USER: return new AlterUser(name(cmd), string(null)); } break; case OPEN: return new Open(string(cmd)); case ATTACH: switch (consume(CmdAttach.class, cmd)) { case TRIGGER: return new AttachTrigger(name(cmd)); } break; case DETACH: switch (consume(CmdDetach.class, cmd)) { case TRIGGER: return new DetachTrigger(name(cmd)); } break; case CHECK: return new Check(string(cmd)); case ADD: String arg1 = key(AS, null) ? string(cmd) : null; String arg2 = key(TO, null) ? string(cmd) : null; return new Add(s ? remaining(cmd) : string(cmd), arg1, arg2); case DELETE: return new Delete(string(cmd)); case INFO: switch(consume(CmdInfo.class, cmd)) { case NULL: return new Info(); case DATABASE: case DB: return new InfoDB(); case INDEX: return new InfoIndex(consume(CmdIndexInfo.class, null)); case STORAGE: arg1 = number(null); arg2 = arg1 != null ? number(null) : null; if(arg1 == null) arg1 = xquery(null); return new InfoStorage(arg1, arg2); } break; case CLOSE: return new Close(); case LIST: final String input = string(null); return input == null ? new List() : new ListDB(input); case DROP: switch(consume(CmdDrop.class, cmd)) { case DATABASE: case DB: return new DropDB(name(cmd)); case INDEX: return new DropIndex(consume(CmdIndex.class, cmd)); case USER: return new DropUser(name(cmd), key(ON, null) ? name(cmd) : null); case BACKUP: return new DropBackup(name(cmd)); case TRIGGER: return new DropTrigger(name(cmd)); } break; case OPTIMIZE: return new Optimize(); case EXPORT: return new Export(string(cmd)); case XQUERY: return new XQuery(xquery(cmd)); case RUN: return new Run(string(cmd)); case FIND: return new Find(string(cmd)); case CS: return new Cs(xquery(cmd)); case GET: return new Get(name(cmd)); case SET: return new Set(name(cmd), string(null)); case PASSWORD: return new Password(string(null)); case HELP: String hc = name(null); String form = null; if(hc != null) { if(hc.equalsIgnoreCase("wiki")) { form = hc; hc = null; } else { qp = qm; hc = consume(Cmd.class, cmd).toString(); form = name(null); } } return new Help(hc, form); case EXIT: case QUIT: return new Exit(); case KILL: return new Kill(name(cmd)); case BACKUP: return new Backup(name(cmd)); case RESTORE: return new Restore(name(cmd)); case SHOW: switch(consume(CmdShow.class, cmd)) { case DATABASES: return new ShowDatabases(); case SESSIONS: return new ShowSessions(); case USERS: return new ShowUsers(key(ON, null) ? name(cmd) : null); case BACKUPS: return new ShowBackups(); case TRIGGERS: return new ShowTriggers(); default: } break; case GRANT: final CmdPerm perm = consume(CmdPerm.class, cmd); if(perm == null) help(null, cmd); final String db = key(ON, null) ? name(cmd) : null; key(TO, cmd); return db == null ? new Grant(perm, name(cmd)) : new Grant(perm, name(cmd), db); default: } return null; }
diff --git a/geotools2/geotools-src/wmsserver/src/org/geotools/renderer/LegendImageGenerator.java b/geotools2/geotools-src/wmsserver/src/org/geotools/renderer/LegendImageGenerator.java index bc7410c12..2580d003b 100644 --- a/geotools2/geotools-src/wmsserver/src/org/geotools/renderer/LegendImageGenerator.java +++ b/geotools2/geotools-src/wmsserver/src/org/geotools/renderer/LegendImageGenerator.java @@ -1,418 +1,422 @@ /* * LegendImageGenerator.java * * Created on 18 June 2003, 12:00 */ package org.geotools.renderer; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.LineString; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Polygon; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import java.util.*; import java.util.logging.Logger; import org.geotools.feature.AttributeType; import org.geotools.feature.AttributeTypeFactory; import org.geotools.feature.Feature; import org.geotools.feature.FeatureFactory; import org.geotools.feature.FeatureType; import org.geotools.feature.FeatureTypeFactory; import org.geotools.feature.IllegalAttributeException; import org.geotools.feature.SchemaException; import org.geotools.filter.FilterFactory; import org.geotools.renderer.Java2DRenderer; import org.geotools.renderer.RenderedObject; import org.geotools.renderer.RenderedPoint; import org.geotools.renderer.Renderer; import org.geotools.styling.FeatureTypeStyle; import org.geotools.styling.Graphic; import org.geotools.styling.LineSymbolizer; import org.geotools.styling.PointSymbolizer; import org.geotools.styling.PolygonSymbolizer; import org.geotools.styling.Rule; import org.geotools.styling.Style; import org.geotools.styling.StyleFactory; import org.geotools.styling.Symbolizer; import org.geotools.styling.TextSymbolizer; /** * Based on a Style object return an Image of a legend for the style. * * @author iant */ public class LegendImageGenerator { private static final Logger LOGGER = Logger.getLogger( "org.geotools.wmsserver"); /** The style to use **/ Style[] styles; /** the current renderer object **/ Java2DRenderer renderer = new Java2DRenderer(); /** the width of the returned image **/ int width = 100; /** The hieght of the returned image **/ int height = 100; int hpadding = 3; int vpadding = 3; int symbolWidth = 20; int symbolHeight = 20; double scale = 1.0; static StyleFactory sFac= StyleFactory.createStyleFactory(); static FilterFactory filFac = FilterFactory.createFilterFactory(); GeometryFactory gFac = new GeometryFactory(); // FeatureFactory fFac,labelFac; FeatureType fFac,labelFac; /** Creates a new instance of LegendImageGenerator */ public LegendImageGenerator() { // FeatureType type = FeatureTypeFactory.newFeatureType(new FeatureType[] {(new AttributeTypeDefault("testGeometry",Geometry.class)},"legend"); // fFac = org.geotools.feature.FeatureFactoryFinder.getFeatureFactory(type); // AttributeTypeDefault[] attribs = { // new AttributeTypeDefault("geometry:text",Geometry.class), // new AttributeTypeDefault("label",String.class) // }; // try{ // FeatureType labeltype = new FeatureTypeFlat(attribs); // labelFac = org.geotools.feature.FeatureFactoryFinder.getFeatureFactory(labeltype); // }catch (SchemaException se){ // throw new RuntimeException(se); // } AttributeType[] attribs = { AttributeTypeFactory.newAttributeType("geometry:text",Geometry.class), AttributeTypeFactory.newAttributeType("label",String.class) }; try{ fFac = FeatureTypeFactory.newFeatureType( new AttributeType[] {AttributeTypeFactory.newAttributeType("testGeometry",Geometry.class)},"legend" ); labelFac = FeatureTypeFactory.newFeatureType(attribs,"attribs"); }catch (SchemaException se){ throw new RuntimeException(se); } } /** Creates a new instance of LegendImageGenerator */ public LegendImageGenerator(Style style, int width, int height) { this(); setStyles(new Style[]{style}); setWidth(width); setHeight(height); } public LegendImageGenerator(Style[] styles, int width, int height) { this(); setStyles(styles); setWidth(width); setHeight(height); } public BufferedImage getLegend(){ return getLegend(null); } public BufferedImage getLegend(Color background){ BufferedImage image = new BufferedImage(getWidth(),getHeight(),BufferedImage.TYPE_INT_RGB); Color fgcolor=Color.black; Graphics2D graphics = image.createGraphics(); LOGGER.fine("bgcolor "+background); if(!(background==null)){ graphics.setColor(background); graphics.fillRect(0,0, getWidth(),getHeight()); int red1 = Color.LIGHT_GRAY.getRed(); int blue1 = Color.LIGHT_GRAY.getBlue(); int green1 = Color.LIGHT_GRAY.getGreen(); int red2 = background.getRed(); int blue2 = background.getBlue(); int green2 = background.getGreen(); if(red2<red1||blue2<blue1||green2<green1){ fgcolor = Color.white; } } renderer.setScaleDenominator(getScale()); renderer.render(graphics, new java.awt.Rectangle(0,0,getWidth(),getHeight())); RenderedPoint rp=null; PointSymbolizer ps; Point p; Polygon poly; Feature feature=null, labelFeature=null; TextSymbolizer textSym = sFac.getDefaultTextSymbolizer(); textSym.getFonts()[0].setFontSize(filFac.createLiteralExpression(12.0)); String colorCode = "#" + Integer.toHexString(fgcolor.getRed()) + Integer.toHexString(fgcolor.getGreen()) + Integer.toHexString(fgcolor.getBlue()); textSym.setFill(sFac.createFill(filFac.createLiteralExpression(colorCode))); int offset = vpadding; int items=0; int hstep = (getWidth() - 2* hpadding)/2; Set rendered = new LinkedHashSet(); for(int s=0;s<styles.length;s++){ FeatureTypeStyle[] fts = styles[s].getFeatureTypeStyles(); for(int i=0;i<fts.length;i++){ Rule[] rules = fts[i].getRules(); for(int j=0;j<rules.length;j++){ String name = rules[j].getTitle(); if((name==null||name.equalsIgnoreCase("title"))&&rules[j].getFilter()!=null){ name = rules[j].getFilter().toString(); } + if(name.equalsIgnoreCase("title")){ + continue; + } Graphic[] g = rules[j].getLegendGraphic(); if(g != null && g.length>0){ //System.out.println("got a legend graphic"); for(int k=0;k<g.length;k++){ p = gFac.createPoint(new Coordinate(hpadding+symbolWidth/2,offset+symbolHeight/2)); Object[] attrib = {p}; try{ feature = fFac.create(attrib); }catch (IllegalAttributeException ife){ throw new RuntimeException(ife); } ps = sFac.createPointSymbolizer(); ps.setGraphic(g[k]); rp = new RenderedPoint(feature, ps); if(rp.isRenderable()) break; } - rp.render(graphics); + rendered.add(rp); +// rp.render(graphics); }else{ // no legend graphic provided Symbolizer[] syms = rules[j].getSymbolizers(); for(int k=0;k<syms.length;k++){ if (syms[k] instanceof PolygonSymbolizer) { //System.out.println("building polygon"); Coordinate[] c = new Coordinate[5]; c[0] = new Coordinate(hpadding, offset); c[1] = new Coordinate(hpadding+symbolWidth, offset); c[2] = new Coordinate(hpadding+symbolWidth, offset+symbolHeight); c[3] = new Coordinate(hpadding, offset+symbolHeight); c[4] = new Coordinate(hpadding, offset); com.vividsolutions.jts.geom.LinearRing r = null; try { r = gFac.createLinearRing(c); } catch (com.vividsolutions.jts.geom.TopologyException e) { System.err.println("Topology Exception in GMLBox"); return null; } poly = gFac.createPolygon(r, null); Object[] attrib = {poly}; try{ feature = fFac.create(attrib); }catch (IllegalAttributeException ife){ throw new RuntimeException(ife); } //System.out.println("feature = "+feature); } else if (syms[k] instanceof LineSymbolizer){ //System.out.println("building line"); Coordinate[] c = new Coordinate[5]; c[0] = new Coordinate(hpadding, offset); c[1] = new Coordinate(hpadding+symbolWidth*.3, offset+symbolHeight*.3); c[2] = new Coordinate(hpadding+symbolWidth*.3, offset+symbolHeight*.7); c[3] = new Coordinate(hpadding+symbolWidth*.7, offset+symbolHeight*.7); c[4] = new Coordinate(hpadding+symbolWidth, offset+symbolHeight); LineString line = gFac.createLineString(c); Object[] attrib = {line}; try{ feature = fFac.create(attrib); }catch (IllegalAttributeException ife){ throw new RuntimeException(ife); } //System.out.println("feature = "+feature); } else if(syms[k] instanceof PointSymbolizer){ //System.out.println("building point"); p = gFac.createPoint(new Coordinate(hpadding+symbolWidth/2,offset+symbolHeight/2)); Object[] attrib = {p}; try{ feature = fFac.create(attrib); }catch (IllegalAttributeException ife){ throw new RuntimeException(ife); } System.out.println("feature = "+feature); } } if(feature == null) continue; //System.out.println("feature "+feature); renderer.processSymbolizers(rendered,feature, syms); } if(name==null || name =="") name = "unknown"; p = gFac.createPoint(new Coordinate(2*hpadding+symbolWidth,offset+symbolHeight/2)); Object[] attrib = {p,name}; try{ labelFeature = labelFac.create(attrib); }catch (IllegalAttributeException ife){ throw new RuntimeException(ife); } textSym.setLabel(filFac.createLiteralExpression(name)); renderer.processSymbolizers(rendered,labelFeature,new Symbolizer[]{textSym}); offset += symbolHeight+vpadding; } } } Iterator it = rendered.iterator(); while (it.hasNext()) { RenderedObject r = (RenderedObject) it.next(); - System.out.println("DRAWING : " + r); +// System.out.println("DRAWING : " + r); r.render(graphics); } LOGGER.fine("Image = "+image); return image; } /** Getter for property style. * @return Value of property style. * */ public org.geotools.styling.Style[] getStyle() { return styles; } /** Setter for property style. * @param style New value of property style. * */ public void setStyles(org.geotools.styling.Style[] style) { this.styles = style; } /** Getter for property height. * @return Value of property height. * */ public int getHeight() { return height; } /** Setter for property height. * @param height New value of property height. * */ public void setHeight(int height) { this.height = height; } /** Getter for property width. * @return Value of property width. * */ public int getWidth() { return width; } /** Setter for property width. * @param width New value of property width. * */ public void setWidth(int width) { this.width = width; } /** Getter for property hpadding. * @return Value of property hpadding. * */ public int getHpadding() { return hpadding; } /** Setter for property hpadding. * @param hpadding New value of property hpadding. * */ public void setHpadding(int hpadding) { this.hpadding = hpadding; } /** Getter for property vpadding. * @return Value of property vpadding. * */ public int getVpadding() { return vpadding; } /** Setter for property vpadding. * @param vpadding New value of property vpadding. * */ public void setVpadding(int vpadding) { this.vpadding = vpadding; } /** Getter for property symbolWidth. * @return Value of property symbolWidth. * */ public int getSymbolWidth() { return symbolWidth; } /** Setter for property symbolWidth. * @param symbolWidth New value of property symbolWidth. * */ public void setSymbolWidth(int symbolWidth) { this.symbolWidth = symbolWidth; } /** Getter for property symbolHeight. * @return Value of property symbolHeight. * */ public int getSymbolHeight() { return symbolHeight; } /** Setter for property symbolHeight. * @param symbolHeight New value of property symbolHeight. * */ public void setSymbolHeight(int symbolHeight) { this.symbolHeight = symbolHeight; } /** Getter for property scale. * @return Value of property scale. * */ public double getScale() { return scale; } /** Setter for property scale. * @param scale New value of property scale. * */ public void setScale(double scale) { this.scale = scale; } }
false
true
public LegendImageGenerator() { // FeatureType type = FeatureTypeFactory.newFeatureType(new FeatureType[] {(new AttributeTypeDefault("testGeometry",Geometry.class)},"legend"); // fFac = org.geotools.feature.FeatureFactoryFinder.getFeatureFactory(type); // AttributeTypeDefault[] attribs = { // new AttributeTypeDefault("geometry:text",Geometry.class), // new AttributeTypeDefault("label",String.class) // }; // try{ // FeatureType labeltype = new FeatureTypeFlat(attribs); // labelFac = org.geotools.feature.FeatureFactoryFinder.getFeatureFactory(labeltype); // }catch (SchemaException se){ // throw new RuntimeException(se); // } AttributeType[] attribs = { AttributeTypeFactory.newAttributeType("geometry:text",Geometry.class), AttributeTypeFactory.newAttributeType("label",String.class) }; try{ fFac = FeatureTypeFactory.newFeatureType( new AttributeType[] {AttributeTypeFactory.newAttributeType("testGeometry",Geometry.class)},"legend" ); labelFac = FeatureTypeFactory.newFeatureType(attribs,"attribs"); }catch (SchemaException se){ throw new RuntimeException(se); } } /** Creates a new instance of LegendImageGenerator */ public LegendImageGenerator(Style style, int width, int height) { this(); setStyles(new Style[]{style}); setWidth(width); setHeight(height); } public LegendImageGenerator(Style[] styles, int width, int height) { this(); setStyles(styles); setWidth(width); setHeight(height); } public BufferedImage getLegend(){ return getLegend(null); } public BufferedImage getLegend(Color background){ BufferedImage image = new BufferedImage(getWidth(),getHeight(),BufferedImage.TYPE_INT_RGB); Color fgcolor=Color.black; Graphics2D graphics = image.createGraphics(); LOGGER.fine("bgcolor "+background); if(!(background==null)){ graphics.setColor(background); graphics.fillRect(0,0, getWidth(),getHeight()); int red1 = Color.LIGHT_GRAY.getRed(); int blue1 = Color.LIGHT_GRAY.getBlue(); int green1 = Color.LIGHT_GRAY.getGreen(); int red2 = background.getRed(); int blue2 = background.getBlue(); int green2 = background.getGreen(); if(red2<red1||blue2<blue1||green2<green1){ fgcolor = Color.white; } } renderer.setScaleDenominator(getScale()); renderer.render(graphics, new java.awt.Rectangle(0,0,getWidth(),getHeight())); RenderedPoint rp=null; PointSymbolizer ps; Point p; Polygon poly; Feature feature=null, labelFeature=null; TextSymbolizer textSym = sFac.getDefaultTextSymbolizer(); textSym.getFonts()[0].setFontSize(filFac.createLiteralExpression(12.0)); String colorCode = "#" + Integer.toHexString(fgcolor.getRed()) + Integer.toHexString(fgcolor.getGreen()) + Integer.toHexString(fgcolor.getBlue()); textSym.setFill(sFac.createFill(filFac.createLiteralExpression(colorCode))); int offset = vpadding; int items=0; int hstep = (getWidth() - 2* hpadding)/2; Set rendered = new LinkedHashSet(); for(int s=0;s<styles.length;s++){ FeatureTypeStyle[] fts = styles[s].getFeatureTypeStyles(); for(int i=0;i<fts.length;i++){ Rule[] rules = fts[i].getRules(); for(int j=0;j<rules.length;j++){ String name = rules[j].getTitle(); if((name==null||name.equalsIgnoreCase("title"))&&rules[j].getFilter()!=null){ name = rules[j].getFilter().toString(); } Graphic[] g = rules[j].getLegendGraphic(); if(g != null && g.length>0){ //System.out.println("got a legend graphic"); for(int k=0;k<g.length;k++){ p = gFac.createPoint(new Coordinate(hpadding+symbolWidth/2,offset+symbolHeight/2)); Object[] attrib = {p}; try{ feature = fFac.create(attrib); }catch (IllegalAttributeException ife){ throw new RuntimeException(ife); } ps = sFac.createPointSymbolizer(); ps.setGraphic(g[k]); rp = new RenderedPoint(feature, ps); if(rp.isRenderable()) break; } rp.render(graphics); }else{ // no legend graphic provided Symbolizer[] syms = rules[j].getSymbolizers(); for(int k=0;k<syms.length;k++){ if (syms[k] instanceof PolygonSymbolizer) { //System.out.println("building polygon"); Coordinate[] c = new Coordinate[5]; c[0] = new Coordinate(hpadding, offset); c[1] = new Coordinate(hpadding+symbolWidth, offset); c[2] = new Coordinate(hpadding+symbolWidth, offset+symbolHeight); c[3] = new Coordinate(hpadding, offset+symbolHeight); c[4] = new Coordinate(hpadding, offset); com.vividsolutions.jts.geom.LinearRing r = null; try { r = gFac.createLinearRing(c); } catch (com.vividsolutions.jts.geom.TopologyException e) { System.err.println("Topology Exception in GMLBox"); return null; } poly = gFac.createPolygon(r, null); Object[] attrib = {poly}; try{ feature = fFac.create(attrib); }catch (IllegalAttributeException ife){ throw new RuntimeException(ife); } //System.out.println("feature = "+feature); } else if (syms[k] instanceof LineSymbolizer){ //System.out.println("building line"); Coordinate[] c = new Coordinate[5]; c[0] = new Coordinate(hpadding, offset); c[1] = new Coordinate(hpadding+symbolWidth*.3, offset+symbolHeight*.3); c[2] = new Coordinate(hpadding+symbolWidth*.3, offset+symbolHeight*.7); c[3] = new Coordinate(hpadding+symbolWidth*.7, offset+symbolHeight*.7); c[4] = new Coordinate(hpadding+symbolWidth, offset+symbolHeight); LineString line = gFac.createLineString(c); Object[] attrib = {line}; try{ feature = fFac.create(attrib); }catch (IllegalAttributeException ife){ throw new RuntimeException(ife); } //System.out.println("feature = "+feature); } else if(syms[k] instanceof PointSymbolizer){ //System.out.println("building point"); p = gFac.createPoint(new Coordinate(hpadding+symbolWidth/2,offset+symbolHeight/2)); Object[] attrib = {p}; try{ feature = fFac.create(attrib); }catch (IllegalAttributeException ife){ throw new RuntimeException(ife); } System.out.println("feature = "+feature); } } if(feature == null) continue; //System.out.println("feature "+feature); renderer.processSymbolizers(rendered,feature, syms); } if(name==null || name =="") name = "unknown"; p = gFac.createPoint(new Coordinate(2*hpadding+symbolWidth,offset+symbolHeight/2)); Object[] attrib = {p,name}; try{ labelFeature = labelFac.create(attrib); }catch (IllegalAttributeException ife){ throw new RuntimeException(ife); } textSym.setLabel(filFac.createLiteralExpression(name)); renderer.processSymbolizers(rendered,labelFeature,new Symbolizer[]{textSym}); offset += symbolHeight+vpadding; } } } Iterator it = rendered.iterator(); while (it.hasNext()) { RenderedObject r = (RenderedObject) it.next(); System.out.println("DRAWING : " + r); r.render(graphics); } LOGGER.fine("Image = "+image); return image; } /** Getter for property style. * @return Value of property style. * */ public org.geotools.styling.Style[] getStyle() { return styles; } /** Setter for property style. * @param style New value of property style. * */ public void setStyles(org.geotools.styling.Style[] style) { this.styles = style; } /** Getter for property height. * @return Value of property height. * */ public int getHeight() { return height; } /** Setter for property height. * @param height New value of property height. * */ public void setHeight(int height) { this.height = height; } /** Getter for property width. * @return Value of property width. * */ public int getWidth() { return width; } /** Setter for property width. * @param width New value of property width. * */ public void setWidth(int width) { this.width = width; } /** Getter for property hpadding. * @return Value of property hpadding. * */ public int getHpadding() { return hpadding; } /** Setter for property hpadding. * @param hpadding New value of property hpadding. * */ public void setHpadding(int hpadding) { this.hpadding = hpadding; } /** Getter for property vpadding. * @return Value of property vpadding. * */ public int getVpadding() { return vpadding; } /** Setter for property vpadding. * @param vpadding New value of property vpadding. * */ public void setVpadding(int vpadding) { this.vpadding = vpadding; } /** Getter for property symbolWidth. * @return Value of property symbolWidth. * */ public int getSymbolWidth() { return symbolWidth; } /** Setter for property symbolWidth. * @param symbolWidth New value of property symbolWidth. * */ public void setSymbolWidth(int symbolWidth) { this.symbolWidth = symbolWidth; } /** Getter for property symbolHeight. * @return Value of property symbolHeight. * */ public int getSymbolHeight() { return symbolHeight; } /** Setter for property symbolHeight. * @param symbolHeight New value of property symbolHeight. * */ public void setSymbolHeight(int symbolHeight) { this.symbolHeight = symbolHeight; } /** Getter for property scale. * @return Value of property scale. * */ public double getScale() { return scale; } /** Setter for property scale. * @param scale New value of property scale. * */ public void setScale(double scale) { this.scale = scale; } }
public LegendImageGenerator() { // FeatureType type = FeatureTypeFactory.newFeatureType(new FeatureType[] {(new AttributeTypeDefault("testGeometry",Geometry.class)},"legend"); // fFac = org.geotools.feature.FeatureFactoryFinder.getFeatureFactory(type); // AttributeTypeDefault[] attribs = { // new AttributeTypeDefault("geometry:text",Geometry.class), // new AttributeTypeDefault("label",String.class) // }; // try{ // FeatureType labeltype = new FeatureTypeFlat(attribs); // labelFac = org.geotools.feature.FeatureFactoryFinder.getFeatureFactory(labeltype); // }catch (SchemaException se){ // throw new RuntimeException(se); // } AttributeType[] attribs = { AttributeTypeFactory.newAttributeType("geometry:text",Geometry.class), AttributeTypeFactory.newAttributeType("label",String.class) }; try{ fFac = FeatureTypeFactory.newFeatureType( new AttributeType[] {AttributeTypeFactory.newAttributeType("testGeometry",Geometry.class)},"legend" ); labelFac = FeatureTypeFactory.newFeatureType(attribs,"attribs"); }catch (SchemaException se){ throw new RuntimeException(se); } } /** Creates a new instance of LegendImageGenerator */ public LegendImageGenerator(Style style, int width, int height) { this(); setStyles(new Style[]{style}); setWidth(width); setHeight(height); } public LegendImageGenerator(Style[] styles, int width, int height) { this(); setStyles(styles); setWidth(width); setHeight(height); } public BufferedImage getLegend(){ return getLegend(null); } public BufferedImage getLegend(Color background){ BufferedImage image = new BufferedImage(getWidth(),getHeight(),BufferedImage.TYPE_INT_RGB); Color fgcolor=Color.black; Graphics2D graphics = image.createGraphics(); LOGGER.fine("bgcolor "+background); if(!(background==null)){ graphics.setColor(background); graphics.fillRect(0,0, getWidth(),getHeight()); int red1 = Color.LIGHT_GRAY.getRed(); int blue1 = Color.LIGHT_GRAY.getBlue(); int green1 = Color.LIGHT_GRAY.getGreen(); int red2 = background.getRed(); int blue2 = background.getBlue(); int green2 = background.getGreen(); if(red2<red1||blue2<blue1||green2<green1){ fgcolor = Color.white; } } renderer.setScaleDenominator(getScale()); renderer.render(graphics, new java.awt.Rectangle(0,0,getWidth(),getHeight())); RenderedPoint rp=null; PointSymbolizer ps; Point p; Polygon poly; Feature feature=null, labelFeature=null; TextSymbolizer textSym = sFac.getDefaultTextSymbolizer(); textSym.getFonts()[0].setFontSize(filFac.createLiteralExpression(12.0)); String colorCode = "#" + Integer.toHexString(fgcolor.getRed()) + Integer.toHexString(fgcolor.getGreen()) + Integer.toHexString(fgcolor.getBlue()); textSym.setFill(sFac.createFill(filFac.createLiteralExpression(colorCode))); int offset = vpadding; int items=0; int hstep = (getWidth() - 2* hpadding)/2; Set rendered = new LinkedHashSet(); for(int s=0;s<styles.length;s++){ FeatureTypeStyle[] fts = styles[s].getFeatureTypeStyles(); for(int i=0;i<fts.length;i++){ Rule[] rules = fts[i].getRules(); for(int j=0;j<rules.length;j++){ String name = rules[j].getTitle(); if((name==null||name.equalsIgnoreCase("title"))&&rules[j].getFilter()!=null){ name = rules[j].getFilter().toString(); } if(name.equalsIgnoreCase("title")){ continue; } Graphic[] g = rules[j].getLegendGraphic(); if(g != null && g.length>0){ //System.out.println("got a legend graphic"); for(int k=0;k<g.length;k++){ p = gFac.createPoint(new Coordinate(hpadding+symbolWidth/2,offset+symbolHeight/2)); Object[] attrib = {p}; try{ feature = fFac.create(attrib); }catch (IllegalAttributeException ife){ throw new RuntimeException(ife); } ps = sFac.createPointSymbolizer(); ps.setGraphic(g[k]); rp = new RenderedPoint(feature, ps); if(rp.isRenderable()) break; } rendered.add(rp); // rp.render(graphics); }else{ // no legend graphic provided Symbolizer[] syms = rules[j].getSymbolizers(); for(int k=0;k<syms.length;k++){ if (syms[k] instanceof PolygonSymbolizer) { //System.out.println("building polygon"); Coordinate[] c = new Coordinate[5]; c[0] = new Coordinate(hpadding, offset); c[1] = new Coordinate(hpadding+symbolWidth, offset); c[2] = new Coordinate(hpadding+symbolWidth, offset+symbolHeight); c[3] = new Coordinate(hpadding, offset+symbolHeight); c[4] = new Coordinate(hpadding, offset); com.vividsolutions.jts.geom.LinearRing r = null; try { r = gFac.createLinearRing(c); } catch (com.vividsolutions.jts.geom.TopologyException e) { System.err.println("Topology Exception in GMLBox"); return null; } poly = gFac.createPolygon(r, null); Object[] attrib = {poly}; try{ feature = fFac.create(attrib); }catch (IllegalAttributeException ife){ throw new RuntimeException(ife); } //System.out.println("feature = "+feature); } else if (syms[k] instanceof LineSymbolizer){ //System.out.println("building line"); Coordinate[] c = new Coordinate[5]; c[0] = new Coordinate(hpadding, offset); c[1] = new Coordinate(hpadding+symbolWidth*.3, offset+symbolHeight*.3); c[2] = new Coordinate(hpadding+symbolWidth*.3, offset+symbolHeight*.7); c[3] = new Coordinate(hpadding+symbolWidth*.7, offset+symbolHeight*.7); c[4] = new Coordinate(hpadding+symbolWidth, offset+symbolHeight); LineString line = gFac.createLineString(c); Object[] attrib = {line}; try{ feature = fFac.create(attrib); }catch (IllegalAttributeException ife){ throw new RuntimeException(ife); } //System.out.println("feature = "+feature); } else if(syms[k] instanceof PointSymbolizer){ //System.out.println("building point"); p = gFac.createPoint(new Coordinate(hpadding+symbolWidth/2,offset+symbolHeight/2)); Object[] attrib = {p}; try{ feature = fFac.create(attrib); }catch (IllegalAttributeException ife){ throw new RuntimeException(ife); } System.out.println("feature = "+feature); } } if(feature == null) continue; //System.out.println("feature "+feature); renderer.processSymbolizers(rendered,feature, syms); } if(name==null || name =="") name = "unknown"; p = gFac.createPoint(new Coordinate(2*hpadding+symbolWidth,offset+symbolHeight/2)); Object[] attrib = {p,name}; try{ labelFeature = labelFac.create(attrib); }catch (IllegalAttributeException ife){ throw new RuntimeException(ife); } textSym.setLabel(filFac.createLiteralExpression(name)); renderer.processSymbolizers(rendered,labelFeature,new Symbolizer[]{textSym}); offset += symbolHeight+vpadding; } } } Iterator it = rendered.iterator(); while (it.hasNext()) { RenderedObject r = (RenderedObject) it.next(); // System.out.println("DRAWING : " + r); r.render(graphics); } LOGGER.fine("Image = "+image); return image; } /** Getter for property style. * @return Value of property style. * */ public org.geotools.styling.Style[] getStyle() { return styles; } /** Setter for property style. * @param style New value of property style. * */ public void setStyles(org.geotools.styling.Style[] style) { this.styles = style; } /** Getter for property height. * @return Value of property height. * */ public int getHeight() { return height; } /** Setter for property height. * @param height New value of property height. * */ public void setHeight(int height) { this.height = height; } /** Getter for property width. * @return Value of property width. * */ public int getWidth() { return width; } /** Setter for property width. * @param width New value of property width. * */ public void setWidth(int width) { this.width = width; } /** Getter for property hpadding. * @return Value of property hpadding. * */ public int getHpadding() { return hpadding; } /** Setter for property hpadding. * @param hpadding New value of property hpadding. * */ public void setHpadding(int hpadding) { this.hpadding = hpadding; } /** Getter for property vpadding. * @return Value of property vpadding. * */ public int getVpadding() { return vpadding; } /** Setter for property vpadding. * @param vpadding New value of property vpadding. * */ public void setVpadding(int vpadding) { this.vpadding = vpadding; } /** Getter for property symbolWidth. * @return Value of property symbolWidth. * */ public int getSymbolWidth() { return symbolWidth; } /** Setter for property symbolWidth. * @param symbolWidth New value of property symbolWidth. * */ public void setSymbolWidth(int symbolWidth) { this.symbolWidth = symbolWidth; } /** Getter for property symbolHeight. * @return Value of property symbolHeight. * */ public int getSymbolHeight() { return symbolHeight; } /** Setter for property symbolHeight. * @param symbolHeight New value of property symbolHeight. * */ public void setSymbolHeight(int symbolHeight) { this.symbolHeight = symbolHeight; } /** Getter for property scale. * @return Value of property scale. * */ public double getScale() { return scale; } /** Setter for property scale. * @param scale New value of property scale. * */ public void setScale(double scale) { this.scale = scale; } }
diff --git a/src/org/commoncrawl/mapred/ec2/parser/EC2Launcher.java b/src/org/commoncrawl/mapred/ec2/parser/EC2Launcher.java index 5134fb2..5c83687 100644 --- a/src/org/commoncrawl/mapred/ec2/parser/EC2Launcher.java +++ b/src/org/commoncrawl/mapred/ec2/parser/EC2Launcher.java @@ -1,107 +1,107 @@ /** * Copyright 2012 - CommonCrawl Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * **/ package org.commoncrawl.mapred.ec2.parser; import java.io.File; import java.io.IOException; import java.io.InputStream; /** * EC2Launcher Task (spawned by EMR) * * @author rana * */ public class EC2Launcher { static class InputStreamHandler extends Thread { /** * Stream being read */ private InputStream m_stream; StringBuffer inBuffer = new StringBuffer(); /** * Constructor. * * @param */ InputStreamHandler(InputStream stream) { m_stream = stream; start(); } /** * Stream the data. */ public void run() { try { int nextChar; while ((nextChar = m_stream.read()) != -1) { inBuffer.append((char) nextChar); if (nextChar == '\n' || inBuffer.length() > 2048) { System.out.print(inBuffer.toString()); inBuffer = new StringBuffer(); } } } catch (IOException ioe) { } } } public static void main(String[] args) { System.out.println("Sleeping for 2 mins"); try { Thread.sleep(10000); } catch (InterruptedException e1) { } System.out.println("Done Sleeping"); ProcessBuilder pb = new ProcessBuilder( "./bin/ccAppRun.sh", "--consoleMode", "--heapSize", "4096", "--logdir", "/mnt/var/EC2TaskLogs", - "org.commoncrawl.crawl.database.crawlpipeline.ec2.parser.EC2ParserTask", + "org.commoncrawl.mapred.ec2.parser.EC2ParserTask", "start"); pb.directory(new File("/home/hadoop/ccprod")); try { System.out.println("Starting Job"); Process p = pb.start(); new InputStreamHandler (p.getErrorStream()); new InputStreamHandler (p.getInputStream()); System.out.println("Waiting for Job to Finish"); p.waitFor(); System.out.println("Job Finished"); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }
true
true
public static void main(String[] args) { System.out.println("Sleeping for 2 mins"); try { Thread.sleep(10000); } catch (InterruptedException e1) { } System.out.println("Done Sleeping"); ProcessBuilder pb = new ProcessBuilder( "./bin/ccAppRun.sh", "--consoleMode", "--heapSize", "4096", "--logdir", "/mnt/var/EC2TaskLogs", "org.commoncrawl.crawl.database.crawlpipeline.ec2.parser.EC2ParserTask", "start"); pb.directory(new File("/home/hadoop/ccprod")); try { System.out.println("Starting Job"); Process p = pb.start(); new InputStreamHandler (p.getErrorStream()); new InputStreamHandler (p.getInputStream()); System.out.println("Waiting for Job to Finish"); p.waitFor(); System.out.println("Job Finished"); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }
public static void main(String[] args) { System.out.println("Sleeping for 2 mins"); try { Thread.sleep(10000); } catch (InterruptedException e1) { } System.out.println("Done Sleeping"); ProcessBuilder pb = new ProcessBuilder( "./bin/ccAppRun.sh", "--consoleMode", "--heapSize", "4096", "--logdir", "/mnt/var/EC2TaskLogs", "org.commoncrawl.mapred.ec2.parser.EC2ParserTask", "start"); pb.directory(new File("/home/hadoop/ccprod")); try { System.out.println("Starting Job"); Process p = pb.start(); new InputStreamHandler (p.getErrorStream()); new InputStreamHandler (p.getInputStream()); System.out.println("Waiting for Job to Finish"); p.waitFor(); System.out.println("Job Finished"); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }
diff --git a/hazelcast-client/src/main/java/com/hazelcast/client/MapClientProxy.java b/hazelcast-client/src/main/java/com/hazelcast/client/MapClientProxy.java index 227b87baa9..84c27fee2c 100644 --- a/hazelcast-client/src/main/java/com/hazelcast/client/MapClientProxy.java +++ b/hazelcast-client/src/main/java/com/hazelcast/client/MapClientProxy.java @@ -1,437 +1,437 @@ /* * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.client; import com.hazelcast.client.impl.EntryListenerManager; import com.hazelcast.config.Config; import com.hazelcast.config.MapConfig; import com.hazelcast.config.NearCacheConfig; import com.hazelcast.core.*; import com.hazelcast.impl.CMap.CMapEntry; import com.hazelcast.impl.ClusterOperation; import com.hazelcast.impl.Keys; import com.hazelcast.impl.base.KeyValue; import com.hazelcast.impl.base.Pairs; import com.hazelcast.monitor.LocalMapStats; import com.hazelcast.query.Expression; import com.hazelcast.query.Predicate; import com.hazelcast.util.DistributedTimeoutException; import java.util.*; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static com.hazelcast.client.ProxyHelper.check; import static com.hazelcast.nio.IOUtil.toData; import static com.hazelcast.nio.IOUtil.toObject; public class MapClientProxy<K, V> implements IMap<K, V>, EntryHolder { final ProxyHelper proxyHelper; final private String name; final NearCache<K, V> nearCache; private static String PROP_CLIENT_NEAR_CACHE_CONFIG_ENABLED = "hazelcast.client.near.cache.enabled"; public MapClientProxy(HazelcastClient client, String name) { this.name = name; this.proxyHelper = new ProxyHelper(name, client); Config config = (Config) proxyHelper.doOp(ClusterOperation.GET_CONFIG, null, null); - MapConfig mapConfig = config.getMapConfig(name); + MapConfig mapConfig = config.getMapConfig(name.substring(Prefix.MAP.length())); NearCacheConfig ncc = mapConfig.getNearCacheConfig(); boolean nearCacheEnabled = "true".equalsIgnoreCase(System.getProperty(PROP_CLIENT_NEAR_CACHE_CONFIG_ENABLED, "false")); nearCache = (nearCacheEnabled && ncc != null) ? new GuavaNearCacheImpl<K, V>(ncc, this) : null; if (nearCache != null) { if (ncc.isInvalidateOnChange()) { addEntryListener(new EntryListener<K, V>() { public void entryAdded(EntryEvent<K, V> kvEntryEvent) { nearCache.invalidate(kvEntryEvent.getKey()); } public void entryRemoved(EntryEvent<K, V> kvEntryEvent) { nearCache.invalidate(kvEntryEvent.getKey()); } public void entryUpdated(EntryEvent<K, V> kvEntryEvent) { nearCache.invalidate(kvEntryEvent.getKey()); } public void entryEvicted(EntryEvent<K, V> kvEntryEvent) { nearCache.invalidate(kvEntryEvent.getKey()); } }, false); } } } public void addLocalEntryListener(EntryListener<K, V> listener) { throw new UnsupportedOperationException("client doesn't support local entry listener"); } public void addEntryListener(EntryListener<K, V> listener, boolean includeValue) { addEntryListener(listener, null, includeValue); } public void addEntryListener(EntryListener<K, V> listener, K key, boolean includeValue) { check(listener); Boolean noEntryListenerRegistered = listenerManager().noListenerRegistered(key, name, includeValue); if (noEntryListenerRegistered == null) { proxyHelper.doOp(ClusterOperation.REMOVE_LISTENER, key, null); noEntryListenerRegistered = Boolean.TRUE; } if (noEntryListenerRegistered) { Call c = listenerManager().createNewAddListenerCall(proxyHelper, key, includeValue); proxyHelper.doCall(c); } listenerManager().registerListener(name, key, includeValue, listener); } public void removeEntryListener(EntryListener<K, V> listener) { check(listener); proxyHelper.doOp(ClusterOperation.REMOVE_LISTENER, null, null); listenerManager().removeListener(name, null, listener); } public void removeEntryListener(EntryListener<K, V> listener, K key) { check(listener); check(key); proxyHelper.doOp(ClusterOperation.REMOVE_LISTENER, key, null); listenerManager().removeListener(name, key, listener); } private EntryListenerManager listenerManager() { return proxyHelper.getHazelcastClient().getListenerManager().getEntryListenerManager(); } public Set<java.util.Map.Entry<K, V>> entrySet(Predicate predicate) { final Collection collection = proxyHelper.entries(predicate); return new LightEntrySetSet<K, V>(collection, this, getInstanceType()); } public void flush() { proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_FLUSH, null, null); } public boolean evict(Object key) { ProxyHelper.check(key); return (Boolean) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_EVICT, key, null); } public MapEntry<K, V> getMapEntry(K key) { ProxyHelper.check(key); CMapEntry cMapEntry = (CMapEntry) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_GET_MAP_ENTRY, key, null); if (cMapEntry == null) { return null; } return new ClientMapEntry(cMapEntry, key, this); } public Set<K> keySet(Predicate predicate) { final Collection<K> collection = proxyHelper.keys(predicate); return new LightKeySet<K>(this, new HashSet<K>(collection)); } public boolean lockMap(long time, TimeUnit timeunit) { ProxyHelper.checkTime(time, timeunit); return (Boolean) doLock(ClusterOperation.CONCURRENT_MAP_LOCK_MAP, null, time, timeunit); } public void unlockMap() { doLock(ClusterOperation.CONCURRENT_MAP_UNLOCK_MAP, null, -1, null); } public void lock(K key) { ProxyHelper.check(key); doLock(ClusterOperation.CONCURRENT_MAP_LOCK, key, -1, null); } public boolean isLocked(K key) { return (Boolean) doLock(ClusterOperation.CONCURRENT_MAP_IS_KEY_LOCKED, key, -1, null); } public boolean tryLock(K key) { check(key); return (Boolean) doLock(ClusterOperation.CONCURRENT_MAP_LOCK, key, 0, null); } public V tryLockAndGet(K key, long timeout, TimeUnit timeunit) throws TimeoutException { check(key); Object result = proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_TRY_LOCK_AND_GET, key, null, timeout, timeunit); if (result instanceof DistributedTimeoutException) { throw new TimeoutException(); } return (V) result; } public void putAndUnlock(K key, V value) { check(key); check(value); proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_PUT_AND_UNLOCK, key, value); } public boolean tryLock(K key, long time, TimeUnit timeunit) { check(key); ProxyHelper.checkTime(time, timeunit); return (Boolean) doLock(ClusterOperation.CONCURRENT_MAP_LOCK, key, time, timeunit); } public void unlock(K key) { check(key); proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_UNLOCK, key, null); } public void forceUnlock(K key) { check(key); proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_FORCE_UNLOCK, key, null); } public Collection<V> values(Predicate predicate) { Set<Entry<K, V>> set = entrySet(predicate); return new ValueCollection<K, V>(this, set); } public V putIfAbsent(K key, V value, long ttl, TimeUnit timeunit) { check(key); check(value); return (V) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_PUT_IF_ABSENT, key, value, ttl, timeunit); } public V putIfAbsent(K key, V value) { return (V) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_PUT_IF_ABSENT, key, value); } public boolean remove(Object arg0, Object arg1) { check(arg0); check(arg1); return (Boolean) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_REMOVE_IF_SAME, arg0, arg1); } public V replace(K arg0, V arg1) { check(arg0); check(arg1); return (V) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_REPLACE_IF_NOT_NULL, arg0, arg1); } public boolean replace(K arg0, V arg1, V arg2) { check(arg0); check(arg1); check(arg2); Keys keys = new Keys(); keys.getKeys().add(toData(arg1)); keys.getKeys().add(toData(arg2)); return (Boolean) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_REPLACE_IF_SAME, arg0, keys); } public void clear() { Set keys = keySet(); for (Object key : keys) { remove(key); } } public boolean containsKey(Object arg0) { check(arg0); return (Boolean) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_CONTAINS_KEY, arg0, null); } public boolean containsValue(Object arg0) { check(arg0); return (Boolean) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_CONTAINS_VALUE, null, arg0); } public Set<java.util.Map.Entry<K, V>> entrySet() { return entrySet(null); } public V get(Object key) { if (nearCache != null) return nearCache.get((K) key); return get0(key); } protected V get0(Object key) { check(key); return (V) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_GET, (K) key, null); } public Map<K, V> getAll(Set<K> setKeys) { Keys keys = new Keys(); for (K key : setKeys) { keys.add(toData(key)); } Pairs pairs = (Pairs) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_GET_ALL, keys, null); List<KeyValue> lsKeyValues = pairs.getKeyValues(); Map map = new HashMap(); if (lsKeyValues != null) { for (KeyValue keyValue : lsKeyValues) { map.put(toObject(keyValue.getKeyData()), toObject(keyValue.getValueData())); } } return map; } public boolean isEmpty() { return size() == 0; } public Set<K> localKeySet() { throw new UnsupportedOperationException(); } public Set<K> localKeySet(Predicate predicate) { throw new UnsupportedOperationException(); } public LocalMapStats getLocalMapStats() { throw new UnsupportedOperationException(); } public Set<K> keySet() { return keySet(null); } public Future<V> getAsync(K key) { check(key); return proxyHelper.doAsync(ClusterOperation.CONCURRENT_MAP_GET, key, null); } public Future<V> putAsync(K key, V value) { check(key); check(value); return proxyHelper.doAsync(ClusterOperation.CONCURRENT_MAP_PUT, key, value); } public Future<V> removeAsync(K key) { check(key); return proxyHelper.doAsync(ClusterOperation.CONCURRENT_MAP_REMOVE, key, null); } public V put(K key, V value) { check(key); check(value); return (V) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_PUT, key, value); } public V put(K key, V value, long ttl, TimeUnit timeunit) { check(key); check(value); return (V) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_PUT, key, value, ttl, timeunit); } public void set(K key, V value) { check(key); check(value); proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_SET, key, value, -1, null); } public void set(K key, V value, long ttl, TimeUnit timeunit) { check(key); check(value); proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_SET, key, value, ttl, timeunit); } public void putTransient(K key, V value, long ttl, TimeUnit timeunit) { check(key); check(value); proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_PUT_TRANSIENT, key, value, ttl, timeunit); } public boolean tryPut(K key, V value, long timeout, TimeUnit timeunit) { check(key); check(value); return (Boolean) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_TRY_PUT, key, value, timeout, timeunit); } public void putAll(final Map<? extends K, ? extends V> map) { Pairs pairs = new Pairs(map.size()); for (final K key : map.keySet()) { final V value = map.get(key); pairs.addKeyValue(new KeyValue(toData(key), toData(value))); } proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_PUT_ALL, null, pairs); } public V remove(Object arg0) { check(arg0); return (V) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_REMOVE, arg0, null); } public Object tryRemove(K key, long timeout, TimeUnit timeunit) throws TimeoutException { check(key); Object result = proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_TRY_REMOVE, key, null, timeout, timeunit); if (result instanceof DistributedTimeoutException) { throw new TimeoutException(); } return result; } private Object doLock(ClusterOperation operation, Object key, long timeout, TimeUnit timeUnit) { Packet request = proxyHelper.prepareRequest(operation, key, timeUnit); request.setTimeout(timeout); Packet response = proxyHelper.callAndGetResult(request); return proxyHelper.getValue(response); } public int size() { return (Integer) proxyHelper.doOp(ClusterOperation.CONCURRENT_MAP_SIZE, null, null); } public Collection<V> values() { return values(null); } public Object getId() { return name; } public InstanceType getInstanceType() { return InstanceType.MAP; } public void addIndex(String attribute, boolean ordered) { proxyHelper.doOp(ClusterOperation.ADD_INDEX, attribute, ordered); } public void addIndex(Expression<?> expression, boolean ordered) { proxyHelper.doOp(ClusterOperation.ADD_INDEX, expression, ordered); } public String getName() { return name.substring(Prefix.MAP.length()); } public void destroy() { proxyHelper.destroy(); } @Override public boolean equals(Object o) { if (o instanceof IMap) { return getName().equals(((IMap) o).getName()); } return false; } @Override public int hashCode() { return getName().hashCode(); } public NearCache<K, V> getNearCache() { return nearCache; } }
true
true
public MapClientProxy(HazelcastClient client, String name) { this.name = name; this.proxyHelper = new ProxyHelper(name, client); Config config = (Config) proxyHelper.doOp(ClusterOperation.GET_CONFIG, null, null); MapConfig mapConfig = config.getMapConfig(name); NearCacheConfig ncc = mapConfig.getNearCacheConfig(); boolean nearCacheEnabled = "true".equalsIgnoreCase(System.getProperty(PROP_CLIENT_NEAR_CACHE_CONFIG_ENABLED, "false")); nearCache = (nearCacheEnabled && ncc != null) ? new GuavaNearCacheImpl<K, V>(ncc, this) : null; if (nearCache != null) { if (ncc.isInvalidateOnChange()) { addEntryListener(new EntryListener<K, V>() { public void entryAdded(EntryEvent<K, V> kvEntryEvent) { nearCache.invalidate(kvEntryEvent.getKey()); } public void entryRemoved(EntryEvent<K, V> kvEntryEvent) { nearCache.invalidate(kvEntryEvent.getKey()); } public void entryUpdated(EntryEvent<K, V> kvEntryEvent) { nearCache.invalidate(kvEntryEvent.getKey()); } public void entryEvicted(EntryEvent<K, V> kvEntryEvent) { nearCache.invalidate(kvEntryEvent.getKey()); } }, false); } } }
public MapClientProxy(HazelcastClient client, String name) { this.name = name; this.proxyHelper = new ProxyHelper(name, client); Config config = (Config) proxyHelper.doOp(ClusterOperation.GET_CONFIG, null, null); MapConfig mapConfig = config.getMapConfig(name.substring(Prefix.MAP.length())); NearCacheConfig ncc = mapConfig.getNearCacheConfig(); boolean nearCacheEnabled = "true".equalsIgnoreCase(System.getProperty(PROP_CLIENT_NEAR_CACHE_CONFIG_ENABLED, "false")); nearCache = (nearCacheEnabled && ncc != null) ? new GuavaNearCacheImpl<K, V>(ncc, this) : null; if (nearCache != null) { if (ncc.isInvalidateOnChange()) { addEntryListener(new EntryListener<K, V>() { public void entryAdded(EntryEvent<K, V> kvEntryEvent) { nearCache.invalidate(kvEntryEvent.getKey()); } public void entryRemoved(EntryEvent<K, V> kvEntryEvent) { nearCache.invalidate(kvEntryEvent.getKey()); } public void entryUpdated(EntryEvent<K, V> kvEntryEvent) { nearCache.invalidate(kvEntryEvent.getKey()); } public void entryEvicted(EntryEvent<K, V> kvEntryEvent) { nearCache.invalidate(kvEntryEvent.getKey()); } }, false); } } }
diff --git a/svnkit/src/org/tmatesoft/svn/core/internal/util/SVNSSLUtil.java b/svnkit/src/org/tmatesoft/svn/core/internal/util/SVNSSLUtil.java index 28f9eb3dd..d830f18a2 100644 --- a/svnkit/src/org/tmatesoft/svn/core/internal/util/SVNSSLUtil.java +++ b/svnkit/src/org/tmatesoft/svn/core/internal/util/SVNSSLUtil.java @@ -1,156 +1,157 @@ /* * ==================================================================== * Copyright (c) 2004-2009 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.util; import java.security.MessageDigest; import java.security.cert.CertificateException; import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; import java.util.Collection; import java.util.Date; import java.util.Iterator; /** * @version 1.0 * @author TMate Software Ltd. */ public class SVNSSLUtil { public static StringBuffer getServerCertificatePrompt(X509Certificate cert, String realm, String hostName) { int failures = getServerCertificateFailures(cert, hostName); StringBuffer prompt = new StringBuffer(); prompt.append("Error validating server certificate for '"); prompt.append(realm); prompt.append("':\n"); if ((failures & 8) != 0) { prompt.append(" - The certificate is not issued by a trusted authority. Use the\n" + " fingerprint to validate the certificate manually!\n"); } if ((failures & 4) != 0) { prompt.append(" - The certificate hostname does not match.\n"); } if ((failures & 2) != 0) { prompt.append(" - The certificate has expired.\n"); } if ((failures & 1) != 0) { prompt.append(" - The certificate is not yet valid.\n"); } getServerCertificateInfo(cert, prompt); return prompt; } private static String getFingerprint(X509Certificate cert) { try { return getFingerprint(cert.getEncoded()); } catch (Exception e) { } return null; } public static String getFingerprint(byte[] key) { StringBuffer s = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(key); byte[] digest = md.digest(); for (int i= 0; i < digest.length; i++) { if (i != 0) { s.append(':'); } int b = digest[i] & 0xFF; String hex = Integer.toHexString(b); if (hex.length() == 1) { s.append('0'); } s.append(hex.toLowerCase()); } } catch (Exception e) { } return s.toString(); } private static void getServerCertificateInfo(X509Certificate cert, StringBuffer info) { info.append("Certificate information:"); info.append('\n'); info.append(" - Subject: "); info.append(cert.getSubjectDN().getName()); info.append('\n'); info.append(" - Valid: "); info.append("from " + cert.getNotBefore() + " until " + cert.getNotAfter()); info.append('\n'); info.append(" - Issuer: "); info.append(cert.getIssuerDN().getName()); info.append('\n'); info.append(" - Fingerprint: "); info.append(getFingerprint(cert)); } public static int getServerCertificateFailures(X509Certificate cert, String realHostName) { int mask = 8; Date time = new Date(System.currentTimeMillis()); if (time.before(cert.getNotBefore())) { mask |= 1; } if (time.after(cert.getNotAfter())) { mask |= 2; } String certHostName = cert.getSubjectDN().getName(); - int index = certHostName.indexOf("CN=") + 3; + int index = certHostName.indexOf("CN="); if (index >= 0) { + index += 3; certHostName = certHostName.substring(index); if (certHostName.indexOf(' ') >= 0) { certHostName = certHostName.substring(0, certHostName.indexOf(' ')); } if (certHostName.indexOf(',') >= 0) { certHostName = certHostName.substring(0, certHostName.indexOf(',')); } } if (!realHostName.equals(certHostName)) { try { Collection altNames = cert.getSubjectAlternativeNames(); if(altNames != null) { for (Iterator names = altNames.iterator(); names.hasNext();) { Object nameList = names.next(); if (nameList instanceof Collection && ((Collection) nameList).size() >= 2) { Object[] name = ((Collection) nameList).toArray(); Object type = name[0]; Object host = name[1]; if (type instanceof Integer && host instanceof String) { if (((Integer) type).intValue() == 2 && host.equals(realHostName)) { return mask; } } } } } } catch (CertificateParsingException e) { } mask |= 4; } return mask; } public static class CertificateNotTrustedException extends CertificateException { private static final long serialVersionUID = 4845L; public CertificateNotTrustedException() { super(); } public CertificateNotTrustedException(String msg) { super(msg); } } }
false
true
public static int getServerCertificateFailures(X509Certificate cert, String realHostName) { int mask = 8; Date time = new Date(System.currentTimeMillis()); if (time.before(cert.getNotBefore())) { mask |= 1; } if (time.after(cert.getNotAfter())) { mask |= 2; } String certHostName = cert.getSubjectDN().getName(); int index = certHostName.indexOf("CN=") + 3; if (index >= 0) { certHostName = certHostName.substring(index); if (certHostName.indexOf(' ') >= 0) { certHostName = certHostName.substring(0, certHostName.indexOf(' ')); } if (certHostName.indexOf(',') >= 0) { certHostName = certHostName.substring(0, certHostName.indexOf(',')); } } if (!realHostName.equals(certHostName)) { try { Collection altNames = cert.getSubjectAlternativeNames(); if(altNames != null) { for (Iterator names = altNames.iterator(); names.hasNext();) { Object nameList = names.next(); if (nameList instanceof Collection && ((Collection) nameList).size() >= 2) { Object[] name = ((Collection) nameList).toArray(); Object type = name[0]; Object host = name[1]; if (type instanceof Integer && host instanceof String) { if (((Integer) type).intValue() == 2 && host.equals(realHostName)) { return mask; } } } } } } catch (CertificateParsingException e) { } mask |= 4; } return mask; }
public static int getServerCertificateFailures(X509Certificate cert, String realHostName) { int mask = 8; Date time = new Date(System.currentTimeMillis()); if (time.before(cert.getNotBefore())) { mask |= 1; } if (time.after(cert.getNotAfter())) { mask |= 2; } String certHostName = cert.getSubjectDN().getName(); int index = certHostName.indexOf("CN="); if (index >= 0) { index += 3; certHostName = certHostName.substring(index); if (certHostName.indexOf(' ') >= 0) { certHostName = certHostName.substring(0, certHostName.indexOf(' ')); } if (certHostName.indexOf(',') >= 0) { certHostName = certHostName.substring(0, certHostName.indexOf(',')); } } if (!realHostName.equals(certHostName)) { try { Collection altNames = cert.getSubjectAlternativeNames(); if(altNames != null) { for (Iterator names = altNames.iterator(); names.hasNext();) { Object nameList = names.next(); if (nameList instanceof Collection && ((Collection) nameList).size() >= 2) { Object[] name = ((Collection) nameList).toArray(); Object type = name[0]; Object host = name[1]; if (type instanceof Integer && host instanceof String) { if (((Integer) type).intValue() == 2 && host.equals(realHostName)) { return mask; } } } } } } catch (CertificateParsingException e) { } mask |= 4; } return mask; }
diff --git a/OsmAnd/src/net/osmand/plus/activities/LocalIndexHelper.java b/OsmAnd/src/net/osmand/plus/activities/LocalIndexHelper.java index b9e8cd5e..aecebb90 100644 --- a/OsmAnd/src/net/osmand/plus/activities/LocalIndexHelper.java +++ b/OsmAnd/src/net/osmand/plus/activities/LocalIndexHelper.java @@ -1,518 +1,520 @@ package net.osmand.plus.activities; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TreeSet; import net.osmand.GPXUtilities; import net.osmand.OsmAndFormatter; import net.osmand.GPXUtilities.GPXFileResult; import net.osmand.binary.BinaryIndexPart; import net.osmand.binary.BinaryMapIndexReader; import net.osmand.binary.BinaryMapAddressReaderAdapter.AddressRegion; import net.osmand.binary.BinaryMapIndexReader.MapIndex; import net.osmand.binary.BinaryMapIndexReader.MapRoot; import net.osmand.binary.BinaryMapTransportReaderAdapter.TransportIndex; import net.osmand.data.IndexConstants; import net.osmand.map.TileSourceManager; import net.osmand.map.TileSourceManager.TileSourceTemplate; import net.osmand.osm.MapUtils; import net.osmand.plus.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.ResourceManager; import net.osmand.plus.SQLiteTileSource; import net.osmand.plus.activities.LocalIndexesActivity.LoadLocalIndexTask; import net.osmand.plus.voice.MediaCommandPlayerImpl; import net.osmand.plus.voice.TTSCommandPlayerImpl; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.location.Location; import android.os.Build; public class LocalIndexHelper { private final OsmandApplication app; private MessageFormat dateformat = new MessageFormat("{0,date,dd.MM.yyyy}", Locale.US); public LocalIndexHelper(OsmandApplication app){ this.app = app; } public List<LocalIndexInfo> getAllLocalIndexData(LoadLocalIndexTask loadTask){ return getLocalIndexData(null, loadTask); } public String getInstalledDate(File f){ return app.getString(R.string.local_index_installed) + " : " + dateformat.format(new Object[]{new Date(f.lastModified())}); } public void updateDescription(LocalIndexInfo info){ File f = new File(info.getPathToData()); if(info.getType() == LocalIndexType.MAP_DATA){ updateObfFileInformation(info, f); info.setDescription(info.getDescription() + getInstalledDate(f)); } else if(info.getType() == LocalIndexType.POI_DATA){ info.setDescription(getInstalledDate(f)); } else if(info.getType() == LocalIndexType.GPX_DATA){ updateGpxInfo(info, f); } else if(info.getType() == LocalIndexType.VOICE_DATA){ info.setDescription(getInstalledDate(f)); } else if(info.getType() == LocalIndexType.TTS_VOICE_DATA){ info.setDescription(getInstalledDate(f)); } else if(info.getType() == LocalIndexType.TILES_DATA){ if(f.isDirectory() && TileSourceManager.isTileSourceMetaInfoExist(f)){ TileSourceTemplate template = TileSourceManager.createTileSourceTemplate(new File(info.getPathToData())); Set<Integer> zooms = new TreeSet<Integer>(); for(String s : f.list()){ try { zooms.add(Integer.parseInt(s)); } catch (NumberFormatException e) { } } String descr = app.getString(R.string.local_index_tile_data, template.getName(), template.getMinimumZoomSupported(), template.getMaximumZoomSupported(), template.getUrlTemplate() != null, zooms.toString()); info.setDescription(descr); } else if(f.isFile() && f.getName().endsWith(SQLiteTileSource.EXT)){ SQLiteTileSource template = new SQLiteTileSource(f, TileSourceManager.getKnownSourceTemplates()); // Set<Integer> zooms = new TreeSet<Integer>(); // for(int i=1; i<22; i++){ // if(template.exists(i)){ // zooms.add(i); // } // } String descr = app.getString(R.string.local_index_tile_data, template.getName(), template.getMinimumZoomSupported(), template.getMaximumZoomSupported(), template.couldBeDownloadedFromInternet(), ""); info.setDescription(descr); } } } private void updateGpxInfo(LocalIndexInfo info, File f) { if(info.getGpxFile() == null){ info.setGpxFile(GPXUtilities.loadGPXFile(app, f)); } GPXFileResult result = info.getGpxFile(); if(result.error != null){ info.setCorrupted(true); info.setDescription(result.error); } else { int totalDistance = 0; long startTime = Long.MAX_VALUE; long endTime = Long.MIN_VALUE; double diffElevationUp = 0; double diffElevationDown = 0; double totalElevation = 0; + double Elevation = 0; double minElevation = 99999; double maxElevation = 0; float maxSpeed = 0; int speedCount = 0; double totalSpeedSum = 0; int points = 0; for(int i = 0; i< result.locations.size() ; i++){ List<Location> subtrack = result.locations.get(i); points += subtrack.size(); int distance = 0; for (int j = 0; j < subtrack.size(); j++) { long time = subtrack.get(j).getTime(); if(time != 0){ startTime = Math.min(startTime, time); endTime = Math.max(startTime, time); } float speed = subtrack.get(j).getSpeed(); if(speed > 0){ totalSpeedSum += speed; maxSpeed = Math.max(speed, maxSpeed); speedCount ++; } - totalElevation += subtrack.get(j).getAltitude(); - minElevation = Math.min(totalElevation, minElevation); - maxElevation = Math.max(totalElevation, maxElevation); + Elevation = subtrack.get(j).getAltitude(); + totalElevation += Elevation; + minElevation = Math.min(Elevation, minElevation); + maxElevation = Math.max(Elevation, maxElevation); if (j > 0) { double diff = subtrack.get(j).getAltitude() - subtrack.get(j - 1).getAltitude(); if(diff > 0){ diffElevationUp += diff; } else { diffElevationDown -= diff; } distance += MapUtils.getDistance(subtrack.get(j - 1).getLatitude(), subtrack.get(j - 1).getLongitude(), subtrack .get(j).getLatitude(), subtrack.get(j).getLongitude()); } } totalDistance += distance; } if(startTime == Long.MAX_VALUE){ startTime = f.lastModified(); } if(endTime == Long.MIN_VALUE){ endTime = f.lastModified(); } info.setDescription(app.getString(R.string.local_index_gpx_info, result.locations.size(), points, result.wayPoints.size(), OsmAndFormatter.getFormattedDistance(totalDistance, app), startTime, endTime)); if(totalElevation != 0 || diffElevationUp != 0 || diffElevationDown != 0){ info.setDescription(info.getDescription() + app.getString(R.string.local_index_gpx_info_elevation, totalElevation / points, minElevation, maxElevation, diffElevationUp, diffElevationDown)); } if(speedCount > 0){ info.setDescription(info.getDescription() + app.getString(R.string.local_index_gpx_info_speed, OsmAndFormatter.getFormattedSpeed((float) (totalSpeedSum / speedCount), app), OsmAndFormatter.getFormattedSpeed(maxSpeed, app))); } info.setDescription(info.getDescription() + app.getString(R.string.local_index_gpx_info_show)); } } public List<LocalIndexInfo> getLocalIndexData(LocalIndexType type, LoadLocalIndexTask loadTask){ OsmandSettings settings = OsmandSettings.getOsmandSettings(app.getApplicationContext()); Map<String, String> loadedMaps = app.getResourceManager().getIndexFileNames(); List<LocalIndexInfo> result = new ArrayList<LocalIndexInfo>(); loadVoiceData(settings.extendOsmandPath(ResourceManager.VOICE_PATH), result, false, loadTask); loadObfData(settings.extendOsmandPath(ResourceManager.MAPS_PATH), result, false, loadTask, loadedMaps); loadPoiData(settings.extendOsmandPath(ResourceManager.POI_PATH), result, false, loadTask); loadGPXData(settings.extendOsmandPath(ResourceManager.GPX_PATH), result, false, loadTask); loadTilesData(settings.extendOsmandPath(ResourceManager.TILES_PATH), result, false, loadTask); loadVoiceData(settings.extendOsmandPath(ResourceManager.BACKUP_PATH), result, true, loadTask); loadObfData(settings.extendOsmandPath(ResourceManager.BACKUP_PATH), result, true, loadTask, loadedMaps); loadPoiData(settings.extendOsmandPath(ResourceManager.BACKUP_PATH), result, true, loadTask); loadGPXData(settings.extendOsmandPath(ResourceManager.BACKUP_PATH), result, true, loadTask); loadTilesData(settings.extendOsmandPath(ResourceManager.BACKUP_PATH), result, false, loadTask); return result; } private void loadVoiceData(File voiceDir, List<LocalIndexInfo> result, boolean backup, LoadLocalIndexTask loadTask) { if (voiceDir.canRead()) { for (File voiceF : voiceDir.listFiles()) { if (voiceF.isDirectory()) { LocalIndexInfo info = null; if (MediaCommandPlayerImpl.isMyData(voiceF)) { info = new LocalIndexInfo(LocalIndexType.VOICE_DATA, voiceF, backup); } else if (Integer.parseInt(Build.VERSION.SDK) >= 4) { if (TTSCommandPlayerImpl.isMyData(voiceF)) { info = new LocalIndexInfo(LocalIndexType.TTS_VOICE_DATA, voiceF, backup); } } if(info != null){ result.add(info); loadTask.loadFile(info); } } } } } private void loadTilesData(File tilesPath, List<LocalIndexInfo> result, boolean backup, LoadLocalIndexTask loadTask) { if (tilesPath.canRead()) { for (File tileFile : tilesPath.listFiles()) { if (tileFile.isFile() && tileFile.getName().endsWith(SQLiteTileSource.EXT)) { LocalIndexInfo info = new LocalIndexInfo(LocalIndexType.TILES_DATA, tileFile, backup); result.add(info); loadTask.loadFile(info); } else if (tileFile.isDirectory()) { LocalIndexInfo info = new LocalIndexInfo(LocalIndexType.TILES_DATA, tileFile, backup); if(!TileSourceManager.isTileSourceMetaInfoExist(tileFile)){ info.setCorrupted(true); } result.add(info); loadTask.loadFile(info); } } } } private void loadObfData(File mapPath, List<LocalIndexInfo> result, boolean backup, LoadLocalIndexTask loadTask, Map<String, String> loadedMaps) { if (mapPath.canRead()) { for (File mapFile : mapPath.listFiles()) { if (mapFile.isFile() && mapFile.getName().endsWith(IndexConstants.BINARY_MAP_INDEX_EXT)) { LocalIndexInfo info = new LocalIndexInfo(LocalIndexType.MAP_DATA, mapFile, backup); if(loadedMaps.containsKey(mapFile.getName()) && !backup){ info.setLoaded(true); } result.add(info); loadTask.loadFile(info); } } } } private void loadGPXData(File mapPath, List<LocalIndexInfo> result, boolean backup, LoadLocalIndexTask loadTask) { if (mapPath.canRead()) { for (File gpxFile : mapPath.listFiles()) { if (gpxFile.isFile() && gpxFile.getName().endsWith(".gpx")) { LocalIndexInfo info = new LocalIndexInfo(LocalIndexType.GPX_DATA, gpxFile, backup); result.add(info); loadTask.loadFile(info); } } } } private void loadPoiData(File mapPath, List<LocalIndexInfo> result, boolean backup, LoadLocalIndexTask loadTask) { if (mapPath.canRead()) { for (File poiFile : mapPath.listFiles()) { if (poiFile.isFile() && poiFile.getName().endsWith(IndexConstants.POI_INDEX_EXT)) { LocalIndexInfo info = new LocalIndexInfo(LocalIndexType.POI_DATA, poiFile, backup); if (!backup) { checkPoiFileVersion(info, poiFile); } result.add(info); loadTask.loadFile(info); } } } } private void checkPoiFileVersion(LocalIndexInfo info, File poiFile) { try { SQLiteDatabase db = SQLiteDatabase.openDatabase(poiFile.getPath(), null, SQLiteDatabase.OPEN_READONLY); int version = db.getVersion(); info.setNotSupported(version != IndexConstants.POI_TABLE_VERSION); db.close(); } catch(RuntimeException e){ info.setCorrupted(true); } } private MessageFormat format = new MessageFormat("\t {0}, {1} NE \n\t {2}, {3} NE", Locale.US); private String formatLatLonBox(int left, int right, int top, int bottom) { double l = MapUtils.get31LongitudeX(left); double r = MapUtils.get31LongitudeX(right); double t = MapUtils.get31LatitudeY(top); double b = MapUtils.get31LatitudeY(bottom); return format.format(new Object[] { l, t, r, b }); } private void updateObfFileInformation(LocalIndexInfo info, File mapFile) { try { RandomAccessFile mf = new RandomAccessFile(mapFile, "r"); BinaryMapIndexReader reader = new BinaryMapIndexReader(mf, false); info.setNotSupported(reader.getVersion() != IndexConstants.BINARY_MAP_VERSION); List<BinaryIndexPart> indexes = reader.getIndexes(); StringBuilder builder = new StringBuilder(); for(BinaryIndexPart part : indexes){ if(part instanceof MapIndex){ MapIndex mi = ((MapIndex) part); builder.append(app.getString(R.string.local_index_map_data)).append(": "). append(mi.getName()).append("\n"); if(mi.getRoots().size() > 0){ MapRoot mapRoot = mi.getRoots().get(0); String box = formatLatLonBox(mapRoot.getLeft(), mapRoot.getRight(), mapRoot.getTop(), mapRoot.getBottom()); builder.append(box).append("\n"); } } else if(part instanceof TransportIndex){ TransportIndex mi = ((TransportIndex) part); int sh = (31 - BinaryMapIndexReader.TRANSPORT_STOP_ZOOM); builder.append(app.getString(R.string.local_index_transport_data)).append(": "). append(mi.getName()).append("\n"); String box = formatLatLonBox(mi.getLeft() << sh, mi.getRight() << sh, mi.getTop() << sh, mi.getBottom() << sh); builder.append(box).append("\n"); } else if(part instanceof AddressRegion){ AddressRegion mi = ((AddressRegion) part); builder.append(app.getString(R.string.local_index_address_data)).append(": "). append(mi.getName()).append("\n"); } } info.setDescription(builder.toString()); reader.close(); } catch (IOException e) { info.setCorrupted(true); } } public enum LocalIndexType { VOICE_DATA(R.string.local_indexes_cat_voice), TTS_VOICE_DATA(R.string.local_indexes_cat_tts), TILES_DATA(R.string.local_indexes_cat_tile), GPX_DATA(R.string.local_indexes_cat_gpx), MAP_DATA(R.string.local_indexes_cat_map), POI_DATA(R.string.local_indexes_cat_poi); private final int resId; private LocalIndexType(int resId){ this.resId = resId; } public String getHumanString(Context ctx){ return ctx.getString(resId); } } public static class LocalIndexInfo { private LocalIndexType type; private String description = ""; private String name; private boolean backupedData; private boolean corrupted = false; private boolean notSupported = false; private boolean loaded; private String pathToData; private String fileName; private boolean singleFile; private int kbSize = -1; // UI state expanded private boolean expanded; private GPXFileResult gpxFile; public LocalIndexInfo(LocalIndexType type, File f, boolean backuped){ pathToData = f.getAbsolutePath(); fileName = f.getName(); name = formatName(f.getName()); this.type = type; singleFile = !f.isDirectory(); if(singleFile){ kbSize = (int) (f.length() >> 10); } this.backupedData = backuped; } private String formatName(String name) { int ext = name.indexOf('.'); if(ext != -1){ name = name.substring(0, ext); } return name.replace('_', ' '); } // Special domain object represents category public LocalIndexInfo(LocalIndexType type, boolean backup){ this.type = type; backupedData = backup; } public void setCorrupted(boolean corrupted) { this.corrupted = corrupted; if(corrupted){ this.loaded = false; } } public void setBackupedData(boolean backupedData) { this.backupedData = backupedData; } public void setSize(int size) { this.kbSize = size; } public void setGpxFile(GPXFileResult gpxFile) { this.gpxFile = gpxFile; } public GPXFileResult getGpxFile() { return gpxFile; } public boolean isExpanded() { return expanded; } public void setExpanded(boolean expanded) { this.expanded = expanded; } public void setDescription(String description) { this.description = description; } public void setLoaded(boolean loaded) { this.loaded = loaded; } public void setNotSupported(boolean notSupported) { this.notSupported = notSupported; if(notSupported){ this.loaded = false; } } public int getSize() { return kbSize; } public boolean isNotSupported() { return notSupported; } public String getName() { return name; } public LocalIndexType getType() { return type; } public boolean isSingleFile() { return singleFile; } public boolean isLoaded() { return loaded; } public boolean isCorrupted() { return corrupted; } public boolean isBackupedData() { return backupedData; } public String getPathToData() { return pathToData; } public String getDescription() { return description; } public String getFileName() { return fileName; } } }
false
true
private void updateGpxInfo(LocalIndexInfo info, File f) { if(info.getGpxFile() == null){ info.setGpxFile(GPXUtilities.loadGPXFile(app, f)); } GPXFileResult result = info.getGpxFile(); if(result.error != null){ info.setCorrupted(true); info.setDescription(result.error); } else { int totalDistance = 0; long startTime = Long.MAX_VALUE; long endTime = Long.MIN_VALUE; double diffElevationUp = 0; double diffElevationDown = 0; double totalElevation = 0; double minElevation = 99999; double maxElevation = 0; float maxSpeed = 0; int speedCount = 0; double totalSpeedSum = 0; int points = 0; for(int i = 0; i< result.locations.size() ; i++){ List<Location> subtrack = result.locations.get(i); points += subtrack.size(); int distance = 0; for (int j = 0; j < subtrack.size(); j++) { long time = subtrack.get(j).getTime(); if(time != 0){ startTime = Math.min(startTime, time); endTime = Math.max(startTime, time); } float speed = subtrack.get(j).getSpeed(); if(speed > 0){ totalSpeedSum += speed; maxSpeed = Math.max(speed, maxSpeed); speedCount ++; } totalElevation += subtrack.get(j).getAltitude(); minElevation = Math.min(totalElevation, minElevation); maxElevation = Math.max(totalElevation, maxElevation); if (j > 0) { double diff = subtrack.get(j).getAltitude() - subtrack.get(j - 1).getAltitude(); if(diff > 0){ diffElevationUp += diff; } else { diffElevationDown -= diff; } distance += MapUtils.getDistance(subtrack.get(j - 1).getLatitude(), subtrack.get(j - 1).getLongitude(), subtrack .get(j).getLatitude(), subtrack.get(j).getLongitude()); } } totalDistance += distance; } if(startTime == Long.MAX_VALUE){ startTime = f.lastModified(); } if(endTime == Long.MIN_VALUE){ endTime = f.lastModified(); } info.setDescription(app.getString(R.string.local_index_gpx_info, result.locations.size(), points, result.wayPoints.size(), OsmAndFormatter.getFormattedDistance(totalDistance, app), startTime, endTime)); if(totalElevation != 0 || diffElevationUp != 0 || diffElevationDown != 0){ info.setDescription(info.getDescription() + app.getString(R.string.local_index_gpx_info_elevation, totalElevation / points, minElevation, maxElevation, diffElevationUp, diffElevationDown)); } if(speedCount > 0){ info.setDescription(info.getDescription() + app.getString(R.string.local_index_gpx_info_speed, OsmAndFormatter.getFormattedSpeed((float) (totalSpeedSum / speedCount), app), OsmAndFormatter.getFormattedSpeed(maxSpeed, app))); } info.setDescription(info.getDescription() + app.getString(R.string.local_index_gpx_info_show)); } }
private void updateGpxInfo(LocalIndexInfo info, File f) { if(info.getGpxFile() == null){ info.setGpxFile(GPXUtilities.loadGPXFile(app, f)); } GPXFileResult result = info.getGpxFile(); if(result.error != null){ info.setCorrupted(true); info.setDescription(result.error); } else { int totalDistance = 0; long startTime = Long.MAX_VALUE; long endTime = Long.MIN_VALUE; double diffElevationUp = 0; double diffElevationDown = 0; double totalElevation = 0; double Elevation = 0; double minElevation = 99999; double maxElevation = 0; float maxSpeed = 0; int speedCount = 0; double totalSpeedSum = 0; int points = 0; for(int i = 0; i< result.locations.size() ; i++){ List<Location> subtrack = result.locations.get(i); points += subtrack.size(); int distance = 0; for (int j = 0; j < subtrack.size(); j++) { long time = subtrack.get(j).getTime(); if(time != 0){ startTime = Math.min(startTime, time); endTime = Math.max(startTime, time); } float speed = subtrack.get(j).getSpeed(); if(speed > 0){ totalSpeedSum += speed; maxSpeed = Math.max(speed, maxSpeed); speedCount ++; } Elevation = subtrack.get(j).getAltitude(); totalElevation += Elevation; minElevation = Math.min(Elevation, minElevation); maxElevation = Math.max(Elevation, maxElevation); if (j > 0) { double diff = subtrack.get(j).getAltitude() - subtrack.get(j - 1).getAltitude(); if(diff > 0){ diffElevationUp += diff; } else { diffElevationDown -= diff; } distance += MapUtils.getDistance(subtrack.get(j - 1).getLatitude(), subtrack.get(j - 1).getLongitude(), subtrack .get(j).getLatitude(), subtrack.get(j).getLongitude()); } } totalDistance += distance; } if(startTime == Long.MAX_VALUE){ startTime = f.lastModified(); } if(endTime == Long.MIN_VALUE){ endTime = f.lastModified(); } info.setDescription(app.getString(R.string.local_index_gpx_info, result.locations.size(), points, result.wayPoints.size(), OsmAndFormatter.getFormattedDistance(totalDistance, app), startTime, endTime)); if(totalElevation != 0 || diffElevationUp != 0 || diffElevationDown != 0){ info.setDescription(info.getDescription() + app.getString(R.string.local_index_gpx_info_elevation, totalElevation / points, minElevation, maxElevation, diffElevationUp, diffElevationDown)); } if(speedCount > 0){ info.setDescription(info.getDescription() + app.getString(R.string.local_index_gpx_info_speed, OsmAndFormatter.getFormattedSpeed((float) (totalSpeedSum / speedCount), app), OsmAndFormatter.getFormattedSpeed(maxSpeed, app))); } info.setDescription(info.getDescription() + app.getString(R.string.local_index_gpx_info_show)); } }
diff --git a/client/android/UrbanTag/src/com/ubikod/urbantag/UrbanTagApplication.java b/client/android/UrbanTag/src/com/ubikod/urbantag/UrbanTagApplication.java index a9ea01b..33f10b9 100644 --- a/client/android/UrbanTag/src/com/ubikod/urbantag/UrbanTagApplication.java +++ b/client/android/UrbanTag/src/com/ubikod/urbantag/UrbanTagApplication.java @@ -1,104 +1,104 @@ package com.ubikod.urbantag; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.util.Log; import com.ubikod.capptain.android.sdk.CapptainApplication; import com.ubikod.urbantag.model.DatabaseHelper; import com.ubikod.urbantag.model.Tag; import com.ubikod.urbantag.model.TagManager; public class UrbanTagApplication extends CapptainApplication { private static final String ACTION_FETCH_TAGS_LIST = "tag/get/all"; @Override protected void onApplicationProcessCreate() { Log.i(UrbanTag.TAG, "Launching App !"); NotificationHelper notifHelper = new NotificationHelper(this); notifHelper.notifyAppliRunning(); // re initiate wifi message display SharedPreferences pref = getApplicationContext().getSharedPreferences("URBAN_TAG_PREF", Context.MODE_PRIVATE); pref.edit().putBoolean("notifiedWifi", false).commit(); AsyncTask<Void, Void, List<Tag>> updateTagList = new AsyncTask<Void, Void, List<Tag>>() { @Override protected List<Tag> doInBackground(Void... v) { List<Tag> res = new ArrayList<Tag>(); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(UrbanTag.API_URL + ACTION_FETCH_TAGS_LIST); - Log.i(UrbanTag.TAG, "Fetching tags list on : " + request.toString()); + Log.i(UrbanTag.TAG, "Fetching tags list on : " + request.getURI().toString()); try { HttpResponse response = client.execute(request); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity() .getContent())); String textResponse = ""; String line = ""; while ((line = rd.readLine()) != null) { textResponse += line; } Log.i(UrbanTag.TAG, "Received :" + textResponse); JSONArray jsonTagsArray = new JSONArray(textResponse); for (int i = 0; i < jsonTagsArray.length(); i++) { Tag t = TagManager.createTag(jsonTagsArray.getJSONObject(i)); if (t != null) { res.add(t); } } } catch (ClientProtocolException cpe) { Log.e(UrbanTag.TAG, cpe.getMessage()); } catch (IOException ioe) { Log.e(UrbanTag.TAG, ioe.getMessage()); } catch (JSONException je) { Log.e(UrbanTag.TAG, je.getMessage()); } return res; } @Override protected void onPostExecute(List<Tag> list) { TagManager tagManager = new TagManager(new DatabaseHelper(getApplicationContext(), null)); if (list.size() > 0) tagManager.update(list); } }; updateTagList.execute(); } }
true
true
protected void onApplicationProcessCreate() { Log.i(UrbanTag.TAG, "Launching App !"); NotificationHelper notifHelper = new NotificationHelper(this); notifHelper.notifyAppliRunning(); // re initiate wifi message display SharedPreferences pref = getApplicationContext().getSharedPreferences("URBAN_TAG_PREF", Context.MODE_PRIVATE); pref.edit().putBoolean("notifiedWifi", false).commit(); AsyncTask<Void, Void, List<Tag>> updateTagList = new AsyncTask<Void, Void, List<Tag>>() { @Override protected List<Tag> doInBackground(Void... v) { List<Tag> res = new ArrayList<Tag>(); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(UrbanTag.API_URL + ACTION_FETCH_TAGS_LIST); Log.i(UrbanTag.TAG, "Fetching tags list on : " + request.toString()); try { HttpResponse response = client.execute(request); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity() .getContent())); String textResponse = ""; String line = ""; while ((line = rd.readLine()) != null) { textResponse += line; } Log.i(UrbanTag.TAG, "Received :" + textResponse); JSONArray jsonTagsArray = new JSONArray(textResponse); for (int i = 0; i < jsonTagsArray.length(); i++) { Tag t = TagManager.createTag(jsonTagsArray.getJSONObject(i)); if (t != null) { res.add(t); } } } catch (ClientProtocolException cpe) { Log.e(UrbanTag.TAG, cpe.getMessage()); } catch (IOException ioe) { Log.e(UrbanTag.TAG, ioe.getMessage()); } catch (JSONException je) { Log.e(UrbanTag.TAG, je.getMessage()); } return res; } @Override protected void onPostExecute(List<Tag> list) { TagManager tagManager = new TagManager(new DatabaseHelper(getApplicationContext(), null)); if (list.size() > 0) tagManager.update(list); } }; updateTagList.execute(); }
protected void onApplicationProcessCreate() { Log.i(UrbanTag.TAG, "Launching App !"); NotificationHelper notifHelper = new NotificationHelper(this); notifHelper.notifyAppliRunning(); // re initiate wifi message display SharedPreferences pref = getApplicationContext().getSharedPreferences("URBAN_TAG_PREF", Context.MODE_PRIVATE); pref.edit().putBoolean("notifiedWifi", false).commit(); AsyncTask<Void, Void, List<Tag>> updateTagList = new AsyncTask<Void, Void, List<Tag>>() { @Override protected List<Tag> doInBackground(Void... v) { List<Tag> res = new ArrayList<Tag>(); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(UrbanTag.API_URL + ACTION_FETCH_TAGS_LIST); Log.i(UrbanTag.TAG, "Fetching tags list on : " + request.getURI().toString()); try { HttpResponse response = client.execute(request); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity() .getContent())); String textResponse = ""; String line = ""; while ((line = rd.readLine()) != null) { textResponse += line; } Log.i(UrbanTag.TAG, "Received :" + textResponse); JSONArray jsonTagsArray = new JSONArray(textResponse); for (int i = 0; i < jsonTagsArray.length(); i++) { Tag t = TagManager.createTag(jsonTagsArray.getJSONObject(i)); if (t != null) { res.add(t); } } } catch (ClientProtocolException cpe) { Log.e(UrbanTag.TAG, cpe.getMessage()); } catch (IOException ioe) { Log.e(UrbanTag.TAG, ioe.getMessage()); } catch (JSONException je) { Log.e(UrbanTag.TAG, je.getMessage()); } return res; } @Override protected void onPostExecute(List<Tag> list) { TagManager tagManager = new TagManager(new DatabaseHelper(getApplicationContext(), null)); if (list.size() > 0) tagManager.update(list); } }; updateTagList.execute(); }
diff --git a/src/main/java/de/deepamehta/plugins/eduzen/migrations/Migration7.java b/src/main/java/de/deepamehta/plugins/eduzen/migrations/Migration7.java index 4ffed3a..d16c83f 100644 --- a/src/main/java/de/deepamehta/plugins/eduzen/migrations/Migration7.java +++ b/src/main/java/de/deepamehta/plugins/eduzen/migrations/Migration7.java @@ -1,174 +1,175 @@ package de.deepamehta.plugins.eduzen.migrations; import java.util.List; import java.util.logging.Logger; import de.deepamehta.core.Topic; import de.deepamehta.core.TopicType; import de.deepamehta.core.AssociationType; import de.deepamehta.core.RelatedTopic; import de.deepamehta.core.ResultSet; import de.deepamehta.core.model.CompositeValue; import de.deepamehta.core.model.AssociationDefinitionModel; import de.deepamehta.core.model.AssociationTypeModel; import de.deepamehta.core.model.AssociationModel; import de.deepamehta.core.model.TopicRoleModel; import de.deepamehta.core.model.TopicModel; import de.deepamehta.core.service.Migration; public class Migration7 extends Migration { private Logger logger = Logger.getLogger(getClass().getName()); private long WORKSPACE_ID = 9676; // -------------------------------------------------------------------------------------------------- Public Methods @Override public void run() { // set URI for default Workspace Topic defaultWorkspace = dms.getTopic(WORKSPACE_ID, false, null); defaultWorkspace.setUri("tub.eduzen.workspace_editors"); // create new "EduZEN"-Workspace for users dms.createTopic(new TopicModel("tub.eduzen.workspace_users", "dm4.workspaces.workspace", new CompositeValue().put("dm4.workspaces.name", "EduZEN Users")), null); // assign all eduzen topic types to "EduZEN Editors"-Workspace TopicType studyPathName = dms.getTopicType("tub.eduzen.studypath_name", null); assignWorkspace(studyPathName); TopicType moduleName = dms.getTopicType("tub.eduzen.module_name", null); assignWorkspace(moduleName); TopicType topicalareaName = dms.getTopicType("tub.eduzen.topicalarea_name", null); assignWorkspace(topicalareaName); TopicType topicalareaAlias = dms.getTopicType("tub.eduzen.topicalarea_alias", null); assignWorkspace(topicalareaAlias); TopicType courseName = dms.getTopicType("tub.eduzen.course_name", null); assignWorkspace(courseName); TopicType courseType = dms.getTopicType("tub.eduzen.course_type", null); assignWorkspace(courseType); TopicType lectureType = dms.getTopicType("tub.eduzen.lecture_type", null); assignWorkspace(lectureType); TopicType approachCorrectness = dms.getTopicType("tub.eduzen.approach_correctness", null); assignWorkspace(approachCorrectness); TopicType lecturePlace = dms.getTopicType("tub.eduzen.lecture_place", null); assignWorkspace(lecturePlace); TopicType resourceName = dms.getTopicType("tub.eduzen.resource_name", null); assignWorkspace(resourceName); TopicType resourceContent = dms.getTopicType("tub.eduzen.resource_content", null); assignWorkspace(resourceContent); TopicType excerciseObject = dms.getTopicType("tub.eduzen.excercise_object", null); assignWorkspace(excerciseObject); TopicType excerciseDifficulcy = dms.getTopicType("tub.eduzen.excercise_difficulcy", null); assignWorkspace(excerciseDifficulcy); TopicType timeframeNote = dms.getTopicType("tub.eduzen.timeframe_note", null); assignWorkspace(timeframeNote); TopicType timeframeStart = dms.getTopicType("tub.eduzen.timeframe_start", null); assignWorkspace(timeframeStart); TopicType timeframeEnd = dms.getTopicType("tub.eduzen.timeframe_end", null); assignWorkspace(timeframeEnd); TopicType practicesheetDue = dms.getTopicType("tub.eduzen.practicesheet_due", null); assignWorkspace(practicesheetDue); TopicType practicesheetName = dms.getTopicType("tub.eduzen.practicesheet_name", null); assignWorkspace(practicesheetName); TopicType practicesheetGiven = dms.getTopicType("tub.eduzen.practicesheet_given", null); assignWorkspace(practicesheetGiven); TopicType excerciseName = dms.getTopicType("tub.eduzen.excercise_name", null); assignWorkspace(excerciseName); TopicType excerciseFrozen = dms.getTopicType("tub.eduzen.excercise_frozen", null); assignWorkspace(excerciseFrozen); TopicType excerciseArchived = dms.getTopicType("tub.eduzen.excercise_archived", null); assignWorkspace(excerciseArchived); TopicType approachContent = dms.getTopicType("tub.eduzen.approach_content", null); assignWorkspace(approachContent); TopicType approachSample = dms.getTopicType("tub.eduzen.approach_sample", null); assignWorkspace(approachSample); TopicType commentCorrect = dms.getTopicType("tub.eduzen.comment_correct", null); assignWorkspace(commentCorrect); TopicType commentExplanation = dms.getTopicType("tub.eduzen.comment_explanation", null); assignWorkspace(commentExplanation); TopicType identity = dms.getTopicType("tub.eduzen.identity", null); assignWorkspace(identity); TopicType topicalarea = dms.getTopicType("tub.eduzen.topicalarea", null); assignWorkspace(topicalarea); TopicType lecture = dms.getTopicType("tub.eduzen.lecture", null); assignWorkspace(lecture); TopicType resource = dms.getTopicType("tub.eduzen.resource", null); assignWorkspace(resource); TopicType comment = dms.getTopicType("tub.eduzen.comment", null); assignWorkspace(comment); TopicType approach = dms.getTopicType("tub.eduzen.approach", null); assignWorkspace(approach); TopicType excerciseText = dms.getTopicType("tub.eduzen.excercise_text", null); assignWorkspace(excerciseText); TopicType excercise = dms.getTopicType("tub.eduzen.excercise", null); assignWorkspace(excercise); TopicType course = dms.getTopicType("tub.eduzen.course", null); assignWorkspace(course); TopicType module = dms.getTopicType("tub.eduzen.module", null); assignWorkspace(module); TopicType studypath = dms.getTopicType("tub.eduzen.studypath", null); assignWorkspace(studypath); TopicType practicesheet = dms.getTopicType("tub.eduzen.practicesheet", null); assignWorkspace(practicesheet); // assocTypes AssociationType contentItem = dms.getAssociationType("tub.eduzen.content_item", null); assignWorkspace(contentItem); AssociationType originItem = dms.getAssociationType("tub.eduzen.origin_item", null); assignWorkspace(originItem); AssociationType participant = dms.getAssociationType("tub.eduzen.participant", null); assignWorkspace(participant); AssociationType lecturer = dms.getAssociationType("tub.eduzen.lecturer", null); assignWorkspace(lecturer); AssociationType submitter = dms.getAssociationType("tub.eduzen.submitter", null); assignWorkspace(submitter); AssociationType author = dms.getAssociationType("tub.eduzen.author", null); assignWorkspace(author); AssociationType hint = dms.getAssociationType("tub.eduzen.hint", null); assignWorkspace(hint); AssociationType corrector = dms.getAssociationType("tub.eduzen.corrector", null); assignWorkspace(corrector); AssociationType requirement = dms.getAssociationType("tub.eduzen.requirement", null); assignWorkspace(requirement); AssociationType compatible = dms.getAssociationType("tub.eduzen.compatible", null); assignWorkspace(compatible); AssociationType identical = dms.getAssociationType("tub.eduzen.identical", null); assignWorkspace(identical); - // maybe we need to add, some dm4.types to the EduZEN Editors-Workspace too? + // maybe we need to add, some dm4.types to the EduZEN Editors-Workspace too? + // this was just tested with "Web Resource", admin can create and edit instances of such, postponing issue. - // create AggregationDefinition between "tub.eduzen.identity" and "dm4.accesscontrol.username" // fixme: cannot create new AssocDefModel via this call with a new ViewConfig (editable=false) // fixme: cannot be edited, does this new assoc also needs to be associated with a workspace, if so, how? identity.addAssocDef(new AssociationDefinitionModel("dm4.core.aggregation_def", "tub.eduzen.identity", "dm4.accesscontrol.username", "dm4.core.one", "dm4.core.one")); // create LV AssocType manually dms.createAssociationType(new AssociationTypeModel("tub.eduzen.lecture_content", "Lecture Content", "dm4.core.text"), null); + // assign new assoctype to workspace AssociationType lectureContent = dms.getAssociationType("tub.eduzen.lecture_content", null); - assignWorkspace(lectureContent); // as well as this new assoctype needs to be associated with a workspace? - lectureContent.getViewConfig().addSetting("dm4.webclient.view_config", "dm4.webclient.color", "#3e3edd"); + assignWorkspace(lectureContent); + lectureContent.getViewConfig().addSetting("dm4.webclient.view_config", "dm4.webclient.color", "#1072c8"); } // === Workspace === private void assignWorkspace(Topic topic) { if (hasWorkspace(topic)) { return; } dms.createAssociation(new AssociationModel("dm4.core.aggregation", new TopicRoleModel(topic.getId(), "dm4.core.whole"), new TopicRoleModel(WORKSPACE_ID, "dm4.core.part") ), null); } private boolean hasWorkspace(Topic topic) { return topic.getRelatedTopics("dm4.core.aggregation", "dm4.core.whole", "dm4.core.part", "dm4.workspaces.workspace", false, false, 0, null).getSize() > 0; } }
false
true
public void run() { // set URI for default Workspace Topic defaultWorkspace = dms.getTopic(WORKSPACE_ID, false, null); defaultWorkspace.setUri("tub.eduzen.workspace_editors"); // create new "EduZEN"-Workspace for users dms.createTopic(new TopicModel("tub.eduzen.workspace_users", "dm4.workspaces.workspace", new CompositeValue().put("dm4.workspaces.name", "EduZEN Users")), null); // assign all eduzen topic types to "EduZEN Editors"-Workspace TopicType studyPathName = dms.getTopicType("tub.eduzen.studypath_name", null); assignWorkspace(studyPathName); TopicType moduleName = dms.getTopicType("tub.eduzen.module_name", null); assignWorkspace(moduleName); TopicType topicalareaName = dms.getTopicType("tub.eduzen.topicalarea_name", null); assignWorkspace(topicalareaName); TopicType topicalareaAlias = dms.getTopicType("tub.eduzen.topicalarea_alias", null); assignWorkspace(topicalareaAlias); TopicType courseName = dms.getTopicType("tub.eduzen.course_name", null); assignWorkspace(courseName); TopicType courseType = dms.getTopicType("tub.eduzen.course_type", null); assignWorkspace(courseType); TopicType lectureType = dms.getTopicType("tub.eduzen.lecture_type", null); assignWorkspace(lectureType); TopicType approachCorrectness = dms.getTopicType("tub.eduzen.approach_correctness", null); assignWorkspace(approachCorrectness); TopicType lecturePlace = dms.getTopicType("tub.eduzen.lecture_place", null); assignWorkspace(lecturePlace); TopicType resourceName = dms.getTopicType("tub.eduzen.resource_name", null); assignWorkspace(resourceName); TopicType resourceContent = dms.getTopicType("tub.eduzen.resource_content", null); assignWorkspace(resourceContent); TopicType excerciseObject = dms.getTopicType("tub.eduzen.excercise_object", null); assignWorkspace(excerciseObject); TopicType excerciseDifficulcy = dms.getTopicType("tub.eduzen.excercise_difficulcy", null); assignWorkspace(excerciseDifficulcy); TopicType timeframeNote = dms.getTopicType("tub.eduzen.timeframe_note", null); assignWorkspace(timeframeNote); TopicType timeframeStart = dms.getTopicType("tub.eduzen.timeframe_start", null); assignWorkspace(timeframeStart); TopicType timeframeEnd = dms.getTopicType("tub.eduzen.timeframe_end", null); assignWorkspace(timeframeEnd); TopicType practicesheetDue = dms.getTopicType("tub.eduzen.practicesheet_due", null); assignWorkspace(practicesheetDue); TopicType practicesheetName = dms.getTopicType("tub.eduzen.practicesheet_name", null); assignWorkspace(practicesheetName); TopicType practicesheetGiven = dms.getTopicType("tub.eduzen.practicesheet_given", null); assignWorkspace(practicesheetGiven); TopicType excerciseName = dms.getTopicType("tub.eduzen.excercise_name", null); assignWorkspace(excerciseName); TopicType excerciseFrozen = dms.getTopicType("tub.eduzen.excercise_frozen", null); assignWorkspace(excerciseFrozen); TopicType excerciseArchived = dms.getTopicType("tub.eduzen.excercise_archived", null); assignWorkspace(excerciseArchived); TopicType approachContent = dms.getTopicType("tub.eduzen.approach_content", null); assignWorkspace(approachContent); TopicType approachSample = dms.getTopicType("tub.eduzen.approach_sample", null); assignWorkspace(approachSample); TopicType commentCorrect = dms.getTopicType("tub.eduzen.comment_correct", null); assignWorkspace(commentCorrect); TopicType commentExplanation = dms.getTopicType("tub.eduzen.comment_explanation", null); assignWorkspace(commentExplanation); TopicType identity = dms.getTopicType("tub.eduzen.identity", null); assignWorkspace(identity); TopicType topicalarea = dms.getTopicType("tub.eduzen.topicalarea", null); assignWorkspace(topicalarea); TopicType lecture = dms.getTopicType("tub.eduzen.lecture", null); assignWorkspace(lecture); TopicType resource = dms.getTopicType("tub.eduzen.resource", null); assignWorkspace(resource); TopicType comment = dms.getTopicType("tub.eduzen.comment", null); assignWorkspace(comment); TopicType approach = dms.getTopicType("tub.eduzen.approach", null); assignWorkspace(approach); TopicType excerciseText = dms.getTopicType("tub.eduzen.excercise_text", null); assignWorkspace(excerciseText); TopicType excercise = dms.getTopicType("tub.eduzen.excercise", null); assignWorkspace(excercise); TopicType course = dms.getTopicType("tub.eduzen.course", null); assignWorkspace(course); TopicType module = dms.getTopicType("tub.eduzen.module", null); assignWorkspace(module); TopicType studypath = dms.getTopicType("tub.eduzen.studypath", null); assignWorkspace(studypath); TopicType practicesheet = dms.getTopicType("tub.eduzen.practicesheet", null); assignWorkspace(practicesheet); // assocTypes AssociationType contentItem = dms.getAssociationType("tub.eduzen.content_item", null); assignWorkspace(contentItem); AssociationType originItem = dms.getAssociationType("tub.eduzen.origin_item", null); assignWorkspace(originItem); AssociationType participant = dms.getAssociationType("tub.eduzen.participant", null); assignWorkspace(participant); AssociationType lecturer = dms.getAssociationType("tub.eduzen.lecturer", null); assignWorkspace(lecturer); AssociationType submitter = dms.getAssociationType("tub.eduzen.submitter", null); assignWorkspace(submitter); AssociationType author = dms.getAssociationType("tub.eduzen.author", null); assignWorkspace(author); AssociationType hint = dms.getAssociationType("tub.eduzen.hint", null); assignWorkspace(hint); AssociationType corrector = dms.getAssociationType("tub.eduzen.corrector", null); assignWorkspace(corrector); AssociationType requirement = dms.getAssociationType("tub.eduzen.requirement", null); assignWorkspace(requirement); AssociationType compatible = dms.getAssociationType("tub.eduzen.compatible", null); assignWorkspace(compatible); AssociationType identical = dms.getAssociationType("tub.eduzen.identical", null); assignWorkspace(identical); // maybe we need to add, some dm4.types to the EduZEN Editors-Workspace too? // create AggregationDefinition between "tub.eduzen.identity" and "dm4.accesscontrol.username" // fixme: cannot create new AssocDefModel via this call with a new ViewConfig (editable=false) // fixme: cannot be edited, does this new assoc also needs to be associated with a workspace, if so, how? identity.addAssocDef(new AssociationDefinitionModel("dm4.core.aggregation_def", "tub.eduzen.identity", "dm4.accesscontrol.username", "dm4.core.one", "dm4.core.one")); // create LV AssocType manually dms.createAssociationType(new AssociationTypeModel("tub.eduzen.lecture_content", "Lecture Content", "dm4.core.text"), null); AssociationType lectureContent = dms.getAssociationType("tub.eduzen.lecture_content", null); assignWorkspace(lectureContent); // as well as this new assoctype needs to be associated with a workspace? lectureContent.getViewConfig().addSetting("dm4.webclient.view_config", "dm4.webclient.color", "#3e3edd"); }
public void run() { // set URI for default Workspace Topic defaultWorkspace = dms.getTopic(WORKSPACE_ID, false, null); defaultWorkspace.setUri("tub.eduzen.workspace_editors"); // create new "EduZEN"-Workspace for users dms.createTopic(new TopicModel("tub.eduzen.workspace_users", "dm4.workspaces.workspace", new CompositeValue().put("dm4.workspaces.name", "EduZEN Users")), null); // assign all eduzen topic types to "EduZEN Editors"-Workspace TopicType studyPathName = dms.getTopicType("tub.eduzen.studypath_name", null); assignWorkspace(studyPathName); TopicType moduleName = dms.getTopicType("tub.eduzen.module_name", null); assignWorkspace(moduleName); TopicType topicalareaName = dms.getTopicType("tub.eduzen.topicalarea_name", null); assignWorkspace(topicalareaName); TopicType topicalareaAlias = dms.getTopicType("tub.eduzen.topicalarea_alias", null); assignWorkspace(topicalareaAlias); TopicType courseName = dms.getTopicType("tub.eduzen.course_name", null); assignWorkspace(courseName); TopicType courseType = dms.getTopicType("tub.eduzen.course_type", null); assignWorkspace(courseType); TopicType lectureType = dms.getTopicType("tub.eduzen.lecture_type", null); assignWorkspace(lectureType); TopicType approachCorrectness = dms.getTopicType("tub.eduzen.approach_correctness", null); assignWorkspace(approachCorrectness); TopicType lecturePlace = dms.getTopicType("tub.eduzen.lecture_place", null); assignWorkspace(lecturePlace); TopicType resourceName = dms.getTopicType("tub.eduzen.resource_name", null); assignWorkspace(resourceName); TopicType resourceContent = dms.getTopicType("tub.eduzen.resource_content", null); assignWorkspace(resourceContent); TopicType excerciseObject = dms.getTopicType("tub.eduzen.excercise_object", null); assignWorkspace(excerciseObject); TopicType excerciseDifficulcy = dms.getTopicType("tub.eduzen.excercise_difficulcy", null); assignWorkspace(excerciseDifficulcy); TopicType timeframeNote = dms.getTopicType("tub.eduzen.timeframe_note", null); assignWorkspace(timeframeNote); TopicType timeframeStart = dms.getTopicType("tub.eduzen.timeframe_start", null); assignWorkspace(timeframeStart); TopicType timeframeEnd = dms.getTopicType("tub.eduzen.timeframe_end", null); assignWorkspace(timeframeEnd); TopicType practicesheetDue = dms.getTopicType("tub.eduzen.practicesheet_due", null); assignWorkspace(practicesheetDue); TopicType practicesheetName = dms.getTopicType("tub.eduzen.practicesheet_name", null); assignWorkspace(practicesheetName); TopicType practicesheetGiven = dms.getTopicType("tub.eduzen.practicesheet_given", null); assignWorkspace(practicesheetGiven); TopicType excerciseName = dms.getTopicType("tub.eduzen.excercise_name", null); assignWorkspace(excerciseName); TopicType excerciseFrozen = dms.getTopicType("tub.eduzen.excercise_frozen", null); assignWorkspace(excerciseFrozen); TopicType excerciseArchived = dms.getTopicType("tub.eduzen.excercise_archived", null); assignWorkspace(excerciseArchived); TopicType approachContent = dms.getTopicType("tub.eduzen.approach_content", null); assignWorkspace(approachContent); TopicType approachSample = dms.getTopicType("tub.eduzen.approach_sample", null); assignWorkspace(approachSample); TopicType commentCorrect = dms.getTopicType("tub.eduzen.comment_correct", null); assignWorkspace(commentCorrect); TopicType commentExplanation = dms.getTopicType("tub.eduzen.comment_explanation", null); assignWorkspace(commentExplanation); TopicType identity = dms.getTopicType("tub.eduzen.identity", null); assignWorkspace(identity); TopicType topicalarea = dms.getTopicType("tub.eduzen.topicalarea", null); assignWorkspace(topicalarea); TopicType lecture = dms.getTopicType("tub.eduzen.lecture", null); assignWorkspace(lecture); TopicType resource = dms.getTopicType("tub.eduzen.resource", null); assignWorkspace(resource); TopicType comment = dms.getTopicType("tub.eduzen.comment", null); assignWorkspace(comment); TopicType approach = dms.getTopicType("tub.eduzen.approach", null); assignWorkspace(approach); TopicType excerciseText = dms.getTopicType("tub.eduzen.excercise_text", null); assignWorkspace(excerciseText); TopicType excercise = dms.getTopicType("tub.eduzen.excercise", null); assignWorkspace(excercise); TopicType course = dms.getTopicType("tub.eduzen.course", null); assignWorkspace(course); TopicType module = dms.getTopicType("tub.eduzen.module", null); assignWorkspace(module); TopicType studypath = dms.getTopicType("tub.eduzen.studypath", null); assignWorkspace(studypath); TopicType practicesheet = dms.getTopicType("tub.eduzen.practicesheet", null); assignWorkspace(practicesheet); // assocTypes AssociationType contentItem = dms.getAssociationType("tub.eduzen.content_item", null); assignWorkspace(contentItem); AssociationType originItem = dms.getAssociationType("tub.eduzen.origin_item", null); assignWorkspace(originItem); AssociationType participant = dms.getAssociationType("tub.eduzen.participant", null); assignWorkspace(participant); AssociationType lecturer = dms.getAssociationType("tub.eduzen.lecturer", null); assignWorkspace(lecturer); AssociationType submitter = dms.getAssociationType("tub.eduzen.submitter", null); assignWorkspace(submitter); AssociationType author = dms.getAssociationType("tub.eduzen.author", null); assignWorkspace(author); AssociationType hint = dms.getAssociationType("tub.eduzen.hint", null); assignWorkspace(hint); AssociationType corrector = dms.getAssociationType("tub.eduzen.corrector", null); assignWorkspace(corrector); AssociationType requirement = dms.getAssociationType("tub.eduzen.requirement", null); assignWorkspace(requirement); AssociationType compatible = dms.getAssociationType("tub.eduzen.compatible", null); assignWorkspace(compatible); AssociationType identical = dms.getAssociationType("tub.eduzen.identical", null); assignWorkspace(identical); // maybe we need to add, some dm4.types to the EduZEN Editors-Workspace too? // this was just tested with "Web Resource", admin can create and edit instances of such, postponing issue. // fixme: cannot create new AssocDefModel via this call with a new ViewConfig (editable=false) // fixme: cannot be edited, does this new assoc also needs to be associated with a workspace, if so, how? identity.addAssocDef(new AssociationDefinitionModel("dm4.core.aggregation_def", "tub.eduzen.identity", "dm4.accesscontrol.username", "dm4.core.one", "dm4.core.one")); // create LV AssocType manually dms.createAssociationType(new AssociationTypeModel("tub.eduzen.lecture_content", "Lecture Content", "dm4.core.text"), null); // assign new assoctype to workspace AssociationType lectureContent = dms.getAssociationType("tub.eduzen.lecture_content", null); assignWorkspace(lectureContent); lectureContent.getViewConfig().addSetting("dm4.webclient.view_config", "dm4.webclient.color", "#1072c8"); }
diff --git a/src/main/java/com/dumptruckman/chunky/command/CommandChunkyClaim.java b/src/main/java/com/dumptruckman/chunky/command/CommandChunkyClaim.java index 6754feb..9d704e4 100644 --- a/src/main/java/com/dumptruckman/chunky/command/CommandChunkyClaim.java +++ b/src/main/java/com/dumptruckman/chunky/command/CommandChunkyClaim.java @@ -1,59 +1,61 @@ package com.dumptruckman.chunky.command; import com.dumptruckman.chunky.ChunkyManager; import com.dumptruckman.chunky.config.Config; import com.dumptruckman.chunky.locale.Language; import com.dumptruckman.chunky.module.ChunkyCommand; import com.dumptruckman.chunky.module.ChunkyCommandExecutor; import com.dumptruckman.chunky.object.ChunkyChunk; import com.dumptruckman.chunky.object.ChunkyPlayer; import com.dumptruckman.chunky.permission.bukkit.Permissions; import com.dumptruckman.chunky.util.Logging; import org.bukkit.Location; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.Map; /** * @author dumptruckman */ public class CommandChunkyClaim implements ChunkyCommandExecutor { public void onCommand(CommandSender sender, ChunkyCommand command, String label, String[] args) { if (!(sender instanceof Player)) { Language.IN_GAME_ONLY.bad(sender); return; } Player player = (Player)sender; if (Permissions.CHUNKY_CLAIM.hasPerm(player)) { // Grab the chunk claim limit for the player int chunkLimit = Config.getPlayerChunkLimitDefault(); for (Map.Entry<String,Integer> limit : Config.getCustomPlayerChunkLimits().entrySet()) { if (Permissions.hasPerm(player, Permissions.PLAYER_CHUNK_LIMIT.getNode() + "." + limit.getKey())) { chunkLimit = limit.getValue(); break; } } ChunkyPlayer chunkyPlayer = ChunkyManager.getChunkyPlayer(player.getName()); - if (Permissions.PLAYER_NO_CHUNK_LIMIT.hasPerm(player) || chunkyPlayer.getOwnables().get(ChunkyChunk.class.getName().hashCode()).size() < chunkLimit) { + if (Permissions.PLAYER_NO_CHUNK_LIMIT.hasPerm(player) || + (chunkyPlayer.getOwnables().containsKey(ChunkyChunk.class.getName().hashCode()) && + chunkyPlayer.getOwnables().get(ChunkyChunk.class.getName().hashCode()).size() < chunkLimit)) { ChunkyChunk chunkyChunk; Location location = player.getLocation(); chunkyChunk = ChunkyManager.getChunk(location); if (chunkyChunk.isOwned()) { Language.CHUNK_OWNED.bad(player, chunkyChunk.getOwner().getName()); return; } chunkyChunk.setOwner(chunkyPlayer, true); chunkyChunk.setName("~" + chunkyPlayer.getName()); Logging.debug(chunkyPlayer.getName() + " claimed " + chunkyChunk.getCoord().getX() + ":" + chunkyChunk.getCoord().getZ()); Language.CHUNK_CLAIMED.good(player, chunkyChunk.getCoord().getX(), chunkyChunk.getCoord().getZ()); } else { Language.CHUNK_LIMIT_REACHED.bad(player, chunkLimit); } } else { Language.NO_COMMAND_PERMISSION.bad(player); } } }
true
true
public void onCommand(CommandSender sender, ChunkyCommand command, String label, String[] args) { if (!(sender instanceof Player)) { Language.IN_GAME_ONLY.bad(sender); return; } Player player = (Player)sender; if (Permissions.CHUNKY_CLAIM.hasPerm(player)) { // Grab the chunk claim limit for the player int chunkLimit = Config.getPlayerChunkLimitDefault(); for (Map.Entry<String,Integer> limit : Config.getCustomPlayerChunkLimits().entrySet()) { if (Permissions.hasPerm(player, Permissions.PLAYER_CHUNK_LIMIT.getNode() + "." + limit.getKey())) { chunkLimit = limit.getValue(); break; } } ChunkyPlayer chunkyPlayer = ChunkyManager.getChunkyPlayer(player.getName()); if (Permissions.PLAYER_NO_CHUNK_LIMIT.hasPerm(player) || chunkyPlayer.getOwnables().get(ChunkyChunk.class.getName().hashCode()).size() < chunkLimit) { ChunkyChunk chunkyChunk; Location location = player.getLocation(); chunkyChunk = ChunkyManager.getChunk(location); if (chunkyChunk.isOwned()) { Language.CHUNK_OWNED.bad(player, chunkyChunk.getOwner().getName()); return; } chunkyChunk.setOwner(chunkyPlayer, true); chunkyChunk.setName("~" + chunkyPlayer.getName()); Logging.debug(chunkyPlayer.getName() + " claimed " + chunkyChunk.getCoord().getX() + ":" + chunkyChunk.getCoord().getZ()); Language.CHUNK_CLAIMED.good(player, chunkyChunk.getCoord().getX(), chunkyChunk.getCoord().getZ()); } else { Language.CHUNK_LIMIT_REACHED.bad(player, chunkLimit); } } else { Language.NO_COMMAND_PERMISSION.bad(player); } }
public void onCommand(CommandSender sender, ChunkyCommand command, String label, String[] args) { if (!(sender instanceof Player)) { Language.IN_GAME_ONLY.bad(sender); return; } Player player = (Player)sender; if (Permissions.CHUNKY_CLAIM.hasPerm(player)) { // Grab the chunk claim limit for the player int chunkLimit = Config.getPlayerChunkLimitDefault(); for (Map.Entry<String,Integer> limit : Config.getCustomPlayerChunkLimits().entrySet()) { if (Permissions.hasPerm(player, Permissions.PLAYER_CHUNK_LIMIT.getNode() + "." + limit.getKey())) { chunkLimit = limit.getValue(); break; } } ChunkyPlayer chunkyPlayer = ChunkyManager.getChunkyPlayer(player.getName()); if (Permissions.PLAYER_NO_CHUNK_LIMIT.hasPerm(player) || (chunkyPlayer.getOwnables().containsKey(ChunkyChunk.class.getName().hashCode()) && chunkyPlayer.getOwnables().get(ChunkyChunk.class.getName().hashCode()).size() < chunkLimit)) { ChunkyChunk chunkyChunk; Location location = player.getLocation(); chunkyChunk = ChunkyManager.getChunk(location); if (chunkyChunk.isOwned()) { Language.CHUNK_OWNED.bad(player, chunkyChunk.getOwner().getName()); return; } chunkyChunk.setOwner(chunkyPlayer, true); chunkyChunk.setName("~" + chunkyPlayer.getName()); Logging.debug(chunkyPlayer.getName() + " claimed " + chunkyChunk.getCoord().getX() + ":" + chunkyChunk.getCoord().getZ()); Language.CHUNK_CLAIMED.good(player, chunkyChunk.getCoord().getX(), chunkyChunk.getCoord().getZ()); } else { Language.CHUNK_LIMIT_REACHED.bad(player, chunkLimit); } } else { Language.NO_COMMAND_PERMISSION.bad(player); } }
diff --git a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/tta/TTABackendImpl.java b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/tta/TTABackendImpl.java index c968b17d7..80edf25ce 100644 --- a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/tta/TTABackendImpl.java +++ b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/tta/TTABackendImpl.java @@ -1,360 +1,362 @@ /* * Copyright (c) 2011, IRISA * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the IETR/INSA of Rennes nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package net.sf.orcc.backends.tta; import static net.sf.orcc.OrccActivator.getDefault; import static net.sf.orcc.OrccLaunchConstants.DEBUG_MODE; import static net.sf.orcc.OrccLaunchConstants.FIFO_SIZE; import static net.sf.orcc.preferences.PreferenceConstants.P_TTA_LIB; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.dftools.graph.Edge; import net.sf.orcc.OrccException; import net.sf.orcc.backends.AbstractBackend; import net.sf.orcc.backends.CustomPrinter; import net.sf.orcc.backends.StandardPrinter; import net.sf.orcc.backends.llvm.LLVMExpressionPrinter; import net.sf.orcc.backends.llvm.LLVMTypePrinter; import net.sf.orcc.backends.llvm.transformations.BoolToIntTransformation; import net.sf.orcc.backends.llvm.transformations.GetElementPtrAdder; import net.sf.orcc.backends.llvm.transformations.StringTransformation; import net.sf.orcc.backends.transformations.CastAdder; import net.sf.orcc.backends.transformations.EmptyNodeRemover; import net.sf.orcc.backends.transformations.InstPhiTransformation; import net.sf.orcc.backends.transformations.TypeResizer; import net.sf.orcc.backends.transformations.UnitImporter; import net.sf.orcc.backends.transformations.ssa.ConstantPropagator; import net.sf.orcc.backends.transformations.ssa.CopyPropagator; import net.sf.orcc.backends.tta.architecture.ArchitectureFactory; import net.sf.orcc.backends.tta.architecture.Processor; import net.sf.orcc.backends.tta.architecture.util.ArchitectureMemoryStats; import net.sf.orcc.backends.tta.transformations.BroadcastTypeResizer; import net.sf.orcc.df.Actor; import net.sf.orcc.df.DfFactory; import net.sf.orcc.df.Entity; import net.sf.orcc.df.Instance; import net.sf.orcc.df.Network; import net.sf.orcc.df.transformations.BroadcastAdder; import net.sf.orcc.df.transformations.Instantiator; import net.sf.orcc.df.transformations.NetworkFlattener; import net.sf.orcc.df.util.DfSwitch; import net.sf.orcc.ir.transformations.BlockCombine; import net.sf.orcc.ir.transformations.BuildCFG; import net.sf.orcc.ir.transformations.RenameTransformation; import net.sf.orcc.ir.transformations.SSATransformation; import net.sf.orcc.ir.transformations.TacTransformation; import net.sf.orcc.util.OrccUtil; import org.eclipse.core.resources.IFile; import org.eclipse.emf.common.util.BasicEList; /** * TTA back-end. * * @author Herve Yviquel * */ public class TTABackendImpl extends AbstractBackend { /** * Backend options */ private boolean debug; private boolean finalize; private String fpgaBrand; private String fpgaFamily; private boolean targetAltera; private String libPath; private int fifoWidthu; private final Map<String, String> transformations; private final List<String> processorIntensiveActors; /** * Creates a new instance of the TTA back-end. Initializes the * transformation hash map. */ public TTABackendImpl() { transformations = new HashMap<String, String>(); transformations.put("abs", "abs_"); transformations.put("getw", "getw_"); transformations.put("index", "index_"); transformations.put("min", "min_"); transformations.put("max", "max_"); transformations.put("select", "select_"); processorIntensiveActors = new ArrayList<String>(); // processorIntensiveActors.add("fi.oulu.ee.mvg.Mgnt_Address"); // processorIntensiveActors.add("com.xilinx.Add"); // processorIntensiveActors.add("org.mpeg4.part2.motion.Algo_Interpolation_halfpel"); // processorIntensiveActors.add("org.sc29.wg11.mpeg4.part2.texture.Algo_IDCT2D_ISOIEC_23002_1"); // processorIntensiveActors.add("fi.oulu.ee.mvg.Algo_IAP"); processorIntensiveActors.add("fi.oulu.ee.mvg.Framebuffer"); } @Override public void doInitializeOptions() { debug = getAttribute(DEBUG_MODE, true); finalize = getAttribute("net.sf.orcc.backends.tta.finalizeGeneration", false); libPath = getDefault().getPreference(P_TTA_LIB, ""); fpgaBrand = getAttribute("net.sf.orcc.backends.tta.fpgaBrand", "Altera"); fpgaFamily = getAttribute("net.sf.orcc.backends.tta.fpgaFamily", "Stratix III"); targetAltera = fpgaBrand.equals("Altera"); // Set default FIFO size to 256 fifoSize = getAttribute(FIFO_SIZE, 256); fifoWidthu = (int) Math.ceil(Math.log(fifoSize) / Math.log(2)); } @Override protected void doTransformActor(Actor actor) throws OrccException { DfSwitch<?>[] transformations = { new UnitImporter(), new SSATransformation(), new BoolToIntTransformation(), new TypeResizer(true, true, false, true), new StringTransformation(), new RenameTransformation(this.transformations), new TacTransformation(), new CopyPropagator(), new ConstantPropagator(), new InstPhiTransformation(), new GetElementPtrAdder(), new CastAdder(false), new EmptyNodeRemover(), new BlockCombine(), new BuildCFG() }; for (DfSwitch<?> transformation : transformations) { transformation.doSwitch(actor); } actor.setTemplateData(new TTAActorTemplateData(actor)); } private Network doTransformNetwork(Network network) throws OrccException { write("Instantiating...\n"); network = new Instantiator().doSwitch(network); write("Flattening...\n"); new NetworkFlattener().doSwitch(network); new BroadcastAdder().doSwitch(network); new BroadcastTypeResizer().doSwitch(network); for (Entity entity : network.getEntities()) { Instance instance = DfFactory.eINSTANCE.createInstance( entity.getSimpleName(), entity); network.getInstances().add(instance); for (Edge edge : new BasicEList<Edge>(entity.getIncoming())) { edge.setTarget(instance); } for (Edge edge : new BasicEList<Edge>(entity.getOutgoing())) { edge.setSource(instance); } } return network; } @Override protected void doVtlCodeGeneration(List<IFile> files) throws OrccException { // do not generate a VTL } @Override protected void doXdfCodeGeneration(Network network) throws OrccException { network = doTransformNetwork(network); transformActors(network.getAllActors()); printInstances(network); network.computeTemplateMaps(); printNetwork(network); if (finalize) { runPythonScript(); } } private int getAluNb(Instance instance) { if (instance.isActor() && processorIntensiveActors.contains(instance.getActor() .getName())) { return 4; } return 1; } private int getBusNb(Instance instance) { if (instance.isActor() && processorIntensiveActors.contains(instance.getActor() .getName())) { return 8; } return 2; } private int getRegNb(Instance instance) { if (instance.isActor() && processorIntensiveActors.contains(instance.getActor() .getName())) { return 6; } return 2; } @Override protected boolean printInstance(Instance instance) throws OrccException { StandardPrinter printer = new StandardPrinter( "net/sf/orcc/backends/tta/LLVM_Actor.stg", !debug, true); printer.setExpressionPrinter(new LLVMExpressionPrinter()); printer.setTypePrinter(new LLVMTypePrinter()); String instancePath = null; if (!(instance.isActor() && instance.getActor().isNative())) { instancePath = OrccUtil .createFolder(path, instance.getSimpleName()); printProcessor(instance, instancePath); // ModelSim String simPath = OrccUtil.createFolder(instancePath, "simulation"); StandardPrinter tbPrinter = new StandardPrinter( "net/sf/orcc/backends/tta/VHDL_Testbench.stg", !debug, false); StandardPrinter tclPrinter = new StandardPrinter( "net/sf/orcc/backends/tta/ModelSim_Script.stg"); StandardPrinter wavePrinter = new StandardPrinter( "net/sf/orcc/backends/tta/ModelSim_Wave.stg"); tbPrinter.print(instance.getSimpleName() + "_tb.vhd", simPath, instance); tclPrinter.print(instance.getSimpleName() + ".tcl", instancePath, instance); wavePrinter.print("wave.do", simPath, instance); } return printer.print(instance.getSimpleName() + ".ll", instancePath, instance); } private void printNetwork(Network network) { // VHDL Network of TTA processors StandardPrinter networkPrinter = new StandardPrinter( "net/sf/orcc/backends/tta/VHDL_Network.stg"); networkPrinter.setExpressionPrinter(new LLVMExpressionPrinter()); networkPrinter.getOptions().put("fifoSize", fifoSize); networkPrinter.getOptions().put("fifoWidthu", fifoWidthu); networkPrinter.getOptions().put("targetAltera", targetAltera); networkPrinter.getOptions().put("fpgaFamily", fpgaFamily); networkPrinter.print("top.vhd", path, network); // Python package String pythonPath = OrccUtil.createFolder(path, "informations_"); StandardPrinter pythonPrinter = new StandardPrinter( "net/sf/orcc/backends/tta/Python_Network.stg"); pythonPrinter.getOptions().put("targetAltera", targetAltera); pythonPrinter.print("informations.py", pythonPath, network); OrccUtil.createFile(pythonPath, "__init__.py"); if (targetAltera) { // Quartus CustomPrinter projectQsfPrinter = new CustomPrinter( "net/sf/orcc/backends/tta/Quartus_Project.stg"); CustomPrinter projectQpfPrinter = new CustomPrinter( "net/sf/orcc/backends/tta/Quartus_Project.stg"); projectQsfPrinter.print("top.qsf", path, "qsfNetwork", "network", network); projectQpfPrinter.print("top.qpf", path, "qpfNetwork", "network", network); } else { // ISE CustomPrinter projectXisePrinter = new CustomPrinter( "net/sf/orcc/backends/tta/ISE_Project.stg"); projectXisePrinter.print("top.xise", path, "xiseNetwork", "network", network); + projectXisePrinter.print("top.ucf", path, "ucfNetwork", + "network", network); } // ModelSim StandardPrinter tclPrinter = new StandardPrinter( "net/sf/orcc/backends/tta/ModelSim_Script.stg"); StandardPrinter tbPrinter = new StandardPrinter( "net/sf/orcc/backends/tta/VHDL_Testbench.stg"); StandardPrinter wavePrinter = new StandardPrinter( "net/sf/orcc/backends/tta/ModelSim_Wave.stg"); wavePrinter.setExpressionPrinter(new LLVMExpressionPrinter()); tclPrinter.print("top.tcl", path, network); tbPrinter.print("top_tb.vhd", path, network); wavePrinter.print("wave.do", path, network); } private void printProcessor(Instance instance, String instancePath) { int ramSize = instance.isActor() ? ArchitectureMemoryStats .computeNeededMemorySize(instance.getActor()) : 1; Processor tta = ArchitectureFactory.eINSTANCE.createProcessor( instance.getSimpleName(), getBusNb(instance), getRegNb(instance), getAluNb(instance), instance.getEntity() .getInputs().size(), instance.getEntity().getOutputs() .size(), ramSize); CustomPrinter adfPrinter = new CustomPrinter( "net/sf/orcc/backends/tta/TCE_Processor_ADF.stg"); CustomPrinter idfPrinter = new CustomPrinter( "net/sf/orcc/backends/tta/TCE_Processor_IDF.stg"); adfPrinter.print("processor_" + instance.getSimpleName() + ".adf", instancePath, "printTTA", "tta", tta); idfPrinter.print("processor_" + instance.getSimpleName() + ".idf", instancePath, "printTTA", "tta", tta); } private void runPythonScript() throws OrccException { List<String> cmdList = new ArrayList<String>(); cmdList.add(libPath + File.separator + "generate"); cmdList.add("-cg"); if (debug) { cmdList.add("--debug"); } cmdList.add(path); String[] cmd = cmdList.toArray(new String[] {}); try { write("Generating design...\n"); long t0 = System.currentTimeMillis(); final Process process = Runtime.getRuntime().exec(cmd); process.waitFor(); long t1 = System.currentTimeMillis(); write("Done in " + ((float) (t1 - t0) / (float) 1000) + "s\n"); } catch (IOException e) { System.err.println("TCE error: "); e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }
true
true
private void printNetwork(Network network) { // VHDL Network of TTA processors StandardPrinter networkPrinter = new StandardPrinter( "net/sf/orcc/backends/tta/VHDL_Network.stg"); networkPrinter.setExpressionPrinter(new LLVMExpressionPrinter()); networkPrinter.getOptions().put("fifoSize", fifoSize); networkPrinter.getOptions().put("fifoWidthu", fifoWidthu); networkPrinter.getOptions().put("targetAltera", targetAltera); networkPrinter.getOptions().put("fpgaFamily", fpgaFamily); networkPrinter.print("top.vhd", path, network); // Python package String pythonPath = OrccUtil.createFolder(path, "informations_"); StandardPrinter pythonPrinter = new StandardPrinter( "net/sf/orcc/backends/tta/Python_Network.stg"); pythonPrinter.getOptions().put("targetAltera", targetAltera); pythonPrinter.print("informations.py", pythonPath, network); OrccUtil.createFile(pythonPath, "__init__.py"); if (targetAltera) { // Quartus CustomPrinter projectQsfPrinter = new CustomPrinter( "net/sf/orcc/backends/tta/Quartus_Project.stg"); CustomPrinter projectQpfPrinter = new CustomPrinter( "net/sf/orcc/backends/tta/Quartus_Project.stg"); projectQsfPrinter.print("top.qsf", path, "qsfNetwork", "network", network); projectQpfPrinter.print("top.qpf", path, "qpfNetwork", "network", network); } else { // ISE CustomPrinter projectXisePrinter = new CustomPrinter( "net/sf/orcc/backends/tta/ISE_Project.stg"); projectXisePrinter.print("top.xise", path, "xiseNetwork", "network", network); } // ModelSim StandardPrinter tclPrinter = new StandardPrinter( "net/sf/orcc/backends/tta/ModelSim_Script.stg"); StandardPrinter tbPrinter = new StandardPrinter( "net/sf/orcc/backends/tta/VHDL_Testbench.stg"); StandardPrinter wavePrinter = new StandardPrinter( "net/sf/orcc/backends/tta/ModelSim_Wave.stg"); wavePrinter.setExpressionPrinter(new LLVMExpressionPrinter()); tclPrinter.print("top.tcl", path, network); tbPrinter.print("top_tb.vhd", path, network); wavePrinter.print("wave.do", path, network); }
private void printNetwork(Network network) { // VHDL Network of TTA processors StandardPrinter networkPrinter = new StandardPrinter( "net/sf/orcc/backends/tta/VHDL_Network.stg"); networkPrinter.setExpressionPrinter(new LLVMExpressionPrinter()); networkPrinter.getOptions().put("fifoSize", fifoSize); networkPrinter.getOptions().put("fifoWidthu", fifoWidthu); networkPrinter.getOptions().put("targetAltera", targetAltera); networkPrinter.getOptions().put("fpgaFamily", fpgaFamily); networkPrinter.print("top.vhd", path, network); // Python package String pythonPath = OrccUtil.createFolder(path, "informations_"); StandardPrinter pythonPrinter = new StandardPrinter( "net/sf/orcc/backends/tta/Python_Network.stg"); pythonPrinter.getOptions().put("targetAltera", targetAltera); pythonPrinter.print("informations.py", pythonPath, network); OrccUtil.createFile(pythonPath, "__init__.py"); if (targetAltera) { // Quartus CustomPrinter projectQsfPrinter = new CustomPrinter( "net/sf/orcc/backends/tta/Quartus_Project.stg"); CustomPrinter projectQpfPrinter = new CustomPrinter( "net/sf/orcc/backends/tta/Quartus_Project.stg"); projectQsfPrinter.print("top.qsf", path, "qsfNetwork", "network", network); projectQpfPrinter.print("top.qpf", path, "qpfNetwork", "network", network); } else { // ISE CustomPrinter projectXisePrinter = new CustomPrinter( "net/sf/orcc/backends/tta/ISE_Project.stg"); projectXisePrinter.print("top.xise", path, "xiseNetwork", "network", network); projectXisePrinter.print("top.ucf", path, "ucfNetwork", "network", network); } // ModelSim StandardPrinter tclPrinter = new StandardPrinter( "net/sf/orcc/backends/tta/ModelSim_Script.stg"); StandardPrinter tbPrinter = new StandardPrinter( "net/sf/orcc/backends/tta/VHDL_Testbench.stg"); StandardPrinter wavePrinter = new StandardPrinter( "net/sf/orcc/backends/tta/ModelSim_Wave.stg"); wavePrinter.setExpressionPrinter(new LLVMExpressionPrinter()); tclPrinter.print("top.tcl", path, network); tbPrinter.print("top_tb.vhd", path, network); wavePrinter.print("wave.do", path, network); }
diff --git a/2014-AerialAssist/AerialAssist/src/org/discobots/aerialassist/commands/drive/MecanumDrive.java b/2014-AerialAssist/AerialAssist/src/org/discobots/aerialassist/commands/drive/MecanumDrive.java index 227c891..9f0f28f 100644 --- a/2014-AerialAssist/AerialAssist/src/org/discobots/aerialassist/commands/drive/MecanumDrive.java +++ b/2014-AerialAssist/AerialAssist/src/org/discobots/aerialassist/commands/drive/MecanumDrive.java @@ -1,89 +1,89 @@ /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.discobots.aerialassist.commands.drive; import com.sun.squawk.util.MathUtils; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.discobots.aerialassist.commands.CommandBase; /** * * @author Patrick */ public class MecanumDrive extends CommandBase { float xPrev, yPrev, rPrev; private final double rampThreshold = 0.1; public MecanumDrive() { requires(drivetrainSub); xPrev = 0; yPrev = 0; rPrev = 0; } protected void initialize() { drivetrainSub.holonomicPolar(0, 0, 0); System.out.println("Mecanum wheels engaged\n"); } protected void execute() { // Get input from gamepad double x = oi.getRawAnalogStickALX(); double y = oi.getRawAnalogStickALY(); double rotation = oi.getRawAnalogStickARX(); // Deadzone if (Math.abs(x) < 0.05) { x = 0; } if (Math.abs(y) < 0.05) { y = 0; } if (Math.abs(rotation) < 0.05) { rotation = 0; } // Ramp if (xPrev - x > rampThreshold) { x = xPrev - rampThreshold; } else if (x - xPrev > rampThreshold) { x = xPrev + rampThreshold; } if (yPrev - y > rampThreshold) { y = yPrev - rampThreshold; } else if (y - yPrev > rampThreshold) { y = yPrev + rampThreshold; } if (rPrev - rotation > rampThreshold) { rotation = rPrev - rampThreshold; } else if (rotation - rPrev > rampThreshold) { rotation = rPrev + rampThreshold; } - xPrev = x; - yPrev = y; - rPrev = rotation; + xPrev = (float)x; + yPrev = (float)y; + rPrev = (float)rotation; double magnitude = Math.sqrt(x * x + y * y); double angle = MathUtils.atan2(y, x) * 180.0 / Math.PI; double gyroAngle = drivetrainSub.getGyroAngle(); drivetrainSub.holonomicPolar(magnitude, angle + gyroAngle, rotation); } protected boolean isFinished() { return false; } protected void end() { drivetrainSub.holonomicPolar(0, 0, 0); } protected void interrupted() { end(); } }
true
true
protected void execute() { // Get input from gamepad double x = oi.getRawAnalogStickALX(); double y = oi.getRawAnalogStickALY(); double rotation = oi.getRawAnalogStickARX(); // Deadzone if (Math.abs(x) < 0.05) { x = 0; } if (Math.abs(y) < 0.05) { y = 0; } if (Math.abs(rotation) < 0.05) { rotation = 0; } // Ramp if (xPrev - x > rampThreshold) { x = xPrev - rampThreshold; } else if (x - xPrev > rampThreshold) { x = xPrev + rampThreshold; } if (yPrev - y > rampThreshold) { y = yPrev - rampThreshold; } else if (y - yPrev > rampThreshold) { y = yPrev + rampThreshold; } if (rPrev - rotation > rampThreshold) { rotation = rPrev - rampThreshold; } else if (rotation - rPrev > rampThreshold) { rotation = rPrev + rampThreshold; } xPrev = x; yPrev = y; rPrev = rotation; double magnitude = Math.sqrt(x * x + y * y); double angle = MathUtils.atan2(y, x) * 180.0 / Math.PI; double gyroAngle = drivetrainSub.getGyroAngle(); drivetrainSub.holonomicPolar(magnitude, angle + gyroAngle, rotation); }
protected void execute() { // Get input from gamepad double x = oi.getRawAnalogStickALX(); double y = oi.getRawAnalogStickALY(); double rotation = oi.getRawAnalogStickARX(); // Deadzone if (Math.abs(x) < 0.05) { x = 0; } if (Math.abs(y) < 0.05) { y = 0; } if (Math.abs(rotation) < 0.05) { rotation = 0; } // Ramp if (xPrev - x > rampThreshold) { x = xPrev - rampThreshold; } else if (x - xPrev > rampThreshold) { x = xPrev + rampThreshold; } if (yPrev - y > rampThreshold) { y = yPrev - rampThreshold; } else if (y - yPrev > rampThreshold) { y = yPrev + rampThreshold; } if (rPrev - rotation > rampThreshold) { rotation = rPrev - rampThreshold; } else if (rotation - rPrev > rampThreshold) { rotation = rPrev + rampThreshold; } xPrev = (float)x; yPrev = (float)y; rPrev = (float)rotation; double magnitude = Math.sqrt(x * x + y * y); double angle = MathUtils.atan2(y, x) * 180.0 / Math.PI; double gyroAngle = drivetrainSub.getGyroAngle(); drivetrainSub.holonomicPolar(magnitude, angle + gyroAngle, rotation); }
diff --git a/Freerider/src/no/ntnu/idi/socialhitchhiking/map/XMLParser.java b/Freerider/src/no/ntnu/idi/socialhitchhiking/map/XMLParser.java index 896523b..339fdf5 100644 --- a/Freerider/src/no/ntnu/idi/socialhitchhiking/map/XMLParser.java +++ b/Freerider/src/no/ntnu/idi/socialhitchhiking/map/XMLParser.java @@ -1,288 +1,288 @@ package no.ntnu.idi.socialhitchhiking.map; import java.io.IOException; import java.io.InputStream; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.util.Log; import android.util.Xml; import no.ntnu.idi.freerider.model.MapLocation; import no.ntnu.idi.socialhitchhiking.map.MapRoute; public class XMLParser { private static final String ns = null; public XMLParser(){ } public MapRoute parse(InputStream is) throws XmlPullParserException, IOException{ try { XmlPullParser parser = Xml.newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); parser.setInput(is,null); parser.nextTag(); Log.e("Reached","Parse"); return readFeed(parser); } finally { is.close(); } } private MapRoute readFeed(XmlPullParser parser) throws XmlPullParserException, IOException { Log.e("Reached","Feed"); MapRoute route = new MapRoute(); parser.require(XmlPullParser.START_TAG, ns, "DirectionsResponse"); while(parser.next() != XmlPullParser.END_TAG) { if(parser.getEventType() != XmlPullParser.START_TAG) { continue; } String name = parser.getName(); if(name.equals("route")) { route = readRoute(parser); } else { skip(parser); } } Log.e("Reached","End Feed"); return route; } private MapRoute readRoute(XmlPullParser parser) throws XmlPullParserException, IOException { MapRoute route = new MapRoute(); Log.e("Reached","Route"); parser.require(XmlPullParser.START_TAG, ns, "route"); while(parser.next() != XmlPullParser.END_TAG) { if(parser.getEventType() != XmlPullParser.START_TAG) { continue; } String name = parser.getName(); if(name.equals("leg")) { route = readLeg(parser); } else { skip(parser); } } Log.e("Reached","End Route"); return route; } private MapRoute readLeg(XmlPullParser parser) throws XmlPullParserException, IOException { Log.e("Reached","Leg"); MapRoute route = new MapRoute(); //ArrayList<MapLocation> mapPoints = new ArrayList<MapLocation>(); double duration = 0; parser.require(XmlPullParser.START_TAG, ns, "leg"); //int i = 0; while(parser.next() != XmlPullParser.END_TAG) { if(parser.getEventType() != XmlPullParser.START_TAG) { continue; } String name = parser.getName(); if(name.equals("step")) { Log.e("Reached","Step0"); Step step = readStep(parser); try { duration = duration + Double.parseDouble(step.minutesDuration.replace(" mins", "").replace(" min", "")); Log.e("Duration", Double.toString(Double.parseDouble(step.minutesDuration.replace(" mins", "").replace(" min", "")))); - //Log.e("Total duration",) + //Log.e("Total duration",n } catch(Exception e) { Log.e("DurationException", e.getMessage()); } //MapRoute tempRoute = new MapRoute(); route.addCoordinate(new MapLocation(Double.parseDouble(step.getStartLatitude()), Double.parseDouble(step.getStartLongitude()))); route.addCoordinate(new MapLocation(Double.parseDouble(step.getEndLatitude()), Double.parseDouble(step.getEndLongitude()))); route.addToDrivingThroughList(new MapLocation(Double.parseDouble(step.getEndLatitude()), Double.parseDouble(step.getEndLongitude()))); //route.setDistanceDescription(step.getDescription()); //route.setDistanceInKilometers(Double.parseDouble(step.getKmDistance())); route.setDistanceInMinutes(duration); //route.setName("Test"); //Use <summary>? //route.addRouteAsPartOfThis(tempRoute, (i==0)); //i++; } else { skip(parser); } } Log.e("Reached","End Leg"); return route; } private Step readStep(XmlPullParser parser) throws XmlPullParserException, IOException { //Log.e("Reached","Step1"); Step step = new Step(); parser.require(XmlPullParser.START_TAG, ns, "step"); while(parser.next() != XmlPullParser.END_TAG) { //Log.e("Reached",parser.getName()); if(parser.getEventType() != XmlPullParser.START_TAG){ continue; } String name = parser.getName(); //Log.e("Type", name); if(name.equals("start_location")) { LowLocation ll = readStartLocation(parser); step.setStartLatitude(ll.getLatitude()); step.setStartLongitude(ll.getLongitude()); } else if(name.equals("end_location")) { LowLocation ll = readEndLocation(parser); step.setEndLatitude(ll.getLatitude()); step.setEndLongitude(ll.getLongitude()); } else if(name.equals("polyline")) { step.setMapPoints(readPolyline(parser)); } else if(name.equals("duration")) { step.setMinutesDuration(readDuration(parser)); } else if(name.equals("html_instructions")) { step.setDescription(readString(parser,"html_instructions")); } else if(name.equals("distance")) { step.setKmDistance(readDistance(parser)); } else { skip(parser); } } //Log.e("Step",step.getDescription()); Log.e("Reached","Step"); return step; } private LowLocation readEndLocation(XmlPullParser parser) throws XmlPullParserException, IOException { LowLocation ll = new LowLocation(); parser.require(XmlPullParser.START_TAG, ns, "end_location"); while(parser.next() != XmlPullParser.END_TAG) { if(parser.getEventType() != XmlPullParser.START_TAG) { continue; } String name = parser.getName(); if(name.equals("lat")) { ll.setLatitude(readString(parser,"lat")); } else if(name.equals("lng")) { ll.setLongitude(readString(parser,"lng")); } else { skip(parser); } } return ll; } private LowLocation readStartLocation(XmlPullParser parser) throws XmlPullParserException, IOException { LowLocation ll = new LowLocation(); parser.require(XmlPullParser.START_TAG, ns, "start_location"); while(parser.next() != XmlPullParser.END_TAG) { if(parser.getEventType() != XmlPullParser.START_TAG) { continue; } String name = parser.getName(); if(name.equals("lat")) { ll.setLatitude(readString(parser,"lat")); } else if(name.equals("lng")) { ll.setLongitude(readString(parser,"lng")); } else { skip(parser); } } return ll; } private String readDistance(XmlPullParser parser) throws XmlPullParserException, IOException { String ret = ""; parser.require(XmlPullParser.START_TAG, ns, "distance"); while(parser.next() != XmlPullParser.END_TAG) { if(parser.getEventType() != XmlPullParser.START_TAG) { continue; } String name = parser.getName(); if(name.equals("text")) { ret = readString(parser,"text"); } else { skip(parser); } } return ret; } private String readDuration(XmlPullParser parser) throws XmlPullParserException, IOException { String ret = ""; parser.require(XmlPullParser.START_TAG, ns, "duration"); while(parser.next() != XmlPullParser.END_TAG) { if(parser.getEventType() != XmlPullParser.START_TAG) { continue; } String name = parser.getName(); if(name.equals("text")) { ret = readString(parser,"text"); } else { skip(parser); } } return ret; } private String readPolyline(XmlPullParser parser) throws XmlPullParserException, IOException { String ret = ""; parser.require(XmlPullParser.START_TAG, ns, "polyline"); while(parser.next() != XmlPullParser.END_TAG) { if(parser.getEventType() != XmlPullParser.START_TAG) { continue; } String name = parser.getName(); if(name.equals("points")) { ret = readString(parser,"points"); } else { skip(parser); } } return ret; } private String readString(XmlPullParser parser, String name) throws XmlPullParserException, IOException { parser.require(XmlPullParser.START_TAG, ns, name); String result = ""; if(parser.next() == XmlPullParser.TEXT) { result = parser.getText(); parser.nextTag(); } parser.require(XmlPullParser.END_TAG, ns, name); //Log.e("Result",result); return result; } private void skip(XmlPullParser parser) throws XmlPullParserException, IOException { if(parser.getEventType() != XmlPullParser.START_TAG) { throw new IllegalStateException(); } int depth = 1; while(depth != 0) { switch(parser.next()) { case XmlPullParser.END_TAG: depth--; break; case XmlPullParser.START_TAG: depth++; break; } } } }
true
true
private MapRoute readLeg(XmlPullParser parser) throws XmlPullParserException, IOException { Log.e("Reached","Leg"); MapRoute route = new MapRoute(); //ArrayList<MapLocation> mapPoints = new ArrayList<MapLocation>(); double duration = 0; parser.require(XmlPullParser.START_TAG, ns, "leg"); //int i = 0; while(parser.next() != XmlPullParser.END_TAG) { if(parser.getEventType() != XmlPullParser.START_TAG) { continue; } String name = parser.getName(); if(name.equals("step")) { Log.e("Reached","Step0"); Step step = readStep(parser); try { duration = duration + Double.parseDouble(step.minutesDuration.replace(" mins", "").replace(" min", "")); Log.e("Duration", Double.toString(Double.parseDouble(step.minutesDuration.replace(" mins", "").replace(" min", "")))); //Log.e("Total duration",) } catch(Exception e) { Log.e("DurationException", e.getMessage()); } //MapRoute tempRoute = new MapRoute(); route.addCoordinate(new MapLocation(Double.parseDouble(step.getStartLatitude()), Double.parseDouble(step.getStartLongitude()))); route.addCoordinate(new MapLocation(Double.parseDouble(step.getEndLatitude()), Double.parseDouble(step.getEndLongitude()))); route.addToDrivingThroughList(new MapLocation(Double.parseDouble(step.getEndLatitude()), Double.parseDouble(step.getEndLongitude()))); //route.setDistanceDescription(step.getDescription()); //route.setDistanceInKilometers(Double.parseDouble(step.getKmDistance())); route.setDistanceInMinutes(duration); //route.setName("Test"); //Use <summary>? //route.addRouteAsPartOfThis(tempRoute, (i==0)); //i++; } else { skip(parser); } } Log.e("Reached","End Leg"); return route; }
private MapRoute readLeg(XmlPullParser parser) throws XmlPullParserException, IOException { Log.e("Reached","Leg"); MapRoute route = new MapRoute(); //ArrayList<MapLocation> mapPoints = new ArrayList<MapLocation>(); double duration = 0; parser.require(XmlPullParser.START_TAG, ns, "leg"); //int i = 0; while(parser.next() != XmlPullParser.END_TAG) { if(parser.getEventType() != XmlPullParser.START_TAG) { continue; } String name = parser.getName(); if(name.equals("step")) { Log.e("Reached","Step0"); Step step = readStep(parser); try { duration = duration + Double.parseDouble(step.minutesDuration.replace(" mins", "").replace(" min", "")); Log.e("Duration", Double.toString(Double.parseDouble(step.minutesDuration.replace(" mins", "").replace(" min", "")))); //Log.e("Total duration",n } catch(Exception e) { Log.e("DurationException", e.getMessage()); } //MapRoute tempRoute = new MapRoute(); route.addCoordinate(new MapLocation(Double.parseDouble(step.getStartLatitude()), Double.parseDouble(step.getStartLongitude()))); route.addCoordinate(new MapLocation(Double.parseDouble(step.getEndLatitude()), Double.parseDouble(step.getEndLongitude()))); route.addToDrivingThroughList(new MapLocation(Double.parseDouble(step.getEndLatitude()), Double.parseDouble(step.getEndLongitude()))); //route.setDistanceDescription(step.getDescription()); //route.setDistanceInKilometers(Double.parseDouble(step.getKmDistance())); route.setDistanceInMinutes(duration); //route.setName("Test"); //Use <summary>? //route.addRouteAsPartOfThis(tempRoute, (i==0)); //i++; } else { skip(parser); } } Log.e("Reached","End Leg"); return route; }
diff --git a/src/org/doube/geometry/Trig.java b/src/org/doube/geometry/Trig.java index 2d530cc8..443b824c 100644 --- a/src/org/doube/geometry/Trig.java +++ b/src/org/doube/geometry/Trig.java @@ -1,108 +1,108 @@ package org.doube.geometry; /** * Provides simple trigonometric calculations * * @author Michael Doube */ public class Trig { /** * <p> * Calculate the distance between 2 3D points p and q using Pythagoras' * theorem, <i>a</i><sup>2</sup> = <i>b</i><sup>2</sup> + * <i>c</i><sup>2</sup> * </p> * * @param p * a 3 element array * @param q * another 3 element array * @return distance between <i>p</i> and <i>q</i> */ public static double distance3D(double[] p, double[] q) { return distance3D(p[0], p[1], p[2], q[0], q[1], q[2]); } /** * <p> * Calculate the distance between 2 3D points <i>p</i>(x, y, z) and * <i>q</i>(x, y, z) using Pythagoras' theorem * </p> * * @param px * x-coordinate of first point * @param py * y-coordinate of first point * @param pz * z-coordinate of first point * @param qx * x-coordinate of second point * @param qy * y-coordinate of second point * @param qz * z-coordinate of second point * @return */ public static double distance3D(double px, double py, double pz, double qx, double qy, double qz) { final double pqx = px - qx; final double pqy = py - qy; final double pqz = pz - qz; return Math.sqrt(pqx * pqx + pqy * pqy + pqz * pqz); } /** * <p> * Calculate the distance to the origin, (0,0,0). Given 3 orthogonal * vectors, calculates the vector sum * </p> * * @param x * @param y * @param z * @return */ public static double distance3D(double x, double y, double z) { return distance3D(x, y, z, 0, 0, 0); } public static double distance3D(double[] v) { return distance3D(v[0], v[1], v[2], 0, 0, 0); } /** * Caculate the angle between two vectors joined at their tails at the point * (xv, yv, zv) * * @param x0 * @param y0 * @param z0 * @param x1 * @param y1 * @param z1 * @param xv * @param yv * @param zv * @return */ public static double angle3D(double x0, double y0, double z0, double x1, double y1, double z1, double xv, double yv, double zv) { x0 -= xv; y0 -= yv; z0 -= zv; x1 -= xv; y1 -= yv; z1 -= zv; double dot = x0 * x1 + y0 * y1 + z0 * z1; - double d0 = distance3D(xv, yv, zv, x0, y0, z0); - double d1 = distance3D(xv, yv, zv, x0, y0, z0); + double d0 = distance3D(x0, y0, z0); + double d1 = distance3D(x1, y1, z1); double cosTheta = dot / (d0 * d1); return Math.acos(cosTheta); } }
true
true
public static double angle3D(double x0, double y0, double z0, double x1, double y1, double z1, double xv, double yv, double zv) { x0 -= xv; y0 -= yv; z0 -= zv; x1 -= xv; y1 -= yv; z1 -= zv; double dot = x0 * x1 + y0 * y1 + z0 * z1; double d0 = distance3D(xv, yv, zv, x0, y0, z0); double d1 = distance3D(xv, yv, zv, x0, y0, z0); double cosTheta = dot / (d0 * d1); return Math.acos(cosTheta); }
public static double angle3D(double x0, double y0, double z0, double x1, double y1, double z1, double xv, double yv, double zv) { x0 -= xv; y0 -= yv; z0 -= zv; x1 -= xv; y1 -= yv; z1 -= zv; double dot = x0 * x1 + y0 * y1 + z0 * z1; double d0 = distance3D(x0, y0, z0); double d1 = distance3D(x1, y1, z1); double cosTheta = dot / (d0 * d1); return Math.acos(cosTheta); }
diff --git a/src/com/ceco/gm2/gravitybox/ModMms.java b/src/com/ceco/gm2/gravitybox/ModMms.java index 1075710..9f3b033 100644 --- a/src/com/ceco/gm2/gravitybox/ModMms.java +++ b/src/com/ceco/gm2/gravitybox/ModMms.java @@ -1,125 +1,125 @@ package com.ceco.gm2.gravitybox; import android.os.Bundle; import android.text.TextWatcher; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XSharedPreferences; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.XposedHelpers; public class ModMms { public static final String PACKAGE_NAME = "com.android.mms"; private static final String TAG = "GB:ModMms"; private static final String CLASS_COMPOSE_MSG_ACTIVITY = "com.android.mms.ui.ComposeMessageActivity"; private static final String CLASS_WORKING_MESSAGE = "com.android.mms.data.WorkingMessage"; private static final String CLASS_DIALOG_MODE_ACTIVITY = "com.android.mms.ui.DialogModeActivity"; private static final boolean DEBUG = false; private static UnicodeFilter mUnicodeFilter; private static XSharedPreferences mPrefs; private static void log(String message) { XposedBridge.log(TAG + ": " + message); } public static void init(final XSharedPreferences prefs, final ClassLoader classLoader) { try { mPrefs = prefs; final Class<?> composeMsgActivityClass = XposedHelpers.findClass(CLASS_COMPOSE_MSG_ACTIVITY, classLoader); final Class<?> workingMessageClass = XposedHelpers.findClass(CLASS_WORKING_MESSAGE, classLoader); XposedHelpers.findAndHookMethod(composeMsgActivityClass, "onCreate", Bundle.class, activityOnCreateHook); - if (Utils.hasGeminiSupport()) { + if (Utils.isMtkDevice()) { XposedHelpers.findAndHookMethod(workingMessageClass, "send", String.class, int.class, workingMessageSendHook); try { if (DEBUG) log ("Trying to hook on Dialog Mode activity (quickmessage)"); final Class<?> dialogModeActivityClass = XposedHelpers.findClass( CLASS_DIALOG_MODE_ACTIVITY, classLoader); XposedHelpers.findAndHookMethod(dialogModeActivityClass, "onCreate", Bundle.class, activityOnCreateHook); } catch (Throwable t) { XposedBridge.log("Error hooking to quick message dialog. Ignoring."); } } else { XposedHelpers.findAndHookMethod(workingMessageClass, "send", String.class, workingMessageSendHook); } } catch (Throwable t) { XposedBridge.log(t); } } private static XC_MethodHook activityOnCreateHook = new XC_MethodHook() { @Override protected void afterHookedMethod(final MethodHookParam param) throws Throwable { try { if (!prepareUnicodeFilter()) return; if (DEBUG) log("ComposeMessageActivity created. Hooking to TextEditorWatcher"); final TextWatcher textEditorWatcher = (TextWatcher) XposedHelpers.getObjectField( param.thisObject, "mTextEditorWatcher"); if (textEditorWatcher != null) { XposedHelpers.findAndHookMethod(textEditorWatcher.getClass(), "onTextChanged", CharSequence.class, int.class, int.class, int.class, new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param2) throws Throwable { if (param2.thisObject != textEditorWatcher) return; CharSequence s = (CharSequence) param2.args[0]; if (DEBUG) log ("TextEditorWatcher.onTextChanged: original ='" + s + "'"); s = mUnicodeFilter.filter(s); if (DEBUG) log ("TextEditorWatcher.onTextChanged: stripped ='" + s + "'"); XposedHelpers.callMethod(param.thisObject, "updateCounter", s, param2.args[1], param2.args[2], param2.args[3]); } }); } } catch (Throwable t) { XposedBridge.log(t); } } }; private static XC_MethodHook workingMessageSendHook = new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { try { if (mUnicodeFilter == null) return; CharSequence msg = (CharSequence) XposedHelpers.getObjectField(param.thisObject, "mText"); if (DEBUG) log("WorkingMessage.send called; mText = '" + msg + "'"); msg = mUnicodeFilter.filter(msg); if (DEBUG) log("Stripped mText = '" + msg + "'"); XposedHelpers.setObjectField(param.thisObject, "mText", msg); } catch (Throwable t) { XposedBridge.log(t); } } }; private static boolean prepareUnicodeFilter() { mPrefs.reload(); final String uniStrMode = mPrefs.getString( GravityBoxSettings.PREF_KEY_MMS_UNICODE_STRIPPING, GravityBoxSettings.UNISTR_LEAVE_INTACT); if (uniStrMode.equals(GravityBoxSettings.UNISTR_LEAVE_INTACT)) { mUnicodeFilter = null; if (DEBUG) log("prepareUnicodeFilter: Unicode stripping disabled"); return false; } else { mUnicodeFilter = new UnicodeFilter(uniStrMode.equals( GravityBoxSettings.UNISTR_NON_ENCODABLE)); if (DEBUG) log("prepareUnicodeFilter: Unicode filter prepared; mode=" + uniStrMode); return true; } } }
true
true
public static void init(final XSharedPreferences prefs, final ClassLoader classLoader) { try { mPrefs = prefs; final Class<?> composeMsgActivityClass = XposedHelpers.findClass(CLASS_COMPOSE_MSG_ACTIVITY, classLoader); final Class<?> workingMessageClass = XposedHelpers.findClass(CLASS_WORKING_MESSAGE, classLoader); XposedHelpers.findAndHookMethod(composeMsgActivityClass, "onCreate", Bundle.class, activityOnCreateHook); if (Utils.hasGeminiSupport()) { XposedHelpers.findAndHookMethod(workingMessageClass, "send", String.class, int.class, workingMessageSendHook); try { if (DEBUG) log ("Trying to hook on Dialog Mode activity (quickmessage)"); final Class<?> dialogModeActivityClass = XposedHelpers.findClass( CLASS_DIALOG_MODE_ACTIVITY, classLoader); XposedHelpers.findAndHookMethod(dialogModeActivityClass, "onCreate", Bundle.class, activityOnCreateHook); } catch (Throwable t) { XposedBridge.log("Error hooking to quick message dialog. Ignoring."); } } else { XposedHelpers.findAndHookMethod(workingMessageClass, "send", String.class, workingMessageSendHook); } } catch (Throwable t) { XposedBridge.log(t); } }
public static void init(final XSharedPreferences prefs, final ClassLoader classLoader) { try { mPrefs = prefs; final Class<?> composeMsgActivityClass = XposedHelpers.findClass(CLASS_COMPOSE_MSG_ACTIVITY, classLoader); final Class<?> workingMessageClass = XposedHelpers.findClass(CLASS_WORKING_MESSAGE, classLoader); XposedHelpers.findAndHookMethod(composeMsgActivityClass, "onCreate", Bundle.class, activityOnCreateHook); if (Utils.isMtkDevice()) { XposedHelpers.findAndHookMethod(workingMessageClass, "send", String.class, int.class, workingMessageSendHook); try { if (DEBUG) log ("Trying to hook on Dialog Mode activity (quickmessage)"); final Class<?> dialogModeActivityClass = XposedHelpers.findClass( CLASS_DIALOG_MODE_ACTIVITY, classLoader); XposedHelpers.findAndHookMethod(dialogModeActivityClass, "onCreate", Bundle.class, activityOnCreateHook); } catch (Throwable t) { XposedBridge.log("Error hooking to quick message dialog. Ignoring."); } } else { XposedHelpers.findAndHookMethod(workingMessageClass, "send", String.class, workingMessageSendHook); } } catch (Throwable t) { XposedBridge.log(t); } }
diff --git a/src/symbolTable/namespace/Namespace.java b/src/symbolTable/namespace/Namespace.java index d583e69..3a21b77 100644 --- a/src/symbolTable/namespace/Namespace.java +++ b/src/symbolTable/namespace/Namespace.java @@ -1,647 +1,647 @@ package symbolTable.namespace; import errorHandling.*; import java.util.*; import symbolTable.types.Method; import symbolTable.types.Type; /** * * @author kostas */ public class Namespace implements DefinesNamespace{ String name; protected Map<String, NamespaceElement<? extends Type>> allSymbols = new HashMap<String, NamespaceElement<? extends Type>>(); protected Map<String, NamespaceElement<Type>> fields; protected Map<String, Map<Method.Signature, NamespaceElement<Method>>> methods; protected Map<String, NamespaceElement<Namespace>> innerNamespaces; protected Map<String, NamespaceElement<CpmClass>> innerTypes; protected Map<String, NamespaceElement<SynonymType>> innerSynonynms; protected Map<String, TypeDefinition> visibleTypeNames; protected List<MethodDefinition> methodDefinitions; protected Set<Namespace> usingDirectives = null; protected Set<String> conflictsInTypeNames = null; DefinesNamespace belongsTo; String fileName; int line, pos; private void findAllCandidates(String name, DefinesNamespace from_scope, HashSet<Namespace> visited, List<TypeDefinition> typeAgr, List<Namespace> namespaceAgr, List<NamespaceElement<? extends Type>> fieldArg, List<Map<Method.Signature, ? extends MemberElementInfo<Method>>> methAgr, Namespace firstNamespace, boolean searchInSupers) { if(visited.contains(this) == true) return; visited.add(this); if(this.innerTypes != null && this.innerTypes.containsKey(name) == true){ NamespaceElement<CpmClass> tElem = this.innerTypes.get(name); typeAgr.add(tElem.element); } else if(this.innerSynonynms != null && this.innerSynonynms.containsKey(name) == true){ NamespaceElement<SynonymType> sElem = this.innerSynonynms.get(name); typeAgr.add(sElem.element); } else if(this.innerNamespaces != null && this.innerNamespaces.containsKey(name) == true){ NamespaceElement<Namespace> nElem = this.innerNamespaces.get(name); namespaceAgr.add(nElem.element); } else if(this.fields != null && this.fields.containsKey(name) == true){ NamespaceElement<Type> tElem = this.fields.get(name); fieldArg.add(tElem); } else if(this.methods != null && this.methods.containsKey(name) == true){ methAgr.add(this.methods.get(name)); } if((typeAgr.isEmpty() == false || namespaceAgr.isEmpty() == false || fieldArg.isEmpty() == false || methAgr.isEmpty() == false) && this == firstNamespace) return; if(this.usingDirectives != null && searchInSupers == true){ for(Namespace namSpace : this.usingDirectives){ namSpace.findAllCandidates(name, from_scope, visited, typeAgr, namespaceAgr, fieldArg, methAgr, firstNamespace, true); } } } protected class NamespaceElement <T> implements MemberElementInfo<T> { T element; String fileName; int line, pos; public NamespaceElement(T element, String fileName, int line, int pos){ this.element = element; this.fileName = fileName; this.line = line; this.pos = pos; } @Override public String getFileName(){ return this.fileName; } @Override public int getLine(){ return this.line; } @Override public int getPos(){ return this.pos; } @Override public T getElement(){ return this.element; } @Override public boolean equals(Object o){ if(o == null) return false; if(! (o instanceof NamespaceElement)) return false; if(o != this){ NamespaceElement<?> othElem = (NamespaceElement<?>) o; if(this.element.equals(othElem.element) == false) return false; if(this.fileName.equals(othElem.fileName) == false) return false; if(this.line != othElem.line) return false; if(this.pos != othElem.pos) return false; } return true; } @Override public int hashCode() { int hash = 5; hash = 59 * hash + (this.element != null ? this.element.hashCode() : 0); hash = 59 * hash + (this.fileName != null ? this.fileName.hashCode() : 0); hash = 59 * hash + this.line; hash = 59 * hash + this.pos; return hash; } @Override public boolean isStatic() { return false; } @Override public boolean isClassMember() { return false; } @Override public boolean isDefined() { return true; } @Override public void defineStatic(int defLine, int defPos, String defFilename) { throw new UnsupportedOperationException("Definition of a static namespace element is the declaration point."); } @Override public int getStaticDefLine() { return this.getLine(); } @Override public int getStaticDefPos() { return this.getPos(); } @Override public String getStaticDefFile() { return this.getFileName(); } } private void insertInAllSymbols(String name, NamespaceElement<? extends Type> entry){ this.allSymbols.put(name, entry); } private String getFieldsFullName(String field_name){ String rv = this.belongsTo != null ? this.belongsTo.toString() : ""; if(rv.equals("") == false) rv += "::"; rv += field_name; return rv; } private void checkForConflictsInDecl(String name, Type t, int line, int pos) throws ConflictingDeclaration{ if(this.allSymbols.containsKey(name) == true){ NamespaceElement<? extends Type> old_entry = this.allSymbols.get(name); String id = this.getFieldsFullName(name); throw new ConflictingDeclaration(id, t, old_entry.element, line, pos, old_entry.fileName, old_entry.line, old_entry.pos); } } private void checkForConflictsInDecl(String name, TypeDefinition t, int line, int pos) throws ConflictingDeclaration{ if(this.allSymbols.containsKey(name) == true){ NamespaceElement<? extends Type> old_entry = this.allSymbols.get(name); String id = this.getFieldsFullName(name); throw new ConflictingDeclaration(id, t, old_entry.element, line, pos, old_entry.fileName, old_entry.line, old_entry.pos); } } private void checkForConflictsInDecl(String name, Namespace namespace, int line, int pos) throws DiffrentSymbol{ if(this.allSymbols.containsKey(name) == true){ NamespaceElement<? extends Type> old_entry = this.allSymbols.get(name); String id = this.getFieldsFullName(name); throw new DiffrentSymbol(id, namespace, old_entry.element, line, pos, old_entry.fileName, old_entry.line, old_entry.pos); } } private void checkForConflictsWithNamespaces(String name, Type t, int line, int pos) throws DiffrentSymbol{ if(this.innerNamespaces != null && this.innerNamespaces.containsKey(name) == true){ NamespaceElement<Namespace> namespace = this.innerNamespaces.get(name); String id = this.getFieldsFullName(name); throw new DiffrentSymbol(id, t, namespace.element, line, pos, namespace.line, namespace.pos); } } private void checkForConflictsWithNamespaces(String name, TypeDefinition t, int line, int pos) throws DiffrentSymbol{ if(this.innerNamespaces != null && this.innerNamespaces.containsKey(name) == true){ NamespaceElement<Namespace> namespace = this.innerNamespaces.get(name); String id = this.getFieldsFullName(name); throw new DiffrentSymbol(id, t, namespace.element, line, pos, namespace.line, namespace.pos); } } private void checkForChangingMeaningOfType(String name, Type new_entry, int line, int pos) throws ChangingMeaningOf { if(this.visibleTypeNames.containsKey(name) == true){ TypeDefinition t = this.visibleTypeNames.get(name); String id = this.getFieldsFullName(name); throw new ChangingMeaningOf(id, name, new_entry, t, line, pos); } } public Namespace(String name, DefinesNamespace belongsTo){ this.name = name; this.belongsTo = belongsTo; if(this.belongsTo != null){ this.visibleTypeNames = new HashMap<String, TypeDefinition>(this.belongsTo.getVisibleTypeNames()); } else{ this.visibleTypeNames = new HashMap<String, TypeDefinition>(); } } public void insertField(String name, Type t, String fileName, int line, int pos) throws ConflictingDeclaration, ChangingMeaningOf, DiffrentSymbol { if(fields == null) fields = new HashMap<String, NamespaceElement<Type>>(); this.checkForConflictsInDecl(name, t, line, pos); this.checkForChangingMeaningOfType(name, t, line, pos); this.checkForConflictsWithNamespaces(name, t, line, pos); NamespaceElement<Type> elem = new NamespaceElement<Type>(t, fileName, line, pos); fields.put(name, elem); insertInAllSymbols(name, elem); } public void insertMethod(String name, Method m, String fileName, int line, int pos) throws CannotBeOverloaded, ConflictingDeclaration, ChangingMeaningOf, DiffrentSymbol, Redefinition{ if(methods == null) methods = new HashMap<String, Map<Method.Signature, NamespaceElement<Method>>>(); if(methods.containsKey(name) == true){ Map<Method.Signature, NamespaceElement<Method>> ms = methods.get(name); if(ms.containsKey(m.getSignature())){ NamespaceElement<Method> old_m = ms.get(m.getSignature()); Method old = old_m.element; String id = this.getFieldsFullName(name); if(m.equals(old) == true){ if(m.isDefined() && old.isDefined()){ throw new Redefinition(id, m, line, pos, old, old_m.fileName, old_m.line, old_m.pos); } } else{ throw new CannotBeOverloaded(m.toString(id), old_m.element.toString(id), line, pos, old_m.fileName, old_m.line, old_m.pos); } } ms.put(m.getSignature(), new NamespaceElement<Method>(m, fileName, line, pos)); } else{ this.checkForConflictsInDecl(name, m, line, pos); this.checkForChangingMeaningOfType(name, m, line, pos); this.checkForConflictsWithNamespaces(name, m, line, pos); HashMap<Method.Signature, NamespaceElement<Method>> new_entry = new HashMap<Method.Signature, NamespaceElement<Method>>(); NamespaceElement<Method> elem = new NamespaceElement<Method>(m, fileName, line, pos); new_entry.put(m.getSignature(), elem); methods.put(name, new_entry); insertInAllSymbols(name, elem); } } public void insertInnerType(String name, CpmClass t) throws ConflictingDeclaration, DiffrentSymbol, Redefinition { if(innerTypes == null) innerTypes = new HashMap<String, NamespaceElement<CpmClass>>(); this.checkForConflictsInDecl(name, t, t.line, t.pos); this.checkForConflictsWithNamespaces(name, t, t.line, t.pos); if(innerTypes.containsKey(name) == true){ CpmClass t1 = innerTypes.get(name).element; if(t1.isComplete() == false){ innerTypes.put(name, new NamespaceElement<CpmClass>(t, t.fileName, t.line, t.pos)); } else if(t.isComplete() == true){ throw new Redefinition(t, t1); } return; } else if(this.innerSynonynms != null && this.innerSynonynms.containsKey(name) == true){ NamespaceElement<SynonymType> old_entry = this.innerSynonynms.get(name); throw new Redefinition(t, old_entry.element); } innerTypes.put(name, new NamespaceElement<CpmClass>(t, t.fileName, t.line, t.pos)); this.visibleTypeNames.put(name, t); } public void insertInnerSynonym(String name, SynonymType syn) throws ConflictingDeclaration, DiffrentSymbol, Redefinition { if(innerSynonynms == null) innerSynonynms = new HashMap<String, NamespaceElement<SynonymType>>(); this.checkForConflictsInDecl(name, syn, syn.line, syn.pos); this.checkForConflictsWithNamespaces(name, syn, syn.line, syn.pos); if(this.innerSynonynms.containsKey(name) == true){ NamespaceElement<SynonymType> old_entry = this.innerSynonynms.get(name); throw new Redefinition(syn, old_entry.element); } else if(this.innerTypes != null && this.innerTypes.containsKey(name) == true){ NamespaceElement<CpmClass> old_entry = this.innerTypes.get(name); throw new Redefinition(syn, old_entry.element); } this.innerSynonynms.put(name, new NamespaceElement<SynonymType>(syn, syn.fileName, syn.line, syn.pos)); this.visibleTypeNames.put(name, syn); } public Namespace insertInnerNamespace(String name, Namespace namespace) throws DiffrentSymbol{ if(innerNamespaces == null) innerNamespaces = new HashMap<String, NamespaceElement<Namespace>>(); this.checkForConflictsInDecl(name, namespace, namespace.line, namespace.pos); - if(this.innerSynonynms != null && this.innerTypes.containsKey(name) == true) { + if(this.innerTypes != null && this.innerTypes.containsKey(name) == true) { NamespaceElement<CpmClass> old_entry = this.innerTypes.get(name); String id = this.getFieldsFullName(name); throw new DiffrentSymbol(id, namespace, old_entry.element, namespace.line, namespace.pos, old_entry.line, old_entry.pos); } else if(this.innerSynonynms != null && this.innerSynonynms.containsKey(name) == true){ NamespaceElement<SynonymType> old_entry = this.innerSynonynms.get(name); String id = this.getFieldsFullName(name); throw new DiffrentSymbol(id, namespace, old_entry.element, namespace.line, namespace.pos, old_entry.line, old_entry.pos); } Namespace rv; if(!innerNamespaces.containsKey(name)){ innerNamespaces.put(name, new NamespaceElement<Namespace>(namespace, namespace.fileName, namespace.line, namespace.pos)); rv = namespace; } else{ /* * merging the existing namespace with the extension declaration. */ NamespaceElement<Namespace> elem = this.innerNamespaces.get(name); if(elem.fileName == null){ elem.fileName = namespace.fileName; elem.line = namespace.line; elem.line = namespace.pos; } rv = elem.element; /* if(namespace.fields != null){ for(String key : namespace.fields.keySet()){ NamespaceElement<Type> elem = namespace.fields.get(key); Type t = elem.element; exists.insertField(name, t, namespace.fileName, elem.line, elem.pos); } } if(namespace.methods != null){ for(String key : namespace.methods.keySet()){ HashMap<Method.Signature, NamespaceElement<Method>> ms = namespace.methods.get(key); for(NamespaceElement<Method> m : ms.values()){ exists.insertMethod(key, m.element, m.line, m.pos); } } } if(namespace.innerNamespaces != null){ for(String key : namespace.innerNamespaces.keySet()){ ///* //* merge again all the inner namespaces. // NamespaceElement<Namespace> n = namespace.innerNamespaces.get(key); exists.insertInnerNamespace(key, n.element); } } if(namespace.innerTypes != null){ for(String key : namespace.innerTypes.keySet()){ NamespaceElement<CpmClass> t = namespace.innerTypes.get(key); exists.insertInnerType(key, t.element); } } if(namespace.innerSynonynms != null){ for(String key : namespace.innerSynonynms.keySet()){ NamespaceElement<SynonymType> syn = namespace.innerSynonynms.get(key); exists.insertInnerSynonym(key, syn.element); } }*/ } return rv; } public void insertMethodDefinition(MethodDefinition methDef){ if(this.methodDefinitions == null) this.methodDefinitions = new ArrayList<MethodDefinition>(); this.methodDefinitions.add(methDef); } public void setLineAndPos(int line, int pos){ this.line = line; this.pos = pos; } public void setFileName(String fileName){ this.fileName = fileName; } public String getFileName(){ return this.fileName; } public int getLine(){ return this.line; } public int getPos(){ return this.pos; } @Override public String toString(){ return "namespace " + this.getStringName(new StringBuilder()).toString(); } /* * DefinesNamespace methods */ @Override public StringBuilder getStringName(StringBuilder in){ if(belongsTo == null) return in.append(name); StringBuilder parent = this.belongsTo.getStringName(in); return parent.append(parent.toString().equals("") ? "" : "::").append(name); } @Override public DefinesNamespace getParentNamespace() { return this.belongsTo; } @Override public TypeDefinition isValidTypeDefinition(String name, boolean ignore_access) throws AccessSpecViolation, AmbiguousReference { TypeDefinition rv = null; DefinesNamespace curr_namespace = this; while(curr_namespace != null){ /* * from_scope is null because all parents are namespaces. */ rv = curr_namespace.findTypeDefinition(name, null, ignore_access); if(rv != null) break; curr_namespace = curr_namespace.getParentNamespace(); } return rv; } @Override public TypeDefinition findTypeDefinition(String name, DefinesNamespace from_scope, boolean ignore_access) throws AmbiguousReference, AccessSpecViolation { TypeDefinition rv; LookupResult res = this.localLookup(name, from_scope, true, ignore_access); rv = res.isResultType(); return rv; } @Override public DefinesNamespace findNamespace(String name, DefinesNamespace from_scope, boolean ignore_access) throws AccessSpecViolation, AmbiguousReference, InvalidScopeResolution{ DefinesNamespace rv; rv = this.findInnerNamespace(name, from_scope, ignore_access); if(rv == null && this.belongsTo != null){ rv = this.belongsTo.findNamespace(name, from_scope, ignore_access); } return rv; } @Override public DefinesNamespace findInnerNamespace(String name, DefinesNamespace from_scope, boolean ignore_access) throws AmbiguousReference, AccessSpecViolation, InvalidScopeResolution { DefinesNamespace rv; LookupResult res = this.localLookup(name, from_scope, true, ignore_access); rv = res.doesResultDefinesNamespace(); return rv; } @Override public Map<String, TypeDefinition> getVisibleTypeNames() { return this.visibleTypeNames; } @Override public String getFullName(){ return this.getStringName(new StringBuilder()).toString(); } @Override public String getName(){ return this.name; } @Override public LookupResult localLookup(String name, DefinesNamespace from_scope, boolean searchInSupers, boolean ignore_access){ List<TypeDefinition> candidatesTypes = new ArrayList<TypeDefinition>(); List<NamespaceElement<? extends Type>> candidateFields = new ArrayList<NamespaceElement<? extends Type>>(); List<Map<Method.Signature, ? extends MemberElementInfo<Method>>> candidateMethods = new ArrayList<Map<Method.Signature, ? extends MemberElementInfo<Method>>> (); List<Namespace> candidateNamespaces = new ArrayList<Namespace>(); this.findAllCandidates(name, from_scope, new HashSet<Namespace>(), candidatesTypes, candidateNamespaces, candidateFields, candidateMethods, this, true); return new LookupResult(name, candidatesTypes, candidateNamespaces, candidateFields, candidateMethods, null, null, ignore_access); } @Override public LookupResult lookup(String name, DefinesNamespace from_scope, boolean searchInSupers, boolean ignore_access){ LookupResult rv; DefinesNamespace curr = this; do{ rv = curr.localLookup(name, from_scope, searchInSupers, ignore_access); curr = curr.getParentNamespace(); }while(rv.isResultEmpty()); return rv; } @Override public boolean isEnclosedInNamespace(DefinesNamespace namespace){ boolean rv = false; DefinesNamespace curr = this.belongsTo; while(curr != null){ if(curr == namespace){ rv = true; break; } curr = curr.getParentNamespace(); } return rv; } @Override public void resetNonClassFields(){ this.fields = null; this.methods = null; if(this.innerNamespaces != null){ for(NamespaceElement<Namespace> namElem : this.innerNamespaces.values()){ namElem.element.resetNonClassFields(); } } if(this.methodDefinitions != null){ for(MethodDefinition methDef : this.methodDefinitions){ methDef.resetNonClassFields(); } } } private DefinesNamespace isNameSpace(TypeDefinition n_type) throws InvalidScopeResolution { DefinesNamespace rv = null; if(n_type != null){ if(n_type instanceof DefinesNamespace){ rv = (DefinesNamespace)n_type; } else{ throw new InvalidScopeResolution(); //change this to invalid use of :: } } return rv; } public void insertUsingDirective(Namespace nm){ if(this.conflictsInTypeNames == null) this.conflictsInTypeNames = new HashSet<String>(); if(this.usingDirectives == null) this.usingDirectives = new HashSet<Namespace>(); this.usingDirectives.add(nm); Set<String> typeNames = nm.visibleTypeNames.keySet(); Set<String> fieldNames = nm.allSymbols.keySet(); for(String typeName : typeNames){ if(this.conflictsInTypeNames.contains(typeName) == false){ if(this.visibleTypeNames.containsKey(typeName) == false){ this.visibleTypeNames.put(typeName, nm.visibleTypeNames.get(typeName)); } else{ this.visibleTypeNames.remove(typeName); this.conflictsInTypeNames.add(typeName); } } } for(String fieldName : fieldNames){ if(this.conflictsInTypeNames.contains(fieldName) == false){ if(this.visibleTypeNames.containsKey(fieldName) == true){ this.visibleTypeNames.remove(fieldName); } } } } }
true
true
public Namespace insertInnerNamespace(String name, Namespace namespace) throws DiffrentSymbol{ if(innerNamespaces == null) innerNamespaces = new HashMap<String, NamespaceElement<Namespace>>(); this.checkForConflictsInDecl(name, namespace, namespace.line, namespace.pos); if(this.innerSynonynms != null && this.innerTypes.containsKey(name) == true) { NamespaceElement<CpmClass> old_entry = this.innerTypes.get(name); String id = this.getFieldsFullName(name); throw new DiffrentSymbol(id, namespace, old_entry.element, namespace.line, namespace.pos, old_entry.line, old_entry.pos); } else if(this.innerSynonynms != null && this.innerSynonynms.containsKey(name) == true){ NamespaceElement<SynonymType> old_entry = this.innerSynonynms.get(name); String id = this.getFieldsFullName(name); throw new DiffrentSymbol(id, namespace, old_entry.element, namespace.line, namespace.pos, old_entry.line, old_entry.pos); } Namespace rv; if(!innerNamespaces.containsKey(name)){ innerNamespaces.put(name, new NamespaceElement<Namespace>(namespace, namespace.fileName, namespace.line, namespace.pos)); rv = namespace; } else{ /* * merging the existing namespace with the extension declaration. */ NamespaceElement<Namespace> elem = this.innerNamespaces.get(name); if(elem.fileName == null){ elem.fileName = namespace.fileName; elem.line = namespace.line; elem.line = namespace.pos; } rv = elem.element; /* if(namespace.fields != null){ for(String key : namespace.fields.keySet()){ NamespaceElement<Type> elem = namespace.fields.get(key); Type t = elem.element; exists.insertField(name, t, namespace.fileName, elem.line, elem.pos); } } if(namespace.methods != null){ for(String key : namespace.methods.keySet()){ HashMap<Method.Signature, NamespaceElement<Method>> ms = namespace.methods.get(key); for(NamespaceElement<Method> m : ms.values()){ exists.insertMethod(key, m.element, m.line, m.pos); } } } if(namespace.innerNamespaces != null){ for(String key : namespace.innerNamespaces.keySet()){ ///* //* merge again all the inner namespaces. // NamespaceElement<Namespace> n = namespace.innerNamespaces.get(key); exists.insertInnerNamespace(key, n.element); } } if(namespace.innerTypes != null){ for(String key : namespace.innerTypes.keySet()){ NamespaceElement<CpmClass> t = namespace.innerTypes.get(key); exists.insertInnerType(key, t.element); } } if(namespace.innerSynonynms != null){ for(String key : namespace.innerSynonynms.keySet()){ NamespaceElement<SynonymType> syn = namespace.innerSynonynms.get(key); exists.insertInnerSynonym(key, syn.element); } }*/ } return rv; }
public Namespace insertInnerNamespace(String name, Namespace namespace) throws DiffrentSymbol{ if(innerNamespaces == null) innerNamespaces = new HashMap<String, NamespaceElement<Namespace>>(); this.checkForConflictsInDecl(name, namespace, namespace.line, namespace.pos); if(this.innerTypes != null && this.innerTypes.containsKey(name) == true) { NamespaceElement<CpmClass> old_entry = this.innerTypes.get(name); String id = this.getFieldsFullName(name); throw new DiffrentSymbol(id, namespace, old_entry.element, namespace.line, namespace.pos, old_entry.line, old_entry.pos); } else if(this.innerSynonynms != null && this.innerSynonynms.containsKey(name) == true){ NamespaceElement<SynonymType> old_entry = this.innerSynonynms.get(name); String id = this.getFieldsFullName(name); throw new DiffrentSymbol(id, namespace, old_entry.element, namespace.line, namespace.pos, old_entry.line, old_entry.pos); } Namespace rv; if(!innerNamespaces.containsKey(name)){ innerNamespaces.put(name, new NamespaceElement<Namespace>(namespace, namespace.fileName, namespace.line, namespace.pos)); rv = namespace; } else{ /* * merging the existing namespace with the extension declaration. */ NamespaceElement<Namespace> elem = this.innerNamespaces.get(name); if(elem.fileName == null){ elem.fileName = namespace.fileName; elem.line = namespace.line; elem.line = namespace.pos; } rv = elem.element; /* if(namespace.fields != null){ for(String key : namespace.fields.keySet()){ NamespaceElement<Type> elem = namespace.fields.get(key); Type t = elem.element; exists.insertField(name, t, namespace.fileName, elem.line, elem.pos); } } if(namespace.methods != null){ for(String key : namespace.methods.keySet()){ HashMap<Method.Signature, NamespaceElement<Method>> ms = namespace.methods.get(key); for(NamespaceElement<Method> m : ms.values()){ exists.insertMethod(key, m.element, m.line, m.pos); } } } if(namespace.innerNamespaces != null){ for(String key : namespace.innerNamespaces.keySet()){ ///* //* merge again all the inner namespaces. // NamespaceElement<Namespace> n = namespace.innerNamespaces.get(key); exists.insertInnerNamespace(key, n.element); } } if(namespace.innerTypes != null){ for(String key : namespace.innerTypes.keySet()){ NamespaceElement<CpmClass> t = namespace.innerTypes.get(key); exists.insertInnerType(key, t.element); } } if(namespace.innerSynonynms != null){ for(String key : namespace.innerSynonynms.keySet()){ NamespaceElement<SynonymType> syn = namespace.innerSynonynms.get(key); exists.insertInnerSynonym(key, syn.element); } }*/ } return rv; }
diff --git a/src/vooga/rts/gui/menus/MultiMenu.java b/src/vooga/rts/gui/menus/MultiMenu.java index 253033b2..495908e6 100755 --- a/src/vooga/rts/gui/menus/MultiMenu.java +++ b/src/vooga/rts/gui/menus/MultiMenu.java @@ -1,72 +1,70 @@ package vooga.rts.gui.menus; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.List; import java.util.Observable; import java.util.Observer; import javax.swing.JFrame; import javax.swing.JInternalFrame; import vooga.rts.gui.Menu; import vooga.rts.gui.Window; import vooga.rts.networking.client.ClientModel; import vooga.rts.networking.communications.ExpandedLobbyInfo; import vooga.rts.networking.server.MatchmakerServer; public class MultiMenu extends Menu implements Observer { private JFrame myFrame; private ClientModel myClientModel; public MultiMenu (JFrame f) { myFrame = f; - MatchmakerServer server = new MatchmakerServer(); - server.startAcceptingConnections(); List<String> factions = new ArrayList<String>(); factions.add("protoss"); factions.add("zerg"); List<String> maps = new ArrayList<String>(); maps.add("map1"); maps.add("map2"); List<Integer> maxPlayers = new ArrayList<Integer>(); maxPlayers.add(4); maxPlayers.add(6); - // myClientModel = new ClientModel(null, "Test Game", "User 1", factions, maps, maxPlayers); + //myClientModel = new ClientModel(null, "Test Game", "User 1", factions, maps, maxPlayers); } public void setFrame () { myFrame.setContentPane(myClientModel.getView()); myFrame.setVisible(true); } public void unsetFrame() { myFrame.remove(myClientModel.getView()); } @Override public void paint (Graphics2D pen) { } public void handleMouseDown (int x, int y) { myFrame.remove(myClientModel.getView()); setChanged(); notifyObservers(); } @Override public void update (Observable o, Object a) { if (o instanceof ClientModel) { ClientModel c = (ClientModel) o; ExpandedLobbyInfo e = (ExpandedLobbyInfo) a; } setChanged(); notifyObservers(); } }
false
true
public MultiMenu (JFrame f) { myFrame = f; MatchmakerServer server = new MatchmakerServer(); server.startAcceptingConnections(); List<String> factions = new ArrayList<String>(); factions.add("protoss"); factions.add("zerg"); List<String> maps = new ArrayList<String>(); maps.add("map1"); maps.add("map2"); List<Integer> maxPlayers = new ArrayList<Integer>(); maxPlayers.add(4); maxPlayers.add(6); // myClientModel = new ClientModel(null, "Test Game", "User 1", factions, maps, maxPlayers); }
public MultiMenu (JFrame f) { myFrame = f; List<String> factions = new ArrayList<String>(); factions.add("protoss"); factions.add("zerg"); List<String> maps = new ArrayList<String>(); maps.add("map1"); maps.add("map2"); List<Integer> maxPlayers = new ArrayList<Integer>(); maxPlayers.add(4); maxPlayers.add(6); //myClientModel = new ClientModel(null, "Test Game", "User 1", factions, maps, maxPlayers); }
diff --git a/bundles/org.eclipse.build.tools/src/org/eclipse/releng/generators/ErrorTracker.java b/bundles/org.eclipse.build.tools/src/org/eclipse/releng/generators/ErrorTracker.java index 64fe9e7..d8d37b1 100644 --- a/bundles/org.eclipse.build.tools/src/org/eclipse/releng/generators/ErrorTracker.java +++ b/bundles/org.eclipse.build.tools/src/org/eclipse/releng/generators/ErrorTracker.java @@ -1,218 +1,220 @@ /******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.releng.generators; import java.io.IOException; import java.util.Enumeration; import java.util.Hashtable; import java.io.File; import java.util.Vector; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * @version 1.0 * @author */ public class ErrorTracker { // List of test logs expected at end of build private Vector testLogs = new Vector(); // Platforms keyed on private Hashtable platforms = new Hashtable(); private Hashtable logFiles = new Hashtable(); private Hashtable typesMap = new Hashtable(); private Vector typesList = new Vector(); public static void main(String[] args) { // For testing only. Should not be invoked ErrorTracker anInstance = new ErrorTracker(); anInstance.loadFile("D:\\workspaces\\builder_rework\\org.eclipse.releng.eclipsebuilder\\testManifest.xml"); String[] theTypes = anInstance.getTypes(); for (int i=0; i < theTypes.length; i++) { // System.out.println("Type: " + theTypes[i]); PlatformStatus[] thePlatforms = anInstance.getPlatforms(theTypes[i]); for (int j=0; j < thePlatforms.length; j++) { // System.out.println("Out ID: " + thePlatforms[j].getId()); } } } public void loadFile(String fileName) { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser=null; try { parser = docBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e1) { e1.printStackTrace(); } try { Document document = parser.parse(fileName); NodeList elements = document.getElementsByTagName("platform"); int elementCount = elements.getLength(); int errorCount = 0; for (int i = 0; i < elementCount; i++) { PlatformStatus aPlatform = new PlatformStatus((Element) elements.item(i)); // System.out.println("ID: " + aPlatform.getId()); platforms.put(aPlatform.getId(), aPlatform); Node zipType = elements.item(i).getParentNode(); String zipTypeName = (String) zipType.getAttributes().getNamedItem("name").getNodeValue(); Vector aVector = (Vector) typesMap.get(zipTypeName); if (aVector == null) { typesList.add(zipTypeName); aVector = new Vector(); typesMap.put(zipTypeName, aVector); } aVector.add(aPlatform.getId()); } NodeList effectedFiles = document.getElementsByTagName("effectedFile"); int effectedFilesCount = effectedFiles.getLength(); for (int i = 0; i < effectedFilesCount; i++) { Node anEffectedFile = effectedFiles.item(i); Node logFile = anEffectedFile.getParentNode(); String logFileName = (String) logFile.getAttributes().getNamedItem("name").getNodeValue(); logFileName=convertPathDelimiters(logFileName); String effectedFileID = (String) anEffectedFile.getAttributes().getNamedItem("id").getNodeValue(); //System.out.println(logFileName); Vector aVector = (Vector) logFiles.get(logFileName); if (aVector == null) { aVector = new Vector(); logFiles.put(logFileName, aVector); } - aVector.addElement((PlatformStatus) platforms.get(effectedFileID)); + PlatformStatus ps=(PlatformStatus) platforms.get(effectedFileID); + if (ps!=null) + aVector.addElement(ps); } // store a list of the test logs expected after testing NodeList testLogList = document.getElementsByTagName("logFile"); int testLogCount = testLogList.getLength(); for (int i = 0; i < testLogCount; i++) { Node testLog = testLogList.item(i); String testLogName = (String) testLog.getAttributes().getNamedItem("name").getNodeValue(); if (testLogName.endsWith(".xml")){ testLogs.add(testLogName); //System.out.println(testLogName); } } // // Test this mess. // Object[] results = platforms.values().toArray(); // for (int i=0; i < results.length; i++) { // PlatformStatus ap = (PlatformStatus) results[i]; // System.out.println("ID: " + ap.getId() + " passed: " + ap.getPassed()); // } // // Enumeration anEnumeration = logFiles.keys(); // while (anEnumeration.hasMoreElements()) { // String aKey = (String) anEnumeration.nextElement(); // System.out.println("Whack a key: " + aKey); // ((PlatformStatus) logFiles.get(aKey)).setPassed(false); // } // // results = platforms.values().toArray(); // for (int i=0; i < results.length; i++) { // PlatformStatus ap = (PlatformStatus) results[i]; // System.out.println("ID: " + ap.getId() + " passed: " + ap.getPassed()); // } } catch (IOException e) { System.out.println("IOException: " + fileName); // e.printStackTrace(); } catch (SAXException e) { System.out.println("SAXException: " + fileName); e.printStackTrace(); } } public void registerError(String fileName) { // System.out.println("Found an error in: " + fileName); if (logFiles.containsKey(fileName)) { Vector aVector = (Vector) logFiles.get(fileName); for (int i = 0; i < aVector.size(); i++) { ((PlatformStatus) aVector.elementAt(i)).registerError(); } } else { // If a log file is not specified explicitly it effects // all "platforms" except JDT Enumeration values = platforms.elements(); while (values.hasMoreElements()) { PlatformStatus aValue = (PlatformStatus) values.nextElement(); if (!aValue.getId().equals("JA") && !aValue.getId().equals("EW") && !aValue.getId().equals("EA")) { aValue.registerError(); } } } } public boolean hasErrors(String id) { return ((PlatformStatus) platforms.get(id)).hasErrors(); } // Answer a string array of the zip type names in the order they appear in // the .xml file. public String[] getTypes() { return (String[]) typesList.toArray(new String[typesList.size()]); } // Answer an array of PlatformStatus objects for a given type. public PlatformStatus[] getPlatforms(String type) { Vector platformIDs = (Vector) typesMap.get(type); PlatformStatus[] result = new PlatformStatus[platformIDs.size()]; for (int i = 0; i < platformIDs.size(); i++) { result[i] = (PlatformStatus) platforms.get((String) platformIDs.elementAt(i)); } return result; } /** * Returns the testLogs. * @return Vector */ public Vector getTestLogs() { return testLogs; } private String convertPathDelimiters(String path){ return new File(path).getPath(); } }
true
true
public void loadFile(String fileName) { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser=null; try { parser = docBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e1) { e1.printStackTrace(); } try { Document document = parser.parse(fileName); NodeList elements = document.getElementsByTagName("platform"); int elementCount = elements.getLength(); int errorCount = 0; for (int i = 0; i < elementCount; i++) { PlatformStatus aPlatform = new PlatformStatus((Element) elements.item(i)); // System.out.println("ID: " + aPlatform.getId()); platforms.put(aPlatform.getId(), aPlatform); Node zipType = elements.item(i).getParentNode(); String zipTypeName = (String) zipType.getAttributes().getNamedItem("name").getNodeValue(); Vector aVector = (Vector) typesMap.get(zipTypeName); if (aVector == null) { typesList.add(zipTypeName); aVector = new Vector(); typesMap.put(zipTypeName, aVector); } aVector.add(aPlatform.getId()); } NodeList effectedFiles = document.getElementsByTagName("effectedFile"); int effectedFilesCount = effectedFiles.getLength(); for (int i = 0; i < effectedFilesCount; i++) { Node anEffectedFile = effectedFiles.item(i); Node logFile = anEffectedFile.getParentNode(); String logFileName = (String) logFile.getAttributes().getNamedItem("name").getNodeValue(); logFileName=convertPathDelimiters(logFileName); String effectedFileID = (String) anEffectedFile.getAttributes().getNamedItem("id").getNodeValue(); //System.out.println(logFileName); Vector aVector = (Vector) logFiles.get(logFileName); if (aVector == null) { aVector = new Vector(); logFiles.put(logFileName, aVector); } aVector.addElement((PlatformStatus) platforms.get(effectedFileID)); } // store a list of the test logs expected after testing NodeList testLogList = document.getElementsByTagName("logFile"); int testLogCount = testLogList.getLength(); for (int i = 0; i < testLogCount; i++) { Node testLog = testLogList.item(i); String testLogName = (String) testLog.getAttributes().getNamedItem("name").getNodeValue(); if (testLogName.endsWith(".xml")){ testLogs.add(testLogName); //System.out.println(testLogName); } } // // Test this mess. // Object[] results = platforms.values().toArray(); // for (int i=0; i < results.length; i++) { // PlatformStatus ap = (PlatformStatus) results[i]; // System.out.println("ID: " + ap.getId() + " passed: " + ap.getPassed()); // } // // Enumeration anEnumeration = logFiles.keys(); // while (anEnumeration.hasMoreElements()) { // String aKey = (String) anEnumeration.nextElement(); // System.out.println("Whack a key: " + aKey); // ((PlatformStatus) logFiles.get(aKey)).setPassed(false); // } // // results = platforms.values().toArray(); // for (int i=0; i < results.length; i++) { // PlatformStatus ap = (PlatformStatus) results[i]; // System.out.println("ID: " + ap.getId() + " passed: " + ap.getPassed()); // } } catch (IOException e) { System.out.println("IOException: " + fileName); // e.printStackTrace(); } catch (SAXException e) { System.out.println("SAXException: " + fileName); e.printStackTrace(); } }
public void loadFile(String fileName) { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser=null; try { parser = docBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e1) { e1.printStackTrace(); } try { Document document = parser.parse(fileName); NodeList elements = document.getElementsByTagName("platform"); int elementCount = elements.getLength(); int errorCount = 0; for (int i = 0; i < elementCount; i++) { PlatformStatus aPlatform = new PlatformStatus((Element) elements.item(i)); // System.out.println("ID: " + aPlatform.getId()); platforms.put(aPlatform.getId(), aPlatform); Node zipType = elements.item(i).getParentNode(); String zipTypeName = (String) zipType.getAttributes().getNamedItem("name").getNodeValue(); Vector aVector = (Vector) typesMap.get(zipTypeName); if (aVector == null) { typesList.add(zipTypeName); aVector = new Vector(); typesMap.put(zipTypeName, aVector); } aVector.add(aPlatform.getId()); } NodeList effectedFiles = document.getElementsByTagName("effectedFile"); int effectedFilesCount = effectedFiles.getLength(); for (int i = 0; i < effectedFilesCount; i++) { Node anEffectedFile = effectedFiles.item(i); Node logFile = anEffectedFile.getParentNode(); String logFileName = (String) logFile.getAttributes().getNamedItem("name").getNodeValue(); logFileName=convertPathDelimiters(logFileName); String effectedFileID = (String) anEffectedFile.getAttributes().getNamedItem("id").getNodeValue(); //System.out.println(logFileName); Vector aVector = (Vector) logFiles.get(logFileName); if (aVector == null) { aVector = new Vector(); logFiles.put(logFileName, aVector); } PlatformStatus ps=(PlatformStatus) platforms.get(effectedFileID); if (ps!=null) aVector.addElement(ps); } // store a list of the test logs expected after testing NodeList testLogList = document.getElementsByTagName("logFile"); int testLogCount = testLogList.getLength(); for (int i = 0; i < testLogCount; i++) { Node testLog = testLogList.item(i); String testLogName = (String) testLog.getAttributes().getNamedItem("name").getNodeValue(); if (testLogName.endsWith(".xml")){ testLogs.add(testLogName); //System.out.println(testLogName); } } // // Test this mess. // Object[] results = platforms.values().toArray(); // for (int i=0; i < results.length; i++) { // PlatformStatus ap = (PlatformStatus) results[i]; // System.out.println("ID: " + ap.getId() + " passed: " + ap.getPassed()); // } // // Enumeration anEnumeration = logFiles.keys(); // while (anEnumeration.hasMoreElements()) { // String aKey = (String) anEnumeration.nextElement(); // System.out.println("Whack a key: " + aKey); // ((PlatformStatus) logFiles.get(aKey)).setPassed(false); // } // // results = platforms.values().toArray(); // for (int i=0; i < results.length; i++) { // PlatformStatus ap = (PlatformStatus) results[i]; // System.out.println("ID: " + ap.getId() + " passed: " + ap.getPassed()); // } } catch (IOException e) { System.out.println("IOException: " + fileName); // e.printStackTrace(); } catch (SAXException e) { System.out.println("SAXException: " + fileName); e.printStackTrace(); } }
diff --git a/onebusaway-nyc-vehicle-tracking/src/main/java/org/onebusaway/nyc/vehicle_tracking/model/RecordLibrary.java b/onebusaway-nyc-vehicle-tracking/src/main/java/org/onebusaway/nyc/vehicle_tracking/model/RecordLibrary.java index ff6e43f3f..444b4acc2 100644 --- a/onebusaway-nyc-vehicle-tracking/src/main/java/org/onebusaway/nyc/vehicle_tracking/model/RecordLibrary.java +++ b/onebusaway-nyc-vehicle-tracking/src/main/java/org/onebusaway/nyc/vehicle_tracking/model/RecordLibrary.java @@ -1,30 +1,30 @@ package org.onebusaway.nyc.vehicle_tracking.model; import org.onebusaway.realtime.api.EVehiclePhase; import org.onebusaway.realtime.api.VehicleLocationRecord; import org.onebusaway.transit_data_federation.services.AgencyAndIdLibrary; public class RecordLibrary { public static NycTestLocationRecord getVehicleLocationRecordAsNycTestLocationRecord( VehicleLocationRecord record) { NycTestLocationRecord r = new NycTestLocationRecord(); return r; } public static VehicleLocationRecord getNycTestLocationRecordAsVehicleLocationRecord( NycTestLocationRecord record) { VehicleLocationRecord vlr = new VehicleLocationRecord(); vlr.setTimeOfRecord(record.getTimestamp()); vlr.setTimeOfLocationUpdate(record.getTimestamp()); vlr.setBlockId(AgencyAndIdLibrary.convertFromString(record.getInferredBlockId())); vlr.setServiceDate(record.getInferredServiceDate()); vlr.setDistanceAlongBlock(record.getInferredDistanceAlongBlock()); - vlr.setCurrentLocationLat(record.getInferredLat()); - vlr.setCurrentLocationLon(record.getInferredLon()); + vlr.setCurrentLocationLat(record.getLat()); + vlr.setCurrentLocationLon(record.getLon()); vlr.setPhase(EVehiclePhase.valueOf(record.getInferredPhase())); vlr.setStatus(record.getInferredStatus()); return vlr; } }
true
true
public static VehicleLocationRecord getNycTestLocationRecordAsVehicleLocationRecord( NycTestLocationRecord record) { VehicleLocationRecord vlr = new VehicleLocationRecord(); vlr.setTimeOfRecord(record.getTimestamp()); vlr.setTimeOfLocationUpdate(record.getTimestamp()); vlr.setBlockId(AgencyAndIdLibrary.convertFromString(record.getInferredBlockId())); vlr.setServiceDate(record.getInferredServiceDate()); vlr.setDistanceAlongBlock(record.getInferredDistanceAlongBlock()); vlr.setCurrentLocationLat(record.getInferredLat()); vlr.setCurrentLocationLon(record.getInferredLon()); vlr.setPhase(EVehiclePhase.valueOf(record.getInferredPhase())); vlr.setStatus(record.getInferredStatus()); return vlr; }
public static VehicleLocationRecord getNycTestLocationRecordAsVehicleLocationRecord( NycTestLocationRecord record) { VehicleLocationRecord vlr = new VehicleLocationRecord(); vlr.setTimeOfRecord(record.getTimestamp()); vlr.setTimeOfLocationUpdate(record.getTimestamp()); vlr.setBlockId(AgencyAndIdLibrary.convertFromString(record.getInferredBlockId())); vlr.setServiceDate(record.getInferredServiceDate()); vlr.setDistanceAlongBlock(record.getInferredDistanceAlongBlock()); vlr.setCurrentLocationLat(record.getLat()); vlr.setCurrentLocationLon(record.getLon()); vlr.setPhase(EVehiclePhase.valueOf(record.getInferredPhase())); vlr.setStatus(record.getInferredStatus()); return vlr; }
diff --git a/src/java/com/scratchdisk/script/rhino/RhinoScriptException.java b/src/java/com/scratchdisk/script/rhino/RhinoScriptException.java index b74cd150..8f6168b6 100644 --- a/src/java/com/scratchdisk/script/rhino/RhinoScriptException.java +++ b/src/java/com/scratchdisk/script/rhino/RhinoScriptException.java @@ -1,162 +1,162 @@ /* * Scriptographer * * This file is part of Scriptographer, a Plugin for Adobe Illustrator. * * Copyright (c) 2002-2010 Juerg Lehni, http://www.scratchdisk.com. * All rights reserved. * * Please visit http://scriptographer.org/ for updates and contact. * * -- GPL LICENSE NOTICE -- * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * -- GPL LICENSE NOTICE -- * * File created on Apr 10, 2007. */ package com.scratchdisk.script.rhino; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.mozilla.javascript.JavaScriptException; import org.mozilla.javascript.RhinoException; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.WrappedException; import org.mozilla.javascript.Wrapper; import com.scratchdisk.script.ScriptException; import com.scratchdisk.util.StringUtils; /** * ScriptException for Rhino, preferably called RhinoException, but * that's already used by Rhino (org.mozilla.javascript.RhinoException). */ public class RhinoScriptException extends ScriptException { private RhinoEngine engine; private static Throwable getCause(Throwable cause) { // Unwrap multiple wrapped exceptions, but make sure we have one // WrappedException that contains information about script and line // number. if (cause instanceof WrappedException) { Throwable wrapped = ((WrappedException) cause).getWrappedException(); // Unwrap wrapped RhinoScriptExceptions if wrapped more than once if (wrapped instanceof RhinoScriptException) cause = ((RhinoScriptException) wrapped).getCause(); // Unwrapped multiply wrapped Rhino Exceptions if (wrapped instanceof RhinoException) cause = wrapped; } else if (cause instanceof JavaScriptException) { JavaScriptException jse = (JavaScriptException) cause; Object value = jse.getValue(); if (value instanceof Wrapper) { value = ((Wrapper) value).unwrap(); } else if (value instanceof Scriptable) { value = ScriptableObject.getProperty((Scriptable) value, "exception"); } if (value instanceof Throwable) return (Throwable) value; } return cause; } private static String getMessage(Throwable cause) { // Do not use RhinoException#getMessage for short messages // since it adds line number information. Use #details instead. if (cause instanceof RhinoException) { return ((RhinoException) cause).details(); } else { return cause.getMessage(); } } public String getFullMessage() { Throwable cause = getCause(); String separator = System.getProperty("file.separator"); if (cause instanceof RhinoException) { RhinoException re = (RhinoException) cause; StringWriter buf = new StringWriter(); PrintWriter writer = new PrintWriter(buf); if (re instanceof WrappedException) { // Make sure we're not printing the "Wrapped ...Exception:" part writer.println(((WrappedException) re).getWrappedException() .getMessage()); } else { writer.println(re.details()); } - String[] stackTrace = re.getScriptStackTrace().split("[\\n\\r]"); + String[] stackTrace = re.getScriptStackTrace().split("\\r\\n|\\n|\\r"); String sourceName = re.sourceName(); if (sourceName != null) { int lineNumber = re.lineNumber(); // Report sourceName / lineNumber if it is not in the stack // trace already. // TODO Why is this needed? Rhino bug? if (stackTrace.length == 0 || stackTrace[0].indexOf( sourceName + ":" + lineNumber) == -1) { String[] path = engine.getScriptPath(new File(sourceName)); if (path != null) writer.println("\tat " + StringUtils.join(path, separator) + ":" + lineNumber); } } // Parse the lines for filename:linenumber - Pattern pattern = Pattern.compile("\\s+at\\s+([^:]+):(\\d+)"); + Pattern pattern = Pattern.compile("\\s+at\\s+(.+):(\\d+)"); for (int i = 0; i < stackTrace.length; i++) { String line = stackTrace[i]; Matcher matcher = pattern.matcher(line); if (matcher.find()) { String file = matcher.group(1); // Filter out hidden scripts. Only report scripts // that are located in base: if (file.indexOf(separator + "__") == -1) { String[] path = engine.getScriptPath(new File(file)); if (path != null) { writer.println("\tat " + StringUtils.join(path, separator) + ":" + matcher.group(2)); } } } } return buf.toString().trim(); } else { String message = cause.getMessage(); String error = cause.getClass().getSimpleName(); if (message != null && message.length() != 0) error += ": " + message; return error; } } public Throwable getWrappedException() { Throwable cause = getCause(); if (cause instanceof WrappedException) cause = ((WrappedException) cause).getWrappedException(); return cause; } public RhinoScriptException(RhinoEngine engine, Throwable cause) { super(getMessage(getCause(cause)), getCause(cause)); this.engine = engine; } }
false
true
public String getFullMessage() { Throwable cause = getCause(); String separator = System.getProperty("file.separator"); if (cause instanceof RhinoException) { RhinoException re = (RhinoException) cause; StringWriter buf = new StringWriter(); PrintWriter writer = new PrintWriter(buf); if (re instanceof WrappedException) { // Make sure we're not printing the "Wrapped ...Exception:" part writer.println(((WrappedException) re).getWrappedException() .getMessage()); } else { writer.println(re.details()); } String[] stackTrace = re.getScriptStackTrace().split("[\\n\\r]"); String sourceName = re.sourceName(); if (sourceName != null) { int lineNumber = re.lineNumber(); // Report sourceName / lineNumber if it is not in the stack // trace already. // TODO Why is this needed? Rhino bug? if (stackTrace.length == 0 || stackTrace[0].indexOf( sourceName + ":" + lineNumber) == -1) { String[] path = engine.getScriptPath(new File(sourceName)); if (path != null) writer.println("\tat " + StringUtils.join(path, separator) + ":" + lineNumber); } } // Parse the lines for filename:linenumber Pattern pattern = Pattern.compile("\\s+at\\s+([^:]+):(\\d+)"); for (int i = 0; i < stackTrace.length; i++) { String line = stackTrace[i]; Matcher matcher = pattern.matcher(line); if (matcher.find()) { String file = matcher.group(1); // Filter out hidden scripts. Only report scripts // that are located in base: if (file.indexOf(separator + "__") == -1) { String[] path = engine.getScriptPath(new File(file)); if (path != null) { writer.println("\tat " + StringUtils.join(path, separator) + ":" + matcher.group(2)); } } } } return buf.toString().trim(); } else { String message = cause.getMessage(); String error = cause.getClass().getSimpleName(); if (message != null && message.length() != 0) error += ": " + message; return error; } }
public String getFullMessage() { Throwable cause = getCause(); String separator = System.getProperty("file.separator"); if (cause instanceof RhinoException) { RhinoException re = (RhinoException) cause; StringWriter buf = new StringWriter(); PrintWriter writer = new PrintWriter(buf); if (re instanceof WrappedException) { // Make sure we're not printing the "Wrapped ...Exception:" part writer.println(((WrappedException) re).getWrappedException() .getMessage()); } else { writer.println(re.details()); } String[] stackTrace = re.getScriptStackTrace().split("\\r\\n|\\n|\\r"); String sourceName = re.sourceName(); if (sourceName != null) { int lineNumber = re.lineNumber(); // Report sourceName / lineNumber if it is not in the stack // trace already. // TODO Why is this needed? Rhino bug? if (stackTrace.length == 0 || stackTrace[0].indexOf( sourceName + ":" + lineNumber) == -1) { String[] path = engine.getScriptPath(new File(sourceName)); if (path != null) writer.println("\tat " + StringUtils.join(path, separator) + ":" + lineNumber); } } // Parse the lines for filename:linenumber Pattern pattern = Pattern.compile("\\s+at\\s+(.+):(\\d+)"); for (int i = 0; i < stackTrace.length; i++) { String line = stackTrace[i]; Matcher matcher = pattern.matcher(line); if (matcher.find()) { String file = matcher.group(1); // Filter out hidden scripts. Only report scripts // that are located in base: if (file.indexOf(separator + "__") == -1) { String[] path = engine.getScriptPath(new File(file)); if (path != null) { writer.println("\tat " + StringUtils.join(path, separator) + ":" + matcher.group(2)); } } } } return buf.toString().trim(); } else { String message = cause.getMessage(); String error = cause.getClass().getSimpleName(); if (message != null && message.length() != 0) error += ": " + message; return error; } }
diff --git a/test/SocialNetworkTest.java b/test/SocialNetworkTest.java index ee9cb38..a3e4630 100644 --- a/test/SocialNetworkTest.java +++ b/test/SocialNetworkTest.java @@ -1,29 +1,29 @@ import org.junit.Test; import static org.junit.Assert.*; public class SocialNetworkTest { private final static String PERSON1 = "Kernighan"; private final static String PERSON2 = "Ritchie"; private final static String PERSON3 = "Stallman"; @Test public void testSizeGettersEmpty() { SocialNetwork network = new SocialNetwork(); assertEquals(0, network.getNumNodes()); assertEquals(0, network.getNumConnections()); } @Test public void testSizeGetters() { SocialNetwork network = new SocialNetwork(); Connection connection1 = new Connection(PERSON1, PERSON2); network.add(connection1); Connection connection2 = new Connection(PERSON3, PERSON2); network.add(connection2); - assertEquals(2, network.getNumNodes()); - assertEquals(3, network.getNumConnections()); + assertEquals(3, network.getNumNodes()); + assertEquals(2, network.getNumConnections()); } }
true
true
public void testSizeGetters() { SocialNetwork network = new SocialNetwork(); Connection connection1 = new Connection(PERSON1, PERSON2); network.add(connection1); Connection connection2 = new Connection(PERSON3, PERSON2); network.add(connection2); assertEquals(2, network.getNumNodes()); assertEquals(3, network.getNumConnections()); }
public void testSizeGetters() { SocialNetwork network = new SocialNetwork(); Connection connection1 = new Connection(PERSON1, PERSON2); network.add(connection1); Connection connection2 = new Connection(PERSON3, PERSON2); network.add(connection2); assertEquals(3, network.getNumNodes()); assertEquals(2, network.getNumConnections()); }
diff --git a/modules/org.pathvisio.desktop/src/org/pathvisio/desktop/plugin/PluginManager.java b/modules/org.pathvisio.desktop/src/org/pathvisio/desktop/plugin/PluginManager.java index e5abb08f..1ac61290 100644 --- a/modules/org.pathvisio.desktop/src/org/pathvisio/desktop/plugin/PluginManager.java +++ b/modules/org.pathvisio.desktop/src/org/pathvisio/desktop/plugin/PluginManager.java @@ -1,111 +1,111 @@ // PathVisio, // a tool for data visualization and analysis using Biological Pathways // Copyright 2006-2011 BiGCaT Bioinformatics // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.pathvisio.desktop.plugin; import java.util.ArrayList; import java.util.List; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.pathvisio.core.debug.Logger; import org.pathvisio.core.preferences.PreferenceManager; import org.pathvisio.desktop.PvDesktop; /** * This class loads and maintains a collection of plugins */ public class PluginManager { private PvDesktop pvDesktop; private List<PluginInfo> plugins; private RepositoryManager repositoryManager; private List<Plugin> startedPlugins; /** * Create a plugin manager that loads plugins from the given locations */ public PluginManager(PvDesktop pvDesktop) { this.pvDesktop = pvDesktop; startedPlugins = new ArrayList<Plugin>(); plugins = new ArrayList<PluginInfo>(); repositoryManager = new RepositoryManager(pvDesktop); if(PreferenceManager.getCurrent().getBoolean(PluginDialogSwitch.PLUGIN_DIALOG_SWITCH)) { repositoryManager.loadRepositories(); } startPlugins(); } /** * */ public void startPlugins() { try { ServiceReference[] refs = pvDesktop.getContext().getServiceReferences(Plugin.class.getName(), null); if(refs != null) { for(int i = 0; i < refs.length; i++) { Plugin plugin = (Plugin) pvDesktop.getContext().getService(refs[i]); if(!startedPlugins.contains(plugin)) { PluginInfo pi = new PluginInfo(); pi.plugin = plugin.getClass(); pi.param = ""; pi.jar = refs[i].getBundle().getLocation(); try { plugin.init(pvDesktop); startedPlugins.add(plugin); } catch (Exception ex) { + Logger.log.error("Could not initialize plugin", ex); pi.error = ex; - ex.printStackTrace(); } info.add(pi); plugins.add(pi); } } } } catch (InvalidSyntaxException e) { Logger.log.error("Couldn't load plugins."); } } /** * Info about a plugin (active or non-active). * Gives info about * <li>from which jar it was loaded, if any * <li>if there were any errors * <li>which parameter caused it to be loaded */ public static class PluginInfo { public Class<? extends Plugin> plugin; public String jar; // may be null if it wasn't a jar public Throwable error; // null if there was no error public String param; // parameter that caused this plugin to be loaded } List<PluginInfo> info = new ArrayList<PluginInfo>(); public List<PluginInfo> getPluginInfo() { return info; } public RepositoryManager getRepositoryManager() { return repositoryManager; } }
false
true
public void startPlugins() { try { ServiceReference[] refs = pvDesktop.getContext().getServiceReferences(Plugin.class.getName(), null); if(refs != null) { for(int i = 0; i < refs.length; i++) { Plugin plugin = (Plugin) pvDesktop.getContext().getService(refs[i]); if(!startedPlugins.contains(plugin)) { PluginInfo pi = new PluginInfo(); pi.plugin = plugin.getClass(); pi.param = ""; pi.jar = refs[i].getBundle().getLocation(); try { plugin.init(pvDesktop); startedPlugins.add(plugin); } catch (Exception ex) { pi.error = ex; ex.printStackTrace(); } info.add(pi); plugins.add(pi); } } } } catch (InvalidSyntaxException e) { Logger.log.error("Couldn't load plugins."); } }
public void startPlugins() { try { ServiceReference[] refs = pvDesktop.getContext().getServiceReferences(Plugin.class.getName(), null); if(refs != null) { for(int i = 0; i < refs.length; i++) { Plugin plugin = (Plugin) pvDesktop.getContext().getService(refs[i]); if(!startedPlugins.contains(plugin)) { PluginInfo pi = new PluginInfo(); pi.plugin = plugin.getClass(); pi.param = ""; pi.jar = refs[i].getBundle().getLocation(); try { plugin.init(pvDesktop); startedPlugins.add(plugin); } catch (Exception ex) { Logger.log.error("Could not initialize plugin", ex); pi.error = ex; } info.add(pi); plugins.add(pi); } } } } catch (InvalidSyntaxException e) { Logger.log.error("Couldn't load plugins."); } }
diff --git a/contentconnector/contentconnector-lucene/src/main/java/com/gentics/cr/lucene/search/CRSearcher.java b/contentconnector/contentconnector-lucene/src/main/java/com/gentics/cr/lucene/search/CRSearcher.java index 1de61e1f..684ae421 100644 --- a/contentconnector/contentconnector-lucene/src/main/java/com/gentics/cr/lucene/search/CRSearcher.java +++ b/contentconnector/contentconnector-lucene/src/main/java/com/gentics/cr/lucene/search/CRSearcher.java @@ -1,539 +1,544 @@ package com.gentics.cr.lucene.search; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import org.apache.log4j.Logger; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Term; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.Explanation; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Searcher; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.TopDocsCollector; import org.apache.lucene.search.TopFieldCollector; import org.apache.lucene.search.TopScoreDocCollector; import com.gentics.cr.CRConfig; import com.gentics.cr.CRRequest; import com.gentics.cr.configuration.GenericConfiguration; import com.gentics.cr.exceptions.CRException; import com.gentics.cr.lucene.didyoumean.DidYouMeanProvider; import com.gentics.cr.lucene.indexaccessor.IndexAccessor; import com.gentics.cr.lucene.indexer.index.LuceneAnalyzerFactory; import com.gentics.cr.lucene.indexer.index.LuceneIndexLocation; import com.gentics.cr.lucene.search.query.BooleanQueryRewriter; import com.gentics.cr.lucene.search.query.CRQueryParserFactory; import com.gentics.cr.util.StringUtils; import com.gentics.cr.util.generics.Instanciator; /** * CRSearcher. * Last changed: $Date: 2010-04-01 15:25:54 +0200 (Do, 01 Apr 2010) $ * @version $Revision: 545 $ * @author $Author: [email protected] $ */ public class CRSearcher { private static Logger log = Logger.getLogger(CRSearcher.class); private static Logger log_explain = Logger.getLogger(CRSearcher.class); protected static final String INDEX_LOCATION_KEY = "indexLocation"; protected static final String COMPUTE_SCORES_KEY = "computescores"; protected static final String STEMMING_KEY = "STEMMING"; protected static final String STEMMER_NAME_KEY = "STEMMERNAME"; private static final String COLLECTOR_CLASS_KEY = "collectorClass"; private static final String COLLECTOR_CONFIG_KEY = "collector"; /** * Key to store the searchquery in the result. */ public static final String RESULT_QUERY_KEY = "query"; /** * Key to store the hitcount in the result. */ public static final String RESULT_HITS_KEY = "hits"; /** * Key to store the result in the result. */ public static final String RESULT_RESULT_KEY = "result"; /** * Key to store the maximum score of the result in the result. */ public static final String RESULT_MAXSCORE_KEY = "maxscore"; /** * Key to store the bestquery in the result. */ public static final String RESULT_BESTQUERY_KEY = "bestquery"; /** * Key to store the hitcount of the bestquery in the result. */ public static final String RESULT_BESTQUERYHITS_KEY = "bestqueryhits"; /** * Key to store the map for the suggestion terms as strings in the result. */ public static final String RESULT_SUGGESTIONS_KEY = "suggestions"; /** * Key to store the map for the suggestion terms in the result. */ public static final String RESULT_SUGGESTIONTERMS_KEY = "suggestionTerms"; /** * Key to put the suggested term for the bestresult into the result. */ public static final String RESULT_SUGGESTEDTERM_KEY = "suggestedTerm"; /** * Key to put the orignal term for the suggested term into the bestresult. */ private static final String RESULT_ORIGTERM_KEY = "originalTerm"; /** * Key to configure the limit of results we activate the didyoumean code. */ private static final String DIDYOUMEAN_ACTIVATE_KEY = "didyoumean_activatelimit"; public static final String DIDYOUMEAN_ENABLED_KEY = "didyoumean"; private static final String DIDYOUMEAN_BESTQUERY_KEY = "didyoumeanbestquery"; private static final String ADVANCED_DIDYOUMEAN_BESTQUERY_KEY = "didyoumeanbestqueryadvanced"; private static final String DIDYOUMEAN_SUGGEST_COUNT_KEY = "didyoumeansuggestions"; private static final String DIDYOUMEAN_MIN_SCORE = "didyoumeanminscore"; protected CRConfig config; private boolean computescores = true; private boolean didyoumeanenabled = false; private boolean didyoumeanbestquery = true; private boolean advanceddidyoumeanbestquery = false; private int didyoumeansuggestcount = 5; private float didyoumeanminscore = 0.5f; /** * resultsizelimit to activate the didyoumeanfunctionality. */ private int didyoumeanactivatelimit = 0; private DidYouMeanProvider didyoumeanprovider = null; /** * Create new instance of CRSearcher. * @param config */ public CRSearcher(CRConfig config) { this.config = config; computescores = config.getBoolean(COMPUTE_SCORES_KEY, computescores); didyoumeanenabled = config.getBoolean(DIDYOUMEAN_ENABLED_KEY, didyoumeanenabled); didyoumeansuggestcount = config.getInteger(DIDYOUMEAN_SUGGEST_COUNT_KEY, didyoumeansuggestcount); didyoumeanminscore = config.getFloat(DIDYOUMEAN_MIN_SCORE, didyoumeanminscore); if (didyoumeanenabled) { didyoumeanprovider = new DidYouMeanProvider(config); didyoumeanbestquery = config.getBoolean(DIDYOUMEAN_BESTQUERY_KEY, didyoumeanbestquery); advanceddidyoumeanbestquery = config.getBoolean(ADVANCED_DIDYOUMEAN_BESTQUERY_KEY, advanceddidyoumeanbestquery); didyoumeanactivatelimit = config.getInteger(DIDYOUMEAN_ACTIVATE_KEY, didyoumeanactivatelimit); } } /** * Create the appropriate collector. * * @param hits * @param sorting * @return * @throws IOException */ TopDocsCollector<?> createCollector(final Searcher searcher, final int hits, final String[] sorting, final boolean computescores, final String[] userPermissions) throws IOException { TopDocsCollector<?> coll = null; String collectorClassName = (String) config.get(COLLECTOR_CLASS_KEY); if (collectorClassName != null) { Class<?> genericCollectorClass; try { genericCollectorClass = Class.forName(collectorClassName); GenericConfiguration collectorConfiguration = config.getSubConfigs().get(COLLECTOR_CONFIG_KEY.toUpperCase()); Object[][] prioritizedParameters = new Object[3][]; prioritizedParameters[0] = new Object[] { searcher, hits, collectorConfiguration, userPermissions }; prioritizedParameters[1] = new Object[] { searcher, hits, collectorConfiguration }; prioritizedParameters[2] = new Object[] { hits, collectorConfiguration }; Object collectorObject = Instanciator.getInstance(genericCollectorClass, prioritizedParameters); if (collectorObject instanceof TopDocsCollector) { coll = (TopDocsCollector<?>) collectorObject; } } catch (ClassNotFoundException e) { log.error("Cannot find configured collector class: \"" + collectorClassName + "\" in " + config.getName(), e); } } if (coll == null && sorting != null) { // TODO make collector configurable coll = TopFieldCollector.create(createSort(sorting), hits, true, computescores, computescores, computescores); } if (coll == null) { coll = TopScoreDocCollector.create(hits, true); } return coll; } /** * Creates a Sort object for the Sort collector. The general syntax for sort properties is [property][:asc|:desc] * where the postfix determines the sortorder. If neither :asc nor :desc is given, the sorting will be done * ascending for this property. * * NOTE: using "score:asc" or "score:desc" will both result in an ascating relevance sorting * * @param sorting * @return */ private Sort createSort(String[] sorting) { Sort ret = null; ArrayList<SortField> sortFields = new ArrayList<SortField>(); for (String s : sorting) { // split attribute on :. First element is attribute name the // second is the direction String[] sort = s.split(":"); if (sort[0] != null) { boolean reverse; if ("desc".equals(sort[1].toLowerCase())) { reverse = true; } else { reverse = false; } if ("score".equalsIgnoreCase(sort[0])) { sortFields.add(SortField.FIELD_SCORE); } else { sortFields.add(new SortField(sort[0], Locale.getDefault(), reverse)); } } } ret = new Sort(sortFields.toArray(new SortField[] {})); return ret; } /** * Run a Search against the lucene index. * * @param searcher * @param parsedQuery * @param count * @param collector * @param explain * @param start * @return ArrayList of results */ private HashMap<String, Object> executeSearcher(final TopDocsCollector<?> collector, final Searcher searcher, final Query parsedQuery, final boolean explain, final int count, final int start) { try { searcher.search(parsedQuery, collector); TopDocs tdocs = collector.topDocs(start, count); float maxScoreReturn = tdocs.getMaxScore(); log.debug("maxScoreReturn: " + maxScoreReturn); ScoreDoc[] hits = tdocs.scoreDocs; log.debug("hits (topdocs): \n" + StringUtils.getCollectionSummary(Arrays.asList(hits), "\n")); LinkedHashMap<Document, Float> result = new LinkedHashMap<Document, Float>(hits.length); // Calculate the number of documents to be fetched int num = Math.min(hits.length, count); for (int i = 0; i < num; i++) { ScoreDoc currentDoc = hits[i]; if (currentDoc.doc != Integer.MAX_VALUE) { log.debug("currentDoc id: " + currentDoc.doc + " ; score: " + currentDoc.score); Document doc = searcher.doc(currentDoc.doc); // add id field for AdvancedContentHighlighter doc.add(new Field("id", hits[i].doc + "", Field.Store.YES, Field.Index.NO)); log.debug("adding contentid: " + doc.getField("contentid")); log.debug("with hits[" + i + "].score = " + hits[i].score); result.put(doc, hits[i].score); if (explain) { Explanation ex = searcher.explain(parsedQuery, hits[i].doc); log_explain.debug("Explanation for " + doc.toString() + " - " + ex.toString()); } } else { log.error("Loading search documents failed partly (document has MAX_INTEGER as document id"); } } log.debug("Fetched Document " + start + " to " + (start + num) + " of " + collector.getTotalHits() + " found Documents"); HashMap<String, Object> ret = new HashMap<String, Object>(2); ret.put(RESULT_RESULT_KEY, result); ret.put(RESULT_MAXSCORE_KEY, maxScoreReturn); return ret; } catch (Exception e) { log.error("Error running search for query " + parsedQuery, e); } return null; } public HashMap<String, Object> search(String query, String[] searchedAttributes, int count, int start, boolean explain) throws IOException, CRException { return search(query, searchedAttributes, count, start, explain, null); } public HashMap<String, Object> search(String query, String[] searchedAttributes, int count, int start, boolean explain, String[] sorting) throws IOException, CRException { return search(query, searchedAttributes, count, start, explain, sorting, new CRRequest()); } /** * Search in lucene index (executes executeSearcher). * * @param query query string * @param searchedAttributes TODO javadoc * @param count - max number of results that are to be returned * @param start - the start number of the page e.g. if start = 50 and count = 10 you will get the elements 50 - 60 * @param explain - if set to true the searcher will add extra explain output to the logger * com.gentics.cr.lucene.searchCRSearcher.explain * @param sorting - this argument takes the sorting array that can look like this: ["contentid:asc","name:desc"] * @param request TODO javadoc * @return HashMap&lt;String,Object&gt; with two entries. Entry "query" contains the parsed query and entry "result" * contains a Collection of result documents. * @throws IOException TODO javadoc * @throws CRException in case maxclausecount is reached and failOnMaxClauses is enabled in the config object */ @SuppressWarnings("unchecked") public final HashMap<String, Object> search(final String query, final String[] searchedAttributes, final int count, final int start, final boolean explain, final String[] sorting, final CRRequest request) throws IOException, CRException { Searcher searcher; Analyzer analyzer; // Collect count + start hits int hits = count + start; // we want to retreive the startcount (start) to endcount (hits) LuceneIndexLocation idsLocation = LuceneIndexLocation.getIndexLocation(this.config); IndexAccessor indexAccessor = idsLocation.getAccessor(); searcher = indexAccessor.getPrioritizedSearcher(); Object userPermissionsObject = request.get(CRRequest.PERMISSIONS_KEY); String[] userPermissions = new String[0]; if (userPermissionsObject instanceof String[]) { userPermissions = (String[]) userPermissionsObject; } TopDocsCollector<?> collector = createCollector(searcher, hits, sorting, computescores, userPermissions); HashMap<String, Object> result = null; try { analyzer = LuceneAnalyzerFactory.createAnalyzer(this.config); if (searchedAttributes != null && searchedAttributes.length > 0 && query != null && !query.equals("")) { QueryParser parser = CRQueryParserFactory.getConfiguredParser(searchedAttributes, analyzer, request, config); Query parsedQuery = parser.parse(query); // GENERATE A NATIVE QUERY parsedQuery = searcher.rewrite(parsedQuery); result = new HashMap<String, Object>(3); result.put(RESULT_QUERY_KEY, parsedQuery); Map<String, Object> ret = executeSearcher(collector, searcher, parsedQuery, explain, count, start); if (log.isDebugEnabled()) { for (Object res : ret.values()) { if (res instanceof LinkedHashMap) { LinkedHashMap<Document, Float> documents = (LinkedHashMap<Document, Float>) res; if (documents != null) { for (Entry doc : documents.entrySet()) { Document doCument = (Document) doc.getKey(); - log.debug("CRSearcher.search: " + doCument.getField("contentid").toString()); + String contentid + = doCument.get("contentid"); + log.debug("CRSearcher.search: " + + doCument.toString() + + " Contentid: " + + contentid); } } } } } if (ret != null) { LinkedHashMap<Document, Float> coll = (LinkedHashMap<Document, Float>) ret.get(RESULT_RESULT_KEY); float maxScore = (Float) ret.get(RESULT_MAXSCORE_KEY); result.put(RESULT_RESULT_KEY, coll); int totalhits = collector.getTotalHits(); result.put(RESULT_HITS_KEY, totalhits); result.put(RESULT_MAXSCORE_KEY, maxScore); // PLUG IN DIDYOUMEAN boolean didyoumeanEnabledForRequest = StringUtils.getBoolean(request.get(DIDYOUMEAN_ENABLED_KEY), true); if (start == 0 && didyoumeanenabled && didyoumeanEnabledForRequest && (totalhits <= didyoumeanactivatelimit || didyoumeanactivatelimit == -1 || maxScore < this.didyoumeanminscore)) { HashMap<String, Object> didyoumeanResult = didyoumean( query, parsedQuery, indexAccessor, parser, searcher, sorting, userPermissions); result.putAll(didyoumeanResult); } // PLUG IN DIDYOUMEAN END int size = 0; if (coll != null) { size = coll.size(); } log.debug("Fetched " + size + " objects with query: " + query); } else { result = null; } } } catch (Exception e) { if (config.getBoolean("FAILONMAXCLAUSES")) { log.debug("Error getting the results.", e); throw new CRException(e); } else { log.error("Error getting the results.", e); result = null; } } finally { indexAccessor.release(searcher); } return result; } /** * get Result for didyoumean. * * @param originalQuery - original query for fallback when wildcards are replaced with nothing. * @param parsedQuery - parsed query in which we can replace the search words * @param indexAccessor - accessor to get results from the index * @param parser - query parser * @param searcher - searcher to search in the index * @param sorting - sorting to use * @param userPermissions - user permission used to get the original result * @return Map containing the replacement for the searchterm and the result for the resulting query. */ private HashMap<String, Object> didyoumean(final String originalQuery, final Query parsedQuery, final IndexAccessor indexAccessor, final QueryParser parser, final Searcher searcher, final String[] sorting, final String[] userPermissions) { long dymStart = System.currentTimeMillis(); HashMap<String, Object> result = new HashMap<String, Object>(3); IndexReader reader = null; try { reader = indexAccessor.getReader(false); Query rwQuery = parsedQuery; Set<Term> termset = new HashSet<Term>(); rwQuery.extractTerms(termset); Map<Term, Term[]> suggestions = this.didyoumeanprovider.getSuggestionTerms(termset, this.didyoumeansuggestcount, reader); boolean containswildcards = originalQuery.indexOf('*') != -1; if (suggestions.size() == 0 && containswildcards) { String newSuggestionQuery = originalQuery.replaceAll(":\\*?([^*]*)\\*?", ":$1"); try { rwQuery = parser.parse(newSuggestionQuery); termset = new HashSet<Term>(); // REWRITE NEWLY PARSED QUERY rwQuery = rwQuery.rewrite(reader); rwQuery.extractTerms(termset); suggestions = this.didyoumeanprovider.getSuggestionTerms(termset, this.didyoumeansuggestcount, reader); } catch (ParseException e) { log.error("Cannot Parse Suggestion Query.", e); } } result.put(RESULT_SUGGESTIONTERMS_KEY, suggestions); result.put(RESULT_SUGGESTIONS_KEY, this.didyoumeanprovider.getSuggestionsStringFromMap(suggestions)); log.debug("DYM Suggestions took " + (System.currentTimeMillis() - dymStart) + "ms"); if (didyoumeanbestquery || advanceddidyoumeanbestquery) { // SPECIAL SUGGESTION // TODO Test if the query will be altered and if any suggestion // have been made... otherwise don't execute second query and // don't include the bestquery for (Entry<Term, Term[]> e : suggestions.entrySet()) { Term term = e.getKey(); Term[] suggestionsForTerm = e.getValue(); if (advanceddidyoumeanbestquery) { TreeMap<Integer, HashMap<String, Object>> suggestionsResults = new TreeMap<Integer, HashMap<String, Object>>( Collections.reverseOrder()); for (Term suggestedTerm : suggestionsForTerm) { Query newquery = BooleanQueryRewriter.replaceTerm(rwQuery, term, suggestedTerm); HashMap<String, Object> resultOfNewQuery = getResultsForQuery(newquery, searcher, sorting, userPermissions); if (resultOfNewQuery != null) { resultOfNewQuery.put(RESULT_SUGGESTEDTERM_KEY, suggestedTerm.text()); resultOfNewQuery.put(RESULT_ORIGTERM_KEY, term.text()); Integer resultCount = (Integer) resultOfNewQuery.get(RESULT_BESTQUERYHITS_KEY); if (resultCount > 0) { suggestionsResults.put(resultCount, resultOfNewQuery); } } } result.put(RESULT_BESTQUERY_KEY, suggestionsResults); } else { Query newquery = BooleanQueryRewriter.replaceTerm(rwQuery, term, suggestionsForTerm[0]); HashMap<String, Object> resultOfNewQuery = getResultsForQuery(newquery, searcher, sorting, userPermissions); result.putAll(resultOfNewQuery); } } } log.debug("DYM took " + (System.currentTimeMillis() - dymStart) + "ms"); return result; } catch (IOException e) { log.error("Cannot access index for didyoumean functionality.", e); } finally { if (indexAccessor != null && reader != null) { indexAccessor.release(reader, false); } } return null; } private HashMap<String, Object> getResultsForQuery(final String query, final QueryParser parser, final Searcher searcher, final String[] sorting, final String[] userPermissions) { try { return getResultsForQuery(parser.parse(query), searcher, sorting, userPermissions); } catch (ParseException e) { log.error("Cannot parse query to get results for.", e); } return null; } private HashMap<String, Object> getResultsForQuery(final Query query, final Searcher searcher, final String[] sorting, final String[] userPermissions) { HashMap<String, Object> result = new HashMap<String, Object>(3); try { TopDocsCollector<?> bestcollector = createCollector(searcher, 1, sorting, computescores, userPermissions); executeSearcher(bestcollector, searcher, query, false, 1, 0); result.put(RESULT_BESTQUERY_KEY, query); result.put(RESULT_BESTQUERYHITS_KEY, bestcollector.getTotalHits()); return result; } catch (IOException e) { log.error("Cannot create collector to get results for query.", e); } return null; } }
true
true
public final HashMap<String, Object> search(final String query, final String[] searchedAttributes, final int count, final int start, final boolean explain, final String[] sorting, final CRRequest request) throws IOException, CRException { Searcher searcher; Analyzer analyzer; // Collect count + start hits int hits = count + start; // we want to retreive the startcount (start) to endcount (hits) LuceneIndexLocation idsLocation = LuceneIndexLocation.getIndexLocation(this.config); IndexAccessor indexAccessor = idsLocation.getAccessor(); searcher = indexAccessor.getPrioritizedSearcher(); Object userPermissionsObject = request.get(CRRequest.PERMISSIONS_KEY); String[] userPermissions = new String[0]; if (userPermissionsObject instanceof String[]) { userPermissions = (String[]) userPermissionsObject; } TopDocsCollector<?> collector = createCollector(searcher, hits, sorting, computescores, userPermissions); HashMap<String, Object> result = null; try { analyzer = LuceneAnalyzerFactory.createAnalyzer(this.config); if (searchedAttributes != null && searchedAttributes.length > 0 && query != null && !query.equals("")) { QueryParser parser = CRQueryParserFactory.getConfiguredParser(searchedAttributes, analyzer, request, config); Query parsedQuery = parser.parse(query); // GENERATE A NATIVE QUERY parsedQuery = searcher.rewrite(parsedQuery); result = new HashMap<String, Object>(3); result.put(RESULT_QUERY_KEY, parsedQuery); Map<String, Object> ret = executeSearcher(collector, searcher, parsedQuery, explain, count, start); if (log.isDebugEnabled()) { for (Object res : ret.values()) { if (res instanceof LinkedHashMap) { LinkedHashMap<Document, Float> documents = (LinkedHashMap<Document, Float>) res; if (documents != null) { for (Entry doc : documents.entrySet()) { Document doCument = (Document) doc.getKey(); log.debug("CRSearcher.search: " + doCument.getField("contentid").toString()); } } } } } if (ret != null) { LinkedHashMap<Document, Float> coll = (LinkedHashMap<Document, Float>) ret.get(RESULT_RESULT_KEY); float maxScore = (Float) ret.get(RESULT_MAXSCORE_KEY); result.put(RESULT_RESULT_KEY, coll); int totalhits = collector.getTotalHits(); result.put(RESULT_HITS_KEY, totalhits); result.put(RESULT_MAXSCORE_KEY, maxScore); // PLUG IN DIDYOUMEAN boolean didyoumeanEnabledForRequest = StringUtils.getBoolean(request.get(DIDYOUMEAN_ENABLED_KEY), true); if (start == 0 && didyoumeanenabled && didyoumeanEnabledForRequest && (totalhits <= didyoumeanactivatelimit || didyoumeanactivatelimit == -1 || maxScore < this.didyoumeanminscore)) { HashMap<String, Object> didyoumeanResult = didyoumean( query, parsedQuery, indexAccessor, parser, searcher, sorting, userPermissions); result.putAll(didyoumeanResult); } // PLUG IN DIDYOUMEAN END int size = 0; if (coll != null) { size = coll.size(); } log.debug("Fetched " + size + " objects with query: " + query); } else { result = null; } } } catch (Exception e) { if (config.getBoolean("FAILONMAXCLAUSES")) { log.debug("Error getting the results.", e); throw new CRException(e); } else { log.error("Error getting the results.", e); result = null; } } finally { indexAccessor.release(searcher); } return result; }
public final HashMap<String, Object> search(final String query, final String[] searchedAttributes, final int count, final int start, final boolean explain, final String[] sorting, final CRRequest request) throws IOException, CRException { Searcher searcher; Analyzer analyzer; // Collect count + start hits int hits = count + start; // we want to retreive the startcount (start) to endcount (hits) LuceneIndexLocation idsLocation = LuceneIndexLocation.getIndexLocation(this.config); IndexAccessor indexAccessor = idsLocation.getAccessor(); searcher = indexAccessor.getPrioritizedSearcher(); Object userPermissionsObject = request.get(CRRequest.PERMISSIONS_KEY); String[] userPermissions = new String[0]; if (userPermissionsObject instanceof String[]) { userPermissions = (String[]) userPermissionsObject; } TopDocsCollector<?> collector = createCollector(searcher, hits, sorting, computescores, userPermissions); HashMap<String, Object> result = null; try { analyzer = LuceneAnalyzerFactory.createAnalyzer(this.config); if (searchedAttributes != null && searchedAttributes.length > 0 && query != null && !query.equals("")) { QueryParser parser = CRQueryParserFactory.getConfiguredParser(searchedAttributes, analyzer, request, config); Query parsedQuery = parser.parse(query); // GENERATE A NATIVE QUERY parsedQuery = searcher.rewrite(parsedQuery); result = new HashMap<String, Object>(3); result.put(RESULT_QUERY_KEY, parsedQuery); Map<String, Object> ret = executeSearcher(collector, searcher, parsedQuery, explain, count, start); if (log.isDebugEnabled()) { for (Object res : ret.values()) { if (res instanceof LinkedHashMap) { LinkedHashMap<Document, Float> documents = (LinkedHashMap<Document, Float>) res; if (documents != null) { for (Entry doc : documents.entrySet()) { Document doCument = (Document) doc.getKey(); String contentid = doCument.get("contentid"); log.debug("CRSearcher.search: " + doCument.toString() + " Contentid: " + contentid); } } } } } if (ret != null) { LinkedHashMap<Document, Float> coll = (LinkedHashMap<Document, Float>) ret.get(RESULT_RESULT_KEY); float maxScore = (Float) ret.get(RESULT_MAXSCORE_KEY); result.put(RESULT_RESULT_KEY, coll); int totalhits = collector.getTotalHits(); result.put(RESULT_HITS_KEY, totalhits); result.put(RESULT_MAXSCORE_KEY, maxScore); // PLUG IN DIDYOUMEAN boolean didyoumeanEnabledForRequest = StringUtils.getBoolean(request.get(DIDYOUMEAN_ENABLED_KEY), true); if (start == 0 && didyoumeanenabled && didyoumeanEnabledForRequest && (totalhits <= didyoumeanactivatelimit || didyoumeanactivatelimit == -1 || maxScore < this.didyoumeanminscore)) { HashMap<String, Object> didyoumeanResult = didyoumean( query, parsedQuery, indexAccessor, parser, searcher, sorting, userPermissions); result.putAll(didyoumeanResult); } // PLUG IN DIDYOUMEAN END int size = 0; if (coll != null) { size = coll.size(); } log.debug("Fetched " + size + " objects with query: " + query); } else { result = null; } } } catch (Exception e) { if (config.getBoolean("FAILONMAXCLAUSES")) { log.debug("Error getting the results.", e); throw new CRException(e); } else { log.error("Error getting the results.", e); result = null; } } finally { indexAccessor.release(searcher); } return result; }
diff --git a/atlas-web/src/main/java/ae3/service/structuredquery/AtlasStructuredQueryService.java b/atlas-web/src/main/java/ae3/service/structuredquery/AtlasStructuredQueryService.java index ec25f794e..e8bd40dc5 100644 --- a/atlas-web/src/main/java/ae3/service/structuredquery/AtlasStructuredQueryService.java +++ b/atlas-web/src/main/java/ae3/service/structuredquery/AtlasStructuredQueryService.java @@ -1,1481 +1,1481 @@ /* * Copyright 2008-2010 Microarray Informatics Team, EMBL-European Bioinformatics Institute * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * For further details of the Gene Expression Atlas project, including source code, * downloads and documentation, please see: * * http://gxa.github.com/gxa */ package ae3.service.structuredquery; import ae3.dao.AtlasSolrDAO; import ae3.model.*; import org.apache.solr.common.params.FacetParams; 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.apache.solr.client.solrj.response.FacetField; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.core.CoreContainer; import org.apache.solr.core.SolrCore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import uk.ac.ebi.gxa.index.GeneExpressionAnalyticsTable; import uk.ac.ebi.gxa.efo.Efo; import uk.ac.ebi.gxa.efo.EfoTerm; import uk.ac.ebi.gxa.utils.*; import uk.ac.ebi.gxa.index.builder.IndexBuilderEventHandler; import uk.ac.ebi.gxa.index.builder.IndexBuilder; import uk.ac.ebi.gxa.index.builder.listener.IndexBuilderEvent; import uk.ac.ebi.gxa.properties.AtlasProperties; import uk.ac.ebi.microarray.atlas.model.ExpressionAnalysis; import java.util.*; /** * Structured query support class. The main query engine of the Atlas. * @author pashky */ public class AtlasStructuredQueryService implements IndexBuilderEventHandler, DisposableBean { private static final int MAX_EFV_COLUMNS = 120; final private Logger log = LoggerFactory.getLogger(getClass()); private SolrServer solrServerAtlas; private SolrServer solrServerExpt; private SolrServer solrServerProp; private AtlasProperties atlasProperties; private IndexBuilder indexBuilder; private AtlasEfvService efvService; private AtlasEfoService efoService; private AtlasGenePropertyService genePropService; private AtlasSolrDAO atlasSolrDAO; private CoreContainer coreContainer; private Efo efo; private final Set<String> cacheFill = new HashSet<String>(); private SortedSet<String> allSpecies = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); /** * Hack: prevents OOMs by clearing Lucene field cache by closing the searcher which closes the IndexReader * (it's the only way now if we don't hack Lucene) */ private void controlCache() { if(coreContainer == null) return; synchronized (cacheFill) { if(cacheFill.size() > 500) { SolrCore core = coreContainer.getCore(Constants.CORE_ATLAS); if( core != null ) { core.closeSearcher(); core.close(); } cacheFill.clear(); } } } /** * Adds field to cache watcher (it's supposed to estimate number of fileds which actually end up in Lucene cache, * which we can't check directly) * @param field */ private void notifyCache(String field) { synchronized (cacheFill) { cacheFill.add(field); } } public SolrServer getSolrServerAtlas() { return solrServerAtlas; } public void setSolrServerAtlas(SolrServer solrServerAtlas) { this.solrServerAtlas = solrServerAtlas; } public SolrServer getSolrServerExpt() { return solrServerExpt; } public void setSolrServerExpt(SolrServer solrServerExpt) { this.solrServerExpt = solrServerExpt; } public SolrServer getSolrServerProp() { return solrServerProp; } public void setSolrServerProp(SolrServer solrServerProp) { this.solrServerProp = solrServerProp; } public CoreContainer getCoreContainer() { return coreContainer; } public void setCoreContainer(CoreContainer coreContainer) { this.coreContainer = coreContainer; } public AtlasEfvService getEfvService() { return efvService; } public void setEfvService(AtlasEfvService efvService) { this.efvService = efvService; } public AtlasEfoService getEfoService() { return efoService; } public void setEfoService(AtlasEfoService efoService) { this.efoService = efoService; } public AtlasSolrDAO getAtlasSolrDAO() { return atlasSolrDAO; } public void setAtlasSolrDAO(AtlasSolrDAO atlasSolrDAO) { this.atlasSolrDAO = atlasSolrDAO; } public void setIndexBuilder(IndexBuilder indexBuilder) { this.indexBuilder = indexBuilder; indexBuilder.registerIndexBuildEventHandler(this); } public Efo getEfo() { return efo; } public void setEfo(Efo efo) { this.efo = efo; } public void setGenePropService(AtlasGenePropertyService genePropService) { this.genePropService = genePropService; } public AtlasProperties getAtlasProperties() { return atlasProperties; } public void setAtlasProperties(AtlasProperties atlasProperties) { this.atlasProperties = atlasProperties; } /** * SOLR query builder class. Collects necessary part of SOLR query string as we go through conditions. * Can't use just StringBuilder as we need to maintain two separate chains - query itself and scoring function. * * Can be used as chain of calls as all appendXX() methods return self */ private static class SolrQueryBuilder { /** * Query string */ private StringBuilder solrq = new StringBuilder(); /** * Scoring function string */ private StringBuilder scores = new StringBuilder(); /** * Field suffixes corresponding to query types */ private static final EnumMap<QueryExpression,String> SCORE_EXP_MAP = new EnumMap<QueryExpression,String>(QueryExpression.class); static { SCORE_EXP_MAP.put(QueryExpression.UP, "_up"); SCORE_EXP_MAP.put(QueryExpression.DOWN, "_dn"); SCORE_EXP_MAP.put(QueryExpression.UP_ONLY, "_up"); SCORE_EXP_MAP.put(QueryExpression.DOWN_ONLY, "_dn"); SCORE_EXP_MAP.put(QueryExpression.UP_DOWN, "_ud"); SCORE_EXP_MAP.put(QueryExpression.NON_D_E, "_no"); } /** * Appends AND to query only if it is needed * @return self */ public SolrQueryBuilder appendAnd() { if(solrq.length() > 0) solrq.append(" AND "); return this; } /** * Appends string to query * @param s string * @return self */ public SolrQueryBuilder append(String s) { solrq.append(s); return this; } /** * Appends object to query * @param s object * @return self */ public SolrQueryBuilder append(Object s) { solrq.append(s); return this; } /** * Appends other SB to query * @param s SB * @return self */ public SolrQueryBuilder append(StringBuilder s) { solrq.append(s); return this; } /** * Appends string to score part * @param s string * @return self */ public SolrQueryBuilder appendScore(String s) { if(scores.length() > 0) scores.append(","); scores.append(s); return this; } /** * Appends one field query * @param id field id * @param e query expression * @param minExp minimum number of experiments required * @return self */ public SolrQueryBuilder appendExpFields(String id, QueryExpression e, int minExp) { String minExpS = minExp == 1 ? "*" : String.valueOf(minExp); switch(e) { case UP_ONLY: case UP: solrq.append("cnt_").append(id).append("_up:[").append(minExpS).append(" TO *]"); break; case DOWN_ONLY: case DOWN: solrq.append("cnt_").append(id).append("_dn:[").append(minExpS).append(" TO *]"); break; case UP_DOWN: solrq.append("cnt_").append(id).append("_up:[").append(minExpS).append(" TO *] ") .append("cnt_").append(id).append("_dn:[").append(minExpS).append(" TO *]"); break; case NON_D_E: solrq.append("cnt_").append(id).append("_no:[").append(minExpS).append(" TO *] "); break; default: throw new IllegalArgumentException("Unknown regulation option specified " + e); } return this; } /** * Appends one field to score part * @param id field id * @param e query expression * @return self */ public SolrQueryBuilder appendExpScores(String id, QueryExpression e) { if(scores.length() > 0) scores.append(","); scores.append("s_").append(id).append(SCORE_EXP_MAP.get(e)); return this; } /** * Returns assembled query string * @return string */ @Override public String toString() { StringBuilder sb = new StringBuilder(solrq); if(scores.length() > 0) sb.append(" AND _val_:\"sum(").append(scores).append(")\""); else sb.append(" AND _val_:\"sum(cnt_efo_EFO_0000001_up,cnt_efo_EFO_0000001_dn)\""); return sb.toString(); } /** * Checks if query is empty * @return true or false */ public boolean isEmpty() { return solrq.length() == 0; } } /** * Column information class to be used as paylod in result EFV tree. Base version storing just position * of EFV data in result counters array */ private static class BaseColumnInfo implements ColumnInfo { private int position; private BaseColumnInfo(int position) { this.position = position; } public int getPosition() { return position; } public int compareTo(ColumnInfo o) { return Integer.valueOf(getPosition()).compareTo(o.getPosition()); } public boolean isQualified(UpdownCounter ud) { return !ud.isZero(); } } /** * Extended version of columninfo, checking required minimum number of experiments */ private static class QueryColumnInfo extends BaseColumnInfo { private int minUpExperiments = Integer.MAX_VALUE; private int minDnExperiments = Integer.MAX_VALUE; private int minOrExperiments = Integer.MAX_VALUE; private int minNoExperiments = Integer.MAX_VALUE; private QueryColumnInfo(int position) { super(position); } /** * Update column minimum requirements with provided query information * (to be called on each query condition) * @param expression query expression * @param minExperiments minimum number of experiments for this expression */ public void update(QueryExpression expression, int minExperiments) { switch(expression) { case UP: case UP_ONLY: minUpExperiments = Math.min(minExperiments, this.minUpExperiments); break; case DOWN: case DOWN_ONLY: minDnExperiments = Math.min(minExperiments, this.minDnExperiments); break; case UP_DOWN: minOrExperiments = Math.min(minExperiments, this.minOrExperiments); break; case NON_D_E: minNoExperiments = Math.min(minExperiments, this.minNoExperiments); break; } } /** * Here it checks counter against minimal numbers * @param ud counter * @return true or false */ public boolean isQualified(UpdownCounter ud) { if(ud.getUps() >= minUpExperiments) return true; if(ud.getDowns() >= minDnExperiments) return true; if(ud.getNones() >= minNoExperiments) return true; if(ud.getUps() >= minOrExperiments || ud.getDowns() >= minOrExperiments) return true; return false; } } /** * Internal class to pass query state around methods (the main class itself is stateless hence thread-safe) */ private class QueryState { private final SolrQueryBuilder solrq = new SolrQueryBuilder(); private final EfvTree<ColumnInfo> efvs = new EfvTree<ColumnInfo>(); private final EfoTree<ColumnInfo> efos = new EfoTree<ColumnInfo>(getEfo()); private final Set<String> experiments = new HashSet<String>(); private int num = 0; /** * Column numberer factory used to add new EFV columns into heatmap */ private Maker<ColumnInfo> numberer = new Maker<ColumnInfo>() { public ColumnInfo make() { return new QueryColumnInfo(num++); } }; /** * Returns SOLR query builder * @return solr query builder */ public SolrQueryBuilder getSolrq() { return solrq; } /** * Adds experiment IDs to query * @param ids */ public void addExperiments(Collection<String> ids) { experiments.addAll(ids); } /** * Adds EFV to query EFV tree * @param ef factor * @param efv value * @param minExperiments required minimum number of experiments * @param expression query expression */ public void addEfv(String ef, String efv, int minExperiments, QueryExpression expression) { ((QueryColumnInfo)efvs.getOrCreate(ef, efv, numberer)).update(expression, minExperiments); } /** * Adds EFO accession to query EFO tree * @param id EFO accession * @param minExperiments required minimum number of experiments * @param expression query expression */ public void addEfo(String id, int minExperiments, QueryExpression expression) { for(ColumnInfo ci : efos.add(id, numberer, true)) ((QueryColumnInfo)ci).update(expression, minExperiments); } /** * Returns set of experiments mentioned in the query * @return set of experiment IDs */ public Set<String> getExperiments() { return experiments; } /** * Returns query EFV tree * @return query EFV tree */ public EfvTree<ColumnInfo> getEfvs() { return efvs; } /** * Returns query EFO tree * @return query EFO tree */ public EfoTree<ColumnInfo> getEfos() { return efos; } /** * Checks if query is empty * @return true or false */ public boolean isEmpty() { return solrq.isEmpty(); } /** * Checks if query has any condtion EFV/EFOs * @return */ public boolean hasQueryEfoEfvs() { return efvs.getNumEfvs() + efos.getNumEfos() > 0; } /** * Informative string representing the query * @return string */ @Override public String toString() { return "SOLR query: <" + solrq.toString() + ">, Experiments: [" + StringUtils.join(experiments, ", ") + "]"; } } /** * Process structured Atlas query * @param query parsed query * @return matching results * @throws java.io.IOException */ public AtlasStructuredQueryResult doStructuredAtlasQuery(final AtlasStructuredQuery query) { final QueryState qstate = new QueryState(); final Iterable<ExpFactorResultCondition> conditions = appendEfvsQuery(query, qstate); appendGeneQuery(query, qstate.getSolrq()); appendSpeciesQuery(query, qstate.getSolrq()); log.info("Structured query for " + query.getApiUrl() + ": " + qstate.toString()); AtlasStructuredQueryResult result = new AtlasStructuredQueryResult(query.getStart(), query.getRowsPerPage(), query.getExpsPerGene()); result.setConditions(conditions); if(!qstate.isEmpty()) { try { controlCache(); SolrQuery q = setupSolrQuery(query, qstate); QueryResponse response = solrServerAtlas.query(q); processResultGenes(response, result, qstate, query); Set<String> expandableEfs = new HashSet<String>(); EfvTree<ColumnInfo> trimmedEfvs = trimColumns(query, result, expandableEfs); result.setResultEfvs(trimmedEfvs); result.setExpandableEfs(expandableEfs); if(response.getFacetFields() != null) { result.setEfvFacet(getEfvFacet(response, qstate)); for(String p : genePropService.getDrilldownProperties()) { Set<String> hasVals = new HashSet<String>(); for(GeneQueryCondition qc : query.getGeneConditions()) if(qc.getFactor().equals(p)) hasVals.addAll(qc.getFactorValues()); Iterable<FacetCounter> facet = getGeneFacet(response, "property_f_" + p, hasVals); if(facet.iterator().hasNext()) result.setGeneFacet(p, facet); } if(!query.getSpecies().iterator().hasNext()) result.setGeneFacet("species", getGeneFacet(response, "species", new HashSet<String>())); } } catch (SolrServerException e) { log.error("Error in structured query!", e); } } return result; } /** * Returns list of genes found for particular experiment * @param geneIds list of gene conditions * @param experimentId experiment id to search * @param start start position * @param rows number of rows to return * @return list of result rows */ public List<ListResultRow> findGenesForExperiment(Object geneIds, long experimentId, int start, int rows) { AtlasStructuredQueryResult result = doStructuredAtlasQuery(new AtlasStructuredQueryBuilder() .andGene(geneIds) .andUpdnIn(Constants.EXP_FACTOR_NAME, String.valueOf(experimentId)) .viewAs(ViewType.LIST) .rowsPerPage(rows) .startFrom(start) .expsPerGene(atlasProperties.getQueryExperimentsPerGene()).query()); List<ListResultRow> res = new ArrayList<ListResultRow>(); for(AtlasStructuredQueryResult.ListResultGene gene : result.getListResultsGenes()) { ListResultRow minRow = null; float minPvalue = 1; for(ListResultRow row : gene.getExpressions()) { float pvalue = 1; for(ListResultRowExperiment e : row.getExp_list()) { if(e.getExperimentId() == experimentId) { pvalue = e.getPvalue(); row.setExp_list(Collections.singleton(e)); break; } } if(minRow == null || pvalue < minPvalue) { minRow = row; minPvalue = pvalue; } } if(minRow != null) res.add(minRow); } return res; } /** * Trims factors to contain only small amount of EFVs if too many of them were requested * User can ask to expand some of them * @param query query to process * @param result result to process * @param expandableEfs which EFs to expand in result * @return trimmed result EFV tree */ private EfvTree<ColumnInfo> trimColumns(final AtlasStructuredQuery query, final AtlasStructuredQueryResult result, Collection<String> expandableEfs) { final Set<String> expand = query.getExpandColumns(); EfvTree<ColumnInfo> trimmedEfvs = new EfvTree<ColumnInfo>(result.getResultEfvs()); if(expand.contains("*")) return trimmedEfvs; if(trimmedEfvs.getNumEfvs() < MAX_EFV_COLUMNS) return trimmedEfvs; int threshold = MAX_EFV_COLUMNS / trimmedEfvs.getNumEfs(); for(EfvTree.Ef<ColumnInfo> ef : trimmedEfvs.getNameSortedTree()) { if(expand.contains(ef.getEf()) || ef.getEfvs().size() < threshold) continue; Map<EfvTree.Efv<ColumnInfo>,Double> scores = new HashMap<EfvTree.Efv<ColumnInfo>,Double>(); for(EfvTree.Efv<ColumnInfo> efv : ef.getEfvs()) scores.put(efv, 0.0); for(StructuredResultRow row : result.getResults()) { for(EfvTree.Efv<ColumnInfo> efv : ef.getEfvs()) { UpdownCounter c = row.getCounters().get(efv.getPayload().getPosition()); scores.put(efv, scores.get(efv) + c.getDowns() * (1.0 - c.getMpvDn()) + c.getUps() * (1.0 - c.getMpvUp())); } } @SuppressWarnings("unchecked") Map.Entry<EfvTree.Efv<ColumnInfo>,Double>[] scoreset = scores.entrySet().toArray(new Map.Entry[1]); Arrays.sort(scoreset, new Comparator<Map.Entry<EfvTree.Efv<ColumnInfo>,Double>>() { public int compare(Map.Entry<EfvTree.Efv<ColumnInfo>, Double> o1, Map.Entry<EfvTree.Efv<ColumnInfo>, Double> o2) { return o2.getValue().compareTo(o1.getValue()); } }); for(int i = threshold; i < scoreset.length; ++i) { trimmedEfvs.removeEfv(ef.getEf(), scoreset[i].getKey().getEfv()); expandableEfs.add(ef.getEf()); } } return trimmedEfvs; } /** * Finds experiment by search string * @param query search strings * @param condEfvs EFV tree to fill with EFVs mentioned in experiment * @return collection of found experiment IDs * @throws SolrServerException */ private Collection<String> findExperiments(String query, EfvTree<Boolean> condEfvs) throws SolrServerException { List<String> result = new ArrayList<String>(); if(query.length() == 0) return result; SolrQuery q = new SolrQuery("id:(" + query + ") accession:(" + query + ")"); q.addField("*"); q.setRows(50); q.setStart(0); QueryResponse qr = solrServerExpt.query(q); for(SolrDocument doc : qr.getResults()) { String id = String.valueOf(doc.getFieldValue("id")); if(id != null) { result.add(id); for(String name : doc.getFieldNames()) if(name.startsWith("a_property_")) for(Object val : doc.getFieldValues(name)) condEfvs.put(name.substring("a_property_".length()), String.valueOf(val), true); } } return result; } /** * Returns experiment query part from provided IDs and query expression * @param ids experiment IDs * @param e query expression * @return string builder with query part to be fed to SolrQueryBuilder */ private StringBuilder makeExperimentsQuery(Iterable<String> ids, QueryExpression e) { StringBuilder sb = new StringBuilder(); String idss = StringUtils.join(ids.iterator(), " "); if(idss.length() == 0) return sb; switch(e) { case UP: sb.append("exp_up_ids:(").append(idss).append(") "); break; case DOWN: sb.append("exp_dn_ids:(").append(idss).append(") "); break; case UP_DOWN: sb.append("exp_ud_ids:(").append(idss).append(") "); break; case NON_D_E: sb.append("exp_no_ids:(").append(idss).append(") "); break; } return sb; } /** * Appends conditions part of the query to query state. Finds mathcing EFVs/EFOs and appends them to SOLR query string. * @param query query * @param qstate state * @return iterable conditions resulted from this append */ private Iterable<ExpFactorResultCondition> appendEfvsQuery(final AtlasStructuredQuery query, final QueryState qstate) { final List<ExpFactorResultCondition> conds = new ArrayList<ExpFactorResultCondition>(); SolrQueryBuilder solrq = qstate.getSolrq(); for(ExpFactorQueryCondition c : query.getConditions()) { boolean isExperiment = Constants.EXP_FACTOR_NAME.equals(c.getFactor()); if(c.isAnything() || (isExperiment && c.isAnyValue())) { // do nothing } else if(c.isOnly() && !c.isAnyFactor() && !Constants.EFO_FACTOR_NAME.equals(c.getFactor()) && !Constants.EXP_FACTOR_NAME.equals(c.getFactor())) { try { EfvTree<Boolean> condEfvs = getCondEfvsForFactor(c.getFactor(), c.getFactorValues()); EfvTree<Boolean> allEfvs = getCondEfvsAllForFactor(c.getFactor()); if(condEfvs.getNumEfs() + allEfvs.getNumEfs() > 0) { solrq.appendAnd().append("(("); for(EfvTree.EfEfv<Boolean> condEfv : condEfvs.getNameSortedList()) { solrq.append(" "); String efefvId = condEfv.getEfEfvId(); solrq.appendExpFields(efefvId, c.getExpression(), c.getMinExperiments()); solrq.appendExpScores(efefvId, c.getExpression()); notifyCache(efefvId + c.getExpression()); qstate.addEfv(condEfv.getEf(), condEfv.getEfv(), c.getMinExperiments(), c.getExpression()); } solrq.append(")"); for(EfvTree.EfEfv<Boolean> allEfv : allEfvs.getNameSortedList()) if(!condEfvs.has(allEfv.getEf(), allEfv.getEfv())) { String efefvId = allEfv.getEfEfvId(); solrq.append(" AND NOT ("); solrq.appendExpFields(efefvId, c.getExpression(), 1); solrq.append(")"); notifyCache(efefvId + c.getExpression()); qstate.addEfv(allEfv.getEf(), allEfv.getEfv(), 1, QueryExpression.UP_DOWN); } solrq.append(")"); conds.add(new ExpFactorResultCondition(c, Collections.<List<AtlasEfoService.EfoTermCount>>emptyList(), false)); } } catch (SolrServerException e) { log.error("Error querying Atlas index", e); } } else { try { boolean nonemptyQuery = false; EfvTree<Boolean> condEfvs = isExperiment ? new EfvTree<Boolean>() : getConditionEfvs(c); if(condEfvs.getNumEfs() > 0) { solrq.appendAnd().append("("); int i = 0; for(EfvTree.EfEfv<Boolean> condEfv : condEfvs.getNameSortedList()) { if(++i > 100) break; solrq.append(" "); String efefvId = condEfv.getEfEfvId(); solrq.appendExpFields(efefvId, c.getExpression(), c.getMinExperiments()); solrq.appendExpScores(efefvId, c.getExpression()); notifyCache(efefvId + c.getExpression()); if(Constants.EFO_FACTOR_NAME.equals(condEfv.getEf())) { qstate.addEfo(condEfv.getEfv(), c.getMinExperiments(), c.getExpression()); } else { qstate.addEfv(condEfv.getEf(), condEfv.getEfv(), c.getMinExperiments(), c.getExpression()); } } solrq.append(")"); nonemptyQuery = true; } else if(c.isAnyFactor() || isExperiment) { // try to search for experiment too if no matching conditions are found Collection<String> experiments = findExperiments(c.getSolrEscapedFactorValues(), condEfvs); qstate.addExperiments(experiments); StringBuilder expq = makeExperimentsQuery(experiments, c.getExpression()); if(expq.length() > 0) { for(EfvTree.EfEfv<Boolean> condEfv : condEfvs.getNameSortedList()) { qstate.addEfv(condEfv.getEf(), condEfv.getEfv(), c.getMinExperiments(), c.getExpression()); solrq.appendExpScores(condEfv.getEfEfvId(), c.getExpression()); } solrq.appendAnd().append(expq); nonemptyQuery = true; } } Collection<List<AtlasEfoService.EfoTermCount>> efoPaths = new ArrayList<List<AtlasEfoService.EfoTermCount>>(); Collection<EfvTree.Efv<Boolean>> condEfos = condEfvs.getEfvs(Constants.EFO_FACTOR_NAME); for(EfvTree.Efv<Boolean> efv : condEfos) { efoPaths.addAll(efoService.getTermParentPaths(efv.getEfv())); } conds.add(new ExpFactorResultCondition(c, efoPaths, !nonemptyQuery)); } catch (SolrServerException e) { log.error("Error querying Atlas index", e); } } } return conds; } /** * Appends gene part of the query. Parses query condtions and appends them to SOLR query string. * @param query query * @param solrq solr query */ private void appendGeneQuery(AtlasStructuredQuery query, SolrQueryBuilder solrq) { for(GeneQueryCondition geneQuery : query.getGeneConditions()) { solrq.appendAnd(); if(geneQuery.isNegated()) solrq.append(" NOT "); String escapedQ = geneQuery.getSolrEscapedFactorValues(); if(geneQuery.isAnyFactor()) { solrq.append("(name:(").append(escapedQ).append(") species:(").append(escapedQ) .append(") identifier:(").append(escapedQ).append(") id:(").append(escapedQ).append(")"); for(String p : genePropService.getIdNameDescProperties()) solrq.append(" property_").append(p).append(":(").append(escapedQ).append(")"); solrq.append(") "); } else if(Constants.GENE_PROPERTY_NAME.equals(geneQuery.getFactor())) { solrq.append("(name:(").append(escapedQ).append(") "); solrq.append("identifier:(").append(escapedQ).append(") "); solrq.append("id:(").append(escapedQ).append(") "); for(String nameProp : genePropService.getNameProperties()) solrq.append("property_" + nameProp + ":(").append(escapedQ).append(") "); solrq.append(")"); } else if(genePropService.getDescProperties().contains(geneQuery.getFactor()) || genePropService.getIdProperties().contains(geneQuery.getFactor())) { String field = "property_" + geneQuery.getFactor(); solrq.append(field).append(":(").append(escapedQ).append(")"); } } } /** * Appends species part of the query to SOLR query * @param query query * @param solrq solr query */ private void appendSpeciesQuery(AtlasStructuredQuery query, SolrQueryBuilder solrq) { Set<String> species = new HashSet<String>(); for(String s : query.getSpecies()) for(String as : getSpeciesOptions()) if(as.toLowerCase().contains(s.toLowerCase())) species.add(as); if(!species.isEmpty()) { solrq.appendAnd().append("species:(").append(EscapeUtil.escapeSolrValueList(species)).append(")"); } } /** * Returns tree of EFO/EFVs matching one specified query condition * EFOs are stored under "magic" factor named "efo" at this point, they will go to EfoTree later * * This is dispatcher function calling one of specific for several query condtion cases. See the code. * * @param c condition * @return tree of EFVs/EFO * @throws SolrServerException */ private EfvTree<Boolean> getConditionEfvs(QueryCondition c) throws SolrServerException { if(c.isAnyValue()) return getCondEfvsAllForFactor(c.getFactor()); if(c.isAnyFactor()) return getCondEfvsForFactor(null, c.getFactorValues()); return getCondEfvsForFactor(c.getFactor(), c.getFactorValues()); } /** * Returns all EFVs/EFOs for specified factor * @param factor factor * @return tree of EFVs/EFO */ private EfvTree<Boolean> getCondEfvsAllForFactor(String factor) { EfvTree<Boolean> condEfvs = new EfvTree<Boolean>(); if(Constants.EFO_FACTOR_NAME.equals(factor)) { Efo efo = getEfo(); int i = 0; for (String v : efo.getRootIds()) { condEfvs.put(Constants.EFO_FACTOR_NAME, v, true); if (++i >= MAX_EFV_COLUMNS) { break; } } } else { int i = 0; for (String v : efvService.listAllValues(factor)) { condEfvs.put(factor, v, true); if (++i >= MAX_EFV_COLUMNS) { break; } } } return condEfvs; } /** * Returns matching EFVs/EFOs for factor * @param factor factor * @param values values search strings * @return tree of EFVs/EFO * @throws SolrServerException */ private EfvTree<Boolean> getCondEfvsForFactor(final String factor, final Iterable<String> values) throws SolrServerException { EfvTree<Boolean> condEfvs = new EfvTree<Boolean>(); if(Constants.EFO_FACTOR_NAME.equals(factor) || null == factor) { Efo efo = getEfo(); for(String v : values) { for(EfoTerm term : efo.searchTerm(EscapeUtil.escapeSolr(v))) { condEfvs.put(Constants.EFO_FACTOR_NAME, term.getId(), true); } } } if(Constants.EFO_FACTOR_NAME.equals(factor)) return condEfvs; String queryString = EscapeUtil.escapeSolrValueList(values); if(factor != null) queryString = "(" + queryString + ") AND property:" + EscapeUtil.escapeSolr(factor); SolrQuery q = new SolrQuery(queryString); q.setRows(10000); q.setStart(0); q.setFields("*"); QueryResponse qr = solrServerProp.query(q); for(SolrDocument doc : qr.getResults()) { String ef = (String)doc.getFieldValue("property"); String efv = (String)doc.getFieldValue("value"); condEfvs.put(ef, efv, true); } return condEfvs; } /** * Processes SOLR query response and generates Atlas structured query result * @param response SOLR response * @param result ATlas result * @param qstate query state * @param query query itself * @throws SolrServerException */ private void processResultGenes(QueryResponse response, AtlasStructuredQueryResult result, QueryState qstate, AtlasStructuredQuery query) throws SolrServerException { SolrDocumentList docs = response.getResults(); result.setTotal(docs.getNumFound()); EfvTree<ColumnInfo> resultEfvs = new EfvTree<ColumnInfo>(); EfoTree<ColumnInfo> resultEfos = qstate.getEfos(); Iterable<EfvTree.EfEfv<ColumnInfo>> efvList = qstate.getEfvs().getValueSortedList(); Iterable<EfoTree.EfoItem<ColumnInfo>> efoList = qstate.getEfos().getValueOrderedList(); boolean hasQueryEfvs = qstate.hasQueryEfoEfvs(); Maker<ColumnInfo> numberer = new Maker<ColumnInfo>() { private int num = 0; public ColumnInfo make() { return new BaseColumnInfo(num++); } }; Collection<String> autoFactors = query.isFullHeatmap() ? efvService.getAllFactors() : efvService.getAnyConditionFactors(); for(SolrDocument doc : docs) { Integer id = (Integer)doc.getFieldValue("id"); if(id == null) continue; Map<Long,List<Long>> experiments = new HashMap<Long,List<Long>>(); AtlasGene gene = new AtlasGene(doc); if(response.getHighlighting() != null) gene.setGeneHighlights(response.getHighlighting().get(id.toString())); List<UpdownCounter> counters = new ArrayList<UpdownCounter>() { @Override public UpdownCounter get(int index) { if(index < size()) return super.get(index); else return new UpdownCounter(0, 0, 0, 0, 0); } }; if(!hasQueryEfvs && query.getViewType() != ViewType.LIST) { int threshold = 0; if(!query.isFullHeatmap()) { if(resultEfos.getNumExplicitEfos() > 0) threshold = 1; else if(resultEfos.getNumExplicitEfos() > 20) threshold = 3; } for(ExpressionAnalysis ea : gene.getExpressionAnalyticsTable().getAll()) { if(ea.isNo()) continue; if(autoFactors.contains(ea.getEfName())) resultEfvs.getOrCreate(ea.getEfName(), ea.getEfvName(), numberer); if(!experiments.containsKey(ea.getEfvId())) experiments.put(ea.getEfvId(), new ArrayList<Long>()); experiments.get(ea.getEfvId()).add(ea.getExperimentID()); for(String efo : ea.getEfoAccessions()) - if(EscapeUtil.nullzero((Number)doc.getFieldValue("cnt_efo_" + EscapeUtil.encode(efo) + "_s_ud")) > threshold) + if(EscapeUtil.nullzero((Number)doc.getFieldValue("cnt_efo_" + EscapeUtil.encode(efo) + "_s_up")) > threshold) resultEfos.add(efo, numberer, false); } efvList = resultEfvs.getValueSortedList(); efoList = resultEfos.getValueOrderedList(); } Iterator<EfvTree.EfEfv<ColumnInfo>> itEfv = efvList.iterator(); Iterator<EfoTree.EfoItem<ColumnInfo>> itEfo = efoList.iterator(); EfvTree.EfEfv<ColumnInfo> efv = null; EfoTree.EfoItem<ColumnInfo> efo = null; while(itEfv.hasNext() || itEfo.hasNext() || efv != null || efo != null) { if(itEfv.hasNext() && efv == null) efv = itEfv.next(); if(itEfo.hasNext() && efo == null) efo = itEfo.next(); if(efv!=null) efv.setExperiments(experiments.get(efv.getEfEfvId())); String cellId; boolean usingEfv = efo == null || (efv != null && efv.getPayload().compareTo(efo.getPayload()) < 0); if(usingEfv) { cellId = efv.getEfEfvId(); } else { cellId = EscapeUtil.encode("efo", efo.getId()); } UpdownCounter counter = new UpdownCounter( EscapeUtil.nullzero((Number)doc.getFieldValue("cnt_" + cellId + "_up")), EscapeUtil.nullzero((Number)doc.getFieldValue("cnt_" + cellId + "_dn")), EscapeUtil.nullzero((Number)doc.getFieldValue("cnt_" + cellId + "_no")), EscapeUtil.nullzerof((Number)doc.getFieldValue("minpval_" + cellId + "_up")), EscapeUtil.nullzerof((Number)doc.getFieldValue("minpval_" + cellId + "_dn"))); counters.add(counter); boolean nonZero = (counter.getUps() + counter.getDowns() + counter.getNones() > 0); if (usingEfv) { if (hasQueryEfvs && efv.getPayload().isQualified(counter)) resultEfvs.put(efv); efv = null; } else { if (nonZero) resultEfos.mark(efo.getId()); efo = null; } } if(query.getViewType() == ViewType.LIST) { loadListExperiments(result, gene, resultEfvs, resultEfos, qstate.getExperiments()); } result.addResult(new StructuredResultRow(gene, counters)); } result.setResultEfvs(resultEfvs); result.setResultEfos(resultEfos); log.info("Retrieved query completely: " + result.getSize() + " records of " + result.getTotal() + " total starting from " + result.getStart() ); log.debug("Resulting EFVs are: " + resultEfvs); log.debug("Resulting EFOs are: " + resultEfos); } /** * Loads experiments data for list view * @param result atlas result * @param efvTree result efv tree * @param efoTree result efo tree * @param experiments query experiments */ private void loadListExperiments(AtlasStructuredQueryResult result, AtlasGene gene, final EfvTree<ColumnInfo> efvTree, final EfoTree<ColumnInfo> efoTree, Set<String> experiments) { Iterable<ExpressionAnalysis> exps = null; GeneExpressionAnalyticsTable table = gene.getExpressionAnalyticsTable(); if(efvTree.getNumEfvs() + efoTree.getNumExplicitEfos() > 0) { Iterable<String> efviter = new Iterable<String>() { public Iterator<String> iterator() { return new MappingIterator<EfvTree.EfEfv<ColumnInfo>, String>(efvTree.getNameSortedList().iterator()) { public String map(EfvTree.EfEfv<ColumnInfo> efEfv) { return efEfv.getEfEfvId(); } }; } }; Iterable<String> efoiter = new Iterable<String>() { public Iterator<String> iterator() { return new Iterator<String>() { private Iterator<String> explit = efoTree.getExplicitEfos().iterator(); private Iterator<String> childit; public boolean hasNext() { return explit.hasNext() || (childit != null && childit.hasNext()); } public String next() { if(childit != null) { String r = childit.next(); if(!childit.hasNext() && explit.hasNext()) childit = getEfo().getTermAndAllChildrenIds(explit.next()).iterator(); return r; } else { childit = getEfo().getTermAndAllChildrenIds(explit.next()).iterator(); return next(); } } public void remove() { } }; } }; exps = table.findByEfEfvEfoSet(efviter, efoiter); } else { exps = table.getAll(); } Map<Pair<String,String>,List<ListResultRowExperiment>> map = new HashMap<Pair<String,String>, List<ListResultRowExperiment>>(); for(ExpressionAnalysis exp : exps) { if(!experiments.isEmpty() && !experiments.contains(String.valueOf(exp.getExperimentID()))) continue; AtlasExperiment aexp = atlasSolrDAO.getExperimentById(exp.getExperimentID()); if(aexp != null) { Pair<String,String> key = new Pair<String,String>(exp.getEfName(), exp.getEfvName()); if(!map.containsKey(key)) map.put(key, new ArrayList<ListResultRowExperiment>()); map.get(key).add(new ListResultRowExperiment(exp.getExperimentID(), aexp.getAccession(), aexp.getDescription(), exp.getPValAdjusted(), exp.isNo() ? Expression.NONDE : (exp.isUp() ? Expression.UP : Expression.DOWN)) ); } } int listRowsPerGene = 0; for(Map.Entry<Pair<String,String>,List<ListResultRowExperiment>> e : map.entrySet()) { if(listRowsPerGene++ >= result.getRowsPerGene()) break; int cup = 0, cdn = 0, cno = 0; float pup = 1, pdn = 1; for(ListResultRowExperiment exp : e.getValue()) if(exp.getUpdn().isNo()) ++cno; else if(exp.getUpdn().isUp()) { ++cup; pup = Math.min(pup, exp.getPvalue()); } else { ++cdn; pdn = Math.min(pdn, exp.getPvalue()); } ListResultRow row = new ListResultRow(e.getKey().getFirst(), e.getKey().getSecond(), cup, cdn, cno, pup, pdn); row.setGene(gene); Collections.sort(e.getValue(), new Comparator<ListResultRowExperiment>() { public int compare(ListResultRowExperiment o1, ListResultRowExperiment o2) { return Float.valueOf(o1.getPvalue()).compareTo(o2.getPvalue()); } }); row.setExp_list(e.getValue()); result.addListResult(row); } } /** * Creates SOLR query from atlas query * @param query query * @param qstate query state * @return solr query object */ private SolrQuery setupSolrQuery(AtlasStructuredQuery query, QueryState qstate) { SolrQuery q = new SolrQuery(qstate.getSolrq().toString()); q.setRows(query.getRowsPerPage()); q.setStart(query.getStart()); q.setSortField("score", SolrQuery.ORDER.desc); q.setFacet(true); int max = 0; if(qstate.hasQueryEfoEfvs()) { for(EfvTree.Ef<ColumnInfo> ef : qstate.getEfvs().getNameSortedTree()) { if(max < ef.getEfvs().size()) max = ef.getEfvs().size(); for(EfvTree.Efv<ColumnInfo> efv : ef.getEfvs()) { q.addField("cnt_" + EscapeUtil.encode(ef.getEf(), efv.getEfv()) + "_up"); q.addField("cnt_" + EscapeUtil.encode(ef.getEf(), efv.getEfv()) + "_dn"); q.addField("cnt_" + EscapeUtil.encode(ef.getEf(), efv.getEfv()) + "_no"); q.addField("minpval_" + EscapeUtil.encode(ef.getEf(), efv.getEfv()) + "_up"); q.addField("minpval_" + EscapeUtil.encode(ef.getEf(), efv.getEfv()) + "_dn"); } } if (max < qstate.getEfos().getNumEfos()) { max = qstate.getEfos().getNumEfos(); } for(String id : qstate.getEfos().getEfoIds()) { String ide = EscapeUtil.encode(id); q.addField("cnt_efo_" + ide + "_up"); q.addField("cnt_efo_" + ide + "_dn"); q.addField("cnt_efo_" + ide + "_no"); q.addField("minpval_efo_" + ide + "_up"); q.addField("minpval_efo_" + ide + "_dn"); } q.addField("score"); q.addField("id"); q.addField("name"); q.addField("identifier"); q.addField("species"); q.addField("exp_info"); for(String p : genePropService.getIdNameDescProperties()) q.addField("property_" + p); } else { q.addField("*"); } q.setFacetLimit(5 + max); q.setFacetMinCount(2); q.setFacetSort(FacetParams.FACET_SORT_COUNT); for(String p : genePropService.getDrilldownProperties()) { q.addFacetField("property_f_" + p); } q.addFacetField("species"); q.addFacetField("exp_up_ids"); q.addFacetField("exp_dn_ids"); for(String ef : efvService.getFacetFactors()) { q.addFacetField("efvs_up_" + ef); q.addFacetField("efvs_dn_" + ef); } q.setHighlight(true); q.setHighlightSnippets(100); q.setParam("hl.usePhraseHighlighter", "true"); q.setParam("hl.mergeContiguous", "true"); q.setHighlightRequireFieldMatch(true); q.addHighlightField("id"); q.addHighlightField("name"); q.addHighlightField("synonym"); q.addHighlightField("identifier"); for(String p : genePropService.getIdNameDescProperties()) q.addHighlightField("property_" + p); return q; } /** * Retrieves gene facets from SOLR response * @param response solr response * @param name field name to exptract * @param values query values (to clear off the facet) * @return iterable collection of facet values with counters */ private Iterable<FacetCounter> getGeneFacet(QueryResponse response, final String name, Set<String> values) { List<FacetCounter> facet = new ArrayList<FacetCounter>(); FacetField ff = response.getFacetField(name); if(ff == null || ff.getValueCount() < 2 || ff.getValues() == null) return new ArrayList<FacetCounter>(); for (FacetField.Count ffc : ff.getValues()) if(!values.contains(ffc.getName())) facet.add(new FacetCounter(ffc.getName(), (int)ffc.getCount())); if(facet.size() < 2) return new ArrayList<FacetCounter>(); Collections.sort(facet); return facet.subList(0, Math.min(facet.size(), 5)); } /** * Retrieves EFVs facets tree * @param response solr response * @param qstate query state * @return efvtree of facet counters */ private EfvTree<FacetUpDn> getEfvFacet(QueryResponse response, QueryState qstate) { EfvTree<FacetUpDn> efvFacet = new EfvTree<FacetUpDn>(); Maker<FacetUpDn> creator = new Maker<FacetUpDn>() { public FacetUpDn make() { return new FacetUpDn(); } }; for (FacetField ff : response.getFacetFields()) { if(ff.getValueCount() > 1) { if(ff.getName().startsWith("efvs_")) { String ef = ff.getName().substring(8); for (FacetField.Count ffc : ff.getValues()) { if(!qstate.efvs.has(ef, ffc.getName())) { int count = (int)ffc.getCount(); efvFacet.getOrCreate(ef, ffc.getName(), creator) .add(count, ff.getName().substring(5,7).equals("up")); } } } else if(ff.getName().startsWith("exp_")) { for (FacetField.Count ffc : ff.getValues()) if(!qstate.getExperiments().contains(ffc.getName())) { AtlasExperiment exp = atlasSolrDAO.getExperimentById(ffc.getName()); if(exp != null) { String expName = exp.getAccession(); if(expName != null) { int count = (int)ffc.getCount(); efvFacet.getOrCreate(Constants.EXP_FACTOR_NAME, expName, creator) .add(count, ff.getName().substring(4,6).equals("up")); } } } } } } return efvFacet; } /** * Returns set of experimental factor for drop-down, fileterd by config * @return set of strings representing experimental factors */ public Collection<String> getExperimentalFactorOptions() { List<String> factors = new ArrayList<String>(); factors.addAll(efvService.getOptionsFactors()); factors.add(Constants.EXP_FACTOR_NAME); Collections.sort(factors, new Comparator<String>() { public int compare(String o1, String o2) { return atlasProperties.getCuratedEf(o1).compareToIgnoreCase(atlasProperties.getCuratedGeneProperty(o2)); } }); return factors; } /** * Returns list of available gene property options sorted by curated value * @return list of strings */ public List<String> getGenePropertyOptions() { List<String> result = new ArrayList<String>(); for(String v : genePropService.getIdNameDescProperties()) result.add(v); result.add(Constants.GENE_PROPERTY_NAME); Collections.sort(result, new Comparator<String>() { public int compare(String o1, String o2) { return atlasProperties.getCuratedGeneProperty(o1).compareToIgnoreCase(atlasProperties.getCuratedGeneProperty(o2)); } }); return result; } /** * Returns list of available species * @return list of species strings */ public SortedSet<String> getSpeciesOptions() { if(allSpecies.isEmpty()) { SolrQuery q = new SolrQuery("*:*"); q.setRows(0); q.addFacetField("species"); q.setFacet(true); q.setFacetLimit(-1); q.setFacetMinCount(1); q.setFacetSort(FacetParams.FACET_SORT_COUNT); try { QueryResponse qr = solrServerAtlas.query(q); if (qr.getFacetFields().get(0).getValues() != null) { for (FacetField.Count ffc : qr.getFacetFields().get(0).getValues()) { allSpecies.add(ffc.getName()); } } } catch(SolrServerException e) { throw new RuntimeException("Can't fetch all factors", e); } } return allSpecies; } /** * Index rebuild notification handler * @param builder builder * @param event event */ public void onIndexBuildFinish(IndexBuilder builder, IndexBuilderEvent event) { allSpecies.clear(); } public void onIndexBuildStart(IndexBuilder builder) { } /** * Destructor called by Spring * @throws Exception */ public void destroy() throws Exception { if(indexBuilder != null) indexBuilder.unregisterIndexBuildEventHandler(this); } }
true
true
private void processResultGenes(QueryResponse response, AtlasStructuredQueryResult result, QueryState qstate, AtlasStructuredQuery query) throws SolrServerException { SolrDocumentList docs = response.getResults(); result.setTotal(docs.getNumFound()); EfvTree<ColumnInfo> resultEfvs = new EfvTree<ColumnInfo>(); EfoTree<ColumnInfo> resultEfos = qstate.getEfos(); Iterable<EfvTree.EfEfv<ColumnInfo>> efvList = qstate.getEfvs().getValueSortedList(); Iterable<EfoTree.EfoItem<ColumnInfo>> efoList = qstate.getEfos().getValueOrderedList(); boolean hasQueryEfvs = qstate.hasQueryEfoEfvs(); Maker<ColumnInfo> numberer = new Maker<ColumnInfo>() { private int num = 0; public ColumnInfo make() { return new BaseColumnInfo(num++); } }; Collection<String> autoFactors = query.isFullHeatmap() ? efvService.getAllFactors() : efvService.getAnyConditionFactors(); for(SolrDocument doc : docs) { Integer id = (Integer)doc.getFieldValue("id"); if(id == null) continue; Map<Long,List<Long>> experiments = new HashMap<Long,List<Long>>(); AtlasGene gene = new AtlasGene(doc); if(response.getHighlighting() != null) gene.setGeneHighlights(response.getHighlighting().get(id.toString())); List<UpdownCounter> counters = new ArrayList<UpdownCounter>() { @Override public UpdownCounter get(int index) { if(index < size()) return super.get(index); else return new UpdownCounter(0, 0, 0, 0, 0); } }; if(!hasQueryEfvs && query.getViewType() != ViewType.LIST) { int threshold = 0; if(!query.isFullHeatmap()) { if(resultEfos.getNumExplicitEfos() > 0) threshold = 1; else if(resultEfos.getNumExplicitEfos() > 20) threshold = 3; } for(ExpressionAnalysis ea : gene.getExpressionAnalyticsTable().getAll()) { if(ea.isNo()) continue; if(autoFactors.contains(ea.getEfName())) resultEfvs.getOrCreate(ea.getEfName(), ea.getEfvName(), numberer); if(!experiments.containsKey(ea.getEfvId())) experiments.put(ea.getEfvId(), new ArrayList<Long>()); experiments.get(ea.getEfvId()).add(ea.getExperimentID()); for(String efo : ea.getEfoAccessions()) if(EscapeUtil.nullzero((Number)doc.getFieldValue("cnt_efo_" + EscapeUtil.encode(efo) + "_s_ud")) > threshold) resultEfos.add(efo, numberer, false); } efvList = resultEfvs.getValueSortedList(); efoList = resultEfos.getValueOrderedList(); } Iterator<EfvTree.EfEfv<ColumnInfo>> itEfv = efvList.iterator(); Iterator<EfoTree.EfoItem<ColumnInfo>> itEfo = efoList.iterator(); EfvTree.EfEfv<ColumnInfo> efv = null; EfoTree.EfoItem<ColumnInfo> efo = null; while(itEfv.hasNext() || itEfo.hasNext() || efv != null || efo != null) { if(itEfv.hasNext() && efv == null) efv = itEfv.next(); if(itEfo.hasNext() && efo == null) efo = itEfo.next(); if(efv!=null) efv.setExperiments(experiments.get(efv.getEfEfvId())); String cellId; boolean usingEfv = efo == null || (efv != null && efv.getPayload().compareTo(efo.getPayload()) < 0); if(usingEfv) { cellId = efv.getEfEfvId(); } else { cellId = EscapeUtil.encode("efo", efo.getId()); } UpdownCounter counter = new UpdownCounter( EscapeUtil.nullzero((Number)doc.getFieldValue("cnt_" + cellId + "_up")), EscapeUtil.nullzero((Number)doc.getFieldValue("cnt_" + cellId + "_dn")), EscapeUtil.nullzero((Number)doc.getFieldValue("cnt_" + cellId + "_no")), EscapeUtil.nullzerof((Number)doc.getFieldValue("minpval_" + cellId + "_up")), EscapeUtil.nullzerof((Number)doc.getFieldValue("minpval_" + cellId + "_dn"))); counters.add(counter); boolean nonZero = (counter.getUps() + counter.getDowns() + counter.getNones() > 0); if (usingEfv) { if (hasQueryEfvs && efv.getPayload().isQualified(counter)) resultEfvs.put(efv); efv = null; } else { if (nonZero) resultEfos.mark(efo.getId()); efo = null; } } if(query.getViewType() == ViewType.LIST) { loadListExperiments(result, gene, resultEfvs, resultEfos, qstate.getExperiments()); } result.addResult(new StructuredResultRow(gene, counters)); } result.setResultEfvs(resultEfvs); result.setResultEfos(resultEfos); log.info("Retrieved query completely: " + result.getSize() + " records of " + result.getTotal() + " total starting from " + result.getStart() ); log.debug("Resulting EFVs are: " + resultEfvs); log.debug("Resulting EFOs are: " + resultEfos); }
private void processResultGenes(QueryResponse response, AtlasStructuredQueryResult result, QueryState qstate, AtlasStructuredQuery query) throws SolrServerException { SolrDocumentList docs = response.getResults(); result.setTotal(docs.getNumFound()); EfvTree<ColumnInfo> resultEfvs = new EfvTree<ColumnInfo>(); EfoTree<ColumnInfo> resultEfos = qstate.getEfos(); Iterable<EfvTree.EfEfv<ColumnInfo>> efvList = qstate.getEfvs().getValueSortedList(); Iterable<EfoTree.EfoItem<ColumnInfo>> efoList = qstate.getEfos().getValueOrderedList(); boolean hasQueryEfvs = qstate.hasQueryEfoEfvs(); Maker<ColumnInfo> numberer = new Maker<ColumnInfo>() { private int num = 0; public ColumnInfo make() { return new BaseColumnInfo(num++); } }; Collection<String> autoFactors = query.isFullHeatmap() ? efvService.getAllFactors() : efvService.getAnyConditionFactors(); for(SolrDocument doc : docs) { Integer id = (Integer)doc.getFieldValue("id"); if(id == null) continue; Map<Long,List<Long>> experiments = new HashMap<Long,List<Long>>(); AtlasGene gene = new AtlasGene(doc); if(response.getHighlighting() != null) gene.setGeneHighlights(response.getHighlighting().get(id.toString())); List<UpdownCounter> counters = new ArrayList<UpdownCounter>() { @Override public UpdownCounter get(int index) { if(index < size()) return super.get(index); else return new UpdownCounter(0, 0, 0, 0, 0); } }; if(!hasQueryEfvs && query.getViewType() != ViewType.LIST) { int threshold = 0; if(!query.isFullHeatmap()) { if(resultEfos.getNumExplicitEfos() > 0) threshold = 1; else if(resultEfos.getNumExplicitEfos() > 20) threshold = 3; } for(ExpressionAnalysis ea : gene.getExpressionAnalyticsTable().getAll()) { if(ea.isNo()) continue; if(autoFactors.contains(ea.getEfName())) resultEfvs.getOrCreate(ea.getEfName(), ea.getEfvName(), numberer); if(!experiments.containsKey(ea.getEfvId())) experiments.put(ea.getEfvId(), new ArrayList<Long>()); experiments.get(ea.getEfvId()).add(ea.getExperimentID()); for(String efo : ea.getEfoAccessions()) if(EscapeUtil.nullzero((Number)doc.getFieldValue("cnt_efo_" + EscapeUtil.encode(efo) + "_s_up")) > threshold) resultEfos.add(efo, numberer, false); } efvList = resultEfvs.getValueSortedList(); efoList = resultEfos.getValueOrderedList(); } Iterator<EfvTree.EfEfv<ColumnInfo>> itEfv = efvList.iterator(); Iterator<EfoTree.EfoItem<ColumnInfo>> itEfo = efoList.iterator(); EfvTree.EfEfv<ColumnInfo> efv = null; EfoTree.EfoItem<ColumnInfo> efo = null; while(itEfv.hasNext() || itEfo.hasNext() || efv != null || efo != null) { if(itEfv.hasNext() && efv == null) efv = itEfv.next(); if(itEfo.hasNext() && efo == null) efo = itEfo.next(); if(efv!=null) efv.setExperiments(experiments.get(efv.getEfEfvId())); String cellId; boolean usingEfv = efo == null || (efv != null && efv.getPayload().compareTo(efo.getPayload()) < 0); if(usingEfv) { cellId = efv.getEfEfvId(); } else { cellId = EscapeUtil.encode("efo", efo.getId()); } UpdownCounter counter = new UpdownCounter( EscapeUtil.nullzero((Number)doc.getFieldValue("cnt_" + cellId + "_up")), EscapeUtil.nullzero((Number)doc.getFieldValue("cnt_" + cellId + "_dn")), EscapeUtil.nullzero((Number)doc.getFieldValue("cnt_" + cellId + "_no")), EscapeUtil.nullzerof((Number)doc.getFieldValue("minpval_" + cellId + "_up")), EscapeUtil.nullzerof((Number)doc.getFieldValue("minpval_" + cellId + "_dn"))); counters.add(counter); boolean nonZero = (counter.getUps() + counter.getDowns() + counter.getNones() > 0); if (usingEfv) { if (hasQueryEfvs && efv.getPayload().isQualified(counter)) resultEfvs.put(efv); efv = null; } else { if (nonZero) resultEfos.mark(efo.getId()); efo = null; } } if(query.getViewType() == ViewType.LIST) { loadListExperiments(result, gene, resultEfvs, resultEfos, qstate.getExperiments()); } result.addResult(new StructuredResultRow(gene, counters)); } result.setResultEfvs(resultEfvs); result.setResultEfos(resultEfos); log.info("Retrieved query completely: " + result.getSize() + " records of " + result.getTotal() + " total starting from " + result.getStart() ); log.debug("Resulting EFVs are: " + resultEfvs); log.debug("Resulting EFOs are: " + resultEfos); }
diff --git a/src/gui/GoGui.java b/src/gui/GoGui.java index ec53c4bd..ae8f6928 100644 --- a/src/gui/GoGui.java +++ b/src/gui/GoGui.java @@ -1,1657 +1,1656 @@ //----------------------------------------------------------------------------- // $Id$ // $Source$ //----------------------------------------------------------------------------- import java.awt.*; import java.awt.event.*; import java.awt.print.*; import java.io.*; import java.net.*; import java.util.*; import javax.swing.*; import board.*; import gtp.*; import sgf.*; import utils.*; //----------------------------------------------------------------------------- class GoGui extends JFrame implements ActionListener, AnalyzeCommand.Callback, Board.Listener, GtpShell.Callback, WindowListener { GoGui(String program, Preferences prefs, String file, int move, boolean gtpShell, String time, boolean verbose, boolean fillPasses, boolean computerNone, boolean autoplay, String gtpFile) throws Gtp.Error, AnalyzeCommand.Error { if (program != null && ! program.equals("")) { // Must be created before m_gtp (stderr callback of Gtp!) m_gtpShell = new GtpShell(null, "GoGui", this, prefs); Gtp gtp = new Gtp(program, verbose, m_gtpShell); m_gtpShell.setProgramCommand(gtp.getProgramCommand()); m_commandThread = new CommandThread(gtp, m_gtpShell); m_commandThread.start(); } m_prefs = prefs; m_boardSize = prefs.getBoardSize(); m_file = file; m_fillPasses = fillPasses; m_gtpFile = gtpFile; m_move = move; m_computerNoneOption = computerNone; m_autoplay = autoplay; m_verbose = verbose; Container contentPane = getContentPane(); m_toolBar = new ToolBar(this, prefs, this); contentPane.add(m_toolBar, BorderLayout.NORTH); m_timeControl = new TimeControl(); m_board = new Board(m_boardSize); m_board.setListener(this); JPanel boardPanel = new JPanel(); boardPanel.setLayout(new SquareLayout()); boardPanel.setBorder(BorderFactory.createLoweredBevelBorder()); boardPanel.add(m_board); contentPane.add(boardPanel, BorderLayout.CENTER); JPanel infoPanel = new JPanel(); infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS)); infoPanel.setBorder(utils.GuiUtils.createSmallEmptyBorder()); Dimension pad = new Dimension(0, utils.GuiUtils.PAD); m_gameInfo = new GameInfo(m_board, m_timeControl); infoPanel.add(m_gameInfo); infoPanel.add(Box.createRigidArea(pad)); infoPanel.add(createStatusBar()); contentPane.add(infoPanel, BorderLayout.SOUTH); addWindowListener(this); setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); setIconImage(new GoIcon()); m_menuBars = new MenuBars(this); m_menuBars.selectBoardSizeItem(m_boardSize); setJMenuBar(m_menuBars.getNormalMenu()); if (program == null || program.equals("")) m_toolBar.disableComputerButtons(); pack(); setVisible(true); ++m_instanceCount; if (m_gtpShell != null) DialogUtils.center(m_gtpShell, this); if (gtpShell && m_gtpShell != null) { m_gtpShell.toTop(); } try { if (time != null) m_timeControl.setTime(time); } catch (TimeControl.Error e) { showWarning(e.getMessage()); } Runnable callback = new Runnable() { public void run() { initialize(); } }; SwingUtilities.invokeLater(callback); } public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if (m_commandInProgress && ! command.equals("computer-black") && ! command.equals("computer-both") && ! command.equals("computer-none") && ! command.equals("computer-white") && ! command.equals("interrupt") && ! command.equals("exit")) return; if (command.equals("about")) cbShowAbout(); else if (command.equals("analyze")) cbAnalyze(); else if (command.equals("backward")) cbBackward(1); else if (command.equals("backward-10")) cbBackward(10); else if (command.equals("beginning")) cbBeginning(); else if (command.startsWith("board-size-")) cbNewGame(command.substring(new String("board-size-").length())); else if (command.equals("computer-black")) computerBlack(); else if (command.equals("computer-both")) cbComputerBoth(); else if (command.equals("computer-none")) computerNone(); else if (command.equals("computer-white")) computerWhite(); else if (command.equals("end")) cbEnd(); else if (command.equals("exit")) close(); else if (command.equals("forward")) cbForward(1); else if (command.equals("forward-10")) cbForward(10); else if (command.equals("gtp-file")) cbGtpFile(); else if (command.equals("gtp-shell")) cbGtpShell(); else if (command.startsWith("handicap-")) cbHandicap(command.substring(new String("handicap-").length())); else if (command.equals("help")) cbHelp(); else if (command.equals("interrupt")) cbInterrupt(); else if (command.equals("komi")) cbKomi(); else if (command.equals("load")) cbLoad(); else if (command.equals("new-game")) cbNewGame(m_boardSize); else if (command.equals("open-with-program")) cbOpenWithProgram(); else if (command.equals("pass")) cbPass(); else if (command.equals("play")) cbPlay(); else if (command.equals("print")) cbPrint(); else if (command.equals("rules-chinese")) cbRules(Board.RULES_CHINESE); else if (command.equals("rules-japanese")) cbRules(Board.RULES_JAPANESE); else if (command.equals("save")) cbSave(); else if (command.equals("save-position")) cbSavePosition(); else if (command.equals("score")) cbScore(); else if (command.equals("score-done")) cbScoreDone(); else if (command.equals("setup")) cbSetup(); else if (command.equals("setup-black")) cbSetupBlack(); else if (command.equals("setup-done")) cbSetupDone(); else if (command.equals("setup-white")) cbSetupWhite(); else assert(false); } public void clearAnalyzeCommand() { m_analyzeCmd = null; if (m_analyzeRequestPoint) { m_analyzeRequestPoint = false; setBoardCursorDefault(); } resetBoard(); clearStatus(); } public void fieldClicked(board.Point p) { if (m_commandInProgress) return; if (m_analyzeRequestPoint) { m_analyzePointArg = p; m_board.clearAllCrossHair(); m_board.setCrossHair(p, true); analyzeBegin(false); return; } if (m_setupMode) { if (m_board.getColor(p) != m_setupColor) m_board.play(new Move(p, m_setupColor)); else m_board.play(new Move(p, board.Color.EMPTY)); return; } if (m_scoreMode) { m_board.scoreSetDead(p); return; } humanMoved(new Move(p, m_board.getToMove())); } public static void main(String[] args) { try { String s = UIManager.getSystemLookAndFeelClassName(); UIManager.setLookAndFeel(s); } catch (Exception e) { } try { - String options[] = - { - "analyze:", - "autoplay", - "computer-none", - "file:", - "fillpasses", - "gtpfile:", - "gtpshell", - "help", - "move:", - "size:", - "time:", - "verbose" - }; + String options[] = { + "analyze:", + "autoplay", + "computer-none", + "file:", + "fillpasses", + "gtpfile:", + "gtpshell", + "help", + "move:", + "size:", + "time:", + "verbose" + }; Options opt = new Options(args, options); if (opt.isSet("help")) { String helpText = - "Usage: java -jar GoGui.jar [options] program\n" + + "Usage: java -jar gogui.jar [options] program\n" + "Graphical user interface for Go programs\n" + "using the Go Text Protocol.\n" + "\n" + " -analyze name initialize analyze command\n" + " -autoplay auto play games (if computer both)\n" + " -computer-none computer plays no side\n" + " -file filename load SGF file\n" + " -fillpasses never send subsequent moves of\n" + " the same color to the program\n" + " -gtpshell open GTP shell at startup\n" + " -gtpfile send GTP file at startup\n" + " -help display this help and exit\n" + " -move load SGF file until move number\n" + " -size set board size\n" + " -time set time limits (min[+min/moves])\n" + " -verbose print debugging messages\n"; System.out.print(helpText); System.exit(0); } Preferences prefs = new Preferences(); if (opt.contains("analyze")) prefs.setAnalyzeCommand(opt.getString("analyze")); boolean autoplay = opt.isSet("autoplay"); boolean computerNone = opt.isSet("computer-none"); String file = opt.getString("file", ""); boolean fillPasses = opt.isSet("fillpasses"); boolean gtpShell = opt.isSet("gtpshell"); String gtpFile = opt.getString("gtpfile", ""); int move = opt.getInteger("move", -1); if (opt.contains("size")) prefs.setBoardSize(opt.getInteger("size")); String time = opt.getString("time", null); boolean verbose = opt.isSet("verbose"); Vector arguments = opt.getArguments(); String program = null; if (arguments.size() == 1) program = (String)arguments.get(0); else if (arguments.size() > 1) { System.err.println("Only one program argument allowed."); System.exit(-1); } else program = SelectProgram.select(null); GoGui gui = new GoGui(program, prefs, file, move, gtpShell, time, verbose, fillPasses, computerNone, autoplay, gtpFile); } catch (Throwable t) { String msg = t.getMessage(); if (msg == null) msg = t.getClass().getName(); SimpleDialogs.showError(null, msg); t.printStackTrace(); System.exit(-1); } } public boolean sendGtpCommand(String command, boolean sync) throws Gtp.Error { if (m_commandInProgress) return false; if (sync) { m_commandThread.sendCommand(command); return true; } Runnable callback = new Runnable() { public void run() { sendGtpCommandContinue(); } }; beginLengthyCommand(); m_commandThread.sendCommand(command, callback); return true; } public void sendGtpCommandContinue() { m_commandThread.getException(); endLengthyCommand(); } public void initAnalyzeCommand(int type, String label, String command, String title, double scale) { m_analyzeType = type; m_analyzeTitle = title; m_analyzeLabel = label; m_analyzeCmd = command; m_analyzeScale = scale; m_analyzeRequestPoint = false; if (m_analyzeCmd.indexOf("%p") >= 0) { m_analyzeRequestPoint = true; setBoardCursor(Cursor.CROSSHAIR_CURSOR); showStatus("Please select a field."); } } public void setAnalyzeCommand(int type, String label, String command, String title, double scale) { initAnalyzeCommand(type, label, command, title, scale); if (m_commandInProgress) return; if (m_analyzeCmd.indexOf("%p") < 0) analyzeBegin(false); } public void windowActivated(WindowEvent e) { } public void windowClosed(WindowEvent e) { } public void windowClosing(WindowEvent e) { close(); } public void windowDeactivated(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowOpened(WindowEvent e) { } private boolean m_analyzeRequestPoint; private boolean m_autoplay; private boolean m_boardNeedsReset; private boolean m_computerBlack; private boolean m_computerWhite; private boolean m_computerNoneOption; private boolean m_commandInProgress; private boolean m_fillPasses; private boolean m_lostOnTimeShown; private boolean m_resetBoardAfterAnalyze; private boolean m_scoreMode; private boolean m_setupMode; private boolean m_verbose; private int m_analyzeType = AnalyzeCommand.NONE; private int m_boardSize; private int m_handicap; private static int m_instanceCount; private int m_move; private double m_analyzeScale; private board.Color m_setupColor; private board.Point m_analyzePointArg; private board.Score m_score; private Board m_board; private CommandThread m_commandThread; private GameInfo m_gameInfo; private GoGui m_gui; private GtpShell m_gtpShell; private JLabel m_statusLabel; private MenuBars m_menuBars; private String m_analyzeCmd; private String m_analyzeLabel; private String m_analyzeTitle; private String m_file; private String m_gtpFile; private String m_name = "Unknown Go Program"; private String m_pid; private String m_version = "?"; /** Preferences. Preferences are shared between instances created with "Open with program", the last instance of GoGui saves them. */ private Preferences m_prefs; private TimeControl m_timeControl; private ToolBar m_toolBar; private Vector m_commandList = new Vector(128, 128); private void analyzeBegin(boolean resetBoardAfterAnalyze) { if (m_commandThread == null) return; m_resetBoardAfterAnalyze = resetBoardAfterAnalyze; StringBuffer buffer = new StringBuffer(m_analyzeCmd); StringUtils.replace(buffer, "%m", m_board.getToMove().toString()); if (m_analyzeCmd.indexOf("%p") >= 0) { if (m_analyzePointArg == null) return; StringUtils.replace(buffer, "%p", m_analyzePointArg.toString()); } showStatus("Running analyze command..."); Runnable callback = new Runnable() { public void run() { analyzeContinue(); } }; runLengthyCommand(buffer.toString(), callback); } private void analyzeContinue() { endLengthyCommand(); try { if (m_resetBoardAfterAnalyze) resetBoard(); Gtp.Error e = m_commandThread.getException(); if (e != null) throw e; String answer = m_commandThread.getAnswer(); if (m_analyzeType == AnalyzeCommand.COLORBOARD) { String board[][] = Gtp.parseStringBoard(answer, m_analyzeTitle, m_boardSize); showColorBoard(board); } else if (m_analyzeType == AnalyzeCommand.DOUBLEBOARD) { double board[][] = Gtp.parseDoubleBoard(answer, m_analyzeTitle, m_boardSize); showDoubleBoard(board, m_analyzeScale); } else if (m_analyzeType == AnalyzeCommand.POINTLIST) { board.Point pointList[] = Gtp.parsePointList(answer); showPointList(pointList); } else if (m_analyzeType == AnalyzeCommand.STRINGBOARD) { String board[][] = Gtp.parseStringBoard(answer, m_analyzeTitle, m_boardSize); showStringBoard(board); } StringBuffer title = new StringBuffer(m_analyzeLabel); if (m_analyzePointArg != null) { title.append(" "); title.append(m_analyzePointArg.toString()); } if (m_analyzeType == AnalyzeCommand.STRING) { if (answer.indexOf("\n") < 0) { title.append(": "); title.append(answer); showStatus(title.toString()); } else { JDialog dialog = new JDialog(this, "GoGui: " + title); JLabel label = new JLabel(title.toString()); Container contentPane = dialog.getContentPane(); contentPane.add(label, BorderLayout.NORTH); JTextArea textArea = new JTextArea(answer, 17, 40); textArea.setEditable(false); textArea.setFont(new Font("Monospaced", Font.PLAIN, getFont().getSize())); JScrollPane scrollPane = new JScrollPane(textArea); contentPane.add(scrollPane, BorderLayout.CENTER); dialog.setDefaultCloseOperation(DISPOSE_ON_CLOSE); dialog.pack(); dialog.setVisible(true); if (m_analyzeRequestPoint) showStatus("Please select a field."); else clearStatus(); } } else showStatus(title.toString()); if (! m_analyzeRequestPoint) checkComputerMove(); } catch(Gtp.Error e) { showGtpError(e); if (m_analyzeRequestPoint) showStatus("Please select a field."); else clearStatus(); return; } } private void backward(int n) { try { for (int i = 0; i < n; ++i) { if (m_board.getMoveNumber() == 0) break; if (m_commandThread != null) m_commandThread.sendCommand("undo"); m_board.undo(); } computerNone(); boardChanged(); } catch (Gtp.Error e) { showGtpError(e); } } private void beginLengthyCommand() { setBoardCursor(Cursor.WAIT_CURSOR); m_menuBars.setCommandInProgress(true); m_toolBar.enableAll(false, null); m_gtpShell.setInputEnabled(false); m_commandInProgress = true; } private void boardChanged() { m_gameInfo.update(); m_toolBar.updateGameButtons(m_board); clearStatus(); if (m_commandThread != null && m_analyzeCmd != null) analyzeBegin(true); else { resetBoard(); checkComputerMove(); } } private void cbAnalyze() { m_toolBar.toggleAnalyze(); } private void cbBeginning() { backward(m_board.getMoveNumber()); } private void cbBackward(int n) { backward(n); } private void cbComputerBoth() { computerBoth(); checkComputerMove(); } private void cbEnd() { forward(m_board.getNumberSavedMoves() - m_board.getMoveNumber()); } private void cbForward(int n) { forward(n); } private void cbGtpFile() { if (m_commandThread == null) return; File file = SimpleDialogs.showOpen(this, "Choose GTP file."); if (file != null) sendGtpFile(file); } private void cbGtpShell() { if (m_gtpShell != null) m_gtpShell.toTop(); } private void cbHandicap(String handicap) { try { m_handicap = Integer.parseInt(handicap); if (m_board.isModified()) showInfo("Handicap will take effect on next game."); else { newGame(m_boardSize, m_board.getKomi()); boardChanged(); } } catch (NumberFormatException e) { assert(false); } catch (Gtp.Error e) { showGtpError(e); } } private void cbHelp() { URL u = getClass().getClassLoader().getResource("doc/index.html"); if (u == null) { showError("Help not found."); return; } Help help = new Help(null, u); } private void cbInterrupt() { if (m_computerBlack && m_computerWhite) computerNone(); if (! m_commandInProgress) showError("No command in progress."); else if (m_commandThread == null) showError("No program loaded."); else if (m_commandThread.isProgramDead()) showError("Program is dead."); else if (m_pid.equals("")) showError("Program does not support interrupting.\n" + "See documentation section \"Interrupting programs\"."); else { if (! showQuestion("Interrupt command?")) return; runCommand("kill -INT " + m_pid); } } private void cbKomi() { Object obj = JOptionPane.showInputDialog(this, "Komi value", "GoGui: Set komi", JOptionPane.PLAIN_MESSAGE, null, null, Float.toString(m_board.getKomi())); float komi = Float.parseFloat((String)obj); setKomi(komi); } private void cbLoad() { File file = SimpleDialogs.showOpenSgf(this); if (file == null) return; loadFile(file, -1); } private void cbNewGame(int size) { try { if (! checkAbortGame()) return; m_prefs.setBoardSize(size); newGame(size, m_board.getKomi()); boardChanged(); } catch (Gtp.Error e) { showGtpError(e); m_menuBars.selectBoardSizeItem(m_boardSize); } } private void cbNewGame(String size) { try { cbNewGame(Integer.parseInt(size)); } catch (NumberFormatException e) { assert(false); } } private void cbOpenWithProgram() { try { String program = SelectProgram.select(this); if (program == null) return; File file = File.createTempFile("gogui-", "*.sgf"); save(file); GoGui gui = new GoGui(program, m_prefs, file.toString(), m_board.getMoveNumber(), false, null, m_verbose, m_fillPasses, m_computerNoneOption, m_autoplay, ""); } catch (Throwable t) { String msg = t.getMessage(); if (msg == null) msg = t.getClass().getName(); showError(msg); } } private void cbPass() { humanMoved(new Move(null, m_board.getToMove())); } private void cbPlay() { if (m_board.getToMove() == board.Color.BLACK) { m_menuBars.setComputerBlack(); computerBlack(); } else { m_menuBars.setComputerWhite(); computerWhite(); } checkComputerMove(); } private void cbPrint() { PrinterJob job = PrinterJob.getPrinterJob(); job.setPrintable(m_board); if (job.printDialog()) { try { job.print(); } catch (Exception e) { showError("Printing failed.", e); } } } private void cbRules(int rules) { m_board.setRules(rules); setRules(); } private void cbSave() { File file = SimpleDialogs.showSaveSgf(this); if (file == null) return; try { if (file.exists()) if (! showQuestion("Overwrite " + file + "?")) return; save(file); showInfo("Game saved."); } catch (FileNotFoundException e) { showError("Could not save game.", e); } } private void cbSavePosition() { File file = SimpleDialogs.showSaveSgf(this); if (file == null) return; try { if (file.exists()) if (! showQuestion("Overwrite " + file + "?")) return; savePosition(file); showInfo("Position saved."); } catch (FileNotFoundException e) { showError("Could not save position.", e); } } private void cbScore() { resetBoard(); m_board.scoreBegin(); m_scoreMode = true; setJMenuBar(m_menuBars.getScoreMenu()); m_toolBar.enableAll(false, null); pack(); showStatus("Please remove dead groups."); } private void cbScoreDone() { m_score = m_board.scoreGet(); int black = m_score.m_territoryBlack; int white = m_score.m_territoryWhite; clearStatus(); String rules = (m_score.m_rules == Board.RULES_JAPANESE ? "Japanese" : "Chinese"); showInfo("Territory Black: " + black + "\n" + "Territory White: " + white + "\n" + "Area Black: " + m_score.m_areaBlack + "\n" + "Area White: " + m_score.m_areaWhite + "\n" + "Captured Black: " + m_score.m_capturedBlack + "\n" + "Captured Black: " + m_score.m_capturedWhite + "\n" + "Komi: " + m_board.getKomi() + "\n" + "Result Chinese: " + m_score.m_resultChinese + "\n" + "Result Japanese: " + m_score.m_resultJapanese + "\n" + "Rules: " + rules + "\n" + "\n" + "Game result:\n" + m_score.formatResult()); m_board.clearAll(); m_scoreMode = false; setJMenuBar(m_menuBars.getNormalMenu()); m_toolBar.enableAll(true, m_board); pack(); } private void cbSetup() { resetBoard(); m_setupMode = true; setJMenuBar(m_menuBars.getSetupMenu()); m_toolBar.enableAll(false, null); pack(); showStatus("Setup black."); m_setupColor = board.Color.BLACK; } private void cbSetupBlack() { showStatus("Setup black."); m_setupColor = board.Color.BLACK; } private void cbSetupDone() { try { m_setupMode = false; setJMenuBar(m_menuBars.getNormalMenu()); pack(); m_toolBar.enableAll(true, m_board); int size = m_board.getBoardSize(); board.Color color[][] = new board.Color[size][size]; for (int i = 0; i < m_board.getNumberPoints(); ++i) { board.Point p = m_board.getPoint(i); color[p.getX()][p.getY()] = m_board.getColor(p); } board.Color toMove = m_board.getToMove().otherColor(); newGame(size, m_board.getKomi()); Vector moves = new Vector(m_board.getNumberPoints()); for (int i = 0; i < m_board.getNumberPoints(); ++i) { board.Point p = m_board.getPoint(i); int x = p.getX(); int y = p.getY(); board.Color c = color[x][y]; if (c != board.Color.EMPTY) { moves.add(new Move(p, c)); } } if (m_fillPasses) moves = fillPasses(moves); for (int i = 0; i < moves.size(); ++i) { Move m = (Move)moves.get(i); if (m_commandThread != null) m_commandThread.sendCommandPlay(m); m_board.setup(m); } if (m_board.getToMove() != toMove) { Move m = new Move(null, m_board.getToMove()); if (m_commandThread != null) m_commandThread.sendCommandPlay(m); m_board.play(m); } computerNone(); boardChanged(); } catch (Gtp.Error e) { showGtpError(e); } } private void cbSetupWhite() { showStatus("Setup white."); m_setupColor = board.Color.WHITE; } private void cbShowAbout() { String message = m_name + "\n" + "Version " + m_version; SimpleDialogs.showAbout(this, message); } private boolean checkAbortGame() { if (! m_board.isModified()) return true; return showQuestion("Abort game?"); } private void checkComputerMove() { if (m_computerBlack && m_computerWhite) { if (m_board.bothPassed()) { if (m_autoplay) { try { newGame(m_boardSize, m_board.getKomi()); boardChanged(); } catch (Gtp.Error e) { showGtpError(e); } } else { showInfo("Game finished."); computerNone(); } return; } else generateMove(); } else { if (computerToMove()) generateMove(); } m_timeControl.startMove(m_board.getToMove()); } private void clearStatus() { showStatus(" "); } private void close() { if (m_commandInProgress) { String message = "Interrupt command and exit?"; if (! showQuestion(message)) return; } else { if (m_commandThread != null && ! m_commandThread.isProgramDead()) try { m_commandThread.sendCommand("quit"); } catch(Gtp.Error e) { } } if (m_gtpShell != null) m_gtpShell.saveHistory(); dispose(); assert(m_instanceCount > 0); if (--m_instanceCount == 0) { try { m_prefs.save(); } catch (Preferences.Error e) { showError("Could not save preferences.", e); } System.exit(0); } } private void computerBlack() { m_computerBlack = true; m_computerWhite = false; m_menuBars.setComputerBlack(); } private void computerBoth() { m_computerBlack = true; m_computerWhite = true; m_menuBars.setComputerBoth(); } private void computerMoved() { assert(m_commandThread != null); endLengthyCommand(); //java.awt.Toolkit.getDefaultToolkit().beep(); try { Gtp.Error e = m_commandThread.getException(); if (e != null) throw e; board.Point p = Gtp.parsePoint(m_commandThread.getAnswer()); board.Color toMove = m_board.getToMove(); Move m = new Move(p, toMove); m_board.play(m); m_timeControl.stopMove(); boardChanged(); } catch (Gtp.Error e) { showGtpError(e); } } private void computerNone() { m_computerBlack = false; m_computerWhite = false; m_menuBars.setComputerNone(); } private boolean computerToMove() { if (m_board.getToMove() == board.Color.BLACK) return m_computerBlack; else return m_computerWhite; } private void computerWhite() { m_computerBlack = false; m_computerWhite = true; m_menuBars.setComputerWhite(); } private JComponent createStatusBar() { JPanel panel = new JPanel(); panel.setLayout(new GridLayout(1, 0)); JLabel label = new JLabel(); label.setBorder(BorderFactory.createLoweredBevelBorder()); label.setHorizontalAlignment(SwingConstants.LEFT); panel.add(label); m_statusLabel = label; clearStatus(); return panel; } private void endLengthyCommand() { m_menuBars.setCommandInProgress(false); m_toolBar.enableAll(true, m_board); if (m_gtpShell != null) m_gtpShell.setInputEnabled(true); m_commandInProgress = false; if (m_analyzeRequestPoint) setBoardCursor(Cursor.CROSSHAIR_CURSOR); else setBoardCursorDefault(); } private Vector fillPasses(Vector moves) { assert(m_fillPasses); Vector result = new Vector(moves.size() * 2); if (moves.size() == 0) return result; board.Color toMove = m_board.getToMove(); for (int i = 0; i < moves.size(); ++i) { Move m = (Move)moves.get(i); if (m.getColor() != toMove) result.add(new Move(null, toMove)); result.add(m); toMove = m.getColor().otherColor(); } return result; } private void forward(int n) { try { for (int i = 0; i < n; ++i) { int moveNumber = m_board.getMoveNumber(); if (moveNumber >= m_board.getNumberSavedMoves()) break; Move m = m_board.getMove(moveNumber); if (m_commandThread != null) m_commandThread.sendCommandPlay(m); m_board.play(m); } computerNone(); boardChanged(); } catch (Gtp.Error e) { showGtpError(e); } } private void generateMove() { board.Color toMove = m_board.getToMove(); String command = m_commandThread.getCommandGenmove(toMove); showStatus("Computer is thinking..."); Runnable callback = new Runnable() { public void run() { computerMoved(); } }; runLengthyCommand(command, callback); } private void humanMoved(Move m) { try { board.Point p = m.getPoint(); if (p != null && m_board.getColor(p) != board.Color.EMPTY) return; if (m_commandThread != null) m_commandThread.sendCommandPlay(m); m_board.play(m); m_timeControl.stopMove(); if (m_board.getMoveNumber() > 0 && m_timeControl.lostOnTime(m.getColor()) && ! m_lostOnTimeShown) { showInfo(m.getColor().toString() + " lost on time."); m_lostOnTimeShown = true; } boardChanged(); } catch (Gtp.Error e) { showGtpError(e); } } private void initialize() { try { if (m_commandThread != null) { m_name = m_commandThread.sendCommand("name", 30000).trim(); m_gtpShell.setProgramName(m_name); setTitle(m_name); } if (m_commandThread != null) { try { m_commandThread.queryProtocolVersion(); } catch (Gtp.Error e) { showGtpError(e); } try { m_version = m_commandThread.sendCommand("version").trim(); queryCommandList(); if (m_commandList.contains("gogui_sigint")) m_pid = m_commandThread.sendCommand("gogui_sigint").trim(); } catch (Gtp.Error e) { } m_gtpShell.setInitialCompletions(m_commandList); if (! m_gtpFile.equals("")) sendGtpFile(new File(m_gtpFile)); } if (m_commandThread == null || m_computerNoneOption) computerNone(); else computerWhite(); File file = null; if (! m_file.equals("")) newGame(m_boardSize, new File(m_file), m_move, 0); else { newGame(m_boardSize, null, -1, 0); boardChanged(); } } catch (Gtp.Error e) { showGtpError(e); showStatus(e.getMessage()); } } private void loadFile(File file, int move) { try { sgf.Reader reader = new sgf.Reader(file); int boardSize = reader.getBoardSize(); newGame(boardSize, 0); Vector moves = new Vector(361, 361); Vector setupBlack = reader.getSetupBlack(); for (int i = 0; i < setupBlack.size(); ++i) { board.Point p = (board.Point)setupBlack.get(i); moves.add(new Move(p, board.Color.BLACK)); } Vector setupWhite = reader.getSetupWhite(); for (int i = 0; i < setupWhite.size(); ++i) { board.Point p = (board.Point)setupWhite.get(i); moves.add(new Move(p, board.Color.WHITE)); } if (m_fillPasses) moves = fillPasses(moves); for (int i = 0; i < moves.size(); ++i) { Move m = (Move)moves.get(i); m_board.setup(m); m_commandThread.sendCommandPlay(m); } int numberMoves = reader.getMoves().size(); board.Color toMove = reader.getToMove(); if (numberMoves > 0) toMove = reader.getMove(0).getColor(); if (toMove != m_board.getToMove()) { if (m_fillPasses) { Move m = new Move(null, m_board.getToMove()); m_board.setup(m); m_commandThread.sendCommandPlay(m); } else m_board.setToMove(toMove); } moves.clear(); for (int i = 0; i < numberMoves; ++i) moves.add(reader.getMove(i)); if (m_fillPasses) moves = fillPasses(moves); for (int i = 0; i < moves.size(); ++i) { Move m = (Move)moves.get(i); m_board.play(m); } while (m_board.getMoveNumber() > 0) m_board.undo(); if (move > 0) forward(move); } catch (sgf.Reader.Error e) { showError("Could not read file.", e); } catch (Gtp.Error e) { showGtpError(e); } } private void newGame(int size, float komi) throws Gtp.Error { newGame(size, (File)null, -1, komi); } private void newGame(int size, File file, int move, float komi) throws Gtp.Error { if (m_commandThread != null) { m_commandThread.sendCommandsClearBoard(size); } if (size != m_boardSize) { m_boardSize = size; m_board.initSize(size); pack(); } m_board.newGame(); resetBoard(); m_timeControl.reset(); m_lostOnTimeShown = false; m_score = null; if (file != null) { loadFile(new File(m_file), move); m_gameInfo.update(); } else { setHandicap(); setKomi(komi); setRules(); } } private void queryCommandList() { assert(m_commandThread != null); m_gtpShell.setProgramVersion(m_version); try { String s = m_commandThread.sendCommandListCommands(); BufferedReader r = new BufferedReader(new StringReader(s)); try { while (true) { String line = r.readLine(); if (line == null) break; m_commandList.add(line); } } catch (IOException e) { } } catch (Gtp.Error e) { } } private void resetBoard() { if (! m_boardNeedsReset) return; clearStatus(); m_board.clearAll(); m_boardNeedsReset = false; } private void runCommand(String command) { Runtime runtime = Runtime.getRuntime(); try { Process process = runtime.exec(command); int result = process.waitFor(); if (result != 0) showError("Command \"" + command + "\" returned " + result + "."); } catch (IOException e) { showError("Could not run program.", e); } catch (InterruptedException e) { } } private void runLengthyCommand(String cmd, Runnable callback) { assert(m_commandThread != null); beginLengthyCommand(); m_commandThread.sendCommand(cmd, callback); } private void save(File file) throws FileNotFoundException { String playerBlack = null; String playerWhite = null; String gameComment = null; if (m_commandThread != null) { if (m_computerBlack) playerBlack = m_name + ":" + m_version; if (m_computerWhite) playerWhite = m_name + ":" + m_version; gameComment = "Program command: " + m_commandThread.getProgramCommand(); } sgf.Writer w = new sgf.Writer(file, m_board, m_handicap, playerBlack, playerWhite, gameComment, m_score); } private void savePosition(File file) throws FileNotFoundException { sgf.Writer w = new sgf.Writer(file, m_board); } private void sendGtpFile(File file) { java.io.BufferedReader in; try { in = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { showError("Could not send commands.", e); return; } while (true) { try { String line = in.readLine(); if (line == null) return; m_gtpShell.sendCommand(line, this); } catch (IOException e) { showError("Sending commands aborted.", e); return; } } } private void setHandicap() throws Gtp.Error { Vector handicap = m_board.getHandicapStones(m_handicap); if (handicap == null) { showWarning("Handicap stone locations are\n" + "not defined for this board size."); return; } Vector moves = new Vector(handicap.size()); for (int i = 0; i < handicap.size(); ++i) { board.Point p = (board.Point)handicap.get(i); moves.add(new Move(p, board.Color.BLACK)); } if (m_fillPasses) moves = fillPasses(moves); for (int i = 0; i < moves.size(); ++i) { Move m = (Move)moves.get(i); m_commandThread.sendCommandPlay(m); m_board.setup(m); } } private void setBoardCursor(int type) { Cursor cursor = Cursor.getPredefinedCursor(type); m_board.setCursor(cursor); } private void setBoardCursorDefault() { m_board.setCursor(Cursor.getDefaultCursor()); } private void setKomi(float komi) { m_board.setKomi(komi); if (m_commandThread == null) return; try { m_commandThread.sendCommand("komi " + komi); } catch (Gtp.Error e) { showWarning("Program does not accept komi\n" + "(" + e.getMessage() + ")."); } } private void setRules() { if (m_commandThread == null) return; if (! m_commandList.contains("scoring_system")) return; try { int rules = m_board.getRules(); String s = (rules == Board.RULES_JAPANESE ? "territory" : "area"); m_commandThread.sendCommand("scoring_system " + s); } catch (Gtp.Error e) { showWarning("Program does not accept scoring system\n" + "(" + e.getMessage() + ")."); } } private void showColorBoard(String[][] board) throws Gtp.Error { m_board.showColorBoard(board); m_boardNeedsReset = true; } private void showDoubleBoard(double[][] board, double scale) { m_board.showDoubleBoard(board, scale); m_boardNeedsReset = true; } private void showError(String message, Exception e) { String m = e.getMessage(); String c = e.getClass().getName(); if (m == null) showError(message + "\n" + e.getClass().getName()); else showError(message + "\n" + m); } private void showError(String message) { SimpleDialogs.showError(this, message); } private void showGtpError(Gtp.Error e) { showGtpError(this, e); } private void showGtpError(Component frame, Gtp.Error e) { SimpleDialogs.showError(frame, e.getMessage()); } private void showInfo(String message) { SimpleDialogs.showInfo(this, message); } private boolean showQuestion(String message) { return SimpleDialogs.showQuestion(this, message); } private void showPointList(board.Point pointList[]) throws Gtp.Error { m_board.showPointList(pointList); m_boardNeedsReset = true; } private void showStatus(String text) { m_statusLabel.setText(text); m_statusLabel.repaint(); } private void showStringBoard(String[][] board) throws Gtp.Error { m_board.showStringBoard(board); m_boardNeedsReset = true; } private void showWarning(String message) { SimpleDialogs.showWarning(this, message); } } //-----------------------------------------------------------------------------
false
true
public static void main(String[] args) { try { String s = UIManager.getSystemLookAndFeelClassName(); UIManager.setLookAndFeel(s); } catch (Exception e) { } try { String options[] = { "analyze:", "autoplay", "computer-none", "file:", "fillpasses", "gtpfile:", "gtpshell", "help", "move:", "size:", "time:", "verbose" }; Options opt = new Options(args, options); if (opt.isSet("help")) { String helpText = "Usage: java -jar GoGui.jar [options] program\n" + "Graphical user interface for Go programs\n" + "using the Go Text Protocol.\n" + "\n" + " -analyze name initialize analyze command\n" + " -autoplay auto play games (if computer both)\n" + " -computer-none computer plays no side\n" + " -file filename load SGF file\n" + " -fillpasses never send subsequent moves of\n" + " the same color to the program\n" + " -gtpshell open GTP shell at startup\n" + " -gtpfile send GTP file at startup\n" + " -help display this help and exit\n" + " -move load SGF file until move number\n" + " -size set board size\n" + " -time set time limits (min[+min/moves])\n" + " -verbose print debugging messages\n"; System.out.print(helpText); System.exit(0); } Preferences prefs = new Preferences(); if (opt.contains("analyze")) prefs.setAnalyzeCommand(opt.getString("analyze")); boolean autoplay = opt.isSet("autoplay"); boolean computerNone = opt.isSet("computer-none"); String file = opt.getString("file", ""); boolean fillPasses = opt.isSet("fillpasses"); boolean gtpShell = opt.isSet("gtpshell"); String gtpFile = opt.getString("gtpfile", ""); int move = opt.getInteger("move", -1); if (opt.contains("size")) prefs.setBoardSize(opt.getInteger("size")); String time = opt.getString("time", null); boolean verbose = opt.isSet("verbose"); Vector arguments = opt.getArguments(); String program = null; if (arguments.size() == 1) program = (String)arguments.get(0); else if (arguments.size() > 1) { System.err.println("Only one program argument allowed."); System.exit(-1); } else program = SelectProgram.select(null); GoGui gui = new GoGui(program, prefs, file, move, gtpShell, time, verbose, fillPasses, computerNone, autoplay, gtpFile); } catch (Throwable t) { String msg = t.getMessage(); if (msg == null) msg = t.getClass().getName(); SimpleDialogs.showError(null, msg); t.printStackTrace(); System.exit(-1); } }
public static void main(String[] args) { try { String s = UIManager.getSystemLookAndFeelClassName(); UIManager.setLookAndFeel(s); } catch (Exception e) { } try { String options[] = { "analyze:", "autoplay", "computer-none", "file:", "fillpasses", "gtpfile:", "gtpshell", "help", "move:", "size:", "time:", "verbose" }; Options opt = new Options(args, options); if (opt.isSet("help")) { String helpText = "Usage: java -jar gogui.jar [options] program\n" + "Graphical user interface for Go programs\n" + "using the Go Text Protocol.\n" + "\n" + " -analyze name initialize analyze command\n" + " -autoplay auto play games (if computer both)\n" + " -computer-none computer plays no side\n" + " -file filename load SGF file\n" + " -fillpasses never send subsequent moves of\n" + " the same color to the program\n" + " -gtpshell open GTP shell at startup\n" + " -gtpfile send GTP file at startup\n" + " -help display this help and exit\n" + " -move load SGF file until move number\n" + " -size set board size\n" + " -time set time limits (min[+min/moves])\n" + " -verbose print debugging messages\n"; System.out.print(helpText); System.exit(0); } Preferences prefs = new Preferences(); if (opt.contains("analyze")) prefs.setAnalyzeCommand(opt.getString("analyze")); boolean autoplay = opt.isSet("autoplay"); boolean computerNone = opt.isSet("computer-none"); String file = opt.getString("file", ""); boolean fillPasses = opt.isSet("fillpasses"); boolean gtpShell = opt.isSet("gtpshell"); String gtpFile = opt.getString("gtpfile", ""); int move = opt.getInteger("move", -1); if (opt.contains("size")) prefs.setBoardSize(opt.getInteger("size")); String time = opt.getString("time", null); boolean verbose = opt.isSet("verbose"); Vector arguments = opt.getArguments(); String program = null; if (arguments.size() == 1) program = (String)arguments.get(0); else if (arguments.size() > 1) { System.err.println("Only one program argument allowed."); System.exit(-1); } else program = SelectProgram.select(null); GoGui gui = new GoGui(program, prefs, file, move, gtpShell, time, verbose, fillPasses, computerNone, autoplay, gtpFile); } catch (Throwable t) { String msg = t.getMessage(); if (msg == null) msg = t.getClass().getName(); SimpleDialogs.showError(null, msg); t.printStackTrace(); System.exit(-1); } }
diff --git a/src/elxris/SpiceCraft/Objects/Mail.java b/src/elxris/SpiceCraft/Objects/Mail.java index b77e59f..e2d5b12 100644 --- a/src/elxris/SpiceCraft/Objects/Mail.java +++ b/src/elxris/SpiceCraft/Objects/Mail.java @@ -1,253 +1,253 @@ package elxris.SpiceCraft.Objects; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.bukkit.configuration.Configuration; import org.bukkit.configuration.MemoryConfiguration; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import elxris.SpiceCraft.SpiceCraft; import elxris.SpiceCraft.Utils.Archivo; import elxris.SpiceCraft.Utils.Chat; import elxris.SpiceCraft.Utils.Fecha; import elxris.SpiceCraft.Utils.Strings; public class Mail{ FileConfiguration cache; Configuration draft; Archivo archivo; public Mail(){ interpreta(); } public void interpreta(){ if(!getConfig().isSet("msg")){ sendMensajeATodos(SpiceCraft.plugin().getConfig().getString("mail.serverUserName", "Server"), Strings.getString("mbox.first")); return; } Set<String> listacorreos = getConfig().getConfigurationSection("msg").getKeys(false); for(String k: listacorreos){ int usuarios = getConfig().getConfigurationSection("msg."+k+".usuarios").getKeys(false).size(); if(usuarios == 0 || System.currentTimeMillis()-Long.parseLong(k) >= SpiceCraft.plugin().getConfig().getLong("mail.clearOnDays", 15)*24*60*60*1000){ // Los correos mayores a 15 d�as (15*24*60*60*1000) milisegundos, se eliminan. getConfig().set("msg."+k, null); } } } public void eliminar(String jugador, Long mail){ getConfig().set("msg."+mail+".usuarios."+jugador, null); } public void eliminarAll(String jugador){ if(!getConfig().isSet("msg")){ return; } Set<String> mensajes = getConfig().getConfigurationSection("msg").getKeys(false); for(String lng: mensajes){ eliminar(jugador, Long.parseLong(lng)); } save(); } public String[] getMail(Long id){ String remitente = getConfig().getString("msg."+id+".remitente"); if(getConfig().getBoolean("msg."+id+".servidor") == true){ remitente = "Servidor"; } String[] mail = {remitente, Fecha.formatoFechaDiff(id), getConfig().getString("msg."+id+".mensaje"), remitente}; return mail; } public void getMailList(String jugador){ int mensajes = 0; Set<String> mail = getConfig().getConfigurationSection("msg").getKeys(false); for(String id: mail){ if(getConfig().getBoolean("msg."+id+".usuarios."+jugador, false)){ mensajes++; } } Chat.mensaje(jugador, "mbox.list", mensajes); } public void getNextMail(String jugador){ //Obtiene todos los correos. List<String> mensajes = new ArrayList<String>(); Set<String> mail = getConfig().getConfigurationSection("msg").getKeys(false); for(String id: mail){ String path = "msg."+id+".usuarios."+jugador; if(getConfig().isSet(path)){ mensajes.add(id); getConfig().set(path, false); } } if(mensajes.size() == 0){ Chat.mensaje(jugador, "mbox.listEnd"); return; } Chat.mensaje(jugador, "mbox.readStart"); // Enviando cada uno de los mensajes. for(String lng: mensajes){ String[] mensaje = getMail(Long.parseLong(lng)); Chat.mensaje(jugador, "mbox.mail", mensaje); } Chat.mensaje(jugador, "mbox.readFinish"); save(); } public void createBorrador(String jugador, String args[]){ //Inicia el borrador. clearBorrador(jugador); List<String> destinatarios = checkDestinatarios(jugador, args); if(destinatarios.size() >= 1){ getDraft().set(jugador+".destinatarios", destinatarios); Chat.mensaje(jugador, "mbox.created"); }else{ Chat.mensaje(jugador, "mbox.noPlayerAdded"); } } public void setMensaje(String jugador, String mensaje){ getDraft().set(jugador+".mensaje", mensaje); } public void addMensaje(String jugador, String mensaje){ if(getDraft().getStringList(jugador+".destinatarios").size() < 1){ Chat.mensaje(jugador, "mbox.noMessage"); return; } String mensajeAnterior = ""; if(getDraft().isSet(jugador+".mensaje")){ mensajeAnterior = getDraft().getString(jugador+".mensaje"); } if(mensajeAnterior.length() > SpiceCraft.plugin().getConfig().getInt("mail.maxChar")){ if(!SpiceCraft.getOnlinePlayer(jugador).hasPermission("spicecraft.mail.noCharLimit")){ Chat.mensaje(jugador, "mbox.limit", SpiceCraft.plugin().getConfig().getInt("mail.maxChar")); return; } } setMensaje(jugador, mensajeAnterior+" "+mensaje); Chat.mensaje(jugador, "mbox.add"); } public void clearMensaje(String jugador){ setMensaje(jugador, ""); } public void clearBorrador(String jugador){ getDraft().set(jugador, null); } public void sendMensaje(String jugador, List<String> destinatarios, String mensaje, Boolean servidor){ destinatarios = checkDestinatarios(jugador, destinatarios.toArray(new String[0])); if(destinatarios.size() < 1){ return; } - if(isFlooding(jugador)){ + if(!servidor && isFlooding(jugador)){ Chat.mensaje(SpiceCraft.getOnlineExactPlayer(jugador), "mbox.flood"); return; } long fecha = System.currentTimeMillis(); String path = "msg."+fecha+"."; getConfig().set(path+"remitente", jugador); getConfig().set(path+"servidor", servidor); getConfig().set(path+"mensaje", mensaje); for(String s : destinatarios){ getConfig().set(path+"usuarios."+s, true); } for(String k: destinatarios){ Chat.mensaje(k, "mbox.catched"); } Chat.mensaje(jugador, "mbox.sended"); clearBorrador(jugador); save(); } public void sendMensaje(String jugador){ if(!hasMensaje(jugador)){ return; } List<String> destinatarios = getDraft().getStringList(jugador+".destinatarios"); String mensaje = getDraft().getString(jugador+".mensaje"); sendMensaje(jugador, destinatarios, mensaje, false); } public void sendMensajeATodos(String jugador){ if(!hasMensaje(jugador)){ return; } sendMensajeATodos(jugador, getDraft().getString(jugador+".mensaje")); } public void sendMensajeATodos(String jugador, String mensaje){ if(!jugador.contentEquals(SpiceCraft.plugin().getConfig().getString("mail.serverUserName", "Server")) && !SpiceCraft.getOnlinePlayer(jugador).hasPermission("spicecraft.mail.massive")){ return; } List<String> destinatarios = new ArrayList<String>(); for(String p: SpiceCraft.getOfflinePlayerNames()){ destinatarios.add(p); } sendMensaje(jugador, destinatarios, mensaje, true); } public String isDestinatario(String player){ List<Player> l = SpiceCraft.plugin().getServer().matchPlayer(player); if(l.size() == 1){ return l.get(0).getName(); }else{ if(SpiceCraft.plugin().getServer().getOfflinePlayer(player).hasPlayedBefore()){ return player; } } return null; } public boolean hasMensaje(String jugador){ if(!getDraft().isSet(jugador+".mensaje")){ Chat.mensaje(jugador, "mbox.noMessage"); return false; } return true; } public boolean isFlooding(String jugador){ long fecha = System.currentTimeMillis(); String[] mails = getConfig().getConfigurationSection("msg").getKeys(false).toArray(new String[0]); int count = SpiceCraft.plugin().getConfig().getInt("mail.maxMailsIn15Minutes", 10); for(int i = mails.length-1; i >= 0; i--){ if(Long.parseLong(mails[i])+15*60*1000 > fecha){ if(getConfig().getString("msg."+mails[i]+".remitente").contentEquals(jugador)){ count--; } if(count <= 0){ return true; } }else{ break; } } return false; } public List<String> checkDestinatarios(String jugador, String[] destinatarios){ List<String> checked = new ArrayList<String>(); for(String s: destinatarios){ String destinatario = isDestinatario(s); if(destinatario != null){ checked.add(destinatario); }else{ Chat.mensaje(jugador, "mbox.playerNotExist", s); } } return checked; } private Archivo getArchivo(){ if(archivo == null){ archivo = new Archivo("mail.yml"); } return archivo; } private FileConfiguration getConfig(){ if(cache == null){ cache = getArchivo().load(); } return cache; } private Configuration getDraft(){ if(draft == null){ draft = new MemoryConfiguration(); } return draft; } private void save(){ getArchivo().save(getConfig()); } }
true
true
public void sendMensaje(String jugador, List<String> destinatarios, String mensaje, Boolean servidor){ destinatarios = checkDestinatarios(jugador, destinatarios.toArray(new String[0])); if(destinatarios.size() < 1){ return; } if(isFlooding(jugador)){ Chat.mensaje(SpiceCraft.getOnlineExactPlayer(jugador), "mbox.flood"); return; } long fecha = System.currentTimeMillis(); String path = "msg."+fecha+"."; getConfig().set(path+"remitente", jugador); getConfig().set(path+"servidor", servidor); getConfig().set(path+"mensaje", mensaje); for(String s : destinatarios){ getConfig().set(path+"usuarios."+s, true); } for(String k: destinatarios){ Chat.mensaje(k, "mbox.catched"); } Chat.mensaje(jugador, "mbox.sended"); clearBorrador(jugador); save(); }
public void sendMensaje(String jugador, List<String> destinatarios, String mensaje, Boolean servidor){ destinatarios = checkDestinatarios(jugador, destinatarios.toArray(new String[0])); if(destinatarios.size() < 1){ return; } if(!servidor && isFlooding(jugador)){ Chat.mensaje(SpiceCraft.getOnlineExactPlayer(jugador), "mbox.flood"); return; } long fecha = System.currentTimeMillis(); String path = "msg."+fecha+"."; getConfig().set(path+"remitente", jugador); getConfig().set(path+"servidor", servidor); getConfig().set(path+"mensaje", mensaje); for(String s : destinatarios){ getConfig().set(path+"usuarios."+s, true); } for(String k: destinatarios){ Chat.mensaje(k, "mbox.catched"); } Chat.mensaje(jugador, "mbox.sended"); clearBorrador(jugador); save(); }
diff --git a/src/main/java/com/atex/whatsnew/WhatsNewMojo.java b/src/main/java/com/atex/whatsnew/WhatsNewMojo.java index 8716456..3e49612 100644 --- a/src/main/java/com/atex/whatsnew/WhatsNewMojo.java +++ b/src/main/java/com/atex/whatsnew/WhatsNewMojo.java @@ -1,211 +1,211 @@ package com.atex.whatsnew; import static com.google.common.collect.Iterables.filter; import static com.google.common.collect.Iterables.transform; import java.io.File; import java.util.Collections; import java.util.List; import java.util.Map; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.settings.Server; import org.apache.maven.settings.Settings; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; @Mojo(name = "whats-new", defaultPhase = LifecyclePhase.GENERATE_RESOURCES, requiresOnline = true, requiresProject = true, threadSafe = true) /** * Generates a 'whatsnew.html' from all Closed and Resolved issues from a jira project. Possibly including attached image resources as screenshots. */ public class WhatsNewMojo extends AbstractMojo { /** * The target directory of the generated whats new page, contains the main 'whatsnew.html' and possible * image resources in directory 'whatsnew-img'. */ @Parameter(defaultValue = "${project.build.directory}/generated-resources", property = "outputDir") private File outputDirectory; /** * The template file used to produce the 'whatsnew.html', default ${pojrect.directory}/src/main/whatsnew/whatsnew.html */ @Parameter(defaultValue = "${project.basedir}/src/main/whatsnew/whatsnew.html", property = "templateFile") private File templateFile; /** * The base url to the jira installation (eg http://support.polopoly.com/jira) */ @Parameter(defaultValue = "http://support.polopoly.com/jira", property = "jira.url") private String jiraUrl; /** * Field(s) to use as what changed note (the first non empty is used), comma separated list. */ @Parameter(defaultValue = "customfield_10068,summary", property = "jira.fields") private String fields; /** * Field(s) to exclude, because sometimes jira does not allow negation in searches... */ @Parameter(defaultValue = "customfield_10067=Exclude release note", property = "jira.excludes") private String excludes; /** * The id of the server in ~/.m2/settings.xml to use for username/password to login to the jira instance. */ @Parameter(defaultValue = "jira", property = "jira.server-id") private String jiraId; /** * The jira project key, default 'ART'. */ @Parameter(defaultValue = "ART", property = "jira.project-key") private String project; /** * The jira version, default '{project.version}' strips '-SNAPSHOT' and possibly fix version (eg 1.0.1-SNAPSHOT becomes 1.0 or 1.0.1 depending on jira.strip-fix-version). */ @Parameter(defaultValue = "${project.version}", property = "jira.project-version") private String version; /** * Strip the jira version's fix version */ @Parameter(defaultValue = "true", property="jira.strip-fix-version") private boolean stripFixVersion; /** * The git directory */ @Parameter(defaultValue = "${project.basedir}", property = "git.directory") private File git; /** * Use git to get correct dates and determine if a ticket found in jira should * be included or not. If not enabled a ticket must be Closed or Resolved to * be included. If git is enabled the branch will be inspected for tickets and * all tickets that has a corresponding commit will be included. */ @Parameter(defaultValue = "true", property = "git.enabled") private boolean gitEnabled; /** * The settings bean, not configurable (Do not touch). */ @Parameter(defaultValue = "${settings}", readonly = true) private Settings settings; public void execute() throws MojoExecutionException { if (settings == null) { throw new MojoExecutionException("No settings"); } Server server = settings.getServer(jiraId); if (server == null) { throw new MojoExecutionException(String.format("No server '%s' in settings", jiraId)); } JiraClient client = new JiraClient(jiraUrl, server.getUsername(), server.getPassword(), getLog()); client.project = project; Splitter splitter = Splitter.on(',').trimResults().omitEmptyStrings();; client.fields = ImmutableList.copyOf(splitter.splitToList(fields)); client.excludes = ImmutableMap.copyOf(parseExcludes(splitter.splitToList(excludes))); client.version = stripVersion(version, stripFixVersion); Predicate<String> prefilter = null; GitClient gitClient = null; if (gitEnabled) { gitClient = new GitClient(git, project, getLog()); prefilter = gitPrefilter(gitClient); } List<Change> changes = client.changes(prefilter); client.downloadImages(filter(changes, hasPreview()), new File(outputDirectory, "whatsnew-images")); if (gitEnabled) { changes = Lists.newArrayList(transform(changes, correctDate(gitClient))); Collections.sort(changes); Collections.reverse(changes); } Map<String, Object> context = Maps.newHashMap(); context.put("changes", changes); if (gitEnabled) { context.put("branch", gitClient.getResolvedHeadBranchName()); context.put("hash", gitClient.getResolvedHeadObjectId().getName()); } - context.put("version", version); + context.put("version", stripVersion(version, stripFixVersion)); context.put("imagesDir", "whatsnew-images"); new WhatsNewTemplate(outputDirectory, templateFile, context).write(); } private Map<String, String> parseExcludes(List<String> excludes) throws MojoExecutionException { Map<String, String> map = Maps.newHashMap(); for (String exclude : excludes) { int index = exclude.indexOf('='); if (index == -1) { throw new MojoExecutionException("Illegal exclude pattern: " + exclude); } map.put(exclude.substring(0, index), exclude.substring(index+1)); } return map; } static String stripVersion(String version, boolean stripMinor) { if (version.endsWith("-SNAPSHOT")) { version = version.substring(0, version.length() - "-SNAPSHOT".length()); } if (stripMinor && version.matches("\\d+\\.\\d+\\.\\d+")) { version = version.substring(0, version.lastIndexOf('.')); } return version; } public static Predicate<String> gitPrefilter(final GitClient git) { return new Predicate<String>() { public boolean apply(String input) { return git.hasId(input); } }; } public static Function<Change, String> getPreviewUrl() { return new Function<Change, String>() { public String apply(Change input) { return input.preview; } }; } public static Predicate<Change> hasPreview() { return new Predicate<Change>() { public boolean apply(Change input) { return input.preview != null; } }; } public static Function<Change, Change> correctDate(final GitClient git) { return new Function<Change, Change>() { public Change apply(Change input) { String gitDate = git.dateOf(input.id); if (gitDate != null) { input.date = gitDate; } return input; } }; } }
true
true
public void execute() throws MojoExecutionException { if (settings == null) { throw new MojoExecutionException("No settings"); } Server server = settings.getServer(jiraId); if (server == null) { throw new MojoExecutionException(String.format("No server '%s' in settings", jiraId)); } JiraClient client = new JiraClient(jiraUrl, server.getUsername(), server.getPassword(), getLog()); client.project = project; Splitter splitter = Splitter.on(',').trimResults().omitEmptyStrings();; client.fields = ImmutableList.copyOf(splitter.splitToList(fields)); client.excludes = ImmutableMap.copyOf(parseExcludes(splitter.splitToList(excludes))); client.version = stripVersion(version, stripFixVersion); Predicate<String> prefilter = null; GitClient gitClient = null; if (gitEnabled) { gitClient = new GitClient(git, project, getLog()); prefilter = gitPrefilter(gitClient); } List<Change> changes = client.changes(prefilter); client.downloadImages(filter(changes, hasPreview()), new File(outputDirectory, "whatsnew-images")); if (gitEnabled) { changes = Lists.newArrayList(transform(changes, correctDate(gitClient))); Collections.sort(changes); Collections.reverse(changes); } Map<String, Object> context = Maps.newHashMap(); context.put("changes", changes); if (gitEnabled) { context.put("branch", gitClient.getResolvedHeadBranchName()); context.put("hash", gitClient.getResolvedHeadObjectId().getName()); } context.put("version", version); context.put("imagesDir", "whatsnew-images"); new WhatsNewTemplate(outputDirectory, templateFile, context).write(); }
public void execute() throws MojoExecutionException { if (settings == null) { throw new MojoExecutionException("No settings"); } Server server = settings.getServer(jiraId); if (server == null) { throw new MojoExecutionException(String.format("No server '%s' in settings", jiraId)); } JiraClient client = new JiraClient(jiraUrl, server.getUsername(), server.getPassword(), getLog()); client.project = project; Splitter splitter = Splitter.on(',').trimResults().omitEmptyStrings();; client.fields = ImmutableList.copyOf(splitter.splitToList(fields)); client.excludes = ImmutableMap.copyOf(parseExcludes(splitter.splitToList(excludes))); client.version = stripVersion(version, stripFixVersion); Predicate<String> prefilter = null; GitClient gitClient = null; if (gitEnabled) { gitClient = new GitClient(git, project, getLog()); prefilter = gitPrefilter(gitClient); } List<Change> changes = client.changes(prefilter); client.downloadImages(filter(changes, hasPreview()), new File(outputDirectory, "whatsnew-images")); if (gitEnabled) { changes = Lists.newArrayList(transform(changes, correctDate(gitClient))); Collections.sort(changes); Collections.reverse(changes); } Map<String, Object> context = Maps.newHashMap(); context.put("changes", changes); if (gitEnabled) { context.put("branch", gitClient.getResolvedHeadBranchName()); context.put("hash", gitClient.getResolvedHeadObjectId().getName()); } context.put("version", stripVersion(version, stripFixVersion)); context.put("imagesDir", "whatsnew-images"); new WhatsNewTemplate(outputDirectory, templateFile, context).write(); }
diff --git a/core/src/visad/trunk/bom/BarbRendererJ2D.java b/core/src/visad/trunk/bom/BarbRendererJ2D.java index 9d4b1e9b9..e455fcc96 100644 --- a/core/src/visad/trunk/bom/BarbRendererJ2D.java +++ b/core/src/visad/trunk/bom/BarbRendererJ2D.java @@ -1,197 +1,197 @@ // // BarbRendererJ2D.java // /* VisAD system for interactive analysis and visualization of numerical data. Copyright (C) 1996 - 1999 Bill Hibbard, Curtis Rueden, Tom Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and Tommy Jasmin. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ package visad.bom; import visad.*; import visad.java2d.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.*; import java.rmi.*; /** BarbRendererJ2D is the VisAD class for rendering of wind barbs under Java2D - otherwise it behaves just like DefaultRendererJ2D */ public class BarbRendererJ2D extends DefaultRendererJ2D { /** this DataRenderer supports direct manipulation for RealTuple representations of wind barbs; four of the RealTuple's Real components must be mapped to XAxis, YAxis, Flow1X and Flow1Y */ public BarbRendererJ2D () { super(); } public ShadowType makeShadowFunctionType( FunctionType type, DataDisplayLink link, ShadowType parent) throws VisADException, RemoteException { return new ShadowBarbFunctionTypeJ2D(type, link, parent); } public ShadowType makeShadowRealTupleType( RealTupleType type, DataDisplayLink link, ShadowType parent) throws VisADException, RemoteException { return new ShadowBarbRealTupleTypeJ2D(type, link, parent); } public ShadowType makeShadowRealType( RealType type, DataDisplayLink link, ShadowType parent) throws VisADException, RemoteException { return new ShadowBarbRealTypeJ2D(type, link, parent); } public ShadowType makeShadowSetType( SetType type, DataDisplayLink link, ShadowType parent) throws VisADException, RemoteException { return new ShadowBarbSetTypeJ2D(type, link, parent); } public ShadowType makeShadowTupleType( TupleType type, DataDisplayLink link, ShadowType parent) throws VisADException, RemoteException { return new ShadowBarbTupleTypeJ2D(type, link, parent); } static final int N = 5; /** run 'java visad.bom.BarbRendererJ2D middle_latitude' to test with Cartesian winds run 'java visad.bom.BarbRendererJ2D middle_latitude x' to test with polar winds adjust middle_latitude for south or north barbs */ public static void main(String args[]) throws VisADException, RemoteException { double mid_lat = -10.0; if (args.length > 0) { try { mid_lat = Double.valueOf(args[0]).doubleValue(); } catch(NumberFormatException e) { } } RealType lat = RealType.Latitude; RealType lon = RealType.Longitude; RealType flowx = new RealType("flowx", CommonUnit.meterPerSecond, null); RealType flowy = new RealType("flowy", CommonUnit.meterPerSecond, null); RealType red = new RealType("red"); RealType green = new RealType("green"); RealType index = new RealType("index"); EarthVectorType flowxy = new EarthVectorType(flowx, flowy); TupleType range = null; if (args.length > 1) { System.out.println("polar winds"); RealType flow_degree = new RealType("flow_degree", CommonUnit.degree, null); RealType flow_speed = new RealType("flow_speed", CommonUnit.meterPerSecond, null); RealTupleType flowds = new RealTupleType(new RealType[] {flow_degree, flow_speed}, new WindPolarCoordinateSystem(flowxy), null); range = new TupleType(new MathType[] {lon, lat, flowds, red, green}); } else { System.out.println("Cartesian winds"); range = new TupleType(new MathType[] {lon, lat, flowxy, red, green}); } FunctionType flow_field = new FunctionType(index, range); DisplayImpl display = new DisplayImplJ2D("display1"); ScalarMap xmap = new ScalarMap(lon, Display.XAxis); display.addMap(xmap); ScalarMap ymap = new ScalarMap(lat, Display.YAxis); display.addMap(ymap); ScalarMap flowx_map = new ScalarMap(flowx, Display.Flow1X); display.addMap(flowx_map); flowx_map.setRange(-1.0, 1.0); ScalarMap flowy_map = new ScalarMap(flowy, Display.Flow1Y); display.addMap(flowy_map); flowy_map.setRange(-1.0, 1.0); FlowControl flow_control = (FlowControl) flowy_map.getControl(); flow_control.setFlowScale(0.1f); display.addMap(new ScalarMap(red, Display.Red)); display.addMap(new ScalarMap(green, Display.Green)); display.addMap(new ConstantMap(1.0, Display.Blue)); Integer1DSet set = new Integer1DSet(N * N); double[][] values = new double[6][N * N]; int m = 0; for (int i=0; i<N; i++) { for (int j=0; j<N; j++) { double u = 2.0 * i / (N - 1.0) - 1.0; double v = 2.0 * j / (N - 1.0) - 1.0; values[0][m] = 10.0 * u; values[1][m] = 10.0 * v + mid_lat; double fx = 30.0 * u; double fy = 30.0 * v; if (args.length > 1) { values[2][m] = - Data.RADIANS_TO_DEGREES * Math.atan2(fx, fy); + Data.RADIANS_TO_DEGREES * Math.atan2(-fx, -fy); values[3][m] = Math.sqrt(fx * fx + fy * fy); } else { values[2][m] = fx; values[3][m] = fy; } values[4][m] = u; values[5][m] = v; m++; } } FlatField field = new FlatField(flow_field, set); field.setSamples(values); DataReferenceImpl ref = new DataReferenceImpl("ref"); ref.setData(field); display.addReferences(new BarbRendererJ2D(), ref); // create JFrame (i.e., a window) for display and slider JFrame frame = new JFrame("test BarbRendererJ2D"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); // create JPanel in JFrame JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.setAlignmentY(JPanel.TOP_ALIGNMENT); panel.setAlignmentX(JPanel.LEFT_ALIGNMENT); frame.getContentPane().add(panel); // add display to JPanel panel.add(display.getComponent()); // set size of JFrame and make it visible frame.setSize(500, 500); frame.setVisible(true); } }
true
true
public static void main(String args[]) throws VisADException, RemoteException { double mid_lat = -10.0; if (args.length > 0) { try { mid_lat = Double.valueOf(args[0]).doubleValue(); } catch(NumberFormatException e) { } } RealType lat = RealType.Latitude; RealType lon = RealType.Longitude; RealType flowx = new RealType("flowx", CommonUnit.meterPerSecond, null); RealType flowy = new RealType("flowy", CommonUnit.meterPerSecond, null); RealType red = new RealType("red"); RealType green = new RealType("green"); RealType index = new RealType("index"); EarthVectorType flowxy = new EarthVectorType(flowx, flowy); TupleType range = null; if (args.length > 1) { System.out.println("polar winds"); RealType flow_degree = new RealType("flow_degree", CommonUnit.degree, null); RealType flow_speed = new RealType("flow_speed", CommonUnit.meterPerSecond, null); RealTupleType flowds = new RealTupleType(new RealType[] {flow_degree, flow_speed}, new WindPolarCoordinateSystem(flowxy), null); range = new TupleType(new MathType[] {lon, lat, flowds, red, green}); } else { System.out.println("Cartesian winds"); range = new TupleType(new MathType[] {lon, lat, flowxy, red, green}); } FunctionType flow_field = new FunctionType(index, range); DisplayImpl display = new DisplayImplJ2D("display1"); ScalarMap xmap = new ScalarMap(lon, Display.XAxis); display.addMap(xmap); ScalarMap ymap = new ScalarMap(lat, Display.YAxis); display.addMap(ymap); ScalarMap flowx_map = new ScalarMap(flowx, Display.Flow1X); display.addMap(flowx_map); flowx_map.setRange(-1.0, 1.0); ScalarMap flowy_map = new ScalarMap(flowy, Display.Flow1Y); display.addMap(flowy_map); flowy_map.setRange(-1.0, 1.0); FlowControl flow_control = (FlowControl) flowy_map.getControl(); flow_control.setFlowScale(0.1f); display.addMap(new ScalarMap(red, Display.Red)); display.addMap(new ScalarMap(green, Display.Green)); display.addMap(new ConstantMap(1.0, Display.Blue)); Integer1DSet set = new Integer1DSet(N * N); double[][] values = new double[6][N * N]; int m = 0; for (int i=0; i<N; i++) { for (int j=0; j<N; j++) { double u = 2.0 * i / (N - 1.0) - 1.0; double v = 2.0 * j / (N - 1.0) - 1.0; values[0][m] = 10.0 * u; values[1][m] = 10.0 * v + mid_lat; double fx = 30.0 * u; double fy = 30.0 * v; if (args.length > 1) { values[2][m] = Data.RADIANS_TO_DEGREES * Math.atan2(fx, fy); values[3][m] = Math.sqrt(fx * fx + fy * fy); } else { values[2][m] = fx; values[3][m] = fy; } values[4][m] = u; values[5][m] = v; m++; } } FlatField field = new FlatField(flow_field, set); field.setSamples(values); DataReferenceImpl ref = new DataReferenceImpl("ref"); ref.setData(field); display.addReferences(new BarbRendererJ2D(), ref); // create JFrame (i.e., a window) for display and slider JFrame frame = new JFrame("test BarbRendererJ2D"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); // create JPanel in JFrame JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.setAlignmentY(JPanel.TOP_ALIGNMENT); panel.setAlignmentX(JPanel.LEFT_ALIGNMENT); frame.getContentPane().add(panel); // add display to JPanel panel.add(display.getComponent()); // set size of JFrame and make it visible frame.setSize(500, 500); frame.setVisible(true); }
public static void main(String args[]) throws VisADException, RemoteException { double mid_lat = -10.0; if (args.length > 0) { try { mid_lat = Double.valueOf(args[0]).doubleValue(); } catch(NumberFormatException e) { } } RealType lat = RealType.Latitude; RealType lon = RealType.Longitude; RealType flowx = new RealType("flowx", CommonUnit.meterPerSecond, null); RealType flowy = new RealType("flowy", CommonUnit.meterPerSecond, null); RealType red = new RealType("red"); RealType green = new RealType("green"); RealType index = new RealType("index"); EarthVectorType flowxy = new EarthVectorType(flowx, flowy); TupleType range = null; if (args.length > 1) { System.out.println("polar winds"); RealType flow_degree = new RealType("flow_degree", CommonUnit.degree, null); RealType flow_speed = new RealType("flow_speed", CommonUnit.meterPerSecond, null); RealTupleType flowds = new RealTupleType(new RealType[] {flow_degree, flow_speed}, new WindPolarCoordinateSystem(flowxy), null); range = new TupleType(new MathType[] {lon, lat, flowds, red, green}); } else { System.out.println("Cartesian winds"); range = new TupleType(new MathType[] {lon, lat, flowxy, red, green}); } FunctionType flow_field = new FunctionType(index, range); DisplayImpl display = new DisplayImplJ2D("display1"); ScalarMap xmap = new ScalarMap(lon, Display.XAxis); display.addMap(xmap); ScalarMap ymap = new ScalarMap(lat, Display.YAxis); display.addMap(ymap); ScalarMap flowx_map = new ScalarMap(flowx, Display.Flow1X); display.addMap(flowx_map); flowx_map.setRange(-1.0, 1.0); ScalarMap flowy_map = new ScalarMap(flowy, Display.Flow1Y); display.addMap(flowy_map); flowy_map.setRange(-1.0, 1.0); FlowControl flow_control = (FlowControl) flowy_map.getControl(); flow_control.setFlowScale(0.1f); display.addMap(new ScalarMap(red, Display.Red)); display.addMap(new ScalarMap(green, Display.Green)); display.addMap(new ConstantMap(1.0, Display.Blue)); Integer1DSet set = new Integer1DSet(N * N); double[][] values = new double[6][N * N]; int m = 0; for (int i=0; i<N; i++) { for (int j=0; j<N; j++) { double u = 2.0 * i / (N - 1.0) - 1.0; double v = 2.0 * j / (N - 1.0) - 1.0; values[0][m] = 10.0 * u; values[1][m] = 10.0 * v + mid_lat; double fx = 30.0 * u; double fy = 30.0 * v; if (args.length > 1) { values[2][m] = Data.RADIANS_TO_DEGREES * Math.atan2(-fx, -fy); values[3][m] = Math.sqrt(fx * fx + fy * fy); } else { values[2][m] = fx; values[3][m] = fy; } values[4][m] = u; values[5][m] = v; m++; } } FlatField field = new FlatField(flow_field, set); field.setSamples(values); DataReferenceImpl ref = new DataReferenceImpl("ref"); ref.setData(field); display.addReferences(new BarbRendererJ2D(), ref); // create JFrame (i.e., a window) for display and slider JFrame frame = new JFrame("test BarbRendererJ2D"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); // create JPanel in JFrame JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.setAlignmentY(JPanel.TOP_ALIGNMENT); panel.setAlignmentX(JPanel.LEFT_ALIGNMENT); frame.getContentPane().add(panel); // add display to JPanel panel.add(display.getComponent()); // set size of JFrame and make it visible frame.setSize(500, 500); frame.setVisible(true); }
diff --git a/twitter4j-core/src/test/java/twitter4j/SearchAPITest.java b/twitter4j-core/src/test/java/twitter4j/SearchAPITest.java index 27958a01..677c67ed 100644 --- a/twitter4j-core/src/test/java/twitter4j/SearchAPITest.java +++ b/twitter4j-core/src/test/java/twitter4j/SearchAPITest.java @@ -1,199 +1,199 @@ /* Copyright (c) 2007-2010, Yusuke Yamamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package twitter4j; import twitter4j.internal.http.HttpParameter; import java.text.SimpleDateFormat; import java.util.List; import java.util.Date; public class SearchAPITest extends TwitterTestBase { public SearchAPITest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public void testQuery() throws Exception { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Query query = new Query("test") .until(format.format(new java.util.Date(System.currentTimeMillis() - 3600*24))); HttpParameter[] params = query.asHttpParameterArray(); assertTrue(findParameter(params,"q")); assertTrue(findParameter(params,"until")); } private boolean findParameter(HttpParameter[] params, String paramName){ boolean found = false; for(HttpParameter param: params){ if(paramName.equals(param.getName())){ found = true; break; } } return found; } public void testSearch() throws Exception { String queryStr = "test"; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); - String dateStr = format.format(new java.util.Date()); + String dateStr = format.format(new java.util.Date(System.currentTimeMillis() - 24 * 3600 * 1000)); Query query = new Query(queryStr).until(dateStr); QueryResult queryResult = unauthenticated.search(query); assertTrue("sinceId", -1 != queryResult.getSinceId()); assertTrue(1265204883 < queryResult.getMaxId()); assertTrue(-1 != queryResult.getRefreshUrl().indexOf(queryStr)); assertEquals(15, queryResult.getResultsPerPage()); assertTrue(0 < queryResult.getCompletedIn()); assertEquals(1, queryResult.getPage()); assertEquals(queryStr + " until:"+ dateStr, queryResult.getQuery()); List<Tweet> tweets = queryResult.getTweets(); assertTrue(1<=tweets.size()); assertNotNull(tweets.get(0).getText()); assertNotNull(tweets.get(0).getCreatedAt()); assertNotNull("from user", tweets.get(0).getFromUser()); assertTrue("fromUserId", -1 != tweets.get(0).getFromUserId()); assertTrue(-1 != tweets.get(0).getId()); // assertNotNull(tweets.get(0).getIsoLanguageCode()); String profileImageURL = tweets.get(0).getProfileImageUrl(); assertTrue(-1 != profileImageURL.toLowerCase().indexOf(".jpg") || -1 != profileImageURL.toLowerCase().indexOf(".png") || -1 != profileImageURL.toLowerCase().indexOf(".gif")); String source = tweets.get(0).getSource(); assertTrue(-1 != source.indexOf("<a href=\"") || "web".equals(source) || "API".equals(source)); query = new Query("from:twit4j doesnothit"); queryResult = unauthenticated.search(query); assertEquals(0, queryResult.getSinceId()); assertEquals(-1, queryResult.getMaxId()); assertNull(queryResult.getRefreshUrl()); assertEquals(15, queryResult.getResultsPerPage()); // assertEquals(-1, queryResult.getTotal()); assertNull(queryResult.getWarning()); assertTrue(1 > queryResult.getCompletedIn()); assertEquals(1, queryResult.getPage()); assertEquals("from:twit4j doesnothit", queryResult.getQuery()); queryStr = "%... 日本語"; twitterAPI1.updateStatus("%... 日本語"); query = new Query("%... 日本語"); queryResult = unauthenticated.search(query); assertEquals(queryStr, queryResult.getQuery()); assertTrue(0 < queryResult.getTweets().size()); query.setQuery("from:al3x"); query.setGeoCode(new GeoLocation(37.78233252646689,-122.39301681518555) ,10,Query.KILOMETERS); queryResult = unauthenticated.search(query); assertTrue(0 < queryResult.getTweets().size()); query = new Query("from:beastieboys"); query.setSinceId(1671199128); queryResult = unauthenticated.search(query); assertEquals(0, queryResult.getTweets().size()); query = new Query("\\u5e30%u5e30 <%}& foobar").rpp(100).page(1); QueryResult result = twitterAPI1.search(query); } public void testTrends() throws Exception{ Trends trends; trends = unauthenticated.getTrends(); assertTrue(100000 > (trends.getAsOf().getTime() - System.currentTimeMillis())); assertEquals(10, trends.getTrends().length); for (int i = 0; i < 10; i++) { assertNotNull(trends.getTrends()[i].getName()); assertNotNull(trends.getTrends()[i].getUrl()); assertNull(trends.getTrends()[i].getQuery()); trends.getTrends()[i].hashCode(); trends.getTrends()[i].toString(); } trends = unauthenticated.getCurrentTrends(); assertTrue(100000 > (trends.getAsOf().getTime() - System.currentTimeMillis())); assertEquals(10, trends.getTrends().length); for (Trend trend : trends.getTrends()) { assertNotNull(trend.getName()); assertNull(trend.getUrl()); assertNotNull(trend.getQuery()); trend.hashCode(); trend.toString(); } trends = unauthenticated.getCurrentTrends(true); assertTrue(100000 > (trends.getAsOf().getTime() - System.currentTimeMillis())); Trend[] trendArray = trends.getTrends(); assertEquals(10, trendArray.length); for (Trend trend : trends.getTrends()) { assertNotNull(trend.getName()); assertNull(trend.getUrl()); assertNotNull(trend.getQuery()); trend.hashCode(); trend.toString(); } List<Trends> trendsList; trendsList = unauthenticated.getDailyTrends(); assertTrue(100000 > (trends.getAsOf().getTime() - System.currentTimeMillis())); assertTrends(trendsList,20); trendsList = unauthenticated.getDailyTrends(new Date(), true); assertTrue(100000 > (trends.getAsOf().getTime() - System.currentTimeMillis())); assertTrends(trendsList,20); trendsList = unauthenticated.getWeeklyTrends(); assertTrue(100000 > (trends.getAsOf().getTime() - System.currentTimeMillis())); assertTrends(trendsList,30); trendsList = unauthenticated.getWeeklyTrends(new Date(), true); assertTrue(100000 > (trends.getAsOf().getTime() - System.currentTimeMillis())); assertTrends(trendsList,30); } private void assertTrends(List<Trends> trendsArray, int expectedSize) throws Exception{ Date trendAt = null; for(Trends singleTrends : trendsArray){ assertEquals(expectedSize, singleTrends.getTrends().length); if(null != trendAt){ assertTrue(trendAt.before(singleTrends.getTrendAt())); } trendAt = singleTrends.getTrendAt(); for (int i = 0; i < singleTrends.getTrends().length; i++) { assertNotNull(singleTrends.getTrends()[i].getName()); assertNull(singleTrends.getTrends()[i].getUrl()); assertNotNull(singleTrends.getTrends()[i].getQuery()); } } } }
true
true
public void testSearch() throws Exception { String queryStr = "test"; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String dateStr = format.format(new java.util.Date()); Query query = new Query(queryStr).until(dateStr); QueryResult queryResult = unauthenticated.search(query); assertTrue("sinceId", -1 != queryResult.getSinceId()); assertTrue(1265204883 < queryResult.getMaxId()); assertTrue(-1 != queryResult.getRefreshUrl().indexOf(queryStr)); assertEquals(15, queryResult.getResultsPerPage()); assertTrue(0 < queryResult.getCompletedIn()); assertEquals(1, queryResult.getPage()); assertEquals(queryStr + " until:"+ dateStr, queryResult.getQuery()); List<Tweet> tweets = queryResult.getTweets(); assertTrue(1<=tweets.size()); assertNotNull(tweets.get(0).getText()); assertNotNull(tweets.get(0).getCreatedAt()); assertNotNull("from user", tweets.get(0).getFromUser()); assertTrue("fromUserId", -1 != tweets.get(0).getFromUserId()); assertTrue(-1 != tweets.get(0).getId()); // assertNotNull(tweets.get(0).getIsoLanguageCode()); String profileImageURL = tweets.get(0).getProfileImageUrl(); assertTrue(-1 != profileImageURL.toLowerCase().indexOf(".jpg") || -1 != profileImageURL.toLowerCase().indexOf(".png") || -1 != profileImageURL.toLowerCase().indexOf(".gif")); String source = tweets.get(0).getSource(); assertTrue(-1 != source.indexOf("<a href=\"") || "web".equals(source) || "API".equals(source)); query = new Query("from:twit4j doesnothit"); queryResult = unauthenticated.search(query); assertEquals(0, queryResult.getSinceId()); assertEquals(-1, queryResult.getMaxId()); assertNull(queryResult.getRefreshUrl()); assertEquals(15, queryResult.getResultsPerPage()); // assertEquals(-1, queryResult.getTotal()); assertNull(queryResult.getWarning()); assertTrue(1 > queryResult.getCompletedIn()); assertEquals(1, queryResult.getPage()); assertEquals("from:twit4j doesnothit", queryResult.getQuery()); queryStr = "%... 日本語"; twitterAPI1.updateStatus("%... 日本語"); query = new Query("%... 日本語"); queryResult = unauthenticated.search(query); assertEquals(queryStr, queryResult.getQuery()); assertTrue(0 < queryResult.getTweets().size()); query.setQuery("from:al3x"); query.setGeoCode(new GeoLocation(37.78233252646689,-122.39301681518555) ,10,Query.KILOMETERS); queryResult = unauthenticated.search(query); assertTrue(0 < queryResult.getTweets().size()); query = new Query("from:beastieboys"); query.setSinceId(1671199128); queryResult = unauthenticated.search(query); assertEquals(0, queryResult.getTweets().size()); query = new Query("\\u5e30%u5e30 <%}& foobar").rpp(100).page(1); QueryResult result = twitterAPI1.search(query); }
public void testSearch() throws Exception { String queryStr = "test"; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String dateStr = format.format(new java.util.Date(System.currentTimeMillis() - 24 * 3600 * 1000)); Query query = new Query(queryStr).until(dateStr); QueryResult queryResult = unauthenticated.search(query); assertTrue("sinceId", -1 != queryResult.getSinceId()); assertTrue(1265204883 < queryResult.getMaxId()); assertTrue(-1 != queryResult.getRefreshUrl().indexOf(queryStr)); assertEquals(15, queryResult.getResultsPerPage()); assertTrue(0 < queryResult.getCompletedIn()); assertEquals(1, queryResult.getPage()); assertEquals(queryStr + " until:"+ dateStr, queryResult.getQuery()); List<Tweet> tweets = queryResult.getTweets(); assertTrue(1<=tweets.size()); assertNotNull(tweets.get(0).getText()); assertNotNull(tweets.get(0).getCreatedAt()); assertNotNull("from user", tweets.get(0).getFromUser()); assertTrue("fromUserId", -1 != tweets.get(0).getFromUserId()); assertTrue(-1 != tweets.get(0).getId()); // assertNotNull(tweets.get(0).getIsoLanguageCode()); String profileImageURL = tweets.get(0).getProfileImageUrl(); assertTrue(-1 != profileImageURL.toLowerCase().indexOf(".jpg") || -1 != profileImageURL.toLowerCase().indexOf(".png") || -1 != profileImageURL.toLowerCase().indexOf(".gif")); String source = tweets.get(0).getSource(); assertTrue(-1 != source.indexOf("<a href=\"") || "web".equals(source) || "API".equals(source)); query = new Query("from:twit4j doesnothit"); queryResult = unauthenticated.search(query); assertEquals(0, queryResult.getSinceId()); assertEquals(-1, queryResult.getMaxId()); assertNull(queryResult.getRefreshUrl()); assertEquals(15, queryResult.getResultsPerPage()); // assertEquals(-1, queryResult.getTotal()); assertNull(queryResult.getWarning()); assertTrue(1 > queryResult.getCompletedIn()); assertEquals(1, queryResult.getPage()); assertEquals("from:twit4j doesnothit", queryResult.getQuery()); queryStr = "%... 日本語"; twitterAPI1.updateStatus("%... 日本語"); query = new Query("%... 日本語"); queryResult = unauthenticated.search(query); assertEquals(queryStr, queryResult.getQuery()); assertTrue(0 < queryResult.getTweets().size()); query.setQuery("from:al3x"); query.setGeoCode(new GeoLocation(37.78233252646689,-122.39301681518555) ,10,Query.KILOMETERS); queryResult = unauthenticated.search(query); assertTrue(0 < queryResult.getTweets().size()); query = new Query("from:beastieboys"); query.setSinceId(1671199128); queryResult = unauthenticated.search(query); assertEquals(0, queryResult.getTweets().size()); query = new Query("\\u5e30%u5e30 <%}& foobar").rpp(100).page(1); QueryResult result = twitterAPI1.search(query); }
diff --git a/src/de/htwg/wzzrd/util/IObserver.java b/src/de/htwg/wzzrd/util/IObserver.java index a82a817..096293e 100644 --- a/src/de/htwg/wzzrd/util/IObserver.java +++ b/src/de/htwg/wzzrd/util/IObserver.java @@ -1,5 +1,5 @@ package de.htwg.wzzrd.util; public interface IObserver { - public abstract void update(UIObservable ui); + void update(UIObservable ui); }
true
true
public abstract void update(UIObservable ui);
void update(UIObservable ui);
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/core/refactoring/LaunchConfigurationProjectMainTypeChange.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/core/refactoring/LaunchConfigurationProjectMainTypeChange.java index 999eae47e..c9018db3d 100644 --- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/core/refactoring/LaunchConfigurationProjectMainTypeChange.java +++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/core/refactoring/LaunchConfigurationProjectMainTypeChange.java @@ -1,173 +1,171 @@ /******************************************************************************* * Copyright (c) 2003, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.debug.core.refactoring; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.internal.launching.JavaMigrationDelegate; import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants; import org.eclipse.ltk.core.refactoring.Change; import org.eclipse.ltk.core.refactoring.RefactoringStatus; import com.ibm.icu.text.MessageFormat; /** * The change for the main type project change of a launch configuration */ public class LaunchConfigurationProjectMainTypeChange extends Change { private ILaunchConfiguration fLaunchConfiguration; private String fNewMainTypeName; private String fNewProjectName; private String fNewLaunchConfigurationName; private String fOldMainTypeName; private String fOldProjectName; private String fNewConfigContainerName; /** * LaunchConfigurationProjectMainTypeChange constructor. * @param launchConfiguration the launch configuration to modify * @param newMainTypeName the name of the new main type, or <code>null</code> if not modified. * @param newProjectName the name of the project, or <code>null</code> if not modified. */ public LaunchConfigurationProjectMainTypeChange(ILaunchConfiguration launchConfiguration, String newMainTypeName, String newProjectName) throws CoreException { fLaunchConfiguration = launchConfiguration; fNewMainTypeName = newMainTypeName; fNewProjectName = newProjectName; fOldMainTypeName = fLaunchConfiguration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, (String) null); fOldProjectName = fLaunchConfiguration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, (String) null); if (fNewMainTypeName != null) { // generate the new configuration name String oldName = Signature.getSimpleName(fOldMainTypeName); String newName = Signature.getSimpleName(fNewMainTypeName); String lcname = fLaunchConfiguration.getName(); fNewLaunchConfigurationName = lcname.replaceAll(oldName, newName); if (lcname.equals(fNewLaunchConfigurationName) || DebugPlugin.getDefault().getLaunchManager().isExistingLaunchConfigurationName(fNewLaunchConfigurationName)) { fNewLaunchConfigurationName = null; } } } /* (non-Javadoc) * @see org.eclipse.ltk.core.refactoring.Change#getModifiedElement() */ public Object getModifiedElement() { return fLaunchConfiguration; } /* (non-Javadoc) * @see org.eclipse.ltk.core.refactoring.Change#getName() */ public String getName() { if (fNewLaunchConfigurationName != null) { return MessageFormat.format(RefactoringMessages.LaunchConfigurationProjectMainTypeChange_0, new String[] {fLaunchConfiguration.getName(), fNewLaunchConfigurationName}); } if (fNewProjectName == null) { return MessageFormat.format(RefactoringMessages.LaunchConfigurationProjectMainTypeChange_1, new String[] {fLaunchConfiguration.getName()}); } if (fNewMainTypeName == null) { return MessageFormat.format(RefactoringMessages.LaunchConfigurationProjectMainTypeChange_2, new String[] {fLaunchConfiguration.getName()}); } return MessageFormat.format(RefactoringMessages.LaunchConfigurationProjectMainTypeChange_3, new String[] {fLaunchConfiguration.getName()}); } /* (non-Javadoc) * @see org.eclipse.ltk.core.refactoring.Change#initializeValidationData(org.eclipse.core.runtime.IProgressMonitor) */ public void initializeValidationData(IProgressMonitor pm) {} /* (non-Javadoc) * @see org.eclipse.ltk.core.refactoring.Change#isValid(org.eclipse.core.runtime.IProgressMonitor) */ public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException, OperationCanceledException { if (fLaunchConfiguration.exists()) { String typeName = fLaunchConfiguration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, (String)null); String projectName = fLaunchConfiguration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, (String)null); if(fOldMainTypeName != null) { if (fOldMainTypeName.equals(typeName)) { if (fOldProjectName.equals(projectName)) { return new RefactoringStatus(); } return RefactoringStatus.createWarningStatus(MessageFormat.format(RefactoringMessages.LaunchConfigurationProjectMainTypeChange_4, new String[] {fLaunchConfiguration.getName(), fOldProjectName})); } return RefactoringStatus.createWarningStatus(MessageFormat.format(RefactoringMessages.LaunchConfigurationProjectMainTypeChange_5, new String[] {fLaunchConfiguration.getName(), fOldMainTypeName})); } else { //need to catch the case for remote java LC's, they have no maintype if (fOldProjectName.equals(projectName)) { return new RefactoringStatus(); } return RefactoringStatus.createWarningStatus(MessageFormat.format(RefactoringMessages.LaunchConfigurationProjectMainTypeChange_4, new String[] {fLaunchConfiguration.getName(), fOldProjectName})); } } return RefactoringStatus.createFatalErrorStatus(MessageFormat.format(RefactoringMessages.LaunchConfigurationProjectMainTypeChange_6, new String[] {fLaunchConfiguration.getName()})); } /* (non-Javadoc) * @see org.eclipse.ltk.core.refactoring.Change#perform(org.eclipse.core.runtime.IProgressMonitor) */ public Change perform(IProgressMonitor pm) throws CoreException { final ILaunchConfigurationWorkingCopy wc = fLaunchConfiguration.getWorkingCopy(); if (fNewConfigContainerName != null) { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = workspace.getRoot(); IProject project = root.getProject(fNewProjectName); IContainer container = (IContainer) project.findMember(fNewConfigContainerName); wc.setContainer(container); } String oldMainTypeName; String oldProjectName; if (fNewMainTypeName != null) { oldMainTypeName = fOldMainTypeName; wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, fNewMainTypeName); } else { oldMainTypeName = null; } if (fNewProjectName != null) { oldProjectName = fOldProjectName; wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, fNewProjectName); - //CONTEXTLAUNCHING - JavaMigrationDelegate.updateResourceMapping(wc); } else { oldProjectName = null; } if (fNewLaunchConfigurationName != null) { wc.rename(fNewLaunchConfigurationName); } // update resource mapping JavaMigrationDelegate.updateResourceMapping(wc); if (wc.isDirty()) { fLaunchConfiguration = wc.doSave(); } // create the undo change return new LaunchConfigurationProjectMainTypeChange(wc, oldMainTypeName, oldProjectName); } /** * Sets the new container name * @param newContainerName the new name for the container */ public void setNewContainerName(String newContainerName) { fNewConfigContainerName = newContainerName; } }
true
true
public Change perform(IProgressMonitor pm) throws CoreException { final ILaunchConfigurationWorkingCopy wc = fLaunchConfiguration.getWorkingCopy(); if (fNewConfigContainerName != null) { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = workspace.getRoot(); IProject project = root.getProject(fNewProjectName); IContainer container = (IContainer) project.findMember(fNewConfigContainerName); wc.setContainer(container); } String oldMainTypeName; String oldProjectName; if (fNewMainTypeName != null) { oldMainTypeName = fOldMainTypeName; wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, fNewMainTypeName); } else { oldMainTypeName = null; } if (fNewProjectName != null) { oldProjectName = fOldProjectName; wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, fNewProjectName); //CONTEXTLAUNCHING JavaMigrationDelegate.updateResourceMapping(wc); } else { oldProjectName = null; } if (fNewLaunchConfigurationName != null) { wc.rename(fNewLaunchConfigurationName); } // update resource mapping JavaMigrationDelegate.updateResourceMapping(wc); if (wc.isDirty()) { fLaunchConfiguration = wc.doSave(); } // create the undo change return new LaunchConfigurationProjectMainTypeChange(wc, oldMainTypeName, oldProjectName); }
public Change perform(IProgressMonitor pm) throws CoreException { final ILaunchConfigurationWorkingCopy wc = fLaunchConfiguration.getWorkingCopy(); if (fNewConfigContainerName != null) { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = workspace.getRoot(); IProject project = root.getProject(fNewProjectName); IContainer container = (IContainer) project.findMember(fNewConfigContainerName); wc.setContainer(container); } String oldMainTypeName; String oldProjectName; if (fNewMainTypeName != null) { oldMainTypeName = fOldMainTypeName; wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, fNewMainTypeName); } else { oldMainTypeName = null; } if (fNewProjectName != null) { oldProjectName = fOldProjectName; wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, fNewProjectName); } else { oldProjectName = null; } if (fNewLaunchConfigurationName != null) { wc.rename(fNewLaunchConfigurationName); } // update resource mapping JavaMigrationDelegate.updateResourceMapping(wc); if (wc.isDirty()) { fLaunchConfiguration = wc.doSave(); } // create the undo change return new LaunchConfigurationProjectMainTypeChange(wc, oldMainTypeName, oldProjectName); }
diff --git a/org.eclipse.nebula.widgets.nattable.core/src/org/eclipse/nebula/widgets/nattable/ui/matcher/LetterOrDigitKeyEventMatcher.java b/org.eclipse.nebula.widgets.nattable.core/src/org/eclipse/nebula/widgets/nattable/ui/matcher/LetterOrDigitKeyEventMatcher.java index ebb2cd77..49f649f5 100644 --- a/org.eclipse.nebula.widgets.nattable.core/src/org/eclipse/nebula/widgets/nattable/ui/matcher/LetterOrDigitKeyEventMatcher.java +++ b/org.eclipse.nebula.widgets.nattable.core/src/org/eclipse/nebula/widgets/nattable/ui/matcher/LetterOrDigitKeyEventMatcher.java @@ -1,82 +1,82 @@ /******************************************************************************* * Copyright (c) 2012 Original authors and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Original authors and others - initial API and implementation ******************************************************************************/ package org.eclipse.nebula.widgets.nattable.ui.matcher; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyEvent; /** * {@link IKeyEventMatcher} implementation that will check if a pressed key * is a letter or digit key, in combination with the configured state mask * for the keyboard modifier. * <p> * Since 1.0.0 this matcher has evolved to match more than only letter or * digit keys. It will now also check for several special characters that * are able to be populated to an editor like e.g. the question mark. The * following regular expression will be used by this matcher: * * <b>[\\.:,;\\-_#\'+*~!?§$%&/()\\[\\]\\{\\}=\\\\\"]</b> */ public class LetterOrDigitKeyEventMatcher implements IKeyEventMatcher { /** * The state of the keyboard modifier keys at the time * the event was generated, as defined by the key code * constants in class <code>SWT</code>. */ private int stateMask; /** * Will create a new key event matcher that accepts no keyboard * modifiers on typing a key. */ public LetterOrDigitKeyEventMatcher() { this(SWT.NONE); } /** * Will create a new key event matcher that accepts only the given * keyboard modifiers on typing a key. * @param stateMask The state of the keyboard modifier keys at the time * the event was generated, as defined by the key code * constants in class <code>SWT</code>. */ public LetterOrDigitKeyEventMatcher(int stateMask) { this.stateMask = stateMask; } /* (non-Javadoc) * @see org.eclipse.nebula.widgets.nattable.ui.matcher.IKeyEventMatcher#matches(org.eclipse.swt.events.KeyEvent) */ @Override public boolean matches(KeyEvent event) { return event.stateMask == this.stateMask && isLetterOrDigit(event.character); } /** * Will check if the given character is a letter or digit character, and moreover * will check special characters that can be typed that will cause a character to * be printed. * <p> * This method is intended to be used to determine whether a keypress is able to * open an editor, populating the representing character of the key to the editor. * @param character The character to check if it is a letter, digit or * specified special character. * @return <code>true</code> if the character is an acceptable character, * <code>false</code> if not. */ public static boolean isLetterOrDigit(char character) { return Character.isLetterOrDigit(character) || Character.valueOf(character).toString().matches( - "[\\.:,;\\-_#\'+*~!?�$%&/()\\[\\]\\{\\}=\\\\\"]"); //$NON-NLS-1$ + "[\\.:,;\\-_#\'+*~!?§$%&/()\\[\\]\\{\\}=\\\\\"]"); //$NON-NLS-1$ } }
true
true
public static boolean isLetterOrDigit(char character) { return Character.isLetterOrDigit(character) || Character.valueOf(character).toString().matches( "[\\.:,;\\-_#\'+*~!?�$%&/()\\[\\]\\{\\}=\\\\\"]"); //$NON-NLS-1$ }
public static boolean isLetterOrDigit(char character) { return Character.isLetterOrDigit(character) || Character.valueOf(character).toString().matches( "[\\.:,;\\-_#\'+*~!?§$%&/()\\[\\]\\{\\}=\\\\\"]"); //$NON-NLS-1$ }
diff --git a/src/uk/ac/cam/db538/dexter/dex/code/insn/DexInstruction.java b/src/uk/ac/cam/db538/dexter/dex/code/insn/DexInstruction.java index f42b4827..1a1bf24a 100644 --- a/src/uk/ac/cam/db538/dexter/dex/code/insn/DexInstruction.java +++ b/src/uk/ac/cam/db538/dexter/dex/code/insn/DexInstruction.java @@ -1,181 +1,184 @@ package uk.ac.cam.db538.dexter.dex.code.insn; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import lombok.val; import uk.ac.cam.db538.dexter.dex.code.DexCode; import uk.ac.cam.db538.dexter.dex.code.DexCode_InstrumentationState; import uk.ac.cam.db538.dexter.dex.code.DexRegister; import uk.ac.cam.db538.dexter.dex.code.elem.DexCatchAll; import uk.ac.cam.db538.dexter.dex.code.elem.DexCodeElement; import uk.ac.cam.db538.dexter.dex.code.elem.DexLabel; import uk.ac.cam.db538.dexter.dex.code.elem.DexTryBlockEnd; import uk.ac.cam.db538.dexter.dex.code.elem.DexTryBlockStart; import uk.ac.cam.db538.dexter.dex.type.DexClassType; public abstract class DexInstruction extends DexCodeElement { public DexInstruction(DexCode methodCode) { super(methodCode); } // PARSING protected static final InstructionParsingException FORMAT_EXCEPTION = new InstructionParsingException("Unknown instruction format or opcode"); // INSTRUCTION INSTRUMENTATION public void instrument(DexCode_InstrumentationState state) { throw new UnsupportedOperationException("Instruction " + this.getClass().getSimpleName() + " doesn't have instrumentation implemented"); } // THROWING INSTRUCTIONS @Override public final boolean cfgExitsMethod() { val jumpTargets = this.cfgJumpTargets(); if (jumpTargets.isEmpty()) return true; val exceptions = this.throwsExceptions(); if (exceptions != null) for (val exception : exceptions) if (throwingInsn_CanExitMethod(exception)) return true; return false; } // protected final boolean throwingInsn_CanExitMethod() { // return throwingInsn_CanExitMethod( // DexClassType.parse("Ljava/lang/Throwable;", // getParentFile().getParsingCache())); // } protected final boolean throwingInsn_CanExitMethod(DexClassType thrownExceptionType) { val code = getMethodCode(); val classHierarchy = getParentFile().getClassHierarchy(); for (val tryBlockEnd : code.getTryBlocks()) { val tryBlockStart = tryBlockEnd.getBlockStart(); // check that the instruction is in this try block if (code.isBetween(tryBlockStart, tryBlockEnd, this)) { // if the block has CatchAll handler, it can't exit the method if (tryBlockStart.getCatchAllHandler() != null) return false; // if there is a catch block catching the exception or its ancestor, // it can't exit the method either for (val catchBlock : tryBlockStart.getCatchHandlers()) if (classHierarchy.isAncestor(thrownExceptionType, catchBlock.getExceptionType())) return false; } } return true; } protected final Set<DexCodeElement> throwingInsn_CatchHandlers(DexClassType thrownExceptionType) { val set = new HashSet<DexCodeElement>(); val code = getMethodCode(); val classHierarchy = getParentFile().getClassHierarchy(); for (val tryBlockEnd : code.getTryBlocks()) { val tryBlockStart = tryBlockEnd.getBlockStart(); // check that the instruction is in this try block if (code.isBetween(tryBlockStart, tryBlockEnd, this)) { // if the block has CatchAll handler, it can jump to it val catchAllHandler = tryBlockStart.getCatchAllHandler(); if (catchAllHandler != null) set.add(catchAllHandler); // similarly, add all catch blocks as possible successors - // if they catch the given exception type or its ancestor + // if either they catch the given exception type or its ancestor (a guaranteed catch) + // or if the catch is the subclass of the thrown exception (a potential catch) for (val catchBlock : tryBlockStart.getCatchHandlers()) - if (thrownExceptionType == null || classHierarchy.isAncestor(thrownExceptionType, catchBlock.getExceptionType())) + if (thrownExceptionType == null || + classHierarchy.isAncestor(catchBlock.getExceptionType(), thrownExceptionType) || + classHierarchy.isAncestor(thrownExceptionType, catchBlock.getExceptionType())) set.add(catchBlock); } } return set; } protected final Set<DexCodeElement> throwingInsn_CatchHandlers() { return throwingInsn_CatchHandlers(null); } protected final DexTryBlockEnd getSurroundingTryBlock() { val code = getMethodCode(); for (val tryBlockEnd : code.getTryBlocks()) // check that the instruction is in this try block if (code.isBetween(tryBlockEnd.getBlockStart(), tryBlockEnd, this)) return tryBlockEnd; return null; } protected final List<DexCodeElement> throwingInsn_GenerateSurroundingCatchBlock(DexCodeElement[] tryBlockCode, DexCodeElement[] catchBlockCode, DexRegister regException) { val code = getMethodCode(); val catchAll = new DexCatchAll(code); val tryStart = new DexTryBlockStart(code); tryStart.setCatchAllHandler(catchAll); val tryEnd = new DexTryBlockEnd(code, tryStart); val labelSucc = new DexLabel(code); val gotoSucc = new DexInstruction_Goto(code, labelSucc); val moveException = new DexInstruction_MoveException(code, regException); val throwException = new DexInstruction_Throw(code, regException); val instrumentedCode = new ArrayList<DexCodeElement>(); instrumentedCode.add(tryStart); instrumentedCode.addAll(Arrays.asList(tryBlockCode)); instrumentedCode.add(gotoSucc); instrumentedCode.add(tryEnd); instrumentedCode.add(catchAll); instrumentedCode.add(moveException); instrumentedCode.addAll(Arrays.asList(catchBlockCode)); instrumentedCode.add(throwException); instrumentedCode.add(labelSucc); return instrumentedCode; } abstract public void accept(DexInstructionVisitor visitor); // Subclasses should overrides this if the instruction may throw exceptions during execution. protected DexClassType[] throwsExceptions() { return null; } @Override public boolean cfgEndsBasicBlock() { DexClassType[] exceptions = throwsExceptions(); return exceptions != null && exceptions.length > 0; } @Override public final Set<DexCodeElement> cfgGetSuccessors() { // uses the DexCodeElement definition of cfgGetSuccessors // (non-throwing semantics) but adds behavior after exceptions // are thrown val set = super.cfgGetSuccessors(); DexClassType[] exceptions = throwsExceptions(); if (exceptions != null) { for(DexClassType exception : exceptions) set.addAll(throwingInsn_CatchHandlers(exception)); } return set; } }
false
true
protected final Set<DexCodeElement> throwingInsn_CatchHandlers(DexClassType thrownExceptionType) { val set = new HashSet<DexCodeElement>(); val code = getMethodCode(); val classHierarchy = getParentFile().getClassHierarchy(); for (val tryBlockEnd : code.getTryBlocks()) { val tryBlockStart = tryBlockEnd.getBlockStart(); // check that the instruction is in this try block if (code.isBetween(tryBlockStart, tryBlockEnd, this)) { // if the block has CatchAll handler, it can jump to it val catchAllHandler = tryBlockStart.getCatchAllHandler(); if (catchAllHandler != null) set.add(catchAllHandler); // similarly, add all catch blocks as possible successors // if they catch the given exception type or its ancestor for (val catchBlock : tryBlockStart.getCatchHandlers()) if (thrownExceptionType == null || classHierarchy.isAncestor(thrownExceptionType, catchBlock.getExceptionType())) set.add(catchBlock); } } return set; }
protected final Set<DexCodeElement> throwingInsn_CatchHandlers(DexClassType thrownExceptionType) { val set = new HashSet<DexCodeElement>(); val code = getMethodCode(); val classHierarchy = getParentFile().getClassHierarchy(); for (val tryBlockEnd : code.getTryBlocks()) { val tryBlockStart = tryBlockEnd.getBlockStart(); // check that the instruction is in this try block if (code.isBetween(tryBlockStart, tryBlockEnd, this)) { // if the block has CatchAll handler, it can jump to it val catchAllHandler = tryBlockStart.getCatchAllHandler(); if (catchAllHandler != null) set.add(catchAllHandler); // similarly, add all catch blocks as possible successors // if either they catch the given exception type or its ancestor (a guaranteed catch) // or if the catch is the subclass of the thrown exception (a potential catch) for (val catchBlock : tryBlockStart.getCatchHandlers()) if (thrownExceptionType == null || classHierarchy.isAncestor(catchBlock.getExceptionType(), thrownExceptionType) || classHierarchy.isAncestor(thrownExceptionType, catchBlock.getExceptionType())) set.add(catchBlock); } } return set; }
diff --git a/src/edu/wheaton/simulator/gui/StatisticsScreen.java b/src/edu/wheaton/simulator/gui/StatisticsScreen.java index 211e2d3e..4446bd02 100644 --- a/src/edu/wheaton/simulator/gui/StatisticsScreen.java +++ b/src/edu/wheaton/simulator/gui/StatisticsScreen.java @@ -1,198 +1,198 @@ /** * StatisticsScreen * * Class representing the screen that allows users to view statistics. * * @author Willy McHie * Wheaton College, CSCI 335, Spring 2013 */ package edu.wheaton.simulator.gui; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.HashMap; import javax.swing.*; import edu.wheaton.simulator.statistics.StatisticsManager; public class StatisticsScreen extends Screen { private JPanel dataPanel; private String[] entities; private String[] agentFields; private JComboBox popEntityBox; private JComboBox fieldEntityBox; private JComboBox lifeEntityBox; private HashMap<String, JComboBox> agentFieldsBoxes; private JPanel fieldCard; private StatisticsManager statMan; /** * */ private static final long serialVersionUID = 714636604315959167L; //TODO fix layout of this screen //TODO make sure that correct fields box gets put on the panel when an agent is selected. public StatisticsScreen(final ScreenManager sm) { super(sm); this.setLayout(new BorderLayout()); JLabel label = new JLabel("Statistics"); label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); label.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); label.setPreferredSize(new Dimension(300, 150)); JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); JPanel graphPanel = new JPanel(); dataPanel = new JPanel(); dataPanel.setLayout(new CardLayout()); JPanel populationCard = new JPanel(); String populations = "Card with Populations"; fieldCard = new JPanel(); String fields = "Card with Fields"; JPanel lifespanCard = new JPanel(); String lifespans = "Card with Lifespans"; dataPanel.add(populationCard, populations); dataPanel.add(fieldCard, fields); dataPanel.add(lifespanCard, lifespans); JPanel boxPanel = new JPanel(); String[] boxItems = {populations, fields, lifespans}; JComboBox cardSelector = new JComboBox(boxItems); cardSelector.addItemListener( new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { CardLayout cl = (CardLayout)dataPanel.getLayout(); cl.show(dataPanel, (String)e.getItem()); } } ); boxPanel.add(cardSelector); populationCard.setLayout(new BoxLayout(populationCard, BoxLayout.X_AXIS)); fieldCard.setLayout(new BoxLayout(fieldCard, BoxLayout.X_AXIS)); lifespanCard.setLayout(new BoxLayout(lifespanCard, BoxLayout.X_AXIS)); //TODO placeholder //String[] entities = {"Fox", "Rabbit", "Clover", "Bear"}; entities = new String[0]; popEntityBox = new JComboBox(entities); populationCard.add(popEntityBox); fieldEntityBox = new JComboBox(entities); //TODO placeholder //String[] agentFields = {"height", "weight", "speed"}; agentFields = new String[0]; agentFieldsBoxes = new HashMap<String, JComboBox>(); agentFieldsBoxes.put("", new JComboBox(agentFields)); fieldEntityBox.addItemListener( new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { fieldCard.remove(1); - fieldCard.add(agentFieldsBoxes.get((String)e.getItem())); + fieldCard.add(agentFieldsBoxes.get(e.getItem())); validate(); repaint(); } } ); fieldCard.add(fieldEntityBox); fieldCard.add(agentFieldsBoxes.get("")); lifeEntityBox = new JComboBox(entities); lifespanCard.add(lifeEntityBox); JButton finishButton = new JButton("Finish"); finishButton.setPreferredSize(new Dimension(150, 70)); finishButton.setAlignmentX(CENTER_ALIGNMENT); finishButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sm.update(sm.getScreen("Edit Simulation")); } }); if(popEntityBox.getSelectedIndex() >= 0){ StatisticsManager statMan = sm.getStatManager(); int[] p = statMan.getPopVsTime(sm.getFacade(). getPrototype(popEntityBox.getSelectedItem().toString()) .getPrototypeID() ); String[] popTime = {"Population", "Time"}; Object[][] timePop = new Object[p.length][2]; for(int i = 0; i < p.length; i++){ Object[] array= {i, p[i]}; timePop[i] = array; } JTable jt = new JTable(timePop ,popTime); populationCard.add(jt); } //COMING SOON: Average Field Table Statistics // if(fieldEntityTypes.getSelectedIndex() >= 0){ // statMan = sm.getStatManager(); // double[] p = statMan.getAvgFieldValue((sm.getFacade(). // getPrototype(popEntityTypes.getSelectedItem().toString()) // .getPrototypeID()), (String) agentFieldsBox.getSelectedItem() // ); // String[] popTime = {"Population", "Time"}; // Object[][] timePop = new Object[p.length][2]; // for(int i = 0; i < p.length; i++){ // Object[] array= {i, p[i]}; // timePop[i] = array; // } // // JTable jt = new JTable(timePop ,popTime); // populationCard.add(jt); // } // // this.add(label, BorderLayout.NORTH); //TODO MAJOR figure out how to make a graph or something!! graphPanel.add(new JLabel("Graph object goes here")); mainPanel.add(graphPanel); mainPanel.add(boxPanel); mainPanel.add(dataPanel); mainPanel.add(finishButton); this.add(mainPanel); } //TODO finish this @Override public void load() { //TODO make sure that listeners are assigned entities = new String[sm.getFacade().prototypeNames().size()]; popEntityBox.removeAllItems(); fieldEntityBox.removeAllItems(); lifeEntityBox.removeAllItems(); agentFieldsBoxes.clear(); int i = 0; for (String s : sm.getFacade().prototypeNames()) { entities[i++] = s; agentFields = sm.getFacade().getPrototype(s).getCustomFieldMap().keySet().toArray(agentFields); agentFieldsBoxes.put(s, new JComboBox(agentFields)); popEntityBox.addItem(s); fieldEntityBox.addItem(s); lifeEntityBox.addItem(s); } } }
true
true
public StatisticsScreen(final ScreenManager sm) { super(sm); this.setLayout(new BorderLayout()); JLabel label = new JLabel("Statistics"); label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); label.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); label.setPreferredSize(new Dimension(300, 150)); JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); JPanel graphPanel = new JPanel(); dataPanel = new JPanel(); dataPanel.setLayout(new CardLayout()); JPanel populationCard = new JPanel(); String populations = "Card with Populations"; fieldCard = new JPanel(); String fields = "Card with Fields"; JPanel lifespanCard = new JPanel(); String lifespans = "Card with Lifespans"; dataPanel.add(populationCard, populations); dataPanel.add(fieldCard, fields); dataPanel.add(lifespanCard, lifespans); JPanel boxPanel = new JPanel(); String[] boxItems = {populations, fields, lifespans}; JComboBox cardSelector = new JComboBox(boxItems); cardSelector.addItemListener( new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { CardLayout cl = (CardLayout)dataPanel.getLayout(); cl.show(dataPanel, (String)e.getItem()); } } ); boxPanel.add(cardSelector); populationCard.setLayout(new BoxLayout(populationCard, BoxLayout.X_AXIS)); fieldCard.setLayout(new BoxLayout(fieldCard, BoxLayout.X_AXIS)); lifespanCard.setLayout(new BoxLayout(lifespanCard, BoxLayout.X_AXIS)); //TODO placeholder //String[] entities = {"Fox", "Rabbit", "Clover", "Bear"}; entities = new String[0]; popEntityBox = new JComboBox(entities); populationCard.add(popEntityBox); fieldEntityBox = new JComboBox(entities); //TODO placeholder //String[] agentFields = {"height", "weight", "speed"}; agentFields = new String[0]; agentFieldsBoxes = new HashMap<String, JComboBox>(); agentFieldsBoxes.put("", new JComboBox(agentFields)); fieldEntityBox.addItemListener( new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { fieldCard.remove(1); fieldCard.add(agentFieldsBoxes.get((String)e.getItem())); validate(); repaint(); } } ); fieldCard.add(fieldEntityBox); fieldCard.add(agentFieldsBoxes.get("")); lifeEntityBox = new JComboBox(entities); lifespanCard.add(lifeEntityBox); JButton finishButton = new JButton("Finish"); finishButton.setPreferredSize(new Dimension(150, 70)); finishButton.setAlignmentX(CENTER_ALIGNMENT); finishButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sm.update(sm.getScreen("Edit Simulation")); } }); if(popEntityBox.getSelectedIndex() >= 0){ StatisticsManager statMan = sm.getStatManager(); int[] p = statMan.getPopVsTime(sm.getFacade(). getPrototype(popEntityBox.getSelectedItem().toString()) .getPrototypeID() ); String[] popTime = {"Population", "Time"}; Object[][] timePop = new Object[p.length][2]; for(int i = 0; i < p.length; i++){ Object[] array= {i, p[i]}; timePop[i] = array; } JTable jt = new JTable(timePop ,popTime); populationCard.add(jt); } //COMING SOON: Average Field Table Statistics // if(fieldEntityTypes.getSelectedIndex() >= 0){ // statMan = sm.getStatManager(); // double[] p = statMan.getAvgFieldValue((sm.getFacade(). // getPrototype(popEntityTypes.getSelectedItem().toString()) // .getPrototypeID()), (String) agentFieldsBox.getSelectedItem() // ); // String[] popTime = {"Population", "Time"}; // Object[][] timePop = new Object[p.length][2]; // for(int i = 0; i < p.length; i++){ // Object[] array= {i, p[i]}; // timePop[i] = array; // } // // JTable jt = new JTable(timePop ,popTime); // populationCard.add(jt); // } // // this.add(label, BorderLayout.NORTH); //TODO MAJOR figure out how to make a graph or something!! graphPanel.add(new JLabel("Graph object goes here")); mainPanel.add(graphPanel); mainPanel.add(boxPanel); mainPanel.add(dataPanel); mainPanel.add(finishButton); this.add(mainPanel); }
public StatisticsScreen(final ScreenManager sm) { super(sm); this.setLayout(new BorderLayout()); JLabel label = new JLabel("Statistics"); label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); label.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); label.setPreferredSize(new Dimension(300, 150)); JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); JPanel graphPanel = new JPanel(); dataPanel = new JPanel(); dataPanel.setLayout(new CardLayout()); JPanel populationCard = new JPanel(); String populations = "Card with Populations"; fieldCard = new JPanel(); String fields = "Card with Fields"; JPanel lifespanCard = new JPanel(); String lifespans = "Card with Lifespans"; dataPanel.add(populationCard, populations); dataPanel.add(fieldCard, fields); dataPanel.add(lifespanCard, lifespans); JPanel boxPanel = new JPanel(); String[] boxItems = {populations, fields, lifespans}; JComboBox cardSelector = new JComboBox(boxItems); cardSelector.addItemListener( new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { CardLayout cl = (CardLayout)dataPanel.getLayout(); cl.show(dataPanel, (String)e.getItem()); } } ); boxPanel.add(cardSelector); populationCard.setLayout(new BoxLayout(populationCard, BoxLayout.X_AXIS)); fieldCard.setLayout(new BoxLayout(fieldCard, BoxLayout.X_AXIS)); lifespanCard.setLayout(new BoxLayout(lifespanCard, BoxLayout.X_AXIS)); //TODO placeholder //String[] entities = {"Fox", "Rabbit", "Clover", "Bear"}; entities = new String[0]; popEntityBox = new JComboBox(entities); populationCard.add(popEntityBox); fieldEntityBox = new JComboBox(entities); //TODO placeholder //String[] agentFields = {"height", "weight", "speed"}; agentFields = new String[0]; agentFieldsBoxes = new HashMap<String, JComboBox>(); agentFieldsBoxes.put("", new JComboBox(agentFields)); fieldEntityBox.addItemListener( new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { fieldCard.remove(1); fieldCard.add(agentFieldsBoxes.get(e.getItem())); validate(); repaint(); } } ); fieldCard.add(fieldEntityBox); fieldCard.add(agentFieldsBoxes.get("")); lifeEntityBox = new JComboBox(entities); lifespanCard.add(lifeEntityBox); JButton finishButton = new JButton("Finish"); finishButton.setPreferredSize(new Dimension(150, 70)); finishButton.setAlignmentX(CENTER_ALIGNMENT); finishButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sm.update(sm.getScreen("Edit Simulation")); } }); if(popEntityBox.getSelectedIndex() >= 0){ StatisticsManager statMan = sm.getStatManager(); int[] p = statMan.getPopVsTime(sm.getFacade(). getPrototype(popEntityBox.getSelectedItem().toString()) .getPrototypeID() ); String[] popTime = {"Population", "Time"}; Object[][] timePop = new Object[p.length][2]; for(int i = 0; i < p.length; i++){ Object[] array= {i, p[i]}; timePop[i] = array; } JTable jt = new JTable(timePop ,popTime); populationCard.add(jt); } //COMING SOON: Average Field Table Statistics // if(fieldEntityTypes.getSelectedIndex() >= 0){ // statMan = sm.getStatManager(); // double[] p = statMan.getAvgFieldValue((sm.getFacade(). // getPrototype(popEntityTypes.getSelectedItem().toString()) // .getPrototypeID()), (String) agentFieldsBox.getSelectedItem() // ); // String[] popTime = {"Population", "Time"}; // Object[][] timePop = new Object[p.length][2]; // for(int i = 0; i < p.length; i++){ // Object[] array= {i, p[i]}; // timePop[i] = array; // } // // JTable jt = new JTable(timePop ,popTime); // populationCard.add(jt); // } // // this.add(label, BorderLayout.NORTH); //TODO MAJOR figure out how to make a graph or something!! graphPanel.add(new JLabel("Graph object goes here")); mainPanel.add(graphPanel); mainPanel.add(boxPanel); mainPanel.add(dataPanel); mainPanel.add(finishButton); this.add(mainPanel); }
diff --git a/src/edu/cmu/cs/diamond/snapfind2/search/XQueryAnomalyFilter.java b/src/edu/cmu/cs/diamond/snapfind2/search/XQueryAnomalyFilter.java index c2dd0a1..2bead69 100644 --- a/src/edu/cmu/cs/diamond/snapfind2/search/XQueryAnomalyFilter.java +++ b/src/edu/cmu/cs/diamond/snapfind2/search/XQueryAnomalyFilter.java @@ -1,642 +1,644 @@ /* * StrangeFind, an anomaly detection system for the OpenDiamond Platform * * Copyright (c) 2007-2008 Carnegie Mellon University * All rights reserved. * * StrangeFind is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 2. * * StrangeFind is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with StrangeFind. If not, see <http://www.gnu.org/licenses/>. * * Linking StrangeFind statically or dynamically with other modules is * making a combined work based on StrangeFind. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of * StrangeFind give you permission to combine StrangeFind with free software * programs or libraries that are released under the GNU LGPL or the * Eclipse Public License 1.0. You may copy and distribute such a system * following the terms of the GNU GPL for StrangeFind and the licenses of * the other code concerned, provided that you include the source code of * that other code when and as the GNU GPL requires distribution of source * code. * * Note that people who make modified versions of StrangeFind are not * obligated to grant this special exception for their modified versions; * it is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. */ package edu.cmu.cs.diamond.snapfind2.search; import java.awt.BorderLayout; import java.awt.Component; import java.io.*; import java.text.DecimalFormat; import java.util.*; import java.util.Map.Entry; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.filechooser.FileNameExtensionFilter; import edu.cmu.cs.diamond.opendiamond.*; import edu.cmu.cs.diamond.snapfind2.Annotator; import edu.cmu.cs.diamond.snapfind2.Decorator; import edu.cmu.cs.diamond.snapfind2.LogicEngine; import edu.cmu.cs.diamond.snapfind2.SnapFindSearch; public class XQueryAnomalyFilter implements SnapFindSearch { private boolean negateEasyOp; public XQueryAnomalyFilter(Component parent) { attrMap = new HashMap<String, String>(); // load file JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter( "Attribute Map Files", "attrmap"); chooser.setFileFilter(filter); int returnVal = chooser.showOpenDialog(parent); if (returnVal == JFileChooser.APPROVE_OPTION) { File f = chooser.getSelectedFile(); parseAttrFile(f, attrMap); } else { // XXX throw new RuntimeException("You must choose a file"); } // init GUI elements checkboxes = new JCheckBox[attrMap.size()]; stddevs = new JSpinner[attrMap.size()]; niceLabels = new String[attrMap.size()]; labels = new String[attrMap.size()]; queries = new String[attrMap.size()]; { int i = 0; for (Entry<String, String> e : attrMap.entrySet()) { // convert spaces to underscores, in an attempt to not crash the // lexer? labels[i] = e.getKey().replaceAll("\\t", " ").replaceAll("_", "__").replaceAll(" ", "_"); niceLabels[i] = e.getKey(); queries[i] = e.getValue(); i++; } } for (int i = 0; i < niceLabels.length; i++) { checkboxes[i] = new JCheckBox(niceLabels[i] + " ($" + (i + 1) + ")"); checkboxes[i].setToolTipText(queries[i]); checkboxes[i].setSelected(true); checkboxes[i].addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { updateEasyLogicExpression(); } }); JSpinner s = new JSpinner( new SpinnerNumberModel(3.0, 1.0, 7.0, 0.5)); stddevs[i] = s; } } protected void updateEasyLogicExpression() { if (easyOp == "") { return; // not easy } JTextArea t = logicalExpressionTextArea; StringBuilder sb = new StringBuilder(); if (negateEasyOp) { sb.append("NOT("); } sb.append(easyOp + "("); boolean someSelected = false; boolean first = true; for (int i = 0; i < checkboxes.length; i++) { JCheckBox c = checkboxes[i]; if (c.isSelected()) { someSelected = true; if (!first) { sb.append(", "); } else { first = false; } sb.append("$" + (i + 1)); } } sb.append(")"); if (negateEasyOp) { sb.append(")"); } String text; if (someSelected) { text = sb.toString(); } else { text = ""; } t.setText(text); } static private void parseAttrFile(File f, Map<String, String> attrMap) { FileReader fr = null; BufferedReader in = null; try { fr = new FileReader(f); in = new BufferedReader(fr); String line; while ((line = in.readLine()) != null) { String tokens[] = line.split(":", 2); String key = tokens[0].replaceAll("\\t", " "); attrMap.put(key, tokens[1]); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fr != null) { try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } public Annotator getAnnotator() { final List<String> selectedLabels = new ArrayList<String>(); final List<String> niceSelectedLabels = new ArrayList<String>(); for (int i = 0; i < checkboxes.length; i++) { JCheckBox c = checkboxes[i]; if (c.isSelected()) { selectedLabels.add(labels[i]); niceSelectedLabels.add(niceLabels[i]); } } return new Annotator() { public String annotate(Result r) { return annotateTooltip(r); } public String annotateNonHTML(Result r) { return annotateTooltip(r, false); } public String annotateTooltip(Result r) { return annotateTooltip(r, true); } private String annotateTooltip(Result r, boolean useHTML) { DecimalFormat df = new DecimalFormat("0.###"); StringBuilder sb = new StringBuilder(); if (useHTML) { sb.append("<html>"); } String server = r.getServerName(); String name = getName(r); int samples = getSamples(r, 0); for (int i = 0; i < labels.length; i++) { boolean isA = getIsAnomalous(r, i); if (useHTML) { sb.append("<p>"); + } else { + sb.append("\n\n"); } if (isA) { if (useHTML) { sb.append("<b>"); } sb.append("*"); } String descriptor = niceLabels[i]; double stddev = getStddev(r, i); double value = getValue(r, i); double mean = getMean(r, i); double stddevDiff = getStddevDiff(stddev, value, mean); String aboveOrBelow = getAboveOrBelow(stddevDiff, "+", "−"); sb.append(descriptor); if (isA) { if (useHTML) { sb.append("</b>"); } } sb.append(" = " + format(mean, df) + " " + aboveOrBelow + " " + format(Math.abs(stddevDiff), df) + "σ (" + format(value, df) + ")"); } if (useHTML) { sb.append("<hr><p>" + name + "<p>" + server + " [" + samples + "]</html>"); } else { - sb.append("\n\n---\n\n" + name + "\n\n" + server + " [" + sb.append("\n---\n\n" + name + "\n\n" + server + " [" + samples + "]"); } return sb.toString(); // // double stddev = getStddev(r); // String keyValue = selectedLabels.get(key); // String strValue = Util.extractString(r.getValue(keyValue)); // // return "<html><p>" + descriptor + "<br>" + "= " // DecimalFormat df = new DecimalFormat("0.###"); // // int key = getKey(r); // String descriptor = niceSelectedLabels.get(key); // // double stddev = getStddev(r); // String keyValue = selectedLabels.get(key); // String strValue = Util.extractString(r.getValue(keyValue)); // System.out.println("key: " + key + ", value: " + keyValue // + ", strValue: " + strValue); // double value = getValue(strValue); // double mean = getMean(r); // double stddevDiff = getStddevDiff(stddev, value, mean); // // String aboveOrBelow = getAboveOrBelow(stddevDiff); // // // return "<html><p><b>" + descriptor + "</b> = " // + df.format(value) + "<p><b>" // + df.format(Math.abs(stddevDiff)) + "</b> stddev <b>" // + aboveOrBelow + "</b> mean of <b>" + df.format(mean) // + "</b><hr><p>" + name + "<p>" + server + " [" // + samples + "]</html>"; } private String getAboveOrBelow(double stddevDiff) { return getAboveOrBelow(stddevDiff, "above", "below"); } private String getName(Result r) { String name = r.getObjectName(); name = name.substring(name.lastIndexOf('/') + 1); return name; } private String getAboveOrBelow(double stddevDiff, String above, String below) { String aboveOrBelow = Math.signum(stddevDiff) >= 0.0 ? above : below; return aboveOrBelow; } private int getSamples(Result r, int descriptor) { int samples = Util.extractInt(r .getValue("anomaly-descriptor-count-" + descriptor + ".int")); return samples; } private double getValue(Result r, int descriptor) { double value = Util.extractDouble(r .getValue("anomaly-descriptor-value-" + descriptor + ".double")); return value; } private double getStddevDiff(double stddev, double value, double mean) { double stddevDiff = (value - mean) / stddev; return stddevDiff; } private double getMean(Result r, int descriptor) { double mean = Util.extractDouble(r .getValue("anomaly-descriptor-mean-" + descriptor + ".double")); return mean; } private double getValue(String strValue) { double value = Double.parseDouble(strValue); return value; } private double getStddev(Result r, int descriptor) { double stddev = Util.extractDouble(r .getValue("anomaly-descriptor-stddev-" + descriptor + ".double")); return stddev; } private boolean getIsAnomalous(Result r, int descriptor) { int isAnomalous = Util.extractInt(r .getValue("anomaly-descriptor-is_anomalous-" + descriptor + ".int")); return isAnomalous == 1 ? true : false; } @Override public String annotateOneLine(Result r) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < labels.length; i++) { if (getIsAnomalous(r, i)) { sb.append("$" + (i + 1) + " "); } } if (sb.toString().equals("")) { sb.append("none"); } return "<html><p>Anomalous: " + sb.toString() + "</html>"; } @Override public String annotateVerbose(Result r) { // TODO do this with XML parser // XXX ByteArrayInputStream in = new ByteArrayInputStream(r.getData()); BufferedReader reader = new BufferedReader( new InputStreamReader(in)); String line; StringBuilder output = new StringBuilder(); boolean skip = false; try { while ((line = reader.readLine()) != null) { if (line.equals("<ResultType name=\"Cell\">")) { skip = true; } if (skip == true && line.equals("</ResultType>")) { skip = false; } if (!skip) { output.append(line); output.append('\n'); } } } catch (IOException e) { e.printStackTrace(); } return output.toString(); } }; } protected String format(double d, DecimalFormat df) { if (Double.isNaN(d)) { return "NaN"; } else { return df.format(d); } } public Decorator getDecorator() { return null; } private static final DoubleComposer composer = new DoubleComposer() { public double compose(String key, double a, double b) { return a + b; } }; public DoubleComposer getDoubleComposer() { return composer; } public String[] getApplicationDependencies() { return new String[] { "xquery" }; } public Filter[] getFilters() { Filter xquery = null; Filter anom = null; try { FilterCode c; c = new FilterCode(new FileInputStream( "/opt/snapfind/lib/fil_xquery.so")); byte queryBlob[] = generateQueryBlob(); System.out.println("queryBlob: " + new String(queryBlob)); xquery = new Filter("xquery", c, "f_eval_xquery", "f_init_xquery", "f_fini_xquery", 0, new String[0], new String[] {}, 400, queryBlob); System.out.println(xquery); List<String> paramsList = new ArrayList<String>(); for (int i = 0; i < checkboxes.length; i++) { paramsList.add(labels[i]); paramsList.add(stddevs[i].getValue().toString()); } String anomArgs[] = new String[paramsList.size() + 3]; anomArgs[0] = ignoreSpinner.getValue().toString(); // skip anomArgs[1] = UUID.randomUUID().toString(); // random value anomArgs[2] = LogicEngine .getMachineCodeForExpression(logicalExpressionTextArea .getText()); // machine code System.arraycopy(paramsList.toArray(), 0, anomArgs, 3, paramsList .size()); c = new FilterCode(new FileInputStream( "/home/agoode/diamond-git/snapfind2/native/fil_anomaly.so")); anom = new Filter("anomaly", c, "f_eval_afilter", "f_init_afilter", "f_fini_afilter", 1, new String[] { "xquery" }, anomArgs, 400); System.out.println(anom); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return new Filter[] { xquery, anom }; } private byte[] generateQueryBlob() { StringBuilder sb = new StringBuilder(); sb.append("document { <attributes>"); for (int i = 0; i < labels.length; i++) { // TODO(agoode) validate or escape xpath/xquery input sb.append("<attribute name='" + labels[i] + "' value='" + queries[i] + "'/>"); } sb .append("<attribute name='image-1' value='{//Images/ImageFile[1]/text()}'/>" + "<attribute name='image-2' value='{//Images/ImageFile[2]/text()}'/>" + "<attribute name='image-3' value='{//Images/ImageFile[3]/text()}'/>" + "</attributes>}"); return sb.toString().getBytes(); } final private JCheckBox[] checkboxes; final private JSpinner[] stddevs; final private JSpinner ignoreSpinner = new JSpinner(new SpinnerNumberModel( 5, 0, 100, 1)); final private Map<String, String> attrMap; final private String labels[]; final private String niceLabels[]; final private String queries[]; final private JTextArea logicalExpressionTextArea = new JTextArea(); protected String easyOp; public JPanel getInterface() { // XXX do this another way JPanel result = new JPanel(); result.setBorder(BorderFactory .createTitledBorder("XQuery Anomaly Detector")); result.setLayout(new BorderLayout()); Box b = Box.createVerticalBox(); result.add(b); JPanel innerResult = new JPanel(); innerResult.setLayout(new SpringLayout()); innerResult.add(new JLabel("Priming count")); innerResult.add(ignoreSpinner); innerResult.add(new JLabel(" ")); innerResult.add(new JLabel(" ")); innerResult.add(new JLabel("Descriptor")); innerResult.add(new JLabel("Std. dev.")); for (int i = 0; i < labels.length; i++) { innerResult.add(checkboxes[i]); innerResult.add(stddevs[i]); } Util.makeCompactGrid(innerResult, labels.length + 3, 2, 5, 5, 2, 2); b.add(innerResult); // logic ButtonGroup bg = new ButtonGroup(); Box h = Box.createHorizontalBox(); b.add(h); JRadioButton cb = new JRadioButton("OR"); bg.add(cb); h.add(cb); cb.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (((JRadioButton) e.getSource()).isSelected()) { easyOp = "OR"; negateEasyOp = false; updateEasyLogicExpression(); } } }); cb.setSelected(true); cb = new JRadioButton("AND"); cb.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (((JRadioButton) e.getSource()).isSelected()) { easyOp = "AND"; negateEasyOp = false; updateEasyLogicExpression(); } } }); bg.add(cb); h.add(cb); cb = new JRadioButton("NOT"); bg.add(cb); h.add(cb); cb.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (((JRadioButton) e.getSource()).isSelected()) { easyOp = "OR"; negateEasyOp = true; updateEasyLogicExpression(); } } }); cb = new JRadioButton("Custom:"); cb.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (((JRadioButton) e.getSource()).isSelected()) { easyOp = ""; logicalExpressionTextArea.setEditable(true); } else { logicalExpressionTextArea.setEditable(false); } } }); bg.add(cb); h.add(cb); logicalExpressionTextArea.setRows(4); logicalExpressionTextArea.setLineWrap(true); logicalExpressionTextArea.setEditable(false); b.add(new JScrollPane(logicalExpressionTextArea)); return result; } }
false
true
public Annotator getAnnotator() { final List<String> selectedLabels = new ArrayList<String>(); final List<String> niceSelectedLabels = new ArrayList<String>(); for (int i = 0; i < checkboxes.length; i++) { JCheckBox c = checkboxes[i]; if (c.isSelected()) { selectedLabels.add(labels[i]); niceSelectedLabels.add(niceLabels[i]); } } return new Annotator() { public String annotate(Result r) { return annotateTooltip(r); } public String annotateNonHTML(Result r) { return annotateTooltip(r, false); } public String annotateTooltip(Result r) { return annotateTooltip(r, true); } private String annotateTooltip(Result r, boolean useHTML) { DecimalFormat df = new DecimalFormat("0.###"); StringBuilder sb = new StringBuilder(); if (useHTML) { sb.append("<html>"); } String server = r.getServerName(); String name = getName(r); int samples = getSamples(r, 0); for (int i = 0; i < labels.length; i++) { boolean isA = getIsAnomalous(r, i); if (useHTML) { sb.append("<p>"); } if (isA) { if (useHTML) { sb.append("<b>"); } sb.append("*"); } String descriptor = niceLabels[i]; double stddev = getStddev(r, i); double value = getValue(r, i); double mean = getMean(r, i); double stddevDiff = getStddevDiff(stddev, value, mean); String aboveOrBelow = getAboveOrBelow(stddevDiff, "+", "−"); sb.append(descriptor); if (isA) { if (useHTML) { sb.append("</b>"); } } sb.append(" = " + format(mean, df) + " " + aboveOrBelow + " " + format(Math.abs(stddevDiff), df) + "σ (" + format(value, df) + ")"); } if (useHTML) { sb.append("<hr><p>" + name + "<p>" + server + " [" + samples + "]</html>"); } else { sb.append("\n\n---\n\n" + name + "\n\n" + server + " [" + samples + "]"); } return sb.toString(); // // double stddev = getStddev(r); // String keyValue = selectedLabels.get(key); // String strValue = Util.extractString(r.getValue(keyValue)); // // return "<html><p>" + descriptor + "<br>" + "= " // DecimalFormat df = new DecimalFormat("0.###"); // // int key = getKey(r); // String descriptor = niceSelectedLabels.get(key); // // double stddev = getStddev(r); // String keyValue = selectedLabels.get(key); // String strValue = Util.extractString(r.getValue(keyValue)); // System.out.println("key: " + key + ", value: " + keyValue // + ", strValue: " + strValue); // double value = getValue(strValue); // double mean = getMean(r); // double stddevDiff = getStddevDiff(stddev, value, mean); // // String aboveOrBelow = getAboveOrBelow(stddevDiff); // // // return "<html><p><b>" + descriptor + "</b> = " // + df.format(value) + "<p><b>" // + df.format(Math.abs(stddevDiff)) + "</b> stddev <b>" // + aboveOrBelow + "</b> mean of <b>" + df.format(mean) // + "</b><hr><p>" + name + "<p>" + server + " [" // + samples + "]</html>"; } private String getAboveOrBelow(double stddevDiff) { return getAboveOrBelow(stddevDiff, "above", "below"); } private String getName(Result r) { String name = r.getObjectName(); name = name.substring(name.lastIndexOf('/') + 1); return name; } private String getAboveOrBelow(double stddevDiff, String above, String below) { String aboveOrBelow = Math.signum(stddevDiff) >= 0.0 ? above : below; return aboveOrBelow; } private int getSamples(Result r, int descriptor) { int samples = Util.extractInt(r .getValue("anomaly-descriptor-count-" + descriptor + ".int")); return samples; } private double getValue(Result r, int descriptor) { double value = Util.extractDouble(r .getValue("anomaly-descriptor-value-" + descriptor + ".double")); return value; } private double getStddevDiff(double stddev, double value, double mean) { double stddevDiff = (value - mean) / stddev; return stddevDiff; } private double getMean(Result r, int descriptor) { double mean = Util.extractDouble(r .getValue("anomaly-descriptor-mean-" + descriptor + ".double")); return mean; } private double getValue(String strValue) { double value = Double.parseDouble(strValue); return value; } private double getStddev(Result r, int descriptor) { double stddev = Util.extractDouble(r .getValue("anomaly-descriptor-stddev-" + descriptor + ".double")); return stddev; } private boolean getIsAnomalous(Result r, int descriptor) { int isAnomalous = Util.extractInt(r .getValue("anomaly-descriptor-is_anomalous-" + descriptor + ".int")); return isAnomalous == 1 ? true : false; } @Override public String annotateOneLine(Result r) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < labels.length; i++) { if (getIsAnomalous(r, i)) { sb.append("$" + (i + 1) + " "); } } if (sb.toString().equals("")) { sb.append("none"); } return "<html><p>Anomalous: " + sb.toString() + "</html>"; } @Override public String annotateVerbose(Result r) { // TODO do this with XML parser // XXX ByteArrayInputStream in = new ByteArrayInputStream(r.getData()); BufferedReader reader = new BufferedReader( new InputStreamReader(in)); String line; StringBuilder output = new StringBuilder(); boolean skip = false; try { while ((line = reader.readLine()) != null) { if (line.equals("<ResultType name=\"Cell\">")) { skip = true; } if (skip == true && line.equals("</ResultType>")) { skip = false; } if (!skip) { output.append(line); output.append('\n'); } } } catch (IOException e) { e.printStackTrace(); } return output.toString(); } }; }
public Annotator getAnnotator() { final List<String> selectedLabels = new ArrayList<String>(); final List<String> niceSelectedLabels = new ArrayList<String>(); for (int i = 0; i < checkboxes.length; i++) { JCheckBox c = checkboxes[i]; if (c.isSelected()) { selectedLabels.add(labels[i]); niceSelectedLabels.add(niceLabels[i]); } } return new Annotator() { public String annotate(Result r) { return annotateTooltip(r); } public String annotateNonHTML(Result r) { return annotateTooltip(r, false); } public String annotateTooltip(Result r) { return annotateTooltip(r, true); } private String annotateTooltip(Result r, boolean useHTML) { DecimalFormat df = new DecimalFormat("0.###"); StringBuilder sb = new StringBuilder(); if (useHTML) { sb.append("<html>"); } String server = r.getServerName(); String name = getName(r); int samples = getSamples(r, 0); for (int i = 0; i < labels.length; i++) { boolean isA = getIsAnomalous(r, i); if (useHTML) { sb.append("<p>"); } else { sb.append("\n\n"); } if (isA) { if (useHTML) { sb.append("<b>"); } sb.append("*"); } String descriptor = niceLabels[i]; double stddev = getStddev(r, i); double value = getValue(r, i); double mean = getMean(r, i); double stddevDiff = getStddevDiff(stddev, value, mean); String aboveOrBelow = getAboveOrBelow(stddevDiff, "+", "−"); sb.append(descriptor); if (isA) { if (useHTML) { sb.append("</b>"); } } sb.append(" = " + format(mean, df) + " " + aboveOrBelow + " " + format(Math.abs(stddevDiff), df) + "σ (" + format(value, df) + ")"); } if (useHTML) { sb.append("<hr><p>" + name + "<p>" + server + " [" + samples + "]</html>"); } else { sb.append("\n---\n\n" + name + "\n\n" + server + " [" + samples + "]"); } return sb.toString(); // // double stddev = getStddev(r); // String keyValue = selectedLabels.get(key); // String strValue = Util.extractString(r.getValue(keyValue)); // // return "<html><p>" + descriptor + "<br>" + "= " // DecimalFormat df = new DecimalFormat("0.###"); // // int key = getKey(r); // String descriptor = niceSelectedLabels.get(key); // // double stddev = getStddev(r); // String keyValue = selectedLabels.get(key); // String strValue = Util.extractString(r.getValue(keyValue)); // System.out.println("key: " + key + ", value: " + keyValue // + ", strValue: " + strValue); // double value = getValue(strValue); // double mean = getMean(r); // double stddevDiff = getStddevDiff(stddev, value, mean); // // String aboveOrBelow = getAboveOrBelow(stddevDiff); // // // return "<html><p><b>" + descriptor + "</b> = " // + df.format(value) + "<p><b>" // + df.format(Math.abs(stddevDiff)) + "</b> stddev <b>" // + aboveOrBelow + "</b> mean of <b>" + df.format(mean) // + "</b><hr><p>" + name + "<p>" + server + " [" // + samples + "]</html>"; } private String getAboveOrBelow(double stddevDiff) { return getAboveOrBelow(stddevDiff, "above", "below"); } private String getName(Result r) { String name = r.getObjectName(); name = name.substring(name.lastIndexOf('/') + 1); return name; } private String getAboveOrBelow(double stddevDiff, String above, String below) { String aboveOrBelow = Math.signum(stddevDiff) >= 0.0 ? above : below; return aboveOrBelow; } private int getSamples(Result r, int descriptor) { int samples = Util.extractInt(r .getValue("anomaly-descriptor-count-" + descriptor + ".int")); return samples; } private double getValue(Result r, int descriptor) { double value = Util.extractDouble(r .getValue("anomaly-descriptor-value-" + descriptor + ".double")); return value; } private double getStddevDiff(double stddev, double value, double mean) { double stddevDiff = (value - mean) / stddev; return stddevDiff; } private double getMean(Result r, int descriptor) { double mean = Util.extractDouble(r .getValue("anomaly-descriptor-mean-" + descriptor + ".double")); return mean; } private double getValue(String strValue) { double value = Double.parseDouble(strValue); return value; } private double getStddev(Result r, int descriptor) { double stddev = Util.extractDouble(r .getValue("anomaly-descriptor-stddev-" + descriptor + ".double")); return stddev; } private boolean getIsAnomalous(Result r, int descriptor) { int isAnomalous = Util.extractInt(r .getValue("anomaly-descriptor-is_anomalous-" + descriptor + ".int")); return isAnomalous == 1 ? true : false; } @Override public String annotateOneLine(Result r) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < labels.length; i++) { if (getIsAnomalous(r, i)) { sb.append("$" + (i + 1) + " "); } } if (sb.toString().equals("")) { sb.append("none"); } return "<html><p>Anomalous: " + sb.toString() + "</html>"; } @Override public String annotateVerbose(Result r) { // TODO do this with XML parser // XXX ByteArrayInputStream in = new ByteArrayInputStream(r.getData()); BufferedReader reader = new BufferedReader( new InputStreamReader(in)); String line; StringBuilder output = new StringBuilder(); boolean skip = false; try { while ((line = reader.readLine()) != null) { if (line.equals("<ResultType name=\"Cell\">")) { skip = true; } if (skip == true && line.equals("</ResultType>")) { skip = false; } if (!skip) { output.append(line); output.append('\n'); } } } catch (IOException e) { e.printStackTrace(); } return output.toString(); } }; }
diff --git a/modules/server/jetty-util/src/test/java/org/mortbay/thread/TimeoutTest.java b/modules/server/jetty-util/src/test/java/org/mortbay/thread/TimeoutTest.java index ab7d1c4fd..d59b3a617 100644 --- a/modules/server/jetty-util/src/test/java/org/mortbay/thread/TimeoutTest.java +++ b/modules/server/jetty-util/src/test/java/org/mortbay/thread/TimeoutTest.java @@ -1,257 +1,257 @@ //======================================================================== //$Id: TimeoutTest.java,v 1.1 2005/10/05 14:09:42 janb Exp $ //Copyright 2004-2005 Mort Bay Consulting Pty. Ltd. //------------------------------------------------------------------------ //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at //http://www.apache.org/licenses/LICENSE-2.0 //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //======================================================================== package org.mortbay.thread; import junit.framework.TestCase; public class TimeoutTest extends TestCase { Object lock = new Object(); Timeout timeout = new Timeout(null); Timeout.Task[] tasks; /* ------------------------------------------------------------ */ /* * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); timeout=new Timeout(lock); tasks= new Timeout.Task[10]; for (int i=0;i<tasks.length;i++) { tasks[i]=new Timeout.Task(); timeout.setNow(1000+i*100); timeout.schedule(tasks[i]); } timeout.setNow(100); } /* ------------------------------------------------------------ */ /* * @see junit.framework.TestCase#tearDown() */ protected void tearDown() throws Exception { super.tearDown(); } /* ------------------------------------------------------------ */ public void testExpiry() { timeout.setDuration(200); timeout.setNow(1500); timeout.tick(); for (int i=0;i<tasks.length;i++) { assertEquals("isExpired "+i,i<4, tasks[i].isExpired()); } } /* ------------------------------------------------------------ */ public void testCancel() { timeout.setDuration(200); timeout.setNow(1700); for (int i=0;i<tasks.length;i++) if (i%2==1) tasks[i].cancel(); timeout.tick(); for (int i=0;i<tasks.length;i++) { assertEquals("isExpired "+i,i%2==0 && i<6, tasks[i].isExpired()); } } /* ------------------------------------------------------------ */ public void testTouch() { timeout.setDuration(200); timeout.setNow(1350); timeout.schedule(tasks[2]); timeout.setNow(1500); timeout.tick(); for (int i=0;i<tasks.length;i++) { assertEquals("isExpired "+i,i!=2 && i<4, tasks[i].isExpired()); } timeout.setNow(1550); timeout.tick(); for (int i=0;i<tasks.length;i++) { assertEquals("isExpired "+i, i<4, tasks[i].isExpired()); } } /* ------------------------------------------------------------ */ public void testDelay() { Timeout.Task task = new Timeout.Task(); timeout.setNow(1100); timeout.schedule(task, 300); timeout.setDuration(200); timeout.setNow(1300); timeout.tick(); assertEquals("delay", false, task.isExpired()); timeout.setNow(1500); timeout.tick(); assertEquals("delay", false, task.isExpired()); timeout.setNow(1700); timeout.tick(); assertEquals("delay", true, task.isExpired()); } /* ------------------------------------------------------------ */ public void testStress() throws Exception { final int LOOP=500; final boolean[] running = {true}; final int[] count = {0,0,0}; timeout.setNow(System.currentTimeMillis()); timeout.setDuration(100); // Start a ticker thread that will tick over the timer frequently. Thread ticker = new Thread() { public void run() { while (running[0]) { try { // use lock.wait so we have a memory barrier and // have no funny optimisation issues. synchronized (lock) { lock.wait(40); } timeout.tick(System.currentTimeMillis()); } catch(Exception e) { e.printStackTrace(); } } } }; ticker.start(); // start lots of test threads for (int i=0;i<LOOP;i++) { final int l =i; // Thread th = new Thread() { public void run() { // count how many threads were started (should == LOOP) synchronized(count) { count[0]++; } // create a task for this thread Timeout.Task task = new Timeout.Task() { public void expired() { // count the number of expires synchronized(count) { count[2]++; } } }; // this thread will loop and each loop with schedule a // task with a delay between 200 and 300ms on top of the timeouts 100ms duration // mostly this thread will then wait 50ms and cancel the task // But once it will wait 1000ms and the task will expire long delay = 200+this.hashCode() % 100; int once = (int)( 10+(System.currentTimeMillis() % 50)); - System.err.println(l+" "+delay+" "+once); + // System.err.println(l+" "+delay+" "+once); // do the looping until we are stopped int loop=0; while (running[0]) { try { timeout.schedule(task,delay); long wait=50; if (loop++==once) { // THIS loop is the one time we wait 1000ms synchronized(count) { count[1]++; } wait=1000; } // do the wait synchronized (lock) { lock.wait(wait); } // cancel task (which may have expired) task.cancel(); } catch(Exception e) { e.printStackTrace(); } } } }; th.start(); } // run test for 5s Thread.sleep(5000); synchronized (lock) { running[0]=false; } // give some time for test to stop Thread.sleep(1000); timeout.tick(System.currentTimeMillis()); // check the counts assertEquals("count threads", LOOP,count[0]); assertEquals("count once waits",LOOP,count[1]); assertEquals("count expires",LOOP,count[2]); } }
true
true
public void testStress() throws Exception { final int LOOP=500; final boolean[] running = {true}; final int[] count = {0,0,0}; timeout.setNow(System.currentTimeMillis()); timeout.setDuration(100); // Start a ticker thread that will tick over the timer frequently. Thread ticker = new Thread() { public void run() { while (running[0]) { try { // use lock.wait so we have a memory barrier and // have no funny optimisation issues. synchronized (lock) { lock.wait(40); } timeout.tick(System.currentTimeMillis()); } catch(Exception e) { e.printStackTrace(); } } } }; ticker.start(); // start lots of test threads for (int i=0;i<LOOP;i++) { final int l =i; // Thread th = new Thread() { public void run() { // count how many threads were started (should == LOOP) synchronized(count) { count[0]++; } // create a task for this thread Timeout.Task task = new Timeout.Task() { public void expired() { // count the number of expires synchronized(count) { count[2]++; } } }; // this thread will loop and each loop with schedule a // task with a delay between 200 and 300ms on top of the timeouts 100ms duration // mostly this thread will then wait 50ms and cancel the task // But once it will wait 1000ms and the task will expire long delay = 200+this.hashCode() % 100; int once = (int)( 10+(System.currentTimeMillis() % 50)); System.err.println(l+" "+delay+" "+once); // do the looping until we are stopped int loop=0; while (running[0]) { try { timeout.schedule(task,delay); long wait=50; if (loop++==once) { // THIS loop is the one time we wait 1000ms synchronized(count) { count[1]++; } wait=1000; } // do the wait synchronized (lock) { lock.wait(wait); } // cancel task (which may have expired) task.cancel(); } catch(Exception e) { e.printStackTrace(); } } } }; th.start(); } // run test for 5s Thread.sleep(5000); synchronized (lock) { running[0]=false; } // give some time for test to stop Thread.sleep(1000); timeout.tick(System.currentTimeMillis()); // check the counts assertEquals("count threads", LOOP,count[0]); assertEquals("count once waits",LOOP,count[1]); assertEquals("count expires",LOOP,count[2]); }
public void testStress() throws Exception { final int LOOP=500; final boolean[] running = {true}; final int[] count = {0,0,0}; timeout.setNow(System.currentTimeMillis()); timeout.setDuration(100); // Start a ticker thread that will tick over the timer frequently. Thread ticker = new Thread() { public void run() { while (running[0]) { try { // use lock.wait so we have a memory barrier and // have no funny optimisation issues. synchronized (lock) { lock.wait(40); } timeout.tick(System.currentTimeMillis()); } catch(Exception e) { e.printStackTrace(); } } } }; ticker.start(); // start lots of test threads for (int i=0;i<LOOP;i++) { final int l =i; // Thread th = new Thread() { public void run() { // count how many threads were started (should == LOOP) synchronized(count) { count[0]++; } // create a task for this thread Timeout.Task task = new Timeout.Task() { public void expired() { // count the number of expires synchronized(count) { count[2]++; } } }; // this thread will loop and each loop with schedule a // task with a delay between 200 and 300ms on top of the timeouts 100ms duration // mostly this thread will then wait 50ms and cancel the task // But once it will wait 1000ms and the task will expire long delay = 200+this.hashCode() % 100; int once = (int)( 10+(System.currentTimeMillis() % 50)); // System.err.println(l+" "+delay+" "+once); // do the looping until we are stopped int loop=0; while (running[0]) { try { timeout.schedule(task,delay); long wait=50; if (loop++==once) { // THIS loop is the one time we wait 1000ms synchronized(count) { count[1]++; } wait=1000; } // do the wait synchronized (lock) { lock.wait(wait); } // cancel task (which may have expired) task.cancel(); } catch(Exception e) { e.printStackTrace(); } } } }; th.start(); } // run test for 5s Thread.sleep(5000); synchronized (lock) { running[0]=false; } // give some time for test to stop Thread.sleep(1000); timeout.tick(System.currentTimeMillis()); // check the counts assertEquals("count threads", LOOP,count[0]); assertEquals("count once waits",LOOP,count[1]); assertEquals("count expires",LOOP,count[2]); }
diff --git a/src/gov/nih/nci/nautilus/struts/form/ClinicalDataForm.java b/src/gov/nih/nci/nautilus/struts/form/ClinicalDataForm.java index 644b281d..52175fd5 100755 --- a/src/gov/nih/nci/nautilus/struts/form/ClinicalDataForm.java +++ b/src/gov/nih/nci/nautilus/struts/form/ClinicalDataForm.java @@ -1,1092 +1,1096 @@ // Created by Xslt generator for Eclipse. // XSL : not found (java.io.FileNotFoundException: (Bad file descriptor)) // Default XSL used : easystruts.jar$org.easystruts.xslgen.JavaClass.xsl package gov.nih.nci.nautilus.struts.form; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionError; import org.apache.struts.util.LabelValueBean; import java.util.*; import java.lang.reflect.*; import org.apache.log4j.Level; import gov.nih.nci.nautilus.criteria.*; import gov.nih.nci.nautilus.de.*; import gov.nih.nci.nautilus.util.Logging; import gov.nih.nci.nautilus.util.LogEntry; /** * ClinicalDataForm.java created by EasyStruts - XsltGen. * http://easystruts.sf.net * created on 08-11-2004 * * XDoclet definition: * @struts:form name="clinicalDataForm" */ public class ClinicalDataForm extends BaseForm { // --------------------------------------------------------- Instance Variables /** queryName property */ private String queryName; private String resultView; /** tumorType property */ private String tumorType; /** tumorGrade property */ private String tumorGrade; /** occurence first presentation property */ private String firstPresentation; /** occurence recurrence property */ private String recurrence; /** occurence recurrence type property */ private String recurrenceType; /** radiation group property */ private String radiation; /** radiation type property */ private String radiationType; /** chemo agent group property */ private String chemo; /** chemo agent type property */ private String chemoType; /** surgery group property */ private String surgery; /** surgery type property */ private String surgeryType; /** survival lower property */ private String survivalLower; /** survival upper property */ private String survivalUpper; /** age lower property */ private String ageLower; /** age upper property */ private String ageUpper; /** gender property */ private String genderType; // Collections used for Lookup values. //private ArrayList diseaseType;// moved to the upper class: BaseForm.java private ArrayList recurrenceTypeColl; private ArrayList radiationTypeColl; private ArrayList chemoAgentTypeColl; private ArrayList surgeryTypeColl; private ArrayList survivalLowerColl; private ArrayList survivalUpperColl; private ArrayList ageLowerColl; private ArrayList ageUpperColl; private ArrayList genderTypeColl; // criteria objects private DiseaseOrGradeCriteria diseaseOrGradeCriteria; private OccurrenceCriteria occurrenceCriteria; private RadiationTherapyCriteria radiationTherapyCriteria; private ChemoAgentCriteria chemoAgentCriteria; private SurgeryTypeCriteria surgeryTypeCriteria; private SurvivalCriteria survivalCriteria; private AgeCriteria ageCriteria; private GenderCriteria genderCriteria; // Hashmap to store Domain elements private HashMap diseaseDomainMap; private HashMap gradeDomainMap;// this one may not be used for this release. private HashMap occurrenceDomainMap; private HashMap radiationDomainMap; private HashMap chemoAgentDomainMap; private HashMap surgeryDomainMap; private HashMap survivalDomainMap; private HashMap ageDomainMap; private HashMap genderDomainMap; private HttpServletRequest thisRequest; // --------------------------------------------------------- Methods public ClinicalDataForm(){ super(); // Create Lookups for Clinical Data screens setClinicalDataLookup(); } /** * Method validate * @param ActionMapping mapping * @param HttpServletRequest request * @return ActionErrors */ public ActionErrors validate( ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); // Query Name cannot be blank if ((queryName == null || queryName.length() < 1)) errors.add("queryName", new ActionError("gov.nih.nci.nautilus.struts.form.queryname.no.error")); // survival range validations if (this.survivalLower != null && this.survivalUpper != null) { try{ if(Integer.parseInt(survivalLower) >= Integer.parseInt(survivalUpper)){ errors.add("survivalUpper", new ActionError("gov.nih.nci.nautilus.struts.form.survivalRange.upperRange.error")); } } catch(NumberFormatException ex){ LogEntry logEntry = new LogEntry(Level.ERROR,ex.fillInStackTrace()); Logging.add(logEntry); } } if (this.ageLower != null && this.ageUpper != null) { try{ if(Integer.parseInt(ageLower) >=Integer.parseInt(ageUpper)){ errors.add("ageUpper", new ActionError("gov.nih.nci.nautilus.struts.form.ageRange.upperRange.error")); } } catch(NumberFormatException ex){ LogEntry logEntry = new LogEntry(Level.ERROR,ex.fillInStackTrace()); Logging.add(logEntry); } } if (errors.isEmpty()) { createDiseaseCriteriaObject(); createOccurrenceCriteriaObject(); createRadiationTherapyCriteriaObject(); createChemoAgentCriteriaObject(); createSurgeryTypeCriteriaObject(); createSurvivalCriteriaObject(); createAgeCriteriaObject(); createGenderCriteriaObject(); } return errors; } private void createDiseaseCriteriaObject(){ if(diseaseDomainMap != null){ Set keySet = diseaseDomainMap.keySet(); Iterator iter = keySet.iterator(); while(iter.hasNext()){ try{ String key = (String)iter.next(); String className = (String)diseaseDomainMap.get(key); Constructor[] diseaseConstructors = Class.forName(className).getConstructors(); String[] initargs = {key}; DiseaseNameDE diseaseDE = (DiseaseNameDE)diseaseConstructors[0].newInstance(initargs); diseaseOrGradeCriteria.setDisease(diseaseDE); } // end of try catch (Exception ex) { LogEntry logEntry = new LogEntry(Level.ERROR,"Error in createDiseaseCriteriaObject() method: "+ex.getMessage()); Logging.add(logEntry); logEntry = new LogEntry(Level.ERROR,ex.fillInStackTrace()); Logging.add(logEntry); } catch (LinkageError le) { LogEntry logEntry = new LogEntry(Level.ERROR,"Linkage Error in createDiseaseCriteriaObject() method: "+ le.getMessage()); Logging.add(logEntry); logEntry = new LogEntry(Level.ERROR,le.fillInStackTrace()); Logging.add(logEntry); } }// end of while }// end of if } private void createOccurrenceCriteriaObject() { // Loop thru the HashMap, extract the Domain elements and create respective Criteria Objects Set keys = occurrenceDomainMap.keySet(); System.out.println("occurrenceDomainMap.size() is :"+occurrenceDomainMap.size()); Iterator i = keys.iterator(); while (i.hasNext()) { Object key = i.next(); LogEntry logEntry = new LogEntry(Level.DEBUG,key + "=>" + occurrenceDomainMap.get(key)); Logging.add(logEntry); try { String strOccurenceClass = (String) occurrenceDomainMap.get(key); Constructor [] occurrenceConstructors = Class.forName(strOccurenceClass).getConstructors(); Object [] parameterObjects = {key}; OccurrenceDE occurrenceDE = (OccurrenceDE) occurrenceConstructors[0].newInstance(parameterObjects); occurrenceCriteria.setOccurrence(occurrenceDE); logEntry = new LogEntry(Level.DEBUG,"Occurrence Domain Element Value==> "+occurrenceDE.getValueObject()); Logging.add(logEntry); } catch (Exception ex) { logEntry = new LogEntry(Level.ERROR,"Error in createOccurrenceCriteriaObject() method: "+ex.getMessage()); Logging.add(logEntry); logEntry = new LogEntry(Level.ERROR,ex.fillInStackTrace()); Logging.add(logEntry); } catch (LinkageError le) { logEntry = new LogEntry(Level.ERROR,"Linkage Error in createOccurrenceCriteriaObject() method "+ le.getMessage()); Logging.add(logEntry); logEntry = new LogEntry(Level.ERROR,le.fillInStackTrace()); Logging.add(logEntry); } } } private void createRadiationTherapyCriteriaObject() { Set keys = radiationDomainMap.keySet(); Iterator i = keys.iterator(); while (i.hasNext()) { Object key = i.next(); LogEntry logEntry = new LogEntry(Level.ERROR,key + "=>" + radiationDomainMap.get(key)); Logging.add(logEntry); try { String strRadiationClass = (String) radiationDomainMap.get(key); Constructor [] radiationConstructors = Class.forName(strRadiationClass).getConstructors(); Object [] parameterObjects = {(String) key}; RadiationTherapyDE radiationTherapyDE = (RadiationTherapyDE) radiationConstructors[0].newInstance(parameterObjects); radiationTherapyCriteria.setRadiationTherapyDE(radiationTherapyDE); logEntry = new LogEntry(Level.DEBUG,"Radiation Domain Element Value is ==>"+radiationTherapyDE.getValueObject()); Logging.add(logEntry); } catch (Exception ex) { logEntry = new LogEntry(Level.ERROR,"Error in createRadiationTherapyCriteriaObject() mehtod :"+ex.getMessage()); Logging.add(logEntry); logEntry = new LogEntry(Level.ERROR,ex.fillInStackTrace()); Logging.add(logEntry); } catch (LinkageError le) { logEntry = new LogEntry(Level.ERROR,"Linkage Error in createRadiationTherapyCriteriaObject() method :"+ le.getMessage()); Logging.add(logEntry); logEntry = new LogEntry(Level.ERROR,le.fillInStackTrace()); Logging.add(logEntry); } } } private void createChemoAgentCriteriaObject() { Set keys = chemoAgentDomainMap.keySet(); Iterator i = keys.iterator(); while (i.hasNext()) { Object key = i.next(); LogEntry logEntry = new LogEntry(Level.DEBUG,key + "=>" + chemoAgentDomainMap.get(key)); Logging.add(logEntry); try { String strChemoDomainClass = (String) chemoAgentDomainMap.get(key); Constructor [] chemoConstructors = Class.forName(strChemoDomainClass).getConstructors(); Object [] parameterObjects = {(String) key}; ChemoAgentDE chemoAgentDE = (ChemoAgentDE) chemoConstructors[0].newInstance(parameterObjects); chemoAgentCriteria.setChemoAgentDE(chemoAgentDE); logEntry = new LogEntry(Level.DEBUG,"Chemo Agent Domain Element Value is ==>"+chemoAgentDE.getValueObject()); Logging.add(logEntry); } catch (Exception ex) { logEntry = new LogEntry(Level.ERROR,"Error in createChemoAgentCriteriaObject() method: "+ex.getMessage()); Logging.add(logEntry); logEntry = new LogEntry(Level.ERROR,ex.fillInStackTrace()); Logging.add(logEntry); } catch (LinkageError le) { logEntry = new LogEntry(Level.ERROR,"Linkage Error in createChemoAgentCriteriaObject() method: "+ le.getMessage()); Logging.add(logEntry); logEntry = new LogEntry(Level.ERROR,le.fillInStackTrace()); Logging.add(logEntry); } } } private void createSurgeryTypeCriteriaObject() { // Loop thru the surgeryDomainMap HashMap, extract the Domain elements and create respective Criteria Objects Set keys = surgeryDomainMap.keySet(); Iterator i = keys.iterator(); while (i.hasNext()) { Object key = i.next(); LogEntry logEntry = new LogEntry(Level.DEBUG,key + "=>" + surgeryDomainMap.get(key)); Logging.add(logEntry); try { String strSurgeryDomainClass = (String) surgeryDomainMap.get(key); Constructor [] surgeryConstructors = Class.forName(strSurgeryDomainClass).getConstructors(); Object [] parameterObjects = {key}; SurgeryTypeDE surgeryTypeDE = (SurgeryTypeDE) surgeryConstructors[0].newInstance(parameterObjects); surgeryTypeCriteria.setSurgeryTypeDE(surgeryTypeDE); logEntry = new LogEntry(Level.DEBUG,"Surgery Domain Element Value==> "+surgeryTypeDE.getValueObject()); Logging.add(logEntry); } catch (Exception ex) { logEntry = new LogEntry(Level.ERROR,"Error in createSurgeryTypeCriteriaObject() method: "+ex.getMessage()); Logging.add(logEntry); logEntry = new LogEntry(Level.ERROR,ex.fillInStackTrace()); Logging.add(logEntry); } catch (LinkageError le) { logEntry = new LogEntry(Level.ERROR,"Linkage Error in createSurgeryTypeCriteriaObject() method: "+ le.getMessage()); Logging.add(logEntry); logEntry = new LogEntry(Level.ERROR,le.fillInStackTrace()); Logging.add(logEntry); } } } private void createSurvivalCriteriaObject() { // Loop thru the survivalDomainMap HashMap, extract the Domain elements and create respective Criteria Objects Set keys = survivalDomainMap.keySet(); Iterator i = keys.iterator(); while (i.hasNext()) { Object key = i.next(); System.out.println(key + "=>" + survivalDomainMap.get(key)); try { String strSurvivalDomainClass = (String) survivalDomainMap.get(key); Constructor [] survivalConstructors = Class.forName(strSurvivalDomainClass).getConstructors(); if(strSurvivalDomainClass.endsWith("LowerSurvivalRange")){ Object [] parameterObjects = {Integer.valueOf((String) key)}; SurvivalDE.LowerSurvivalRange lowerSurvivalRange = (SurvivalDE.LowerSurvivalRange)survivalConstructors[0].newInstance(parameterObjects); survivalCriteria.setLowerSurvivalRange(lowerSurvivalRange); } else if(strSurvivalDomainClass.endsWith("UpperSurvivalRange")){ Object [] parameterObjects = {Integer.valueOf((String) key)}; SurvivalDE.UpperSurvivalRange upperSurvivalRange = (SurvivalDE.UpperSurvivalRange)survivalConstructors[0].newInstance(parameterObjects); survivalCriteria.setUpperSurvivalRange(upperSurvivalRange); } } catch (Exception ex) { LogEntry logEntry = new LogEntry(Level.ERROR,"Error in createSurvivalCriteriaObject() method: "+ ex.getMessage()); Logging.add(logEntry); logEntry = new LogEntry(Level.ERROR,ex.fillInStackTrace()); Logging.add(logEntry); } catch (LinkageError le) { LogEntry logEntry = new LogEntry(Level.ERROR,"Linkage Error in createSurvivalCriteriaObject() method: "+ le.getMessage()); Logging.add(logEntry); logEntry = new LogEntry(Level.ERROR,le.fillInStackTrace()); Logging.add(logEntry); } } } private void createAgeCriteriaObject() { // Loop thru the ageDomainMap HashMap, extract the Domain elements and create respective Criteria Objects Set keys = ageDomainMap.keySet(); Iterator i = keys.iterator(); while (i.hasNext()) { Object key = i.next(); LogEntry logEntry = new LogEntry(Level.DEBUG,key + "=>" + ageDomainMap.get(key)); Logging.add(logEntry); try { String strAgeDomainClass = (String) ageDomainMap.get(key); Constructor [] ageConstructors = Class.forName(strAgeDomainClass).getConstructors(); if(strAgeDomainClass.endsWith("LowerAgeLimit")){ Object [] parameterObjects = {Integer.valueOf((String) key)}; AgeAtDiagnosisDE.LowerAgeLimit lowerAgeLimit = (AgeAtDiagnosisDE.LowerAgeLimit)ageConstructors[0].newInstance(parameterObjects); ageCriteria.setLowerAgeLimit(lowerAgeLimit); } else if(strAgeDomainClass.endsWith("UpperAgeLimit")){ Object [] parameterObjects = {Integer.valueOf((String) key)}; AgeAtDiagnosisDE.UpperAgeLimit upperAgeLimit = (AgeAtDiagnosisDE.UpperAgeLimit)ageConstructors[0].newInstance(parameterObjects); ageCriteria.setUpperAgeLimit(upperAgeLimit); } } catch (Exception ex) { logEntry = new LogEntry(Level.ERROR,"Error in createGeneCriteriaObject: "+ ex.getMessage()); Logging.add(logEntry); logEntry = new LogEntry(Level.ERROR,ex.fillInStackTrace()); Logging.add(logEntry); } catch (LinkageError le) { logEntry = new LogEntry(Level.ERROR,"Linkage Error in createAgeCriteriaObject() method: "+ le.getMessage()); Logging.add(logEntry); logEntry = new LogEntry(Level.ERROR,le.fillInStackTrace()); Logging.add(logEntry); } } } private void createGenderCriteriaObject() { // Loop thru the genderDomainMap HashMap, extract the Domain elements and create respective Criteria Objects Set keys = genderDomainMap.keySet(); Iterator i = keys.iterator(); while (i.hasNext()) { Object key = i.next(); LogEntry logEntry = new LogEntry(Level.ERROR,key + "=>" + genderDomainMap.get(key)); Logging.add(logEntry); try { String strGenderDomainClass = (String) genderDomainMap.get(key); Constructor [] genderConstructors = Class.forName(strGenderDomainClass).getConstructors(); Object [] parameterObjects = {key}; GenderDE genderDE = (GenderDE)genderConstructors[0].newInstance(parameterObjects); genderCriteria.setGenderDE(genderDE); logEntry = new LogEntry(Level.DEBUG,"Gender Domain Element Value==> "+genderDE.getValueObject()); Logging.add(logEntry); } catch (Exception ex) { logEntry = new LogEntry(Level.ERROR,"Error in createGenderCriteriaObject() method: "+ex.getMessage()); Logging.add(logEntry); logEntry = new LogEntry(Level.ERROR,ex.fillInStackTrace()); Logging.add(logEntry); } catch (LinkageError le) { logEntry = new LogEntry(Level.ERROR,"Linkage Error in createGenderCriteriaObject() method: "+ le.getMessage()); Logging.add(logEntry); logEntry = new LogEntry(Level.ERROR,le.fillInStackTrace()); Logging.add(logEntry); } } } public void setClinicalDataLookup() { recurrenceTypeColl = new ArrayList(); radiationTypeColl = new ArrayList(); chemoAgentTypeColl = new ArrayList(); surgeryTypeColl = new ArrayList(); survivalLowerColl = new ArrayList(); survivalUpperColl = new ArrayList(); ageLowerColl = new ArrayList(); ageUpperColl = new ArrayList(); genderTypeColl = new ArrayList(); recurrenceTypeColl.add( new LabelValueBean( "Any", "any" ) ); recurrenceTypeColl.add( new LabelValueBean( "1", "1" ) ); recurrenceTypeColl.add( new LabelValueBean( "2", "2" ) ); recurrenceTypeColl.add( new LabelValueBean( "3", "3" ) ); radiationTypeColl.add( new LabelValueBean( "Any", "any" ) ); radiationTypeColl.add( new LabelValueBean( "Photon", "photon" ) ); chemoAgentTypeColl.add( new LabelValueBean( "Any", "any" ) ); surgeryTypeColl.add( new LabelValueBean( "Any", "any" ) ); surgeryTypeColl.add( new LabelValueBean( "Complete Resection(CR)", "Complete Resection(CR)" ) ); surgeryTypeColl.add( new LabelValueBean( "Partial Resection(PR)", "Partial Resection(PR)" ) ); surgeryTypeColl.add( new LabelValueBean( "Bioposy Only(BX)", "Bioposy Only(BX)" ) ); + survivalLowerColl.add( new LabelValueBean( "", "" ) ); survivalLowerColl.add( new LabelValueBean( "0", "0" ) ); survivalLowerColl.add( new LabelValueBean( "10", "10" ) ); survivalLowerColl.add( new LabelValueBean( "20", "20" ) ); survivalLowerColl.add( new LabelValueBean( "30", "30" ) ); survivalLowerColl.add( new LabelValueBean( "40", "40" ) ); survivalLowerColl.add( new LabelValueBean( "50", "50" ) ); survivalLowerColl.add( new LabelValueBean( "60", "60" ) ); survivalLowerColl.add( new LabelValueBean( "70", "70" ) ); survivalLowerColl.add( new LabelValueBean( "80", "80" ) ); survivalLowerColl.add( new LabelValueBean( "90", "90" ) ); + survivalUpperColl.add( new LabelValueBean( "", "" ) ); survivalUpperColl.add( new LabelValueBean( "0", "0" ) ); survivalUpperColl.add( new LabelValueBean( "10", "10" ) ); survivalUpperColl.add( new LabelValueBean( "20", "20" ) ); survivalUpperColl.add( new LabelValueBean( "30", "30" ) ); survivalUpperColl.add( new LabelValueBean( "40", "40" ) ); survivalUpperColl.add( new LabelValueBean( "50", "50" ) ); survivalUpperColl.add( new LabelValueBean( "60", "60" ) ); survivalUpperColl.add( new LabelValueBean( "70", "70" ) ); survivalUpperColl.add( new LabelValueBean( "80", "80" ) ); survivalUpperColl.add( new LabelValueBean( "90", "90" ) ); survivalUpperColl.add( new LabelValueBean( "90+", "90+" ) ); + ageLowerColl.add( new LabelValueBean( "", "" ) ); ageLowerColl.add( new LabelValueBean( "0", "0" ) ); ageLowerColl.add( new LabelValueBean( "10", "10" ) ); ageLowerColl.add( new LabelValueBean( "20", "20" ) ); ageLowerColl.add( new LabelValueBean( "30", "30" ) ); ageLowerColl.add( new LabelValueBean( "40", "40" ) ); ageLowerColl.add( new LabelValueBean( "50", "50" ) ); ageLowerColl.add( new LabelValueBean( "60", "60" ) ); ageLowerColl.add( new LabelValueBean( "70", "70" ) ); ageLowerColl.add( new LabelValueBean( "80", "80" ) ); ageLowerColl.add( new LabelValueBean( "90", "90" ) ); + ageUpperColl.add( new LabelValueBean( "", "" ) ); ageUpperColl.add( new LabelValueBean( "0", "0" ) ); ageUpperColl.add( new LabelValueBean( "10", "10" ) ); ageUpperColl.add( new LabelValueBean( "20", "20" ) ); ageUpperColl.add( new LabelValueBean( "30", "30" ) ); ageUpperColl.add( new LabelValueBean( "40", "40" ) ); ageUpperColl.add( new LabelValueBean( "50", "50" ) ); ageUpperColl.add( new LabelValueBean( "60", "60" ) ); ageUpperColl.add( new LabelValueBean( "70", "70" ) ); ageUpperColl.add( new LabelValueBean( "80", "80" ) ); ageUpperColl.add( new LabelValueBean( "90", "90" ) ); ageUpperColl.add( new LabelValueBean( "90+", "90+" ) ); genderTypeColl.add( new LabelValueBean( "all", "all" ) ); genderTypeColl.add( new LabelValueBean( "Male", "male" ) ); genderTypeColl.add( new LabelValueBean( "Female", "female" ) ); genderTypeColl.add( new LabelValueBean( "Other", "other" ) ); } /** * Method reset. * Reset all properties to their default values. * @param ActionMapping mapping used to select this instance. * @param HttpServletRequest request The servlet request we are processing. */ public void reset(ActionMapping mapping, HttpServletRequest request) { queryName =""; resultView = ""; tumorType=""; tumorGrade=""; firstPresentation=""; recurrence=""; recurrenceType =""; radiation=""; radiationType=""; chemo=""; chemoType=""; surgery=""; surgeryType=""; survivalLower=""; survivalUpper=""; ageLower=""; ageUpper=""; genderType=""; diseaseOrGradeCriteria = new DiseaseOrGradeCriteria(); occurrenceCriteria = new OccurrenceCriteria(); radiationTherapyCriteria = new RadiationTherapyCriteria(); chemoAgentCriteria = new ChemoAgentCriteria(); surgeryTypeCriteria = new SurgeryTypeCriteria(); survivalCriteria = new SurvivalCriteria(); ageCriteria = new AgeCriteria(); genderCriteria = new GenderCriteria(); diseaseDomainMap = new HashMap(); gradeDomainMap = new HashMap(); occurrenceDomainMap = new HashMap(); radiationDomainMap = new HashMap(); chemoAgentDomainMap = new HashMap(); surgeryDomainMap = new HashMap(); survivalDomainMap = new HashMap(); ageDomainMap = new HashMap(); genderDomainMap = new HashMap(); thisRequest = request; } /** * Set the tumorType. * @param tumorType The tumorType to set */ public void setTumorType(String tumorType) { this.tumorType = tumorType; diseaseDomainMap.put(this.tumorType, DiseaseNameDE.class.getName()); } /** * Returns the tumorGrade. * @return String */ public String getTumorGrade() { return tumorGrade; } /** * Set the tumorGrade. * @param tumorType The tumorGrade to set */ public void setTumorGrade(String tumorGrade) { this.tumorGrade = tumorGrade; gradeDomainMap.put(this.tumorGrade, GradeDE.class.getName()); } /** * Returns the tumorType. * @return String */ public String getTumorType() { return tumorType; } /** * Set the firstPresentation. * @param firstPresentation The firstPresentation to set */ public void setFirstPresentation(String firstPresentation) { if(firstPresentation != null && firstPresentation.equalsIgnoreCase("on")){ this.firstPresentation = "first presentation"; } String firstPresent = (String)thisRequest.getParameter("firstPresentation"); if(firstPresent != null){ occurrenceDomainMap.put(this.firstPresentation , OccurrenceDE.class.getName()); } } /** * Returns the firstPresentation. * @return String */ public String getFirstPresentation() { return firstPresentation; } /** * Set the recurrence. * @param recurrence The recurrence to set */ public void setRecurrence(String recurrence) { this.recurrence = recurrence; String recurrenceStr = (String)thisRequest.getParameter("recur"); String recurrenceSpecify =(String)thisRequest.getParameter("recurrence"); if(recurrenceStr != null && recurrenceSpecify != null){ occurrenceDomainMap.put(this.recurrence, OccurrenceDE.class.getName()); } } /** * Returns the recurrence. * @return String */ public String getRecurrence() { return recurrence; } /** * Set the recurrenceType. * @param recurrenceType The recurrenceType to set */ public void setRecurrenceType(String recurrenceType) { this.recurrenceType = recurrenceType; occurrenceDomainMap.put(this.recurrenceType, OccurrenceDE.class.getName()); } /** * Returns the recurrenceType. * @return String */ public String getRecurrenceType() { return recurrenceType; } /** * Set the radiation. * @param radiation The radiation to set */ public void setRadiation(String radiation) { this.radiation = radiation; } /** * Returns the radiation. * @return String */ public String getRadiation() { return radiation; } /** * Set the radiationType. * @param radiationType The radiationType to set */ public void setRadiationType(String radiationType) { this.radiationType = radiationType; // this is to check if radiation option is selected String thisRadiation = (String)thisRequest.getParameter("radiation"); LogEntry logEntry = new LogEntry(Level.DEBUG,"thisRadiation is this is a test:"+thisRadiation); Logging.add(logEntry); // this is to check the type of radiation String thisRadiationType = (String)thisRequest.getParameter("radiationType"); if(thisRadiation != null && thisRadiationType != null && !thisRadiationType.equals("")){ radiationDomainMap.put(this.radiationType, RadiationTherapyDE.class.getName()); } } /** * Returns the radiationType. * @return String */ public String getRadiationType() { return radiationType; } /** * Set the chemo. * @param chemo The chemo to set */ public void setChemo(String chemo) { this.chemo = chemo; } /** * Returns the chemo. * @return String */ public String getChemo() { return chemo; } /** * Set the chemoType. * @param chemoType The chemoType to set */ public void setChemoType(String chemoType) { this.chemoType = chemoType; // this is to check if the chemo option is selected String thisChemo = (String)thisRequest.getParameter("chemo"); // this is to check the chemo type String thisChemoType = (String)thisRequest.getParameter("chemoType"); if(thisChemo != null && thisChemoType != null && !thisChemoType.equals("")){ chemoAgentDomainMap.put(this.chemoType, ChemoAgentDE.class.getName()); } } /** * Returns the chemoType. * @return String */ public String getChemoType() { return chemoType; } /** * Set the surgery. * @param surgery The surgery to set */ public void setSurgery(String surgery) { this.surgery = surgery; } /** * Returns the surgery. * @return String */ public String getSurgery() { return surgery; } /** * Set the surgeryType. * @param surgeryType The surgeryType to set */ public void setSurgeryType(String surgeryType) { this.surgeryType = surgeryType; String thisSurgery =(String)thisRequest.getParameter("sugery"); String thisSurgeryType = (String)thisRequest.getParameter("surgeryType"); if(thisSurgery != null && thisSurgeryType != null && !thisSurgeryType.equals("")){ surgeryDomainMap.put(this.surgeryType, SurgeryTypeDE.class.getName()); } } /** * Returns the surgeryType. * @return String */ public String getSurgeryType() { return surgeryType; } /** * Set the survivalLower. * @param survivalLower The survivalLower to set */ public void setSurvivalLower(String survivalLower) { this.survivalLower = survivalLower; survivalDomainMap.put(this.survivalLower, SurvivalDE.LowerSurvivalRange.class.getName()); } /** * Returns the survivalLower. * @return String */ public String getSurvivalLower() { return survivalLower; } /** * Set the survivalUpper. * @param survivalUpper The survivalUpper to set */ public void setSurvivalUpper(String survivalUpper) { this.survivalUpper = survivalUpper; survivalDomainMap.put(this.survivalUpper, SurvivalDE.UpperSurvivalRange.class.getName()); } /** * Returns the survivalUpper. * @return String */ public String getSurvivalUpper() { return survivalUpper; } /** * Set the ageLower. * @param ageLower The ageLower to set */ public void setAgeLower(String ageLower) { this.ageLower = ageLower; ageDomainMap.put(this.ageLower, AgeAtDiagnosisDE.LowerAgeLimit.class.getName()); } /** * Returns the ageLower. * @return String */ public String getAgeLower() { return ageLower; } /** * Set the ageUpper. * @param ageUpper The ageUpper to set */ public void setAgeUpper(String ageUpper) { this.ageUpper = ageUpper; ageDomainMap.put(this.ageUpper, AgeAtDiagnosisDE.UpperAgeLimit.class.getName()); } /** * Returns the genderType. * @return String */ public String getAgeUpper() { return ageUpper; } /** * Set the genderType. * @param genderType The genderType to set */ public void setGenderType(String genderType) { this.genderType = genderType; genderDomainMap.put(this.genderType, GenderDE.class.getName()); } /** * Returns the genderType. * @return String */ public String getGenderType() { return genderType; } /** * Set the queryName. * @param queryName The queryName to set */ public void setQueryName(String queryName) { this.queryName = queryName; } /** * Returns the queryName. * @return String */ public String getQueryName() { return queryName; } /** * Returns the resultView. * @return String */ public String getResultView() { return resultView; } /** * Set the resultView. * @param resultView The resultView to set */ public void setResultView(String resultView) { this.resultView = resultView; } public DiseaseOrGradeCriteria getDiseaseOrGradeCriteria() { return this.diseaseOrGradeCriteria; } public OccurrenceCriteria getOccurrenceCriteria() { return this.occurrenceCriteria; } public SurgeryTypeCriteria getSurgeryTypeCriteria(){ return this.surgeryTypeCriteria; } public RadiationTherapyCriteria getRadiationTherapyCriteria(){ return this.radiationTherapyCriteria; } public ChemoAgentCriteria getChemoAgentCriteria(){ return this.chemoAgentCriteria; } public SurvivalCriteria getSurvivalCriteria(){ return this.survivalCriteria; } public AgeCriteria getAgeCriteria(){ return this.ageCriteria; } public GenderCriteria getGenderCriteria(){ return this.genderCriteria; } public ArrayList getRecurrenceTypeColl() { return recurrenceTypeColl; } public ArrayList getRadiationTypeColl() { return radiationTypeColl; } public ArrayList getChemoAgentTypeColl() { return chemoAgentTypeColl; } public ArrayList getSurgeryTypeColl() { return surgeryTypeColl; } public ArrayList getSurvivalLowerColl() { return survivalLowerColl; } public ArrayList getSurvivalUpperColl() { return survivalUpperColl; } public ArrayList getAgeLowerColl() { return ageLowerColl; } public ArrayList getAgeUpperColl() { return ageUpperColl; } public ArrayList getGenderTypeColl() { return genderTypeColl; } }
false
true
public void setClinicalDataLookup() { recurrenceTypeColl = new ArrayList(); radiationTypeColl = new ArrayList(); chemoAgentTypeColl = new ArrayList(); surgeryTypeColl = new ArrayList(); survivalLowerColl = new ArrayList(); survivalUpperColl = new ArrayList(); ageLowerColl = new ArrayList(); ageUpperColl = new ArrayList(); genderTypeColl = new ArrayList(); recurrenceTypeColl.add( new LabelValueBean( "Any", "any" ) ); recurrenceTypeColl.add( new LabelValueBean( "1", "1" ) ); recurrenceTypeColl.add( new LabelValueBean( "2", "2" ) ); recurrenceTypeColl.add( new LabelValueBean( "3", "3" ) ); radiationTypeColl.add( new LabelValueBean( "Any", "any" ) ); radiationTypeColl.add( new LabelValueBean( "Photon", "photon" ) ); chemoAgentTypeColl.add( new LabelValueBean( "Any", "any" ) ); surgeryTypeColl.add( new LabelValueBean( "Any", "any" ) ); surgeryTypeColl.add( new LabelValueBean( "Complete Resection(CR)", "Complete Resection(CR)" ) ); surgeryTypeColl.add( new LabelValueBean( "Partial Resection(PR)", "Partial Resection(PR)" ) ); surgeryTypeColl.add( new LabelValueBean( "Bioposy Only(BX)", "Bioposy Only(BX)" ) ); survivalLowerColl.add( new LabelValueBean( "0", "0" ) ); survivalLowerColl.add( new LabelValueBean( "10", "10" ) ); survivalLowerColl.add( new LabelValueBean( "20", "20" ) ); survivalLowerColl.add( new LabelValueBean( "30", "30" ) ); survivalLowerColl.add( new LabelValueBean( "40", "40" ) ); survivalLowerColl.add( new LabelValueBean( "50", "50" ) ); survivalLowerColl.add( new LabelValueBean( "60", "60" ) ); survivalLowerColl.add( new LabelValueBean( "70", "70" ) ); survivalLowerColl.add( new LabelValueBean( "80", "80" ) ); survivalLowerColl.add( new LabelValueBean( "90", "90" ) ); survivalUpperColl.add( new LabelValueBean( "0", "0" ) ); survivalUpperColl.add( new LabelValueBean( "10", "10" ) ); survivalUpperColl.add( new LabelValueBean( "20", "20" ) ); survivalUpperColl.add( new LabelValueBean( "30", "30" ) ); survivalUpperColl.add( new LabelValueBean( "40", "40" ) ); survivalUpperColl.add( new LabelValueBean( "50", "50" ) ); survivalUpperColl.add( new LabelValueBean( "60", "60" ) ); survivalUpperColl.add( new LabelValueBean( "70", "70" ) ); survivalUpperColl.add( new LabelValueBean( "80", "80" ) ); survivalUpperColl.add( new LabelValueBean( "90", "90" ) ); survivalUpperColl.add( new LabelValueBean( "90+", "90+" ) ); ageLowerColl.add( new LabelValueBean( "0", "0" ) ); ageLowerColl.add( new LabelValueBean( "10", "10" ) ); ageLowerColl.add( new LabelValueBean( "20", "20" ) ); ageLowerColl.add( new LabelValueBean( "30", "30" ) ); ageLowerColl.add( new LabelValueBean( "40", "40" ) ); ageLowerColl.add( new LabelValueBean( "50", "50" ) ); ageLowerColl.add( new LabelValueBean( "60", "60" ) ); ageLowerColl.add( new LabelValueBean( "70", "70" ) ); ageLowerColl.add( new LabelValueBean( "80", "80" ) ); ageLowerColl.add( new LabelValueBean( "90", "90" ) ); ageUpperColl.add( new LabelValueBean( "0", "0" ) ); ageUpperColl.add( new LabelValueBean( "10", "10" ) ); ageUpperColl.add( new LabelValueBean( "20", "20" ) ); ageUpperColl.add( new LabelValueBean( "30", "30" ) ); ageUpperColl.add( new LabelValueBean( "40", "40" ) ); ageUpperColl.add( new LabelValueBean( "50", "50" ) ); ageUpperColl.add( new LabelValueBean( "60", "60" ) ); ageUpperColl.add( new LabelValueBean( "70", "70" ) ); ageUpperColl.add( new LabelValueBean( "80", "80" ) ); ageUpperColl.add( new LabelValueBean( "90", "90" ) ); ageUpperColl.add( new LabelValueBean( "90+", "90+" ) ); genderTypeColl.add( new LabelValueBean( "all", "all" ) ); genderTypeColl.add( new LabelValueBean( "Male", "male" ) ); genderTypeColl.add( new LabelValueBean( "Female", "female" ) ); genderTypeColl.add( new LabelValueBean( "Other", "other" ) ); }
public void setClinicalDataLookup() { recurrenceTypeColl = new ArrayList(); radiationTypeColl = new ArrayList(); chemoAgentTypeColl = new ArrayList(); surgeryTypeColl = new ArrayList(); survivalLowerColl = new ArrayList(); survivalUpperColl = new ArrayList(); ageLowerColl = new ArrayList(); ageUpperColl = new ArrayList(); genderTypeColl = new ArrayList(); recurrenceTypeColl.add( new LabelValueBean( "Any", "any" ) ); recurrenceTypeColl.add( new LabelValueBean( "1", "1" ) ); recurrenceTypeColl.add( new LabelValueBean( "2", "2" ) ); recurrenceTypeColl.add( new LabelValueBean( "3", "3" ) ); radiationTypeColl.add( new LabelValueBean( "Any", "any" ) ); radiationTypeColl.add( new LabelValueBean( "Photon", "photon" ) ); chemoAgentTypeColl.add( new LabelValueBean( "Any", "any" ) ); surgeryTypeColl.add( new LabelValueBean( "Any", "any" ) ); surgeryTypeColl.add( new LabelValueBean( "Complete Resection(CR)", "Complete Resection(CR)" ) ); surgeryTypeColl.add( new LabelValueBean( "Partial Resection(PR)", "Partial Resection(PR)" ) ); surgeryTypeColl.add( new LabelValueBean( "Bioposy Only(BX)", "Bioposy Only(BX)" ) ); survivalLowerColl.add( new LabelValueBean( "", "" ) ); survivalLowerColl.add( new LabelValueBean( "0", "0" ) ); survivalLowerColl.add( new LabelValueBean( "10", "10" ) ); survivalLowerColl.add( new LabelValueBean( "20", "20" ) ); survivalLowerColl.add( new LabelValueBean( "30", "30" ) ); survivalLowerColl.add( new LabelValueBean( "40", "40" ) ); survivalLowerColl.add( new LabelValueBean( "50", "50" ) ); survivalLowerColl.add( new LabelValueBean( "60", "60" ) ); survivalLowerColl.add( new LabelValueBean( "70", "70" ) ); survivalLowerColl.add( new LabelValueBean( "80", "80" ) ); survivalLowerColl.add( new LabelValueBean( "90", "90" ) ); survivalUpperColl.add( new LabelValueBean( "", "" ) ); survivalUpperColl.add( new LabelValueBean( "0", "0" ) ); survivalUpperColl.add( new LabelValueBean( "10", "10" ) ); survivalUpperColl.add( new LabelValueBean( "20", "20" ) ); survivalUpperColl.add( new LabelValueBean( "30", "30" ) ); survivalUpperColl.add( new LabelValueBean( "40", "40" ) ); survivalUpperColl.add( new LabelValueBean( "50", "50" ) ); survivalUpperColl.add( new LabelValueBean( "60", "60" ) ); survivalUpperColl.add( new LabelValueBean( "70", "70" ) ); survivalUpperColl.add( new LabelValueBean( "80", "80" ) ); survivalUpperColl.add( new LabelValueBean( "90", "90" ) ); survivalUpperColl.add( new LabelValueBean( "90+", "90+" ) ); ageLowerColl.add( new LabelValueBean( "", "" ) ); ageLowerColl.add( new LabelValueBean( "0", "0" ) ); ageLowerColl.add( new LabelValueBean( "10", "10" ) ); ageLowerColl.add( new LabelValueBean( "20", "20" ) ); ageLowerColl.add( new LabelValueBean( "30", "30" ) ); ageLowerColl.add( new LabelValueBean( "40", "40" ) ); ageLowerColl.add( new LabelValueBean( "50", "50" ) ); ageLowerColl.add( new LabelValueBean( "60", "60" ) ); ageLowerColl.add( new LabelValueBean( "70", "70" ) ); ageLowerColl.add( new LabelValueBean( "80", "80" ) ); ageLowerColl.add( new LabelValueBean( "90", "90" ) ); ageUpperColl.add( new LabelValueBean( "", "" ) ); ageUpperColl.add( new LabelValueBean( "0", "0" ) ); ageUpperColl.add( new LabelValueBean( "10", "10" ) ); ageUpperColl.add( new LabelValueBean( "20", "20" ) ); ageUpperColl.add( new LabelValueBean( "30", "30" ) ); ageUpperColl.add( new LabelValueBean( "40", "40" ) ); ageUpperColl.add( new LabelValueBean( "50", "50" ) ); ageUpperColl.add( new LabelValueBean( "60", "60" ) ); ageUpperColl.add( new LabelValueBean( "70", "70" ) ); ageUpperColl.add( new LabelValueBean( "80", "80" ) ); ageUpperColl.add( new LabelValueBean( "90", "90" ) ); ageUpperColl.add( new LabelValueBean( "90+", "90+" ) ); genderTypeColl.add( new LabelValueBean( "all", "all" ) ); genderTypeColl.add( new LabelValueBean( "Male", "male" ) ); genderTypeColl.add( new LabelValueBean( "Female", "female" ) ); genderTypeColl.add( new LabelValueBean( "Other", "other" ) ); }
diff --git a/kikko-jpa/src/main/java/pl/kikko/jpa/entity/BaseEntity.java b/kikko-jpa/src/main/java/pl/kikko/jpa/entity/BaseEntity.java index 6460464..fead7df 100644 --- a/kikko-jpa/src/main/java/pl/kikko/jpa/entity/BaseEntity.java +++ b/kikko-jpa/src/main/java/pl/kikko/jpa/entity/BaseEntity.java @@ -1,32 +1,32 @@ package pl.kikko.jpa.entity; import pl.kikko.patterns.builder.AbstractBuildableBuilder; import pl.kikko.patterns.builder.Buildable; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.MappedSuperclass; @MappedSuperclass public abstract class BaseEntity implements Buildable { @Id @GeneratedValue protected Long id; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public static abstract class BaseEntityBuilder<TYPE extends BaseEntity, BUILDER extends BaseEntityBuilder<TYPE, BUILDER>> extends AbstractBuildableBuilder<TYPE, BUILDER> { - BUILDER id(Long id) { + public BUILDER id(Long id) { buildable.setId(id); return builder; } } }
true
true
BUILDER id(Long id) { buildable.setId(id); return builder; }
public BUILDER id(Long id) { buildable.setId(id); return builder; }
diff --git a/svnkit/src/org/tmatesoft/svn/core/wc/SVNCopyClient.java b/svnkit/src/org/tmatesoft/svn/core/wc/SVNCopyClient.java index c8872d98a..9e113bf6c 100644 --- a/svnkit/src/org/tmatesoft/svn/core/wc/SVNCopyClient.java +++ b/svnkit/src/org/tmatesoft/svn/core/wc/SVNCopyClient.java @@ -1,1853 +1,1853 @@ /* * ==================================================================== * Copyright (c) 2004-2007 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.wc; import java.io.File; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNCommitInfo; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNDirEntry; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNMergeInfoInheritance; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNProperty; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNHashMap; import org.tmatesoft.svn.core.internal.util.SVNMergeInfoUtil; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.wc.ISVNCommitPathHandler; import org.tmatesoft.svn.core.internal.wc.SVNAdminUtil; import org.tmatesoft.svn.core.internal.wc.SVNCancellableOutputStream; import org.tmatesoft.svn.core.internal.wc.SVNCommitMediator; import org.tmatesoft.svn.core.internal.wc.SVNCommitUtil; import org.tmatesoft.svn.core.internal.wc.SVNCommitter; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNEventFactory; import org.tmatesoft.svn.core.internal.wc.SVNExternal; import org.tmatesoft.svn.core.internal.wc.SVNFileListUtil; import org.tmatesoft.svn.core.internal.wc.SVNFileType; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.internal.wc.SVNPropertiesManager; import org.tmatesoft.svn.core.internal.wc.SVNWCManager; import org.tmatesoft.svn.core.internal.wc.admin.SVNAdminArea; import org.tmatesoft.svn.core.internal.wc.admin.SVNEntry; import org.tmatesoft.svn.core.internal.wc.admin.SVNVersionedProperties; import org.tmatesoft.svn.core.internal.wc.admin.SVNWCAccess; import org.tmatesoft.svn.core.io.ISVNEditor; import org.tmatesoft.svn.core.io.SVNLocationEntry; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; /** * The <b>SVNCopyClient</b> provides methods to perform any kinds of copying and moving that SVN * supports - operating on both Working Copies (WC) and URLs. * * <p> * Copy operations allow a user to copy versioned files and directories with all their * previous history in several ways. * * <p> * Supported copy operations are: * <ul> * <li> Working Copy to Working Copy (WC-to-WC) copying - this operation copies the source * Working Copy item to the destination one and schedules the source copy for addition with history. * <li> Working Copy to URL (WC-to-URL) copying - this operation commits to the repository (exactly * to that repository location that is specified by URL) a copy of the Working Copy item. * <li> URL to Working Copy (URL-to-WC) copying - this operation will copy the source item from * the repository to the Working Copy item and schedule the source copy for addition with history. * <li> URL to URL (URL-to-URL) copying - this is a fully repository-side operation, it commits * a copy of the source item to a specified repository location (within the same repository, of * course). * </ul> * * <p> * Besides just copying <b>SVNCopyClient</b> also is able to move a versioned item - that is * first making a copy of the source item and then scheduling the source item for deletion * when operating on a Working Copy, or right committing the deletion of the source item when * operating immediately on the repository. * * <p> * Supported move operations are: * <ul> * <li> Working Copy to Working Copy (WC-to-WC) moving - this operation copies the source * Working Copy item to the destination one and schedules the source item for deletion. * <li> URL to URL (URL-to-URL) moving - this is a fully repository-side operation, it commits * a copy of the source item to a specified repository location and deletes the source item. * </ul> * * <p> * Overloaded <b>doCopy()</b> methods of <b>SVNCopyClient</b> are similar to * <code>'svn copy'</code> and <code>'svn move'</code> commands of the SVN command line client. * * @version 1.1.1 * @author TMate Software Ltd. * @see <a target="_top" href="http://svnkit.com/kb/examples/">Examples</a> * */ public class SVNCopyClient extends SVNBasicClient { private ISVNCommitHandler myCommitHandler; private ISVNCommitParameters myCommitParameters; private ISVNExternalsHandler myExternalsHandler; /** * Constructs and initializes an <b>SVNCopyClient</b> object * with the specified run-time configuration and authentication * drivers. * * <p> * If <code>options</code> is <span class="javakeyword">null</span>, * then this <b>SVNCopyClient</b> will be using a default run-time * configuration driver which takes client-side settings from the * default SVN's run-time configuration area but is not able to * change those settings (read more on {@link ISVNOptions} and {@link SVNWCUtil}). * * <p> * If <code>authManager</code> is <span class="javakeyword">null</span>, * then this <b>SVNCopyClient</b> will be using a default authentication * and network layers driver (see {@link SVNWCUtil#createDefaultAuthenticationManager()}) * which uses server-side settings and auth storage from the * default SVN's run-time configuration area (or system properties * if that area is not found). * * @param authManager an authentication and network layers driver * @param options a run-time configuration options driver */ public SVNCopyClient(ISVNAuthenticationManager authManager, ISVNOptions options) { super(authManager, options); } public SVNCopyClient(ISVNRepositoryPool repositoryPool, ISVNOptions options) { super(repositoryPool, options); } /** * Sets an implementation of <b>ISVNCommitHandler</b> to * the commit handler that will be used during commit operations to handle * commit log messages. The handler will receive a clien's log message and items * (represented as <b>SVNCommitItem</b> objects) that will be * committed. Depending on implementor's aims the initial log message can * be modified (or something else) and returned back. * * <p> * If using <b>SVNCopyClient</b> without specifying any * commit handler then a default one will be used - {@link DefaultSVNCommitHandler}. * * @param handler an implementor's handler that will be used to handle * commit log messages * @see #getCommitHandler() * @see SVNCommitItem */ public void setCommitHandler(ISVNCommitHandler handler) { myCommitHandler = handler; } /** * Returns the specified commit handler (if set) being in use or a default one * (<b>DefaultSVNCommitHandler</b>) if no special * implementations of <b>ISVNCommitHandler</b> were * previousely provided. * * @return the commit handler being in use or a default one * @see #setCommitHandler(ISVNCommitHandler) * @see DefaultSVNCommitHandler */ public ISVNCommitHandler getCommitHandler() { if (myCommitHandler == null) { myCommitHandler = new DefaultSVNCommitHandler(); } return myCommitHandler; } /** * Sets commit parameters to use. * * <p> * When no parameters are set {@link DefaultSVNCommitParameters default} * ones are used. * * @param parameters commit parameters * @see #getCommitParameters() */ public void setCommitParameters(ISVNCommitParameters parameters) { myCommitParameters = parameters; } /** * Returns commit parameters. * * <p> * If no user parameters were previously specified, once creates and * returns {@link DefaultSVNCommitParameters default} ones. * * @return commit parameters * @see #setCommitParameters(ISVNCommitParameters) */ public ISVNCommitParameters getCommitParameters() { if (myCommitParameters == null) { myCommitParameters = new DefaultSVNCommitParameters(); } return myCommitParameters; } public void setExternalsHandler(ISVNExternalsHandler externalsHandler) { myExternalsHandler = externalsHandler; } public ISVNExternalsHandler getExternalsHandler() { if (myExternalsHandler == null) { myExternalsHandler = ISVNExternalsHandler.DEFAULT; } return myExternalsHandler; } public void doCopy(SVNCopySource[] sources, File dst, boolean isMove, boolean makeParents, boolean failWhenDstExists) throws SVNException { if (sources.length > 1 && failWhenDstExists) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_MULTIPLE_SOURCES_DISALLOWED); SVNErrorManager.error(err, SVNLogType.DEFAULT); } sources = expandCopySources(sources); if (sources.length == 0) { return; } try { setupCopy(sources, new SVNPath(dst.getAbsolutePath()), isMove, makeParents, null, null); } catch (SVNException e) { SVNErrorCode err = e.getErrorMessage().getErrorCode(); if (!failWhenDstExists && sources.length == 1 && (err == SVNErrorCode.ENTRY_EXISTS || err == SVNErrorCode.FS_ALREADY_EXISTS)) { SVNCopySource source = sources[0]; String baseName = source.getName(); if (source.isURL()) { baseName = SVNEncodingUtil.uriDecode(baseName); } try { setupCopy(sources, new SVNPath(new File(dst, baseName).getAbsolutePath()), isMove, makeParents, null, null); } catch (SVNException second) { throw second; } return; } throw e; } } public SVNCommitInfo doCopy(SVNCopySource[] sources, SVNURL dst, boolean isMove, boolean makeParents, boolean failWhenDstExists, String commitMessage, SVNProperties revisionProperties) throws SVNException { if (sources.length > 1 && failWhenDstExists) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_MULTIPLE_SOURCES_DISALLOWED); SVNErrorManager.error(err, SVNLogType.DEFAULT); } sources = expandCopySources(sources); if (sources.length == 0) { return SVNCommitInfo.NULL; } try { return setupCopy(sources, new SVNPath(dst.toString()), isMove, makeParents, commitMessage, revisionProperties); } catch (SVNException e) { SVNErrorCode err = e.getErrorMessage().getErrorCode(); if (!failWhenDstExists && sources.length == 1 && (err == SVNErrorCode.ENTRY_EXISTS || err == SVNErrorCode.FS_ALREADY_EXISTS)) { SVNCopySource source = sources[0]; String baseName = source.getName(); if (!source.isURL()) { baseName = SVNEncodingUtil.uriEncode(baseName); } try { return setupCopy(sources, new SVNPath(dst.appendPath(baseName, true).toString()), isMove, makeParents, commitMessage, revisionProperties); } catch (SVNException second) { throw second; } } throw e; } } /** * Converts a disjoint wc to a copied one. */ public void doCopy(File nestedWC) throws SVNException { copyDisjointWCToWC(nestedWC); } private SVNCopySource[] expandCopySources(SVNCopySource[] sources) throws SVNException { Collection expanded = new ArrayList(sources.length); for (int i = 0; i < sources.length; i++) { SVNCopySource source = sources[i]; if (source.isCopyContents() && source.isURL()) { // get children at revision. SVNRevision pegRevision = source.getPegRevision(); if (!pegRevision.isValid()) { pegRevision = SVNRevision.HEAD; } SVNRevision startRevision = source.getRevision(); if (!startRevision.isValid()) { startRevision = pegRevision; } SVNRepositoryLocation[] locations = getLocations(source.getURL(), null, null, pegRevision, startRevision, SVNRevision.UNDEFINED); SVNRepository repository = createRepository(locations[0].getURL(), null, null, true); long revision = locations[0].getRevisionNumber(); Collection entries = new ArrayList(); repository.getDir("", revision, null, 0, entries); for (Iterator ents = entries.iterator(); ents.hasNext();) { SVNDirEntry entry = (SVNDirEntry) ents.next(); // add new copy source. expanded.add(new SVNCopySource(SVNRevision.UNDEFINED, source.getRevision(), entry.getURL())); } } else { expanded.add(source); } } return (SVNCopySource[]) expanded.toArray(new SVNCopySource[expanded.size()]); } private String getUUIDFromPath(SVNWCAccess wcAccess, File path) throws SVNException { SVNEntry entry = wcAccess.getVersionedEntry(path, true); String uuid = null; if (entry.getUUID() != null) { uuid = entry.getUUID(); } else if (entry.getURL() != null) { SVNRepository repos = createRepository(entry.getSVNURL(), null, null, false); try { uuid = repos.getRepositoryUUID(true); } finally { repos.closeSession(); } } else { if (wcAccess.isWCRoot(path)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_MISSING_URL, "''{0}'' has no URL", path); SVNErrorManager.error(err, SVNLogType.WC); } uuid = getUUIDFromPath(wcAccess, path.getParentFile()); } return uuid; } private static void postCopyCleanup(SVNAdminArea dir) throws SVNException { SVNPropertiesManager.deleteWCProperties(dir, null, false); SVNFileUtil.setHidden(dir.getAdminDirectory(), true); Map attributes = new SVNHashMap(); boolean save = false; for(Iterator entries = dir.entries(true); entries.hasNext();) { SVNEntry entry = (SVNEntry) entries.next(); boolean deleted = entry.isDeleted(); SVNNodeKind kind = entry.getKind(); boolean force = false; if (entry.isDeleted()) { force = true; attributes.put(SVNProperty.SCHEDULE, SVNProperty.SCHEDULE_DELETE); attributes.put(SVNProperty.DELETED, null); if (entry.isDirectory()) { attributes.put(SVNProperty.KIND, SVNProperty.KIND_FILE); } } if (entry.getLockToken() != null) { force = true; attributes.put(SVNProperty.LOCK_TOKEN, null); attributes.put(SVNProperty.LOCK_OWNER, null); attributes.put(SVNProperty.LOCK_CREATION_DATE, null); } if (force) { dir.modifyEntry(entry.getName(), attributes, false, force); save = true; } if (!deleted && kind == SVNNodeKind.DIR && !dir.getThisDirName().equals(entry.getName())) { SVNAdminArea childDir = dir.getWCAccess().retrieve(dir.getFile(entry.getName())); postCopyCleanup(childDir); } attributes.clear(); } if (save) { dir.saveEntries(false); } } private SVNCommitInfo setupCopy(SVNCopySource[] sources, SVNPath dst, boolean isMove, boolean makeParents, String message, SVNProperties revprops) throws SVNException { List pairs = new ArrayList(sources.length); for (int i = 0; i < sources.length; i++) { SVNCopySource source = sources[i]; if (source.isURL() && (source.getPegRevision() == SVNRevision.BASE || source.getPegRevision() == SVNRevision.COMMITTED || source.getPegRevision() == SVNRevision.PREVIOUS)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_BAD_REVISION, "Revision type requires a working copy path, not URL"); SVNErrorManager.error(err, SVNLogType.WC); } } boolean srcIsURL = sources[0].isURL(); boolean dstIsURL = dst.isURL(); if (sources.length > 1) { for (int i = 0; i < sources.length; i++) { SVNCopySource source = sources[i]; CopyPair pair = new CopyPair(); pair.mySource = source.isURL() ? source.getURL().toString() : source.getFile().getAbsolutePath().replace(File.separatorChar, '/'); pair.setSourceRevisions(source.getPegRevision(), source.getRevision()); if (SVNPathUtil.isURL(pair.mySource) != srcIsURL) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Cannot mix repository and working copy sources"); SVNErrorManager.error(err, SVNLogType.WC); } String baseName = source.getName(); if (srcIsURL && !dstIsURL) { baseName = SVNEncodingUtil.uriDecode(baseName); } pair.myDst = dstIsURL ? dst.getURL().appendPath(baseName, true).toString() : new File(dst.getFile(), baseName).getAbsolutePath().replace(File.separatorChar, '/'); pairs.add(pair); } } else { SVNCopySource source = sources[0]; CopyPair pair = new CopyPair(); pair.mySource = source.isURL() ? source.getURL().toString() : source.getFile().getAbsolutePath().replace(File.separatorChar, '/'); pair.setSourceRevisions(source.getPegRevision(), source.getRevision()); pair.myDst = dstIsURL ? dst.getURL().toString() : dst.getFile().getAbsolutePath().replace(File.separatorChar, '/'); pairs.add(pair); } if (!srcIsURL && !dstIsURL) { for (Iterator ps = pairs.iterator(); ps.hasNext();) { CopyPair pair = (CopyPair) ps.next(); String srcPath = pair.mySource; String dstPath = pair.myDst; if (SVNPathUtil.isAncestor(srcPath, dstPath)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Cannot copy path ''{0}'' into its own child ''{1}", new Object[] { srcPath, dstPath }); SVNErrorManager.error(err, SVNLogType.WC); } } } if (isMove) { if (srcIsURL == dstIsURL) { for (Iterator ps = pairs.iterator(); ps.hasNext();) { CopyPair pair = (CopyPair) ps.next(); File srcPath = new File(pair.mySource); File dstPath = new File(pair.myDst); if (srcPath.equals(dstPath)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Cannot move path ''{0}'' into itself", srcPath); SVNErrorManager.error(err, SVNLogType.WC); } } } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Moves between the working copy and the repository are not supported"); SVNErrorManager.error(err, SVNLogType.WC); } } else { if (!srcIsURL) { boolean needReposRevision = false; boolean needReposPegRevision = false; for (Iterator ps = pairs.iterator(); ps.hasNext();) { CopyPair pair = (CopyPair) ps.next(); if (pair.mySourceRevision != SVNRevision.UNDEFINED && pair.mySourceRevision != SVNRevision.WORKING) { needReposRevision = true; } if (pair.mySourcePegRevision != SVNRevision.UNDEFINED && pair.mySourcePegRevision != SVNRevision.WORKING) { needReposPegRevision = true; } if (needReposRevision || needReposPegRevision) { break; } } if (needReposRevision || needReposPegRevision) { for (Iterator ps = pairs.iterator(); ps.hasNext();) { CopyPair pair = (CopyPair) ps.next(); SVNWCAccess wcAccess = createWCAccess(); try { wcAccess.probeOpen(new File(pair.mySource), false, 0); SVNEntry entry = wcAccess.getEntry(new File(pair.mySource), false); SVNURL url = entry.isCopied() ? entry.getCopyFromSVNURL() : entry.getSVNURL(); if (url == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_MISSING_URL, "''{0}'' does not have a URL associated with it", new File(pair.mySource)); SVNErrorManager.error(err, SVNLogType.WC); } pair.mySource = url.toString(); if (!needReposPegRevision || pair.mySourcePegRevision == SVNRevision.BASE) { pair.mySourcePegRevision = entry.isCopied() ? SVNRevision.create(entry.getCopyFromRevision()) : SVNRevision.create(entry.getRevision()); } if (pair.mySourceRevision == SVNRevision.BASE) { pair.mySourceRevision = entry.isCopied() ? SVNRevision.create(entry.getCopyFromRevision()) : SVNRevision.create(entry.getRevision()); } } finally { wcAccess.close(); } } srcIsURL = true; } } } if (!srcIsURL && !dstIsURL) { copyWCToWC(pairs, isMove, makeParents); return SVNCommitInfo.NULL; } else if (!srcIsURL && dstIsURL) { //wc2url. return copyWCToRepos(pairs, makeParents, message, revprops); } else if (srcIsURL && !dstIsURL) { // url2wc. copyReposToWC(pairs, makeParents); return SVNCommitInfo.NULL; } else { return copyReposToRepos(pairs, makeParents, isMove, message, revprops); } } private SVNCommitInfo copyWCToRepos(List copyPairs, boolean makeParents, String message, SVNProperties revprops) throws SVNException { String topSrc = ((CopyPair) copyPairs.get(0)).mySource; for (int i = 1; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); topSrc = SVNPathUtil.getCommonPathAncestor(topSrc, pair.mySource); } SVNWCAccess wcAccess = createWCAccess(); SVNCommitInfo info = null; ISVNEditor commitEditor = null; Collection tmpFiles = null; try { SVNAdminArea adminArea = wcAccess.probeOpen(new File(topSrc), false, SVNWCAccess.INFINITE_DEPTH); wcAccess.setAnchor(adminArea.getRoot()); String topDstURL = ((CopyPair) copyPairs.get(0)).myDst; topDstURL = SVNPathUtil.removeTail(topDstURL); for (int i = 1; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); topDstURL = SVNPathUtil.getCommonPathAncestor(topDstURL, pair.myDst); } // should we use also wcAccess here? i do not think so. SVNRepository repos = createRepository(SVNURL.parseURIEncoded(topDstURL), adminArea.getRoot(), wcAccess, true); List newDirs = new ArrayList(); if (makeParents) { String rootURL = topDstURL; SVNNodeKind kind = repos.checkPath("", -1); while(kind == SVNNodeKind.NONE) { newDirs.add(rootURL); rootURL = SVNPathUtil.removeTail(rootURL); repos.setLocation(SVNURL.parseURIEncoded(rootURL), false); kind = repos.checkPath("", -1); } topDstURL = rootURL; } for (int i = 0; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); SVNEntry entry = wcAccess.getEntry(new File(pair.mySource), false); pair.mySourceRevisionNumber = entry.getRevision(); String dstRelativePath = SVNPathUtil.getPathAsChild(topDstURL, pair.myDst); dstRelativePath = SVNEncodingUtil.uriDecode(dstRelativePath); SVNNodeKind kind = repos.checkPath(dstRelativePath, -1); if (kind != SVNNodeKind.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.FS_ALREADY_EXISTS, "Path ''{0}'' already exists", SVNURL.parseURIEncoded(pair.myDst)); SVNErrorManager.error(err, SVNLogType.WC); } } // create commit items list to fetch log messages. List commitItems = new ArrayList(copyPairs.size()); if (makeParents) { for (int i = 0; i < newDirs.size(); i++) { String newDirURL = (String) newDirs.get(i); SVNURL url = SVNURL.parseURIEncoded(newDirURL); SVNCommitItem item = new SVNCommitItem(null, url, null, SVNNodeKind.NONE, null, null, true, false, false, false, false, false); commitItems.add(item); } } for (int i = 0; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); SVNURL url = SVNURL.parseURIEncoded(pair.myDst); SVNCommitItem item = new SVNCommitItem(null, url, null, SVNNodeKind.NONE, null, null, true, false, false, false, false, false); commitItems.add(item); } SVNCommitItem[] commitables = (SVNCommitItem[]) commitItems.toArray(new SVNCommitItem[commitItems.size()]); message = getCommitHandler().getCommitMessage(message, commitables); if (message == null) { return SVNCommitInfo.NULL; } revprops = getCommitHandler().getRevisionProperties(message, commitables, revprops == null ? new SVNProperties() : revprops); if (revprops == null) { return SVNCommitInfo.NULL; } Map allCommitables = new TreeMap(SVNCommitUtil.FILE_COMPARATOR); repos.setLocation(repos.getRepositoryRoot(true), false); Map pathsToExternalsProps = new SVNHashMap(); for (int i = 0; i < copyPairs.size(); i++) { CopyPair source = (CopyPair) copyPairs.get(i); File srcFile = new File(source.mySource); SVNEntry entry = wcAccess.getVersionedEntry(srcFile, false); SVNAdminArea dirArea = null; if (entry.isDirectory()) { dirArea = wcAccess.retrieve(srcFile); } else { dirArea = wcAccess.retrieve(srcFile.getParentFile()); } pathsToExternalsProps.clear(); SVNCommitUtil.harvestCommitables(allCommitables, dirArea, srcFile, null, entry, source.myDst, entry.getURL(), true, false, false, null, SVNDepth.INFINITY, false, null, getCommitParameters(), pathsToExternalsProps); SVNCommitItem item = (SVNCommitItem) allCommitables.get(srcFile); SVNURL srcURL = entry.getSVNURL(); Map mergeInfo = calculateTargetMergeInfo(srcFile, wcAccess, srcURL, source.mySourceRevisionNumber, repos, false); Map wcMergeInfo = SVNPropertiesManager.parseMergeInfo(srcFile, entry, false); if (wcMergeInfo != null && mergeInfo != null) { mergeInfo = SVNMergeInfoUtil.mergeMergeInfos(mergeInfo, wcMergeInfo); } else if (mergeInfo == null) { mergeInfo = wcMergeInfo; } if (mergeInfo != null) { String mergeInfoString = SVNMergeInfoUtil.formatMergeInfoToString(mergeInfo); item.setProperty(SVNProperty.MERGE_INFO, SVNPropertyValue.create(mergeInfoString)); } if (!pathsToExternalsProps.isEmpty()) { LinkedList newExternals = new LinkedList(); for (Iterator pathsIter = pathsToExternalsProps.keySet().iterator(); pathsIter.hasNext();) { File localPath = (File) pathsIter.next(); String externalsPropString = (String) pathsToExternalsProps.get(localPath); SVNExternal[] externals = SVNExternal.parseExternals(localPath.getAbsolutePath(), externalsPropString); boolean introduceVirtualExternalChange = false; newExternals.clear(); for (int k = 0; k < externals.length; k++) { File externalWC = new File(localPath, externals[k].getPath()); SVNEntry externalEntry = null; try { wcAccess.open(externalWC, false, 0); externalEntry = wcAccess.getVersionedEntry(externalWC, false); } catch (SVNException svne) { if (svne instanceof SVNCancelException) { throw svne; } } finally { wcAccess.closeAdminArea(externalWC); } SVNRevision externalsWCRevision = SVNRevision.UNDEFINED; if (externalEntry != null) { externalsWCRevision = SVNRevision.create(externalEntry.getRevision()); } SVNRevision[] revs = getExternalsHandler().handleExternal(externalWC, externals[k].resolveURL(repos.getRepositoryRoot(true), externalEntry.getSVNURL()), externals[k].getRevision(), externals[k].getPegRevision(), externals[k].getRawValue(), externalsWCRevision); if (revs != null && revs[0] == externals[k].getRevision()) { newExternals.add(externals[k].getRawValue()); } else if (revs != null) { SVNExternal newExternal = new SVNExternal(externals[k].getPath(), externals[k].getUnresolvedUrl(), revs[1], revs[0], true, externals[k].isPegRevisionExplicit(), externals[k].isNewFormat()); newExternals.add(newExternal.toString()); if (!introduceVirtualExternalChange) { introduceVirtualExternalChange = true; } } } if (introduceVirtualExternalChange) { String newExternalsProp = ""; for (Iterator externalsIter = newExternals.iterator(); externalsIter.hasNext();) { String external = (String) externalsIter.next(); newExternalsProp += external + '\n'; } SVNCommitItem itemWithExternalsChanges = (SVNCommitItem) allCommitables.get(localPath); if (itemWithExternalsChanges != null) { itemWithExternalsChanges.setProperty(SVNProperty.EXTERNALS, SVNPropertyValue.create(newExternalsProp)); } else { SVNAdminArea childArea = wcAccess.retrieve(localPath); String relativePath = childArea.getRelativePath(dirArea); String itemURL = SVNPathUtil.append(source.myDst, SVNEncodingUtil.uriEncode(relativePath)); itemWithExternalsChanges = new SVNCommitItem(localPath, SVNURL.parseURIEncoded(itemURL), null, SVNNodeKind.DIR, null, null, false, false, true, false, false, false); itemWithExternalsChanges.setProperty(SVNProperty.EXTERNALS, SVNPropertyValue.create(newExternalsProp)); allCommitables.put(localPath, itemWithExternalsChanges); } } } } } commitItems = new ArrayList(allCommitables.values()); // add parents to commits hash? if (makeParents) { for (int i = 0; i < newDirs.size(); i++) { String newDirURL = (String) newDirs.get(i); SVNURL url = SVNURL.parseURIEncoded(newDirURL); SVNCommitItem item = new SVNCommitItem(null, url, null, SVNNodeKind.NONE, null, null, true, false, false, false, false, false); commitItems.add(item); } } commitables = (SVNCommitItem[]) commitItems.toArray(new SVNCommitItem[commitItems.size()]); for (int i = 0; i < commitables.length; i++) { commitables[i].setWCAccess(wcAccess); } - allCommitables.clear(); + allCommitables = new TreeMap(); SVNURL url = SVNCommitUtil.translateCommitables(commitables, allCommitables); repos = createRepository(url, null, null, true); SVNCommitMediator mediator = new SVNCommitMediator(allCommitables); tmpFiles = mediator.getTmpFiles(); message = SVNCommitClient.validateCommitMessage(message); SVNURL rootURL = repos.getRepositoryRoot(true); commitEditor = repos.getCommitEditor(message, null, true, revprops, mediator); info = SVNCommitter.commit(tmpFiles, allCommitables, rootURL.getPath(), commitEditor); commitEditor = null; } catch (SVNCancelException cancel) { throw cancel; } catch (SVNException e) { // wrap error message. SVNErrorMessage err = e.getErrorMessage().wrap("Commit failed (details follow):"); SVNErrorManager.error(err, SVNLogType.WC); } finally { if (tmpFiles != null) { for (Iterator files = tmpFiles.iterator(); files.hasNext();) { File file = (File) files.next(); SVNFileUtil.deleteFile(file); } } if (commitEditor != null && info == null) { // should we hide this exception? try { commitEditor.abortEdit(); } catch (SVNException e) { SVNDebugLog.getDefaultLog().logFine(SVNLogType.WC, e); } } if (wcAccess != null) { wcAccess.close(); } } if (info != null && info.getNewRevision() >= 0) { dispatchEvent(SVNEventFactory.createSVNEvent(null, SVNNodeKind.NONE, null, info.getNewRevision(), SVNEventAction.COMMIT_COMPLETED, null, null, null), ISVNEventHandler.UNKNOWN); } return info != null ? info : SVNCommitInfo.NULL; } private SVNCommitInfo copyReposToRepos(List copyPairs, boolean makeParents, boolean isMove, String message, SVNProperties revprops) throws SVNException { List pathInfos = new ArrayList(); Map pathsMap = new SVNHashMap(); for (int i = 0; i < copyPairs.size(); i++) { CopyPathInfo info = new CopyPathInfo(); pathInfos.add(info); } String topURL = ((CopyPair) copyPairs.get(0)).mySource; String topDstURL = ((CopyPair) copyPairs.get(0)).myDst; for (int i = 1; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); topURL = SVNPathUtil.getCommonPathAncestor(topURL, pair.mySource); } if (copyPairs.size() == 1) { topURL = SVNPathUtil.getCommonPathAncestor(topURL, topDstURL); } else { topURL = SVNPathUtil.getCommonPathAncestor(topURL, SVNPathUtil.removeTail(topDstURL)); } try { SVNURL.parseURIEncoded(topURL); } catch (SVNException e) { topURL = null; } if (topURL == null) { SVNURL url1 = SVNURL.parseURIEncoded(((CopyPair) copyPairs.get(0)).mySource); SVNURL url2 = SVNURL.parseURIEncoded(((CopyPair) copyPairs.get(0)).myDst); SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Source and dest appear not to be in the same repository (src: ''{0}''; dst: ''{1}'')", new Object[] {url1, url2}); SVNErrorManager.error(err, SVNLogType.WC); } for (int i = 0; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); CopyPathInfo info = (CopyPathInfo) pathInfos.get(i); if (pair.mySource.equals(pair.myDst)) { info.isResurrection = true; if (topURL.equals(pair.mySource)) { topURL = SVNPathUtil.removeTail(topURL); } } } SVNRepository topRepos = createRepository(SVNURL.parseURIEncoded(topURL), null, null, true); List newDirs = new ArrayList(); if (makeParents) { CopyPair pair = (CopyPair) copyPairs.get(0); String relativeDir = SVNPathUtil.getPathAsChild(topURL, SVNPathUtil.removeTail(pair.myDst)); if (relativeDir != null) { relativeDir = SVNEncodingUtil.uriDecode(relativeDir); SVNNodeKind kind = topRepos.checkPath(relativeDir, -1); while(kind == SVNNodeKind.NONE) { newDirs.add(relativeDir); relativeDir = SVNPathUtil.removeTail(relativeDir); kind = topRepos.checkPath(relativeDir, -1); } } } String rootURL = topRepos.getRepositoryRoot(true).toString(); for (int i = 0; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); CopyPathInfo info = (CopyPathInfo) pathInfos.get(i); if (!pair.myDst.equals(rootURL) && SVNPathUtil.getPathAsChild(pair.myDst, pair.mySource) != null) { info.isResurrection = true; // TODO still looks like a bug. // if (SVNPathUtil.removeTail(pair.myDst).equals(topURL)) { topURL = SVNPathUtil.removeTail(topURL); // } } } topRepos.setLocation(SVNURL.parseURIEncoded(topURL), false); long latestRevision = topRepos.getLatestRevision(); for (int i = 0; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); CopyPathInfo info = (CopyPathInfo) pathInfos.get(i); pair.mySourceRevisionNumber = getRevisionNumber(pair.mySourceRevision, topRepos, null); info.mySourceRevisionNumber = pair.mySourceRevisionNumber; SVNRepositoryLocation[] locations = getLocations(SVNURL.parseURIEncoded(pair.mySource), null, topRepos, pair.mySourcePegRevision, pair.mySourceRevision, SVNRevision.UNDEFINED); pair.mySource = locations[0].getURL().toString(); String srcRelative = SVNPathUtil.getPathAsChild(topURL, pair.mySource); if (srcRelative != null) { srcRelative = SVNEncodingUtil.uriDecode(srcRelative); } else { srcRelative = ""; } String dstRelative = SVNPathUtil.getPathAsChild(topURL, pair.myDst); if (dstRelative != null) { dstRelative = SVNEncodingUtil.uriDecode(dstRelative); } else { dstRelative = ""; } if ("".equals(srcRelative) && isMove) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Cannot move URL ''{0}'' into itself", SVNURL.parseURIEncoded(pair.mySource)); SVNErrorManager.error(err, SVNLogType.WC); } info.mySourceKind = topRepos.checkPath(srcRelative, pair.mySourceRevisionNumber); if (info.mySourceKind == SVNNodeKind.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.FS_NOT_FOUND, "Path ''{0}'' does not exist in revision {1}", new Object[] {SVNURL.parseURIEncoded(pair.mySource), new Long(pair.mySourceRevisionNumber)}); SVNErrorManager.error(err, SVNLogType.WC); } SVNNodeKind dstKind = topRepos.checkPath(dstRelative, latestRevision); if (dstKind != SVNNodeKind.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.FS_ALREADY_EXISTS, "Path ''{0}'' already exists", dstRelative); SVNErrorManager.error(err, SVNLogType.WC); } info.mySource = pair.mySource; info.mySourcePath = srcRelative; info.myDstPath = dstRelative; } List paths = new ArrayList(copyPairs.size() * 2); List commitItems = new ArrayList(copyPairs.size() * 2); if (makeParents) { for (Iterator newDirsIter = newDirs.iterator(); newDirsIter.hasNext();) { String dirPath = (String) newDirsIter.next(); SVNURL itemURL = SVNURL.parseURIEncoded(SVNPathUtil.append(topURL, dirPath)); SVNCommitItem item = new SVNCommitItem(null, itemURL, null, SVNNodeKind.NONE, null, null, true, false, false, false, false, false); commitItems.add(item); } } for (Iterator infos = pathInfos.iterator(); infos.hasNext();) { CopyPathInfo info = (CopyPathInfo) infos.next(); SVNURL itemURL = SVNURL.parseURIEncoded(SVNPathUtil.append(topURL, info.myDstPath)); SVNCommitItem item = new SVNCommitItem(null, itemURL, null, SVNNodeKind.NONE, null, null, true, false, false, false, false, false); commitItems.add(item); pathsMap.put(info.myDstPath, info); if (isMove && !info.isResurrection) { itemURL = SVNURL.parseURIEncoded(SVNPathUtil.append(topURL, info.mySourcePath)); item = new SVNCommitItem(null, itemURL, null, SVNNodeKind.NONE, null, null, false, true, false, false, false, false); commitItems.add(item); pathsMap.put(info.mySourcePath, info); } } if (makeParents) { for (Iterator newDirsIter = newDirs.iterator(); newDirsIter.hasNext();) { String dirPath = (String) newDirsIter.next(); CopyPathInfo info = new CopyPathInfo(); info.myDstPath = dirPath; info.isDirAdded = true; paths.add(info.myDstPath); pathsMap.put(dirPath, info); } } for (Iterator infos = pathInfos.iterator(); infos.hasNext();) { CopyPathInfo info = (CopyPathInfo) infos.next(); Map mergeInfo = calculateTargetMergeInfo(null, null, SVNURL.parseURIEncoded(info.mySource), info.mySourceRevisionNumber, topRepos, false); if (mergeInfo != null) { info.myMergeInfoProp = SVNMergeInfoUtil.formatMergeInfoToString(mergeInfo); } paths.add(info.myDstPath); if (isMove && !info.isResurrection) { paths.add(info.mySourcePath); } } SVNCommitItem[] commitables = (SVNCommitItem[]) commitItems.toArray(new SVNCommitItem[commitItems.size()]); message = getCommitHandler().getCommitMessage(message, commitables); if (message == null) { return SVNCommitInfo.NULL; } message = SVNCommitClient.validateCommitMessage(message); revprops = getCommitHandler().getRevisionProperties(message, commitables, revprops == null ? new SVNProperties() : revprops); if (revprops == null) { return SVNCommitInfo.NULL; } // now do real commit. ISVNEditor commitEditor = topRepos.getCommitEditor(message, null, true, revprops, null); ISVNCommitPathHandler committer = new CopyCommitPathHandler(pathsMap, isMove); SVNCommitInfo result = null; try { SVNCommitUtil.driveCommitEditor(committer, paths, commitEditor, latestRevision); result = commitEditor.closeEdit(); } catch (SVNCancelException cancel) { throw cancel; } catch (SVNException e) { SVNErrorMessage err = e.getErrorMessage().wrap("Commit failed (details follow):"); SVNErrorManager.error(err, SVNLogType.DEFAULT); } finally { if (commitEditor != null && result == null) { try { commitEditor.abortEdit(); } catch (SVNException e) { SVNDebugLog.getDefaultLog().logFine(SVNLogType.WC, e); } } } if (result != null && result.getNewRevision() >= 0) { dispatchEvent(SVNEventFactory.createSVNEvent(null, SVNNodeKind.NONE, null, result.getNewRevision(), SVNEventAction.COMMIT_COMPLETED, null, null, null), ISVNEventHandler.UNKNOWN); } return result != null ? result : SVNCommitInfo.NULL; } private void copyReposToWC(List copyPairs, boolean makeParents) throws SVNException { for (Iterator pairs = copyPairs.iterator(); pairs.hasNext();) { CopyPair pair = (CopyPair) pairs.next(); SVNRepositoryLocation[] locations = getLocations(SVNURL.parseURIEncoded(pair.mySource), null, null, pair.mySourcePegRevision, pair.mySourceRevision, SVNRevision.UNDEFINED); // new String actualURL = locations[0].getURL().toString(); String originalSource = pair.mySource; pair.mySource = actualURL; pair.myOriginalSource = originalSource; } // get src and dst ancestors. String topDst = ((CopyPair) copyPairs.get(0)).myDst; if (copyPairs.size() > 1) { topDst = SVNPathUtil.removeTail(topDst); } String topSrc = ((CopyPair) copyPairs.get(0)).mySource; for(int i = 1; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); topSrc = SVNPathUtil.getCommonPathAncestor(topSrc, pair.mySource); } if (copyPairs.size() == 1) { topSrc = SVNPathUtil.removeTail(topSrc); } SVNRepository topSrcRepos = createRepository(SVNURL.parseURIEncoded(topSrc), null, null, false); try { for (Iterator pairs = copyPairs.iterator(); pairs.hasNext();) { CopyPair pair = (CopyPair) pairs.next(); pair.mySourceRevisionNumber = getRevisionNumber(pair.mySourceRevision, topSrcRepos, null); } String reposPath = topSrcRepos.getLocation().toString(); for (Iterator pairs = copyPairs.iterator(); pairs.hasNext();) { CopyPair pair = (CopyPair) pairs.next(); String relativePath = SVNPathUtil.getPathAsChild(reposPath, pair.mySource); relativePath = SVNEncodingUtil.uriDecode(relativePath); SVNNodeKind kind = topSrcRepos.checkPath(relativePath, pair.mySourceRevisionNumber); if (kind == SVNNodeKind.NONE) { SVNErrorMessage err = null; if (pair.mySourceRevisionNumber >= 0) { err = SVNErrorMessage.create(SVNErrorCode.FS_NOT_FOUND, "Path ''{0}'' not found in revision {1}", new Object[] {SVNURL.parseURIEncoded(pair.mySource), new Long(pair.mySourceRevisionNumber)}); } else { err = SVNErrorMessage.create(SVNErrorCode.FS_NOT_FOUND, "Path ''{0}'' not found in head revision", SVNURL.parseURIEncoded(pair.mySource)); } SVNErrorManager.error(err, SVNLogType.WC); } pair.mySourceKind = kind; SVNFileType dstType = SVNFileType.getType(new File(pair.myDst)); if (dstType != SVNFileType.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_EXISTS, "Path ''{0}'' already exists", new File(pair.myDst)); SVNErrorManager.error(err, SVNLogType.WC); } String dstParent = SVNPathUtil.removeTail(pair.myDst); SVNFileType dstParentFileType = SVNFileType.getType(new File(dstParent)); if (makeParents && dstParentFileType == SVNFileType.NONE) { // create parents. addLocalParents(new File(dstParent), getEventDispatcher()); } else if (dstParentFileType != SVNFileType.DIRECTORY) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_DIRECTORY, "Path ''{0}'' is not a directory", dstParent); SVNErrorManager.error(err, SVNLogType.WC); } } SVNWCAccess dstAccess = createWCAccess(); try { dstAccess.probeOpen(new File(topDst), true, 0); for (Iterator pairs = copyPairs.iterator(); pairs.hasNext();) { CopyPair pair = (CopyPair) pairs.next(); SVNEntry dstEntry = dstAccess.getEntry(new File(pair.myDst), false); if (dstEntry != null && !dstEntry.isDirectory() && !dstEntry.isScheduledForDeletion()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_OBSTRUCTED_UPDATE, "Entry for ''{0}'' exists (though the working file is missing)", new File(pair.myDst)); SVNErrorManager.error(err, SVNLogType.WC); } } String srcUUID = null; String dstUUID = null; try { srcUUID = topSrcRepos.getRepositoryUUID(true); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() != SVNErrorCode.RA_NO_REPOS_UUID) { throw e; } } String dstParent = topDst; if (copyPairs.size() == 1) { dstParent = SVNPathUtil.removeTail(topDst); } try { dstUUID = getUUIDFromPath(dstAccess, new File(dstParent)); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() != SVNErrorCode.RA_NO_REPOS_UUID) { throw e; } } boolean sameRepos = false; if (srcUUID != null) { sameRepos = srcUUID.equals(dstUUID); } for (Iterator pairs = copyPairs.iterator(); pairs.hasNext();) { CopyPair pair = (CopyPair) pairs.next(); copyReposToWC(pair, sameRepos, topSrcRepos, dstAccess); } } finally { dstAccess.close(); } } finally { topSrcRepos.closeSession(); } } private void copyReposToWC(CopyPair pair, boolean sameRepositories, SVNRepository topSrcRepos, SVNWCAccess dstAccess) throws SVNException { long srcRevNum = pair.mySourceRevisionNumber; if (pair.mySourceKind == SVNNodeKind.DIR) { // do checkout String srcURL = pair.myOriginalSource; SVNURL url = SVNURL.parseURIEncoded(srcURL); SVNUpdateClient updateClient = new SVNUpdateClient(getRepositoryPool(), getOptions()); updateClient.setEventHandler(getEventDispatcher()); File dstFile = new File(pair.myDst); SVNRevision srcRevision = pair.mySourceRevision; SVNRevision srcPegRevision = pair.mySourcePegRevision; updateClient.doCheckout(url, dstFile, srcPegRevision, srcRevision, SVNDepth.INFINITY, false); if (sameRepositories) { url = SVNURL.parseURIEncoded(pair.mySource); SVNAdminArea dstArea = dstAccess.open(dstFile, true, SVNWCAccess.INFINITE_DEPTH); SVNEntry dstRootEntry = dstArea.getEntry(dstArea.getThisDirName(), false); if (srcRevision == SVNRevision.HEAD) { srcRevNum = dstRootEntry.getRevision(); } SVNAdminArea dir = dstAccess.getAdminArea(dstFile.getParentFile()); SVNWCManager.add(dstFile, dir, url, srcRevNum); Map srcMergeInfo = calculateTargetMergeInfo(null, null, url, srcRevNum, topSrcRepos, false); extendWCMergeInfo(dstFile, dstRootEntry, srcMergeInfo, dstAccess); } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Source URL ''{0}'' is from foreign repository; leaving it as a disjoint WC", url); SVNErrorManager.error(err, SVNLogType.WC); } } else if (pair.mySourceKind == SVNNodeKind.FILE) { String srcURL = pair.mySource; SVNURL url = SVNURL.parseURIEncoded(srcURL); File dst = new File(pair.myDst); SVNAdminArea dir = dstAccess.getAdminArea(dst.getParentFile()); File tmpFile = SVNAdminUtil.createTmpFile(dir); String path = getPathRelativeToRoot(null, url, null, null, topSrcRepos); SVNProperties props = new SVNProperties(); OutputStream os = null; long revision = -1; try { os = SVNFileUtil.openFileForWriting(tmpFile); revision = topSrcRepos.getFile(path, srcRevNum, props, new SVNCancellableOutputStream(os, this)); } finally { SVNFileUtil.closeFile(os); } if (srcRevNum < 0) { srcRevNum = revision; } SVNWCManager.addRepositoryFile(dir, dst.getName(), null, tmpFile, props, null, sameRepositories ? pair.mySource : null, sameRepositories ? srcRevNum : -1); SVNEntry entry = dstAccess.getEntry(dst, false); Map mergeInfo = calculateTargetMergeInfo(null, null, url, srcRevNum, topSrcRepos, false); extendWCMergeInfo(dst, entry, mergeInfo, dstAccess); SVNEvent event = SVNEventFactory.createSVNEvent(dst, SVNNodeKind.FILE, null, SVNRepository.INVALID_REVISION, SVNEventAction.ADD, null, null, null); dstAccess.handleEvent(event); sleepForTimeStamp(); } } private void copyWCToWC(List copyPairs, boolean isMove, boolean makeParents) throws SVNException { for (Iterator pairs = copyPairs.iterator(); pairs.hasNext();) { CopyPair pair = (CopyPair) pairs.next(); SVNFileType srcFileType = SVNFileType.getType(new File(pair.mySource)); if (srcFileType == SVNFileType.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Path ''{0}'' does not exist", new File(pair.mySource)); SVNErrorManager.error(err, SVNLogType.WC); } SVNFileType dstFileType = SVNFileType.getType(new File(pair.myDst)); if (dstFileType != SVNFileType.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_EXISTS, "Path ''{0}'' already exists", new File(pair.myDst)); SVNErrorManager.error(err, SVNLogType.WC); } File dstParent = new File(SVNPathUtil.removeTail(pair.myDst)); pair.myBaseName = SVNPathUtil.tail(pair.myDst); SVNFileType dstParentFileType = SVNFileType.getType(dstParent); if (makeParents && dstParentFileType == SVNFileType.NONE) { // create parents. addLocalParents(dstParent, getEventDispatcher()); } else if (dstParentFileType != SVNFileType.DIRECTORY) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_DIRECTORY, "Path ''{0}'' is not a directory", dstParent); SVNErrorManager.error(err, SVNLogType.WC); } } if (isMove) { moveWCToWC(copyPairs); } else { copyWCToWC(copyPairs); } } private void copyDisjointWCToWC(File nestedWC) throws SVNException { SVNFileType nestedWCType = SVNFileType.getType(nestedWC); if (nestedWCType != SVNFileType.DIRECTORY) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "This kind of copy can be run on a root of a disjoint wc directory only"); SVNErrorManager.error(err, SVNLogType.WC); } nestedWC = new File(nestedWC.getAbsolutePath().replace(File.separatorChar, '/')); File nestedWCParent = nestedWC.getParentFile(); if (nestedWCParent == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "{0} seems to be not a disjoint wc since it has no parent", nestedWC); SVNErrorManager.error(err, SVNLogType.WC); } SVNWCAccess parentWCAccess = createWCAccess(); SVNWCAccess nestedWCAccess = createWCAccess(); try { SVNAdminArea parentArea = parentWCAccess.open(nestedWCParent, true, 0); SVNEntry srcEntryInParent = parentWCAccess.getEntry(nestedWC, false); if (srcEntryInParent != null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_EXISTS, "Entry ''{0}'' already exists in parent directory", nestedWC.getName()); SVNErrorManager.error(err, SVNLogType.WC); } SVNAdminArea nestedArea = nestedWCAccess.open(nestedWC, false, SVNWCAccess.INFINITE_DEPTH); SVNEntry nestedWCThisEntry = nestedWCAccess.getVersionedEntry(nestedWC, false); SVNEntry parentThisEntry = parentWCAccess.getVersionedEntry(nestedWCParent, false); // uuids may be identical while it might be absolutely independent repositories. // subversion uses repos roots comparison for local copies, and uuids comparison for // operations involving ra access. so, I believe we should act similarly here. if (nestedWCThisEntry.getRepositoryRoot() != null && parentThisEntry.getRepositoryRoot() != null && !nestedWCThisEntry.getRepositoryRoot().equals(parentThisEntry.getRepositoryRoot())) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_INVALID_SCHEDULE, "Cannot copy to ''{0}'', as it is not from repository ''{1}''; it is from ''{2}''", new Object[] { nestedWCParent, nestedWCThisEntry.getRepositoryRootURL(), parentThisEntry.getRepositoryRootURL() }); SVNErrorManager.error(err, SVNLogType.WC); } if (parentThisEntry.isScheduledForDeletion()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_INVALID_SCHEDULE, "Cannot copy to ''{0}'', as it is scheduled for deletion", nestedWCParent); SVNErrorManager.error(err, SVNLogType.WC); } if (nestedWCThisEntry.isScheduledForDeletion()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_INVALID_SCHEDULE, "Cannot copy ''{0}'', as it is scheduled for deletion", nestedWC); SVNErrorManager.error(err, SVNLogType.WC); } SVNURL nestedWCReposRoot = getReposRoot(nestedWC, null, SVNRevision.WORKING, nestedArea, nestedWCAccess); String nestedWCPath = getPathRelativeToRoot(nestedWC, null, nestedWCReposRoot, nestedWCAccess, null); SVNURL parentReposRoot = getReposRoot(nestedWCParent, null, SVNRevision.WORKING, parentArea, parentWCAccess); String parentPath = getPathRelativeToRoot(nestedWCParent, null, parentReposRoot, parentWCAccess, null); if (SVNPathUtil.isAncestor(nestedWCPath, parentPath)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Cannot copy path ''{0}'' into its own child ''{1}", new Object[] { nestedWCPath, parentPath }); SVNErrorManager.error(err, SVNLogType.WC); } if ((nestedWCThisEntry.isScheduledForAddition() && !nestedWCThisEntry.isCopied()) || nestedWCThisEntry.getURL() == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_EXISTS, "Cannot copy or move ''{0}'': it is not in repository yet; " + "try committing first", nestedWC); SVNErrorManager.error(err, SVNLogType.WC); } boolean[] extend = { false }; Map mergeInfo = fetchMergeInfoForPropagation(nestedWC, extend, nestedWCAccess); copyDisjointDir(nestedWC, parentWCAccess, nestedWCParent); parentWCAccess.probeTry(nestedWC, true, SVNWCAccess.INFINITE_DEPTH); propagateMegeInfo(nestedWC, mergeInfo, extend, parentWCAccess); } finally { parentWCAccess.close(); nestedWCAccess.close(); sleepForTimeStamp(); } } private void copyDisjointDir(File nestedWC, SVNWCAccess parentAccess, File nestedWCParent) throws SVNException { SVNWCClient wcClient = new SVNWCClient((ISVNAuthenticationManager) null, null); wcClient.setEventHandler(getEventDispatcher()); wcClient.doCleanup(nestedWC); SVNWCAccess nestedWCAccess = createWCAccess(); SVNAdminArea dir = null; String copyFromURL = null; long copyFromRevision = -1; try { dir = nestedWCAccess.open(nestedWC, true, SVNWCAccess.INFINITE_DEPTH); SVNEntry nestedWCThisEntry = nestedWCAccess.getVersionedEntry(nestedWC, false); postCopyCleanup(dir); if (nestedWCThisEntry.isCopied()) { if (nestedWCThisEntry.getCopyFromURL() != null) { copyFromURL = nestedWCThisEntry.getCopyFromURL(); copyFromRevision = nestedWCThisEntry.getCopyFromRevision(); } Map attributes = new SVNHashMap(); attributes.put(SVNProperty.URL, copyFromURL); dir.modifyEntry(dir.getThisDirName(), attributes, true, false); } else { copyFromURL = nestedWCThisEntry.getURL(); copyFromRevision = nestedWCThisEntry.getRevision(); } } finally { nestedWCAccess.close(); } SVNWCManager.add(nestedWC, parentAccess.getAdminArea(nestedWCParent), SVNURL.parseURIEncoded(copyFromURL), copyFromRevision); } private void copyWCToWC(List pairs) throws SVNException { // find common ancestor for all dsts. String dstParentPath = null; for (Iterator ps = pairs.iterator(); ps.hasNext();) { CopyPair pair = (CopyPair) ps.next(); String dstPath = pair.myDst; if (dstParentPath == null) { dstParentPath = SVNPathUtil.removeTail(pair.myDst); } dstParentPath = SVNPathUtil.getCommonPathAncestor(dstParentPath, dstPath); } SVNWCAccess dstAccess = createWCAccess(); try { dstAccess.open(new File(dstParentPath), true, 0); for (Iterator ps = pairs.iterator(); ps.hasNext();) { CopyPair pair = (CopyPair) ps.next(); checkCancelled(); SVNWCAccess srcAccess = null; String srcParent = SVNPathUtil.removeTail(pair.mySource); SVNFileType srcType = SVNFileType.getType(new File(pair.mySource)); try { if (srcParent.equals(dstParentPath)) { if (srcType == SVNFileType.DIRECTORY) { srcAccess = createWCAccess(); srcAccess.open(new File(pair.mySource), false, -1); } else { srcAccess = dstAccess; } } else { try { srcAccess = createWCAccess(); srcAccess.open(new File(srcParent), false, srcType == SVNFileType.DIRECTORY ? -1 : 0); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_DIRECTORY) { srcAccess = null; } else { throw e; } } } // do real copy. File sourceFile = new File(pair.mySource); copyFiles(sourceFile, new File(dstParentPath), dstAccess, pair.myBaseName); if (srcAccess != null) { propagateMegeInfo(sourceFile, new File(pair.myDst), srcAccess, dstAccess); } } finally { if (srcAccess != null && srcAccess != dstAccess) { srcAccess.close(); } } } } finally { dstAccess.close(); sleepForTimeStamp(); } } private void moveWCToWC(List pairs) throws SVNException { for (Iterator ps = pairs.iterator(); ps.hasNext();) { CopyPair pair = (CopyPair) ps.next(); checkCancelled(); File srcParent = new File(SVNPathUtil.removeTail(pair.mySource)); File dstParent = new File(SVNPathUtil.removeTail(pair.myDst)); File sourceFile = new File(pair.mySource); SVNFileType srcType = SVNFileType.getType(sourceFile); SVNWCAccess srcAccess = createWCAccess(); SVNWCAccess dstAccess = null; try { srcAccess.open(srcParent, true, srcType == SVNFileType.DIRECTORY ? -1 : 0); if (srcParent.equals(dstParent)) { dstAccess = srcAccess; } else { String srcParentPath = srcParent.getAbsolutePath().replace(File.separatorChar, '/'); srcParentPath = SVNPathUtil.validateFilePath(srcParentPath); String dstParentPath = dstParent.getAbsolutePath().replace(File.separatorChar, '/'); dstParentPath = SVNPathUtil.validateFilePath(dstParentPath); if (srcType == SVNFileType.DIRECTORY && SVNPathUtil.isAncestor(srcParentPath, dstParentPath)) { dstAccess = srcAccess; } else { dstAccess = createWCAccess(); dstAccess.open(dstParent, true, 0); } } copyFiles(sourceFile, dstParent, dstAccess, pair.myBaseName); propagateMegeInfo(sourceFile, new File(pair.myDst), srcAccess, dstAccess); // delete src. SVNWCManager.delete(srcAccess, srcAccess.getAdminArea(srcParent), sourceFile, true, true); } finally { if (dstAccess != srcAccess) { dstAccess.close(); } srcAccess.close(); } } sleepForTimeStamp(); } private void propagateMegeInfo(File src, File dst, SVNWCAccess srcAccess, SVNWCAccess dstAccess) throws SVNException { boolean[] extend = { false }; Map mergeInfo = fetchMergeInfoForPropagation(src, extend, srcAccess); propagateMegeInfo(dst, mergeInfo, extend, dstAccess); } Map fetchMergeInfoForPropagation(File src, boolean[] extend, SVNWCAccess srcAccess) throws SVNException { SVNEntry entry = srcAccess.getVersionedEntry(src, false); if (entry.getSchedule() == null || (entry.isScheduledForAddition() && entry.isCopied())) { Map mergeInfo = calculateTargetMergeInfo(src, srcAccess, entry.getSVNURL(), entry.getRevision(), null, true); if (mergeInfo == null) { mergeInfo = new TreeMap(); } extend[0] = true; return mergeInfo; } Map mergeInfo = SVNPropertiesManager.parseMergeInfo(src, entry, false); if (mergeInfo == null) { mergeInfo = new TreeMap(); } extend[0] = false; return mergeInfo; } private void propagateMegeInfo(File dst, Map mergeInfo, boolean[] extend, SVNWCAccess dstAccess) throws SVNException { if (extend[0]) { SVNEntry dstEntry = dstAccess.getEntry(dst, false); extendWCMergeInfo(dst, dstEntry, mergeInfo, dstAccess); return; } SVNPropertiesManager.recordWCMergeInfo(dst, mergeInfo, dstAccess); } private void copyFiles(File src, File dstParent, SVNWCAccess dstAccess, String dstName) throws SVNException { SVNWCAccess srcAccess = createWCAccess(); try { srcAccess.probeOpen(src, false, -1); SVNEntry dstEntry = dstAccess.getVersionedEntry(dstParent, false); SVNEntry srcEntry = srcAccess.getVersionedEntry(src, false); if (srcEntry.getRepositoryRoot() != null && dstEntry.getRepositoryRoot() != null && !srcEntry.getRepositoryRoot().equals(dstEntry.getRepositoryRoot())) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_INVALID_SCHEDULE, "Cannot copy to ''{0}'', as it is not from repository ''{1}''; it is from ''{2}''", new Object[] {dstParent, srcEntry.getRepositoryRootURL(), dstEntry.getRepositoryRootURL()}); SVNErrorManager.error(err, SVNLogType.WC); } if (dstEntry.isScheduledForDeletion()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_INVALID_SCHEDULE, "Cannot copy to ''{0}'', as it is scheduled for deletion", dstParent); SVNErrorManager.error(err, SVNLogType.WC); } SVNFileType srcType = SVNFileType.getType(src); if (srcType == SVNFileType.FILE || srcType == SVNFileType.SYMLINK) { if (srcEntry.isScheduledForAddition() && !srcEntry.isCopied()) { copyAddedFileAdm(src, dstAccess, dstParent, dstName, true); } else { copyFileAdm(src, srcAccess, dstParent, dstAccess, dstName); } } else if (srcType == SVNFileType.DIRECTORY) { if (srcEntry.isScheduledForAddition() && !srcEntry.isCopied()) { copyAddedDirAdm(src, srcAccess, dstParent, dstAccess, dstName, true); } else { copyDirAdm(src, srcAccess, dstAccess, dstParent, dstName); } } } finally { srcAccess.close(); } } private void copyFileAdm(File src, SVNWCAccess srcAccess, File dstParent, SVNWCAccess dstAccess, String dstName) throws SVNException { File dst = new File(dstParent, dstName); SVNFileType dstType = SVNFileType.getType(dst); if (dstType != SVNFileType.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_EXISTS, "''{0}'' already exists and is in the way", dst); SVNErrorManager.error(err, SVNLogType.WC); } SVNEntry dstEntry = dstAccess.getEntry(dst, false); if (dstEntry != null && dstEntry.isFile()) { if (!dstEntry.isScheduledForDeletion()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_EXISTS, "There is already a versioned item ''{0}''", dst); SVNErrorManager.error(err, SVNLogType.WC); } } SVNEntry srcEntry = srcAccess.getVersionedEntry(src, false); if ((srcEntry.isScheduledForAddition() && !srcEntry.isCopied()) || srcEntry.getURL() == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_EXISTS, "Cannot copy or move ''{0}'': it is not in repository yet; " + "try committing first", src); SVNErrorManager.error(err, SVNLogType.WC); } String copyFromURL = null; long copyFromRevision = -1; SVNAdminArea srcDir = srcAccess.getAdminArea(src.getParentFile()); if (srcEntry.isCopied()) { // get cf info - one of the parents has to keep that. SVNLocationEntry location = determineCopyFromInfo(src, srcAccess, srcEntry, dstEntry); copyFromURL = location.getPath(); copyFromRevision = location.getRevision(); } else { copyFromURL = srcEntry.getURL(); copyFromRevision = srcEntry.getRevision(); } // copy base file. File srcBaseFile = new File(src.getParentFile(), SVNAdminUtil.getTextBasePath(src.getName(), false)); File dstBaseFile = new File(dstParent, SVNAdminUtil.getTextBasePath(dstName, true)); SVNFileUtil.copyFile(srcBaseFile, dstBaseFile, false); SVNVersionedProperties srcBaseProps = srcDir.getBaseProperties(src.getName()); SVNVersionedProperties srcWorkingProps = srcDir.getProperties(src.getName()); // copy wc file. SVNAdminArea dstDir = dstAccess.getAdminArea(dstParent); File tmpWCFile = SVNAdminUtil.createTmpFile(dstDir); if (srcWorkingProps.getPropertyValue(SVNProperty.SPECIAL) != null) { // TODO create symlink there? SVNFileUtil.copyFile(src, tmpWCFile, false); } else { SVNFileUtil.copyFile(src, tmpWCFile, false); } SVNWCManager.addRepositoryFile(dstDir, dstName, tmpWCFile, null, srcBaseProps.asMap(), srcWorkingProps.asMap(), copyFromURL, copyFromRevision); SVNEvent event = SVNEventFactory.createSVNEvent(dst, SVNNodeKind.FILE, null, SVNRepository.INVALID_REVISION, SVNEventAction.ADD, null, null, null); dstAccess.handleEvent(event); } private void copyAddedFileAdm(File src, SVNWCAccess dstAccess, File dstParent, String dstName, boolean isAdded) throws SVNException { File dst = new File(dstParent, dstName); SVNFileUtil.copyFile(src, dst, false); if (isAdded) { SVNWCManager.add(dst, dstAccess.getAdminArea(dstParent), null, SVNRepository.INVALID_REVISION); } } private void copyDirAdm(File src, SVNWCAccess srcAccess, SVNWCAccess dstAccess, File dstParent, String dstName) throws SVNException { File dst = new File(dstParent, dstName); SVNEntry srcEntry = srcAccess.getVersionedEntry(src, false); if ((srcEntry.isScheduledForAddition() && !srcEntry.isCopied()) || srcEntry.getURL() == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_EXISTS, "Cannot copy or move ''{0}'': it is not in repository yet; " + "try committing first", src); SVNErrorManager.error(err, SVNLogType.WC); } SVNFileUtil.copyDirectory(src, dst, true, getEventDispatcher()); SVNWCClient wcClient = new SVNWCClient((ISVNAuthenticationManager) null, null); wcClient.setEventHandler(getEventDispatcher()); wcClient.doCleanup(dst); SVNWCAccess tgtAccess = createWCAccess(); SVNAdminArea dir = null; String copyFromURL = null; long copyFromRevision = -1; try { dir = tgtAccess.open(dst, true, -1); postCopyCleanup(dir); if (srcEntry.isCopied()) { SVNEntry dstEntry = dstAccess.getEntry(dst, false); SVNLocationEntry info = determineCopyFromInfo(src, srcAccess, srcEntry, dstEntry); copyFromURL = info.getPath(); copyFromRevision = info.getRevision(); Map attributes = new SVNHashMap(); attributes.put(SVNProperty.URL, copyFromURL); dir.modifyEntry(dir.getThisDirName(), attributes, true, false); } else { copyFromURL = srcEntry.getURL(); copyFromRevision = srcEntry.getRevision(); } } finally { tgtAccess.close(); } SVNWCManager.add(dst, dstAccess.getAdminArea(dstParent), SVNURL.parseURIEncoded(copyFromURL), copyFromRevision); } private void copyAddedDirAdm(File src, SVNWCAccess srcAccess, File dstParent, SVNWCAccess dstParentAccess, String dstName, boolean isAdded) throws SVNException { File dst = new File(dstParent, dstName); if (!isAdded) { SVNFileUtil.copyDirectory(src, dst, true, getEventDispatcher()); } else { checkCancelled(); dst.mkdirs(); SVNWCManager.add(dst, dstParentAccess.getAdminArea(dstParent), null, SVNRepository.INVALID_REVISION); SVNAdminArea srcChildArea = srcAccess.retrieve(src); File[] entries = SVNFileListUtil.listFiles(src); for (int i = 0; entries != null && i < entries.length; i++) { checkCancelled(); File fsEntry = entries[i]; String name = fsEntry.getName(); if (SVNFileUtil.getAdminDirectoryName().equals(name)) { continue; } SVNEntry entry = srcChildArea.getEntry(name, true); if (fsEntry.isDirectory()) { copyAddedDirAdm(fsEntry, srcAccess, dst, dstParentAccess, name, entry != null); } else if (fsEntry.isFile()) { copyAddedFileAdm(fsEntry, dstParentAccess, dst, name, entry != null); } } } } private SVNLocationEntry determineCopyFromInfo(File src, SVNWCAccess srcAccess, SVNEntry srcEntry, SVNEntry dstEntry) throws SVNException { String url = null; long rev = -1; if (srcEntry.getCopyFromURL() != null) { url = srcEntry.getCopyFromURL(); rev = srcEntry.getCopyFromRevision(); } else { SVNLocationEntry info = getCopyFromInfoFromParent(src, srcAccess); url = info.getPath(); rev = info.getRevision(); } if (dstEntry != null && rev == dstEntry.getRevision() && url.equals(dstEntry.getCopyFromURL())) { url = null; rev = -1; } return new SVNLocationEntry(rev, url); } private SVNLocationEntry getCopyFromInfoFromParent(File file, SVNWCAccess access) throws SVNException { File parent = file.getParentFile(); String rest = file.getName(); String url = null; long rev = -1; while (parent != null && url == null) { try { SVNEntry entry = access.getVersionedEntry(parent, false); url = entry.getCopyFromURL(); rev = entry.getCopyFromRevision(); } catch (SVNException e) { SVNWCAccess wcAccess = SVNWCAccess.newInstance(null); try { wcAccess.probeOpen(parent, false, -1); SVNEntry entry = wcAccess.getVersionedEntry(parent, false); url = entry.getCopyFromURL(); rev = entry.getCopyFromRevision(); } finally { wcAccess.close(); } } if (url != null) { url = SVNPathUtil.append(url, SVNEncodingUtil.uriEncode(rest)); } else { rest = SVNPathUtil.append(parent.getName(), rest); parent = parent.getParentFile(); } } return new SVNLocationEntry(rev, url); } private void addLocalParents(File path, ISVNEventHandler handler) throws SVNException { boolean created = path.mkdirs(); SVNWCClient wcClient = new SVNWCClient((ISVNAuthenticationManager) null, null); try { wcClient.setEventHandler(handler); wcClient.doAdd(path, false, false, true, SVNDepth.EMPTY, true, true); } catch (SVNException e) { if (created) { SVNFileUtil.deleteAll(path, true); } throw e; } } private void extendWCMergeInfo(File path, SVNEntry entry, Map mergeInfo, SVNWCAccess access) throws SVNException { Map wcMergeInfo = SVNPropertiesManager.parseMergeInfo(path, entry, false); if (wcMergeInfo != null && mergeInfo != null) { wcMergeInfo = SVNMergeInfoUtil.mergeMergeInfos(wcMergeInfo, mergeInfo); } else if (wcMergeInfo == null) { wcMergeInfo = mergeInfo; } SVNPropertiesManager.recordWCMergeInfo(path, wcMergeInfo, access); } private Map calculateTargetMergeInfo(File srcFile, SVNWCAccess access, SVNURL srcURL, long srcRevision, SVNRepository repository, boolean noReposAccess) throws SVNException { boolean isLocallyAdded = false; SVNEntry entry = null; SVNURL url = null; if (access != null) { entry = access.getVersionedEntry(srcFile, false); if (entry.isScheduledForAddition() && !entry.isCopied()) { isLocallyAdded = true; } else { if (entry.getCopyFromURL() != null) { url = entry.getCopyFromSVNURL(); srcRevision = entry.getCopyFromRevision(); } else if (entry.getURL() != null) { url = entry.getSVNURL(); srcRevision = entry.getRevision(); } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_MISSING_URL, "Entry for ''{0}'' has no URL", srcFile); SVNErrorManager.error(err, SVNLogType.WC); } } } else { url = srcURL; } Map targetMergeInfo = null; if (!isLocallyAdded) { String mergeInfoPath = null; if (!noReposAccess) { // TODO reparent repository if needed and then ensure that repository has the same location as before that call. mergeInfoPath = getPathRelativeToRoot(null, url, entry != null ? entry.getRepositoryRootURL() : null, access, repository); targetMergeInfo = getReposMergeInfo(repository, mergeInfoPath, srcRevision, SVNMergeInfoInheritance.INHERITED, true); } else { targetMergeInfo = getWCMergeInfo(srcFile, entry, null, SVNMergeInfoInheritance.INHERITED, false, new boolean[1]); } } return targetMergeInfo; } private static class CopyCommitPathHandler implements ISVNCommitPathHandler { private Map myPathInfos; private boolean myIsMove; public CopyCommitPathHandler(Map pathInfos, boolean isMove) { myPathInfos = pathInfos; myIsMove = isMove; } public boolean handleCommitPath(String commitPath, ISVNEditor commitEditor) throws SVNException { CopyPathInfo pathInfo = (CopyPathInfo) myPathInfos.get(commitPath); boolean doAdd = false; boolean doDelete = false; if (pathInfo.isDirAdded) { commitEditor.addDir(commitPath, null, SVNRepository.INVALID_REVISION); return true; } if (pathInfo.isResurrection) { if (!myIsMove) { doAdd = true; } } else { if (myIsMove) { if (commitPath.equals(pathInfo.mySourcePath)) { doDelete = true; } else { doAdd = true; } } else { doAdd = true; } } if (doDelete) { commitEditor.deleteEntry(commitPath, -1); } boolean closeDir = false; if (doAdd) { SVNPathUtil.checkPathIsValid(commitPath); if (pathInfo.mySourceKind == SVNNodeKind.DIR) { commitEditor.addDir(commitPath, pathInfo.mySourcePath, pathInfo.mySourceRevisionNumber); if (pathInfo.myMergeInfoProp != null) { commitEditor.changeDirProperty(SVNProperty.MERGE_INFO, SVNPropertyValue.create(pathInfo.myMergeInfoProp)); } closeDir = true; } else { commitEditor.addFile(commitPath, pathInfo.mySourcePath, pathInfo.mySourceRevisionNumber); if (pathInfo.myMergeInfoProp != null) { commitEditor.changeFileProperty(commitPath, SVNProperty.MERGE_INFO, SVNPropertyValue.create(pathInfo.myMergeInfoProp)); } commitEditor.closeFile(commitPath, null); } } return closeDir; } } private static class CopyPathInfo { public boolean isDirAdded; public boolean isResurrection; public SVNNodeKind mySourceKind; public String mySource; public String mySourcePath; public String myDstPath; public String myMergeInfoProp; public long mySourceRevisionNumber; } private static class CopyPair { public String mySource; public String myOriginalSource; public SVNNodeKind mySourceKind; public SVNRevision mySourceRevision; public SVNRevision mySourcePegRevision; public long mySourceRevisionNumber; public String myBaseName; public String myDst; public void setSourceRevisions(SVNRevision pegRevision, SVNRevision revision) { if (pegRevision == SVNRevision.UNDEFINED) { if (SVNPathUtil.isURL(mySource)) { pegRevision = SVNRevision.HEAD; } else { pegRevision = SVNRevision.WORKING; } } if (revision == SVNRevision.UNDEFINED) { revision = pegRevision; } mySourceRevision = revision; mySourcePegRevision = pegRevision; } } }
true
true
private SVNCommitInfo copyWCToRepos(List copyPairs, boolean makeParents, String message, SVNProperties revprops) throws SVNException { String topSrc = ((CopyPair) copyPairs.get(0)).mySource; for (int i = 1; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); topSrc = SVNPathUtil.getCommonPathAncestor(topSrc, pair.mySource); } SVNWCAccess wcAccess = createWCAccess(); SVNCommitInfo info = null; ISVNEditor commitEditor = null; Collection tmpFiles = null; try { SVNAdminArea adminArea = wcAccess.probeOpen(new File(topSrc), false, SVNWCAccess.INFINITE_DEPTH); wcAccess.setAnchor(adminArea.getRoot()); String topDstURL = ((CopyPair) copyPairs.get(0)).myDst; topDstURL = SVNPathUtil.removeTail(topDstURL); for (int i = 1; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); topDstURL = SVNPathUtil.getCommonPathAncestor(topDstURL, pair.myDst); } // should we use also wcAccess here? i do not think so. SVNRepository repos = createRepository(SVNURL.parseURIEncoded(topDstURL), adminArea.getRoot(), wcAccess, true); List newDirs = new ArrayList(); if (makeParents) { String rootURL = topDstURL; SVNNodeKind kind = repos.checkPath("", -1); while(kind == SVNNodeKind.NONE) { newDirs.add(rootURL); rootURL = SVNPathUtil.removeTail(rootURL); repos.setLocation(SVNURL.parseURIEncoded(rootURL), false); kind = repos.checkPath("", -1); } topDstURL = rootURL; } for (int i = 0; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); SVNEntry entry = wcAccess.getEntry(new File(pair.mySource), false); pair.mySourceRevisionNumber = entry.getRevision(); String dstRelativePath = SVNPathUtil.getPathAsChild(topDstURL, pair.myDst); dstRelativePath = SVNEncodingUtil.uriDecode(dstRelativePath); SVNNodeKind kind = repos.checkPath(dstRelativePath, -1); if (kind != SVNNodeKind.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.FS_ALREADY_EXISTS, "Path ''{0}'' already exists", SVNURL.parseURIEncoded(pair.myDst)); SVNErrorManager.error(err, SVNLogType.WC); } } // create commit items list to fetch log messages. List commitItems = new ArrayList(copyPairs.size()); if (makeParents) { for (int i = 0; i < newDirs.size(); i++) { String newDirURL = (String) newDirs.get(i); SVNURL url = SVNURL.parseURIEncoded(newDirURL); SVNCommitItem item = new SVNCommitItem(null, url, null, SVNNodeKind.NONE, null, null, true, false, false, false, false, false); commitItems.add(item); } } for (int i = 0; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); SVNURL url = SVNURL.parseURIEncoded(pair.myDst); SVNCommitItem item = new SVNCommitItem(null, url, null, SVNNodeKind.NONE, null, null, true, false, false, false, false, false); commitItems.add(item); } SVNCommitItem[] commitables = (SVNCommitItem[]) commitItems.toArray(new SVNCommitItem[commitItems.size()]); message = getCommitHandler().getCommitMessage(message, commitables); if (message == null) { return SVNCommitInfo.NULL; } revprops = getCommitHandler().getRevisionProperties(message, commitables, revprops == null ? new SVNProperties() : revprops); if (revprops == null) { return SVNCommitInfo.NULL; } Map allCommitables = new TreeMap(SVNCommitUtil.FILE_COMPARATOR); repos.setLocation(repos.getRepositoryRoot(true), false); Map pathsToExternalsProps = new SVNHashMap(); for (int i = 0; i < copyPairs.size(); i++) { CopyPair source = (CopyPair) copyPairs.get(i); File srcFile = new File(source.mySource); SVNEntry entry = wcAccess.getVersionedEntry(srcFile, false); SVNAdminArea dirArea = null; if (entry.isDirectory()) { dirArea = wcAccess.retrieve(srcFile); } else { dirArea = wcAccess.retrieve(srcFile.getParentFile()); } pathsToExternalsProps.clear(); SVNCommitUtil.harvestCommitables(allCommitables, dirArea, srcFile, null, entry, source.myDst, entry.getURL(), true, false, false, null, SVNDepth.INFINITY, false, null, getCommitParameters(), pathsToExternalsProps); SVNCommitItem item = (SVNCommitItem) allCommitables.get(srcFile); SVNURL srcURL = entry.getSVNURL(); Map mergeInfo = calculateTargetMergeInfo(srcFile, wcAccess, srcURL, source.mySourceRevisionNumber, repos, false); Map wcMergeInfo = SVNPropertiesManager.parseMergeInfo(srcFile, entry, false); if (wcMergeInfo != null && mergeInfo != null) { mergeInfo = SVNMergeInfoUtil.mergeMergeInfos(mergeInfo, wcMergeInfo); } else if (mergeInfo == null) { mergeInfo = wcMergeInfo; } if (mergeInfo != null) { String mergeInfoString = SVNMergeInfoUtil.formatMergeInfoToString(mergeInfo); item.setProperty(SVNProperty.MERGE_INFO, SVNPropertyValue.create(mergeInfoString)); } if (!pathsToExternalsProps.isEmpty()) { LinkedList newExternals = new LinkedList(); for (Iterator pathsIter = pathsToExternalsProps.keySet().iterator(); pathsIter.hasNext();) { File localPath = (File) pathsIter.next(); String externalsPropString = (String) pathsToExternalsProps.get(localPath); SVNExternal[] externals = SVNExternal.parseExternals(localPath.getAbsolutePath(), externalsPropString); boolean introduceVirtualExternalChange = false; newExternals.clear(); for (int k = 0; k < externals.length; k++) { File externalWC = new File(localPath, externals[k].getPath()); SVNEntry externalEntry = null; try { wcAccess.open(externalWC, false, 0); externalEntry = wcAccess.getVersionedEntry(externalWC, false); } catch (SVNException svne) { if (svne instanceof SVNCancelException) { throw svne; } } finally { wcAccess.closeAdminArea(externalWC); } SVNRevision externalsWCRevision = SVNRevision.UNDEFINED; if (externalEntry != null) { externalsWCRevision = SVNRevision.create(externalEntry.getRevision()); } SVNRevision[] revs = getExternalsHandler().handleExternal(externalWC, externals[k].resolveURL(repos.getRepositoryRoot(true), externalEntry.getSVNURL()), externals[k].getRevision(), externals[k].getPegRevision(), externals[k].getRawValue(), externalsWCRevision); if (revs != null && revs[0] == externals[k].getRevision()) { newExternals.add(externals[k].getRawValue()); } else if (revs != null) { SVNExternal newExternal = new SVNExternal(externals[k].getPath(), externals[k].getUnresolvedUrl(), revs[1], revs[0], true, externals[k].isPegRevisionExplicit(), externals[k].isNewFormat()); newExternals.add(newExternal.toString()); if (!introduceVirtualExternalChange) { introduceVirtualExternalChange = true; } } } if (introduceVirtualExternalChange) { String newExternalsProp = ""; for (Iterator externalsIter = newExternals.iterator(); externalsIter.hasNext();) { String external = (String) externalsIter.next(); newExternalsProp += external + '\n'; } SVNCommitItem itemWithExternalsChanges = (SVNCommitItem) allCommitables.get(localPath); if (itemWithExternalsChanges != null) { itemWithExternalsChanges.setProperty(SVNProperty.EXTERNALS, SVNPropertyValue.create(newExternalsProp)); } else { SVNAdminArea childArea = wcAccess.retrieve(localPath); String relativePath = childArea.getRelativePath(dirArea); String itemURL = SVNPathUtil.append(source.myDst, SVNEncodingUtil.uriEncode(relativePath)); itemWithExternalsChanges = new SVNCommitItem(localPath, SVNURL.parseURIEncoded(itemURL), null, SVNNodeKind.DIR, null, null, false, false, true, false, false, false); itemWithExternalsChanges.setProperty(SVNProperty.EXTERNALS, SVNPropertyValue.create(newExternalsProp)); allCommitables.put(localPath, itemWithExternalsChanges); } } } } } commitItems = new ArrayList(allCommitables.values()); // add parents to commits hash? if (makeParents) { for (int i = 0; i < newDirs.size(); i++) { String newDirURL = (String) newDirs.get(i); SVNURL url = SVNURL.parseURIEncoded(newDirURL); SVNCommitItem item = new SVNCommitItem(null, url, null, SVNNodeKind.NONE, null, null, true, false, false, false, false, false); commitItems.add(item); } } commitables = (SVNCommitItem[]) commitItems.toArray(new SVNCommitItem[commitItems.size()]); for (int i = 0; i < commitables.length; i++) { commitables[i].setWCAccess(wcAccess); } allCommitables.clear(); SVNURL url = SVNCommitUtil.translateCommitables(commitables, allCommitables); repos = createRepository(url, null, null, true); SVNCommitMediator mediator = new SVNCommitMediator(allCommitables); tmpFiles = mediator.getTmpFiles(); message = SVNCommitClient.validateCommitMessage(message); SVNURL rootURL = repos.getRepositoryRoot(true); commitEditor = repos.getCommitEditor(message, null, true, revprops, mediator); info = SVNCommitter.commit(tmpFiles, allCommitables, rootURL.getPath(), commitEditor); commitEditor = null; } catch (SVNCancelException cancel) { throw cancel; } catch (SVNException e) { // wrap error message. SVNErrorMessage err = e.getErrorMessage().wrap("Commit failed (details follow):"); SVNErrorManager.error(err, SVNLogType.WC); } finally { if (tmpFiles != null) { for (Iterator files = tmpFiles.iterator(); files.hasNext();) { File file = (File) files.next(); SVNFileUtil.deleteFile(file); } } if (commitEditor != null && info == null) { // should we hide this exception? try { commitEditor.abortEdit(); } catch (SVNException e) { SVNDebugLog.getDefaultLog().logFine(SVNLogType.WC, e); } } if (wcAccess != null) { wcAccess.close(); } } if (info != null && info.getNewRevision() >= 0) { dispatchEvent(SVNEventFactory.createSVNEvent(null, SVNNodeKind.NONE, null, info.getNewRevision(), SVNEventAction.COMMIT_COMPLETED, null, null, null), ISVNEventHandler.UNKNOWN); } return info != null ? info : SVNCommitInfo.NULL; }
private SVNCommitInfo copyWCToRepos(List copyPairs, boolean makeParents, String message, SVNProperties revprops) throws SVNException { String topSrc = ((CopyPair) copyPairs.get(0)).mySource; for (int i = 1; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); topSrc = SVNPathUtil.getCommonPathAncestor(topSrc, pair.mySource); } SVNWCAccess wcAccess = createWCAccess(); SVNCommitInfo info = null; ISVNEditor commitEditor = null; Collection tmpFiles = null; try { SVNAdminArea adminArea = wcAccess.probeOpen(new File(topSrc), false, SVNWCAccess.INFINITE_DEPTH); wcAccess.setAnchor(adminArea.getRoot()); String topDstURL = ((CopyPair) copyPairs.get(0)).myDst; topDstURL = SVNPathUtil.removeTail(topDstURL); for (int i = 1; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); topDstURL = SVNPathUtil.getCommonPathAncestor(topDstURL, pair.myDst); } // should we use also wcAccess here? i do not think so. SVNRepository repos = createRepository(SVNURL.parseURIEncoded(topDstURL), adminArea.getRoot(), wcAccess, true); List newDirs = new ArrayList(); if (makeParents) { String rootURL = topDstURL; SVNNodeKind kind = repos.checkPath("", -1); while(kind == SVNNodeKind.NONE) { newDirs.add(rootURL); rootURL = SVNPathUtil.removeTail(rootURL); repos.setLocation(SVNURL.parseURIEncoded(rootURL), false); kind = repos.checkPath("", -1); } topDstURL = rootURL; } for (int i = 0; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); SVNEntry entry = wcAccess.getEntry(new File(pair.mySource), false); pair.mySourceRevisionNumber = entry.getRevision(); String dstRelativePath = SVNPathUtil.getPathAsChild(topDstURL, pair.myDst); dstRelativePath = SVNEncodingUtil.uriDecode(dstRelativePath); SVNNodeKind kind = repos.checkPath(dstRelativePath, -1); if (kind != SVNNodeKind.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.FS_ALREADY_EXISTS, "Path ''{0}'' already exists", SVNURL.parseURIEncoded(pair.myDst)); SVNErrorManager.error(err, SVNLogType.WC); } } // create commit items list to fetch log messages. List commitItems = new ArrayList(copyPairs.size()); if (makeParents) { for (int i = 0; i < newDirs.size(); i++) { String newDirURL = (String) newDirs.get(i); SVNURL url = SVNURL.parseURIEncoded(newDirURL); SVNCommitItem item = new SVNCommitItem(null, url, null, SVNNodeKind.NONE, null, null, true, false, false, false, false, false); commitItems.add(item); } } for (int i = 0; i < copyPairs.size(); i++) { CopyPair pair = (CopyPair) copyPairs.get(i); SVNURL url = SVNURL.parseURIEncoded(pair.myDst); SVNCommitItem item = new SVNCommitItem(null, url, null, SVNNodeKind.NONE, null, null, true, false, false, false, false, false); commitItems.add(item); } SVNCommitItem[] commitables = (SVNCommitItem[]) commitItems.toArray(new SVNCommitItem[commitItems.size()]); message = getCommitHandler().getCommitMessage(message, commitables); if (message == null) { return SVNCommitInfo.NULL; } revprops = getCommitHandler().getRevisionProperties(message, commitables, revprops == null ? new SVNProperties() : revprops); if (revprops == null) { return SVNCommitInfo.NULL; } Map allCommitables = new TreeMap(SVNCommitUtil.FILE_COMPARATOR); repos.setLocation(repos.getRepositoryRoot(true), false); Map pathsToExternalsProps = new SVNHashMap(); for (int i = 0; i < copyPairs.size(); i++) { CopyPair source = (CopyPair) copyPairs.get(i); File srcFile = new File(source.mySource); SVNEntry entry = wcAccess.getVersionedEntry(srcFile, false); SVNAdminArea dirArea = null; if (entry.isDirectory()) { dirArea = wcAccess.retrieve(srcFile); } else { dirArea = wcAccess.retrieve(srcFile.getParentFile()); } pathsToExternalsProps.clear(); SVNCommitUtil.harvestCommitables(allCommitables, dirArea, srcFile, null, entry, source.myDst, entry.getURL(), true, false, false, null, SVNDepth.INFINITY, false, null, getCommitParameters(), pathsToExternalsProps); SVNCommitItem item = (SVNCommitItem) allCommitables.get(srcFile); SVNURL srcURL = entry.getSVNURL(); Map mergeInfo = calculateTargetMergeInfo(srcFile, wcAccess, srcURL, source.mySourceRevisionNumber, repos, false); Map wcMergeInfo = SVNPropertiesManager.parseMergeInfo(srcFile, entry, false); if (wcMergeInfo != null && mergeInfo != null) { mergeInfo = SVNMergeInfoUtil.mergeMergeInfos(mergeInfo, wcMergeInfo); } else if (mergeInfo == null) { mergeInfo = wcMergeInfo; } if (mergeInfo != null) { String mergeInfoString = SVNMergeInfoUtil.formatMergeInfoToString(mergeInfo); item.setProperty(SVNProperty.MERGE_INFO, SVNPropertyValue.create(mergeInfoString)); } if (!pathsToExternalsProps.isEmpty()) { LinkedList newExternals = new LinkedList(); for (Iterator pathsIter = pathsToExternalsProps.keySet().iterator(); pathsIter.hasNext();) { File localPath = (File) pathsIter.next(); String externalsPropString = (String) pathsToExternalsProps.get(localPath); SVNExternal[] externals = SVNExternal.parseExternals(localPath.getAbsolutePath(), externalsPropString); boolean introduceVirtualExternalChange = false; newExternals.clear(); for (int k = 0; k < externals.length; k++) { File externalWC = new File(localPath, externals[k].getPath()); SVNEntry externalEntry = null; try { wcAccess.open(externalWC, false, 0); externalEntry = wcAccess.getVersionedEntry(externalWC, false); } catch (SVNException svne) { if (svne instanceof SVNCancelException) { throw svne; } } finally { wcAccess.closeAdminArea(externalWC); } SVNRevision externalsWCRevision = SVNRevision.UNDEFINED; if (externalEntry != null) { externalsWCRevision = SVNRevision.create(externalEntry.getRevision()); } SVNRevision[] revs = getExternalsHandler().handleExternal(externalWC, externals[k].resolveURL(repos.getRepositoryRoot(true), externalEntry.getSVNURL()), externals[k].getRevision(), externals[k].getPegRevision(), externals[k].getRawValue(), externalsWCRevision); if (revs != null && revs[0] == externals[k].getRevision()) { newExternals.add(externals[k].getRawValue()); } else if (revs != null) { SVNExternal newExternal = new SVNExternal(externals[k].getPath(), externals[k].getUnresolvedUrl(), revs[1], revs[0], true, externals[k].isPegRevisionExplicit(), externals[k].isNewFormat()); newExternals.add(newExternal.toString()); if (!introduceVirtualExternalChange) { introduceVirtualExternalChange = true; } } } if (introduceVirtualExternalChange) { String newExternalsProp = ""; for (Iterator externalsIter = newExternals.iterator(); externalsIter.hasNext();) { String external = (String) externalsIter.next(); newExternalsProp += external + '\n'; } SVNCommitItem itemWithExternalsChanges = (SVNCommitItem) allCommitables.get(localPath); if (itemWithExternalsChanges != null) { itemWithExternalsChanges.setProperty(SVNProperty.EXTERNALS, SVNPropertyValue.create(newExternalsProp)); } else { SVNAdminArea childArea = wcAccess.retrieve(localPath); String relativePath = childArea.getRelativePath(dirArea); String itemURL = SVNPathUtil.append(source.myDst, SVNEncodingUtil.uriEncode(relativePath)); itemWithExternalsChanges = new SVNCommitItem(localPath, SVNURL.parseURIEncoded(itemURL), null, SVNNodeKind.DIR, null, null, false, false, true, false, false, false); itemWithExternalsChanges.setProperty(SVNProperty.EXTERNALS, SVNPropertyValue.create(newExternalsProp)); allCommitables.put(localPath, itemWithExternalsChanges); } } } } } commitItems = new ArrayList(allCommitables.values()); // add parents to commits hash? if (makeParents) { for (int i = 0; i < newDirs.size(); i++) { String newDirURL = (String) newDirs.get(i); SVNURL url = SVNURL.parseURIEncoded(newDirURL); SVNCommitItem item = new SVNCommitItem(null, url, null, SVNNodeKind.NONE, null, null, true, false, false, false, false, false); commitItems.add(item); } } commitables = (SVNCommitItem[]) commitItems.toArray(new SVNCommitItem[commitItems.size()]); for (int i = 0; i < commitables.length; i++) { commitables[i].setWCAccess(wcAccess); } allCommitables = new TreeMap(); SVNURL url = SVNCommitUtil.translateCommitables(commitables, allCommitables); repos = createRepository(url, null, null, true); SVNCommitMediator mediator = new SVNCommitMediator(allCommitables); tmpFiles = mediator.getTmpFiles(); message = SVNCommitClient.validateCommitMessage(message); SVNURL rootURL = repos.getRepositoryRoot(true); commitEditor = repos.getCommitEditor(message, null, true, revprops, mediator); info = SVNCommitter.commit(tmpFiles, allCommitables, rootURL.getPath(), commitEditor); commitEditor = null; } catch (SVNCancelException cancel) { throw cancel; } catch (SVNException e) { // wrap error message. SVNErrorMessage err = e.getErrorMessage().wrap("Commit failed (details follow):"); SVNErrorManager.error(err, SVNLogType.WC); } finally { if (tmpFiles != null) { for (Iterator files = tmpFiles.iterator(); files.hasNext();) { File file = (File) files.next(); SVNFileUtil.deleteFile(file); } } if (commitEditor != null && info == null) { // should we hide this exception? try { commitEditor.abortEdit(); } catch (SVNException e) { SVNDebugLog.getDefaultLog().logFine(SVNLogType.WC, e); } } if (wcAccess != null) { wcAccess.close(); } } if (info != null && info.getNewRevision() >= 0) { dispatchEvent(SVNEventFactory.createSVNEvent(null, SVNNodeKind.NONE, null, info.getNewRevision(), SVNEventAction.COMMIT_COMPLETED, null, null, null), ISVNEventHandler.UNKNOWN); } return info != null ? info : SVNCommitInfo.NULL; }
diff --git a/src/me/neatmonster/spacebukkit/SpaceBukkit.java b/src/me/neatmonster/spacebukkit/SpaceBukkit.java index 42fe6e4..b8e68ae 100644 --- a/src/me/neatmonster/spacebukkit/SpaceBukkit.java +++ b/src/me/neatmonster/spacebukkit/SpaceBukkit.java @@ -1,189 +1,197 @@ /* * This file is part of SpaceBukkit (http://spacebukkit.xereo.net/). * * SpaceBukkit is free software: you can redistribute it and/or modify it under the terms of the * Attribution-NonCommercial-ShareAlike Unported (CC BY-NC-SA) license as published by the Creative Common organization, * either version 3.0 of the license, or (at your option) any later version. * * SpaceBukkit is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Attribution-NonCommercial-ShareAlike * Unported (CC BY-NC-SA) license for more details. * * You should have received a copy of the Attribution-NonCommercial-ShareAlike Unported (CC BY-NC-SA) license along with * this program. If not, see <http://creativecommons.org/licenses/by-nc-sa/3.0/>. */ package me.neatmonster.spacebukkit; import java.io.IOException; import java.util.Timer; import java.util.UUID; import mcstats.Metrics; import me.neatmonster.spacebukkit.actions.PlayerActions; import me.neatmonster.spacebukkit.actions.ServerActions; import me.neatmonster.spacebukkit.actions.SystemActions; import me.neatmonster.spacebukkit.players.SBListener; import me.neatmonster.spacebukkit.plugins.PluginsManager; import me.neatmonster.spacebukkit.system.PerformanceMonitor; import me.neatmonster.spacemodule.SpaceModule; import me.neatmonster.spacemodule.api.ActionsManager; import me.neatmonster.spacertk.SpaceRTK; import org.bukkit.Bukkit; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.java.JavaPlugin; import com.drdanick.rtoolkit.EventDispatcher; import com.drdanick.rtoolkit.event.ToolkitEventHandler; /** * Main class of the Plugin */ public class SpaceBukkit extends JavaPlugin { public static SpaceRTK spaceRTK = null; private static SpaceBukkit spacebukkit; public static SpaceBukkit getInstance() { return spacebukkit; } public int port; public int rPort; public String salt; public int maxJoins; public int maxMessages; public int maxQuits; public PluginsManager pluginsManager; public ActionsManager actionsManager; public PanelListener panelListener; public PerformanceMonitor performanceMonitor; private YamlConfiguration configuration; private final Timer timer = new Timer(); private EventDispatcher edt; private ToolkitEventHandler eventHandler; private PingListener pingListener; @Override public void onDisable() { performanceMonitor.infanticide(); timer.cancel(); pingListener.shutdown(); try { if (panelListener != null) panelListener.stopServer(); } catch (final Exception e) { getLogger().severe(e.getMessage()); } edt.setRunning(false); synchronized (edt) { edt.notifyAll(); } eventHandler.setEnabled(false); } @Override public void onEnable() { spacebukkit = this; configuration = YamlConfiguration.loadConfiguration(SpaceModule.CONFIGURATION); - salt = configuration.getString("General.Salt", "<default>"); + configuration.addDefault("General.salt", "<default>"); + configuration.addDefault("General.worldContainer", Bukkit.getWorldContainer().getPath()); + configuration.addDefault("SpaceBukkit.port", 2011); + configuration.addDefault("SpaceRTK.port", 2012); + configuration.addDefault("SpaceBukkit.maxJoins", 199); + configuration.addDefault("SpaceBukkit.maxMessages", 199); + configuration.addDefault("SpaceBukkit.maxQuits", 199); + configuration.options().copyDefaults(true); + salt = configuration.getString("General.salt", "<default>"); if (salt.equals("<default>")) { salt = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase(); - configuration.set("General.Salt", salt); + configuration.set("General.salt", salt); } - configuration.set("General.WorldContainer", Bukkit.getWorldContainer().getPath()); - port = configuration.getInt("SpaceBukkit.Port", 2011); - rPort = configuration.getInt("SpaceRTK.Port", 2012); + configuration.set("General.worldContainer", Bukkit.getWorldContainer().getPath()); + port = configuration.getInt("SpaceBukkit.port", 2011); + rPort = configuration.getInt("SpaceRTK.port", 2012); maxJoins = configuration.getInt("SpaceBukkit.maxJoins", 199); maxMessages = configuration.getInt("SpaceBukkit.maxMessages", 199); maxQuits = configuration.getInt("SpaceBukkit.maxQuits", 199); try { configuration.save(SpaceModule.CONFIGURATION); } catch (IOException e) { e.printStackTrace(); } try { pingListener = new PingListener(); pingListener.startup(); } catch (IOException e) { e.printStackTrace(); } if(edt == null) edt = new EventDispatcher(); if(!edt.isRunning()) { synchronized(edt) { edt.notifyAll(); } edt.setRunning(true); Thread edtThread = new Thread(edt, "SpaceModule EventDispatcher"); edtThread.setDaemon(true); edtThread.start(); } if(eventHandler != null) { eventHandler.setEnabled(true); if(!eventHandler.isRunning()) new Thread(eventHandler, "SpaceModule EventHandler").start(); } else { eventHandler = new EventHandler(); new Thread(eventHandler, "SpaceModule EventHandler").start(); } setupMetrics(); new SBListener(this); pluginsManager = new PluginsManager(); actionsManager = new ActionsManager(); actionsManager.register(PlayerActions.class); actionsManager.register(ServerActions.class); actionsManager.register(SystemActions.class); panelListener = new PanelListener(); performanceMonitor = new PerformanceMonitor(); timer.scheduleAtFixedRate(performanceMonitor, 0L, 1000L); } /** * Sets up Metrics */ private void setupMetrics() { try { Metrics metrics = new Metrics(this); metrics.start(); } catch (IOException e) { e.printStackTrace(); } } /** * Gets the RTK event dispatcher * @return event dispatcher */ public EventDispatcher getEdt() { return edt; } /** * Gets the RTK event handler * @return event handler */ public ToolkitEventHandler getEventHandler() { return eventHandler; } /** * Forces the event handler into the correct state. */ private class EventHandler extends ToolkitEventHandler { public EventHandler() { setEnabled(true); } } }
false
true
public void onEnable() { spacebukkit = this; configuration = YamlConfiguration.loadConfiguration(SpaceModule.CONFIGURATION); salt = configuration.getString("General.Salt", "<default>"); if (salt.equals("<default>")) { salt = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase(); configuration.set("General.Salt", salt); } configuration.set("General.WorldContainer", Bukkit.getWorldContainer().getPath()); port = configuration.getInt("SpaceBukkit.Port", 2011); rPort = configuration.getInt("SpaceRTK.Port", 2012); maxJoins = configuration.getInt("SpaceBukkit.maxJoins", 199); maxMessages = configuration.getInt("SpaceBukkit.maxMessages", 199); maxQuits = configuration.getInt("SpaceBukkit.maxQuits", 199); try { configuration.save(SpaceModule.CONFIGURATION); } catch (IOException e) { e.printStackTrace(); } try { pingListener = new PingListener(); pingListener.startup(); } catch (IOException e) { e.printStackTrace(); } if(edt == null) edt = new EventDispatcher(); if(!edt.isRunning()) { synchronized(edt) { edt.notifyAll(); } edt.setRunning(true); Thread edtThread = new Thread(edt, "SpaceModule EventDispatcher"); edtThread.setDaemon(true); edtThread.start(); } if(eventHandler != null) { eventHandler.setEnabled(true); if(!eventHandler.isRunning()) new Thread(eventHandler, "SpaceModule EventHandler").start(); } else { eventHandler = new EventHandler(); new Thread(eventHandler, "SpaceModule EventHandler").start(); } setupMetrics(); new SBListener(this); pluginsManager = new PluginsManager(); actionsManager = new ActionsManager(); actionsManager.register(PlayerActions.class); actionsManager.register(ServerActions.class); actionsManager.register(SystemActions.class); panelListener = new PanelListener(); performanceMonitor = new PerformanceMonitor(); timer.scheduleAtFixedRate(performanceMonitor, 0L, 1000L); }
public void onEnable() { spacebukkit = this; configuration = YamlConfiguration.loadConfiguration(SpaceModule.CONFIGURATION); configuration.addDefault("General.salt", "<default>"); configuration.addDefault("General.worldContainer", Bukkit.getWorldContainer().getPath()); configuration.addDefault("SpaceBukkit.port", 2011); configuration.addDefault("SpaceRTK.port", 2012); configuration.addDefault("SpaceBukkit.maxJoins", 199); configuration.addDefault("SpaceBukkit.maxMessages", 199); configuration.addDefault("SpaceBukkit.maxQuits", 199); configuration.options().copyDefaults(true); salt = configuration.getString("General.salt", "<default>"); if (salt.equals("<default>")) { salt = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase(); configuration.set("General.salt", salt); } configuration.set("General.worldContainer", Bukkit.getWorldContainer().getPath()); port = configuration.getInt("SpaceBukkit.port", 2011); rPort = configuration.getInt("SpaceRTK.port", 2012); maxJoins = configuration.getInt("SpaceBukkit.maxJoins", 199); maxMessages = configuration.getInt("SpaceBukkit.maxMessages", 199); maxQuits = configuration.getInt("SpaceBukkit.maxQuits", 199); try { configuration.save(SpaceModule.CONFIGURATION); } catch (IOException e) { e.printStackTrace(); } try { pingListener = new PingListener(); pingListener.startup(); } catch (IOException e) { e.printStackTrace(); } if(edt == null) edt = new EventDispatcher(); if(!edt.isRunning()) { synchronized(edt) { edt.notifyAll(); } edt.setRunning(true); Thread edtThread = new Thread(edt, "SpaceModule EventDispatcher"); edtThread.setDaemon(true); edtThread.start(); } if(eventHandler != null) { eventHandler.setEnabled(true); if(!eventHandler.isRunning()) new Thread(eventHandler, "SpaceModule EventHandler").start(); } else { eventHandler = new EventHandler(); new Thread(eventHandler, "SpaceModule EventHandler").start(); } setupMetrics(); new SBListener(this); pluginsManager = new PluginsManager(); actionsManager = new ActionsManager(); actionsManager.register(PlayerActions.class); actionsManager.register(ServerActions.class); actionsManager.register(SystemActions.class); panelListener = new PanelListener(); performanceMonitor = new PerformanceMonitor(); timer.scheduleAtFixedRate(performanceMonitor, 0L, 1000L); }
diff --git a/src/edu/mit/mitmobile2/libraries/BookDetailView.java b/src/edu/mit/mitmobile2/libraries/BookDetailView.java index 36967dce..ec03fa6f 100644 --- a/src/edu/mit/mitmobile2/libraries/BookDetailView.java +++ b/src/edu/mit/mitmobile2/libraries/BookDetailView.java @@ -1,255 +1,255 @@ package edu.mit.mitmobile2.libraries; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Handler; import android.os.Message; import android.text.Html; import android.text.Spannable; import android.text.Spannable.Factory; import android.text.SpannableStringBuilder; import android.text.style.TextAppearanceSpan; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.LinearLayout; import android.widget.TextView; import edu.mit.mitmobile2.CommonActions; import edu.mit.mitmobile2.DividerView; import edu.mit.mitmobile2.FullScreenLoader; import edu.mit.mitmobile2.LockingScrollView; import edu.mit.mitmobile2.MobileWebApi; import edu.mit.mitmobile2.R; import edu.mit.mitmobile2.SectionHeader; import edu.mit.mitmobile2.SectionHeader.Prominence; import edu.mit.mitmobile2.SliderInterface; import edu.mit.mitmobile2.TwoLineActionRow; import edu.mit.mitmobile2.libraries.BookItem.Holding; import edu.mit.mitmobile2.libraries.BookItem.Holding.Availabilitys; public class BookDetailView implements SliderInterface { enum DetailsLoadingStatus { Loaded, Loading, NotLoaded } private Activity mActivity; private BookItem mBookItem; private LockingScrollView mView; private DetailsLoadingStatus mLoadingStatus; private FullScreenLoader mFullScreenLoader; private TextView mTitleTextView; private LinearLayout mDetailsLinearLayout; private LinearLayout mExtraItemsLayout; private View mEmailCitationButton; public BookDetailView(Activity activity, BookItem bookItem) { mActivity = activity; mBookItem = bookItem; LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mView = (LockingScrollView) inflater.inflate(R.layout.book_detail, null); mFullScreenLoader = (FullScreenLoader) mView.findViewById(R.id.libraryWorldCatBookDetailLoader); mTitleTextView = (TextView) mView.findViewById(R.id.libraryWorldCatBookDetailsTitle); mDetailsLinearLayout = (LinearLayout) mView.findViewById(R.id.libraryWorldCatBookDetailLL); mExtraItemsLayout = (LinearLayout) mView.findViewById(R.id.libraryWorldCatDetailsExtraItems); mEmailCitationButton = mView.findViewById(R.id.libraryWorldCatEmailCitationsButton); mLoadingStatus = DetailsLoadingStatus.NotLoaded; } @Override public LockingScrollView getVerticalScrollView() { return mView; } @Override public View getView() { return mView; } @Override public void onDestroy() { } @Override public void onSelected() { if (mLoadingStatus != DetailsLoadingStatus.Loaded) { if (mBookItem.detailsLoaded) { showBookDetails(); mLoadingStatus = DetailsLoadingStatus.Loaded; } else if (mLoadingStatus != DetailsLoadingStatus.Loading) { mFullScreenLoader.showLoading(); mLoadingStatus = DetailsLoadingStatus.Loading; LibraryModel.fetchWorldCatBookDetails(mBookItem, mActivity, new Handler() { @Override public void handleMessage(Message msg) { if (msg.arg1 == MobileWebApi.SUCCESS) { showBookDetails(); mLoadingStatus = DetailsLoadingStatus.Loaded; } else { mFullScreenLoader.showError(); mLoadingStatus = DetailsLoadingStatus.NotLoaded; } } }); } } } SpannableStringBuilder mSpanBuilder; public void showBookDetails() { mFullScreenLoader.setVisibility(View.GONE); mTitleTextView.setText(mBookItem.title); addRow(null, mBookItem.getAuthorsDisplayString()); if (mBookItem.format != null) { addRow("Format", join(", ", mBookItem.format)); } if (mBookItem.summary != null) { addRow("Summary", join(" ", mBookItem.summary)); } if (mBookItem.publisher != null) { addRow("Publisher", join("", mBookItem.publisher)); } if (mBookItem.editions != null) { addRow("Edition", join(", ", mBookItem.editions)); } if (mBookItem.extent != null) { addRow("Description", join(" ", mBookItem.extent)); } if (mBookItem.isbn != null) { addRow("ISBN", join(" : ", mBookItem.isbn)); } mEmailCitationButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:")); intent.putExtra(Intent.EXTRA_SUBJECT, mBookItem.title); intent.putExtra( Intent.EXTRA_TEXT, Html.fromHtml(mBookItem.emailAndCiteMessage) ); mActivity.startActivity(intent); } }); final List<Holding> mitHoldings = mBookItem.getHoldingsByOCLCCode(BookItem.MITLibrariesOCLCCode); if (mitHoldings.size() > 0) { mExtraItemsLayout.addView(new SectionHeader(mActivity, "MIT Libraries", Prominence.SECONDARY)); TwoLineActionRow requestItem = new TwoLineActionRow(mActivity); - requestItem.setTitle("RequestItem"); + requestItem.setTitle("Request Item"); requestItem.setActionIconResource(R.drawable.action_external); requestItem.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { CommonActions.viewURL(mActivity, mitHoldings.get(0).url); } }); mExtraItemsLayout.addView(requestItem); for (Holding aMitHolding : mitHoldings) { final Map<String, Availabilitys> availabilitiesByLibrary = aMitHolding.getAvailabilitys(); final ArrayList<String> locations = new ArrayList<String>(availabilitiesByLibrary.keySet()); Collections.sort(locations); for (int i = 0; i < locations.size(); i++) { final int index = i; String location = locations.get(i); Availabilitys availablitys = availabilitiesByLibrary.get(location); mExtraItemsLayout.addView(new DividerView(mActivity, null)); TwoLineActionRow availabilityRow = new TwoLineActionRow(mActivity); availabilityRow.setTitle(location); availabilityRow.setSubtitle("" + availablitys.available + " of " + availablitys.total + " available"); availabilityRow.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { LibrariesHoldingsSliderActivity.launch(mActivity, availabilitiesByLibrary, locations, index); } }); mExtraItemsLayout.addView(availabilityRow); } } } int otherHoldingsCount = mBookItem.holdings.size() - mitHoldings.size(); if (otherHoldingsCount > 0) { mExtraItemsLayout.addView(new SectionHeader(mActivity, "Boston Library Consortium", Prominence.SECONDARY)); TwoLineActionRow blcHoldingsRow = new TwoLineActionRow(mActivity); blcHoldingsRow.setTitle("View Holdings"); blcHoldingsRow.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { LibraryBLCHoldingsActivity.launch(mActivity, mBookItem); } }); mExtraItemsLayout.addView(blcHoldingsRow); } } public void addRow(String label, CharSequence value) { Factory factory = Spannable.Factory.getInstance(); if (label != null) { label += ": "; } else { label = ""; } Spannable span = factory.newSpannable(label + value); if (label.length() > 0) { span.setSpan(new TextAppearanceSpan(mActivity, R.style.BoldBodyText), 0, label.length()-1, Spannable.SPAN_INCLUSIVE_INCLUSIVE); } span.setSpan(new TextAppearanceSpan(mActivity, R.style.BodyText), label.length(), span.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); TextView textView = new TextView(mActivity); int padding = mActivity.getResources().getDimensionPixelSize(R.dimen.verticalPadding); textView.setPadding(0, 0, 0, padding); textView.setText(span); mDetailsLinearLayout.addView(textView); } private String join(String delimiter, List<String> parts) { String out = ""; boolean isFirst = true; for (String part : parts) { if (isFirst) { isFirst = false; } else { out += delimiter; } out += part; } return out; } @Override public void updateView() { } }
true
true
public void showBookDetails() { mFullScreenLoader.setVisibility(View.GONE); mTitleTextView.setText(mBookItem.title); addRow(null, mBookItem.getAuthorsDisplayString()); if (mBookItem.format != null) { addRow("Format", join(", ", mBookItem.format)); } if (mBookItem.summary != null) { addRow("Summary", join(" ", mBookItem.summary)); } if (mBookItem.publisher != null) { addRow("Publisher", join("", mBookItem.publisher)); } if (mBookItem.editions != null) { addRow("Edition", join(", ", mBookItem.editions)); } if (mBookItem.extent != null) { addRow("Description", join(" ", mBookItem.extent)); } if (mBookItem.isbn != null) { addRow("ISBN", join(" : ", mBookItem.isbn)); } mEmailCitationButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:")); intent.putExtra(Intent.EXTRA_SUBJECT, mBookItem.title); intent.putExtra( Intent.EXTRA_TEXT, Html.fromHtml(mBookItem.emailAndCiteMessage) ); mActivity.startActivity(intent); } }); final List<Holding> mitHoldings = mBookItem.getHoldingsByOCLCCode(BookItem.MITLibrariesOCLCCode); if (mitHoldings.size() > 0) { mExtraItemsLayout.addView(new SectionHeader(mActivity, "MIT Libraries", Prominence.SECONDARY)); TwoLineActionRow requestItem = new TwoLineActionRow(mActivity); requestItem.setTitle("RequestItem"); requestItem.setActionIconResource(R.drawable.action_external); requestItem.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { CommonActions.viewURL(mActivity, mitHoldings.get(0).url); } }); mExtraItemsLayout.addView(requestItem); for (Holding aMitHolding : mitHoldings) { final Map<String, Availabilitys> availabilitiesByLibrary = aMitHolding.getAvailabilitys(); final ArrayList<String> locations = new ArrayList<String>(availabilitiesByLibrary.keySet()); Collections.sort(locations); for (int i = 0; i < locations.size(); i++) { final int index = i; String location = locations.get(i); Availabilitys availablitys = availabilitiesByLibrary.get(location); mExtraItemsLayout.addView(new DividerView(mActivity, null)); TwoLineActionRow availabilityRow = new TwoLineActionRow(mActivity); availabilityRow.setTitle(location); availabilityRow.setSubtitle("" + availablitys.available + " of " + availablitys.total + " available"); availabilityRow.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { LibrariesHoldingsSliderActivity.launch(mActivity, availabilitiesByLibrary, locations, index); } }); mExtraItemsLayout.addView(availabilityRow); } } } int otherHoldingsCount = mBookItem.holdings.size() - mitHoldings.size(); if (otherHoldingsCount > 0) { mExtraItemsLayout.addView(new SectionHeader(mActivity, "Boston Library Consortium", Prominence.SECONDARY)); TwoLineActionRow blcHoldingsRow = new TwoLineActionRow(mActivity); blcHoldingsRow.setTitle("View Holdings"); blcHoldingsRow.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { LibraryBLCHoldingsActivity.launch(mActivity, mBookItem); } }); mExtraItemsLayout.addView(blcHoldingsRow); } }
public void showBookDetails() { mFullScreenLoader.setVisibility(View.GONE); mTitleTextView.setText(mBookItem.title); addRow(null, mBookItem.getAuthorsDisplayString()); if (mBookItem.format != null) { addRow("Format", join(", ", mBookItem.format)); } if (mBookItem.summary != null) { addRow("Summary", join(" ", mBookItem.summary)); } if (mBookItem.publisher != null) { addRow("Publisher", join("", mBookItem.publisher)); } if (mBookItem.editions != null) { addRow("Edition", join(", ", mBookItem.editions)); } if (mBookItem.extent != null) { addRow("Description", join(" ", mBookItem.extent)); } if (mBookItem.isbn != null) { addRow("ISBN", join(" : ", mBookItem.isbn)); } mEmailCitationButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:")); intent.putExtra(Intent.EXTRA_SUBJECT, mBookItem.title); intent.putExtra( Intent.EXTRA_TEXT, Html.fromHtml(mBookItem.emailAndCiteMessage) ); mActivity.startActivity(intent); } }); final List<Holding> mitHoldings = mBookItem.getHoldingsByOCLCCode(BookItem.MITLibrariesOCLCCode); if (mitHoldings.size() > 0) { mExtraItemsLayout.addView(new SectionHeader(mActivity, "MIT Libraries", Prominence.SECONDARY)); TwoLineActionRow requestItem = new TwoLineActionRow(mActivity); requestItem.setTitle("Request Item"); requestItem.setActionIconResource(R.drawable.action_external); requestItem.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { CommonActions.viewURL(mActivity, mitHoldings.get(0).url); } }); mExtraItemsLayout.addView(requestItem); for (Holding aMitHolding : mitHoldings) { final Map<String, Availabilitys> availabilitiesByLibrary = aMitHolding.getAvailabilitys(); final ArrayList<String> locations = new ArrayList<String>(availabilitiesByLibrary.keySet()); Collections.sort(locations); for (int i = 0; i < locations.size(); i++) { final int index = i; String location = locations.get(i); Availabilitys availablitys = availabilitiesByLibrary.get(location); mExtraItemsLayout.addView(new DividerView(mActivity, null)); TwoLineActionRow availabilityRow = new TwoLineActionRow(mActivity); availabilityRow.setTitle(location); availabilityRow.setSubtitle("" + availablitys.available + " of " + availablitys.total + " available"); availabilityRow.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { LibrariesHoldingsSliderActivity.launch(mActivity, availabilitiesByLibrary, locations, index); } }); mExtraItemsLayout.addView(availabilityRow); } } } int otherHoldingsCount = mBookItem.holdings.size() - mitHoldings.size(); if (otherHoldingsCount > 0) { mExtraItemsLayout.addView(new SectionHeader(mActivity, "Boston Library Consortium", Prominence.SECONDARY)); TwoLineActionRow blcHoldingsRow = new TwoLineActionRow(mActivity); blcHoldingsRow.setTitle("View Holdings"); blcHoldingsRow.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { LibraryBLCHoldingsActivity.launch(mActivity, mBookItem); } }); mExtraItemsLayout.addView(blcHoldingsRow); } }
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.ui/src/org/eclipse/tcf/te/ui/internal/utils/QuickFilter.java b/target_explorer/plugins/org.eclipse.tcf.te.ui/src/org/eclipse/tcf/te/ui/internal/utils/QuickFilter.java index d5facf769..237acd63f 100644 --- a/target_explorer/plugins/org.eclipse.tcf.te.ui/src/org/eclipse/tcf/te/ui/internal/utils/QuickFilter.java +++ b/target_explorer/plugins/org.eclipse.tcf.te.ui/src/org/eclipse/tcf/te/ui/internal/utils/QuickFilter.java @@ -1,201 +1,204 @@ /******************************************************************************* * Copyright (c) 2011, 2012 Wind River Systems, Inc. and others. All rights reserved. * This program and the accompanying materials are made available under the terms * of the Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ package org.eclipse.tcf.te.ui.internal.utils; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.TreePath; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.tcf.te.core.interfaces.IPropertyChangeProvider; /** * A quick filter is a viewer filter that selects elements, * which has the specified name pattern, under a certain tree path. * Other elements outside of this tree path is ignored. */ public class QuickFilter extends TablePatternFilter implements PropertyChangeListener { // The tree viewer to filter. private TreeViewer viewer; // The root path to select from. private Object root; /** * Create a quick filter for the specified viewer. */ public QuickFilter(TreeViewer viewer) { super((ILabelProvider) viewer.getLabelProvider()); this.viewer = viewer; this.addPropertyChangeListener(this); } /** * Show the pop up dialog for the specified root path. * * @param root The root path to filter from. */ public void showFilterPopup(Object root) { this.root = root; + setPattern(null); if (!isFiltering()) { viewer.addFilter(this); } QuickFilterPopup popup = new QuickFilterPopup(viewer, this); Point location = null; if (root != null) { TreeItem[] items = viewer.getTree().getSelection(); if (items != null && items.length > 0) { + for(TreeItem item : items) { + viewer.getTree().showItem(item); + } Rectangle bounds = items[0].getBounds(); location = new Point(bounds.x, bounds.y); } else { location = new Point(0, 0); } } else { location = new Point(0, 0); } location.y -= viewer.getTree().getItemHeight(); location = viewer.getTree().toDisplay(location); popup.open(); popup.getShell().setLocation(location); - viewer.refresh(); } /* * (non-Javadoc) * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent) */ @Override public void propertyChange(PropertyChangeEvent evt) { Object element = getFilteringElement(); if(element != null) { IPropertyChangeProvider provider = getPropertyChangeProvider(element); if(provider!=null) { provider.firePropertyChange(new PropertyChangeEvent(element, evt.getPropertyName(), evt.getOldValue(), evt.getNewValue())); } } } /** * Get an adapter of IPropertyChangeProvider from the specified element. * * @param element The element to get the adapter from. * @return The element's adapter or null if does not adapt to IPropertyChangeProvider. */ private IPropertyChangeProvider getPropertyChangeProvider(Object element) { IPropertyChangeProvider provider = null; if(element instanceof IPropertyChangeProvider) { provider = (IPropertyChangeProvider) element; } if(provider == null && element instanceof IAdaptable) { provider = (IPropertyChangeProvider) ((IAdaptable)element).getAdapter(IPropertyChangeProvider.class); } if(provider == null && element != null) { provider = (IPropertyChangeProvider) Platform.getAdapterManager().getAdapter(element, IPropertyChangeProvider.class); } return provider; } /** * Get the element which is currently being filtered. * * @return The current filtered element. */ private Object getFilteringElement() { Object element = root; if(root instanceof TreePath) { element = ((TreePath)root).getLastSegment(); } return element; } /** * Reset the tree viewer to the original view by removing this filter. */ public void resetViewer() { viewer.removeFilter(this); setPattern(null); root = null; viewer.refresh(); } /** * If the current viewer is being filtered. * * @return true if it has this filter. */ public boolean isFiltering() { ViewerFilter[] filters = viewer.getFilters(); if (filters != null) { for (ViewerFilter filter : filters) { if (filter == this) { return matcher != null; } } } return false; } /* * (non-Javadoc) * @see org.eclipse.tcf.te.ui.dialogs.TablePatternFilter#select(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object) */ @Override public boolean select(Viewer viewer, Object parentElement, Object element) { return skipMatching(parentElement) || super.select(viewer, parentElement, element); } /** * If the specified parent element should be skipped when matching elements. * * @param parentElement The parent element. * @return true if it should be skipped. */ private boolean skipMatching(Object parentElement) { if (root == null || parentElement == null) return true; if (parentElement instanceof TreePath) { if (root instanceof TreePath) { return !root.equals(parentElement); } Object parent = ((TreePath) parentElement).getLastSegment(); return !root.equals(parent); } if (root instanceof TreePath) { Object rootElement = ((TreePath) root).getLastSegment(); return !parentElement.equals(rootElement); } return !root.equals(parentElement); } /** * If the element is being filtered. * * @param element The element to be checked. * @return true if it is filtering. */ public boolean isFiltering(Object element) { if(root != null) { Object rootElement = root; if(root instanceof TreePath) { rootElement = ((TreePath)root).getLastSegment(); } return rootElement == element && matcher != null; } return false; } }
false
true
public void showFilterPopup(Object root) { this.root = root; if (!isFiltering()) { viewer.addFilter(this); } QuickFilterPopup popup = new QuickFilterPopup(viewer, this); Point location = null; if (root != null) { TreeItem[] items = viewer.getTree().getSelection(); if (items != null && items.length > 0) { Rectangle bounds = items[0].getBounds(); location = new Point(bounds.x, bounds.y); } else { location = new Point(0, 0); } } else { location = new Point(0, 0); } location.y -= viewer.getTree().getItemHeight(); location = viewer.getTree().toDisplay(location); popup.open(); popup.getShell().setLocation(location); viewer.refresh(); }
public void showFilterPopup(Object root) { this.root = root; setPattern(null); if (!isFiltering()) { viewer.addFilter(this); } QuickFilterPopup popup = new QuickFilterPopup(viewer, this); Point location = null; if (root != null) { TreeItem[] items = viewer.getTree().getSelection(); if (items != null && items.length > 0) { for(TreeItem item : items) { viewer.getTree().showItem(item); } Rectangle bounds = items[0].getBounds(); location = new Point(bounds.x, bounds.y); } else { location = new Point(0, 0); } } else { location = new Point(0, 0); } location.y -= viewer.getTree().getItemHeight(); location = viewer.getTree().toDisplay(location); popup.open(); popup.getShell().setLocation(location); }
diff --git a/ChessFeud/src/se/chalmers/chessfeud/model/pieces/King.java b/ChessFeud/src/se/chalmers/chessfeud/model/pieces/King.java index cd73a33..636a678 100644 --- a/ChessFeud/src/se/chalmers/chessfeud/model/pieces/King.java +++ b/ChessFeud/src/se/chalmers/chessfeud/model/pieces/King.java @@ -1,53 +1,53 @@ package se.chalmers.chessfeud.model.pieces; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import se.chalmers.chessfeud.constants.C; import se.chalmers.chessfeud.model.utils.Position; /** * The Piece King. * Reprecents the King on the chessborad. Handles the logic for the * Kings movement. * @author Arvid * */ //�ven kallad Kung public class King extends Piece{ public King(int team) { super(team, C.PIECE_KING); // TODO Auto-generated constructor stub } /** * Returns a list of all the theoretical moves the King can do. * Even the moves that are out of bounds. That will be checked in * the rules class. * The list shall contain every position one square away from the king. * @param p the piece current position. * @return posList A list that contains Lists of possible positions in the different directions. */ @Override public List<List<Position>> theoreticalMoves(Position p) { List<List<Position>> posList = new ArrayList<List<Position>>(); for(int x = -1; x < 3; x++){ for(int y = -1; y < 3; y++){ - if((x != 0 && y != 0) && (p.getX() + x < 8 && p.getY() + y < 8)){ + if(!(x == 0 && y == 0) && (p.getX() + x <= 7 && p.getY() + y <= 7)){ List<Position> tmp = new LinkedList<Position>(); tmp.add(new Position(p.getX() + x, p.getY() + y)); posList.add(tmp); } } } return posList; } @Override public String toString(){ return "Piece: King " + "Team: " + getTeam(); } }
true
true
public List<List<Position>> theoreticalMoves(Position p) { List<List<Position>> posList = new ArrayList<List<Position>>(); for(int x = -1; x < 3; x++){ for(int y = -1; y < 3; y++){ if((x != 0 && y != 0) && (p.getX() + x < 8 && p.getY() + y < 8)){ List<Position> tmp = new LinkedList<Position>(); tmp.add(new Position(p.getX() + x, p.getY() + y)); posList.add(tmp); } } } return posList; }
public List<List<Position>> theoreticalMoves(Position p) { List<List<Position>> posList = new ArrayList<List<Position>>(); for(int x = -1; x < 3; x++){ for(int y = -1; y < 3; y++){ if(!(x == 0 && y == 0) && (p.getX() + x <= 7 && p.getY() + y <= 7)){ List<Position> tmp = new LinkedList<Position>(); tmp.add(new Position(p.getX() + x, p.getY() + y)); posList.add(tmp); } } } return posList; }
diff --git a/ini/trakem2/display/Node.java b/ini/trakem2/display/Node.java index 87bcf251..4ceecea4 100644 --- a/ini/trakem2/display/Node.java +++ b/ini/trakem2/display/Node.java @@ -1,1148 +1,1154 @@ package ini.trakem2.display; import java.lang.reflect.InvocationTargetException; import java.util.AbstractCollection; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.Collection; import java.util.Collections; import java.awt.Graphics2D; import java.awt.Stroke; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.RoundRectangle2D; import java.awt.geom.Rectangle2D; import java.awt.Rectangle; import java.awt.Color; import java.awt.Dimension; import java.awt.geom.Point2D; import ini.trakem2.utils.IJError; import ini.trakem2.utils.M; import ini.trakem2.utils.Utils; import ini.trakem2.Project; import javax.vecmath.Point3f; /** Can only have one parent, so there aren't cyclic graphs. */ public abstract class Node<T> implements Taggable { /** Maximum possible confidence in an edge (ranges from 0 to 5, inclusive).*/ static public final byte MAX_EDGE_CONFIDENCE = 5; protected Node<T> parent = null; public Node<T> getParent() { return parent; } protected float x, y; public float getX() { return x; } public float getY() { return y; } protected Color color; public Color getColor() { return this.color; } public void setColor(final Color c) { this.color = c; } /** The confidence value of the edge towards the parent; * in other words, how much this node can be trusted to continue from its parent node. * Defaults to MAX_EDGE_CONFIDENCE for full trust, and 0 for none. */ protected byte confidence = MAX_EDGE_CONFIDENCE; public byte getConfidence() { return confidence; } protected Layer la; public Layer getLayer() { return la; } protected Node<T>[] children = null; public ArrayList<Node<T>> getChildrenNodes() { final ArrayList<Node<T>> a = new ArrayList<Node<T>>(); if (null == children) return a; for (int i=0; i<children.length; i++) a.add(children[i]); return a; } /** @return a map of child node vs edge confidence to that child. */ public Map<Node<T>,Byte> getChildren() { final HashMap<Node<T>,Byte> m = new HashMap<Node<T>,Byte>(); if (null == children) return m; for (int i=0; i<children.length; i++) m.put(children[i], children[i].confidence); return m; } public List<Byte> getEdgeConfidence() { final ArrayList<Byte> a = new ArrayList<Byte>(); if (null == children) return a; for (int i=0; i<children.length; i++) a.add(children[i].confidence); return a; } public byte getEdgeConfidence(final Node<T> child) { if (null == children) return (byte)0; for (int i=0; i<children.length; i++) { if (child == children[i]) return children[i].confidence; } return (byte)0; } public String toString() { return new StringBuilder("{:x ").append(x).append(" :y ").append(y).append(" :layer ").append(la.getId()).append('}').toString(); } /** @param parent The parent Node, which has an edge of a certain confidence value towards this Node. * @param x The X in local coordinates. * @param y The Y in local coordinates. * @param layer The Layer where the point represented by this Node sits. */ public Node(final float x, final float y, final Layer la) { this.x = x; this.y = y; this.la = la; } /** To reconstruct from XML, without a layer. * WARNING this method doesn't do any error checking. If "x" or "y" are not present in @param attr, it will simply fail with a NumberFormatException. */ public Node(final HashMap<String,String> attr) { this.x = Float.parseFloat(attr.get("x")); this.y = Float.parseFloat(attr.get("y")); this.la = null; } public void setLayer(final Layer la) { this.la = la; } /** Returns -1 when not added (e.g. if child is null). */ synchronized public final int add(final Node<T> child, final byte conf) { if (null == child) return -1; if (null != child.parent) { Utils.log("WARNING: tried to add a node that already had a parent!"); return -1; } if (null != children) { for (final Node<T> nd : children) { if (nd == child) { Utils.log("WARNING: tried to add a node to a parent that already had the node as a child!"); return -1; } } } enlargeArrays(1); this.children[children.length-1] = child; child.confidence = conf; child.parent = this; return children.length -1; } synchronized public final boolean remove(final Node<T> child) { if (null == children) { Utils.log("WARNING: tried to remove a child from a childless node!"); return false; // no children! } // find its index int k = -1; for (int i=0; i<children.length; i++) { if (child == children[i]) { k = i; break; } } if (-1 == k) { Utils.log("Not a child!"); return false; // not a child! } child.parent = null; if (1 == children.length) { children = null; return true; } // Else, rearrange arrays: final Node<T>[] ch = (Node<T>[])new Node[children.length-1]; System.arraycopy(children, 0, ch, 0, k); System.arraycopy(children, k+1, ch, k, children.length - k -1); children = ch; return true; } private final void enlargeArrays(final int n_more) { if (null == children) { children = (Node<T>[])new Node[n_more]; } else { final Node<T>[] ch = (Node<T>[])new Node[children.length + n_more]; System.arraycopy(children, 0, ch, 0, children.length); final byte[] co = new byte[children.length + n_more]; children = ch; } } static protected final int TRUE = 0, FALSE = 1, TEST = 2; /** Paint this node, and edges to parent and children varies according to whether they are included in the to_paint list. * Returns a task (or null) to paint the tags. */ final Runnable paint(final Graphics2D g, final Layer active_layer, final boolean active, final Rectangle srcRect, final double magnification, final Collection<Node<T>> to_paint, final Tree<T> tree, final AffineTransform to_screen, final boolean with_arrows, final boolean with_confidence_boxes, final boolean with_data, Color above, Color below) { // The fact that this method is called indicates that this node is to be painted and by definition is inside the Set to_paint. final double actZ = active_layer.getZ(); final double thisZ = this.la.getZ(); final Color node_color; if (null == this.color) { // this node doesn't have its color set, so use tree color and given above/below colors node_color = tree.color; } else { node_color = this.color; // Depth cue colors may not be in use: if (tree.color == above) above = this.color; if (tree.color == below) below = this.color; } // Which edge color? final Color local_edge_color; if (active_layer == this.la) { local_edge_color = node_color; } // default color else if (actZ > thisZ) { local_edge_color = below; } else if (actZ < thisZ) local_edge_color = above; else local_edge_color = node_color; if (with_data) paintData(g, srcRect, tree, to_screen, local_edge_color, active_layer); //if (null == children && !paint) return null; - final boolean paint = with_arrows && null != tags; // with_arrows acts as a flag for both arrows and tags - if (null == parent && !paint) return null; + //final boolean paint = with_arrows && null != tags; // with_arrows acts as a flag for both arrows and tags + //if (null == parent && !paint) return null; final float[] fps = new float[4]; final int parent_x, parent_y; fps[0] = this.x; fps[1] = this.y; if (null == parent) { parent_x = parent_y = 0; tree.at.transform(fps, 0, fps, 0, 1); } else { fps[2] = parent.x; fps[3] = parent.y; tree.at.transform(fps, 0, fps, 0, 2); parent_x = (int)((fps[2] - srcRect.x) * magnification); parent_y = (int)((fps[3] - srcRect.y) * magnification); } // To screen coords: final int x = (int)((fps[0] - srcRect.x) * magnification); final int y = (int)((fps[1] - srcRect.y) * magnification); final Runnable tagsTask; - if (paint) { + if (with_arrows && null != tags) { tagsTask = new Runnable() { public void run() { paintTags(g, x, y, local_edge_color); } }; } else tagsTask = null; - if (null == parent) return tagsTask; + //if (null == parent) return tagsTask; synchronized (this) { if (null != parent) { // Does the line from parent to this cross the srcRect? // Or what is the same, does the line from parent to this cross any of the edges of the srcRect? // Paint full edge, but perhaps in two halves of different colors if (parent.la == this.la && this.la == active_layer) { // in treeline color // Full edge in local color g.setColor(local_edge_color); g.drawLine(x, y, parent_x, parent_y); if (with_arrows) g.fill(M.createArrowhead(parent_x, parent_y, x, y, magnification)); } else if (this.la == active_layer) { // Proximal half in this color g.setColor(local_edge_color); g.drawLine(parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2, x, y); if (with_arrows) g.fill(M.createArrowhead(parent_x, parent_y, x, y, magnification)); // Distal either red or blue: Color c = local_edge_color; // If other towards higher Z: if (actZ < parent.la.getZ()) c = above; // If other towards lower Z: else if (actZ > parent.la.getZ()) c = below; // g.setColor(c); g.drawLine(parent_x, parent_y, parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2); } else if (parent.la == active_layer) { // Distal half in the Displayable or Node color g.setColor(node_color); g.drawLine(parent_x, parent_y, parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2); // Proximal half in either red or blue: g.setColor(local_edge_color); g.drawLine(parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2, x, y); if (with_arrows) g.fill(M.createArrowhead(parent_x, parent_y, x, y, magnification)); } else if (thisZ < actZ && actZ < parent.la.getZ()) { // proximal half in red g.setColor(below); g.drawLine(x, y, parent_x + (x - parent_x)/2, (parent_y + (y - parent_y)/2)); if (with_arrows) g.fill(M.createArrowhead(parent_x, parent_y, x, y, magnification)); // distal half in blue g.setColor(above); g.drawLine(parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2, parent_x, parent_y); } else if (thisZ > actZ && actZ > parent.la.getZ()) { // proximal half in blue g.setColor(above); g.drawLine(x, y, parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2); if (with_arrows) g.fill(M.createArrowhead(parent_x, parent_y, x, y, magnification)); // distal half in red g.setColor(below); g.drawLine(parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2, parent_x, parent_y); } else if ((thisZ < actZ && parent.la.getZ() < actZ) || (thisZ > actZ && parent.la.getZ() > actZ)) { g.setColor(local_edge_color); if (to_paint.contains(parent)) { // full edge g.drawLine(x, y, parent_x, parent_y); } else { // paint proximal half g.drawLine(x, y, parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2); } if (with_arrows) g.fill(M.createArrowhead(parent_x, parent_y, x, y, magnification)); } + } else if (with_arrows && !active) { + // paint a gray handle for the root + g.setColor(active_layer == this.la ? Color.gray : local_edge_color); + g.fillOval((int)x - 6, (int)y - 6, 11, 11); + g.setColor(Color.black); + g.drawString("S", (int)x -3, (int)y + 4); // TODO ensure Font is proper } if (null != children) { final float[] fp = new float[2]; for (final Node<T> child : children) { if (to_paint.contains(child)) continue; fp[0] = child.x; fp[1] = child.y; tree.at.transform(fp, 0, fp, 0, 1); final int cx = (int)(((int)fp[0] - srcRect.x) * magnification), cy = (int)(((int)fp[1] - srcRect.y) * magnification); if (child.la == this.la){ // child in same layer but outside the field of view // paint full edge to it g.setColor(null == child.color ? tree.color : child.color); g.drawLine(x, y, cx, cy); if (with_arrows) g.fill(M.createArrowhead(x, y, cx, cy, magnification)); } else { if (child.la.getZ() < actZ) g.setColor(Color.red); else if (child.la.getZ() > actZ) g.setColor(Color.blue); // paint half edge to the child g.drawLine(x, y, x + (cx - x)/2, y + (cy - y)/2); } } } if (null != parent && active && with_confidence_boxes && (active_layer == this.la || active_layer == parent.la || (thisZ < actZ && actZ < parent.la.getZ()))) { // Draw confidence half-way through the edge final String s = Integer.toString(confidence); final Dimension dim = Utils.getDimensions(s, g.getFont()); g.setColor(Color.white); final int xc = (int)(parent_x + (x - parent_x)/2), yc = (int)(parent_y + (y - parent_y)/2); // y + 0.5*chy - 0.5y = (y + chy)/2 g.fillRect(xc, yc, dim.width+2, dim.height+2); g.setColor(Color.black); g.drawString(s, xc+1, yc+dim.height+1); } } return tagsTask; } static private final Color receiver_color = Color.green.brighter(); protected void paintHandle(final Graphics2D g, final Rectangle srcRect, final double magnification, final Tree<T> t) { paintHandle(g, srcRect, magnification, t, false); } /** Paint in the context of offscreen space, without transformations. */ protected void paintHandle(final Graphics2D g, final Rectangle srcRect, final double magnification, final Tree<T> t, final boolean paint_background) { final Point2D.Double po = t.transformPoint(this.x, this.y); final float x = (float)((po.x - srcRect.x) * magnification); final float y = (float)((po.y - srcRect.y) * magnification); final Color receiver = t.getLastVisited() == this ? Node.receiver_color : null; // paint the node as a draggable point if (null == parent) { // As origin g.setColor(null == receiver ? Color.magenta : receiver); g.fillOval((int)x - 6, (int)y - 6, 11, 11); g.setColor(Color.black); g.drawString("S", (int)x -3, (int)y + 4); // TODO ensure Font is proper } else if (null == children) { // as end point g.setColor(null == receiver ? Color.white : receiver); g.fillOval((int)x - 6, (int)y - 6, 11, 11); g.setColor(Color.black); g.drawString("e", (int)x -4, (int)y + 3); // TODO ensure Font is proper } else if (1 == children.length) { // as a slab: no branches if (paint_background) { g.setColor(Color.black); g.fillOval((int)x - 4, (int)y - 4, 9, 9); } g.setColor(null == receiver ? (null == this.color ? t.getColor() : this.color) : receiver); g.fillOval((int)x - 3, (int)y - 3, 7, 7); } else { // As branch point g.setColor(null == receiver ? Color.yellow : receiver); g.fillOval((int)x - 6, (int)y - 6, 11, 11); g.setColor(Color.black); g.drawString("Y", (int)x -4, (int)y + 4); // TODO ensure Font is proper } } /** Returns a lazy read-only Collection of the nodes belonging to the subtree of this node, including the node itself as the root. * Non-recursive, avoids potential stack overflow. */ public final Collection<Node<T>> getSubtreeNodes() { /* final List<Node<T>> nodes = new ArrayList<Node<T>>(); final LinkedList<Node<T>> todo = new LinkedList<Node<T>>(); todo.add(this); while (!todo.isEmpty()) { // Grab one node from the todo list and add it final Node<T> nd = todo.removeFirst(); nodes.add(nd); // Then add all its children to the todo list if (null != nd.children) { for (final Node<T> child : nd.children) todo.add(child); } } return nodes; */ return new NodeCollection<T>(this, BreadthFirstSubtreeIterator.class); } /** Returns a lazy read-only Collection of the nodes from this node up to the next branch node or end node, inclusive. */ public final Collection<Node<T>> getSlabNodes() { return new NodeCollection<T>(this, SlabIterator.class); } /** Returns a lazy read-only Collection of all branch and end nodes under this node. */ public final Collection<Node<T>> getBranchAndEndNodes() { return new NodeCollection<T>(this, BranchAndEndNodeIterator.class); } /** Returns a lazy read-only Collection of all branch nodes under this node. */ public final Collection<Node<T>> getBranchNodes() { return new NodeCollection<T>(this, BranchNodeIterator.class); } /** Returns a lazy read-only Collection of all end nodes under this node. */ public final Collection<Node<T>> getEndNodes() { return new NodeCollection<T>(this, EndNodeIterator.class); } /** Only this node, not any of its children. */ final public void translate(final float dx, final float dy) { x += dx; y += dy; } /** Returns a recursive copy of this Node subtree, where the copy of this Node is the root. * Non-recursive to avoid stack overflow. */ final public Node<T> clone(final Project pr) { // todo list containing packets of a copied node and the lists of original children and confidence to clone into it final LinkedList<Object[]> todo = new LinkedList<Object[]>(); final Node<T> root = newInstance(x, y, la); root.setData(this.getDataCopy()); root.tags = getTagsCopy(); if (null != this.children) { todo.add(new Object[]{root, this.children}); } final HashMap<Long,Layer> ml; if (pr != la.getProject()) { // Layers must be replaced by their corresponding clones ml = new HashMap<Long,Layer>(); for (final Layer layer : pr.getRootLayerSet().getLayers()) { ml.put(layer.getId(), layer); } } else ml = null; if (null != ml) root.la = ml.get(root.la.getId()); // replace Layer pointer in the copy while (!todo.isEmpty()) { final Object[] o = todo.removeFirst(); final Node<T> copy = (Node<T>)o[0]; final Node<T>[] original_children = (Node<T>[])o[1]; copy.children = (Node<T>[])new Node[original_children.length]; for (int i=0; i<original_children.length; i++) { final Node<T> ochild = original_children[i]; copy.children[i] = newInstance(ochild.x, ochild.y, ochild.la); copy.children[i].setData(ochild.getDataCopy()); copy.children[i].confidence = ochild.confidence; copy.children[i].parent = copy; copy.children[i].tags = ochild.getTagsCopy(); if (null != ml) copy.children[i].la = ml.get(copy.children[i].la.getId()); // replace Layer pointer in the copy if (null != ochild.children) { todo.add(new Object[]{copy.children[i], ochild.children}); } } } return root; } /** Check if this point or the edges to its children are closer to xx,yy than radius, in the 2D plane only. */ final boolean isNear(final float xx, final float yy, final float sqradius) { if (null == children) return sqradius > (Math.pow(xx - x, 2) + Math.pow(yy - y, 2)); // Else, check children: for (int i=0; i<children.length; i++) { if (sqradius > M.distancePointToSegmentSq(xx, yy, 0, // point x, y, 0, // origin of edge (children[i].x - x)/2, (children[i].y - y)/2, 0)) // end of half-edge to child { return true; } } // Check to parent's half segment return null != parent && sqradius > M.distancePointToSegmentSq(xx, yy, 0, // point x, y, 0, // origin of edge (x - parent.x)/2, (y - parent.y)/2, 0); // end of half-edge to parent } public final boolean hasChildren() { return null != children && children.length > 0; } public final int getChildrenCount() { if (null == children) return 0; return children.length; } /** Traverse the tree from this node all the way to the root node, * and count how many nodes apart this node is from the root node: * that is the degree. * Thanks to Johannes Schindelin. */ public final int computeDegree() { int result = 0; for (Node<T> node = this; node != null; node = node.parent) result++; return result; } /** Obtain the (only) list from node a to node b, * including both a (the first element) and b (the last element). * Thanks to Johannes Schindelin. */ public static<I> List<Node<I>> findPath(Node<I> a, Node<I> b) { int degreeA = a.computeDegree(), degreeB = b.computeDegree(); final List<Node<I>> listA = new ArrayList<Node<I>>(), listB = new ArrayList<Node<I>>(); // Traverse upstream the parent chain until finding nodes of the same degree for (; degreeB > degreeA; degreeB--, b = b.parent) listB.add(b); for (; degreeA > degreeB; degreeA--, a = a.parent) listA.add(a); // Traverse upstream the parent chain until finding a common parent node for (; a != b; a = a.parent, b = b.parent) { listA.add(a); listB.add(b); } // Add that common parent node listA.add(a); // add all in reverse for (final ListIterator<Node<I>> it = listB.listIterator(listB.size()); it.hasPrevious(); ) { listA.add(it.previous()); } return listA; } /** Return a map of node vs degree of that node, for the entire subtree (including this node). */ public HashMap<Node<T>,Integer> computeAllDegrees() { final HashMap<Node<T>,Integer> degrees = new HashMap<Node<T>, Integer>(); int degree = 1; ArrayList<Node<T>> next_level = new ArrayList<Node<T>>(); ArrayList<Node<T>> current_level = new ArrayList<Node<T>>(); current_level.add(this); do { for (final Node<T> nd : current_level) { degrees.put(nd, degree); if (null != nd.children) { for (final Node<T> child : nd.children) { next_level.add(child); } } } // rotate lists: current_level.clear(); ArrayList<Node<T>> tmp = current_level; current_level = next_level; next_level = tmp; degree++; } while (!current_level.isEmpty()); return degrees; } /** Assumes this is NOT a graph with cycles. Non-recursive to avoid stack overflows. */ final void setRoot() { // Works, but can be done in one pass TODO // // Find first the list of nodes from this node to the current root // and then proceed in reverse direction! final LinkedList<Node<T>> path = new LinkedList<Node<T>>(); path.add(this); Node<T> parent = this.parent; while (null != parent) { path.addFirst(parent); parent = parent.parent; } Node<T> newchild = path.removeFirst(); for (final Node<T> nd : path) { // Made nd the parent of newchild (was the opposite) // 1 - Find out the confidence of the edge to the child node: byte conf = MAX_EDGE_CONFIDENCE; for (int i=0; i<newchild.children.length; i++) { if (nd == newchild.children[i]) { conf = newchild.children[i].confidence; break; } } // 2 - Remove the child node from the parent's child list newchild.remove(nd); // 3 - Reverse: add newchild to nd (newchild was parent of nd) newchild.parent = null; nd.add(newchild, conf); // 4 - Prepare next step newchild = nd; } // As root: this.parent = null; // TODO Below, it should work, but it doesn't (?) // It results in all touched nodes not having a parent (all appear as 'S') /* Node child = this; Node parent = this.parent; while (null != parent) { // 1 - Find out the confidence of the edge to the child node: byte conf = MAX_EDGE_CONFIDENCE; for (int i=0; i<parent.children.length; i++) { if (child == parent.children[i]) { conf = parent.children[i].confidence; break; } } // 2 - Remove the child node from the parent's child list parent.remove(child); // 3 - Cache the parent's parent, since it will be overwriten in the next step Node pp = parent.parent; // 4 - Add the parent as a child of the child, with the same edge confidence parent.parent = null; // so it won't be refused child.add(parent, conf); // 5 - prepare next step child = parent; parent = pp; } // Make this node the root node this.parent = null; */ } /** Set the confidence value of this node with its parent. */ synchronized public final boolean setConfidence(final byte conf) { if (conf < 0 || conf > MAX_EDGE_CONFIDENCE) return false; confidence = conf; return true; } /** Adjust the confidence value of this node with its parent. */ final public boolean adjustConfidence(final int inc) { byte conf = (byte)((confidence&0xff) + inc); if (conf < 0 || conf > MAX_EDGE_CONFIDENCE) return false; confidence = conf; return true; } /** Returns -1 if not a child of this node. */ final byte getConfidence(final Node<T> child) { if (null == children) return -1; for (int i=0; i<children.length; i++) { if (child == children[i]) return children[i].confidence; } return -1; } final int indexOf(final Node<T> child) { if (null == children) return -1; for (int i=0; i<children.length; i++) { if (child == children[i]) return i; } return -1; } synchronized public final Node<T> findPreviousBranchOrRootPoint() { if (null == this.parent) return null; Node<T> parent = this.parent; while (true) { if (1 == parent.children.length) { if (null == parent.parent) return parent; // the root parent = parent.parent; continue; } return parent; } } /** Assumes there aren't any cycles. */ synchronized public final Node<T> findNextBranchOrEndPoint() { Node<T> child = this; while (true) { if (null == child.children || child.children.length > 1) return child; child = child.children[0]; } } public abstract boolean setData(T t); public abstract T getData(); public abstract T getDataCopy(); public abstract Node<T> newInstance(float x, float y, Layer layer); abstract public void paintData(final Graphics2D g, final Rectangle srcRect, final Tree<T> tree, final AffineTransform to_screen, final Color cc, final Layer active_layer); /** Expects Area in local coords. */ public abstract boolean intersects(Area a); /** May return a false positive but never a false negative. * Checks only for itself and towards its parent. */ public boolean isRoughlyInside(final Rectangle localbox) { if (null == parent) { return localbox.contains((int)this.x, (int)this.y); } else { return localbox.intersectsLine(parent.x, parent.y, this.x, this.y); } } /** Returns area in local coords. */ public Area getArea() { return new Area(new Rectangle2D.Float(x, y, 1, 1)); // a "little square" -- sinful! xDDD } /** Returns a list of Patch to link, which lay under the node. Use the given @param aff to transform the Node data before looking up targets. */ public Collection<Displayable> findLinkTargets(final AffineTransform to_world) { float x = this.x, y = this.y; if (null != to_world && !to_world.isIdentity()) { float[] fp = new float[]{x, y}; to_world.transform(fp, 0, fp, 0, 1); x = fp[0]; y = fp[1]; } return this.la.find(Patch.class, (int)x, (int)y, true); } /** The tags: * null: none * a Tag instance: just one tag * a Tag[] instance: more than one tag, sorted. * * The justification for this seemingly silly storage system is to take the minimal space possible, * while preserving the sortedness of tags. * As expected, the huge storage savings (used to be a TreeSet&lt;Tag&gt;, which has inside a TreeMap, which has a HashMap inside, and so on), * result in heavy computations required to add or remove a Tag, but these operations are rare and thus acceptable. */ Object tags = null; // private to the package /** @return true if the tag wasn't there already. */ synchronized public boolean addTag(final Tag tag) { if (null == this.tags) { // Currently no tags this.tags = tag; return true; } // If not null, there is already at least one tag final Tag[] t2; if (tags instanceof Tag[]) { // Currently more than one tag final Tag[] t1 = (Tag[])tags; for (final Tag t : t1) { if (t.equals(tag)) return false; } t2 = new Tag[t1.length + 1]; System.arraycopy(t1, 0, t2, 0, t1.length); // Add tag as last t2[t2.length -1] = tag; } else { // Currently only one tag if (tag.equals(this.tags)) return false; t2 = new Tag[]{(Tag)this.tags, tag}; } // Sort tags final ArrayList<Tag> al = new ArrayList<Tag>(t2.length); for (final Tag t : t2) al.add(t); Collections.sort(al); this.tags = al.toArray(t2); // reuse t2 array, has the right size return true; } /** @return true if the tag was there. */ synchronized public boolean removeTag(final Tag tag) { if (null == tags) return false; // no tags if (tags instanceof Tag[]) { // Currently more than one tag final Tag[] t1 = (Tag[])this.tags; for (int i=0; i<t1.length; i++) { if (t1[i].equals(tag)) { // remove: if (2 == t1.length) { this.tags = 0 == i ? t1[1] : t1[0]; } else { final Tag[] t2 = new Tag[t1.length -1]; if (0 == i) { System.arraycopy(t1, 1, t2, 0, t2.length); } else if (t1.length -1 == i) { System.arraycopy(t1, 0, t2, 0, t2.length); } else { System.arraycopy(t1, 0, t2, 0, i); System.arraycopy(t1, i+1, t2, i, t2.length - i); } this.tags = t2; } return true; } } return false; } else { // Currently just one tag if (this.tags.equals(tag)) { this.tags = null; } return false; } } protected final void copyProperties(final Node<?> nd) { this.confidence = nd.confidence; this.tags = nd.getTagsCopy(); } synchronized private final Object getTagsCopy() { if (null == this.tags) return null; if (this.tags instanceof Tag) return this.tags; final Tag[] t1 = (Tag[])this.tags; final Tag[] t2 = new Tag[t1.length]; System.arraycopy(t1, 0, t2, 0, t1.length); return t2; } synchronized public boolean hasTag(final Tag t) { if (null == this.tags) return false; return getTags().contains(t); } /** @return a shallow copy of the tags set, if any, or null. */ synchronized public Set<Tag> getTags() { if (null == tags) return null; final TreeSet<Tag> ts = new TreeSet<Tag>(); if (tags instanceof Tag[]) { for (final Tag t : (Tag[])this.tags) ts.add(t); } else { ts.add((Tag)this.tags); } return ts; } /** @return the tags, if any, or null. */ synchronized public Set<Tag> removeAllTags() { final Set<Tag> tags = getTags(); this.tags = null; return tags; } private void paintTags(final Graphics2D g, final int x, final int y, Color background_color) { final int ox = x + 20; int oy = y + 20; Color fontcolor = Color.blue; if (Color.red == background_color || Color.blue == background_color) fontcolor = Color.white; else background_color = Taggable.TAG_BACKGROUND; // so the Color indicated in the parameter background_color is used only as a flag Stroke stroke = g.getStroke(); g.setStroke(Taggable.DASHED_STROKE); g.setColor(background_color); g.drawLine(x, y, ox, oy); g.setStroke(stroke); final Tag[] tags = this.tags instanceof Tag[] ? (Tag[])this.tags : new Tag[]{(Tag)this.tags}; for (final Tag ob : tags) { String tag = ob.toString(); Dimension dim = Utils.getDimensions(tag, g.getFont()); final int arc = (int)(dim.height / 3.0f); RoundRectangle2D rr = new RoundRectangle2D.Float(ox, oy, dim.width+4, dim.height+2, arc, arc); g.setColor(background_color); g.fill(rr); g.setColor(fontcolor); g.drawString(tag, ox +2, oy +dim.height -1); oy += dim.height + 3; } } public void apply(final mpicbg.models.CoordinateTransform ct, final Area roi) { final float[] fp = new float[]{x, y}; ct.applyInPlace(fp); this.x = fp[0]; this.y = fp[1]; } public void apply(final VectorDataTransform vlocal) { for (final VectorDataTransform.ROITransform rt : vlocal.transforms) { // Apply only the first one that contains the point if (rt.roi.contains(x, y)) { final float[] fp = new float[]{x, y}; rt.ct.applyInPlace(fp); x = fp[0]; y = fp[1]; break; } } } public Point3f asPoint() { return new Point3f(x, y, (float)la.getZ()); } /** Apply @param aff to the data, not to the x,y position. */ protected void transformData(final AffineTransform aff) {} // ==================== Node Iterators /** Stateful abstract Node iterator. */ static public abstract class NodeIterator<I> implements Iterator<Node<I>> { Node<I> next; public NodeIterator(final Node<I> first) { this.next = first; } @Override public boolean hasNext() { return null != next; } @Override public void remove() {} } static public abstract class SubtreeIterator<I> extends NodeIterator<I> { final LinkedList<Node<I>> todo = new LinkedList<Node<I>>(); public SubtreeIterator(final Node<I> first) { super(first); todo.add(first); } @Override public boolean hasNext() { return todo.size() > 0; } } /** For a given starting node, iterates over the complete set of children nodes, recursively and breadth-first. */ static public class BreadthFirstSubtreeIterator<I> extends SubtreeIterator<I> { public BreadthFirstSubtreeIterator(final Node<I> first) { super(first); } @Override public Node<I> next() { if (todo.isEmpty()) { next = null; return null; } next = todo.removeFirst(); if (null != next.children) { for (int i=0; i<next.children.length; i++) todo.add(next.children[i]); } return next; } } static public abstract class FilteredIterator<I> extends SubtreeIterator<I> { public FilteredIterator(final Node<I> first) { super(first); prepareNext(); } public abstract boolean accept(final Node<I> node); private final void prepareNext() { while (todo.size() > 0) { final Node<I> nd = todo.removeFirst(); if (null != nd.children) { for (int i=0; i<nd.children.length; i++) todo.add(nd.children[i]); } if (accept(nd)) { next = nd; return; } } next = null; } @Override public boolean hasNext() { return null != next; } @Override public Node<I> next() { try { return next; } finally { prepareNext(); } //final Node<I> node = next; //prepareNext(); //return node; } } static public class BranchAndEndNodeIterator<I> extends FilteredIterator<I> { public BranchAndEndNodeIterator(final Node <I> first) { super(first); } @Override public boolean accept(final Node<I> node) { return 1 != node.getChildrenCount(); } } static public class BranchNodeIterator<I> extends FilteredIterator<I> { public BranchNodeIterator(final Node <I> first) { super(first); } @Override public boolean accept(final Node<I> node) { return node.getChildrenCount() > 1; } } static public class EndNodeIterator<I> extends FilteredIterator<I> { public EndNodeIterator(final Node <I> first) { super(first); } @Override public boolean accept(final Node<I> node) { return 0 == node.getChildrenCount(); } } /** For a given starting node, iterates all the way to the next end node or branch node, inclusive. */ static public class SlabIterator<I> extends SubtreeIterator<I> { public SlabIterator(final Node<I> first) { super(first); } @Override public Node<I> next() { if (todo.isEmpty()) { next = null; return null; // reached an end node or branch node } final Node<I> next = todo.removeFirst(); if (null == next.children || next.children.length > 1) { this.next = null; return next; // reached an end node or branch node } todo.add(next.children[0]); this.next = next; return next; } } /** Read-only Collection with a very expensive size(). * It is meant for traversing Node subtrees. */ static public class NodeCollection<I> extends AbstractCollection<Node<I>> { final Node<I> first; final Class<?> type; public NodeCollection(final Node<I> first, final Class<?> type) { this.first = first; this.type = type; } @Override public Iterator<Node<I>> iterator() { try { return (Iterator<Node<I>>) type.getConstructor(Node.class).newInstance(first); } catch (NoSuchMethodException nsme) { IJError.print(nsme); } catch (InvocationTargetException ite) { IJError.print(ite); } catch (IllegalAccessException iae) { IJError.print(iae); } catch (InstantiationException ie) { IJError.print(ie); } return null; } /** Override to avoid calling size(). */ @Override public boolean isEmpty() { return null == first; } /** WARNING: O(n) operation: will traverse the whole collection. */ @Override public int size() { int count = 0; final Iterator<Node<I>> it = iterator(); while (it.hasNext()) { count++; it.next(); } return count; } /** Override to avoid calling size(), which would iterate the whole list just for that. */ @Override public Node<I>[] toArray() { Node<I>[] a = (Node<I>[])new Node[10]; int next = 0; for (final Iterator<Node<I>> it = iterator(); it.hasNext(); ) { if (a.length == next) { Node[] b = new Node[a.length + 10]; System.arraycopy(a, 0, b, 0, a.length); a = b; } a[next++] = it.next(); } return next < a.length ? Arrays.copyOf(a, next) : a; } @Override public<Y> Y[] toArray(Y[] a) { Node<I>[] b = toArray(); if (a.length < b.length) { return (Y[])b; } System.arraycopy(b, 0, a, 0, b.length); if (a.length > b.length) a[b.length] = null; // null-terminate return a; } } // ============= Operations on collections of nodes /** An operation to be applied to a specific Node. */ static public interface Operation<I> { public void apply(final Node<I> nd) throws Exception; } protected final void apply(final Operation<T> op, final Iterator<Node<T>> nodes) throws Exception { while (nodes.hasNext()) op.apply(nodes.next()); } /** Apply @param op to this Node and all its subtree nodes. */ public void applyToSubtree(final Operation<T> op) throws Exception { apply(op, new BreadthFirstSubtreeIterator<T>(this)); /* final Node<?> first = this; apply(op, new Iterable<Node<?>>() { public Iterator<Node<?>> iterator() { return new NodeIterator(first) { public final boolean hasNext() { if (null == next.children) return false; else if (1 == next.children.length) { next = next.children[0]; return true; } return false; } }; } }); */ } /** Apply @param op to this Node and all its subtree nodes until reaching a branch node or end node, inclusive. */ public void applyToSlab(final Operation<T> op) throws Exception { apply(op, new SlabIterator<T>(this)); } public boolean hasSameTags(final Node<?> other) { if (null == this.tags && null == other.tags) return true; final Set<Tag> t1 = getTags(), t2 = other.getTags(); if (null == t1 || null == t2) return false; // at least one is not null t1.removeAll(t2); return t1.isEmpty(); } }
false
true
final Runnable paint(final Graphics2D g, final Layer active_layer, final boolean active, final Rectangle srcRect, final double magnification, final Collection<Node<T>> to_paint, final Tree<T> tree, final AffineTransform to_screen, final boolean with_arrows, final boolean with_confidence_boxes, final boolean with_data, Color above, Color below) { // The fact that this method is called indicates that this node is to be painted and by definition is inside the Set to_paint. final double actZ = active_layer.getZ(); final double thisZ = this.la.getZ(); final Color node_color; if (null == this.color) { // this node doesn't have its color set, so use tree color and given above/below colors node_color = tree.color; } else { node_color = this.color; // Depth cue colors may not be in use: if (tree.color == above) above = this.color; if (tree.color == below) below = this.color; } // Which edge color? final Color local_edge_color; if (active_layer == this.la) { local_edge_color = node_color; } // default color else if (actZ > thisZ) { local_edge_color = below; } else if (actZ < thisZ) local_edge_color = above; else local_edge_color = node_color; if (with_data) paintData(g, srcRect, tree, to_screen, local_edge_color, active_layer); //if (null == children && !paint) return null; final boolean paint = with_arrows && null != tags; // with_arrows acts as a flag for both arrows and tags if (null == parent && !paint) return null; final float[] fps = new float[4]; final int parent_x, parent_y; fps[0] = this.x; fps[1] = this.y; if (null == parent) { parent_x = parent_y = 0; tree.at.transform(fps, 0, fps, 0, 1); } else { fps[2] = parent.x; fps[3] = parent.y; tree.at.transform(fps, 0, fps, 0, 2); parent_x = (int)((fps[2] - srcRect.x) * magnification); parent_y = (int)((fps[3] - srcRect.y) * magnification); } // To screen coords: final int x = (int)((fps[0] - srcRect.x) * magnification); final int y = (int)((fps[1] - srcRect.y) * magnification); final Runnable tagsTask; if (paint) { tagsTask = new Runnable() { public void run() { paintTags(g, x, y, local_edge_color); } }; } else tagsTask = null; if (null == parent) return tagsTask; synchronized (this) { if (null != parent) { // Does the line from parent to this cross the srcRect? // Or what is the same, does the line from parent to this cross any of the edges of the srcRect? // Paint full edge, but perhaps in two halves of different colors if (parent.la == this.la && this.la == active_layer) { // in treeline color // Full edge in local color g.setColor(local_edge_color); g.drawLine(x, y, parent_x, parent_y); if (with_arrows) g.fill(M.createArrowhead(parent_x, parent_y, x, y, magnification)); } else if (this.la == active_layer) { // Proximal half in this color g.setColor(local_edge_color); g.drawLine(parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2, x, y); if (with_arrows) g.fill(M.createArrowhead(parent_x, parent_y, x, y, magnification)); // Distal either red or blue: Color c = local_edge_color; // If other towards higher Z: if (actZ < parent.la.getZ()) c = above; // If other towards lower Z: else if (actZ > parent.la.getZ()) c = below; // g.setColor(c); g.drawLine(parent_x, parent_y, parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2); } else if (parent.la == active_layer) { // Distal half in the Displayable or Node color g.setColor(node_color); g.drawLine(parent_x, parent_y, parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2); // Proximal half in either red or blue: g.setColor(local_edge_color); g.drawLine(parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2, x, y); if (with_arrows) g.fill(M.createArrowhead(parent_x, parent_y, x, y, magnification)); } else if (thisZ < actZ && actZ < parent.la.getZ()) { // proximal half in red g.setColor(below); g.drawLine(x, y, parent_x + (x - parent_x)/2, (parent_y + (y - parent_y)/2)); if (with_arrows) g.fill(M.createArrowhead(parent_x, parent_y, x, y, magnification)); // distal half in blue g.setColor(above); g.drawLine(parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2, parent_x, parent_y); } else if (thisZ > actZ && actZ > parent.la.getZ()) { // proximal half in blue g.setColor(above); g.drawLine(x, y, parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2); if (with_arrows) g.fill(M.createArrowhead(parent_x, parent_y, x, y, magnification)); // distal half in red g.setColor(below); g.drawLine(parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2, parent_x, parent_y); } else if ((thisZ < actZ && parent.la.getZ() < actZ) || (thisZ > actZ && parent.la.getZ() > actZ)) { g.setColor(local_edge_color); if (to_paint.contains(parent)) { // full edge g.drawLine(x, y, parent_x, parent_y); } else { // paint proximal half g.drawLine(x, y, parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2); } if (with_arrows) g.fill(M.createArrowhead(parent_x, parent_y, x, y, magnification)); } } if (null != children) { final float[] fp = new float[2]; for (final Node<T> child : children) { if (to_paint.contains(child)) continue; fp[0] = child.x; fp[1] = child.y; tree.at.transform(fp, 0, fp, 0, 1); final int cx = (int)(((int)fp[0] - srcRect.x) * magnification), cy = (int)(((int)fp[1] - srcRect.y) * magnification); if (child.la == this.la){ // child in same layer but outside the field of view // paint full edge to it g.setColor(null == child.color ? tree.color : child.color); g.drawLine(x, y, cx, cy); if (with_arrows) g.fill(M.createArrowhead(x, y, cx, cy, magnification)); } else { if (child.la.getZ() < actZ) g.setColor(Color.red); else if (child.la.getZ() > actZ) g.setColor(Color.blue); // paint half edge to the child g.drawLine(x, y, x + (cx - x)/2, y + (cy - y)/2); } } } if (null != parent && active && with_confidence_boxes && (active_layer == this.la || active_layer == parent.la || (thisZ < actZ && actZ < parent.la.getZ()))) { // Draw confidence half-way through the edge final String s = Integer.toString(confidence); final Dimension dim = Utils.getDimensions(s, g.getFont()); g.setColor(Color.white); final int xc = (int)(parent_x + (x - parent_x)/2), yc = (int)(parent_y + (y - parent_y)/2); // y + 0.5*chy - 0.5y = (y + chy)/2 g.fillRect(xc, yc, dim.width+2, dim.height+2); g.setColor(Color.black); g.drawString(s, xc+1, yc+dim.height+1); } } return tagsTask; }
final Runnable paint(final Graphics2D g, final Layer active_layer, final boolean active, final Rectangle srcRect, final double magnification, final Collection<Node<T>> to_paint, final Tree<T> tree, final AffineTransform to_screen, final boolean with_arrows, final boolean with_confidence_boxes, final boolean with_data, Color above, Color below) { // The fact that this method is called indicates that this node is to be painted and by definition is inside the Set to_paint. final double actZ = active_layer.getZ(); final double thisZ = this.la.getZ(); final Color node_color; if (null == this.color) { // this node doesn't have its color set, so use tree color and given above/below colors node_color = tree.color; } else { node_color = this.color; // Depth cue colors may not be in use: if (tree.color == above) above = this.color; if (tree.color == below) below = this.color; } // Which edge color? final Color local_edge_color; if (active_layer == this.la) { local_edge_color = node_color; } // default color else if (actZ > thisZ) { local_edge_color = below; } else if (actZ < thisZ) local_edge_color = above; else local_edge_color = node_color; if (with_data) paintData(g, srcRect, tree, to_screen, local_edge_color, active_layer); //if (null == children && !paint) return null; //final boolean paint = with_arrows && null != tags; // with_arrows acts as a flag for both arrows and tags //if (null == parent && !paint) return null; final float[] fps = new float[4]; final int parent_x, parent_y; fps[0] = this.x; fps[1] = this.y; if (null == parent) { parent_x = parent_y = 0; tree.at.transform(fps, 0, fps, 0, 1); } else { fps[2] = parent.x; fps[3] = parent.y; tree.at.transform(fps, 0, fps, 0, 2); parent_x = (int)((fps[2] - srcRect.x) * magnification); parent_y = (int)((fps[3] - srcRect.y) * magnification); } // To screen coords: final int x = (int)((fps[0] - srcRect.x) * magnification); final int y = (int)((fps[1] - srcRect.y) * magnification); final Runnable tagsTask; if (with_arrows && null != tags) { tagsTask = new Runnable() { public void run() { paintTags(g, x, y, local_edge_color); } }; } else tagsTask = null; //if (null == parent) return tagsTask; synchronized (this) { if (null != parent) { // Does the line from parent to this cross the srcRect? // Or what is the same, does the line from parent to this cross any of the edges of the srcRect? // Paint full edge, but perhaps in two halves of different colors if (parent.la == this.la && this.la == active_layer) { // in treeline color // Full edge in local color g.setColor(local_edge_color); g.drawLine(x, y, parent_x, parent_y); if (with_arrows) g.fill(M.createArrowhead(parent_x, parent_y, x, y, magnification)); } else if (this.la == active_layer) { // Proximal half in this color g.setColor(local_edge_color); g.drawLine(parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2, x, y); if (with_arrows) g.fill(M.createArrowhead(parent_x, parent_y, x, y, magnification)); // Distal either red or blue: Color c = local_edge_color; // If other towards higher Z: if (actZ < parent.la.getZ()) c = above; // If other towards lower Z: else if (actZ > parent.la.getZ()) c = below; // g.setColor(c); g.drawLine(parent_x, parent_y, parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2); } else if (parent.la == active_layer) { // Distal half in the Displayable or Node color g.setColor(node_color); g.drawLine(parent_x, parent_y, parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2); // Proximal half in either red or blue: g.setColor(local_edge_color); g.drawLine(parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2, x, y); if (with_arrows) g.fill(M.createArrowhead(parent_x, parent_y, x, y, magnification)); } else if (thisZ < actZ && actZ < parent.la.getZ()) { // proximal half in red g.setColor(below); g.drawLine(x, y, parent_x + (x - parent_x)/2, (parent_y + (y - parent_y)/2)); if (with_arrows) g.fill(M.createArrowhead(parent_x, parent_y, x, y, magnification)); // distal half in blue g.setColor(above); g.drawLine(parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2, parent_x, parent_y); } else if (thisZ > actZ && actZ > parent.la.getZ()) { // proximal half in blue g.setColor(above); g.drawLine(x, y, parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2); if (with_arrows) g.fill(M.createArrowhead(parent_x, parent_y, x, y, magnification)); // distal half in red g.setColor(below); g.drawLine(parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2, parent_x, parent_y); } else if ((thisZ < actZ && parent.la.getZ() < actZ) || (thisZ > actZ && parent.la.getZ() > actZ)) { g.setColor(local_edge_color); if (to_paint.contains(parent)) { // full edge g.drawLine(x, y, parent_x, parent_y); } else { // paint proximal half g.drawLine(x, y, parent_x + (x - parent_x)/2, parent_y + (y - parent_y)/2); } if (with_arrows) g.fill(M.createArrowhead(parent_x, parent_y, x, y, magnification)); } } else if (with_arrows && !active) { // paint a gray handle for the root g.setColor(active_layer == this.la ? Color.gray : local_edge_color); g.fillOval((int)x - 6, (int)y - 6, 11, 11); g.setColor(Color.black); g.drawString("S", (int)x -3, (int)y + 4); // TODO ensure Font is proper } if (null != children) { final float[] fp = new float[2]; for (final Node<T> child : children) { if (to_paint.contains(child)) continue; fp[0] = child.x; fp[1] = child.y; tree.at.transform(fp, 0, fp, 0, 1); final int cx = (int)(((int)fp[0] - srcRect.x) * magnification), cy = (int)(((int)fp[1] - srcRect.y) * magnification); if (child.la == this.la){ // child in same layer but outside the field of view // paint full edge to it g.setColor(null == child.color ? tree.color : child.color); g.drawLine(x, y, cx, cy); if (with_arrows) g.fill(M.createArrowhead(x, y, cx, cy, magnification)); } else { if (child.la.getZ() < actZ) g.setColor(Color.red); else if (child.la.getZ() > actZ) g.setColor(Color.blue); // paint half edge to the child g.drawLine(x, y, x + (cx - x)/2, y + (cy - y)/2); } } } if (null != parent && active && with_confidence_boxes && (active_layer == this.la || active_layer == parent.la || (thisZ < actZ && actZ < parent.la.getZ()))) { // Draw confidence half-way through the edge final String s = Integer.toString(confidence); final Dimension dim = Utils.getDimensions(s, g.getFont()); g.setColor(Color.white); final int xc = (int)(parent_x + (x - parent_x)/2), yc = (int)(parent_y + (y - parent_y)/2); // y + 0.5*chy - 0.5y = (y + chy)/2 g.fillRect(xc, yc, dim.width+2, dim.height+2); g.setColor(Color.black); g.drawString(s, xc+1, yc+dim.height+1); } } return tagsTask; }
diff --git a/src/semanticMarkup/ling/extract/lib/NumericalChunkProcessor.java b/src/semanticMarkup/ling/extract/lib/NumericalChunkProcessor.java index d5860ded..f2f7cab3 100644 --- a/src/semanticMarkup/ling/extract/lib/NumericalChunkProcessor.java +++ b/src/semanticMarkup/ling/extract/lib/NumericalChunkProcessor.java @@ -1,137 +1,137 @@ package semanticMarkup.ling.extract.lib; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Set; import semanticMarkup.core.description.DescriptionTreatmentElement; import semanticMarkup.know.ICharacterKnowledgeBase; import semanticMarkup.know.IGlossary; import semanticMarkup.know.IPOSKnowledgeBase; import semanticMarkup.ling.chunk.Chunk; import semanticMarkup.ling.chunk.ChunkType; import semanticMarkup.ling.extract.AbstractChunkProcessor; import semanticMarkup.ling.extract.ProcessingContext; import semanticMarkup.ling.extract.ProcessingContextState; import semanticMarkup.ling.learn.ITerminologyLearner; import semanticMarkup.ling.transform.IInflector; import com.google.inject.Inject; import com.google.inject.name.Named; /** * NPListChunkProcessor processes chunks of ChunkType.NUMERICALS * @author rodenhausen */ public class NumericalChunkProcessor extends AbstractChunkProcessor { private boolean attachToLast; /** * @param inflector * @param glossary * @param terminologyLearner * @param characterKnowledgeBase * @param posKnowledgeBase * @param baseCountWords * @param locationPrepositions * @param clusters * @param units * @param equalCharacters * @param numberPattern * @param attachToLast * @param times */ @Inject public NumericalChunkProcessor(IInflector inflector, IGlossary glossary, ITerminologyLearner terminologyLearner, ICharacterKnowledgeBase characterKnowledgeBase, @Named("LearnedPOSKnowledgeBase") IPOSKnowledgeBase posKnowledgeBase, @Named("BaseCountWords")Set<String> baseCountWords, @Named("LocationPrepositionWords")Set<String> locationPrepositions, @Named("Clusters")Set<String> clusters, @Named("Units")String units, @Named("EqualCharacters")HashMap<String, String> equalCharacters, @Named("NumberPattern")String numberPattern, @Named("AttachToLast")boolean attachToLast, @Named("TimesWords")String times) { super(inflector, glossary, terminologyLearner, characterKnowledgeBase, posKnowledgeBase, baseCountWords, locationPrepositions, clusters, units, equalCharacters, numberPattern, attachToLast, times); } @Override protected List<DescriptionTreatmentElement> processChunk(Chunk chunk, ProcessingContext processingContext) { ProcessingContextState processingContextState = processingContext.getCurrentState(); //** find parents, modifiers //TODO: check the use of [ and ( in extreme values //ArrayList<Element> parents = lastStructures(); String text = chunk.getTerminalsText().replaceAll("�", "-"); boolean resetFrom = false; if(text.matches(".*\\bto \\d.*")){ //m[mostly] to 6 m ==> m[mostly] 0-6 m text = text.replaceFirst("to\\s+", "0-"); resetFrom = true; } LinkedList<DescriptionTreatmentElement> parents = this.attachToLast? lastStructures(processingContext, processingContextState ) : processingContextState.getSubjects(); /*String modifier1 = ""; //m[mostly] [4-]8�12[-19] mm m[distally]; m[usually] 1.5-2 times n[size[{longer} than {wide}]]:consider a constraint String modifier2 = ""; modifier1 = text.replaceFirst("\\[?\\d.*$", ""); String rest = text.replace(modifier1, ""); modifier1 = modifier1.replaceAll("(\\w\\[|\\]|\\{|\\})", "").trim(); modifier2 = rest.replaceFirst(".*?(\\d|\\[|\\+|\\-|\\]|%|\\s|" + units + ")+\\s?(?=[a-z]|$)", "");// 4-5[+] String content = rest.replace(modifier2, "").replaceAll("(\\{|\\})", "").trim(); modifier2 = modifier2.replaceAll("(\\w+\\[|\\]|\\{|\\})", "").trim(); */ String content = ""; for(Chunk childChunk : chunk.getChunks()) { if(!childChunk.isOfChunkType(ChunkType.MODIFIER)) content += childChunk.getTerminalsText() + " "; } List<Chunk> modifiers = chunk.getChunks(ChunkType.MODIFIER); modifiers.addAll(processingContextState.getUnassignedModifiers()); String character = text.indexOf("size") >= 0 || content.indexOf('/') > 0 || content.indexOf('%') > 0 || content.indexOf('.') > 0 ? "size" : null; character = "size"; LinkedList<DescriptionTreatmentElement> characters = annotateNumericals(content, character, modifiers, lastStructures(processingContext, processingContextState), resetFrom, processingContextState); processingContextState.setLastElements(characters); if(parents.isEmpty()) { processingContextState.getUnassignedCharacters().addAll(characters); - } else { + }/* else { for(DescriptionTreatmentElement parent : parents) { for(DescriptionTreatmentElement characterElement : characters) { parent.addTreatmentElement(characterElement); } } - } + }*/ processingContextState.setCommaAndOrEosEolAfterLastElements(false); return characters; } //** find parents, modifiers //TODO: check the use of [ and ( in extreme values //ArrayList<Element> parents = lastStructures(); /*String text = ck.toString().replaceAll("�", "-"); boolean resetfrom = false; if(text.matches(".*\\bto \\d.*")){ //m[mostly] to 6 m ==> m[mostly] 0-6 m text = text.replaceFirst("to\\s+", "0-"); resetfrom = true; } ArrayList<Element> parents = this.attachToLast? lastStructures() : subjects; if(printAttach && subjects.get(0).getAttributeValue("name").compareTo(lastStructures().get(0).getAttributeValue("name")) != 0){ log(LogLevel.DEBUG, text + " attached to "+parents.get(0).getAttributeValue("name")); } if(debugNum){ log(LogLevel.DEBUG, ); log(LogLevel.DEBUG, ">>>>>>>>>>>>>"+text); } String modifier1 = "";//m[mostly] [4-]8�12[-19] mm m[distally]; m[usually] 1.5-2 times n[size[{longer} than {wide}]]:consider a constraint String modifier2 = ""; modifier1 = text.replaceFirst("\\[?\\d.*$", ""); String rest = text.replace(modifier1, ""); modifier1 =modifier1.replaceAll("(\\w\\[|\\]|\\{|\\})", "").trim(); modifier2 = rest.replaceFirst(".*?(\\d|\\[|\\+|\\-|\\]|%|\\s|"+ChunkedSentence.units+")+\\s?(?=[a-z]|$)", "");//4-5[+] String content = rest.replace(modifier2, "").replaceAll("(\\{|\\})", "").trim(); modifier2 = modifier2.replaceAll("(\\w+\\[|\\]|\\{|\\})", "").trim(); ArrayList<Element> chars = annotateNumericals(content, text.indexOf("size")>=0 || content.indexOf('/')>0 || content.indexOf('%')>0 || content.indexOf('.')>0? "size" : null, (modifier1+";"+modifier2).replaceAll("(^\\W|\\W$)", ""), lastStructures(), resetfrom); updateLatestElements(chars);*/ }
false
true
protected List<DescriptionTreatmentElement> processChunk(Chunk chunk, ProcessingContext processingContext) { ProcessingContextState processingContextState = processingContext.getCurrentState(); //** find parents, modifiers //TODO: check the use of [ and ( in extreme values //ArrayList<Element> parents = lastStructures(); String text = chunk.getTerminalsText().replaceAll("�", "-"); boolean resetFrom = false; if(text.matches(".*\\bto \\d.*")){ //m[mostly] to 6 m ==> m[mostly] 0-6 m text = text.replaceFirst("to\\s+", "0-"); resetFrom = true; } LinkedList<DescriptionTreatmentElement> parents = this.attachToLast? lastStructures(processingContext, processingContextState ) : processingContextState.getSubjects(); /*String modifier1 = ""; //m[mostly] [4-]8�12[-19] mm m[distally]; m[usually] 1.5-2 times n[size[{longer} than {wide}]]:consider a constraint String modifier2 = ""; modifier1 = text.replaceFirst("\\[?\\d.*$", ""); String rest = text.replace(modifier1, ""); modifier1 = modifier1.replaceAll("(\\w\\[|\\]|\\{|\\})", "").trim(); modifier2 = rest.replaceFirst(".*?(\\d|\\[|\\+|\\-|\\]|%|\\s|" + units + ")+\\s?(?=[a-z]|$)", "");// 4-5[+] String content = rest.replace(modifier2, "").replaceAll("(\\{|\\})", "").trim(); modifier2 = modifier2.replaceAll("(\\w+\\[|\\]|\\{|\\})", "").trim(); */ String content = ""; for(Chunk childChunk : chunk.getChunks()) { if(!childChunk.isOfChunkType(ChunkType.MODIFIER)) content += childChunk.getTerminalsText() + " "; } List<Chunk> modifiers = chunk.getChunks(ChunkType.MODIFIER); modifiers.addAll(processingContextState.getUnassignedModifiers()); String character = text.indexOf("size") >= 0 || content.indexOf('/') > 0 || content.indexOf('%') > 0 || content.indexOf('.') > 0 ? "size" : null; character = "size"; LinkedList<DescriptionTreatmentElement> characters = annotateNumericals(content, character, modifiers, lastStructures(processingContext, processingContextState), resetFrom, processingContextState); processingContextState.setLastElements(characters); if(parents.isEmpty()) { processingContextState.getUnassignedCharacters().addAll(characters); } else { for(DescriptionTreatmentElement parent : parents) { for(DescriptionTreatmentElement characterElement : characters) { parent.addTreatmentElement(characterElement); } } } processingContextState.setCommaAndOrEosEolAfterLastElements(false); return characters; }
protected List<DescriptionTreatmentElement> processChunk(Chunk chunk, ProcessingContext processingContext) { ProcessingContextState processingContextState = processingContext.getCurrentState(); //** find parents, modifiers //TODO: check the use of [ and ( in extreme values //ArrayList<Element> parents = lastStructures(); String text = chunk.getTerminalsText().replaceAll("�", "-"); boolean resetFrom = false; if(text.matches(".*\\bto \\d.*")){ //m[mostly] to 6 m ==> m[mostly] 0-6 m text = text.replaceFirst("to\\s+", "0-"); resetFrom = true; } LinkedList<DescriptionTreatmentElement> parents = this.attachToLast? lastStructures(processingContext, processingContextState ) : processingContextState.getSubjects(); /*String modifier1 = ""; //m[mostly] [4-]8�12[-19] mm m[distally]; m[usually] 1.5-2 times n[size[{longer} than {wide}]]:consider a constraint String modifier2 = ""; modifier1 = text.replaceFirst("\\[?\\d.*$", ""); String rest = text.replace(modifier1, ""); modifier1 = modifier1.replaceAll("(\\w\\[|\\]|\\{|\\})", "").trim(); modifier2 = rest.replaceFirst(".*?(\\d|\\[|\\+|\\-|\\]|%|\\s|" + units + ")+\\s?(?=[a-z]|$)", "");// 4-5[+] String content = rest.replace(modifier2, "").replaceAll("(\\{|\\})", "").trim(); modifier2 = modifier2.replaceAll("(\\w+\\[|\\]|\\{|\\})", "").trim(); */ String content = ""; for(Chunk childChunk : chunk.getChunks()) { if(!childChunk.isOfChunkType(ChunkType.MODIFIER)) content += childChunk.getTerminalsText() + " "; } List<Chunk> modifiers = chunk.getChunks(ChunkType.MODIFIER); modifiers.addAll(processingContextState.getUnassignedModifiers()); String character = text.indexOf("size") >= 0 || content.indexOf('/') > 0 || content.indexOf('%') > 0 || content.indexOf('.') > 0 ? "size" : null; character = "size"; LinkedList<DescriptionTreatmentElement> characters = annotateNumericals(content, character, modifiers, lastStructures(processingContext, processingContextState), resetFrom, processingContextState); processingContextState.setLastElements(characters); if(parents.isEmpty()) { processingContextState.getUnassignedCharacters().addAll(characters); }/* else { for(DescriptionTreatmentElement parent : parents) { for(DescriptionTreatmentElement characterElement : characters) { parent.addTreatmentElement(characterElement); } } }*/ processingContextState.setCommaAndOrEosEolAfterLastElements(false); return characters; }
diff --git a/modules/dCache/org/dcache/pool/movers/RemoteHttpDataTransferProtocol_1.java b/modules/dCache/org/dcache/pool/movers/RemoteHttpDataTransferProtocol_1.java index 1eb308cb46..9fd633756a 100755 --- a/modules/dCache/org/dcache/pool/movers/RemoteHttpDataTransferProtocol_1.java +++ b/modules/dCache/org/dcache/pool/movers/RemoteHttpDataTransferProtocol_1.java @@ -1,155 +1,155 @@ package org.dcache.pool.movers; /** * @author Patrick F. * @author Timur Perelmutov. [email protected] * @version 0.0, 28 Jun 2002 */ import diskCacheV111.vehicles.*; import diskCacheV111.util.Base64; import diskCacheV111.util.PnfsId; import diskCacheV111.util.CacheException; import org.dcache.pool.repository.Allocator; import dmg.cells.nucleus.*; import java.io.*; import java.net.URL; import java.net.URLConnection; import java.net.HttpURLConnection; import java.nio.ByteBuffer; import org.dcache.pool.repository.RepositortyChannel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RemoteHttpDataTransferProtocol_1 implements MoverProtocol { private final static Logger _log = LoggerFactory.getLogger(RemoteHttpDataTransferProtocol_1.class); private final static Logger _logSpaceAllocation = LoggerFactory.getLogger("logger.dev.org.dcache.poolspacemonitor." + RemoteHttpDataTransferProtocol_1.class.getName()); public static final int READ = 1; public static final int WRITE = 2; public static final long SERVER_LIFE_SPAN= 60 * 5 * 1000; /* 5 minutes */ private static final int INC_SPACE = (50*1024*1024); private long allocated_space = 0; private long last_transfer_time = System.currentTimeMillis(); private final CellEndpoint cell; private RemoteHttpDataTransferProtocolInfo remoteHttpProtocolInfo; private long starttime; private URL remoteURL; private volatile long transfered = 0; private boolean changed; public RemoteHttpDataTransferProtocol_1(CellEndpoint cell) { this.cell = cell; say("RemoteHTTPDataTransferAgent_1 created"); } private void say(String str){ _log.info(str); } public void runIO(RepositortyChannel fileChannel, ProtocolInfo protocol, StorageInfo storage, PnfsId pnfsId , Allocator allocator, IoMode access) throws Exception { say("runIO()\n\tprotocol="+ protocol+",\n\tStorageInfo="+storage+",\n\tPnfsId="+pnfsId+ ",\n\taccess ="+ access); if(! (protocol instanceof RemoteHttpDataTransferProtocolInfo)) { throw new CacheException( "protocol info is not RemoteHttpDataTransferProtocolInfo"); } starttime = System.currentTimeMillis(); remoteHttpProtocolInfo = (RemoteHttpDataTransferProtocolInfo) protocol; remoteURL = new URL(remoteHttpProtocolInfo.getSourceHttpUrl()); URLConnection connection = remoteURL.openConnection(); if(! (connection instanceof HttpURLConnection)) { throw new CacheException("wrong URL connection type"); } HttpURLConnection httpconnection = (HttpURLConnection) connection; String userInfo = remoteURL.getUserInfo(); if (userInfo != null) { // set the authentication String userPassEncoding = Base64.byteArrayToBase64(userInfo.getBytes()); httpconnection.setRequestProperty("Authorization", "Basic " + userPassEncoding); } if( access == IoMode.WRITE) { httpconnection.setDoInput(true); httpconnection.setDoOutput(false); InputStream httpinput = httpconnection.getInputStream(); byte[] buffer = new byte[remoteHttpProtocolInfo.getBufferSize()]; ByteBuffer bb = ByteBuffer.wrap(buffer); int read = 0; _logSpaceAllocation.debug("ALLOC: " + pnfsId + " : " + INC_SPACE); allocator.allocate(INC_SPACE); allocated_space+=INC_SPACE; while((read = httpinput.read(buffer)) != -1) { - bb.clear(); last_transfer_time = System.currentTimeMillis(); if(transfered+read > allocated_space) { _logSpaceAllocation.debug("ALLOC: " + pnfsId + " : " + INC_SPACE); allocator.allocate(INC_SPACE); allocated_space+=INC_SPACE; } - bb.flip(); + bb.limit(read); fileChannel.write(bb); changed = true; transfered +=read; + bb.clear(); } say("runIO() wrote "+transfered+"bytes"); } else { httpconnection.setDoInput(false); httpconnection.setDoOutput(true); OutputStream httpoutput = httpconnection.getOutputStream(); } say(" runIO() done"); } public long getLastTransferred() { return last_transfer_time; } public long getBytesTransferred() { return transfered; } public long getTransferTime() { return System.currentTimeMillis() -starttime; } public boolean wasChanged() { return changed; } }
false
true
public void runIO(RepositortyChannel fileChannel, ProtocolInfo protocol, StorageInfo storage, PnfsId pnfsId , Allocator allocator, IoMode access) throws Exception { say("runIO()\n\tprotocol="+ protocol+",\n\tStorageInfo="+storage+",\n\tPnfsId="+pnfsId+ ",\n\taccess ="+ access); if(! (protocol instanceof RemoteHttpDataTransferProtocolInfo)) { throw new CacheException( "protocol info is not RemoteHttpDataTransferProtocolInfo"); } starttime = System.currentTimeMillis(); remoteHttpProtocolInfo = (RemoteHttpDataTransferProtocolInfo) protocol; remoteURL = new URL(remoteHttpProtocolInfo.getSourceHttpUrl()); URLConnection connection = remoteURL.openConnection(); if(! (connection instanceof HttpURLConnection)) { throw new CacheException("wrong URL connection type"); } HttpURLConnection httpconnection = (HttpURLConnection) connection; String userInfo = remoteURL.getUserInfo(); if (userInfo != null) { // set the authentication String userPassEncoding = Base64.byteArrayToBase64(userInfo.getBytes()); httpconnection.setRequestProperty("Authorization", "Basic " + userPassEncoding); } if( access == IoMode.WRITE) { httpconnection.setDoInput(true); httpconnection.setDoOutput(false); InputStream httpinput = httpconnection.getInputStream(); byte[] buffer = new byte[remoteHttpProtocolInfo.getBufferSize()]; ByteBuffer bb = ByteBuffer.wrap(buffer); int read = 0; _logSpaceAllocation.debug("ALLOC: " + pnfsId + " : " + INC_SPACE); allocator.allocate(INC_SPACE); allocated_space+=INC_SPACE; while((read = httpinput.read(buffer)) != -1) { bb.clear(); last_transfer_time = System.currentTimeMillis(); if(transfered+read > allocated_space) { _logSpaceAllocation.debug("ALLOC: " + pnfsId + " : " + INC_SPACE); allocator.allocate(INC_SPACE); allocated_space+=INC_SPACE; } bb.flip(); fileChannel.write(bb); changed = true; transfered +=read; } say("runIO() wrote "+transfered+"bytes"); } else { httpconnection.setDoInput(false); httpconnection.setDoOutput(true); OutputStream httpoutput = httpconnection.getOutputStream(); } say(" runIO() done"); }
public void runIO(RepositortyChannel fileChannel, ProtocolInfo protocol, StorageInfo storage, PnfsId pnfsId , Allocator allocator, IoMode access) throws Exception { say("runIO()\n\tprotocol="+ protocol+",\n\tStorageInfo="+storage+",\n\tPnfsId="+pnfsId+ ",\n\taccess ="+ access); if(! (protocol instanceof RemoteHttpDataTransferProtocolInfo)) { throw new CacheException( "protocol info is not RemoteHttpDataTransferProtocolInfo"); } starttime = System.currentTimeMillis(); remoteHttpProtocolInfo = (RemoteHttpDataTransferProtocolInfo) protocol; remoteURL = new URL(remoteHttpProtocolInfo.getSourceHttpUrl()); URLConnection connection = remoteURL.openConnection(); if(! (connection instanceof HttpURLConnection)) { throw new CacheException("wrong URL connection type"); } HttpURLConnection httpconnection = (HttpURLConnection) connection; String userInfo = remoteURL.getUserInfo(); if (userInfo != null) { // set the authentication String userPassEncoding = Base64.byteArrayToBase64(userInfo.getBytes()); httpconnection.setRequestProperty("Authorization", "Basic " + userPassEncoding); } if( access == IoMode.WRITE) { httpconnection.setDoInput(true); httpconnection.setDoOutput(false); InputStream httpinput = httpconnection.getInputStream(); byte[] buffer = new byte[remoteHttpProtocolInfo.getBufferSize()]; ByteBuffer bb = ByteBuffer.wrap(buffer); int read = 0; _logSpaceAllocation.debug("ALLOC: " + pnfsId + " : " + INC_SPACE); allocator.allocate(INC_SPACE); allocated_space+=INC_SPACE; while((read = httpinput.read(buffer)) != -1) { last_transfer_time = System.currentTimeMillis(); if(transfered+read > allocated_space) { _logSpaceAllocation.debug("ALLOC: " + pnfsId + " : " + INC_SPACE); allocator.allocate(INC_SPACE); allocated_space+=INC_SPACE; } bb.limit(read); fileChannel.write(bb); changed = true; transfered +=read; bb.clear(); } say("runIO() wrote "+transfered+"bytes"); } else { httpconnection.setDoInput(false); httpconnection.setDoOutput(true); OutputStream httpoutput = httpconnection.getOutputStream(); } say(" runIO() done"); }
diff --git a/Jama/src/main/java/controllerLayer/FillerFactoryBean.java b/Jama/src/main/java/controllerLayer/FillerFactoryBean.java index 14a7db7..3188966 100644 --- a/Jama/src/main/java/controllerLayer/FillerFactoryBean.java +++ b/Jama/src/main/java/controllerLayer/FillerFactoryBean.java @@ -1,50 +1,52 @@ package controllerLayer; import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.enterprise.context.SessionScoped; import javax.inject.Inject; import businessLayer.AgreementShareTableFiller; import businessLayer.Department; import daoLayer.FillerDaoBean; @SessionScoped public abstract class FillerFactoryBean implements Serializable { private static final long serialVersionUID = 1L; @Inject protected FillerDaoBean fillerDao; protected Map<Department, AgreementShareTableFiller> cache = new HashMap<>(); public AgreementShareTableFiller getFiller(Department dep) { if (!cache.containsKey(dep)) { cache.put(dep, findFiller(dep)); } return cache.get(dep); } protected AgreementShareTableFiller findFiller(Department dep) { List<AgreementShareTableFiller> fillers = fillerDao.getAll(); AgreementShareTableFiller currentFiller = createFiller(dep.getRateDirectory()); boolean found = false; Iterator<AgreementShareTableFiller> it = fillers.iterator(); while(!found && it.hasNext()){ - if(currentFiller.equals(it.next())){ + AgreementShareTableFiller f = it.next(); + if(currentFiller.equals(f)){ found = true; + currentFiller = f; } } if(!found){ fillerDao.create(currentFiller); } return currentFiller; } protected abstract AgreementShareTableFiller createFiller(String depDirectory); }
false
true
protected AgreementShareTableFiller findFiller(Department dep) { List<AgreementShareTableFiller> fillers = fillerDao.getAll(); AgreementShareTableFiller currentFiller = createFiller(dep.getRateDirectory()); boolean found = false; Iterator<AgreementShareTableFiller> it = fillers.iterator(); while(!found && it.hasNext()){ if(currentFiller.equals(it.next())){ found = true; } } if(!found){ fillerDao.create(currentFiller); } return currentFiller; }
protected AgreementShareTableFiller findFiller(Department dep) { List<AgreementShareTableFiller> fillers = fillerDao.getAll(); AgreementShareTableFiller currentFiller = createFiller(dep.getRateDirectory()); boolean found = false; Iterator<AgreementShareTableFiller> it = fillers.iterator(); while(!found && it.hasNext()){ AgreementShareTableFiller f = it.next(); if(currentFiller.equals(f)){ found = true; currentFiller = f; } } if(!found){ fillerDao.create(currentFiller); } return currentFiller; }
diff --git a/src/org/dita/dost/reader/MergeMapParser.java b/src/org/dita/dost/reader/MergeMapParser.java index bec0a4d29..ff4fdb4af 100644 --- a/src/org/dita/dost/reader/MergeMapParser.java +++ b/src/org/dita/dost/reader/MergeMapParser.java @@ -1,176 +1,179 @@ /* * This file is part of the DITA Open Toolkit project hosted on * Sourceforge.net. See the accompanying license.txt file for * applicable licenses. */ /* * (c) Copyright IBM Corp. 2004, 2005 All Rights Reserved. */ package org.dita.dost.reader; import java.io.File; import org.dita.dost.exception.DITAOTXMLErrorHandler; import org.dita.dost.log.DITAOTJavaLogger; import org.dita.dost.module.Content; import org.dita.dost.module.ContentImpl; import org.dita.dost.util.Constants; import org.dita.dost.util.MergeUtils; import org.dita.dost.util.StringUtils; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; /** * MergeMapParser reads the ditamap file after preprocessing and merges * different files into one intermediate result. It calls MergeTopicParser * to process the topic file. * * @author Zhang, Yuan Peng */ public class MergeMapParser extends AbstractXMLReader { private XMLReader reader = null; private StringBuffer mapInfo = null; private MergeTopicParser topicParser = null; private DITAOTJavaLogger logger = null; private MergeUtils util; private ContentImpl content; private String dirPath = null; /** * Default Constructor */ public MergeMapParser() { logger = new DITAOTJavaLogger(); try{ if (System.getProperty(Constants.SAX_DRIVER_PROPERTY) == null){ //The default sax driver is set to xerces's sax driver StringUtils.initSaxDriver(); } if(reader == null){ reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(this); // reader.setProperty(Constants.LEXICAL_HANDLER_PROPERTY,this); reader.setFeature(Constants.FEATURE_NAMESPACE_PREFIX, true); // reader.setFeature(Constants.FEATURE_VALIDATION, true); // reader.setFeature(Constants.FEATURE_VALIDATION_SCHEMA, true); } if(mapInfo == null){ mapInfo = new StringBuffer(Constants.INT_1024); } topicParser = new MergeTopicParser(); content = new ContentImpl(); util = MergeUtils.getInstance(); }catch (Exception e){ logger.logException(e); } } /** * @see org.dita.dost.reader.AbstractReader#getContent() */ public Content getContent() { content.setValue(mapInfo.append((StringBuffer)topicParser.getContent().getValue())); return content; } /** * @see org.dita.dost.reader.AbstractReader#read(java.lang.String) */ public void read(String filename) { try{ File input = new File(filename); dirPath = input.getParent(); reader.setErrorHandler(new DITAOTXMLErrorHandler(filename)); reader.parse(filename); }catch(Exception e){ logger.logException(e); } } /** * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) */ public void endElement(String uri, String localName, String qName) throws SAXException { mapInfo.append(Constants.LESS_THAN) .append(Constants.SLASH) .append(qName) .append(Constants.GREATER_THAN); } /** * @see org.xml.sax.ContentHandler#characters(char[], int, int) */ public void characters(char[] ch, int start, int length) throws SAXException { mapInfo.append(StringUtils.escapeXML(ch, start, length)); } /** * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) */ public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { String scopeValue = null; String formatValue = null; + String classValue = null; String fileId = null; int attsLen = atts.getLength(); mapInfo.append(Constants.LESS_THAN).append(qName); for (int i = 0; i < attsLen; i++) { String attQName = atts.getQName(i); String attValue = atts.getValue(i); if(Constants.ATTRIBUTE_NAME_HREF.equals(attQName) - && !StringUtils.isEmptyString(attValue)){ + && !StringUtils.isEmptyString(attValue) + && classValue != null + && classValue.indexOf(Constants.ATTR_CLASS_VALUE_TOPICREF)!=-1){ scopeValue = atts.getValue(Constants.ATTRIBUTE_NAME_SCOPE); formatValue = atts.getValue(Constants.ATTRIBUTE_NAME_FORMAT); // if (attValue.indexOf(Constants.SHARP) != -1){ // attValue = attValue.substring(0, attValue.indexOf(Constants.SHARP)); // } if((scopeValue == null || Constants.ATTR_SCOPE_VALUE_LOCAL.equalsIgnoreCase(scopeValue)) && (formatValue == null || Constants.ATTR_FORMAT_VALUE_DITA.equalsIgnoreCase(formatValue))){ if (util.isVisited(attValue)){ mapInfo.append(Constants.STRING_BLANK) .append("ohref").append(Constants.EQUAL).append(Constants.QUOTATION) .append(StringUtils.escapeXML(attValue)).append(Constants.QUOTATION); // random = RandomUtils.getRandomNum(); // filename = attValue + "(" + Long.toString(random) + ")"; attValue = new StringBuffer(Constants.SHARP).append(util.getIdValue(attValue)).toString(); //parse the file but give it another file name // topicParser.read(filename); }else{ mapInfo.append(Constants.STRING_BLANK) .append("ohref").append(Constants.EQUAL).append(Constants.QUOTATION) .append(StringUtils.escapeXML(attValue)).append(Constants.QUOTATION); //parse the topic fileId = topicParser.parse(attValue,dirPath); util.visit(attValue); attValue = new StringBuffer(Constants.SHARP).append(fileId).toString(); } } } //output all attributes mapInfo.append(Constants.STRING_BLANK) .append(attQName).append(Constants.EQUAL).append(Constants.QUOTATION) .append(StringUtils.escapeXML(attValue)).append(Constants.QUOTATION); } mapInfo.append(Constants.GREATER_THAN); } }
false
true
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { String scopeValue = null; String formatValue = null; String fileId = null; int attsLen = atts.getLength(); mapInfo.append(Constants.LESS_THAN).append(qName); for (int i = 0; i < attsLen; i++) { String attQName = atts.getQName(i); String attValue = atts.getValue(i); if(Constants.ATTRIBUTE_NAME_HREF.equals(attQName) && !StringUtils.isEmptyString(attValue)){ scopeValue = atts.getValue(Constants.ATTRIBUTE_NAME_SCOPE); formatValue = atts.getValue(Constants.ATTRIBUTE_NAME_FORMAT); // if (attValue.indexOf(Constants.SHARP) != -1){ // attValue = attValue.substring(0, attValue.indexOf(Constants.SHARP)); // } if((scopeValue == null || Constants.ATTR_SCOPE_VALUE_LOCAL.equalsIgnoreCase(scopeValue)) && (formatValue == null || Constants.ATTR_FORMAT_VALUE_DITA.equalsIgnoreCase(formatValue))){ if (util.isVisited(attValue)){ mapInfo.append(Constants.STRING_BLANK) .append("ohref").append(Constants.EQUAL).append(Constants.QUOTATION) .append(StringUtils.escapeXML(attValue)).append(Constants.QUOTATION); // random = RandomUtils.getRandomNum(); // filename = attValue + "(" + Long.toString(random) + ")"; attValue = new StringBuffer(Constants.SHARP).append(util.getIdValue(attValue)).toString(); //parse the file but give it another file name // topicParser.read(filename); }else{ mapInfo.append(Constants.STRING_BLANK) .append("ohref").append(Constants.EQUAL).append(Constants.QUOTATION) .append(StringUtils.escapeXML(attValue)).append(Constants.QUOTATION); //parse the topic fileId = topicParser.parse(attValue,dirPath); util.visit(attValue); attValue = new StringBuffer(Constants.SHARP).append(fileId).toString(); } } } //output all attributes mapInfo.append(Constants.STRING_BLANK) .append(attQName).append(Constants.EQUAL).append(Constants.QUOTATION) .append(StringUtils.escapeXML(attValue)).append(Constants.QUOTATION); } mapInfo.append(Constants.GREATER_THAN); }
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { String scopeValue = null; String formatValue = null; String classValue = null; String fileId = null; int attsLen = atts.getLength(); mapInfo.append(Constants.LESS_THAN).append(qName); for (int i = 0; i < attsLen; i++) { String attQName = atts.getQName(i); String attValue = atts.getValue(i); if(Constants.ATTRIBUTE_NAME_HREF.equals(attQName) && !StringUtils.isEmptyString(attValue) && classValue != null && classValue.indexOf(Constants.ATTR_CLASS_VALUE_TOPICREF)!=-1){ scopeValue = atts.getValue(Constants.ATTRIBUTE_NAME_SCOPE); formatValue = atts.getValue(Constants.ATTRIBUTE_NAME_FORMAT); // if (attValue.indexOf(Constants.SHARP) != -1){ // attValue = attValue.substring(0, attValue.indexOf(Constants.SHARP)); // } if((scopeValue == null || Constants.ATTR_SCOPE_VALUE_LOCAL.equalsIgnoreCase(scopeValue)) && (formatValue == null || Constants.ATTR_FORMAT_VALUE_DITA.equalsIgnoreCase(formatValue))){ if (util.isVisited(attValue)){ mapInfo.append(Constants.STRING_BLANK) .append("ohref").append(Constants.EQUAL).append(Constants.QUOTATION) .append(StringUtils.escapeXML(attValue)).append(Constants.QUOTATION); // random = RandomUtils.getRandomNum(); // filename = attValue + "(" + Long.toString(random) + ")"; attValue = new StringBuffer(Constants.SHARP).append(util.getIdValue(attValue)).toString(); //parse the file but give it another file name // topicParser.read(filename); }else{ mapInfo.append(Constants.STRING_BLANK) .append("ohref").append(Constants.EQUAL).append(Constants.QUOTATION) .append(StringUtils.escapeXML(attValue)).append(Constants.QUOTATION); //parse the topic fileId = topicParser.parse(attValue,dirPath); util.visit(attValue); attValue = new StringBuffer(Constants.SHARP).append(fileId).toString(); } } } //output all attributes mapInfo.append(Constants.STRING_BLANK) .append(attQName).append(Constants.EQUAL).append(Constants.QUOTATION) .append(StringUtils.escapeXML(attValue)).append(Constants.QUOTATION); } mapInfo.append(Constants.GREATER_THAN); }
diff --git a/src/com/boh/flatmate/FlatMate.java b/src/com/boh/flatmate/FlatMate.java index 5565d8a..40b1a05 100644 --- a/src/com/boh/flatmate/FlatMate.java +++ b/src/com/boh/flatmate/FlatMate.java @@ -1,253 +1,253 @@ package com.boh.flatmate; import java.io.File; import com.boh.flatmate.R; import com.boh.flatmate.connection.Flat; import com.boh.flatmate.connection.ServerConnection; import com.boh.flatmate.connection.ShopItem; import com.boh.flatmate.connection.Shops; import com.boh.flatmate.connection.User; import com.google.android.maps.MapView; import android.app.ActionBar; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; public class FlatMate extends FragmentActivity implements ActionBar.TabListener { AppSectionsPagerAdapter mAppSectionsPagerAdapter; NonSwipeableViewPager mViewPager; View mMapViewContainer; MapView mMapView; public static Intent service; public void onCreate(Bundle savedInstanceState) { setTheme(R.style.flatMateTheme); super.onCreate(savedInstanceState); String value = ""; Bundle extras = getIntent().getExtras(); if (extras != null) { value = extras.getString("page"); } //final boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); contextExchanger.context = this; ConnectionExchanger.connection = new ServerConnection(); FlatDataExchanger.flatData = new Flat(); FlatDataExchanger.flatData = ConnectionExchanger.connection.getMyFlat(); FlatDataExchanger.flatData.setCurrentUser(ConnectionExchanger.connection.getMe()); if(FlatDataExchanger.flatData.getCurrentUser().getFlatApproved().equals("true")){ setContentView(R.layout.flat_mate); FlatDataExchanger.flatData.orderShopItems(); mapExchanger.mMapView = new MapView(this, getString(R.string.maps_api_key)); if(service == null) service = new Intent(FlatMate.this, UpdateService.class); startService(service); mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager()); final ActionBar actionBar = getActionBar(); //actionBar.setHomeButtonEnabled(false); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); mViewPager = (NonSwipeableViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mAppSectionsPagerAdapter); mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); if(value.equals("shopping")){ actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.flatmates_tab) .setTabListener(this),false); actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.shopping_tab) .setTabListener(this),true); actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.location_tab) .setTabListener(this),false); }else{ actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.flatmates_tab) .setTabListener(this),true); actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.shopping_tab) .setTabListener(this),false); actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.location_tab) .setTabListener(this),false); } }else{ - setContentView(R.layout.flat_mate); + setContentView(R.layout.flat_mate_not_approved); } } @Override protected void onRestart() { // TODO Auto-generated method stub super.onRestart(); Intent i = new Intent(FlatMate.this, FlatMate.class); //your class startActivity(i); finish(); } @Override public void onResume(){ super.onResume(); contextExchanger.context = this; } @Override public void onStart(){ super.onStart(); //new loadData().execute(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.menu_logout: File logFile = new File(ConnectionExchanger.connection.FileName); if (logFile.exists()) { logFile.delete(); } if(service != null) stopService(service); finish(); return true; default: return true; } } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction){ mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } public static class AppSectionsPagerAdapter extends FragmentPagerAdapter { public AppSectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int i) { switch (i) { case 0: Fragment FlatList = new FlatFragment(); return FlatList; case 1: Fragment ShoppingList = new ShoppingFragment(); return ShoppingList; case 2: return new MapFragment(); default: Fragment FlatListDefault = new FlatListFragment(); return FlatListDefault; } } @Override public int getCount() { return 3; } @Override public CharSequence getPageTitle(int position) { return ""; } } private class serverUpdateItem extends AsyncTask<Void,Void,Void> { protected Void doInBackground(Void... item) { return null; } protected void onPostExecute(Void result) { onRestart(); } } static public void userApproved(String approvedId, String approverName){ Log.v("APPRV",approverName + " has approved " + approvedId); User me = FlatMate.FlatDataExchanger.flatData.getCurrentUser(); if(me.getId() == Integer.parseInt(approvedId)){ //new FlatMate.contextExchanger.context.serverUpdateItem().execute(); } else { Log.v("APPRV","But that's not me..."); } } public static class ConnectionExchanger{ public static ServerConnection connection; } public static class FlatDataExchanger{ public static Flat flatData; } public static class contextExchanger{ public static Context context; } public static class mapExchanger { public static MapView mMapView; } public static class ShopsExchanger{ public static Shops nearShops; public static Shops bestShops; } }
true
true
public void onCreate(Bundle savedInstanceState) { setTheme(R.style.flatMateTheme); super.onCreate(savedInstanceState); String value = ""; Bundle extras = getIntent().getExtras(); if (extras != null) { value = extras.getString("page"); } //final boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); contextExchanger.context = this; ConnectionExchanger.connection = new ServerConnection(); FlatDataExchanger.flatData = new Flat(); FlatDataExchanger.flatData = ConnectionExchanger.connection.getMyFlat(); FlatDataExchanger.flatData.setCurrentUser(ConnectionExchanger.connection.getMe()); if(FlatDataExchanger.flatData.getCurrentUser().getFlatApproved().equals("true")){ setContentView(R.layout.flat_mate); FlatDataExchanger.flatData.orderShopItems(); mapExchanger.mMapView = new MapView(this, getString(R.string.maps_api_key)); if(service == null) service = new Intent(FlatMate.this, UpdateService.class); startService(service); mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager()); final ActionBar actionBar = getActionBar(); //actionBar.setHomeButtonEnabled(false); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); mViewPager = (NonSwipeableViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mAppSectionsPagerAdapter); mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); if(value.equals("shopping")){ actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.flatmates_tab) .setTabListener(this),false); actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.shopping_tab) .setTabListener(this),true); actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.location_tab) .setTabListener(this),false); }else{ actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.flatmates_tab) .setTabListener(this),true); actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.shopping_tab) .setTabListener(this),false); actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.location_tab) .setTabListener(this),false); } }else{ setContentView(R.layout.flat_mate); } }
public void onCreate(Bundle savedInstanceState) { setTheme(R.style.flatMateTheme); super.onCreate(savedInstanceState); String value = ""; Bundle extras = getIntent().getExtras(); if (extras != null) { value = extras.getString("page"); } //final boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); contextExchanger.context = this; ConnectionExchanger.connection = new ServerConnection(); FlatDataExchanger.flatData = new Flat(); FlatDataExchanger.flatData = ConnectionExchanger.connection.getMyFlat(); FlatDataExchanger.flatData.setCurrentUser(ConnectionExchanger.connection.getMe()); if(FlatDataExchanger.flatData.getCurrentUser().getFlatApproved().equals("true")){ setContentView(R.layout.flat_mate); FlatDataExchanger.flatData.orderShopItems(); mapExchanger.mMapView = new MapView(this, getString(R.string.maps_api_key)); if(service == null) service = new Intent(FlatMate.this, UpdateService.class); startService(service); mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager()); final ActionBar actionBar = getActionBar(); //actionBar.setHomeButtonEnabled(false); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); mViewPager = (NonSwipeableViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mAppSectionsPagerAdapter); mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); if(value.equals("shopping")){ actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.flatmates_tab) .setTabListener(this),false); actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.shopping_tab) .setTabListener(this),true); actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.location_tab) .setTabListener(this),false); }else{ actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.flatmates_tab) .setTabListener(this),true); actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.shopping_tab) .setTabListener(this),false); actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.location_tab) .setTabListener(this),false); } }else{ setContentView(R.layout.flat_mate_not_approved); } }
diff --git a/translator/src/main/java/com/google/devtools/j2objc/Options.java b/translator/src/main/java/com/google/devtools/j2objc/Options.java index 1e260ed9..a93f35a0 100644 --- a/translator/src/main/java/com/google/devtools/j2objc/Options.java +++ b/translator/src/main/java/com/google/devtools/j2objc/Options.java @@ -1,608 +1,612 @@ /* * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.j2objc; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.io.Resources; import com.google.devtools.j2objc.J2ObjC.Language; import com.google.devtools.j2objc.util.DeadCodeMap; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; /** * The set of tool properties, initialized by the command-line arguments. * This class was extracted from the main class, to make it easier for * other classes to access options. * * @author Tom Ball */ public class Options { private static Map<String, String> compilerOptions; private static List<String> sourcePathEntries = Lists.newArrayList("."); private static List<String> classPathEntries = Lists.newArrayList("."); private static List<String> pluginPathEntries = Lists.newArrayList(); private static String pluginOptionString = ""; private static List<Plugin> plugins = new ArrayList<Plugin>(); private static File outputDirectory = new File("."); private static boolean usePackageDirectories = true; private static Language language = Language.OBJECTIVE_C; private static boolean printConvertedSources = false; private static boolean ignoreMissingImports = false; private static MemoryManagementOption memoryManagementOption = null; private static boolean emitLineDirectives = false; private static boolean warningsAsErrors = false; private static boolean deprecatedDeclarations = false; private static Map<String, String> methodMappings = Maps.newLinkedHashMap(); private static boolean generateTestMain = true; private static boolean memoryDebug = false; private static boolean generateNativeStubs = false; private static boolean stripGwtIncompatible = false; private static boolean segmentedHeaders = false; private static String fileEncoding = System.getProperty("file.encoding", "ISO-8859-1"); private static boolean jsniWarnings = true; private static boolean buildClosure = false; private static DeadCodeMap deadCodeMap = null; private static File proGuardUsageFile = null; private static final String JRE_MAPPINGS_FILE = "JRE.mappings"; private static final List<String> mappingFiles = Lists.newArrayList(JRE_MAPPINGS_FILE); private static String fileHeader; private static final String FILE_HEADER_KEY = "file-header"; private static String usageMessage; private static String helpMessage; private static final String USAGE_MSG_KEY = "usage-message"; private static final String HELP_MSG_KEY = "help-message"; private static String temporaryDirectory; private static final String XBOOTCLASSPATH = "-Xbootclasspath:"; private static String bootclasspath = null; private static Map<String, String> packagePrefixes = Maps.newHashMap(); static { // Load string resources. URL propertiesUrl = Resources.getResource(J2ObjC.class, "J2ObjC.properties"); Properties properties = new Properties(); try { properties.load(propertiesUrl.openStream()); } catch (IOException e) { System.err.println("unable to access tool properties: " + e); System.exit(1); } fileHeader = properties.getProperty(FILE_HEADER_KEY); Preconditions.checkNotNull(fileHeader); usageMessage = properties.getProperty(USAGE_MSG_KEY); Preconditions.checkNotNull(usageMessage); helpMessage = properties.getProperty(HELP_MSG_KEY); Preconditions.checkNotNull(helpMessage); } public static enum MemoryManagementOption { REFERENCE_COUNTING, GC, ARC } private static final MemoryManagementOption DEFAULT_MEMORY_MANAGEMENT_OPTION = MemoryManagementOption.REFERENCE_COUNTING; // Share a single logger so it's level is easily configurable. private static final Logger logger = Logger.getLogger(J2ObjC.class.getName()); /** * Load the options from a command-line, returning the arguments that were * not option-related (usually files). If help is requested or an error is * detected, the appropriate status method is invoked and the app terminates. * @throws IOException */ public static String[] load(String[] args) throws IOException { compilerOptions = Maps.newHashMap(); compilerOptions.put(org.eclipse.jdt.core.JavaCore.COMPILER_SOURCE, "1.7"); compilerOptions.put(org.eclipse.jdt.core.JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, "1.7"); compilerOptions.put(org.eclipse.jdt.core.JavaCore.COMPILER_COMPLIANCE, "1.7"); logger.setLevel(Level.INFO); // Create a temporary directory as the sourcepath's first entry, so that // modified sources will take precedence over regular files. sourcePathEntries = Lists.newArrayList(); int nArg = 0; String[] noFiles = new String[0]; while (nArg < args.length) { String arg = args[nArg]; + if (arg.isEmpty()) { + ++nArg; + continue; + } if (arg.equals("-classpath")) { if (++nArg == args.length) { return noFiles; } classPathEntries = getPathArgument(args[nArg]); } else if (arg.equals("-sourcepath")) { if (++nArg == args.length) { usage("-sourcepath requires an argument"); } sourcePathEntries.addAll(getPathArgument(args[nArg])); } else if (arg.equals("-pluginpath")) { if (++nArg == args.length) { usage("-pluginpath requires an argument"); } pluginPathEntries = getPathArgument(args[nArg]); } else if (arg.equals("-pluginoptions")) { if (++nArg == args.length){ usage("-pluginoptions requires an argument"); } pluginOptionString = args[nArg]; } else if (arg.equals("-d")) { if (++nArg == args.length) { usage("-d requires an argument"); } outputDirectory = new File(args[nArg]); } else if (arg.equals("--mapping")) { if (++nArg == args.length) { usage("--mapping requires an argument"); } mappingFiles.add(args[nArg]); } else if (arg.equals("--dead-code-report")) { if (++nArg == args.length) { usage("--dead-code-report requires an argument"); } proGuardUsageFile = new File(args[nArg]); } else if (arg.equals("--prefix")) { if (++nArg == args.length) { usage("--prefix requires an argument"); } addPrefixOption(args[nArg]); } else if (arg.equals("--prefixes")) { if (++nArg == args.length) { usage("--prefixes requires an argument"); } addPrefixesFile(args[nArg]); } else if (arg.equals("-x")) { if (++nArg == args.length) { usage("-x requires an argument"); } String s = args[nArg]; if (s.equals("objective-c")) { language = Language.OBJECTIVE_C; } else if (s.equals("objective-c++")) { language = Language.OBJECTIVE_CPP; } else { usage("unsupported language: " + s); } } else if (arg.equals("--print-converted-sources")) { printConvertedSources = true; } else if (arg.equals("--ignore-missing-imports")) { ignoreMissingImports = true; } else if (arg.equals("-use-reference-counting")) { checkMemoryManagementOption(MemoryManagementOption.REFERENCE_COUNTING); } else if (arg.equals("--generate-test-main")) { generateTestMain = true; } else if (arg.equals("--no-generate-test-main")) { generateTestMain = false; } else if (arg.equals("--no-package-directories")) { usePackageDirectories = false; } else if (arg.equals("-use-gc")) { checkMemoryManagementOption(MemoryManagementOption.GC); } else if (arg.equals("-use-arc")) { checkMemoryManagementOption(MemoryManagementOption.ARC); } else if (arg.equals("-g")) { emitLineDirectives = true; } else if (arg.equals("-Werror")) { warningsAsErrors = true; } else if (arg.equals("--generate-deprecated")) { deprecatedDeclarations = true; } else if (arg.equals("-q") || arg.equals("--quiet")) { logger.setLevel(Level.WARNING); } else if (arg.equals("-t") || arg.equals("--timing-info")) { logger.setLevel(Level.FINE); } else if (arg.equals("-v") || arg.equals("--verbose")) { logger.setLevel(Level.FINEST); } else if (arg.startsWith(XBOOTCLASSPATH)) { bootclasspath = arg.substring(XBOOTCLASSPATH.length()); } else if (arg.equals("-Xno-jsni-delimiters")) { // TODO(user): remove flag when all client builds stop using it. } else if (arg.equals("--mem-debug")) { memoryDebug = true; } else if (arg.equals("--generate-native-stubs")) { generateNativeStubs = true; } else if (arg.equals("-Xno-jsni-warnings")) { jsniWarnings = false; } else if (arg.equals("-encoding")) { if (++nArg == args.length) { usage("-encoding requires an argument"); } fileEncoding = args[nArg]; } else if (arg.equals("--strip-gwt-incompatible")) { stripGwtIncompatible = true; } else if (arg.equals("--segmented-headers")) { segmentedHeaders = true; } else if (arg.equals("--build-closure")) { buildClosure = true; } else if (arg.startsWith("-h") || arg.equals("--help")) { help(false); } else if (arg.startsWith("-")) { usage("invalid flag: " + arg); } else { break; } ++nArg; } if (memoryManagementOption == null) { memoryManagementOption = MemoryManagementOption.REFERENCE_COUNTING; } int nFiles = args.length - nArg; String[] files = new String[nFiles]; for (int i = 0; i < nFiles; i++) { String path = args[i + nArg]; if (path.endsWith(".jar")) { appendSourcePath(path); } files[i] = path; } return files; } /** * Add prefix option, which has a format of "<package>=<prefix>". */ private static void addPrefixOption(String arg) { int i = arg.indexOf('='); // Make sure key and value are at least 1 character. if (i < 1 || i >= arg.length() - 1) { usage("invalid prefix format"); } String pkg = arg.substring(0, i); String prefix = arg.substring(i + 1); addPackagePrefix(pkg, prefix); } /** * Add a file map of packages to their respective prefixes, using the * Properties file format. */ private static void addPrefixesFile(String filename) throws IOException { Properties props = new Properties(); FileInputStream fis = new FileInputStream(filename); props.load(fis); fis.close(); addPrefixProperties(props); } @VisibleForTesting static void addPrefixProperties(Properties props) { for (String pkg : props.stringPropertyNames()) { addPackagePrefix(pkg, props.getProperty(pkg).trim()); } } /** * Check that the memory management option wasn't previously set to a * different value. If okay, then set the option. */ private static void checkMemoryManagementOption(MemoryManagementOption option) { if (memoryManagementOption != null && memoryManagementOption != option) { usage("Multiple memory management options cannot be set."); } setMemoryManagementOption(option); } public static void usage(String invalidUseMsg) { System.err.println("j2objc: " + invalidUseMsg); System.err.println(usageMessage); System.exit(1); } public static void help(boolean errorExit) { System.err.println(helpMessage); // javac exits with 2, but any non-zero value works. System.exit(errorExit ? 2 : 0); } private static List<String> getPathArgument(String argument) { List<String> entries = Lists.newArrayList(); for (String entry : Splitter.on(':').split(argument)) { if (new File(entry).exists()) { // JDT fails with bad path entries. entries.add(entry); } else if (entry.startsWith("~/")) { // Expand bash/csh tildes, which don't get expanded by the shell // first if in the middle of a path string. String expanded = System.getProperty("user.home") + entry.substring(1); if (new File(expanded).exists()) { entries.add(expanded); } } } return entries; } public static Map<String, String> getCompilerOptions() { return compilerOptions; } public static String[] getSourcePathEntries() { return sourcePathEntries.toArray(new String[0]); } public static void appendSourcePath(String entry) { sourcePathEntries.add(entry); } public static void insertSourcePath(int index, String entry) { sourcePathEntries.add(index, entry); } public static String[] getClassPathEntries() { return classPathEntries.toArray(new String[classPathEntries.size()]); } public static String[] getPluginPathEntries() { return pluginPathEntries.toArray(new String[pluginPathEntries.size()]); } public static String getPluginOptionString() { return pluginOptionString; } public static List<Plugin> getPlugins() { return plugins; } public static File getOutputDirectory() { return outputDirectory; } public static boolean memoryDebug() { return memoryDebug; } public static void setMemoryDebug(boolean value) { memoryDebug = value; } public static boolean generateNativeStubs() { return generateNativeStubs; } public static void setGenerateNativeStubs(boolean value) { generateNativeStubs = value; } /** * If true, put output files in sub-directories defined by * package declaration (like javac does). */ public static boolean usePackageDirectories() { return usePackageDirectories; } public static Language getLanguage() { return language; } public static boolean printConvertedSources() { return printConvertedSources; } public static boolean ignoreMissingImports() { return ignoreMissingImports; } public static boolean useReferenceCounting() { return memoryManagementOption == MemoryManagementOption.REFERENCE_COUNTING; } public static boolean useGC() { return memoryManagementOption == MemoryManagementOption.GC; } public static boolean useARC() { return memoryManagementOption == MemoryManagementOption.ARC; } public static MemoryManagementOption getMemoryManagementOption() { return memoryManagementOption; } // Used by tests. public static void setMemoryManagementOption(MemoryManagementOption option) { memoryManagementOption = option; } public static void resetMemoryManagementOption() { memoryManagementOption = DEFAULT_MEMORY_MANAGEMENT_OPTION; } public static boolean emitLineDirectives() { return emitLineDirectives; } public static void setEmitLineDirectives(boolean b) { emitLineDirectives = b; } public static boolean treatWarningsAsErrors() { return warningsAsErrors; } @VisibleForTesting public static void enableDeprecatedDeclarations() { deprecatedDeclarations = true; } @VisibleForTesting public static void resetDeprecatedDeclarations() { deprecatedDeclarations = false; } public static boolean generateDeprecatedDeclarations() { return deprecatedDeclarations; } public static Map<String, String> getMethodMappings() { return methodMappings; } public static List<String> getMappingFiles() { return mappingFiles; } public static String getUsageMessage() { return usageMessage; } public static String getHelpMessage() { return helpMessage; } public static String getFileHeader() { return fileHeader; } public static boolean generateTestMain() { return generateTestMain; } public static File getProGuardUsageFile() { return proGuardUsageFile; } public static DeadCodeMap getDeadCodeMap() { return deadCodeMap; } public static void setDeadCodeMap(DeadCodeMap map) { deadCodeMap = map; } public static String getBootClasspath() { return bootclasspath != null ? bootclasspath : System.getProperty("sun.boot.class.path"); } public static Map<String, String> getPackagePrefixes() { return packagePrefixes; } public static void addPackagePrefix(String pkg, String prefix) { packagePrefixes.put(pkg, prefix); } @VisibleForTesting public static void clearPackagePrefixes() { packagePrefixes.clear(); } public static String getTemporaryDirectory() throws IOException { if (temporaryDirectory != null) { return temporaryDirectory; } File tmpfile = File.createTempFile("j2objc", Long.toString(System.nanoTime())); if (!tmpfile.delete()) { throw new IOException("Could not delete temp file: " + tmpfile.getAbsolutePath()); } if (!tmpfile.mkdir()) { throw new IOException("Could not create temp directory: " + tmpfile.getAbsolutePath()); } temporaryDirectory = tmpfile.getAbsolutePath(); return temporaryDirectory; } // Called on exit. This is done here rather than using File.deleteOnExit(), // so the package directories created by the dead-code-eliminator don't have // to be tracked. public static void deleteTemporaryDirectory() { if (temporaryDirectory != null) { deleteDir(new File(temporaryDirectory)); temporaryDirectory = null; } } private static void deleteDir(File dir) { for (File f : dir.listFiles()) { if (f.isDirectory()) { deleteDir(f); } else if (f.getName().endsWith(".java")) { // Only delete Java files, as other temporary files (like hsperfdata) // may also be in tmpdir. f.delete(); } } dir.delete(); // Will fail if other files in dir, which is fine. } public static String fileEncoding() { return fileEncoding; } /** * Returns an array that has the same number of elements as the source path * entries, containing the file encoding. */ public static String[] getFileEncodings() { int n = sourcePathEntries.size(); String[] result = new String[n]; for (int i = 0; i < n; i++) { result[i] = fileEncoding; } return result; } public static boolean stripGwtIncompatibleMethods() { return stripGwtIncompatible; } @VisibleForTesting public static void setStripGwtIncompatibleMethods(boolean b) { stripGwtIncompatible = b; } public static boolean generateSegmentedHeaders() { return segmentedHeaders; } @VisibleForTesting public static void enableSegmentedHeaders() { segmentedHeaders = true; } @VisibleForTesting public static void resetSegmentedHeaders() { segmentedHeaders = false; } public static boolean jsniWarnings() { return jsniWarnings; } public static void setJsniWarnings(boolean b) { jsniWarnings = b; } public static boolean buildClosure() { return buildClosure; } }
true
true
public static String[] load(String[] args) throws IOException { compilerOptions = Maps.newHashMap(); compilerOptions.put(org.eclipse.jdt.core.JavaCore.COMPILER_SOURCE, "1.7"); compilerOptions.put(org.eclipse.jdt.core.JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, "1.7"); compilerOptions.put(org.eclipse.jdt.core.JavaCore.COMPILER_COMPLIANCE, "1.7"); logger.setLevel(Level.INFO); // Create a temporary directory as the sourcepath's first entry, so that // modified sources will take precedence over regular files. sourcePathEntries = Lists.newArrayList(); int nArg = 0; String[] noFiles = new String[0]; while (nArg < args.length) { String arg = args[nArg]; if (arg.equals("-classpath")) { if (++nArg == args.length) { return noFiles; } classPathEntries = getPathArgument(args[nArg]); } else if (arg.equals("-sourcepath")) { if (++nArg == args.length) { usage("-sourcepath requires an argument"); } sourcePathEntries.addAll(getPathArgument(args[nArg])); } else if (arg.equals("-pluginpath")) { if (++nArg == args.length) { usage("-pluginpath requires an argument"); } pluginPathEntries = getPathArgument(args[nArg]); } else if (arg.equals("-pluginoptions")) { if (++nArg == args.length){ usage("-pluginoptions requires an argument"); } pluginOptionString = args[nArg]; } else if (arg.equals("-d")) { if (++nArg == args.length) { usage("-d requires an argument"); } outputDirectory = new File(args[nArg]); } else if (arg.equals("--mapping")) { if (++nArg == args.length) { usage("--mapping requires an argument"); } mappingFiles.add(args[nArg]); } else if (arg.equals("--dead-code-report")) { if (++nArg == args.length) { usage("--dead-code-report requires an argument"); } proGuardUsageFile = new File(args[nArg]); } else if (arg.equals("--prefix")) { if (++nArg == args.length) { usage("--prefix requires an argument"); } addPrefixOption(args[nArg]); } else if (arg.equals("--prefixes")) { if (++nArg == args.length) { usage("--prefixes requires an argument"); } addPrefixesFile(args[nArg]); } else if (arg.equals("-x")) { if (++nArg == args.length) { usage("-x requires an argument"); } String s = args[nArg]; if (s.equals("objective-c")) { language = Language.OBJECTIVE_C; } else if (s.equals("objective-c++")) { language = Language.OBJECTIVE_CPP; } else { usage("unsupported language: " + s); } } else if (arg.equals("--print-converted-sources")) { printConvertedSources = true; } else if (arg.equals("--ignore-missing-imports")) { ignoreMissingImports = true; } else if (arg.equals("-use-reference-counting")) { checkMemoryManagementOption(MemoryManagementOption.REFERENCE_COUNTING); } else if (arg.equals("--generate-test-main")) { generateTestMain = true; } else if (arg.equals("--no-generate-test-main")) { generateTestMain = false; } else if (arg.equals("--no-package-directories")) { usePackageDirectories = false; } else if (arg.equals("-use-gc")) { checkMemoryManagementOption(MemoryManagementOption.GC); } else if (arg.equals("-use-arc")) { checkMemoryManagementOption(MemoryManagementOption.ARC); } else if (arg.equals("-g")) { emitLineDirectives = true; } else if (arg.equals("-Werror")) { warningsAsErrors = true; } else if (arg.equals("--generate-deprecated")) { deprecatedDeclarations = true; } else if (arg.equals("-q") || arg.equals("--quiet")) { logger.setLevel(Level.WARNING); } else if (arg.equals("-t") || arg.equals("--timing-info")) { logger.setLevel(Level.FINE); } else if (arg.equals("-v") || arg.equals("--verbose")) { logger.setLevel(Level.FINEST); } else if (arg.startsWith(XBOOTCLASSPATH)) { bootclasspath = arg.substring(XBOOTCLASSPATH.length()); } else if (arg.equals("-Xno-jsni-delimiters")) { // TODO(user): remove flag when all client builds stop using it. } else if (arg.equals("--mem-debug")) { memoryDebug = true; } else if (arg.equals("--generate-native-stubs")) { generateNativeStubs = true; } else if (arg.equals("-Xno-jsni-warnings")) { jsniWarnings = false; } else if (arg.equals("-encoding")) { if (++nArg == args.length) { usage("-encoding requires an argument"); } fileEncoding = args[nArg]; } else if (arg.equals("--strip-gwt-incompatible")) { stripGwtIncompatible = true; } else if (arg.equals("--segmented-headers")) { segmentedHeaders = true; } else if (arg.equals("--build-closure")) { buildClosure = true; } else if (arg.startsWith("-h") || arg.equals("--help")) { help(false); } else if (arg.startsWith("-")) { usage("invalid flag: " + arg); } else { break; } ++nArg; } if (memoryManagementOption == null) { memoryManagementOption = MemoryManagementOption.REFERENCE_COUNTING; } int nFiles = args.length - nArg; String[] files = new String[nFiles]; for (int i = 0; i < nFiles; i++) { String path = args[i + nArg]; if (path.endsWith(".jar")) { appendSourcePath(path); } files[i] = path; } return files; }
public static String[] load(String[] args) throws IOException { compilerOptions = Maps.newHashMap(); compilerOptions.put(org.eclipse.jdt.core.JavaCore.COMPILER_SOURCE, "1.7"); compilerOptions.put(org.eclipse.jdt.core.JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, "1.7"); compilerOptions.put(org.eclipse.jdt.core.JavaCore.COMPILER_COMPLIANCE, "1.7"); logger.setLevel(Level.INFO); // Create a temporary directory as the sourcepath's first entry, so that // modified sources will take precedence over regular files. sourcePathEntries = Lists.newArrayList(); int nArg = 0; String[] noFiles = new String[0]; while (nArg < args.length) { String arg = args[nArg]; if (arg.isEmpty()) { ++nArg; continue; } if (arg.equals("-classpath")) { if (++nArg == args.length) { return noFiles; } classPathEntries = getPathArgument(args[nArg]); } else if (arg.equals("-sourcepath")) { if (++nArg == args.length) { usage("-sourcepath requires an argument"); } sourcePathEntries.addAll(getPathArgument(args[nArg])); } else if (arg.equals("-pluginpath")) { if (++nArg == args.length) { usage("-pluginpath requires an argument"); } pluginPathEntries = getPathArgument(args[nArg]); } else if (arg.equals("-pluginoptions")) { if (++nArg == args.length){ usage("-pluginoptions requires an argument"); } pluginOptionString = args[nArg]; } else if (arg.equals("-d")) { if (++nArg == args.length) { usage("-d requires an argument"); } outputDirectory = new File(args[nArg]); } else if (arg.equals("--mapping")) { if (++nArg == args.length) { usage("--mapping requires an argument"); } mappingFiles.add(args[nArg]); } else if (arg.equals("--dead-code-report")) { if (++nArg == args.length) { usage("--dead-code-report requires an argument"); } proGuardUsageFile = new File(args[nArg]); } else if (arg.equals("--prefix")) { if (++nArg == args.length) { usage("--prefix requires an argument"); } addPrefixOption(args[nArg]); } else if (arg.equals("--prefixes")) { if (++nArg == args.length) { usage("--prefixes requires an argument"); } addPrefixesFile(args[nArg]); } else if (arg.equals("-x")) { if (++nArg == args.length) { usage("-x requires an argument"); } String s = args[nArg]; if (s.equals("objective-c")) { language = Language.OBJECTIVE_C; } else if (s.equals("objective-c++")) { language = Language.OBJECTIVE_CPP; } else { usage("unsupported language: " + s); } } else if (arg.equals("--print-converted-sources")) { printConvertedSources = true; } else if (arg.equals("--ignore-missing-imports")) { ignoreMissingImports = true; } else if (arg.equals("-use-reference-counting")) { checkMemoryManagementOption(MemoryManagementOption.REFERENCE_COUNTING); } else if (arg.equals("--generate-test-main")) { generateTestMain = true; } else if (arg.equals("--no-generate-test-main")) { generateTestMain = false; } else if (arg.equals("--no-package-directories")) { usePackageDirectories = false; } else if (arg.equals("-use-gc")) { checkMemoryManagementOption(MemoryManagementOption.GC); } else if (arg.equals("-use-arc")) { checkMemoryManagementOption(MemoryManagementOption.ARC); } else if (arg.equals("-g")) { emitLineDirectives = true; } else if (arg.equals("-Werror")) { warningsAsErrors = true; } else if (arg.equals("--generate-deprecated")) { deprecatedDeclarations = true; } else if (arg.equals("-q") || arg.equals("--quiet")) { logger.setLevel(Level.WARNING); } else if (arg.equals("-t") || arg.equals("--timing-info")) { logger.setLevel(Level.FINE); } else if (arg.equals("-v") || arg.equals("--verbose")) { logger.setLevel(Level.FINEST); } else if (arg.startsWith(XBOOTCLASSPATH)) { bootclasspath = arg.substring(XBOOTCLASSPATH.length()); } else if (arg.equals("-Xno-jsni-delimiters")) { // TODO(user): remove flag when all client builds stop using it. } else if (arg.equals("--mem-debug")) { memoryDebug = true; } else if (arg.equals("--generate-native-stubs")) { generateNativeStubs = true; } else if (arg.equals("-Xno-jsni-warnings")) { jsniWarnings = false; } else if (arg.equals("-encoding")) { if (++nArg == args.length) { usage("-encoding requires an argument"); } fileEncoding = args[nArg]; } else if (arg.equals("--strip-gwt-incompatible")) { stripGwtIncompatible = true; } else if (arg.equals("--segmented-headers")) { segmentedHeaders = true; } else if (arg.equals("--build-closure")) { buildClosure = true; } else if (arg.startsWith("-h") || arg.equals("--help")) { help(false); } else if (arg.startsWith("-")) { usage("invalid flag: " + arg); } else { break; } ++nArg; } if (memoryManagementOption == null) { memoryManagementOption = MemoryManagementOption.REFERENCE_COUNTING; } int nFiles = args.length - nArg; String[] files = new String[nFiles]; for (int i = 0; i < nFiles; i++) { String path = args[i + nArg]; if (path.endsWith(".jar")) { appendSourcePath(path); } files[i] = path; } return files; }
diff --git a/htroot/yacy/search.java b/htroot/yacy/search.java index fd0bbea91..8979849d0 100644 --- a/htroot/yacy/search.java +++ b/htroot/yacy/search.java @@ -1,338 +1,338 @@ // search.java // (C) 2004 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany // first published on http://yacy.net // // This is a part of YaCy, a peer-to-peer based web search engine // // $LastChangedDate$ // $LastChangedRevision$ // $LastChangedBy$ // // LICENSE // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // You must compile this file with // javac -classpath .:../../Classes search.java // if the shell's current path is htroot/yacy import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeSet; import de.anomic.http.httpHeader; import de.anomic.index.indexContainer; import de.anomic.kelondro.kelondroBase64Order; import de.anomic.kelondro.kelondroBitfield; import de.anomic.kelondro.kelondroSortStack; import de.anomic.net.natLib; import de.anomic.plasma.plasmaProfiling; import de.anomic.plasma.plasmaSearchEvent; import de.anomic.plasma.plasmaSearchQuery; import de.anomic.plasma.plasmaSearchRankingProfile; import de.anomic.plasma.plasmaSwitchboard; import de.anomic.plasma.plasmaSearchEvent.ResultEntry; import de.anomic.server.serverCore; import de.anomic.server.serverObjects; import de.anomic.server.serverProfiling; import de.anomic.server.serverSwitch; import de.anomic.tools.crypt; import de.anomic.xml.RSSFeed; import de.anomic.xml.RSSMessage; import de.anomic.yacy.yacyCore; import de.anomic.yacy.yacyNetwork; import de.anomic.yacy.yacySeed; import de.anomic.yacy.yacyURL; public final class search { public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) { // return variable that accumulates replacements final plasmaSwitchboard sb = (plasmaSwitchboard) env; sb.remoteSearchLastAccess = System.currentTimeMillis(); serverObjects prop = new serverObjects(); if ((post == null) || (env == null)) return prop; if (!yacyNetwork.authentifyRequest(post, env)) return prop; String client = (String) header.get(httpHeader.CONNECTION_PROP_CLIENTIP); //System.out.println("yacy: search received request = " + post.toString()); final String oseed = post.get("myseed", ""); // complete seed of the requesting peer // final String youare = post.get("youare", ""); // seed hash of the target peer, used for testing network stability final String key = post.get("key", ""); // transmission key for response final String query = post.get("query", ""); // a string of word hashes that shall be searched and combined final String exclude= post.get("exclude", "");// a string of word hashes that shall not be within the search result String urls = post.get("urls", ""); // a string of url hashes that are preselected for the search: no other may be returned String abstracts = post.get("abstracts", ""); // a string of word hashes for abstracts that shall be generated, or 'auto' (for maxcount-word), or '' (for none) // final String fwdep = post.get("fwdep", ""); // forward depth. if "0" then peer may NOT ask another peer for more results // final String fwden = post.get("fwden", ""); // forward deny, a list of seed hashes. They may NOT be target of forward hopping final int count = Math.min(100, post.getInt("count", 10)); // maximum number of wanted results final int maxdist= post.getInt("maxdist", Integer.MAX_VALUE); final String prefer = post.get("prefer", ""); final String contentdom = post.get("contentdom", "text"); final String filter = post.get("filter", ".*"); final int partitions = post.getInt("partitions", 30); String profile = post.get("profile", ""); // remote profile hand-over if (profile.length() > 0) profile = crypt.simpleDecode(profile, null); //final boolean includesnippet = post.get("includesnippet", "false").equals("true"); kelondroBitfield constraint = ((post.containsKey("constraint")) && (post.get("constraint", "").length() > 0)) ? new kelondroBitfield(4, post.get("constraint", "______")) : null; if (constraint != null) { // check bad handover parameter from older versions boolean allon = true; for (int i = 0; i < 32; i++) { if (!constraint.get(i)) {allon = false; break;} } if (allon) constraint = null; } // final boolean global = ((String) post.get("resource", "global")).equals("global"); // if true, then result may consist of answers from other peers // Date remoteTime = yacyCore.parseUniversalDate((String) post.get(yacySeed.MYTIME)); // read remote time // test: // http://localhost:8080/yacy/search.html?query=4galTpdpDM5Q (search for linux) // http://localhost:8080/yacy/search.html?query=gh8DKIhGKXws (search for book) // http://localhost:8080/yacy/search.html?query=UEhMGfGv2vOE (search for kernel) // http://localhost:8080/yacy/search.html?query=ZX-LjaYo74PP (search for help) // http://localhost:8080/yacy/search.html?query=uDqIalxDfM2a (search for mail) // http://localhost:8080/yacy/search.html?query=4galTpdpDM5Qgh8DKIhGKXws&abstracts=auto (search for linux and book, generate abstract automatically) // http://localhost:8080/yacy/search.html?query=&abstracts=4galTpdpDM5Q (only abstracts for linux) if ((sb.isRobinsonMode()) && (!((sb.isPublicRobinson()) || (sb.isInMyCluster((String)header.get(httpHeader.CONNECTION_PROP_CLIENTIP)))))) { // if we are a robinson cluster, answer only if this client is known by our network definition prop.put("links", ""); prop.put("linkcount", "0"); prop.put("references", ""); return prop; } // check the search tracker TreeSet<Long> trackerHandles = sb.remoteSearchTracker.get(client); if (trackerHandles == null) trackerHandles = new TreeSet<Long>(); boolean block = false; if (trackerHandles.tailSet(new Long(System.currentTimeMillis() - 6000)).size() > 1) try { Thread.sleep(3000); block = true; } catch (InterruptedException e) { e.printStackTrace(); } if (trackerHandles.tailSet(new Long(System.currentTimeMillis() - 60000)).size() > 12) try { Thread.sleep(10000); block = true; } catch (InterruptedException e) { e.printStackTrace(); } if (trackerHandles.tailSet(new Long(System.currentTimeMillis() - 600000)).size() > 36) try { Thread.sleep(30000); block = true; } catch (InterruptedException e) { e.printStackTrace(); } if (block) { prop.put("links", ""); prop.put("linkcount", "0"); prop.put("references", ""); return prop; } // tell all threads to do nothing for a specific time sb.intermissionAllThreads(3000); TreeSet<String> abstractSet = ((abstracts.length() == 0) || (abstracts.equals("auto"))) ? null : plasmaSearchQuery.hashes2Set(abstracts); // store accessing peer yacySeed remoteSeed = yacySeed.genRemoteSeed(oseed, key, false); if (sb.webIndex.seedDB == null) { yacyCore.log.logSevere("yacy.search: seed cache not initialized"); } else { sb.webIndex.peerActions.peerArrival(remoteSeed, true); } // prepare search final TreeSet<String> queryhashes = plasmaSearchQuery.hashes2Set(query); final TreeSet<String> excludehashes = (exclude.length() == 0) ? new TreeSet<String>(kelondroBase64Order.enhancedComparator) : plasmaSearchQuery.hashes2Set(exclude); final long timestamp = System.currentTimeMillis(); // prepare a search profile plasmaSearchRankingProfile rankingProfile = (profile.length() == 0) ? new plasmaSearchRankingProfile(plasmaSearchQuery.contentdomParser(contentdom)) : new plasmaSearchRankingProfile("", profile); // prepare an abstract result StringBuffer indexabstract = new StringBuffer(); int indexabstractContainercount = 0; int joincount = 0; plasmaSearchQuery theQuery = null; ArrayList<kelondroSortStack<ResultEntry>.stackElement> accu = null; plasmaSearchEvent theSearch = null; if ((query.length() == 0) && (abstractSet != null)) { // this is _not_ a normal search, only a request for index abstracts theQuery = new plasmaSearchQuery(null, abstractSet, new TreeSet<String>(kelondroBase64Order.enhancedComparator), rankingProfile, maxdist, prefer, plasmaSearchQuery.contentdomParser(contentdom), false, count, 0, filter, plasmaSearchQuery.SEARCHDOM_LOCAL, null, -1, null, false, yacyURL.TLD_any_zone_filter, client, false); theQuery.domType = plasmaSearchQuery.SEARCHDOM_LOCAL; yacyCore.log.logInfo("INIT HASH SEARCH (abstracts only): " + plasmaSearchQuery.anonymizedQueryHashes(theQuery.queryHashes) + " - " + theQuery.displayResults() + " links"); long timer = System.currentTimeMillis(); Map<String, indexContainer>[] containers = sb.webIndex.localSearchContainers(theQuery, plasmaSearchQuery.hashes2Set(urls)); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(theQuery.id(true), plasmaSearchEvent.COLLECTION, containers[0].size(), System.currentTimeMillis() - timer)); if (containers != null) { Iterator<Map.Entry<String, indexContainer>> ci = containers[0].entrySet().iterator(); Map.Entry<String, indexContainer> entry; String wordhash; while (ci.hasNext()) { entry = ci.next(); wordhash = entry.getKey(); indexContainer container = entry.getValue(); indexabstractContainercount += container.size(); indexabstract.append("indexabstract." + wordhash + "=").append(indexContainer.compressIndex(container, null, 1000).toString()).append(serverCore.CRLF_STRING); } } prop.put("indexcount", ""); prop.put("joincount", "0"); prop.put("references", ""); } else { // retrieve index containers from search request theQuery = new plasmaSearchQuery(null, queryhashes, excludehashes, rankingProfile, maxdist, prefer, plasmaSearchQuery.contentdomParser(contentdom), false, count, 0, filter, plasmaSearchQuery.SEARCHDOM_LOCAL, null, -1, constraint, false, yacyURL.TLD_any_zone_filter, client, false); theQuery.domType = plasmaSearchQuery.SEARCHDOM_LOCAL; yacyCore.log.logInfo("INIT HASH SEARCH (query-" + abstracts + "): " + plasmaSearchQuery.anonymizedQueryHashes(theQuery.queryHashes) + " - " + theQuery.displayResults() + " links"); - RSSFeed.channels(RSSFeed.REMOTESEARCH).addMessage(new RSSMessage("Remote Search Request from " + remoteSeed.getName(), plasmaSearchQuery.anonymizedQueryHashes(theQuery.queryHashes), "")); + RSSFeed.channels(RSSFeed.REMOTESEARCH).addMessage(new RSSMessage("Remote Search Request from " + ((remoteSeed == null) ? "unknown" : remoteSeed.getName()), plasmaSearchQuery.anonymizedQueryHashes(theQuery.queryHashes), "")); // make event theSearch = plasmaSearchEvent.getEvent(theQuery, rankingProfile, sb.webIndex, sb.crawlResults, null, true); // set statistic details of search result and find best result index set if (theSearch.getRankingResult().getLocalResourceSize() == 0) { prop.put("indexcount", ""); prop.put("joincount", "0"); } else { // attach information about index abstracts StringBuffer indexcount = new StringBuffer(); Map.Entry<String, Integer> entry; Iterator<Map.Entry<String, Integer>> i = theSearch.IACount.entrySet().iterator(); while (i.hasNext()) { entry = i.next(); indexcount.append("indexcount.").append((String) entry.getKey()).append('=').append(((Integer) entry.getValue()).toString()).append(serverCore.CRLF_STRING); } if (abstractSet != null) { // if a specific index-abstract is demanded, attach it here Iterator<String> j = abstractSet.iterator(); String wordhash; while (j.hasNext()) { wordhash = (String) j.next(); indexabstractContainercount += ((Integer) theSearch.IACount.get(wordhash)).intValue(); indexabstract.append("indexabstract." + wordhash + "=").append((String) theSearch.IAResults.get(wordhash)).append(serverCore.CRLF_STRING); } } prop.put("indexcount", indexcount.toString()); if (theSearch.getRankingResult().getLocalResourceSize() == 0) { joincount = 0; prop.put("joincount", "0"); } else { joincount = theSearch.getRankingResult().getLocalResourceSize(); prop.put("joincount", Integer.toString(joincount)); accu = theSearch.completeResults(3000); } // generate compressed index for maxcounthash // this is not needed if the search is restricted to specific // urls, because it is a re-search if ((theSearch.IAmaxcounthash == null) || (urls.length() != 0) || (queryhashes.size() <= 1) || (abstracts.length() == 0)) { prop.put("indexabstract", ""); } else if (abstracts.equals("auto")) { // automatically attach the index abstract for the index that has the most references. This should be our target dht position indexabstractContainercount += ((Integer) theSearch.IACount.get(theSearch.IAmaxcounthash)).intValue(); indexabstract.append("indexabstract." + theSearch.IAmaxcounthash + "=").append((String) theSearch.IAResults.get(theSearch.IAmaxcounthash)).append(serverCore.CRLF_STRING); if ((theSearch.IAneardhthash != null) && (!(theSearch.IAneardhthash.equals(theSearch.IAmaxcounthash)))) { // in case that the neardhthash is different from the maxcounthash attach also the neardhthash-container indexabstractContainercount += ((Integer) theSearch.IACount.get(theSearch.IAneardhthash)).intValue(); indexabstract.append("indexabstract." + theSearch.IAneardhthash + "=").append((String) theSearch.IAResults.get(theSearch.IAneardhthash)).append(serverCore.CRLF_STRING); } //System.out.println("DEBUG-ABSTRACTGENERATION: maxcounthash = " + maxcounthash); //System.out.println("DEBUG-ABSTRACTGENERATION: neardhthash = "+ neardhthash); //yacyCore.log.logFine("DEBUG HASH SEARCH: " + indexabstract); } } if (partitions > 0) sb.requestedQueries = sb.requestedQueries + 1d / partitions; // increase query counter // prepare reference hints long timer = System.currentTimeMillis(); Set<String> ws = theSearch.references(10); StringBuffer refstr = new StringBuffer(); Iterator<String> j = ws.iterator(); while (j.hasNext()) { refstr.append(",").append((String) j.next()); } prop.put("references", (refstr.length() > 0) ? refstr.substring(1) : refstr.toString()); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(theQuery.id(true), "reference collection", ws.size(), System.currentTimeMillis() - timer)); } prop.put("indexabstract", indexabstract.toString()); // prepare result if ((joincount == 0) || (accu == null)) { // no results prop.put("links", ""); prop.put("linkcount", "0"); prop.put("references", ""); } else { // result is a List of urlEntry elements long timer = System.currentTimeMillis(); StringBuffer links = new StringBuffer(); String resource = null; kelondroSortStack<plasmaSearchEvent.ResultEntry>.stackElement entry; for (int i = 0; i < accu.size(); i++) { entry = accu.get(i); resource = entry.element.resource(); if (resource != null) { links.append("resource").append(i).append('=').append(resource).append(serverCore.CRLF_STRING); } } prop.put("links", links.toString()); prop.put("linkcount", accu.size()); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(theQuery.id(true), "result list preparation", accu.size(), System.currentTimeMillis() - timer)); } // add information about forward peers prop.put("fwhop", ""); // hops (depth) of forwards that had been performed to construct this result prop.put("fwsrc", ""); // peers that helped to construct this result prop.put("fwrec", ""); // peers that would have helped to construct this result (recommendations) // prepare search statistics theQuery.remotepeer = sb.webIndex.seedDB.lookupByIP(natLib.getInetAddress(client), true, false, false); theQuery.resultcount = (theSearch == null) ? 0 : theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize(); theQuery.searchtime = System.currentTimeMillis() - timestamp; theQuery.urlretrievaltime = (theSearch == null) ? 0 : theSearch.getURLRetrievalTime(); theQuery.snippetcomputationtime = (theSearch == null) ? 0 : theSearch.getSnippetComputationTime(); sb.remoteSearches.add(theQuery); // update the search tracker trackerHandles.add(theQuery.handle); sb.remoteSearchTracker.put(client, trackerHandles); // log yacyCore.log.logInfo("EXIT HASH SEARCH: " + plasmaSearchQuery.anonymizedQueryHashes(theQuery.queryHashes) + " - " + joincount + " links found, " + prop.get("linkcount", "?") + " links selected, " + indexabstractContainercount + " index abstracts, " + (System.currentTimeMillis() - timestamp) + " milliseconds"); prop.put("searchtime", System.currentTimeMillis() - timestamp); final int links = Integer.parseInt(prop.get("linkcount","0")); sb.webIndex.seedDB.mySeed().incSI(links); sb.webIndex.seedDB.mySeed().incSU(links); return prop; } }
true
true
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) { // return variable that accumulates replacements final plasmaSwitchboard sb = (plasmaSwitchboard) env; sb.remoteSearchLastAccess = System.currentTimeMillis(); serverObjects prop = new serverObjects(); if ((post == null) || (env == null)) return prop; if (!yacyNetwork.authentifyRequest(post, env)) return prop; String client = (String) header.get(httpHeader.CONNECTION_PROP_CLIENTIP); //System.out.println("yacy: search received request = " + post.toString()); final String oseed = post.get("myseed", ""); // complete seed of the requesting peer // final String youare = post.get("youare", ""); // seed hash of the target peer, used for testing network stability final String key = post.get("key", ""); // transmission key for response final String query = post.get("query", ""); // a string of word hashes that shall be searched and combined final String exclude= post.get("exclude", "");// a string of word hashes that shall not be within the search result String urls = post.get("urls", ""); // a string of url hashes that are preselected for the search: no other may be returned String abstracts = post.get("abstracts", ""); // a string of word hashes for abstracts that shall be generated, or 'auto' (for maxcount-word), or '' (for none) // final String fwdep = post.get("fwdep", ""); // forward depth. if "0" then peer may NOT ask another peer for more results // final String fwden = post.get("fwden", ""); // forward deny, a list of seed hashes. They may NOT be target of forward hopping final int count = Math.min(100, post.getInt("count", 10)); // maximum number of wanted results final int maxdist= post.getInt("maxdist", Integer.MAX_VALUE); final String prefer = post.get("prefer", ""); final String contentdom = post.get("contentdom", "text"); final String filter = post.get("filter", ".*"); final int partitions = post.getInt("partitions", 30); String profile = post.get("profile", ""); // remote profile hand-over if (profile.length() > 0) profile = crypt.simpleDecode(profile, null); //final boolean includesnippet = post.get("includesnippet", "false").equals("true"); kelondroBitfield constraint = ((post.containsKey("constraint")) && (post.get("constraint", "").length() > 0)) ? new kelondroBitfield(4, post.get("constraint", "______")) : null; if (constraint != null) { // check bad handover parameter from older versions boolean allon = true; for (int i = 0; i < 32; i++) { if (!constraint.get(i)) {allon = false; break;} } if (allon) constraint = null; } // final boolean global = ((String) post.get("resource", "global")).equals("global"); // if true, then result may consist of answers from other peers // Date remoteTime = yacyCore.parseUniversalDate((String) post.get(yacySeed.MYTIME)); // read remote time // test: // http://localhost:8080/yacy/search.html?query=4galTpdpDM5Q (search for linux) // http://localhost:8080/yacy/search.html?query=gh8DKIhGKXws (search for book) // http://localhost:8080/yacy/search.html?query=UEhMGfGv2vOE (search for kernel) // http://localhost:8080/yacy/search.html?query=ZX-LjaYo74PP (search for help) // http://localhost:8080/yacy/search.html?query=uDqIalxDfM2a (search for mail) // http://localhost:8080/yacy/search.html?query=4galTpdpDM5Qgh8DKIhGKXws&abstracts=auto (search for linux and book, generate abstract automatically) // http://localhost:8080/yacy/search.html?query=&abstracts=4galTpdpDM5Q (only abstracts for linux) if ((sb.isRobinsonMode()) && (!((sb.isPublicRobinson()) || (sb.isInMyCluster((String)header.get(httpHeader.CONNECTION_PROP_CLIENTIP)))))) { // if we are a robinson cluster, answer only if this client is known by our network definition prop.put("links", ""); prop.put("linkcount", "0"); prop.put("references", ""); return prop; } // check the search tracker TreeSet<Long> trackerHandles = sb.remoteSearchTracker.get(client); if (trackerHandles == null) trackerHandles = new TreeSet<Long>(); boolean block = false; if (trackerHandles.tailSet(new Long(System.currentTimeMillis() - 6000)).size() > 1) try { Thread.sleep(3000); block = true; } catch (InterruptedException e) { e.printStackTrace(); } if (trackerHandles.tailSet(new Long(System.currentTimeMillis() - 60000)).size() > 12) try { Thread.sleep(10000); block = true; } catch (InterruptedException e) { e.printStackTrace(); } if (trackerHandles.tailSet(new Long(System.currentTimeMillis() - 600000)).size() > 36) try { Thread.sleep(30000); block = true; } catch (InterruptedException e) { e.printStackTrace(); } if (block) { prop.put("links", ""); prop.put("linkcount", "0"); prop.put("references", ""); return prop; } // tell all threads to do nothing for a specific time sb.intermissionAllThreads(3000); TreeSet<String> abstractSet = ((abstracts.length() == 0) || (abstracts.equals("auto"))) ? null : plasmaSearchQuery.hashes2Set(abstracts); // store accessing peer yacySeed remoteSeed = yacySeed.genRemoteSeed(oseed, key, false); if (sb.webIndex.seedDB == null) { yacyCore.log.logSevere("yacy.search: seed cache not initialized"); } else { sb.webIndex.peerActions.peerArrival(remoteSeed, true); } // prepare search final TreeSet<String> queryhashes = plasmaSearchQuery.hashes2Set(query); final TreeSet<String> excludehashes = (exclude.length() == 0) ? new TreeSet<String>(kelondroBase64Order.enhancedComparator) : plasmaSearchQuery.hashes2Set(exclude); final long timestamp = System.currentTimeMillis(); // prepare a search profile plasmaSearchRankingProfile rankingProfile = (profile.length() == 0) ? new plasmaSearchRankingProfile(plasmaSearchQuery.contentdomParser(contentdom)) : new plasmaSearchRankingProfile("", profile); // prepare an abstract result StringBuffer indexabstract = new StringBuffer(); int indexabstractContainercount = 0; int joincount = 0; plasmaSearchQuery theQuery = null; ArrayList<kelondroSortStack<ResultEntry>.stackElement> accu = null; plasmaSearchEvent theSearch = null; if ((query.length() == 0) && (abstractSet != null)) { // this is _not_ a normal search, only a request for index abstracts theQuery = new plasmaSearchQuery(null, abstractSet, new TreeSet<String>(kelondroBase64Order.enhancedComparator), rankingProfile, maxdist, prefer, plasmaSearchQuery.contentdomParser(contentdom), false, count, 0, filter, plasmaSearchQuery.SEARCHDOM_LOCAL, null, -1, null, false, yacyURL.TLD_any_zone_filter, client, false); theQuery.domType = plasmaSearchQuery.SEARCHDOM_LOCAL; yacyCore.log.logInfo("INIT HASH SEARCH (abstracts only): " + plasmaSearchQuery.anonymizedQueryHashes(theQuery.queryHashes) + " - " + theQuery.displayResults() + " links"); long timer = System.currentTimeMillis(); Map<String, indexContainer>[] containers = sb.webIndex.localSearchContainers(theQuery, plasmaSearchQuery.hashes2Set(urls)); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(theQuery.id(true), plasmaSearchEvent.COLLECTION, containers[0].size(), System.currentTimeMillis() - timer)); if (containers != null) { Iterator<Map.Entry<String, indexContainer>> ci = containers[0].entrySet().iterator(); Map.Entry<String, indexContainer> entry; String wordhash; while (ci.hasNext()) { entry = ci.next(); wordhash = entry.getKey(); indexContainer container = entry.getValue(); indexabstractContainercount += container.size(); indexabstract.append("indexabstract." + wordhash + "=").append(indexContainer.compressIndex(container, null, 1000).toString()).append(serverCore.CRLF_STRING); } } prop.put("indexcount", ""); prop.put("joincount", "0"); prop.put("references", ""); } else { // retrieve index containers from search request theQuery = new plasmaSearchQuery(null, queryhashes, excludehashes, rankingProfile, maxdist, prefer, plasmaSearchQuery.contentdomParser(contentdom), false, count, 0, filter, plasmaSearchQuery.SEARCHDOM_LOCAL, null, -1, constraint, false, yacyURL.TLD_any_zone_filter, client, false); theQuery.domType = plasmaSearchQuery.SEARCHDOM_LOCAL; yacyCore.log.logInfo("INIT HASH SEARCH (query-" + abstracts + "): " + plasmaSearchQuery.anonymizedQueryHashes(theQuery.queryHashes) + " - " + theQuery.displayResults() + " links"); RSSFeed.channels(RSSFeed.REMOTESEARCH).addMessage(new RSSMessage("Remote Search Request from " + remoteSeed.getName(), plasmaSearchQuery.anonymizedQueryHashes(theQuery.queryHashes), "")); // make event theSearch = plasmaSearchEvent.getEvent(theQuery, rankingProfile, sb.webIndex, sb.crawlResults, null, true); // set statistic details of search result and find best result index set if (theSearch.getRankingResult().getLocalResourceSize() == 0) { prop.put("indexcount", ""); prop.put("joincount", "0"); } else { // attach information about index abstracts StringBuffer indexcount = new StringBuffer(); Map.Entry<String, Integer> entry; Iterator<Map.Entry<String, Integer>> i = theSearch.IACount.entrySet().iterator(); while (i.hasNext()) { entry = i.next(); indexcount.append("indexcount.").append((String) entry.getKey()).append('=').append(((Integer) entry.getValue()).toString()).append(serverCore.CRLF_STRING); } if (abstractSet != null) { // if a specific index-abstract is demanded, attach it here Iterator<String> j = abstractSet.iterator(); String wordhash; while (j.hasNext()) { wordhash = (String) j.next(); indexabstractContainercount += ((Integer) theSearch.IACount.get(wordhash)).intValue(); indexabstract.append("indexabstract." + wordhash + "=").append((String) theSearch.IAResults.get(wordhash)).append(serverCore.CRLF_STRING); } } prop.put("indexcount", indexcount.toString()); if (theSearch.getRankingResult().getLocalResourceSize() == 0) { joincount = 0; prop.put("joincount", "0"); } else { joincount = theSearch.getRankingResult().getLocalResourceSize(); prop.put("joincount", Integer.toString(joincount)); accu = theSearch.completeResults(3000); } // generate compressed index for maxcounthash // this is not needed if the search is restricted to specific // urls, because it is a re-search if ((theSearch.IAmaxcounthash == null) || (urls.length() != 0) || (queryhashes.size() <= 1) || (abstracts.length() == 0)) { prop.put("indexabstract", ""); } else if (abstracts.equals("auto")) { // automatically attach the index abstract for the index that has the most references. This should be our target dht position indexabstractContainercount += ((Integer) theSearch.IACount.get(theSearch.IAmaxcounthash)).intValue(); indexabstract.append("indexabstract." + theSearch.IAmaxcounthash + "=").append((String) theSearch.IAResults.get(theSearch.IAmaxcounthash)).append(serverCore.CRLF_STRING); if ((theSearch.IAneardhthash != null) && (!(theSearch.IAneardhthash.equals(theSearch.IAmaxcounthash)))) { // in case that the neardhthash is different from the maxcounthash attach also the neardhthash-container indexabstractContainercount += ((Integer) theSearch.IACount.get(theSearch.IAneardhthash)).intValue(); indexabstract.append("indexabstract." + theSearch.IAneardhthash + "=").append((String) theSearch.IAResults.get(theSearch.IAneardhthash)).append(serverCore.CRLF_STRING); } //System.out.println("DEBUG-ABSTRACTGENERATION: maxcounthash = " + maxcounthash); //System.out.println("DEBUG-ABSTRACTGENERATION: neardhthash = "+ neardhthash); //yacyCore.log.logFine("DEBUG HASH SEARCH: " + indexabstract); } } if (partitions > 0) sb.requestedQueries = sb.requestedQueries + 1d / partitions; // increase query counter // prepare reference hints long timer = System.currentTimeMillis(); Set<String> ws = theSearch.references(10); StringBuffer refstr = new StringBuffer(); Iterator<String> j = ws.iterator(); while (j.hasNext()) { refstr.append(",").append((String) j.next()); } prop.put("references", (refstr.length() > 0) ? refstr.substring(1) : refstr.toString()); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(theQuery.id(true), "reference collection", ws.size(), System.currentTimeMillis() - timer)); } prop.put("indexabstract", indexabstract.toString()); // prepare result if ((joincount == 0) || (accu == null)) { // no results prop.put("links", ""); prop.put("linkcount", "0"); prop.put("references", ""); } else { // result is a List of urlEntry elements long timer = System.currentTimeMillis(); StringBuffer links = new StringBuffer(); String resource = null; kelondroSortStack<plasmaSearchEvent.ResultEntry>.stackElement entry; for (int i = 0; i < accu.size(); i++) { entry = accu.get(i); resource = entry.element.resource(); if (resource != null) { links.append("resource").append(i).append('=').append(resource).append(serverCore.CRLF_STRING); } } prop.put("links", links.toString()); prop.put("linkcount", accu.size()); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(theQuery.id(true), "result list preparation", accu.size(), System.currentTimeMillis() - timer)); } // add information about forward peers prop.put("fwhop", ""); // hops (depth) of forwards that had been performed to construct this result prop.put("fwsrc", ""); // peers that helped to construct this result prop.put("fwrec", ""); // peers that would have helped to construct this result (recommendations) // prepare search statistics theQuery.remotepeer = sb.webIndex.seedDB.lookupByIP(natLib.getInetAddress(client), true, false, false); theQuery.resultcount = (theSearch == null) ? 0 : theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize(); theQuery.searchtime = System.currentTimeMillis() - timestamp; theQuery.urlretrievaltime = (theSearch == null) ? 0 : theSearch.getURLRetrievalTime(); theQuery.snippetcomputationtime = (theSearch == null) ? 0 : theSearch.getSnippetComputationTime(); sb.remoteSearches.add(theQuery); // update the search tracker trackerHandles.add(theQuery.handle); sb.remoteSearchTracker.put(client, trackerHandles); // log yacyCore.log.logInfo("EXIT HASH SEARCH: " + plasmaSearchQuery.anonymizedQueryHashes(theQuery.queryHashes) + " - " + joincount + " links found, " + prop.get("linkcount", "?") + " links selected, " + indexabstractContainercount + " index abstracts, " + (System.currentTimeMillis() - timestamp) + " milliseconds"); prop.put("searchtime", System.currentTimeMillis() - timestamp); final int links = Integer.parseInt(prop.get("linkcount","0")); sb.webIndex.seedDB.mySeed().incSI(links); sb.webIndex.seedDB.mySeed().incSU(links); return prop; }
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) { // return variable that accumulates replacements final plasmaSwitchboard sb = (plasmaSwitchboard) env; sb.remoteSearchLastAccess = System.currentTimeMillis(); serverObjects prop = new serverObjects(); if ((post == null) || (env == null)) return prop; if (!yacyNetwork.authentifyRequest(post, env)) return prop; String client = (String) header.get(httpHeader.CONNECTION_PROP_CLIENTIP); //System.out.println("yacy: search received request = " + post.toString()); final String oseed = post.get("myseed", ""); // complete seed of the requesting peer // final String youare = post.get("youare", ""); // seed hash of the target peer, used for testing network stability final String key = post.get("key", ""); // transmission key for response final String query = post.get("query", ""); // a string of word hashes that shall be searched and combined final String exclude= post.get("exclude", "");// a string of word hashes that shall not be within the search result String urls = post.get("urls", ""); // a string of url hashes that are preselected for the search: no other may be returned String abstracts = post.get("abstracts", ""); // a string of word hashes for abstracts that shall be generated, or 'auto' (for maxcount-word), or '' (for none) // final String fwdep = post.get("fwdep", ""); // forward depth. if "0" then peer may NOT ask another peer for more results // final String fwden = post.get("fwden", ""); // forward deny, a list of seed hashes. They may NOT be target of forward hopping final int count = Math.min(100, post.getInt("count", 10)); // maximum number of wanted results final int maxdist= post.getInt("maxdist", Integer.MAX_VALUE); final String prefer = post.get("prefer", ""); final String contentdom = post.get("contentdom", "text"); final String filter = post.get("filter", ".*"); final int partitions = post.getInt("partitions", 30); String profile = post.get("profile", ""); // remote profile hand-over if (profile.length() > 0) profile = crypt.simpleDecode(profile, null); //final boolean includesnippet = post.get("includesnippet", "false").equals("true"); kelondroBitfield constraint = ((post.containsKey("constraint")) && (post.get("constraint", "").length() > 0)) ? new kelondroBitfield(4, post.get("constraint", "______")) : null; if (constraint != null) { // check bad handover parameter from older versions boolean allon = true; for (int i = 0; i < 32; i++) { if (!constraint.get(i)) {allon = false; break;} } if (allon) constraint = null; } // final boolean global = ((String) post.get("resource", "global")).equals("global"); // if true, then result may consist of answers from other peers // Date remoteTime = yacyCore.parseUniversalDate((String) post.get(yacySeed.MYTIME)); // read remote time // test: // http://localhost:8080/yacy/search.html?query=4galTpdpDM5Q (search for linux) // http://localhost:8080/yacy/search.html?query=gh8DKIhGKXws (search for book) // http://localhost:8080/yacy/search.html?query=UEhMGfGv2vOE (search for kernel) // http://localhost:8080/yacy/search.html?query=ZX-LjaYo74PP (search for help) // http://localhost:8080/yacy/search.html?query=uDqIalxDfM2a (search for mail) // http://localhost:8080/yacy/search.html?query=4galTpdpDM5Qgh8DKIhGKXws&abstracts=auto (search for linux and book, generate abstract automatically) // http://localhost:8080/yacy/search.html?query=&abstracts=4galTpdpDM5Q (only abstracts for linux) if ((sb.isRobinsonMode()) && (!((sb.isPublicRobinson()) || (sb.isInMyCluster((String)header.get(httpHeader.CONNECTION_PROP_CLIENTIP)))))) { // if we are a robinson cluster, answer only if this client is known by our network definition prop.put("links", ""); prop.put("linkcount", "0"); prop.put("references", ""); return prop; } // check the search tracker TreeSet<Long> trackerHandles = sb.remoteSearchTracker.get(client); if (trackerHandles == null) trackerHandles = new TreeSet<Long>(); boolean block = false; if (trackerHandles.tailSet(new Long(System.currentTimeMillis() - 6000)).size() > 1) try { Thread.sleep(3000); block = true; } catch (InterruptedException e) { e.printStackTrace(); } if (trackerHandles.tailSet(new Long(System.currentTimeMillis() - 60000)).size() > 12) try { Thread.sleep(10000); block = true; } catch (InterruptedException e) { e.printStackTrace(); } if (trackerHandles.tailSet(new Long(System.currentTimeMillis() - 600000)).size() > 36) try { Thread.sleep(30000); block = true; } catch (InterruptedException e) { e.printStackTrace(); } if (block) { prop.put("links", ""); prop.put("linkcount", "0"); prop.put("references", ""); return prop; } // tell all threads to do nothing for a specific time sb.intermissionAllThreads(3000); TreeSet<String> abstractSet = ((abstracts.length() == 0) || (abstracts.equals("auto"))) ? null : plasmaSearchQuery.hashes2Set(abstracts); // store accessing peer yacySeed remoteSeed = yacySeed.genRemoteSeed(oseed, key, false); if (sb.webIndex.seedDB == null) { yacyCore.log.logSevere("yacy.search: seed cache not initialized"); } else { sb.webIndex.peerActions.peerArrival(remoteSeed, true); } // prepare search final TreeSet<String> queryhashes = plasmaSearchQuery.hashes2Set(query); final TreeSet<String> excludehashes = (exclude.length() == 0) ? new TreeSet<String>(kelondroBase64Order.enhancedComparator) : plasmaSearchQuery.hashes2Set(exclude); final long timestamp = System.currentTimeMillis(); // prepare a search profile plasmaSearchRankingProfile rankingProfile = (profile.length() == 0) ? new plasmaSearchRankingProfile(plasmaSearchQuery.contentdomParser(contentdom)) : new plasmaSearchRankingProfile("", profile); // prepare an abstract result StringBuffer indexabstract = new StringBuffer(); int indexabstractContainercount = 0; int joincount = 0; plasmaSearchQuery theQuery = null; ArrayList<kelondroSortStack<ResultEntry>.stackElement> accu = null; plasmaSearchEvent theSearch = null; if ((query.length() == 0) && (abstractSet != null)) { // this is _not_ a normal search, only a request for index abstracts theQuery = new plasmaSearchQuery(null, abstractSet, new TreeSet<String>(kelondroBase64Order.enhancedComparator), rankingProfile, maxdist, prefer, plasmaSearchQuery.contentdomParser(contentdom), false, count, 0, filter, plasmaSearchQuery.SEARCHDOM_LOCAL, null, -1, null, false, yacyURL.TLD_any_zone_filter, client, false); theQuery.domType = plasmaSearchQuery.SEARCHDOM_LOCAL; yacyCore.log.logInfo("INIT HASH SEARCH (abstracts only): " + plasmaSearchQuery.anonymizedQueryHashes(theQuery.queryHashes) + " - " + theQuery.displayResults() + " links"); long timer = System.currentTimeMillis(); Map<String, indexContainer>[] containers = sb.webIndex.localSearchContainers(theQuery, plasmaSearchQuery.hashes2Set(urls)); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(theQuery.id(true), plasmaSearchEvent.COLLECTION, containers[0].size(), System.currentTimeMillis() - timer)); if (containers != null) { Iterator<Map.Entry<String, indexContainer>> ci = containers[0].entrySet().iterator(); Map.Entry<String, indexContainer> entry; String wordhash; while (ci.hasNext()) { entry = ci.next(); wordhash = entry.getKey(); indexContainer container = entry.getValue(); indexabstractContainercount += container.size(); indexabstract.append("indexabstract." + wordhash + "=").append(indexContainer.compressIndex(container, null, 1000).toString()).append(serverCore.CRLF_STRING); } } prop.put("indexcount", ""); prop.put("joincount", "0"); prop.put("references", ""); } else { // retrieve index containers from search request theQuery = new plasmaSearchQuery(null, queryhashes, excludehashes, rankingProfile, maxdist, prefer, plasmaSearchQuery.contentdomParser(contentdom), false, count, 0, filter, plasmaSearchQuery.SEARCHDOM_LOCAL, null, -1, constraint, false, yacyURL.TLD_any_zone_filter, client, false); theQuery.domType = plasmaSearchQuery.SEARCHDOM_LOCAL; yacyCore.log.logInfo("INIT HASH SEARCH (query-" + abstracts + "): " + plasmaSearchQuery.anonymizedQueryHashes(theQuery.queryHashes) + " - " + theQuery.displayResults() + " links"); RSSFeed.channels(RSSFeed.REMOTESEARCH).addMessage(new RSSMessage("Remote Search Request from " + ((remoteSeed == null) ? "unknown" : remoteSeed.getName()), plasmaSearchQuery.anonymizedQueryHashes(theQuery.queryHashes), "")); // make event theSearch = plasmaSearchEvent.getEvent(theQuery, rankingProfile, sb.webIndex, sb.crawlResults, null, true); // set statistic details of search result and find best result index set if (theSearch.getRankingResult().getLocalResourceSize() == 0) { prop.put("indexcount", ""); prop.put("joincount", "0"); } else { // attach information about index abstracts StringBuffer indexcount = new StringBuffer(); Map.Entry<String, Integer> entry; Iterator<Map.Entry<String, Integer>> i = theSearch.IACount.entrySet().iterator(); while (i.hasNext()) { entry = i.next(); indexcount.append("indexcount.").append((String) entry.getKey()).append('=').append(((Integer) entry.getValue()).toString()).append(serverCore.CRLF_STRING); } if (abstractSet != null) { // if a specific index-abstract is demanded, attach it here Iterator<String> j = abstractSet.iterator(); String wordhash; while (j.hasNext()) { wordhash = (String) j.next(); indexabstractContainercount += ((Integer) theSearch.IACount.get(wordhash)).intValue(); indexabstract.append("indexabstract." + wordhash + "=").append((String) theSearch.IAResults.get(wordhash)).append(serverCore.CRLF_STRING); } } prop.put("indexcount", indexcount.toString()); if (theSearch.getRankingResult().getLocalResourceSize() == 0) { joincount = 0; prop.put("joincount", "0"); } else { joincount = theSearch.getRankingResult().getLocalResourceSize(); prop.put("joincount", Integer.toString(joincount)); accu = theSearch.completeResults(3000); } // generate compressed index for maxcounthash // this is not needed if the search is restricted to specific // urls, because it is a re-search if ((theSearch.IAmaxcounthash == null) || (urls.length() != 0) || (queryhashes.size() <= 1) || (abstracts.length() == 0)) { prop.put("indexabstract", ""); } else if (abstracts.equals("auto")) { // automatically attach the index abstract for the index that has the most references. This should be our target dht position indexabstractContainercount += ((Integer) theSearch.IACount.get(theSearch.IAmaxcounthash)).intValue(); indexabstract.append("indexabstract." + theSearch.IAmaxcounthash + "=").append((String) theSearch.IAResults.get(theSearch.IAmaxcounthash)).append(serverCore.CRLF_STRING); if ((theSearch.IAneardhthash != null) && (!(theSearch.IAneardhthash.equals(theSearch.IAmaxcounthash)))) { // in case that the neardhthash is different from the maxcounthash attach also the neardhthash-container indexabstractContainercount += ((Integer) theSearch.IACount.get(theSearch.IAneardhthash)).intValue(); indexabstract.append("indexabstract." + theSearch.IAneardhthash + "=").append((String) theSearch.IAResults.get(theSearch.IAneardhthash)).append(serverCore.CRLF_STRING); } //System.out.println("DEBUG-ABSTRACTGENERATION: maxcounthash = " + maxcounthash); //System.out.println("DEBUG-ABSTRACTGENERATION: neardhthash = "+ neardhthash); //yacyCore.log.logFine("DEBUG HASH SEARCH: " + indexabstract); } } if (partitions > 0) sb.requestedQueries = sb.requestedQueries + 1d / partitions; // increase query counter // prepare reference hints long timer = System.currentTimeMillis(); Set<String> ws = theSearch.references(10); StringBuffer refstr = new StringBuffer(); Iterator<String> j = ws.iterator(); while (j.hasNext()) { refstr.append(",").append((String) j.next()); } prop.put("references", (refstr.length() > 0) ? refstr.substring(1) : refstr.toString()); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(theQuery.id(true), "reference collection", ws.size(), System.currentTimeMillis() - timer)); } prop.put("indexabstract", indexabstract.toString()); // prepare result if ((joincount == 0) || (accu == null)) { // no results prop.put("links", ""); prop.put("linkcount", "0"); prop.put("references", ""); } else { // result is a List of urlEntry elements long timer = System.currentTimeMillis(); StringBuffer links = new StringBuffer(); String resource = null; kelondroSortStack<plasmaSearchEvent.ResultEntry>.stackElement entry; for (int i = 0; i < accu.size(); i++) { entry = accu.get(i); resource = entry.element.resource(); if (resource != null) { links.append("resource").append(i).append('=').append(resource).append(serverCore.CRLF_STRING); } } prop.put("links", links.toString()); prop.put("linkcount", accu.size()); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(theQuery.id(true), "result list preparation", accu.size(), System.currentTimeMillis() - timer)); } // add information about forward peers prop.put("fwhop", ""); // hops (depth) of forwards that had been performed to construct this result prop.put("fwsrc", ""); // peers that helped to construct this result prop.put("fwrec", ""); // peers that would have helped to construct this result (recommendations) // prepare search statistics theQuery.remotepeer = sb.webIndex.seedDB.lookupByIP(natLib.getInetAddress(client), true, false, false); theQuery.resultcount = (theSearch == null) ? 0 : theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize(); theQuery.searchtime = System.currentTimeMillis() - timestamp; theQuery.urlretrievaltime = (theSearch == null) ? 0 : theSearch.getURLRetrievalTime(); theQuery.snippetcomputationtime = (theSearch == null) ? 0 : theSearch.getSnippetComputationTime(); sb.remoteSearches.add(theQuery); // update the search tracker trackerHandles.add(theQuery.handle); sb.remoteSearchTracker.put(client, trackerHandles); // log yacyCore.log.logInfo("EXIT HASH SEARCH: " + plasmaSearchQuery.anonymizedQueryHashes(theQuery.queryHashes) + " - " + joincount + " links found, " + prop.get("linkcount", "?") + " links selected, " + indexabstractContainercount + " index abstracts, " + (System.currentTimeMillis() - timestamp) + " milliseconds"); prop.put("searchtime", System.currentTimeMillis() - timestamp); final int links = Integer.parseInt(prop.get("linkcount","0")); sb.webIndex.seedDB.mySeed().incSI(links); sb.webIndex.seedDB.mySeed().incSU(links); return prop; }
diff --git a/nuxeo-core-storage-sql/nuxeo-core-storage-sql/src/main/java/org/nuxeo/ecm/core/storage/sql/db/dialect/DialectPostgreSQL.java b/nuxeo-core-storage-sql/nuxeo-core-storage-sql/src/main/java/org/nuxeo/ecm/core/storage/sql/db/dialect/DialectPostgreSQL.java index 5e92d0525..a6c1624c0 100644 --- a/nuxeo-core-storage-sql/nuxeo-core-storage-sql/src/main/java/org/nuxeo/ecm/core/storage/sql/db/dialect/DialectPostgreSQL.java +++ b/nuxeo-core-storage-sql/nuxeo-core-storage-sql/src/main/java/org/nuxeo/ecm/core/storage/sql/db/dialect/DialectPostgreSQL.java @@ -1,1290 +1,1292 @@ /* * (C) Copyright 2008-2009 Nuxeo SA (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * Florent Guillaume * Benoit Delbosc */ package org.nuxeo.ecm.core.storage.sql.db.dialect; import java.io.Serializable; import java.net.SocketException; import java.sql.Array; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.sql.Types; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.GregorianCalendar; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.common.utils.StringUtils; import org.nuxeo.ecm.core.storage.StorageException; import org.nuxeo.ecm.core.storage.sql.Binary; import org.nuxeo.ecm.core.storage.sql.Model; import org.nuxeo.ecm.core.storage.sql.RepositoryDescriptor; import org.nuxeo.ecm.core.storage.sql.Model.FulltextInfo; import org.nuxeo.ecm.core.storage.sql.db.Column; import org.nuxeo.ecm.core.storage.sql.db.ColumnType; import org.nuxeo.ecm.core.storage.sql.db.Database; import org.nuxeo.ecm.core.storage.sql.db.Table; /** * PostgreSQL-specific dialect. * * @author Florent Guillaume */ public class DialectPostgreSQL extends Dialect { private static final Log log = LogFactory.getLog(DialectPostgreSQL.class); private static final String DEFAULT_FULLTEXT_ANALYZER = "english"; protected final String fulltextAnalyzer; protected boolean hierarchyCreated; protected boolean pathOptimizationsEnabled; public DialectPostgreSQL(DatabaseMetaData metadata, RepositoryDescriptor repositoryDescriptor) throws StorageException { super(metadata); fulltextAnalyzer = repositoryDescriptor.fulltextAnalyzer == null ? DEFAULT_FULLTEXT_ANALYZER : repositoryDescriptor.fulltextAnalyzer; pathOptimizationsEnabled = repositoryDescriptor.pathOptimizationsEnabled; } @Override public String toBooleanValueString(boolean bool) { return bool ? "true" : "false"; } @Override public String getNoColumnsInsertString() { return "DEFAULT VALUES"; } @Override public String getCascadeDropConstraintsString() { return "CASCADE"; } @Override public JDBCInfo getJDBCTypeAndString(ColumnType type) { switch (type) { case VARCHAR: return jdbcInfo("varchar", Types.VARCHAR); case CLOB: return jdbcInfo("text", Types.CLOB); case BOOLEAN: return jdbcInfo("bool", Types.BIT); case LONG: return jdbcInfo("int8", Types.BIGINT); case DOUBLE: return jdbcInfo("float8", Types.DOUBLE); case TIMESTAMP: return jdbcInfo("timestamp", Types.TIMESTAMP); case BLOBID: return jdbcInfo("varchar(32)", Types.VARCHAR); // ----- case NODEID: case NODEIDFK: case NODEIDFKNP: case NODEIDFKMUL: case NODEIDFKNULL: case NODEVAL: return jdbcInfo("varchar(36)", Types.VARCHAR); case SYSNAME: return jdbcInfo("varchar(250)", Types.VARCHAR); case TINYINT: return jdbcInfo("int2", Types.SMALLINT); case INTEGER: return jdbcInfo("int4", Types.INTEGER); case FTINDEXED: return jdbcInfo("tsvector", Types.OTHER); case FTSTORED: return jdbcInfo("tsvector", Types.OTHER); case CLUSTERNODE: return jdbcInfo("int4", Types.INTEGER); case CLUSTERFRAGS: return jdbcInfo("varchar[]", Types.ARRAY); } throw new AssertionError(type); } @Override public boolean isAllowedConversion(int expected, int actual, String actualName, int actualSize) { // CLOB vs VARCHAR compatibility if (expected == Types.VARCHAR && actual == Types.CLOB) { return true; } if (expected == Types.CLOB && actual == Types.VARCHAR) { return true; } // INTEGER vs BIGINT compatibility if (expected == Types.BIGINT && actual == Types.INTEGER) { return true; } if (expected == Types.INTEGER && actual == Types.BIGINT) { return true; } return false; } @Override public void setToPreparedStatement(PreparedStatement ps, int index, Serializable value, Column column) throws SQLException { switch (column.getJdbcType()) { case Types.VARCHAR: case Types.CLOB: String v; if (column.getType() == ColumnType.BLOBID) { v = ((Binary) value).getDigest(); } else { v = (String) value; } ps.setString(index, v); break; case Types.BIT: ps.setBoolean(index, ((Boolean) value).booleanValue()); return; case Types.SMALLINT: ps.setInt(index, ((Long) value).intValue()); return; case Types.INTEGER: case Types.BIGINT: ps.setLong(index, ((Long) value).longValue()); return; case Types.DOUBLE: ps.setDouble(index, ((Double) value).doubleValue()); return; case Types.TIMESTAMP: Calendar cal = (Calendar) value; Timestamp ts = new Timestamp(cal.getTimeInMillis()); ps.setTimestamp(index, ts, cal); // cal passed for timezone return; case Types.ARRAY: Array array = createArrayOf(Types.VARCHAR, (Object[]) value, ps.getConnection()); ps.setArray(index, array); return; case Types.OTHER: if (column.getType() == ColumnType.FTSTORED) { ps.setString(index, (String) value); return; } throw new SQLException("Unhandled type: " + column.getType()); default: throw new SQLException("Unhandled JDBC type: " + column.getJdbcType()); } } @Override @SuppressWarnings("boxing") public Serializable getFromResultSet(ResultSet rs, int index, Column column) throws SQLException { switch (column.getJdbcType()) { case Types.VARCHAR: case Types.CLOB: String string = rs.getString(index); if (column.getType() == ColumnType.BLOBID && string != null) { return column.getModel().getBinary(string); } else { return string; } case Types.BIT: return rs.getBoolean(index); case Types.SMALLINT: case Types.INTEGER: case Types.BIGINT: return rs.getLong(index); case Types.DOUBLE: return rs.getDouble(index); case Types.TIMESTAMP: Timestamp ts = rs.getTimestamp(index); if (ts == null) { return null; } else { Serializable cal = new GregorianCalendar(); // XXX timezone ((Calendar) cal).setTimeInMillis(ts.getTime()); return cal; } case Types.ARRAY: return (Serializable) rs.getArray(index).getArray(); } throw new SQLException("Unhandled JDBC type: " + column.getJdbcType()); } @Override public String getCreateFulltextIndexSql(String indexName, String quotedIndexName, Table table, List<Column> columns, Model model) { return String.format("CREATE INDEX %s ON %s USING GIN(%s)", quotedIndexName.toLowerCase(), table.getQuotedName(), columns.get(0).getQuotedName()); } @Override public String getDialectFulltextQuery(String query) { query = query.replace(" & ", " "); // PostgreSQL compatibility BBB query = query.replaceAll(" +", " "); List<String> res = new LinkedList<String>(); for (String word : StringUtils.split(query, ' ', false)) { if (word.startsWith("-")) { res.add("!" + word.substring(1)); } else if (word.startsWith("+")) { res.add(word.substring(1)); } else { res.add(word); } } return StringUtils.join(res, " & "); } @Override public String[] getFulltextMatch(String indexName, String fulltextQuery, Column mainColumn, Model model, Database database) { // TODO multiple indexes String suffix = model.getFulltextIndexSuffix(indexName); Column ftColumn = database.getTable(model.FULLTEXT_TABLE_NAME).getColumn( model.FULLTEXT_FULLTEXT_KEY + suffix); String whereExpr = String.format("NX_CONTAINS(%s, ?)", ftColumn.getFullQuotedName()); return new String[] { null, null, whereExpr, fulltextQuery }; } @Override public boolean getMaterializeFulltextSyntheticColumn() { return true; } @Override public int getFulltextIndexedColumns() { return 1; } @Override public String getFreeVariableSetterForType(ColumnType type) { if (type == ColumnType.FTSTORED) { return "NX_TO_TSVECTOR(?)"; } return "?"; } @Override public boolean supportsUpdateFrom() { return true; } @Override public boolean doesUpdateFromRepeatSelf() { return false; } @Override public boolean needsAliasForDerivedTable() { return true; } @Override public boolean supportsReadAcl() { return true; } @Override public String getReadAclsCheckSql(String idColumnName) { return String.format("%s IN (SELECT * FROM nx_get_read_acls_for(?))", idColumnName); } @Override public String getUpdateReadAclsSql() { return "SELECT nx_update_read_acls();"; } @Override public String getRebuildReadAclsSql() { return "SELECT nx_rebuild_read_acls();"; } @Override public String getSecurityCheckSql(String idColumnName) { return String.format("NX_ACCESS_ALLOWED(%s, ?, ?)", idColumnName); } @Override public boolean supportsDescendantsTable() { return true; } @Override public String getInTreeSql(String idColumnName) { if (pathOptimizationsEnabled) { return String.format( "EXISTS(SELECT 1 FROM descendants WHERE id = ? AND descendantid = %s)", idColumnName); } else { return String.format("NX_IN_TREE(%s, ?)", idColumnName); } } @Override public boolean supportsArrays() { return true; } @Override public Array createArrayOf(int type, Object[] elements, Connection connection) throws SQLException { if (elements == null || elements.length == 0) { return null; } String typeName; switch (type) { case Types.VARCHAR: typeName = "varchar"; break; default: // TODO others not used yet throw new RuntimeException("" + type); } return new PostgreSQLArray(type, typeName, elements); } public static class PostgreSQLArray implements Array { private static final String NOT_SUPPORTED = "Not supported"; protected final int type; protected final String typeName; protected final Object[] elements; protected final String string; public PostgreSQLArray(int type, String typeName, Object[] elements) { this.type = type; if (type == Types.VARCHAR) { typeName = "varchar"; } this.typeName = typeName; this.elements = elements; StringBuilder b = new StringBuilder(); appendArray(b, elements); string = b.toString(); } protected static void appendArray(StringBuilder b, Object[] elements) { b.append('{'); for (int i = 0; i < elements.length; i++) { Object e = elements[i]; if (i > 0) { b.append(','); } if (e == null) { b.append("NULL"); } else if (e.getClass().isArray()) { appendArray(b, (Object[]) e); } else { // we always transform to a string, the postgres // array parsing methods will then reparse this as needed String s = e.toString(); b.append('"'); for (int j = 0; j < s.length(); j++) { char c = s.charAt(j); if (c == '"' || c == '\\') { b.append('\\'); } b.append(c); } b.append('"'); } } b.append('}'); } @Override public String toString() { return string; } public int getBaseType() { return type; } public String getBaseTypeName() { return typeName; } public Object getArray() { return elements; } public Object getArray(Map<String, Class<?>> map) throws SQLException { throw new SQLException(NOT_SUPPORTED); } public Object getArray(long index, int count) throws SQLException { throw new SQLException(NOT_SUPPORTED); } public Object getArray(long index, int count, Map<String, Class<?>> map) throws SQLException { throw new SQLException(NOT_SUPPORTED); } public ResultSet getResultSet() throws SQLException { throw new SQLException(NOT_SUPPORTED); } public ResultSet getResultSet(Map<String, Class<?>> map) throws SQLException { throw new SQLException(NOT_SUPPORTED); } public ResultSet getResultSet(long index, int count) throws SQLException { throw new SQLException(NOT_SUPPORTED); } public ResultSet getResultSet(long index, int count, Map<String, Class<?>> map) throws SQLException { throw new SQLException(NOT_SUPPORTED); } // this is needed by JDBC 4 (Java 6) public void free() { } } @Override public Collection<ConditionalStatement> getConditionalStatements( Model model, Database database) { String idType; switch (model.idGenPolicy) { case APP_UUID: idType = "varchar(36)"; break; case DB_IDENTITY: idType = "integer"; break; default: throw new AssertionError(model.idGenPolicy); } Table ht = database.getTable(model.hierTableName); Table ft = database.getTable(model.FULLTEXT_TABLE_NAME); List<ConditionalStatement> statements = new LinkedList<ConditionalStatement>(); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // String.format( "CREATE OR REPLACE FUNCTION NX_IN_TREE(id %s, baseid %<s) " // + "RETURNS boolean " // + "AS $$ " // + "DECLARE" // + " curid %<s := id; " // + "BEGIN" // + " IF baseid IS NULL OR id IS NULL OR baseid = id THEN" // + " RETURN false;" // + " END IF;" // + " LOOP" // + " SELECT parentid INTO curid FROM hierarchy WHERE hierarchy.id = curid;" // + " IF curid IS NULL THEN" // + " RETURN false; " // + " ELSEIF curid = baseid THEN" // + " RETURN true;" // + " END IF;" // + " END LOOP;" // + "END " // + "$$ " // + "LANGUAGE plpgsql " // + "STABLE " // + "COST 400 " // , idType))); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // String.format( "CREATE OR REPLACE FUNCTION NX_ACCESS_ALLOWED" // + "(id %s, users varchar[], permissions varchar[]) " // + "RETURNS boolean " // + "AS $$ " // + "DECLARE" // + " curid %<s := id;" // + " newid %<s;" // + " r record;" // + " first boolean := true;" // + "BEGIN" // + " WHILE curid IS NOT NULL LOOP" // + " FOR r in SELECT acls.grant, acls.permission, acls.user FROM acls WHERE acls.id = curid ORDER BY acls.pos LOOP" + " IF r.permission = ANY(permissions) AND r.user = ANY(users) THEN" // + " RETURN r.grant;" // + " END IF;" // + " END LOOP;" // + " SELECT parentid INTO newid FROM hierarchy WHERE hierarchy.id = curid;" // + " IF first AND newid IS NULL THEN" // + " SELECT versionableid INTO newid FROM versions WHERE versions.id = curid;" // + " END IF;" // + " first := false;" // + " curid := newid;" // + " END LOOP;" // + " RETURN false; " // + "END " // + "$$ " // + "LANGUAGE plpgsql " // + "STABLE " // + "COST 500 " // , idType))); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // String.format( "CREATE OR REPLACE FUNCTION NX_TO_TSVECTOR(string VARCHAR) " // + "RETURNS TSVECTOR " // + "AS $$" // + " SELECT TO_TSVECTOR('%s', SUBSTR($1, 1, 250000)) " // + "$$ " // + "LANGUAGE sql " // + "STABLE " // , fulltextAnalyzer))); statements.add(new ConditionalStatement( // true, // early Boolean.FALSE, // no drop needed null, // null, // String.format( "CREATE OR REPLACE FUNCTION NX_CONTAINS(ft TSVECTOR, query VARCHAR) " // + "RETURNS boolean " // + "AS $$" // + " SELECT $1 @@ TO_TSQUERY('%s', $2) " // + "$$ " // + "LANGUAGE sql " // + "STABLE " // , fulltextAnalyzer))); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // String.format( "CREATE OR REPLACE FUNCTION NX_CLUSTER_INVAL" // + "(i %s, f varchar[], k int) " // + "RETURNS VOID " // + "AS $$ " // + "DECLARE" // + " nid int; " // + "BEGIN" // + " FOR nid IN SELECT nodeid FROM cluster_nodes WHERE nodeid <> pg_backend_pid() LOOP" // + " INSERT INTO cluster_invals (nodeid, id, fragments, kind) VALUES (nid, i, f, k);" // + " END LOOP; " // + "END " // + "$$ " // + "LANGUAGE plpgsql" // , idType))); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // "CREATE OR REPLACE FUNCTION NX_CLUSTER_GET_INVALS() " // + "RETURNS SETOF RECORD " // + "AS $$ " // + "DECLARE" // + " r RECORD; " // + "BEGIN" // + " FOR r IN SELECT id, fragments, kind FROM cluster_invals WHERE nodeid = pg_backend_pid() LOOP" // + " RETURN NEXT r;" // + " END LOOP;" // + " DELETE FROM cluster_invals WHERE nodeid = pg_backend_pid();" // + " RETURN; " // + "END " // + "$$ " // + "LANGUAGE plpgsql" // )); FulltextInfo fti = model.getFulltextInfo(); List<String> lines = new ArrayList<String>(fti.indexNames.size()); for (String indexName : fti.indexNames) { String suffix = model.getFulltextIndexSuffix(indexName); Column ftft = ft.getColumn(model.FULLTEXT_FULLTEXT_KEY + suffix); Column ftst = ft.getColumn(model.FULLTEXT_SIMPLETEXT_KEY + suffix); Column ftbt = ft.getColumn(model.FULLTEXT_BINARYTEXT_KEY + suffix); String line = String.format( " NEW.%s := COALESCE(NEW.%s, ''::TSVECTOR) || COALESCE(NEW.%s, ''::TSVECTOR);", ftft.getQuotedName(), ftst.getQuotedName(), ftbt.getQuotedName()); lines.add(line); } statements.add(new ConditionalStatement( // false, // late Boolean.FALSE, // no drop needed null, // null, // "CREATE OR REPLACE FUNCTION NX_UPDATE_FULLTEXT() " // + "RETURNS trigger " // + "AS $$ " // + "BEGIN" // + StringUtils.join(lines, "") // + " RETURN NEW; " // + "END " // + "$$ " // + "LANGUAGE plpgsql " // + "VOLATILE " // )); statements.add(new ConditionalStatement( false, // late Boolean.TRUE, // do a drop null, // String.format("DROP TRIGGER IF EXISTS NX_TRIG_FT_UPDATE ON %s", ft.getQuotedName()), String.format("CREATE TRIGGER NX_TRIG_FT_UPDATE " // + "BEFORE INSERT OR UPDATE ON %s " + "FOR EACH ROW EXECUTE PROCEDURE NX_UPDATE_FULLTEXT()" // , ft.getQuotedName()))); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // "CREATE OR REPLACE FUNCTION NX_DESCENDANTS_CREATE_TRIGGERS() " // + "RETURNS void " // + "AS $$ " // + " DROP TRIGGER IF EXISTS NX_TRIG_DESC_INSERT ON hierarchy;" // + " CREATE TRIGGER NX_TRIG_DESC_INSERT" // + " AFTER INSERT ON hierarchy" // + " FOR EACH ROW EXECUTE PROCEDURE NX_DESCENDANTS_INSERT();" // + " DROP TRIGGER IF EXISTS NX_TRIG_DESC_UPDATE ON hierarchy;" // + " CREATE TRIGGER NX_TRIG_DESC_UPDATE" // + " AFTER UPDATE ON hierarchy" // + " FOR EACH ROW EXECUTE PROCEDURE NX_DESCENDANTS_UPDATE(); " // + "$$ " // + "LANGUAGE sql " // + "VOLATILE " // )); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // "CREATE OR REPLACE FUNCTION NX_INIT_DESCENDANTS() " // + "RETURNS void " // + "AS $$ " // + "DECLARE" // + " curid varchar(36); " // + " curparentid varchar(36); " // + "BEGIN " // + " PERFORM NX_DESCENDANTS_CREATE_TRIGGERS(); " // + " CREATE TEMP TABLE nxtodo (id varchar(36), parentid varchar(36)) ON COMMIT DROP; " // + " CREATE INDEX nxtodo_idx ON nxtodo (id);" // + " INSERT INTO nxtodo SELECT id, NULL FROM repositories;" // + " TRUNCATE TABLE descendants;" // + " LOOP" // + " -- get next node in queue\n" // + " SELECT id, parentid INTO curid, curparentid FROM nxtodo LIMIT 1;" // + " IF NOT FOUND THEN" // + " EXIT;" // + " END IF;" // + " DELETE FROM nxtodo WHERE id = curid;" // + " -- add children to queue\n" // + " INSERT INTO nxtodo SELECT id, curid FROM hierarchy" // + " WHERE parentid = curid and NOT isproperty;" // + " IF curparentid IS NULL THEN" // + " CONTINUE;" // + " END IF;" // + " -- process the node\n" // + " INSERT INTO descendants (id, descendantid)" // + " SELECT id, curid FROM descendants WHERE descendantid = curparentid;" // + " INSERT INTO descendants (id, descendantid) VALUES (curparentid, curid);" // + " END LOOP;" // + "END " // + "$$ " // + "LANGUAGE plpgsql " // + "VOLATILE " // )); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // "CREATE OR REPLACE FUNCTION NX_DESCENDANTS_INSERT() " // + "RETURNS trigger " // + "AS $$ " // + "BEGIN " // + " IF NEW.isproperty THEN" // + " RETURN NULL; " // + " END IF;" // + " IF NEW.parentid IS NULL THEN" // + " RETURN NULL; " // + " END IF;" // + " IF NEW.id IS NULL THEN" // + " RAISE EXCEPTION 'Cannot have NULL id'; " // + " END IF;" // + " INSERT INTO descendants (id, descendantid)" // + " SELECT id, NEW.id FROM descendants WHERE descendantid = NEW.parentid;" // + " INSERT INTO descendants (id, descendantid) VALUES (NEW.parentid, NEW.id);" // + " RETURN NULL; " // + "END " // + "$$ " // + "LANGUAGE plpgsql " // + "VOLATILE " // )); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // "CREATE OR REPLACE FUNCTION NX_DESCENDANTS_UPDATE() " // + "RETURNS trigger " // + "AS $$ " // + "BEGIN " // + " IF NEW.isproperty THEN" // + " RETURN NULL; " // + " END IF;" // + " IF OLD.id IS DISTINCT FROM NEW.id THEN" // + " RAISE EXCEPTION 'Cannot change id'; " // + " END IF;" // + " IF OLD.parentid IS NOT DISTINCT FROM NEW.parentid THEN" // + " RETURN NULL; " // + " END IF;" // + " IF NEW.id IS NULL THEN" // + " RAISE EXCEPTION 'Cannot have NULL id'; " // + " END IF;" // + " IF OLD.parentid IS NOT NULL THEN" // + " IF NEW.parentid IS NOT NULL THEN" // + " IF NEW.parentid = NEW.id THEN" // + " RAISE EXCEPTION 'Cannot move a node under itself'; " // + " END IF;" // + " IF EXISTS(SELECT 1 FROM descendants WHERE id = NEW.id AND descendantid = NEW.parentid) THEN" // + " RAISE EXCEPTION 'Cannot move a node under one of its descendants'; " // + " END IF;" // + " END IF;" // + " -- the old parent and its ancestors lose some descendants\n" // + " DELETE FROM descendants" // + " WHERE id IN (SELECT id FROM descendants WHERE descendantid = NEW.id)" // + " AND descendantid IN (SELECT descendantid FROM descendants WHERE id = NEW.id" // + " UNION ALL SELECT NEW.id);" // + " END IF;" // + " IF NEW.parentid IS NOT NULL THEN" // + " -- the new parent's ancestors gain as descendants\n" // + " -- the descendants of the moved node (cross join)\n" // + " INSERT INTO descendants (id, descendantid)" // + " (SELECT A.id, B.descendantid FROM descendants A CROSS JOIN descendants B" // + " WHERE A.descendantid = NEW.parentid AND B.id = NEW.id);" // + " -- the new parent's ancestors gain as descendant the moved node\n" // + " INSERT INTO descendants (id, descendantid)" // + " SELECT id, NEW.id FROM descendants WHERE descendantid = NEW.parentid;" // + " -- the new parent gains as descendants the descendants of the moved node\n" // + " INSERT INTO descendants (id, descendantid)" // + " SELECT NEW.parentid, descendantid FROM descendants WHERE id = NEW.id;" // + " -- the new parent gains as descendant the moved node\n" // + " INSERT INTO descendants (id, descendantid)" // + " VALUES (NEW.parentid, NEW.id);" // + " END IF;" // + " RETURN NULL; " // + "END " // + "$$ " // + "LANGUAGE plpgsql " // + "VOLATILE " // )); // read acls ---------------------------------------------------------- // table to store canonical read acls statements.add(new ConditionalStatement( false, // late null, // perform a check "SELECT 1 WHERE NOT EXISTS(SELECT 1 FROM pg_tables WHERE tablename='read_acls');", "CREATE TABLE read_acls (" + " id character varying(34) PRIMARY KEY," + " acl character varying(4096));", // "SELECT 1;")); // table to maintain a read acl for each hierarchy entry statements.add(new ConditionalStatement( false, // late null, // perform a check "SELECT 1 WHERE NOT EXISTS(SELECT 1 FROM pg_tables WHERE tablename='hierarchy_read_acl');", "CREATE TABLE hierarchy_read_acl (" + " id character varying(36) PRIMARY KEY," + " acl_id character varying(34)," + " CONSTRAINT hierarchy_read_acl_id_fk FOREIGN KEY (id) REFERENCES hierarchy(id) ON DELETE CASCADE" + ");", // "SELECT 1;")); // Add index statements.add(new ConditionalStatement( false, // late null, // perform a check "SELECT 1 WHERE NOT EXISTS(SELECT 1 FROM pg_indexes WHERE indexname='hierarchy_read_acl_acl_id_idx');", "CREATE INDEX hierarchy_read_acl_acl_id_idx ON hierarchy_read_acl USING btree (acl_id);", "SELECT 1;")); // Log hierarchy with updated read acl statements.add(new ConditionalStatement( false, // late null, // perform a check "SELECT 1 WHERE NOT EXISTS(SELECT 1 FROM pg_tables WHERE tablename='hierarchy_modified_acl');", "CREATE TABLE hierarchy_modified_acl (" + " id character varying(36)," // + " is_new boolean" // + ");", // "SELECT 1;")); statements.add(new ConditionalStatement( false, // late Boolean.FALSE, // do a drop null, // null, // "CREATE OR REPLACE FUNCTION nx_get_local_read_acl(id character varying) RETURNS character varying AS $$\n" // + " -- Compute the read acl for a hierarchy id using a local acl\n" // + "DECLARE\n" // + " curid varchar(36) := id;\n" // + " read_acl varchar(4096) := NULL;\n" // + " r record;\n" // + "BEGIN\n" // + " -- RAISE INFO 'call %', curid;\n" // + " FOR r in SELECT CASE\n" // + " WHEN (acls.grant AND\n" // + " acls.permission IN ('Read', 'ReadWrite', 'Everything', 'Browse')) THEN\n" // + " acls.user\n" // + " WHEN (NOT acls.grant AND\n" // + " acls.permission IN ('Read', 'ReadWrite', 'Everything', 'Browse')) THEN\n" // + " '-'|| acls.user\n" // + " ELSE NULL END AS op\n" // + " FROM acls WHERE acls.id = curid\n" // + " ORDER BY acls.pos LOOP\n" // + " IF r.op IS NULL THEN\n" // + " CONTINUE;\n" // + " END IF;\n" // + " IF read_acl IS NULL THEN\n" // + " read_acl := r.op;\n" // + " ELSE\n" // + " read_acl := read_acl || ',' || r.op;\n" // + " END IF;\n" // + " END LOOP;\n" // + " RETURN read_acl;\n" // + "END $$\n" // + "LANGUAGE plpgsql STABLE;")); statements.add(new ConditionalStatement( false, // late Boolean.FALSE, // do a drop null, // null, // "CREATE OR REPLACE FUNCTION nx_get_read_acl(id character varying) RETURNS character varying AS $$\n" // + " -- Compute the read acl for a hierarchy id using inherited acl \n" // + "DECLARE\n" // + " curid varchar(36) := id;\n" // + " newid varchar(36);\n" // + " first boolean := true;\n" // + " read_acl varchar(4096);\n" // + " ret varchar(4096);\n" // + "BEGIN\n" // + " -- RAISE INFO 'call %', curid;\n" // + " WHILE curid IS NOT NULL LOOP\n" // + " -- RAISE INFO ' curid %', curid;\n" // + " SELECT nx_get_local_read_acl(curid) INTO read_acl;\n" // + " IF (read_acl IS NOT NULL) THEN\n" // + " IF (ret is NULL) THEN\n" // + " ret = read_acl;\n" // + " ELSE\n" // + " ret := ret || ',' || read_acl;\n" // + " END IF;\n" // + " END IF;\n" // + " SELECT parentid INTO newid FROM hierarchy WHERE hierarchy.id = curid;\n" // + " IF (first AND newid IS NULL) THEN\n" // + " SELECT versionableid INTO newid FROM versions WHERE versions.id = curid;\n" // + " END IF;\n" // + " first := false;\n" // + " curid := newid;\n" // + " END LOOP;\n" // + " IF (ret is NULL) THEN\n" // + " ret = '_empty';\n" // + " END IF;\n" // + " RETURN ret;\n" // + "END $$\n" // + "LANGUAGE plpgsql STABLE;")); statements.add(new ConditionalStatement( false, // late Boolean.FALSE, // do a drop null, // null, // "CREATE OR REPLACE FUNCTION nx_get_read_acls_for(users character varying[]) RETURNS SETOF text AS $$\n" // + "-- List read acl ids for a list of user/groups\n" // + "DECLARE\n" // + " r record;\n" // + " rr record;\n" // + " users_blacklist character varying[];\n" // + "BEGIN\n" // + " RAISE INFO 'nx_get_read_acls_for called';\n" // + " -- Build a black list with negative users\n" // + " SELECT regexp_split_to_array('-' || array_to_string(users, ',-'), ',')\n" // + " INTO users_blacklist;\n" // + " <<acl_loop>>\n" // + " FOR r IN SELECT read_acls.id, read_acls.acl FROM read_acls LOOP\n" // + " -- RAISE INFO 'ACL %', r.id;\n" // + " -- split the acl into aces\n" // + " FOR rr IN SELECT ace FROM regexp_split_to_table(r.acl, ',') AS ace LOOP\n" // + " -- RAISE INFO ' ACE %', rr.ace;\n" // + " IF (rr.ace = ANY(users)) THEN\n" // + " -- RAISE INFO ' GRANT %', users;\n" // + " RETURN NEXT r.id;\n" // + " CONTINUE acl_loop;\n" // + " -- ok\n" // + " ELSEIF (rr.ace = ANY(users_blacklist)) THEN\n" // + " -- RAISE INFO ' DENY';\n" // + " CONTINUE acl_loop;\n" // + " END IF;\n" // + " END LOOP;\n" // + " END LOOP acl_loop;\n" // + " RETURN;\n" // + "END $$\n" // + "LANGUAGE plpgsql STABLE;")); statements.add(new ConditionalStatement( false, // late Boolean.FALSE, // do a drop null, // null, // "CREATE OR REPLACE FUNCTION nx_log_acls_modified() RETURNS trigger AS $$\n" // + "-- Trigger to log change in the acls table\n" // + "DECLARE\n" // + " doc_id varchar(36);\n" // + "BEGIN\n" // + " IF (TG_OP = 'DELETE') THEN\n" // + " doc_id := OLD.id;\n" // + " ELSE\n" // + " doc_id := NEW.id;\n" // + " END IF;\n" // + " INSERT INTO hierarchy_modified_acl VALUES(doc_id, 'f');\n" // + " RETURN NEW;\n" // + "END $$\n" // + "LANGUAGE plpgsql;")); statements.add(new ConditionalStatement( false, // late Boolean.TRUE, // do a drop null, // "DROP TRIGGER IF EXISTS nx_trig_acls_modified ON acls;", "CREATE TRIGGER nx_trig_acls_modified\n" // + " AFTER INSERT OR UPDATE OR DELETE ON acls\n" // + " FOR EACH ROW EXECUTE PROCEDURE nx_log_acls_modified();")); statements.add(new ConditionalStatement( false, // late Boolean.FALSE, // do a drop null, // null, // "CREATE OR REPLACE FUNCTION nx_log_hierarchy_modified() RETURNS trigger AS $$\n" // + "-- Trigger to log doc_id that need read acl update\n" // + "DECLARE\n" // + " doc_id varchar(36);\n" // + "BEGIN\n" // - + " IF (TG_OP = 'INSERT' AND NEW.isproperty = 'f') THEN\n" // - + " -- New document\n" // - + " INSERT INTO hierarchy_modified_acl VALUES(NEW.id, 't');\n" // - + " ELSEIF (TG_OP = 'UPDATE' AND NEW.isproperty = 'f') THEN\n" // - + " IF (NEW.parentid != OLD.parentid) THEN\n" // + + " IF (TG_OP = 'INSERT') THEN\n" // + + " IF (NEW.isproperty = 'f') THEN\n" // + + " -- New document\n" // + + " INSERT INTO hierarchy_modified_acl VALUES(NEW.id, 't');\n" // + + " END IF;\n" // + + " ELSEIF (TG_OP = 'UPDATE') THEN\n" // + + " IF (NEW.isproperty = 'f' AND NEW.parentid != OLD.parentid) THEN\n" // + " -- New container\n" // + " INSERT INTO hierarchy_modified_acl VALUES(NEW.id, 'f');\n" // + " END IF;\n" // + " END IF;\n" // + " RETURN NEW;\n" // + "END $$\n" // + "LANGUAGE plpgsql;")); statements.add(new ConditionalStatement( false, // late Boolean.TRUE, // do a drop null, // "DROP TRIGGER IF EXISTS nx_trig_hierarchy_modified ON hierarchy;", "CREATE TRIGGER nx_trig_hierarchy_modified\n" // + " AFTER INSERT OR UPDATE OR DELETE ON hierarchy\n" // + " FOR EACH ROW EXECUTE PROCEDURE nx_log_hierarchy_modified();")); statements.add(new ConditionalStatement( false, // late Boolean.FALSE, // do a drop null, // null, // "CREATE OR REPLACE FUNCTION nx_rebuild_read_acls() RETURNS void AS $$\n" // + "-- Rebuild the read acls tables\n" // + "BEGIN\n" // + " RAISE INFO 'nx_rebuild_read_acls truncate hierarchy_read_acl';\n" // + " TRUNCATE TABLE hierarchy_read_acl;\n" // + " RAISE INFO 'nx_rebuild_read_acls update acl map';\n" // + " INSERT INTO hierarchy_read_acl\n" // + " SELECT id, md5(nx_get_read_acl(id))\n" // + " FROM (SELECT id FROM hierarchy WHERE isproperty='f') AS uids;\n" // + " RAISE INFO 'nx_rebuild_read_acls truncate read_acls';\n" // + " TRUNCATE TABLE read_acls;\n" // + " INSERT INTO read_acls\n" // + " SELECT md5(acl), acl\n" // + " FROM (SELECT DISTINCT(nx_get_read_acl(id)) AS acl\n" // + " FROM (SELECT DISTINCT(id) AS id\n" // + " FROM acls) AS uids) AS read_acls_input;\n" // + " TRUNCATE TABLE hierarchy_modified_acl;\n" // + " RAISE INFO 'nx_rebuild_read_acls done';\n" // + " RETURN;\n" // + "END $$\n" // + "LANGUAGE plpgsql VOLATILE;")); statements.add(new ConditionalStatement( false, // late Boolean.FALSE, // do a drop null, // null, // "CREATE OR REPLACE FUNCTION nx_update_read_acls() RETURNS void AS $$\n" // + "-- Rebuild only necessary read acls\n" // + "DECLARE\n" // + " update_count integer;\n" // + "BEGIN\n" // + " -- Rebuild read_acls\n" // + " RAISE INFO 'nx_update_read_acls REBUILD read_acls';\n" // + " TRUNCATE TABLE read_acls;\n" // + " INSERT INTO read_acls\n" // + " SELECT md5(acl), acl\n" // + " FROM (SELECT DISTINCT(nx_get_read_acl(id)) AS acl\n" // + " FROM (SELECT DISTINCT(id) AS id FROM acls) AS uids) AS read_acls_input;\n" // + "\n" // + " -- New hierarchy_read_acl entry\n" // + " RAISE INFO 'nx_update_read_acls ADD NEW hierarchy_read_acl entry';\n" // + " INSERT INTO hierarchy_read_acl\n" // + " SELECT id, md5(nx_get_read_acl(id))\n" // + " FROM (SELECT DISTINCT(id) AS id\n" // + " FROM hierarchy_modified_acl \n" // + " WHERE is_new AND\n" // + " EXISTS (SELECT 1 FROM hierarchy WHERE hierarchy_modified_acl.id=hierarchy.id)) AS uids;\n" // + " GET DIAGNOSTICS update_count = ROW_COUNT;\n" // + " RAISE INFO 'nx_update_read_acls % hierarchy_read_acl ADDED', update_count;\n" // + " DELETE FROM hierarchy_modified_acl WHERE is_new;\n" // + "\n" // + " -- Update hierarchy_read_acl entry\n" // + " RAISE INFO 'nx_update_read_acls UPDATE existing hierarchy_read_acl';\n" // + " -- Mark acl that need to be updated (set to NULL)\n" // + " UPDATE hierarchy_read_acl SET acl_id = NULL WHERE id IN (\n" // + " SELECT DISTINCT(id) AS id FROM hierarchy_modified_acl WHERE NOT is_new);\n" // + " GET DIAGNOSTICS update_count = ROW_COUNT;\n" // + " RAISE INFO 'nx_update_read_acls % hierarchy_read_acl MARKED', update_count;\n" // + " DELETE FROM hierarchy_modified_acl WHERE NOT is_new;\n" // + " -- Mark all childrens\n" // + " LOOP\n" // + " UPDATE hierarchy_read_acl SET acl_id = NULL WHERE id IN (\n" // + " SELECT h.id\n" // + " FROM hierarchy AS h\n" // + " JOIN hierarchy_read_acl AS r ON h.id = r.id\n" // + " WHERE r.acl_id IS NOT NULL\n" // + " AND h.parentid IN (SELECT id FROM hierarchy_read_acl WHERE acl_id IS NULL));\n" // + " GET DIAGNOSTICS update_count = ROW_COUNT;\n" // + " RAISE INFO 'nx_update_read_acls % hierarchy_read_acl MARKED for udpate', update_count;\n" // + " IF (update_count = 0) THEN\n" // + " EXIT;\n" // + " END IF;\n" // + " END LOOP;\n" // + " -- Update hierarchy_read_acl acl_ids\n" // + " UPDATE hierarchy_read_acl SET acl_id = md5(nx_get_read_acl(id)) WHERE acl_id IS NULL;\n" // + " GET DIAGNOSTICS update_count = ROW_COUNT;\n" // + " RAISE INFO 'nx_update_read_acls % hierarchy_read_acl UPDATED', update_count;\n" // + "\n" // + " RETURN;\n" // + "END $$\n" // + "LANGUAGE plpgsql VOLATILE;")); // build the read acls if empty, this takes care of the upgrade statements.add(new ConditionalStatement( false, // late null, // perform a check "SELECT 1 WHERE NOT EXISTS(SELECT 1 FROM read_acls LIMIT 1);", "SELECT * FROM nx_rebuild_read_acls();", // "SELECT 1;")); return statements; } @Override public boolean preCreateTable(Connection connection, Table table, Model model, Database database) throws SQLException { if (table.getName().equals(model.hierTableName.toLowerCase())) { hierarchyCreated = true; return true; } if (table.getName().equals(Model.DESCENDANTS_TABLE_NAME.toLowerCase())) { if (hierarchyCreated) { // database initialization return true; } // upgrade of an existing database // check hierarchy size String sql = "SELECT COUNT(*) FROM hierarchy WHERE NOT isproperty"; Statement s = connection.createStatement(); ResultSet rs = s.executeQuery(sql); rs.next(); long count = rs.getLong(1); rs.close(); s.close(); if (count > 1000) { // if the hierarchy table is too big, tell the admin to do the // init by hand pathOptimizationsEnabled = false; log.error("Table DESCENDANTS not initialized automatically because table HIERARCHY is too big. " + "Upgrade by hand by calling: SELECT NX_INIT_DESCENDANTS()"); } return true; } return true; } @Override public List<String> getPostCreateTableSqls(Table table, Model model, Database database) { if (table.getName().equals(Model.DESCENDANTS_TABLE_NAME.toLowerCase())) { List<String> sqls = new ArrayList<String>(); if (pathOptimizationsEnabled) { sqls.add("SELECT NX_INIT_DESCENDANTS()"); } else { log.info("Path optimizations disabled"); } return sqls; } return Collections.emptyList(); } @Override public void existingTableDetected(Connection connection, Table table, Model model, Database database) throws SQLException { if (table.getName().equals(Model.DESCENDANTS_TABLE_NAME.toLowerCase())) { if (!pathOptimizationsEnabled) { log.info("Path optimizations disabled"); return; } // check if we want to initialize the descendants table now, or log // a warning if the hierarchy table is too big String sql = "SELECT COUNT(*) FROM descendants"; Statement s = connection.createStatement(); ResultSet rs = s.executeQuery(sql); rs.next(); long count = rs.getLong(1); rs.close(); s.close(); if (count == 0) { pathOptimizationsEnabled = false; log.error("Table DESCENDANTS empty, must be upgraded by hand by calling: " + "SELECT NX_INIT_DESCENDANTS()"); log.info("Path optimizations disabled"); } } } @Override public boolean isClusteringSupported() { return true; } @Override public String getCleanupClusterNodesSql(Model model, Database database) { Table cln = database.getTable(model.CLUSTER_NODES_TABLE_NAME); Column clnid = cln.getColumn(model.CLUSTER_NODES_NODEID_KEY); // delete nodes for sessions don't exist anymore return String.format( "DELETE FROM %s N WHERE " + "NOT EXISTS(SELECT * FROM pg_stat_activity S WHERE N.%s = S.procpid) ", cln.getQuotedName(), clnid.getQuotedName()); } @Override public String getCreateClusterNodeSql(Model model, Database database) { Table cln = database.getTable(model.CLUSTER_NODES_TABLE_NAME); Column clnid = cln.getColumn(model.CLUSTER_NODES_NODEID_KEY); Column clncr = cln.getColumn(model.CLUSTER_NODES_CREATED_KEY); return String.format( "INSERT INTO %s (%s, %s) VALUES (pg_backend_pid(), CURRENT_TIMESTAMP)", cln.getQuotedName(), clnid.getQuotedName(), clncr.getQuotedName()); } @Override public String getRemoveClusterNodeSql(Model model, Database database) { Table cln = database.getTable(model.CLUSTER_NODES_TABLE_NAME); Column clnid = cln.getColumn(model.CLUSTER_NODES_NODEID_KEY); return String.format("DELETE FROM %s WHERE %s = pg_backend_pid()", cln.getQuotedName(), clnid.getQuotedName()); } @Override public String getClusterInsertInvalidations() { return "SELECT NX_CLUSTER_INVAL(?, ?, ?)"; } @Override public String getClusterGetInvalidations() { // TODO id type return "SELECT * FROM NX_CLUSTER_GET_INVALS() " + "AS invals(id varchar(36), fragments varchar[], kind int2)"; } @Override public Collection<ConditionalStatement> getTestConditionalStatements( Model model, Database database) { List<ConditionalStatement> statements = new LinkedList<ConditionalStatement>(); statements.add(new ConditionalStatement(true, Boolean.FALSE, null, null, // here use a TEXT instead of a VARCHAR to test compatibility "CREATE TABLE testschema2 (id varchar(36) NOT NULL, title text)")); statements.add(new ConditionalStatement(true, Boolean.FALSE, null, null, "ALTER TABLE testschema2 ADD CONSTRAINT testschema2_pk PRIMARY KEY (id)")); return statements; } @Override public boolean connectionClosedByException(Throwable t) { while (t.getCause() != null) { t = t.getCause(); } // org.postgresql.util.PSQLException. message: An I/O error occured // while sending to the backend // Caused by: java.net.SocketException. message: Broken pipe if (t instanceof SocketException) { return true; } // org.postgresql.util.PSQLException. message: FATAL: terminating // connection due to administrator command String message = t.getMessage(); if (message != null && message.contains("FATAL:")) { return true; } return false; } }
true
true
public Collection<ConditionalStatement> getConditionalStatements( Model model, Database database) { String idType; switch (model.idGenPolicy) { case APP_UUID: idType = "varchar(36)"; break; case DB_IDENTITY: idType = "integer"; break; default: throw new AssertionError(model.idGenPolicy); } Table ht = database.getTable(model.hierTableName); Table ft = database.getTable(model.FULLTEXT_TABLE_NAME); List<ConditionalStatement> statements = new LinkedList<ConditionalStatement>(); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // String.format( "CREATE OR REPLACE FUNCTION NX_IN_TREE(id %s, baseid %<s) " // + "RETURNS boolean " // + "AS $$ " // + "DECLARE" // + " curid %<s := id; " // + "BEGIN" // + " IF baseid IS NULL OR id IS NULL OR baseid = id THEN" // + " RETURN false;" // + " END IF;" // + " LOOP" // + " SELECT parentid INTO curid FROM hierarchy WHERE hierarchy.id = curid;" // + " IF curid IS NULL THEN" // + " RETURN false; " // + " ELSEIF curid = baseid THEN" // + " RETURN true;" // + " END IF;" // + " END LOOP;" // + "END " // + "$$ " // + "LANGUAGE plpgsql " // + "STABLE " // + "COST 400 " // , idType))); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // String.format( "CREATE OR REPLACE FUNCTION NX_ACCESS_ALLOWED" // + "(id %s, users varchar[], permissions varchar[]) " // + "RETURNS boolean " // + "AS $$ " // + "DECLARE" // + " curid %<s := id;" // + " newid %<s;" // + " r record;" // + " first boolean := true;" // + "BEGIN" // + " WHILE curid IS NOT NULL LOOP" // + " FOR r in SELECT acls.grant, acls.permission, acls.user FROM acls WHERE acls.id = curid ORDER BY acls.pos LOOP" + " IF r.permission = ANY(permissions) AND r.user = ANY(users) THEN" // + " RETURN r.grant;" // + " END IF;" // + " END LOOP;" // + " SELECT parentid INTO newid FROM hierarchy WHERE hierarchy.id = curid;" // + " IF first AND newid IS NULL THEN" // + " SELECT versionableid INTO newid FROM versions WHERE versions.id = curid;" // + " END IF;" // + " first := false;" // + " curid := newid;" // + " END LOOP;" // + " RETURN false; " // + "END " // + "$$ " // + "LANGUAGE plpgsql " // + "STABLE " // + "COST 500 " // , idType))); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // String.format( "CREATE OR REPLACE FUNCTION NX_TO_TSVECTOR(string VARCHAR) " // + "RETURNS TSVECTOR " // + "AS $$" // + " SELECT TO_TSVECTOR('%s', SUBSTR($1, 1, 250000)) " // + "$$ " // + "LANGUAGE sql " // + "STABLE " // , fulltextAnalyzer))); statements.add(new ConditionalStatement( // true, // early Boolean.FALSE, // no drop needed null, // null, // String.format( "CREATE OR REPLACE FUNCTION NX_CONTAINS(ft TSVECTOR, query VARCHAR) " // + "RETURNS boolean " // + "AS $$" // + " SELECT $1 @@ TO_TSQUERY('%s', $2) " // + "$$ " // + "LANGUAGE sql " // + "STABLE " // , fulltextAnalyzer))); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // String.format( "CREATE OR REPLACE FUNCTION NX_CLUSTER_INVAL" // + "(i %s, f varchar[], k int) " // + "RETURNS VOID " // + "AS $$ " // + "DECLARE" // + " nid int; " // + "BEGIN" // + " FOR nid IN SELECT nodeid FROM cluster_nodes WHERE nodeid <> pg_backend_pid() LOOP" // + " INSERT INTO cluster_invals (nodeid, id, fragments, kind) VALUES (nid, i, f, k);" // + " END LOOP; " // + "END " // + "$$ " // + "LANGUAGE plpgsql" // , idType))); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // "CREATE OR REPLACE FUNCTION NX_CLUSTER_GET_INVALS() " // + "RETURNS SETOF RECORD " // + "AS $$ " // + "DECLARE" // + " r RECORD; " // + "BEGIN" // + " FOR r IN SELECT id, fragments, kind FROM cluster_invals WHERE nodeid = pg_backend_pid() LOOP" // + " RETURN NEXT r;" // + " END LOOP;" // + " DELETE FROM cluster_invals WHERE nodeid = pg_backend_pid();" // + " RETURN; " // + "END " // + "$$ " // + "LANGUAGE plpgsql" // )); FulltextInfo fti = model.getFulltextInfo(); List<String> lines = new ArrayList<String>(fti.indexNames.size()); for (String indexName : fti.indexNames) { String suffix = model.getFulltextIndexSuffix(indexName); Column ftft = ft.getColumn(model.FULLTEXT_FULLTEXT_KEY + suffix); Column ftst = ft.getColumn(model.FULLTEXT_SIMPLETEXT_KEY + suffix); Column ftbt = ft.getColumn(model.FULLTEXT_BINARYTEXT_KEY + suffix); String line = String.format( " NEW.%s := COALESCE(NEW.%s, ''::TSVECTOR) || COALESCE(NEW.%s, ''::TSVECTOR);", ftft.getQuotedName(), ftst.getQuotedName(), ftbt.getQuotedName()); lines.add(line); } statements.add(new ConditionalStatement( // false, // late Boolean.FALSE, // no drop needed null, // null, // "CREATE OR REPLACE FUNCTION NX_UPDATE_FULLTEXT() " // + "RETURNS trigger " // + "AS $$ " // + "BEGIN" // + StringUtils.join(lines, "") // + " RETURN NEW; " // + "END " // + "$$ " // + "LANGUAGE plpgsql " // + "VOLATILE " // )); statements.add(new ConditionalStatement( false, // late Boolean.TRUE, // do a drop null, // String.format("DROP TRIGGER IF EXISTS NX_TRIG_FT_UPDATE ON %s", ft.getQuotedName()), String.format("CREATE TRIGGER NX_TRIG_FT_UPDATE " // + "BEFORE INSERT OR UPDATE ON %s " + "FOR EACH ROW EXECUTE PROCEDURE NX_UPDATE_FULLTEXT()" // , ft.getQuotedName()))); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // "CREATE OR REPLACE FUNCTION NX_DESCENDANTS_CREATE_TRIGGERS() " // + "RETURNS void " // + "AS $$ " // + " DROP TRIGGER IF EXISTS NX_TRIG_DESC_INSERT ON hierarchy;" // + " CREATE TRIGGER NX_TRIG_DESC_INSERT" // + " AFTER INSERT ON hierarchy" // + " FOR EACH ROW EXECUTE PROCEDURE NX_DESCENDANTS_INSERT();" // + " DROP TRIGGER IF EXISTS NX_TRIG_DESC_UPDATE ON hierarchy;" // + " CREATE TRIGGER NX_TRIG_DESC_UPDATE" // + " AFTER UPDATE ON hierarchy" // + " FOR EACH ROW EXECUTE PROCEDURE NX_DESCENDANTS_UPDATE(); " // + "$$ " // + "LANGUAGE sql " // + "VOLATILE " // )); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // "CREATE OR REPLACE FUNCTION NX_INIT_DESCENDANTS() " // + "RETURNS void " // + "AS $$ " // + "DECLARE" // + " curid varchar(36); " // + " curparentid varchar(36); " // + "BEGIN " // + " PERFORM NX_DESCENDANTS_CREATE_TRIGGERS(); " // + " CREATE TEMP TABLE nxtodo (id varchar(36), parentid varchar(36)) ON COMMIT DROP; " // + " CREATE INDEX nxtodo_idx ON nxtodo (id);" // + " INSERT INTO nxtodo SELECT id, NULL FROM repositories;" // + " TRUNCATE TABLE descendants;" // + " LOOP" // + " -- get next node in queue\n" // + " SELECT id, parentid INTO curid, curparentid FROM nxtodo LIMIT 1;" // + " IF NOT FOUND THEN" // + " EXIT;" // + " END IF;" // + " DELETE FROM nxtodo WHERE id = curid;" // + " -- add children to queue\n" // + " INSERT INTO nxtodo SELECT id, curid FROM hierarchy" // + " WHERE parentid = curid and NOT isproperty;" // + " IF curparentid IS NULL THEN" // + " CONTINUE;" // + " END IF;" // + " -- process the node\n" // + " INSERT INTO descendants (id, descendantid)" // + " SELECT id, curid FROM descendants WHERE descendantid = curparentid;" // + " INSERT INTO descendants (id, descendantid) VALUES (curparentid, curid);" // + " END LOOP;" // + "END " // + "$$ " // + "LANGUAGE plpgsql " // + "VOLATILE " // )); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // "CREATE OR REPLACE FUNCTION NX_DESCENDANTS_INSERT() " // + "RETURNS trigger " // + "AS $$ " // + "BEGIN " // + " IF NEW.isproperty THEN" // + " RETURN NULL; " // + " END IF;" // + " IF NEW.parentid IS NULL THEN" // + " RETURN NULL; " // + " END IF;" // + " IF NEW.id IS NULL THEN" // + " RAISE EXCEPTION 'Cannot have NULL id'; " // + " END IF;" // + " INSERT INTO descendants (id, descendantid)" // + " SELECT id, NEW.id FROM descendants WHERE descendantid = NEW.parentid;" // + " INSERT INTO descendants (id, descendantid) VALUES (NEW.parentid, NEW.id);" // + " RETURN NULL; " // + "END " // + "$$ " // + "LANGUAGE plpgsql " // + "VOLATILE " // )); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // "CREATE OR REPLACE FUNCTION NX_DESCENDANTS_UPDATE() " // + "RETURNS trigger " // + "AS $$ " // + "BEGIN " // + " IF NEW.isproperty THEN" // + " RETURN NULL; " // + " END IF;" // + " IF OLD.id IS DISTINCT FROM NEW.id THEN" // + " RAISE EXCEPTION 'Cannot change id'; " // + " END IF;" // + " IF OLD.parentid IS NOT DISTINCT FROM NEW.parentid THEN" // + " RETURN NULL; " // + " END IF;" // + " IF NEW.id IS NULL THEN" // + " RAISE EXCEPTION 'Cannot have NULL id'; " // + " END IF;" // + " IF OLD.parentid IS NOT NULL THEN" // + " IF NEW.parentid IS NOT NULL THEN" // + " IF NEW.parentid = NEW.id THEN" // + " RAISE EXCEPTION 'Cannot move a node under itself'; " // + " END IF;" // + " IF EXISTS(SELECT 1 FROM descendants WHERE id = NEW.id AND descendantid = NEW.parentid) THEN" // + " RAISE EXCEPTION 'Cannot move a node under one of its descendants'; " // + " END IF;" // + " END IF;" // + " -- the old parent and its ancestors lose some descendants\n" // + " DELETE FROM descendants" // + " WHERE id IN (SELECT id FROM descendants WHERE descendantid = NEW.id)" // + " AND descendantid IN (SELECT descendantid FROM descendants WHERE id = NEW.id" // + " UNION ALL SELECT NEW.id);" // + " END IF;" // + " IF NEW.parentid IS NOT NULL THEN" // + " -- the new parent's ancestors gain as descendants\n" // + " -- the descendants of the moved node (cross join)\n" // + " INSERT INTO descendants (id, descendantid)" // + " (SELECT A.id, B.descendantid FROM descendants A CROSS JOIN descendants B" // + " WHERE A.descendantid = NEW.parentid AND B.id = NEW.id);" // + " -- the new parent's ancestors gain as descendant the moved node\n" // + " INSERT INTO descendants (id, descendantid)" // + " SELECT id, NEW.id FROM descendants WHERE descendantid = NEW.parentid;" // + " -- the new parent gains as descendants the descendants of the moved node\n" // + " INSERT INTO descendants (id, descendantid)" // + " SELECT NEW.parentid, descendantid FROM descendants WHERE id = NEW.id;" // + " -- the new parent gains as descendant the moved node\n" // + " INSERT INTO descendants (id, descendantid)" // + " VALUES (NEW.parentid, NEW.id);" // + " END IF;" // + " RETURN NULL; " // + "END " // + "$$ " // + "LANGUAGE plpgsql " // + "VOLATILE " // )); // read acls ---------------------------------------------------------- // table to store canonical read acls statements.add(new ConditionalStatement( false, // late null, // perform a check "SELECT 1 WHERE NOT EXISTS(SELECT 1 FROM pg_tables WHERE tablename='read_acls');", "CREATE TABLE read_acls (" + " id character varying(34) PRIMARY KEY," + " acl character varying(4096));", // "SELECT 1;")); // table to maintain a read acl for each hierarchy entry statements.add(new ConditionalStatement( false, // late null, // perform a check "SELECT 1 WHERE NOT EXISTS(SELECT 1 FROM pg_tables WHERE tablename='hierarchy_read_acl');", "CREATE TABLE hierarchy_read_acl (" + " id character varying(36) PRIMARY KEY," + " acl_id character varying(34)," + " CONSTRAINT hierarchy_read_acl_id_fk FOREIGN KEY (id) REFERENCES hierarchy(id) ON DELETE CASCADE" + ");", // "SELECT 1;")); // Add index statements.add(new ConditionalStatement( false, // late null, // perform a check "SELECT 1 WHERE NOT EXISTS(SELECT 1 FROM pg_indexes WHERE indexname='hierarchy_read_acl_acl_id_idx');", "CREATE INDEX hierarchy_read_acl_acl_id_idx ON hierarchy_read_acl USING btree (acl_id);", "SELECT 1;")); // Log hierarchy with updated read acl statements.add(new ConditionalStatement( false, // late null, // perform a check "SELECT 1 WHERE NOT EXISTS(SELECT 1 FROM pg_tables WHERE tablename='hierarchy_modified_acl');", "CREATE TABLE hierarchy_modified_acl (" + " id character varying(36)," // + " is_new boolean" // + ");", // "SELECT 1;")); statements.add(new ConditionalStatement( false, // late Boolean.FALSE, // do a drop null, // null, // "CREATE OR REPLACE FUNCTION nx_get_local_read_acl(id character varying) RETURNS character varying AS $$\n" // + " -- Compute the read acl for a hierarchy id using a local acl\n" // + "DECLARE\n" // + " curid varchar(36) := id;\n" // + " read_acl varchar(4096) := NULL;\n" // + " r record;\n" // + "BEGIN\n" // + " -- RAISE INFO 'call %', curid;\n" // + " FOR r in SELECT CASE\n" // + " WHEN (acls.grant AND\n" // + " acls.permission IN ('Read', 'ReadWrite', 'Everything', 'Browse')) THEN\n" // + " acls.user\n" // + " WHEN (NOT acls.grant AND\n" // + " acls.permission IN ('Read', 'ReadWrite', 'Everything', 'Browse')) THEN\n" // + " '-'|| acls.user\n" // + " ELSE NULL END AS op\n" // + " FROM acls WHERE acls.id = curid\n" // + " ORDER BY acls.pos LOOP\n" // + " IF r.op IS NULL THEN\n" // + " CONTINUE;\n" // + " END IF;\n" // + " IF read_acl IS NULL THEN\n" // + " read_acl := r.op;\n" // + " ELSE\n" // + " read_acl := read_acl || ',' || r.op;\n" // + " END IF;\n" // + " END LOOP;\n" // + " RETURN read_acl;\n" // + "END $$\n" // + "LANGUAGE plpgsql STABLE;")); statements.add(new ConditionalStatement( false, // late Boolean.FALSE, // do a drop null, // null, // "CREATE OR REPLACE FUNCTION nx_get_read_acl(id character varying) RETURNS character varying AS $$\n" // + " -- Compute the read acl for a hierarchy id using inherited acl \n" // + "DECLARE\n" // + " curid varchar(36) := id;\n" // + " newid varchar(36);\n" // + " first boolean := true;\n" // + " read_acl varchar(4096);\n" // + " ret varchar(4096);\n" // + "BEGIN\n" // + " -- RAISE INFO 'call %', curid;\n" // + " WHILE curid IS NOT NULL LOOP\n" // + " -- RAISE INFO ' curid %', curid;\n" // + " SELECT nx_get_local_read_acl(curid) INTO read_acl;\n" // + " IF (read_acl IS NOT NULL) THEN\n" // + " IF (ret is NULL) THEN\n" // + " ret = read_acl;\n" // + " ELSE\n" // + " ret := ret || ',' || read_acl;\n" // + " END IF;\n" // + " END IF;\n" // + " SELECT parentid INTO newid FROM hierarchy WHERE hierarchy.id = curid;\n" // + " IF (first AND newid IS NULL) THEN\n" // + " SELECT versionableid INTO newid FROM versions WHERE versions.id = curid;\n" // + " END IF;\n" // + " first := false;\n" // + " curid := newid;\n" // + " END LOOP;\n" // + " IF (ret is NULL) THEN\n" // + " ret = '_empty';\n" // + " END IF;\n" // + " RETURN ret;\n" // + "END $$\n" // + "LANGUAGE plpgsql STABLE;")); statements.add(new ConditionalStatement( false, // late Boolean.FALSE, // do a drop null, // null, // "CREATE OR REPLACE FUNCTION nx_get_read_acls_for(users character varying[]) RETURNS SETOF text AS $$\n" // + "-- List read acl ids for a list of user/groups\n" // + "DECLARE\n" // + " r record;\n" // + " rr record;\n" // + " users_blacklist character varying[];\n" // + "BEGIN\n" // + " RAISE INFO 'nx_get_read_acls_for called';\n" // + " -- Build a black list with negative users\n" // + " SELECT regexp_split_to_array('-' || array_to_string(users, ',-'), ',')\n" // + " INTO users_blacklist;\n" // + " <<acl_loop>>\n" // + " FOR r IN SELECT read_acls.id, read_acls.acl FROM read_acls LOOP\n" // + " -- RAISE INFO 'ACL %', r.id;\n" // + " -- split the acl into aces\n" // + " FOR rr IN SELECT ace FROM regexp_split_to_table(r.acl, ',') AS ace LOOP\n" // + " -- RAISE INFO ' ACE %', rr.ace;\n" // + " IF (rr.ace = ANY(users)) THEN\n" // + " -- RAISE INFO ' GRANT %', users;\n" // + " RETURN NEXT r.id;\n" // + " CONTINUE acl_loop;\n" // + " -- ok\n" // + " ELSEIF (rr.ace = ANY(users_blacklist)) THEN\n" // + " -- RAISE INFO ' DENY';\n" // + " CONTINUE acl_loop;\n" // + " END IF;\n" // + " END LOOP;\n" // + " END LOOP acl_loop;\n" // + " RETURN;\n" // + "END $$\n" // + "LANGUAGE plpgsql STABLE;")); statements.add(new ConditionalStatement( false, // late Boolean.FALSE, // do a drop null, // null, // "CREATE OR REPLACE FUNCTION nx_log_acls_modified() RETURNS trigger AS $$\n" // + "-- Trigger to log change in the acls table\n" // + "DECLARE\n" // + " doc_id varchar(36);\n" // + "BEGIN\n" // + " IF (TG_OP = 'DELETE') THEN\n" // + " doc_id := OLD.id;\n" // + " ELSE\n" // + " doc_id := NEW.id;\n" // + " END IF;\n" // + " INSERT INTO hierarchy_modified_acl VALUES(doc_id, 'f');\n" // + " RETURN NEW;\n" // + "END $$\n" // + "LANGUAGE plpgsql;")); statements.add(new ConditionalStatement( false, // late Boolean.TRUE, // do a drop null, // "DROP TRIGGER IF EXISTS nx_trig_acls_modified ON acls;", "CREATE TRIGGER nx_trig_acls_modified\n" // + " AFTER INSERT OR UPDATE OR DELETE ON acls\n" // + " FOR EACH ROW EXECUTE PROCEDURE nx_log_acls_modified();")); statements.add(new ConditionalStatement( false, // late Boolean.FALSE, // do a drop null, // null, // "CREATE OR REPLACE FUNCTION nx_log_hierarchy_modified() RETURNS trigger AS $$\n" // + "-- Trigger to log doc_id that need read acl update\n" // + "DECLARE\n" // + " doc_id varchar(36);\n" // + "BEGIN\n" // + " IF (TG_OP = 'INSERT' AND NEW.isproperty = 'f') THEN\n" // + " -- New document\n" // + " INSERT INTO hierarchy_modified_acl VALUES(NEW.id, 't');\n" // + " ELSEIF (TG_OP = 'UPDATE' AND NEW.isproperty = 'f') THEN\n" // + " IF (NEW.parentid != OLD.parentid) THEN\n" // + " -- New container\n" // + " INSERT INTO hierarchy_modified_acl VALUES(NEW.id, 'f');\n" // + " END IF;\n" // + " END IF;\n" // + " RETURN NEW;\n" // + "END $$\n" // + "LANGUAGE plpgsql;")); statements.add(new ConditionalStatement( false, // late Boolean.TRUE, // do a drop null, // "DROP TRIGGER IF EXISTS nx_trig_hierarchy_modified ON hierarchy;", "CREATE TRIGGER nx_trig_hierarchy_modified\n" // + " AFTER INSERT OR UPDATE OR DELETE ON hierarchy\n" // + " FOR EACH ROW EXECUTE PROCEDURE nx_log_hierarchy_modified();")); statements.add(new ConditionalStatement( false, // late Boolean.FALSE, // do a drop null, // null, // "CREATE OR REPLACE FUNCTION nx_rebuild_read_acls() RETURNS void AS $$\n" // + "-- Rebuild the read acls tables\n" // + "BEGIN\n" // + " RAISE INFO 'nx_rebuild_read_acls truncate hierarchy_read_acl';\n" // + " TRUNCATE TABLE hierarchy_read_acl;\n" // + " RAISE INFO 'nx_rebuild_read_acls update acl map';\n" // + " INSERT INTO hierarchy_read_acl\n" // + " SELECT id, md5(nx_get_read_acl(id))\n" // + " FROM (SELECT id FROM hierarchy WHERE isproperty='f') AS uids;\n" // + " RAISE INFO 'nx_rebuild_read_acls truncate read_acls';\n" // + " TRUNCATE TABLE read_acls;\n" // + " INSERT INTO read_acls\n" // + " SELECT md5(acl), acl\n" // + " FROM (SELECT DISTINCT(nx_get_read_acl(id)) AS acl\n" // + " FROM (SELECT DISTINCT(id) AS id\n" // + " FROM acls) AS uids) AS read_acls_input;\n" // + " TRUNCATE TABLE hierarchy_modified_acl;\n" // + " RAISE INFO 'nx_rebuild_read_acls done';\n" // + " RETURN;\n" // + "END $$\n" // + "LANGUAGE plpgsql VOLATILE;")); statements.add(new ConditionalStatement( false, // late Boolean.FALSE, // do a drop null, // null, // "CREATE OR REPLACE FUNCTION nx_update_read_acls() RETURNS void AS $$\n" // + "-- Rebuild only necessary read acls\n" // + "DECLARE\n" // + " update_count integer;\n" // + "BEGIN\n" // + " -- Rebuild read_acls\n" // + " RAISE INFO 'nx_update_read_acls REBUILD read_acls';\n" // + " TRUNCATE TABLE read_acls;\n" // + " INSERT INTO read_acls\n" // + " SELECT md5(acl), acl\n" // + " FROM (SELECT DISTINCT(nx_get_read_acl(id)) AS acl\n" // + " FROM (SELECT DISTINCT(id) AS id FROM acls) AS uids) AS read_acls_input;\n" // + "\n" // + " -- New hierarchy_read_acl entry\n" // + " RAISE INFO 'nx_update_read_acls ADD NEW hierarchy_read_acl entry';\n" // + " INSERT INTO hierarchy_read_acl\n" // + " SELECT id, md5(nx_get_read_acl(id))\n" // + " FROM (SELECT DISTINCT(id) AS id\n" // + " FROM hierarchy_modified_acl \n" // + " WHERE is_new AND\n" // + " EXISTS (SELECT 1 FROM hierarchy WHERE hierarchy_modified_acl.id=hierarchy.id)) AS uids;\n" // + " GET DIAGNOSTICS update_count = ROW_COUNT;\n" // + " RAISE INFO 'nx_update_read_acls % hierarchy_read_acl ADDED', update_count;\n" // + " DELETE FROM hierarchy_modified_acl WHERE is_new;\n" // + "\n" // + " -- Update hierarchy_read_acl entry\n" // + " RAISE INFO 'nx_update_read_acls UPDATE existing hierarchy_read_acl';\n" // + " -- Mark acl that need to be updated (set to NULL)\n" // + " UPDATE hierarchy_read_acl SET acl_id = NULL WHERE id IN (\n" // + " SELECT DISTINCT(id) AS id FROM hierarchy_modified_acl WHERE NOT is_new);\n" // + " GET DIAGNOSTICS update_count = ROW_COUNT;\n" // + " RAISE INFO 'nx_update_read_acls % hierarchy_read_acl MARKED', update_count;\n" // + " DELETE FROM hierarchy_modified_acl WHERE NOT is_new;\n" // + " -- Mark all childrens\n" // + " LOOP\n" // + " UPDATE hierarchy_read_acl SET acl_id = NULL WHERE id IN (\n" // + " SELECT h.id\n" // + " FROM hierarchy AS h\n" // + " JOIN hierarchy_read_acl AS r ON h.id = r.id\n" // + " WHERE r.acl_id IS NOT NULL\n" // + " AND h.parentid IN (SELECT id FROM hierarchy_read_acl WHERE acl_id IS NULL));\n" // + " GET DIAGNOSTICS update_count = ROW_COUNT;\n" // + " RAISE INFO 'nx_update_read_acls % hierarchy_read_acl MARKED for udpate', update_count;\n" // + " IF (update_count = 0) THEN\n" // + " EXIT;\n" // + " END IF;\n" // + " END LOOP;\n" // + " -- Update hierarchy_read_acl acl_ids\n" // + " UPDATE hierarchy_read_acl SET acl_id = md5(nx_get_read_acl(id)) WHERE acl_id IS NULL;\n" // + " GET DIAGNOSTICS update_count = ROW_COUNT;\n" // + " RAISE INFO 'nx_update_read_acls % hierarchy_read_acl UPDATED', update_count;\n" // + "\n" // + " RETURN;\n" // + "END $$\n" // + "LANGUAGE plpgsql VOLATILE;")); // build the read acls if empty, this takes care of the upgrade statements.add(new ConditionalStatement( false, // late null, // perform a check "SELECT 1 WHERE NOT EXISTS(SELECT 1 FROM read_acls LIMIT 1);", "SELECT * FROM nx_rebuild_read_acls();", // "SELECT 1;")); return statements; }
public Collection<ConditionalStatement> getConditionalStatements( Model model, Database database) { String idType; switch (model.idGenPolicy) { case APP_UUID: idType = "varchar(36)"; break; case DB_IDENTITY: idType = "integer"; break; default: throw new AssertionError(model.idGenPolicy); } Table ht = database.getTable(model.hierTableName); Table ft = database.getTable(model.FULLTEXT_TABLE_NAME); List<ConditionalStatement> statements = new LinkedList<ConditionalStatement>(); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // String.format( "CREATE OR REPLACE FUNCTION NX_IN_TREE(id %s, baseid %<s) " // + "RETURNS boolean " // + "AS $$ " // + "DECLARE" // + " curid %<s := id; " // + "BEGIN" // + " IF baseid IS NULL OR id IS NULL OR baseid = id THEN" // + " RETURN false;" // + " END IF;" // + " LOOP" // + " SELECT parentid INTO curid FROM hierarchy WHERE hierarchy.id = curid;" // + " IF curid IS NULL THEN" // + " RETURN false; " // + " ELSEIF curid = baseid THEN" // + " RETURN true;" // + " END IF;" // + " END LOOP;" // + "END " // + "$$ " // + "LANGUAGE plpgsql " // + "STABLE " // + "COST 400 " // , idType))); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // String.format( "CREATE OR REPLACE FUNCTION NX_ACCESS_ALLOWED" // + "(id %s, users varchar[], permissions varchar[]) " // + "RETURNS boolean " // + "AS $$ " // + "DECLARE" // + " curid %<s := id;" // + " newid %<s;" // + " r record;" // + " first boolean := true;" // + "BEGIN" // + " WHILE curid IS NOT NULL LOOP" // + " FOR r in SELECT acls.grant, acls.permission, acls.user FROM acls WHERE acls.id = curid ORDER BY acls.pos LOOP" + " IF r.permission = ANY(permissions) AND r.user = ANY(users) THEN" // + " RETURN r.grant;" // + " END IF;" // + " END LOOP;" // + " SELECT parentid INTO newid FROM hierarchy WHERE hierarchy.id = curid;" // + " IF first AND newid IS NULL THEN" // + " SELECT versionableid INTO newid FROM versions WHERE versions.id = curid;" // + " END IF;" // + " first := false;" // + " curid := newid;" // + " END LOOP;" // + " RETURN false; " // + "END " // + "$$ " // + "LANGUAGE plpgsql " // + "STABLE " // + "COST 500 " // , idType))); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // String.format( "CREATE OR REPLACE FUNCTION NX_TO_TSVECTOR(string VARCHAR) " // + "RETURNS TSVECTOR " // + "AS $$" // + " SELECT TO_TSVECTOR('%s', SUBSTR($1, 1, 250000)) " // + "$$ " // + "LANGUAGE sql " // + "STABLE " // , fulltextAnalyzer))); statements.add(new ConditionalStatement( // true, // early Boolean.FALSE, // no drop needed null, // null, // String.format( "CREATE OR REPLACE FUNCTION NX_CONTAINS(ft TSVECTOR, query VARCHAR) " // + "RETURNS boolean " // + "AS $$" // + " SELECT $1 @@ TO_TSQUERY('%s', $2) " // + "$$ " // + "LANGUAGE sql " // + "STABLE " // , fulltextAnalyzer))); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // String.format( "CREATE OR REPLACE FUNCTION NX_CLUSTER_INVAL" // + "(i %s, f varchar[], k int) " // + "RETURNS VOID " // + "AS $$ " // + "DECLARE" // + " nid int; " // + "BEGIN" // + " FOR nid IN SELECT nodeid FROM cluster_nodes WHERE nodeid <> pg_backend_pid() LOOP" // + " INSERT INTO cluster_invals (nodeid, id, fragments, kind) VALUES (nid, i, f, k);" // + " END LOOP; " // + "END " // + "$$ " // + "LANGUAGE plpgsql" // , idType))); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // "CREATE OR REPLACE FUNCTION NX_CLUSTER_GET_INVALS() " // + "RETURNS SETOF RECORD " // + "AS $$ " // + "DECLARE" // + " r RECORD; " // + "BEGIN" // + " FOR r IN SELECT id, fragments, kind FROM cluster_invals WHERE nodeid = pg_backend_pid() LOOP" // + " RETURN NEXT r;" // + " END LOOP;" // + " DELETE FROM cluster_invals WHERE nodeid = pg_backend_pid();" // + " RETURN; " // + "END " // + "$$ " // + "LANGUAGE plpgsql" // )); FulltextInfo fti = model.getFulltextInfo(); List<String> lines = new ArrayList<String>(fti.indexNames.size()); for (String indexName : fti.indexNames) { String suffix = model.getFulltextIndexSuffix(indexName); Column ftft = ft.getColumn(model.FULLTEXT_FULLTEXT_KEY + suffix); Column ftst = ft.getColumn(model.FULLTEXT_SIMPLETEXT_KEY + suffix); Column ftbt = ft.getColumn(model.FULLTEXT_BINARYTEXT_KEY + suffix); String line = String.format( " NEW.%s := COALESCE(NEW.%s, ''::TSVECTOR) || COALESCE(NEW.%s, ''::TSVECTOR);", ftft.getQuotedName(), ftst.getQuotedName(), ftbt.getQuotedName()); lines.add(line); } statements.add(new ConditionalStatement( // false, // late Boolean.FALSE, // no drop needed null, // null, // "CREATE OR REPLACE FUNCTION NX_UPDATE_FULLTEXT() " // + "RETURNS trigger " // + "AS $$ " // + "BEGIN" // + StringUtils.join(lines, "") // + " RETURN NEW; " // + "END " // + "$$ " // + "LANGUAGE plpgsql " // + "VOLATILE " // )); statements.add(new ConditionalStatement( false, // late Boolean.TRUE, // do a drop null, // String.format("DROP TRIGGER IF EXISTS NX_TRIG_FT_UPDATE ON %s", ft.getQuotedName()), String.format("CREATE TRIGGER NX_TRIG_FT_UPDATE " // + "BEFORE INSERT OR UPDATE ON %s " + "FOR EACH ROW EXECUTE PROCEDURE NX_UPDATE_FULLTEXT()" // , ft.getQuotedName()))); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // "CREATE OR REPLACE FUNCTION NX_DESCENDANTS_CREATE_TRIGGERS() " // + "RETURNS void " // + "AS $$ " // + " DROP TRIGGER IF EXISTS NX_TRIG_DESC_INSERT ON hierarchy;" // + " CREATE TRIGGER NX_TRIG_DESC_INSERT" // + " AFTER INSERT ON hierarchy" // + " FOR EACH ROW EXECUTE PROCEDURE NX_DESCENDANTS_INSERT();" // + " DROP TRIGGER IF EXISTS NX_TRIG_DESC_UPDATE ON hierarchy;" // + " CREATE TRIGGER NX_TRIG_DESC_UPDATE" // + " AFTER UPDATE ON hierarchy" // + " FOR EACH ROW EXECUTE PROCEDURE NX_DESCENDANTS_UPDATE(); " // + "$$ " // + "LANGUAGE sql " // + "VOLATILE " // )); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // "CREATE OR REPLACE FUNCTION NX_INIT_DESCENDANTS() " // + "RETURNS void " // + "AS $$ " // + "DECLARE" // + " curid varchar(36); " // + " curparentid varchar(36); " // + "BEGIN " // + " PERFORM NX_DESCENDANTS_CREATE_TRIGGERS(); " // + " CREATE TEMP TABLE nxtodo (id varchar(36), parentid varchar(36)) ON COMMIT DROP; " // + " CREATE INDEX nxtodo_idx ON nxtodo (id);" // + " INSERT INTO nxtodo SELECT id, NULL FROM repositories;" // + " TRUNCATE TABLE descendants;" // + " LOOP" // + " -- get next node in queue\n" // + " SELECT id, parentid INTO curid, curparentid FROM nxtodo LIMIT 1;" // + " IF NOT FOUND THEN" // + " EXIT;" // + " END IF;" // + " DELETE FROM nxtodo WHERE id = curid;" // + " -- add children to queue\n" // + " INSERT INTO nxtodo SELECT id, curid FROM hierarchy" // + " WHERE parentid = curid and NOT isproperty;" // + " IF curparentid IS NULL THEN" // + " CONTINUE;" // + " END IF;" // + " -- process the node\n" // + " INSERT INTO descendants (id, descendantid)" // + " SELECT id, curid FROM descendants WHERE descendantid = curparentid;" // + " INSERT INTO descendants (id, descendantid) VALUES (curparentid, curid);" // + " END LOOP;" // + "END " // + "$$ " // + "LANGUAGE plpgsql " // + "VOLATILE " // )); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // "CREATE OR REPLACE FUNCTION NX_DESCENDANTS_INSERT() " // + "RETURNS trigger " // + "AS $$ " // + "BEGIN " // + " IF NEW.isproperty THEN" // + " RETURN NULL; " // + " END IF;" // + " IF NEW.parentid IS NULL THEN" // + " RETURN NULL; " // + " END IF;" // + " IF NEW.id IS NULL THEN" // + " RAISE EXCEPTION 'Cannot have NULL id'; " // + " END IF;" // + " INSERT INTO descendants (id, descendantid)" // + " SELECT id, NEW.id FROM descendants WHERE descendantid = NEW.parentid;" // + " INSERT INTO descendants (id, descendantid) VALUES (NEW.parentid, NEW.id);" // + " RETURN NULL; " // + "END " // + "$$ " // + "LANGUAGE plpgsql " // + "VOLATILE " // )); statements.add(new ConditionalStatement( true, // early Boolean.FALSE, // no drop needed null, // null, // "CREATE OR REPLACE FUNCTION NX_DESCENDANTS_UPDATE() " // + "RETURNS trigger " // + "AS $$ " // + "BEGIN " // + " IF NEW.isproperty THEN" // + " RETURN NULL; " // + " END IF;" // + " IF OLD.id IS DISTINCT FROM NEW.id THEN" // + " RAISE EXCEPTION 'Cannot change id'; " // + " END IF;" // + " IF OLD.parentid IS NOT DISTINCT FROM NEW.parentid THEN" // + " RETURN NULL; " // + " END IF;" // + " IF NEW.id IS NULL THEN" // + " RAISE EXCEPTION 'Cannot have NULL id'; " // + " END IF;" // + " IF OLD.parentid IS NOT NULL THEN" // + " IF NEW.parentid IS NOT NULL THEN" // + " IF NEW.parentid = NEW.id THEN" // + " RAISE EXCEPTION 'Cannot move a node under itself'; " // + " END IF;" // + " IF EXISTS(SELECT 1 FROM descendants WHERE id = NEW.id AND descendantid = NEW.parentid) THEN" // + " RAISE EXCEPTION 'Cannot move a node under one of its descendants'; " // + " END IF;" // + " END IF;" // + " -- the old parent and its ancestors lose some descendants\n" // + " DELETE FROM descendants" // + " WHERE id IN (SELECT id FROM descendants WHERE descendantid = NEW.id)" // + " AND descendantid IN (SELECT descendantid FROM descendants WHERE id = NEW.id" // + " UNION ALL SELECT NEW.id);" // + " END IF;" // + " IF NEW.parentid IS NOT NULL THEN" // + " -- the new parent's ancestors gain as descendants\n" // + " -- the descendants of the moved node (cross join)\n" // + " INSERT INTO descendants (id, descendantid)" // + " (SELECT A.id, B.descendantid FROM descendants A CROSS JOIN descendants B" // + " WHERE A.descendantid = NEW.parentid AND B.id = NEW.id);" // + " -- the new parent's ancestors gain as descendant the moved node\n" // + " INSERT INTO descendants (id, descendantid)" // + " SELECT id, NEW.id FROM descendants WHERE descendantid = NEW.parentid;" // + " -- the new parent gains as descendants the descendants of the moved node\n" // + " INSERT INTO descendants (id, descendantid)" // + " SELECT NEW.parentid, descendantid FROM descendants WHERE id = NEW.id;" // + " -- the new parent gains as descendant the moved node\n" // + " INSERT INTO descendants (id, descendantid)" // + " VALUES (NEW.parentid, NEW.id);" // + " END IF;" // + " RETURN NULL; " // + "END " // + "$$ " // + "LANGUAGE plpgsql " // + "VOLATILE " // )); // read acls ---------------------------------------------------------- // table to store canonical read acls statements.add(new ConditionalStatement( false, // late null, // perform a check "SELECT 1 WHERE NOT EXISTS(SELECT 1 FROM pg_tables WHERE tablename='read_acls');", "CREATE TABLE read_acls (" + " id character varying(34) PRIMARY KEY," + " acl character varying(4096));", // "SELECT 1;")); // table to maintain a read acl for each hierarchy entry statements.add(new ConditionalStatement( false, // late null, // perform a check "SELECT 1 WHERE NOT EXISTS(SELECT 1 FROM pg_tables WHERE tablename='hierarchy_read_acl');", "CREATE TABLE hierarchy_read_acl (" + " id character varying(36) PRIMARY KEY," + " acl_id character varying(34)," + " CONSTRAINT hierarchy_read_acl_id_fk FOREIGN KEY (id) REFERENCES hierarchy(id) ON DELETE CASCADE" + ");", // "SELECT 1;")); // Add index statements.add(new ConditionalStatement( false, // late null, // perform a check "SELECT 1 WHERE NOT EXISTS(SELECT 1 FROM pg_indexes WHERE indexname='hierarchy_read_acl_acl_id_idx');", "CREATE INDEX hierarchy_read_acl_acl_id_idx ON hierarchy_read_acl USING btree (acl_id);", "SELECT 1;")); // Log hierarchy with updated read acl statements.add(new ConditionalStatement( false, // late null, // perform a check "SELECT 1 WHERE NOT EXISTS(SELECT 1 FROM pg_tables WHERE tablename='hierarchy_modified_acl');", "CREATE TABLE hierarchy_modified_acl (" + " id character varying(36)," // + " is_new boolean" // + ");", // "SELECT 1;")); statements.add(new ConditionalStatement( false, // late Boolean.FALSE, // do a drop null, // null, // "CREATE OR REPLACE FUNCTION nx_get_local_read_acl(id character varying) RETURNS character varying AS $$\n" // + " -- Compute the read acl for a hierarchy id using a local acl\n" // + "DECLARE\n" // + " curid varchar(36) := id;\n" // + " read_acl varchar(4096) := NULL;\n" // + " r record;\n" // + "BEGIN\n" // + " -- RAISE INFO 'call %', curid;\n" // + " FOR r in SELECT CASE\n" // + " WHEN (acls.grant AND\n" // + " acls.permission IN ('Read', 'ReadWrite', 'Everything', 'Browse')) THEN\n" // + " acls.user\n" // + " WHEN (NOT acls.grant AND\n" // + " acls.permission IN ('Read', 'ReadWrite', 'Everything', 'Browse')) THEN\n" // + " '-'|| acls.user\n" // + " ELSE NULL END AS op\n" // + " FROM acls WHERE acls.id = curid\n" // + " ORDER BY acls.pos LOOP\n" // + " IF r.op IS NULL THEN\n" // + " CONTINUE;\n" // + " END IF;\n" // + " IF read_acl IS NULL THEN\n" // + " read_acl := r.op;\n" // + " ELSE\n" // + " read_acl := read_acl || ',' || r.op;\n" // + " END IF;\n" // + " END LOOP;\n" // + " RETURN read_acl;\n" // + "END $$\n" // + "LANGUAGE plpgsql STABLE;")); statements.add(new ConditionalStatement( false, // late Boolean.FALSE, // do a drop null, // null, // "CREATE OR REPLACE FUNCTION nx_get_read_acl(id character varying) RETURNS character varying AS $$\n" // + " -- Compute the read acl for a hierarchy id using inherited acl \n" // + "DECLARE\n" // + " curid varchar(36) := id;\n" // + " newid varchar(36);\n" // + " first boolean := true;\n" // + " read_acl varchar(4096);\n" // + " ret varchar(4096);\n" // + "BEGIN\n" // + " -- RAISE INFO 'call %', curid;\n" // + " WHILE curid IS NOT NULL LOOP\n" // + " -- RAISE INFO ' curid %', curid;\n" // + " SELECT nx_get_local_read_acl(curid) INTO read_acl;\n" // + " IF (read_acl IS NOT NULL) THEN\n" // + " IF (ret is NULL) THEN\n" // + " ret = read_acl;\n" // + " ELSE\n" // + " ret := ret || ',' || read_acl;\n" // + " END IF;\n" // + " END IF;\n" // + " SELECT parentid INTO newid FROM hierarchy WHERE hierarchy.id = curid;\n" // + " IF (first AND newid IS NULL) THEN\n" // + " SELECT versionableid INTO newid FROM versions WHERE versions.id = curid;\n" // + " END IF;\n" // + " first := false;\n" // + " curid := newid;\n" // + " END LOOP;\n" // + " IF (ret is NULL) THEN\n" // + " ret = '_empty';\n" // + " END IF;\n" // + " RETURN ret;\n" // + "END $$\n" // + "LANGUAGE plpgsql STABLE;")); statements.add(new ConditionalStatement( false, // late Boolean.FALSE, // do a drop null, // null, // "CREATE OR REPLACE FUNCTION nx_get_read_acls_for(users character varying[]) RETURNS SETOF text AS $$\n" // + "-- List read acl ids for a list of user/groups\n" // + "DECLARE\n" // + " r record;\n" // + " rr record;\n" // + " users_blacklist character varying[];\n" // + "BEGIN\n" // + " RAISE INFO 'nx_get_read_acls_for called';\n" // + " -- Build a black list with negative users\n" // + " SELECT regexp_split_to_array('-' || array_to_string(users, ',-'), ',')\n" // + " INTO users_blacklist;\n" // + " <<acl_loop>>\n" // + " FOR r IN SELECT read_acls.id, read_acls.acl FROM read_acls LOOP\n" // + " -- RAISE INFO 'ACL %', r.id;\n" // + " -- split the acl into aces\n" // + " FOR rr IN SELECT ace FROM regexp_split_to_table(r.acl, ',') AS ace LOOP\n" // + " -- RAISE INFO ' ACE %', rr.ace;\n" // + " IF (rr.ace = ANY(users)) THEN\n" // + " -- RAISE INFO ' GRANT %', users;\n" // + " RETURN NEXT r.id;\n" // + " CONTINUE acl_loop;\n" // + " -- ok\n" // + " ELSEIF (rr.ace = ANY(users_blacklist)) THEN\n" // + " -- RAISE INFO ' DENY';\n" // + " CONTINUE acl_loop;\n" // + " END IF;\n" // + " END LOOP;\n" // + " END LOOP acl_loop;\n" // + " RETURN;\n" // + "END $$\n" // + "LANGUAGE plpgsql STABLE;")); statements.add(new ConditionalStatement( false, // late Boolean.FALSE, // do a drop null, // null, // "CREATE OR REPLACE FUNCTION nx_log_acls_modified() RETURNS trigger AS $$\n" // + "-- Trigger to log change in the acls table\n" // + "DECLARE\n" // + " doc_id varchar(36);\n" // + "BEGIN\n" // + " IF (TG_OP = 'DELETE') THEN\n" // + " doc_id := OLD.id;\n" // + " ELSE\n" // + " doc_id := NEW.id;\n" // + " END IF;\n" // + " INSERT INTO hierarchy_modified_acl VALUES(doc_id, 'f');\n" // + " RETURN NEW;\n" // + "END $$\n" // + "LANGUAGE plpgsql;")); statements.add(new ConditionalStatement( false, // late Boolean.TRUE, // do a drop null, // "DROP TRIGGER IF EXISTS nx_trig_acls_modified ON acls;", "CREATE TRIGGER nx_trig_acls_modified\n" // + " AFTER INSERT OR UPDATE OR DELETE ON acls\n" // + " FOR EACH ROW EXECUTE PROCEDURE nx_log_acls_modified();")); statements.add(new ConditionalStatement( false, // late Boolean.FALSE, // do a drop null, // null, // "CREATE OR REPLACE FUNCTION nx_log_hierarchy_modified() RETURNS trigger AS $$\n" // + "-- Trigger to log doc_id that need read acl update\n" // + "DECLARE\n" // + " doc_id varchar(36);\n" // + "BEGIN\n" // + " IF (TG_OP = 'INSERT') THEN\n" // + " IF (NEW.isproperty = 'f') THEN\n" // + " -- New document\n" // + " INSERT INTO hierarchy_modified_acl VALUES(NEW.id, 't');\n" // + " END IF;\n" // + " ELSEIF (TG_OP = 'UPDATE') THEN\n" // + " IF (NEW.isproperty = 'f' AND NEW.parentid != OLD.parentid) THEN\n" // + " -- New container\n" // + " INSERT INTO hierarchy_modified_acl VALUES(NEW.id, 'f');\n" // + " END IF;\n" // + " END IF;\n" // + " RETURN NEW;\n" // + "END $$\n" // + "LANGUAGE plpgsql;")); statements.add(new ConditionalStatement( false, // late Boolean.TRUE, // do a drop null, // "DROP TRIGGER IF EXISTS nx_trig_hierarchy_modified ON hierarchy;", "CREATE TRIGGER nx_trig_hierarchy_modified\n" // + " AFTER INSERT OR UPDATE OR DELETE ON hierarchy\n" // + " FOR EACH ROW EXECUTE PROCEDURE nx_log_hierarchy_modified();")); statements.add(new ConditionalStatement( false, // late Boolean.FALSE, // do a drop null, // null, // "CREATE OR REPLACE FUNCTION nx_rebuild_read_acls() RETURNS void AS $$\n" // + "-- Rebuild the read acls tables\n" // + "BEGIN\n" // + " RAISE INFO 'nx_rebuild_read_acls truncate hierarchy_read_acl';\n" // + " TRUNCATE TABLE hierarchy_read_acl;\n" // + " RAISE INFO 'nx_rebuild_read_acls update acl map';\n" // + " INSERT INTO hierarchy_read_acl\n" // + " SELECT id, md5(nx_get_read_acl(id))\n" // + " FROM (SELECT id FROM hierarchy WHERE isproperty='f') AS uids;\n" // + " RAISE INFO 'nx_rebuild_read_acls truncate read_acls';\n" // + " TRUNCATE TABLE read_acls;\n" // + " INSERT INTO read_acls\n" // + " SELECT md5(acl), acl\n" // + " FROM (SELECT DISTINCT(nx_get_read_acl(id)) AS acl\n" // + " FROM (SELECT DISTINCT(id) AS id\n" // + " FROM acls) AS uids) AS read_acls_input;\n" // + " TRUNCATE TABLE hierarchy_modified_acl;\n" // + " RAISE INFO 'nx_rebuild_read_acls done';\n" // + " RETURN;\n" // + "END $$\n" // + "LANGUAGE plpgsql VOLATILE;")); statements.add(new ConditionalStatement( false, // late Boolean.FALSE, // do a drop null, // null, // "CREATE OR REPLACE FUNCTION nx_update_read_acls() RETURNS void AS $$\n" // + "-- Rebuild only necessary read acls\n" // + "DECLARE\n" // + " update_count integer;\n" // + "BEGIN\n" // + " -- Rebuild read_acls\n" // + " RAISE INFO 'nx_update_read_acls REBUILD read_acls';\n" // + " TRUNCATE TABLE read_acls;\n" // + " INSERT INTO read_acls\n" // + " SELECT md5(acl), acl\n" // + " FROM (SELECT DISTINCT(nx_get_read_acl(id)) AS acl\n" // + " FROM (SELECT DISTINCT(id) AS id FROM acls) AS uids) AS read_acls_input;\n" // + "\n" // + " -- New hierarchy_read_acl entry\n" // + " RAISE INFO 'nx_update_read_acls ADD NEW hierarchy_read_acl entry';\n" // + " INSERT INTO hierarchy_read_acl\n" // + " SELECT id, md5(nx_get_read_acl(id))\n" // + " FROM (SELECT DISTINCT(id) AS id\n" // + " FROM hierarchy_modified_acl \n" // + " WHERE is_new AND\n" // + " EXISTS (SELECT 1 FROM hierarchy WHERE hierarchy_modified_acl.id=hierarchy.id)) AS uids;\n" // + " GET DIAGNOSTICS update_count = ROW_COUNT;\n" // + " RAISE INFO 'nx_update_read_acls % hierarchy_read_acl ADDED', update_count;\n" // + " DELETE FROM hierarchy_modified_acl WHERE is_new;\n" // + "\n" // + " -- Update hierarchy_read_acl entry\n" // + " RAISE INFO 'nx_update_read_acls UPDATE existing hierarchy_read_acl';\n" // + " -- Mark acl that need to be updated (set to NULL)\n" // + " UPDATE hierarchy_read_acl SET acl_id = NULL WHERE id IN (\n" // + " SELECT DISTINCT(id) AS id FROM hierarchy_modified_acl WHERE NOT is_new);\n" // + " GET DIAGNOSTICS update_count = ROW_COUNT;\n" // + " RAISE INFO 'nx_update_read_acls % hierarchy_read_acl MARKED', update_count;\n" // + " DELETE FROM hierarchy_modified_acl WHERE NOT is_new;\n" // + " -- Mark all childrens\n" // + " LOOP\n" // + " UPDATE hierarchy_read_acl SET acl_id = NULL WHERE id IN (\n" // + " SELECT h.id\n" // + " FROM hierarchy AS h\n" // + " JOIN hierarchy_read_acl AS r ON h.id = r.id\n" // + " WHERE r.acl_id IS NOT NULL\n" // + " AND h.parentid IN (SELECT id FROM hierarchy_read_acl WHERE acl_id IS NULL));\n" // + " GET DIAGNOSTICS update_count = ROW_COUNT;\n" // + " RAISE INFO 'nx_update_read_acls % hierarchy_read_acl MARKED for udpate', update_count;\n" // + " IF (update_count = 0) THEN\n" // + " EXIT;\n" // + " END IF;\n" // + " END LOOP;\n" // + " -- Update hierarchy_read_acl acl_ids\n" // + " UPDATE hierarchy_read_acl SET acl_id = md5(nx_get_read_acl(id)) WHERE acl_id IS NULL;\n" // + " GET DIAGNOSTICS update_count = ROW_COUNT;\n" // + " RAISE INFO 'nx_update_read_acls % hierarchy_read_acl UPDATED', update_count;\n" // + "\n" // + " RETURN;\n" // + "END $$\n" // + "LANGUAGE plpgsql VOLATILE;")); // build the read acls if empty, this takes care of the upgrade statements.add(new ConditionalStatement( false, // late null, // perform a check "SELECT 1 WHERE NOT EXISTS(SELECT 1 FROM read_acls LIMIT 1);", "SELECT * FROM nx_rebuild_read_acls();", // "SELECT 1;")); return statements; }
diff --git a/src/hack/bp/assembler/Assembler.java b/src/hack/bp/assembler/Assembler.java index 6c8ffd1..75acb6a 100755 --- a/src/hack/bp/assembler/Assembler.java +++ b/src/hack/bp/assembler/Assembler.java @@ -1,135 +1,135 @@ package hack.bp.assembler; import java.io.*; /** Assembler.java ********************************************************************** * This is the implementation of the Hack assembler. * * @author bp * * @changes * 0.1 - Initial implementation (cannot handle C_COMMANDs, L_COMMANDs). Single-pass, * will translate A_COMMANDs. -bp * 0.2 - Single pass. Can handle C_COMMANDs. * ***************************************************************************************/ public class Assembler { /** main() ************************************************************************** * Fires off the assembler with run(). This function makes sure that an argument * has been passed-in before running the assembler. ***********************************************************************************/ public static void main( String[] args ) { // Check if the file is passed in if( args.length > 0 ) { if( args[ 0 ].endsWith( ".asm" ) ) run( args[ 0 ] ); else System.out.println( "Usage: <program> <fileName> " + "\n\t -Can only use file with .asm extension."); } else System.out.println( "Usage: <program> <fileName> " + "\n\t -Enter an .asm file."); } /** run() *************************************************************************** * This is the implementation of the assembler. It contains a timer accurate to * the nano-second to measure the assembler's performance. ***********************************************************************************/ public static void run( String fileName ) { // Start the timer for run() long timerStart = System.nanoTime(); // Initialize the parser and default output to write to file Parser parser = new Parser( fileName ); String output = ""; // Initialize the address size (defined in Hack machine code spec) final int ADDRESS_LENGTH = 15; // Start reading the file while( parser.hasMoreCommands() ) { // Grab the next command and store it as the current command parser.advance(); // Handle A_COMMAND if( parser.commandType() == Parser.Commands.A_COMMAND ) { // Set the current address of the instruction parser.setCurrentLineNumber( parser.getCurrentLineNumber() + 1 ); // Initialize the variable to hold the calculated binary string String tempCode = ""; // Calculate and store the binary string int decAddress = Integer.parseInt( parser.symbol() ); tempCode = Integer.toBinaryString( decAddress ); // Format the binary string to meet machine code specs if( ( tempCode.length() < ADDRESS_LENGTH ) && ( tempCode.length() > 0 ) ) { int paddingCount = ADDRESS_LENGTH - tempCode.length(); - // append the A_COMMAND prefix + // Append the A_COMMAND prefix output += "0"; // Pad the output to conform to the machine code specs for( int i = 0; i < paddingCount; i++ ) output += "0"; // Create the machine code and start new line for next code output += tempCode; output += "\n"; } } // Handle C_COMMAND if( parser.commandType() == Parser.Commands.C_COMMAND ) { // Initialize the mnemonic translator Code code = new Code(); // Set the current address of the instruction parser.setCurrentLineNumber( parser.getCurrentLineNumber() + 1 ); - // Append the opcode + // Append the C_COMMAND prefix output += "111"; // Construct the machine code output += code.comp( parser.comp() ) + code.dest( parser.dest() ) + code.jump( parser.jump() ); output += "\n"; } } // Write to file (<filename-minus-extension>.hack) try { // Create buffered writer FileWriter fileStream = new FileWriter( fileName.replace( ".asm", ".hack" ) ); BufferedWriter out = new BufferedWriter( fileStream ); // Write to file and then close the writer out.write( output, 0, output.length() ); out.close(); } catch (Exception e) { System.err.println( "Error: " + e.getMessage() ); e.printStackTrace(); System.exit( 1 ); } // Print the compilation statistics on screen (timer and success msg) long timerEnd = System.nanoTime(); System.out.println( "Assembly completed! (elapsed time: " + ( timerEnd - timerStart ) + "ns)\n"); } }
false
true
public static void run( String fileName ) { // Start the timer for run() long timerStart = System.nanoTime(); // Initialize the parser and default output to write to file Parser parser = new Parser( fileName ); String output = ""; // Initialize the address size (defined in Hack machine code spec) final int ADDRESS_LENGTH = 15; // Start reading the file while( parser.hasMoreCommands() ) { // Grab the next command and store it as the current command parser.advance(); // Handle A_COMMAND if( parser.commandType() == Parser.Commands.A_COMMAND ) { // Set the current address of the instruction parser.setCurrentLineNumber( parser.getCurrentLineNumber() + 1 ); // Initialize the variable to hold the calculated binary string String tempCode = ""; // Calculate and store the binary string int decAddress = Integer.parseInt( parser.symbol() ); tempCode = Integer.toBinaryString( decAddress ); // Format the binary string to meet machine code specs if( ( tempCode.length() < ADDRESS_LENGTH ) && ( tempCode.length() > 0 ) ) { int paddingCount = ADDRESS_LENGTH - tempCode.length(); // append the A_COMMAND prefix output += "0"; // Pad the output to conform to the machine code specs for( int i = 0; i < paddingCount; i++ ) output += "0"; // Create the machine code and start new line for next code output += tempCode; output += "\n"; } } // Handle C_COMMAND if( parser.commandType() == Parser.Commands.C_COMMAND ) { // Initialize the mnemonic translator Code code = new Code(); // Set the current address of the instruction parser.setCurrentLineNumber( parser.getCurrentLineNumber() + 1 ); // Append the opcode output += "111"; // Construct the machine code output += code.comp( parser.comp() ) + code.dest( parser.dest() ) + code.jump( parser.jump() ); output += "\n"; } } // Write to file (<filename-minus-extension>.hack) try { // Create buffered writer FileWriter fileStream = new FileWriter( fileName.replace( ".asm", ".hack" ) ); BufferedWriter out = new BufferedWriter( fileStream ); // Write to file and then close the writer out.write( output, 0, output.length() ); out.close(); } catch (Exception e) { System.err.println( "Error: " + e.getMessage() ); e.printStackTrace(); System.exit( 1 ); } // Print the compilation statistics on screen (timer and success msg) long timerEnd = System.nanoTime(); System.out.println( "Assembly completed! (elapsed time: " + ( timerEnd - timerStart ) + "ns)\n"); }
public static void run( String fileName ) { // Start the timer for run() long timerStart = System.nanoTime(); // Initialize the parser and default output to write to file Parser parser = new Parser( fileName ); String output = ""; // Initialize the address size (defined in Hack machine code spec) final int ADDRESS_LENGTH = 15; // Start reading the file while( parser.hasMoreCommands() ) { // Grab the next command and store it as the current command parser.advance(); // Handle A_COMMAND if( parser.commandType() == Parser.Commands.A_COMMAND ) { // Set the current address of the instruction parser.setCurrentLineNumber( parser.getCurrentLineNumber() + 1 ); // Initialize the variable to hold the calculated binary string String tempCode = ""; // Calculate and store the binary string int decAddress = Integer.parseInt( parser.symbol() ); tempCode = Integer.toBinaryString( decAddress ); // Format the binary string to meet machine code specs if( ( tempCode.length() < ADDRESS_LENGTH ) && ( tempCode.length() > 0 ) ) { int paddingCount = ADDRESS_LENGTH - tempCode.length(); // Append the A_COMMAND prefix output += "0"; // Pad the output to conform to the machine code specs for( int i = 0; i < paddingCount; i++ ) output += "0"; // Create the machine code and start new line for next code output += tempCode; output += "\n"; } } // Handle C_COMMAND if( parser.commandType() == Parser.Commands.C_COMMAND ) { // Initialize the mnemonic translator Code code = new Code(); // Set the current address of the instruction parser.setCurrentLineNumber( parser.getCurrentLineNumber() + 1 ); // Append the C_COMMAND prefix output += "111"; // Construct the machine code output += code.comp( parser.comp() ) + code.dest( parser.dest() ) + code.jump( parser.jump() ); output += "\n"; } } // Write to file (<filename-minus-extension>.hack) try { // Create buffered writer FileWriter fileStream = new FileWriter( fileName.replace( ".asm", ".hack" ) ); BufferedWriter out = new BufferedWriter( fileStream ); // Write to file and then close the writer out.write( output, 0, output.length() ); out.close(); } catch (Exception e) { System.err.println( "Error: " + e.getMessage() ); e.printStackTrace(); System.exit( 1 ); } // Print the compilation statistics on screen (timer and success msg) long timerEnd = System.nanoTime(); System.out.println( "Assembly completed! (elapsed time: " + ( timerEnd - timerStart ) + "ns)\n"); }
diff --git a/src/hr/tvz/programiranje/java/glavna/Glavna.java b/src/hr/tvz/programiranje/java/glavna/Glavna.java index b2eef6f..d43fe17 100644 --- a/src/hr/tvz/programiranje/java/glavna/Glavna.java +++ b/src/hr/tvz/programiranje/java/glavna/Glavna.java @@ -1,75 +1,87 @@ package hr.tvz.programiranje.java.glavna; import hr.tvz.programiranje.java.banka.DeviznaTransakcija; import hr.tvz.programiranje.java.banka.DevizniRacun; import hr.tvz.programiranje.java.banka.TekuciRacun; import hr.tvz.programiranje.java.osoba.Osoba; import java.math.BigDecimal; import java.util.Scanner; public class Glavna { /** * @param args */ //main metoda public static void main(String[] args) { //set scanner Scanner unos = new Scanner(System.in); //potrebno zatraziti unosenje podataka o vlasniku //prvog racuna (ime, prezime i OIB) i postaviti ih u objekt klase Osoba System.out.print("Unesite ime vlasnika prvog računa: "); String imePrviVlasnik = unos.next(); System.out.print("Unesite prezime vlasnika prvog računa: "); String prezimePrviVlasnik = unos.next(); System.out.print("Unesite OIB vlasnika prvog računa: "); String oibPrviVlasnik = unos.next(); + //ponoviti unos u slučaju nije 11-znamenkasti broj + while (!oibPrviVlasnik.matches("\\d{11}")) { + System.err.print("Pogrešan unos. OIB mora imati 11 znamenki.\n"); + System.err.print("Ponovo unesite OIB vlasnika prvog računa: "); + oibPrviVlasnik = unos.next(); + } System.out.print("Unesite broj prvog računa: " ); String brojRacunaPrvogVlasnika = unos.next(); //Nakon toga potrebno je zatraziti unos iznosa na prvom racunu System.out.print("Unesite stanje prvog računa (KN): "); BigDecimal iznosPrvogVlasnikaRacuna = unos.nextBigDecimal(); //postaviti ih u objekt klase Osoba Osoba vlasnikPrvogRacuna = new Osoba(imePrviVlasnik, prezimePrviVlasnik, oibPrviVlasnik); //korak 10 - prvi racun pretvoriti u objekt klase TekuciRacun TekuciRacun prviRacun = new TekuciRacun(vlasnikPrvogRacuna, iznosPrvogVlasnikaRacuna, brojRacunaPrvogVlasnika); //Na slican nacin kreirati i sve navedene podatke za //vlasnika drugog racuna i iznos za drugi racun System.out.print("\n\nUnesite ime vlasnika drugog računa: "); String imeDrugiVlasnik = unos.next(); System.out.print("Unesite prezime vlasnika drugog računa: "); String prezimeDrugiVlasnik = unos.next(); System.out.print("Unesite OIB vlasnika drugog računa: "); String oibDrugiVlasnik = unos.next(); + //ponoviti unos u slučaju nije 11-znamenkasti broj + while (!oibDrugiVlasnik.matches("\\d{11}")) { + System.err.print("Pogrešan unos. OIB mora imati 11 znamenki.\n"); + System.err.print("Ponovo unesite OIB vlasnika drugog računa: "); + oibDrugiVlasnik = unos.next(); + } System.out.print("Unesite IBAN drugog računa: "); String ibanDrugiVlasnik = unos.next(); System.out.print("Unesite valutu drugog računa: "); String valutaDrugiVlasnik = unos.next(); Osoba vlasnikDrugogRacuna = new Osoba(imeDrugiVlasnik, prezimeDrugiVlasnik, oibDrugiVlasnik); System.out.print("Unesite stanje drugog računa: "); BigDecimal iznosDrugogVlasnikaRacuna = unos.nextBigDecimal(); DevizniRacun drugiRacun = new DevizniRacun(vlasnikDrugogRacuna, iznosDrugogVlasnikaRacuna, ibanDrugiVlasnik, valutaDrugiVlasnik); System.out.print("Unesite iznos transakcije (u KN) s prvog na drugi račun: "); BigDecimal iznosTransakcije = unos.nextBigDecimal(); //korak 10 - drugi racun pretvoriti u objekt klase DevizniRacun DeviznaTransakcija transakcija = new DeviznaTransakcija(prviRacun, drugiRacun, iznosTransakcije); transakcija.provediTransakciju(); //Na kraju je jos¡ potrebno ispisati nova stanja na racunu System.out.print("\nStanje prvog računa nakon transakcije: " + prviRacun.getStanjeRacuna() + " HRK"); //korak 12 - Kod ispisa novog stanja deviznog racuna potrebno je ispisivati valutu koja je // postavljena na drugi racun. System.out.print("\nStanje drugog računa nakon transakcije: " + drugiRacun.getStanjeRacuna() + " " + valutaDrugiVlasnik); //zatvori skener unos.close(); } }
false
true
public static void main(String[] args) { //set scanner Scanner unos = new Scanner(System.in); //potrebno zatraziti unosenje podataka o vlasniku //prvog racuna (ime, prezime i OIB) i postaviti ih u objekt klase Osoba System.out.print("Unesite ime vlasnika prvog računa: "); String imePrviVlasnik = unos.next(); System.out.print("Unesite prezime vlasnika prvog računa: "); String prezimePrviVlasnik = unos.next(); System.out.print("Unesite OIB vlasnika prvog računa: "); String oibPrviVlasnik = unos.next(); System.out.print("Unesite broj prvog računa: " ); String brojRacunaPrvogVlasnika = unos.next(); //Nakon toga potrebno je zatraziti unos iznosa na prvom racunu System.out.print("Unesite stanje prvog računa (KN): "); BigDecimal iznosPrvogVlasnikaRacuna = unos.nextBigDecimal(); //postaviti ih u objekt klase Osoba Osoba vlasnikPrvogRacuna = new Osoba(imePrviVlasnik, prezimePrviVlasnik, oibPrviVlasnik); //korak 10 - prvi racun pretvoriti u objekt klase TekuciRacun TekuciRacun prviRacun = new TekuciRacun(vlasnikPrvogRacuna, iznosPrvogVlasnikaRacuna, brojRacunaPrvogVlasnika); //Na slican nacin kreirati i sve navedene podatke za //vlasnika drugog racuna i iznos za drugi racun System.out.print("\n\nUnesite ime vlasnika drugog računa: "); String imeDrugiVlasnik = unos.next(); System.out.print("Unesite prezime vlasnika drugog računa: "); String prezimeDrugiVlasnik = unos.next(); System.out.print("Unesite OIB vlasnika drugog računa: "); String oibDrugiVlasnik = unos.next(); System.out.print("Unesite IBAN drugog računa: "); String ibanDrugiVlasnik = unos.next(); System.out.print("Unesite valutu drugog računa: "); String valutaDrugiVlasnik = unos.next(); Osoba vlasnikDrugogRacuna = new Osoba(imeDrugiVlasnik, prezimeDrugiVlasnik, oibDrugiVlasnik); System.out.print("Unesite stanje drugog računa: "); BigDecimal iznosDrugogVlasnikaRacuna = unos.nextBigDecimal(); DevizniRacun drugiRacun = new DevizniRacun(vlasnikDrugogRacuna, iznosDrugogVlasnikaRacuna, ibanDrugiVlasnik, valutaDrugiVlasnik); System.out.print("Unesite iznos transakcije (u KN) s prvog na drugi račun: "); BigDecimal iznosTransakcije = unos.nextBigDecimal(); //korak 10 - drugi racun pretvoriti u objekt klase DevizniRacun DeviznaTransakcija transakcija = new DeviznaTransakcija(prviRacun, drugiRacun, iznosTransakcije); transakcija.provediTransakciju(); //Na kraju je jos¡ potrebno ispisati nova stanja na racunu System.out.print("\nStanje prvog računa nakon transakcije: " + prviRacun.getStanjeRacuna() + " HRK"); //korak 12 - Kod ispisa novog stanja deviznog racuna potrebno je ispisivati valutu koja je // postavljena na drugi racun. System.out.print("\nStanje drugog računa nakon transakcije: " + drugiRacun.getStanjeRacuna() + " " + valutaDrugiVlasnik); //zatvori skener unos.close(); }
public static void main(String[] args) { //set scanner Scanner unos = new Scanner(System.in); //potrebno zatraziti unosenje podataka o vlasniku //prvog racuna (ime, prezime i OIB) i postaviti ih u objekt klase Osoba System.out.print("Unesite ime vlasnika prvog računa: "); String imePrviVlasnik = unos.next(); System.out.print("Unesite prezime vlasnika prvog računa: "); String prezimePrviVlasnik = unos.next(); System.out.print("Unesite OIB vlasnika prvog računa: "); String oibPrviVlasnik = unos.next(); //ponoviti unos u slučaju nije 11-znamenkasti broj while (!oibPrviVlasnik.matches("\\d{11}")) { System.err.print("Pogrešan unos. OIB mora imati 11 znamenki.\n"); System.err.print("Ponovo unesite OIB vlasnika prvog računa: "); oibPrviVlasnik = unos.next(); } System.out.print("Unesite broj prvog računa: " ); String brojRacunaPrvogVlasnika = unos.next(); //Nakon toga potrebno je zatraziti unos iznosa na prvom racunu System.out.print("Unesite stanje prvog računa (KN): "); BigDecimal iznosPrvogVlasnikaRacuna = unos.nextBigDecimal(); //postaviti ih u objekt klase Osoba Osoba vlasnikPrvogRacuna = new Osoba(imePrviVlasnik, prezimePrviVlasnik, oibPrviVlasnik); //korak 10 - prvi racun pretvoriti u objekt klase TekuciRacun TekuciRacun prviRacun = new TekuciRacun(vlasnikPrvogRacuna, iznosPrvogVlasnikaRacuna, brojRacunaPrvogVlasnika); //Na slican nacin kreirati i sve navedene podatke za //vlasnika drugog racuna i iznos za drugi racun System.out.print("\n\nUnesite ime vlasnika drugog računa: "); String imeDrugiVlasnik = unos.next(); System.out.print("Unesite prezime vlasnika drugog računa: "); String prezimeDrugiVlasnik = unos.next(); System.out.print("Unesite OIB vlasnika drugog računa: "); String oibDrugiVlasnik = unos.next(); //ponoviti unos u slučaju nije 11-znamenkasti broj while (!oibDrugiVlasnik.matches("\\d{11}")) { System.err.print("Pogrešan unos. OIB mora imati 11 znamenki.\n"); System.err.print("Ponovo unesite OIB vlasnika drugog računa: "); oibDrugiVlasnik = unos.next(); } System.out.print("Unesite IBAN drugog računa: "); String ibanDrugiVlasnik = unos.next(); System.out.print("Unesite valutu drugog računa: "); String valutaDrugiVlasnik = unos.next(); Osoba vlasnikDrugogRacuna = new Osoba(imeDrugiVlasnik, prezimeDrugiVlasnik, oibDrugiVlasnik); System.out.print("Unesite stanje drugog računa: "); BigDecimal iznosDrugogVlasnikaRacuna = unos.nextBigDecimal(); DevizniRacun drugiRacun = new DevizniRacun(vlasnikDrugogRacuna, iznosDrugogVlasnikaRacuna, ibanDrugiVlasnik, valutaDrugiVlasnik); System.out.print("Unesite iznos transakcije (u KN) s prvog na drugi račun: "); BigDecimal iznosTransakcije = unos.nextBigDecimal(); //korak 10 - drugi racun pretvoriti u objekt klase DevizniRacun DeviznaTransakcija transakcija = new DeviznaTransakcija(prviRacun, drugiRacun, iznosTransakcije); transakcija.provediTransakciju(); //Na kraju je jos¡ potrebno ispisati nova stanja na racunu System.out.print("\nStanje prvog računa nakon transakcije: " + prviRacun.getStanjeRacuna() + " HRK"); //korak 12 - Kod ispisa novog stanja deviznog racuna potrebno je ispisivati valutu koja je // postavljena na drugi racun. System.out.print("\nStanje drugog računa nakon transakcije: " + drugiRacun.getStanjeRacuna() + " " + valutaDrugiVlasnik); //zatvori skener unos.close(); }
diff --git a/aa-server/src/main/java/edu/umich/eecs/tac/user/DefaultUserViewManager.java b/aa-server/src/main/java/edu/umich/eecs/tac/user/DefaultUserViewManager.java index 509a958..f2cd763 100644 --- a/aa-server/src/main/java/edu/umich/eecs/tac/user/DefaultUserViewManager.java +++ b/aa-server/src/main/java/edu/umich/eecs/tac/user/DefaultUserViewManager.java @@ -1,210 +1,210 @@ /* * DefaultUserViewManager.java * * COPYRIGHT 2008 * THE REGENTS OF THE UNIVERSITY OF MICHIGAN * ALL RIGHTS RESERVED * * PERMISSION IS GRANTED TO USE, COPY, CREATE DERIVATIVE WORKS AND REDISTRIBUTE THIS * SOFTWARE AND SUCH DERIVATIVE WORKS FOR NONCOMMERCIAL EDUCATION AND RESEARCH * PURPOSES, SO LONG AS NO FEE IS CHARGED, AND SO LONG AS THE COPYRIGHT NOTICE * ABOVE, THIS GRANT OF PERMISSION, AND THE DISCLAIMER BELOW APPEAR IN ALL COPIES * MADE; AND SO LONG AS THE NAME OF THE UNIVERSITY OF MICHIGAN IS NOT USED IN ANY * ADVERTISING OR PUBLICITY PERTAINING TO THE USE OR DISTRIBUTION OF THIS SOFTWARE * WITHOUT SPECIFIC, WRITTEN PRIOR AUTHORIZATION. * * THIS SOFTWARE IS PROVIDED AS IS, WITHOUT REPRESENTATION FROM THE UNIVERSITY OF * MICHIGAN AS TO ITS FITNESS FOR ANY PURPOSE, AND WITHOUT WARRANTY BY THE * UNIVERSITY OF MICHIGAN OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT * LIMITATION THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE. THE REGENTS OF THE UNIVERSITY OF MICHIGAN SHALL NOT BE LIABLE FOR ANY * DAMAGES, INCLUDING SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WITH * RESPECT TO ANY CLAIM ARISING OUT OF OR IN CONNECTION WITH THE USE OF THE SOFTWARE, * EVEN IF IT HAS BEEN OR IS HEREAFTER ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. */ package edu.umich.eecs.tac.user; import edu.umich.eecs.tac.props.*; import edu.umich.eecs.tac.sim.RecentConversionsTracker; import java.util.Map; import java.util.Random; import java.util.logging.Logger; import static edu.umich.eecs.tac.user.UserUtils.*; /** * @author Patrick Jordan, Ben Cassell, Lee Callender */ public class DefaultUserViewManager implements UserViewManager { private Logger log = Logger.getLogger(DefaultUserViewManager.class .getName()); private UserEventSupport eventSupport; private Map<String, AdvertiserInfo> advertiserInfo; private SlotInfo slotInfo; private RetailCatalog catalog; private Random random; private UserClickModel userClickModel; private RecentConversionsTracker recentConversionsTracker; public DefaultUserViewManager(RetailCatalog catalog, RecentConversionsTracker recentConversionsTracker, Map<String, AdvertiserInfo> advertiserInfo, SlotInfo slotInfo) { this(catalog, recentConversionsTracker, advertiserInfo, slotInfo, new Random()); } public DefaultUserViewManager(RetailCatalog catalog, RecentConversionsTracker recentConversionsTracker, Map<String, AdvertiserInfo> advertiserInfo, SlotInfo slotInfo, Random random) { if (catalog == null) { throw new NullPointerException("Retail catalog cannot be null"); } if (slotInfo == null) { throw new NullPointerException("Auction info cannot be null"); } if (recentConversionsTracker == null) { throw new NullPointerException( "Recent conversions tracker cannot be null"); } if (advertiserInfo == null) { throw new NullPointerException( "Advertiser information cannot be null"); } if (random == null) { throw new NullPointerException("Random generator cannot be null"); } this.catalog = catalog; this.random = random; this.recentConversionsTracker = recentConversionsTracker; this.advertiserInfo = advertiserInfo; this.slotInfo = slotInfo; eventSupport = new UserEventSupport(); } public void nextTimeUnit(int timeUnit) { } public boolean processImpression(User user, Query query, Auction auction) { fireQueryIssued(query); boolean converted = false; boolean clicking = true; // Grab the continuation probability from the user click model. double continuationProbability = 0.0; int queryIndex = userClickModel.queryIndex(query); if (queryIndex < 0) { log.warning(String.format("Query: %s does not have a click model.", query)); } else { continuationProbability = userClickModel .getContinuationProbability(queryIndex); } Ranking ranking = auction.getRanking(); Pricing pricing = auction.getPricing(); // Users will view all adLinks, but may only click on some. for (int i = 0; i < ranking.size(); i++) { AdLink ad = ranking.get(i); boolean isPromoted = ranking.isPromoted(i); fireAdViewed(query, ad, i + 1, isPromoted); // If the user is still considering clicks, process the attempt if (clicking) { AdvertiserInfo info = advertiserInfo.get(ad.getAdvertiser()); double promotionEffect = ranking.isPromoted(i) ? slotInfo .getPromotedSlotBonus() : 0.0; double clickProbability = calculateClickProbability(user, ad.getAd(), info.getTargetEffect(), promotionEffect, findAdvertiserEffect(query, ad, userClickModel)); if (random.nextDouble() <= clickProbability) { // Users has clicked on the ad fireAdClicked(query, ad, i + 1, pricing.getPrice(ad)); double conversionProbability = calculateConversionProbability( user, query, info, recentConversionsTracker.getRecentConversions(ad.getAdvertiser())); -// if(user.isTransacting()){ + if(user.isTransacting()){ if (random.nextDouble() <= conversionProbability) { // User has converted and will no longer click double salesProfit = catalog.getSalesProfit(user .getProduct()); fireAdConverted(query, ad, i + 1, modifySalesProfitForManufacturerSpecialty(user, info.getManufacturerSpecialty(), info.getManufacturerBonus(), salesProfit)); converted = true; clicking = false; } -// } + } } } if (random.nextDouble() > continuationProbability) { clicking = false; } } return converted; } public boolean addUserEventListener(UserEventListener listener) { return eventSupport.addUserEventListener(listener); } public boolean containsUserEventListener(UserEventListener listener) { return eventSupport.containsUserEventListener(listener); } public boolean removeUserEventListener(UserEventListener listener) { return eventSupport.removeUserEventListener(listener); } private void fireQueryIssued(Query query) { eventSupport.fireQueryIssued(query); } private void fireAdViewed(Query query, AdLink ad, int slot, boolean isPromoted) { eventSupport.fireAdViewed(query, ad, slot, isPromoted); } private void fireAdClicked(Query query, AdLink ad, int slot, double cpc) { eventSupport.fireAdClicked(query, ad, slot, cpc); } private void fireAdConverted(Query query, AdLink ad, int slot, double salesProfit) { eventSupport.fireAdConverted(query, ad, slot, salesProfit); } public UserClickModel getUserClickModel() { return userClickModel; } public void setUserClickModel(UserClickModel userClickModel) { this.userClickModel = userClickModel; } }
false
true
public boolean processImpression(User user, Query query, Auction auction) { fireQueryIssued(query); boolean converted = false; boolean clicking = true; // Grab the continuation probability from the user click model. double continuationProbability = 0.0; int queryIndex = userClickModel.queryIndex(query); if (queryIndex < 0) { log.warning(String.format("Query: %s does not have a click model.", query)); } else { continuationProbability = userClickModel .getContinuationProbability(queryIndex); } Ranking ranking = auction.getRanking(); Pricing pricing = auction.getPricing(); // Users will view all adLinks, but may only click on some. for (int i = 0; i < ranking.size(); i++) { AdLink ad = ranking.get(i); boolean isPromoted = ranking.isPromoted(i); fireAdViewed(query, ad, i + 1, isPromoted); // If the user is still considering clicks, process the attempt if (clicking) { AdvertiserInfo info = advertiserInfo.get(ad.getAdvertiser()); double promotionEffect = ranking.isPromoted(i) ? slotInfo .getPromotedSlotBonus() : 0.0; double clickProbability = calculateClickProbability(user, ad.getAd(), info.getTargetEffect(), promotionEffect, findAdvertiserEffect(query, ad, userClickModel)); if (random.nextDouble() <= clickProbability) { // Users has clicked on the ad fireAdClicked(query, ad, i + 1, pricing.getPrice(ad)); double conversionProbability = calculateConversionProbability( user, query, info, recentConversionsTracker.getRecentConversions(ad.getAdvertiser())); // if(user.isTransacting()){ if (random.nextDouble() <= conversionProbability) { // User has converted and will no longer click double salesProfit = catalog.getSalesProfit(user .getProduct()); fireAdConverted(query, ad, i + 1, modifySalesProfitForManufacturerSpecialty(user, info.getManufacturerSpecialty(), info.getManufacturerBonus(), salesProfit)); converted = true; clicking = false; } // } } } if (random.nextDouble() > continuationProbability) { clicking = false; } } return converted; }
public boolean processImpression(User user, Query query, Auction auction) { fireQueryIssued(query); boolean converted = false; boolean clicking = true; // Grab the continuation probability from the user click model. double continuationProbability = 0.0; int queryIndex = userClickModel.queryIndex(query); if (queryIndex < 0) { log.warning(String.format("Query: %s does not have a click model.", query)); } else { continuationProbability = userClickModel .getContinuationProbability(queryIndex); } Ranking ranking = auction.getRanking(); Pricing pricing = auction.getPricing(); // Users will view all adLinks, but may only click on some. for (int i = 0; i < ranking.size(); i++) { AdLink ad = ranking.get(i); boolean isPromoted = ranking.isPromoted(i); fireAdViewed(query, ad, i + 1, isPromoted); // If the user is still considering clicks, process the attempt if (clicking) { AdvertiserInfo info = advertiserInfo.get(ad.getAdvertiser()); double promotionEffect = ranking.isPromoted(i) ? slotInfo .getPromotedSlotBonus() : 0.0; double clickProbability = calculateClickProbability(user, ad.getAd(), info.getTargetEffect(), promotionEffect, findAdvertiserEffect(query, ad, userClickModel)); if (random.nextDouble() <= clickProbability) { // Users has clicked on the ad fireAdClicked(query, ad, i + 1, pricing.getPrice(ad)); double conversionProbability = calculateConversionProbability( user, query, info, recentConversionsTracker.getRecentConversions(ad.getAdvertiser())); if(user.isTransacting()){ if (random.nextDouble() <= conversionProbability) { // User has converted and will no longer click double salesProfit = catalog.getSalesProfit(user .getProduct()); fireAdConverted(query, ad, i + 1, modifySalesProfitForManufacturerSpecialty(user, info.getManufacturerSpecialty(), info.getManufacturerBonus(), salesProfit)); converted = true; clicking = false; } } } } if (random.nextDouble() > continuationProbability) { clicking = false; } } return converted; }
diff --git a/integrar-t-android/src/main/java/org/utn/proyecto/helpful/integrart/integrar_t_android/menu/ItemDetailFragment.java b/integrar-t-android/src/main/java/org/utn/proyecto/helpful/integrart/integrar_t_android/menu/ItemDetailFragment.java index e027777..9f7cd79 100644 --- a/integrar-t-android/src/main/java/org/utn/proyecto/helpful/integrart/integrar_t_android/menu/ItemDetailFragment.java +++ b/integrar-t-android/src/main/java/org/utn/proyecto/helpful/integrart/integrar_t_android/menu/ItemDetailFragment.java @@ -1,55 +1,55 @@ package org.utn.proyecto.helpful.integrart.integrar_t_android.menu; import org.utn.proyecto.helpful.integrart.integrar_t_android.R; import org.utn.proyecto.helpful.integrart.integrar_t_android.events.EventBus; import org.utn.proyecto.helpful.integrart.integrar_t_android.menu.item.*; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; public class ItemDetailFragment extends Fragment { public static final String ARG_ITEM_ID = "item_id"; MainMenuItem.MenuItem mItem; private EventBus bus; public ItemDetailFragment() {} @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments().containsKey(ARG_ITEM_ID)) { mItem = MainMenuItem.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID)); } } public void setBus(EventBus bus){ this.bus = bus; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.mam_fragment_item_detail, container, false); - rootView.setBackgroundDrawable(mItem.bckground); + rootView.setBackgroundDrawable(mItem.bckground); if (mItem != null) { // ((TextView) rootView.findViewById(R.id.tv_activity_description)).setText(mItem.getActivityDescription()); } Button button = (Button) rootView.findViewById(R.id.btn_activity_launch); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bus.dispatch(mItem.event); } }); return rootView; } }
true
true
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.mam_fragment_item_detail, container, false); rootView.setBackgroundDrawable(mItem.bckground); if (mItem != null) { // ((TextView) rootView.findViewById(R.id.tv_activity_description)).setText(mItem.getActivityDescription()); } Button button = (Button) rootView.findViewById(R.id.btn_activity_launch); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bus.dispatch(mItem.event); } }); return rootView; }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.mam_fragment_item_detail, container, false); rootView.setBackgroundDrawable(mItem.bckground); if (mItem != null) { // ((TextView) rootView.findViewById(R.id.tv_activity_description)).setText(mItem.getActivityDescription()); } Button button = (Button) rootView.findViewById(R.id.btn_activity_launch); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bus.dispatch(mItem.event); } }); return rootView; }
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AndroidLaunchController.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AndroidLaunchController.java index 38d2397f2..16dad906e 100644 --- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AndroidLaunchController.java +++ b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AndroidLaunchController.java @@ -1,1608 +1,1611 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Eclipse Public License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.eclipse.org/org/documents/epl-v10.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.ide.eclipse.adt.internal.launch; import com.android.ddmlib.AndroidDebugBridge; import com.android.ddmlib.Client; import com.android.ddmlib.ClientData; import com.android.ddmlib.IDevice; import com.android.ddmlib.Log; import com.android.ddmlib.AndroidDebugBridge.IClientChangeListener; import com.android.ddmlib.AndroidDebugBridge.IDebugBridgeChangeListener; import com.android.ddmlib.AndroidDebugBridge.IDeviceChangeListener; import com.android.ddmlib.ClientData.DebuggerStatus; import com.android.ide.eclipse.adt.AdtPlugin; import com.android.ide.eclipse.adt.internal.launch.AndroidLaunchConfiguration.TargetMode; import com.android.ide.eclipse.adt.internal.launch.DelayedLaunchInfo.InstallRetryMode; import com.android.ide.eclipse.adt.internal.launch.DeviceChooserDialog.DeviceChooserResponse; import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs; import com.android.ide.eclipse.adt.internal.project.AndroidManifestParser; import com.android.ide.eclipse.adt.internal.project.ApkInstallManager; import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper; import com.android.ide.eclipse.adt.internal.project.ProjectHelper; import com.android.ide.eclipse.adt.internal.sdk.Sdk; import com.android.ide.eclipse.adt.internal.wizards.actions.AvdManagerAction; import com.android.prefs.AndroidLocation.AndroidLocationException; import com.android.sdklib.AndroidVersion; import com.android.sdklib.IAndroidTarget; import com.android.sdklib.NullSdkLog; import com.android.sdklib.internal.avd.AvdManager; import com.android.sdklib.internal.avd.AvdManager.AvdInfo; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationType; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.debug.core.ILaunchManager; import org.eclipse.debug.core.model.IDebugTarget; import org.eclipse.debug.ui.DebugUITools; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants; import org.eclipse.jdt.launching.IVMConnector; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; /** * Controls the launch of Android application either on a device or on the * emulator. If an emulator is already running, this class will attempt to reuse * it. */ public final class AndroidLaunchController implements IDebugBridgeChangeListener, IDeviceChangeListener, IClientChangeListener, ILaunchController { private static final String FLAG_AVD = "-avd"; //$NON-NLS-1$ private static final String FLAG_NETDELAY = "-netdelay"; //$NON-NLS-1$ private static final String FLAG_NETSPEED = "-netspeed"; //$NON-NLS-1$ private static final String FLAG_WIPE_DATA = "-wipe-data"; //$NON-NLS-1$ private static final String FLAG_NO_BOOT_ANIM = "-no-boot-anim"; //$NON-NLS-1$ /** * Map to store {@link ILaunchConfiguration} objects that must be launched as simple connection * to running application. The integer is the port on which to connect. * <b>ALL ACCESS MUST BE INSIDE A <code>synchronized (sListLock)</code> block!</b> */ private static final HashMap<ILaunchConfiguration, Integer> sRunningAppMap = new HashMap<ILaunchConfiguration, Integer>(); private static final Object sListLock = sRunningAppMap; /** * List of {@link DelayedLaunchInfo} waiting for an emulator to connect. * <p>Once an emulator has connected, {@link DelayedLaunchInfo#getDevice()} is set and the * DelayedLaunchInfo object is moved to * {@link AndroidLaunchController#mWaitingForReadyEmulatorList}. * <b>ALL ACCESS MUST BE INSIDE A <code>synchronized (sListLock)</code> block!</b> */ private final ArrayList<DelayedLaunchInfo> mWaitingForEmulatorLaunches = new ArrayList<DelayedLaunchInfo>(); /** * List of application waiting to be launched on a device/emulator.<br> * <b>ALL ACCESS MUST BE INSIDE A <code>synchronized (sListLock)</code> block!</b> * */ private final ArrayList<DelayedLaunchInfo> mWaitingForReadyEmulatorList = new ArrayList<DelayedLaunchInfo>(); /** * Application waiting to show up as waiting for debugger. * <b>ALL ACCESS MUST BE INSIDE A <code>synchronized (sListLock)</code> block!</b> */ private final ArrayList<DelayedLaunchInfo> mWaitingForDebuggerApplications = new ArrayList<DelayedLaunchInfo>(); /** * List of clients that have appeared as waiting for debugger before their name was available. * <b>ALL ACCESS MUST BE INSIDE A <code>synchronized (sListLock)</code> block!</b> */ private final ArrayList<Client> mUnknownClientsWaitingForDebugger = new ArrayList<Client>(); /** static instance for singleton */ private static AndroidLaunchController sThis = new AndroidLaunchController(); /** private constructor to enforce singleton */ private AndroidLaunchController() { AndroidDebugBridge.addDebugBridgeChangeListener(this); AndroidDebugBridge.addDeviceChangeListener(this); AndroidDebugBridge.addClientChangeListener(this); } /** * Returns the singleton reference. */ public static AndroidLaunchController getInstance() { return sThis; } /** * Launches a remote java debugging session on an already running application * @param project The project of the application to debug. * @param debugPort The port to connect the debugger to. */ public static void debugRunningApp(IProject project, int debugPort) { // get an existing or new launch configuration ILaunchConfiguration config = AndroidLaunchController.getLaunchConfig(project); if (config != null) { setPortLaunchConfigAssociation(config, debugPort); // and launch DebugUITools.launch(config, ILaunchManager.DEBUG_MODE); } } /** * Returns an {@link ILaunchConfiguration} for the specified {@link IProject}. * @param project the project * @return a new or already existing <code>ILaunchConfiguration</code> or null if there was * an error when creating a new one. */ public static ILaunchConfiguration getLaunchConfig(IProject project) { // get the launch manager ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager(); // now get the config type for our particular android type. ILaunchConfigurationType configType = manager.getLaunchConfigurationType( LaunchConfigDelegate.ANDROID_LAUNCH_TYPE_ID); String name = project.getName(); // search for an existing launch configuration ILaunchConfiguration config = findConfig(manager, configType, name); // test if we found one or not if (config == null) { // Didn't find a matching config, so we make one. // It'll be made in the "working copy" object first. ILaunchConfigurationWorkingCopy wc = null; try { // make the working copy object wc = configType.newInstance(null, manager.generateUniqueLaunchConfigurationNameFrom(name)); // set the project name wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, name); // set the launch mode to default. wc.setAttribute(LaunchConfigDelegate.ATTR_LAUNCH_ACTION, LaunchConfigDelegate.DEFAULT_LAUNCH_ACTION); // set default target mode wc.setAttribute(LaunchConfigDelegate.ATTR_TARGET_MODE, LaunchConfigDelegate.DEFAULT_TARGET_MODE.getValue()); // default AVD: None wc.setAttribute(LaunchConfigDelegate.ATTR_AVD_NAME, (String) null); // set the default network speed wc.setAttribute(LaunchConfigDelegate.ATTR_SPEED, LaunchConfigDelegate.DEFAULT_SPEED); // and delay wc.setAttribute(LaunchConfigDelegate.ATTR_DELAY, LaunchConfigDelegate.DEFAULT_DELAY); // default wipe data mode wc.setAttribute(LaunchConfigDelegate.ATTR_WIPE_DATA, LaunchConfigDelegate.DEFAULT_WIPE_DATA); // default disable boot animation option wc.setAttribute(LaunchConfigDelegate.ATTR_NO_BOOT_ANIM, LaunchConfigDelegate.DEFAULT_NO_BOOT_ANIM); // set default emulator options IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore(); String emuOptions = store.getString(AdtPrefs.PREFS_EMU_OPTIONS); wc.setAttribute(LaunchConfigDelegate.ATTR_COMMANDLINE, emuOptions); // map the config and the project wc.setMappedResources(getResourcesToMap(project)); // save the working copy to get the launch config object which we return. return wc.doSave(); } catch (CoreException e) { String msg = String.format( "Failed to create a Launch config for project '%1$s': %2$s", project.getName(), e.getMessage()); AdtPlugin.printErrorToConsole(project, msg); // no launch! return null; } } return config; } /** * Returns the list of resources to map to a Launch Configuration. * @param project the project associated to the launch configuration. */ public static IResource[] getResourcesToMap(IProject project) { ArrayList<IResource> array = new ArrayList<IResource>(2); array.add(project); IFile manifest = AndroidManifestParser.getManifest(project); if (manifest != null) { array.add(manifest); } return array.toArray(new IResource[array.size()]); } /** * Launches an android app on the device or emulator * * @param project The project we're launching * @param mode the mode in which to launch, one of the mode constants * defined by <code>ILaunchManager</code> - <code>RUN_MODE</code> or * <code>DEBUG_MODE</code>. * @param apk the resource to the apk to launch. * @param packageName the Android package name of the app * @param debugPackageName the Android package name to debug * @param debuggable the debuggable value of the app, or null if not set. * @param requiredApiVersionNumber the api version required by the app, or null if none. * @param launchAction the action to perform after app sync * @param config the launch configuration * @param launch the launch object */ public void launch(final IProject project, String mode, IFile apk, String packageName, String debugPackageName, Boolean debuggable, String requiredApiVersionNumber, final IAndroidLaunchAction launchAction, final AndroidLaunchConfiguration config, final AndroidLaunch launch, IProgressMonitor monitor) { String message = String.format("Performing %1$s", launchAction.getLaunchDescription()); AdtPlugin.printToConsole(project, message); // create the launch info final DelayedLaunchInfo launchInfo = new DelayedLaunchInfo(project, packageName, debugPackageName, launchAction, apk, debuggable, requiredApiVersionNumber, launch, monitor); // set the debug mode launchInfo.setDebugMode(mode.equals(ILaunchManager.DEBUG_MODE)); // get the SDK Sdk currentSdk = Sdk.getCurrent(); AvdManager avdManager = currentSdk.getAvdManager(); // reload the AVDs to make sure we are up to date try { avdManager.reloadAvds(NullSdkLog.getLogger()); } catch (AndroidLocationException e1) { // this happens if the AVD Manager failed to find the folder in which the AVDs are // stored. This is unlikely to happen, but if it does, we should force to go manual // to allow using physical devices. config.mTargetMode = TargetMode.MANUAL; } // get the project target final IAndroidTarget projectTarget = currentSdk.getTarget(project); // FIXME: check errors on missing sdk, AVD manager, or project target. // device chooser response object. final DeviceChooserResponse response = new DeviceChooserResponse(); /* * Launch logic: * - Manually Mode * Always display a UI that lets a user see the current running emulators/devices. * The UI must show which devices are compatibles, and allow launching new emulators * with compatible (and not yet running) AVD. * - Automatic Way * * Preferred AVD set. * If Preferred AVD is not running: launch it. * Launch the application on the preferred AVD. * * No preferred AVD. * Count the number of compatible emulators/devices. * If != 1, display a UI similar to manual mode. * If == 1, launch the application on this AVD/device. */ if (config.mTargetMode == TargetMode.AUTO) { // if we are in automatic target mode, we need to find the current devices IDevice[] devices = AndroidDebugBridge.getBridge().getDevices(); // first check if we have a preferred AVD name, and if it actually exists, and is valid // (ie able to run the project). // We need to check this in case the AVD was recreated with a different target that is // not compatible. AvdInfo preferredAvd = null; if (config.mAvdName != null) { preferredAvd = avdManager.getAvd(config.mAvdName, true /*validAvdOnly*/); if (projectTarget.isCompatibleBaseFor(preferredAvd.getTarget()) == false) { preferredAvd = null; AdtPlugin.printErrorToConsole(project, String.format( "Preferred AVD '%1$s' is not compatible with the project target '%2$s'. Looking for a compatible AVD...", config.mAvdName, projectTarget.getName())); } } if (preferredAvd != null) { // look for a matching device for (IDevice d : devices) { String deviceAvd = d.getAvdName(); if (deviceAvd != null && deviceAvd.equals(config.mAvdName)) { response.setDeviceToUse(d); AdtPlugin.printToConsole(project, String.format( "Automatic Target Mode: Preferred AVD '%1$s' is available on emulator '%2$s'", config.mAvdName, d)); continueLaunch(response, project, launch, launchInfo, config); return; } } // at this point we have a valid preferred AVD that is not running. // We need to start it. response.setAvdToLaunch(preferredAvd); AdtPlugin.printToConsole(project, String.format( "Automatic Target Mode: Preferred AVD '%1$s' is not available. Launching new emulator.", config.mAvdName)); continueLaunch(response, project, launch, launchInfo, config); return; } // no (valid) preferred AVD? look for one. HashMap<IDevice, AvdInfo> compatibleRunningAvds = new HashMap<IDevice, AvdInfo>(); boolean hasDevice = false; // if there's 1+ device running, we may force manual mode, // as we cannot always detect proper compatibility with // devices. This is the case if the project target is not // a standard platform for (IDevice d : devices) { String deviceAvd = d.getAvdName(); if (deviceAvd != null) { // physical devices return null. AvdInfo info = avdManager.getAvd(deviceAvd, true /*validAvdOnly*/); if (info != null && projectTarget.isCompatibleBaseFor(info.getTarget())) { compatibleRunningAvds.put(d, info); } } else { if (projectTarget.isPlatform()) { // means this can run on any device as long // as api level is high enough AndroidVersion deviceVersion = Sdk.getDeviceVersion(d); - if (deviceVersion.canRun(projectTarget.getVersion())) { + // the deviceVersion may be null if it wasn't yet queried (device just + // plugged in or emulator just booting up. + if (deviceVersion != null && + deviceVersion.canRun(projectTarget.getVersion())) { // device is compatible with project compatibleRunningAvds.put(d, null); continue; } } else { // for non project platform, we can't be sure if a device can // run an application or not, since we don't query the device // for the list of optional libraries that it supports. } hasDevice = true; } } // depending on the number of devices, we'll simulate an automatic choice // from the device chooser or simply show up the device chooser. if (hasDevice == false && compatibleRunningAvds.size() == 0) { // if zero emulators/devices, we launch an emulator. // We need to figure out which AVD first. // we are going to take the closest AVD. ie a compatible AVD that has the API level // closest to the project target. AvdInfo defaultAvd = findMatchingAvd(avdManager, projectTarget); if (defaultAvd != null) { response.setAvdToLaunch(defaultAvd); AdtPlugin.printToConsole(project, String.format( "Automatic Target Mode: launching new emulator with compatible AVD '%1$s'", defaultAvd.getName())); continueLaunch(response, project, launch, launchInfo, config); return; } else { AdtPlugin.printToConsole(project, String.format( "Failed to find an AVD compatible with target '%1$s'.", projectTarget.getName())); final Display display = AdtPlugin.getDisplay(); final boolean[] searchAgain = new boolean[] { false }; // ask the user to create a new one. display.syncExec(new Runnable() { public void run() { Shell shell = display.getActiveShell(); if (MessageDialog.openQuestion(shell, "Android AVD Error", "No compatible targets were found. Do you wish to a add new Android Virtual Device?")) { AvdManagerAction action = new AvdManagerAction(); action.run(null /*action*/); searchAgain[0] = true; } } }); if (searchAgain[0]) { // attempt to reload the AVDs and find one compatible. defaultAvd = findMatchingAvd(avdManager, projectTarget); if (defaultAvd == null) { AdtPlugin.printErrorToConsole(project, String.format( "Still no compatible AVDs with target '%1$s': Aborting launch.", projectTarget.getName())); stopLaunch(launchInfo); } else { response.setAvdToLaunch(defaultAvd); AdtPlugin.printToConsole(project, String.format( "Launching new emulator with compatible AVD '%1$s'", defaultAvd.getName())); continueLaunch(response, project, launch, launchInfo, config); return; } } } } else if (hasDevice == false && compatibleRunningAvds.size() == 1) { Entry<IDevice, AvdInfo> e = compatibleRunningAvds.entrySet().iterator().next(); response.setDeviceToUse(e.getKey()); // get the AvdInfo, if null, the device is a physical device. AvdInfo avdInfo = e.getValue(); if (avdInfo != null) { message = String.format("Automatic Target Mode: using existing emulator '%1$s' running compatible AVD '%2$s'", response.getDeviceToUse(), e.getValue().getName()); } else { message = String.format("Automatic Target Mode: using device '%1$s'", response.getDeviceToUse()); } AdtPlugin.printToConsole(project, message); continueLaunch(response, project, launch, launchInfo, config); return; } // if more than one device, we'll bring up the DeviceChooser dialog below. if (compatibleRunningAvds.size() >= 2) { message = "Automatic Target Mode: Several compatible targets. Please select a target device."; } else if (hasDevice) { message = "Automatic Target Mode: Unable to detect device compatibility. Please select a target device."; } AdtPlugin.printToConsole(project, message); } // bring up the device chooser. AdtPlugin.getDisplay().asyncExec(new Runnable() { public void run() { try { // open the chooser dialog. It'll fill 'response' with the device to use // or the AVD to launch. DeviceChooserDialog dialog = new DeviceChooserDialog( AdtPlugin.getDisplay().getActiveShell(), response, launchInfo.getPackageName(), projectTarget); if (dialog.open() == Dialog.OK) { AndroidLaunchController.this.continueLaunch(response, project, launch, launchInfo, config); } else { AdtPlugin.printErrorToConsole(project, "Launch canceled!"); stopLaunch(launchInfo); return; } } catch (Exception e) { // there seems to be some case where the shell will be null. (might be // an OS X bug). Because of this the creation of the dialog will throw // and IllegalArg exception interrupting the launch with no user feedback. // So we trap all the exception and display something. String msg = e.getMessage(); if (msg == null) { msg = e.getClass().getCanonicalName(); } AdtPlugin.printErrorToConsole(project, String.format("Error during launch: %s", msg)); stopLaunch(launchInfo); } } }); } /** * Find a matching AVD. */ private AvdInfo findMatchingAvd(AvdManager avdManager, final IAndroidTarget projectTarget) { AvdInfo[] avds = avdManager.getValidAvds(); AvdInfo defaultAvd = null; for (AvdInfo avd : avds) { if (projectTarget.isCompatibleBaseFor(avd.getTarget())) { // at this point we can ignore the code name issue since // IAndroidTarget.isCompatibleBaseFor() will already have filtered the non // compatible AVDs. if (defaultAvd == null || avd.getTarget().getVersion().getApiLevel() < defaultAvd.getTarget().getVersion().getApiLevel()) { defaultAvd = avd; } } } return defaultAvd; } /** * Continues the launch based on the DeviceChooser response. * @param response the device chooser response * @param project The project being launched * @param launch The eclipse launch info * @param launchInfo The {@link DelayedLaunchInfo} * @param config The config needed to start a new emulator. */ void continueLaunch(final DeviceChooserResponse response, final IProject project, final AndroidLaunch launch, final DelayedLaunchInfo launchInfo, final AndroidLaunchConfiguration config) { // Since this is called from the UI thread we spawn a new thread // to finish the launch. new Thread() { @Override public void run() { if (response.getAvdToLaunch() != null) { // there was no selected device, we start a new emulator. synchronized (sListLock) { AvdInfo info = response.getAvdToLaunch(); mWaitingForEmulatorLaunches.add(launchInfo); AdtPlugin.printToConsole(project, String.format( "Launching a new emulator with Virtual Device '%1$s'", info.getName())); boolean status = launchEmulator(config, info); if (status == false) { // launching the emulator failed! AdtPlugin.displayError("Emulator Launch", "Couldn't launch the emulator! Make sure the SDK directory is properly setup and the emulator is not missing."); // stop the launch and return mWaitingForEmulatorLaunches.remove(launchInfo); AdtPlugin.printErrorToConsole(project, "Launch canceled!"); stopLaunch(launchInfo); return; } return; } } else if (response.getDeviceToUse() != null) { launchInfo.setDevice(response.getDeviceToUse()); simpleLaunch(launchInfo, launchInfo.getDevice()); } } }.start(); } /** * Queries for a debugger port for a specific {@link ILaunchConfiguration}. * <p/> * If the configuration and a debugger port where added through * {@link #setPortLaunchConfigAssociation(ILaunchConfiguration, int)}, then this method * will return the debugger port, and remove the configuration from the list. * @param launchConfig the {@link ILaunchConfiguration} * @return the debugger port or {@link LaunchConfigDelegate#INVALID_DEBUG_PORT} if the * configuration was not setup. */ static int getPortForConfig(ILaunchConfiguration launchConfig) { synchronized (sListLock) { Integer port = sRunningAppMap.get(launchConfig); if (port != null) { sRunningAppMap.remove(launchConfig); return port; } } return LaunchConfigDelegate.INVALID_DEBUG_PORT; } /** * Set a {@link ILaunchConfiguration} and its associated debug port, in the list of * launch config to connect directly to a running app instead of doing full launch (sync, * launch, and connect to). * @param launchConfig the {@link ILaunchConfiguration} object. * @param port The debugger port to connect to. */ private static void setPortLaunchConfigAssociation(ILaunchConfiguration launchConfig, int port) { synchronized (sListLock) { sRunningAppMap.put(launchConfig, port); } } /** * Checks the build information, and returns whether the launch should continue. * <p/>The value tested are: * <ul> * <li>Minimum API version requested by the application. If the target device does not match, * the launch is canceled.</li> * <li>Debuggable attribute of the application and whether or not the device requires it. If * the device requires it and it is not set in the manifest, the launch will be forced to * "release" mode instead of "debug"</li> * <ul> */ private boolean checkBuildInfo(DelayedLaunchInfo launchInfo, IDevice device) { if (device != null) { // check the app required API level versus the target device API level String deviceVersion = device.getProperty(IDevice.PROP_BUILD_VERSION); String deviceApiLevelString = device.getProperty(IDevice.PROP_BUILD_API_LEVEL); String deviceCodeName = device.getProperty(IDevice.PROP_BUILD_CODENAME); int deviceApiLevel = -1; try { deviceApiLevel = Integer.parseInt(deviceApiLevelString); } catch (NumberFormatException e) { // pass, we'll keep the apiLevel value at -1. } String requiredApiString = launchInfo.getRequiredApiVersionNumber(); if (requiredApiString != null) { int requiredApi = -1; try { requiredApi = Integer.parseInt(requiredApiString); } catch (NumberFormatException e) { // pass, we'll keep requiredApi value at -1. } if (requiredApi == -1) { // this means the manifest uses a codename for minSdkVersion // check that the device is using the same codename if (requiredApiString.equals(deviceCodeName) == false) { AdtPlugin.printErrorToConsole(launchInfo.getProject(), String.format( "ERROR: Application requires a device running '%1$s'!", requiredApiString)); return false; } } else { // app requires a specific API level if (deviceApiLevel == -1) { AdtPlugin.printToConsole(launchInfo.getProject(), "WARNING: Unknown device API version!"); } else if (deviceApiLevel < requiredApi) { String msg = String.format( "ERROR: Application requires API version %1$d. Device API version is %2$d (Android %3$s).", requiredApi, deviceApiLevel, deviceVersion); AdtPlugin.printErrorToConsole(launchInfo.getProject(), msg); // abort the launch return false; } } } else { // warn the application API level requirement is not set. AdtPlugin.printErrorToConsole(launchInfo.getProject(), "WARNING: Application does not specify an API level requirement!"); // and display the target device API level (if known) if (deviceApiLevel == -1) { AdtPlugin.printErrorToConsole(launchInfo.getProject(), "WARNING: Unknown device API version!"); } else { AdtPlugin.printErrorToConsole(launchInfo.getProject(), String.format( "Device API version is %1$d (Android %2$s)", deviceApiLevel, deviceVersion)); } } // now checks that the device/app can be debugged (if needed) if (device.isEmulator() == false && launchInfo.isDebugMode()) { String debuggableDevice = device.getProperty(IDevice.PROP_DEBUGGABLE); if (debuggableDevice != null && debuggableDevice.equals("0")) { //$NON-NLS-1$ // the device is "secure" and requires apps to declare themselves as debuggable! if (launchInfo.getDebuggable() == null) { String message1 = String.format( "Device '%1$s' requires that applications explicitely declare themselves as debuggable in their manifest.", device.getSerialNumber()); String message2 = String.format("Application '%1$s' does not have the attribute 'debuggable' set to TRUE in its manifest and cannot be debugged.", launchInfo.getPackageName()); AdtPlugin.printErrorToConsole(launchInfo.getProject(), message1, message2); // because am -D does not check for ro.debuggable and the // 'debuggable' attribute, it is important we do not use the -D option // in this case or the app will wait for a debugger forever and never // really launch. launchInfo.setDebugMode(false); } else if (launchInfo.getDebuggable() == Boolean.FALSE) { String message = String.format("Application '%1$s' has its 'debuggable' attribute set to FALSE and cannot be debugged.", launchInfo.getPackageName()); AdtPlugin.printErrorToConsole(launchInfo.getProject(), message); // because am -D does not check for ro.debuggable and the // 'debuggable' attribute, it is important we do not use the -D option // in this case or the app will wait for a debugger forever and never // really launch. launchInfo.setDebugMode(false); } } } } return true; } /** * Do a simple launch on the specified device, attempting to sync the new * package, and then launching the application. Failed sync/launch will * stop the current AndroidLaunch and return false; * @param launchInfo * @param device * @return true if succeed */ private boolean simpleLaunch(DelayedLaunchInfo launchInfo, IDevice device) { // API level check if (checkBuildInfo(launchInfo, device) == false) { AdtPlugin.printErrorToConsole(launchInfo.getProject(), "Launch canceled!"); stopLaunch(launchInfo); return false; } // sync the app if (syncApp(launchInfo, device) == false) { AdtPlugin.printErrorToConsole(launchInfo.getProject(), "Launch canceled!"); stopLaunch(launchInfo); return false; } // launch the app launchApp(launchInfo, device); return true; } /** * If needed, syncs the application and all its dependencies on the device/emulator. * * @param launchInfo The Launch information object. * @param device the device on which to sync the application * @return true if the install succeeded. */ private boolean syncApp(DelayedLaunchInfo launchInfo, IDevice device) { boolean alreadyInstalled = ApkInstallManager.getInstance().isApplicationInstalled( launchInfo.getProject(), launchInfo.getPackageName(), device); if (alreadyInstalled) { AdtPlugin.printToConsole(launchInfo.getProject(), "Application already deployed. No need to reinstall."); } else { if (doSyncApp(launchInfo, device) == false) { return false; } } // The app is now installed, now try the dependent projects for (DelayedLaunchInfo dependentLaunchInfo : getDependenciesLaunchInfo(launchInfo)) { String msg = String.format("Project dependency found, installing: %s", dependentLaunchInfo.getProject().getName()); AdtPlugin.printToConsole(launchInfo.getProject(), msg); if (syncApp(dependentLaunchInfo, device) == false) { return false; } } return true; } /** * Syncs the application on the device/emulator. * * @param launchInfo The Launch information object. * @param device the device on which to sync the application * @return true if the install succeeded. */ private boolean doSyncApp(DelayedLaunchInfo launchInfo, IDevice device) { IPath path = launchInfo.getPackageFile().getLocation(); String fileName = path.lastSegment(); try { String message = String.format("Uploading %1$s onto device '%2$s'", fileName, device.getSerialNumber()); AdtPlugin.printToConsole(launchInfo.getProject(), message); String remotePackagePath = device.syncPackageToDevice(path.toOSString()); boolean installResult = installPackage(launchInfo, remotePackagePath, device); device.removeRemotePackage(remotePackagePath); // if the installation succeeded, we register it. if (installResult) { ApkInstallManager.getInstance().registerInstallation( launchInfo.getProject(), launchInfo.getPackageName(), device); } return installResult; } catch (IOException e) { String msg = String.format("Failed to upload %1$s on device '%2$s'", fileName, device.getSerialNumber()); AdtPlugin.printErrorToConsole(launchInfo.getProject(), msg, e); } return false; } /** * For the current launchInfo, create additional DelayedLaunchInfo that should be used to * sync APKs that we are dependent on to the device. * * @param launchInfo the original launch info that we want to find the * @return a list of DelayedLaunchInfo (may be empty if no dependencies were found or error) */ public List<DelayedLaunchInfo> getDependenciesLaunchInfo(DelayedLaunchInfo launchInfo) { List<DelayedLaunchInfo> dependencies = new ArrayList<DelayedLaunchInfo>(); // Convert to equivalent JavaProject IJavaProject javaProject; try { //assuming this is an Android (and Java) project since it is attached to the launchInfo. javaProject = BaseProjectHelper.getJavaProject(launchInfo.getProject()); } catch (CoreException e) { // return empty dependencies AdtPlugin.printErrorToConsole(launchInfo.getProject(), e); return dependencies; } // Get all projects that this depends on List<IJavaProject> androidProjectList; try { androidProjectList = ProjectHelper.getAndroidProjectDependencies(javaProject); } catch (JavaModelException e) { // return empty dependencies AdtPlugin.printErrorToConsole(launchInfo.getProject(), e); return dependencies; } // for each project, parse manifest and create launch information for (IJavaProject androidProject : androidProjectList) { // Parse the Manifest to get various required information // copied from LaunchConfigDelegate AndroidManifestParser manifestParser; try { manifestParser = AndroidManifestParser.parse( androidProject, null /* errorListener */, true /* gatherData */, false /* markErrors */); } catch (CoreException e) { AdtPlugin.printErrorToConsole( launchInfo.getProject(), String.format("Error parsing manifest of %s", androidProject.getElementName())); continue; } // Get the APK location (can return null) IFile apk = ProjectHelper.getApplicationPackage(androidProject.getProject()); if (apk == null) { // getApplicationPackage will have logged an error message continue; } // Create new launchInfo as an hybrid between parent and dependency information DelayedLaunchInfo delayedLaunchInfo = new DelayedLaunchInfo( androidProject.getProject(), manifestParser.getPackage(), manifestParser.getPackage(), launchInfo.getLaunchAction(), apk, manifestParser.getDebuggable(), manifestParser.getApiLevelRequirement(), launchInfo.getLaunch(), launchInfo.getMonitor()); // Add to the list dependencies.add(delayedLaunchInfo); } return dependencies; } /** * Installs the application package on the device, and handles return result * @param launchInfo The launch information * @param remotePath The remote path of the package. * @param device The device on which the launch is done. */ private boolean installPackage(DelayedLaunchInfo launchInfo, final String remotePath, final IDevice device) { String message = String.format("Installing %1$s...", launchInfo.getPackageFile().getName()); AdtPlugin.printToConsole(launchInfo.getProject(), message); try { // try a reinstall first, because the most common case is the app is already installed String result = doInstall(launchInfo, remotePath, device, true /* reinstall */); /* For now we force to retry the install (after uninstalling) because there's no * other way around it: adb install does not want to update a package w/o uninstalling * the old one first! */ return checkInstallResult(result, device, launchInfo, remotePath, InstallRetryMode.ALWAYS); } catch (IOException e) { String msg = String.format( "Failed to install %1$s on device '%2$s!", launchInfo.getPackageFile().getName(), device.getSerialNumber()); AdtPlugin.printErrorToConsole(launchInfo.getProject(), msg, e.getMessage()); } return false; } /** * Checks the result of an installation, and takes optional actions based on it. * @param result the result string from the installation * @param device the device on which the installation occured. * @param launchInfo the {@link DelayedLaunchInfo} * @param remotePath the temporary path of the package on the device * @param retryMode indicates what to do in case, a package already exists. * @return <code>true<code> if success, <code>false</code> otherwise. * @throws IOException */ private boolean checkInstallResult(String result, IDevice device, DelayedLaunchInfo launchInfo, String remotePath, InstallRetryMode retryMode) throws IOException { if (result == null) { AdtPlugin.printToConsole(launchInfo.getProject(), "Success!"); return true; } else if (result.equals("INSTALL_FAILED_ALREADY_EXISTS")) { //$NON-NLS-1$ // this should never happen, since reinstall mode is used on the first attempt if (retryMode == InstallRetryMode.PROMPT) { boolean prompt = AdtPlugin.displayPrompt("Application Install", "A previous installation needs to be uninstalled before the new package can be installed.\nDo you want to uninstall?"); if (prompt) { retryMode = InstallRetryMode.ALWAYS; } else { AdtPlugin.printErrorToConsole(launchInfo.getProject(), "Installation error! The package already exists."); return false; } } if (retryMode == InstallRetryMode.ALWAYS) { /* * TODO: create a UI that gives the dev the choice to: * - clean uninstall on launch * - full uninstall if application exists. * - soft uninstall if application exists (keeps the app data around). * - always ask (choice of soft-reinstall, full reinstall) AdtPlugin.printErrorToConsole(launchInfo.mProject, "Application already exists, uninstalling..."); String res = doUninstall(device, launchInfo); if (res == null) { AdtPlugin.printToConsole(launchInfo.mProject, "Success!"); } else { AdtPlugin.printErrorToConsole(launchInfo.mProject, String.format("Failed to uninstall: %1$s", res)); return false; } */ AdtPlugin.printToConsole(launchInfo.getProject(), "Application already exists. Attempting to re-install instead..."); String res = doInstall(launchInfo, remotePath, device, true /* reinstall */ ); return checkInstallResult(res, device, launchInfo, remotePath, InstallRetryMode.NEVER); } AdtPlugin.printErrorToConsole(launchInfo.getProject(), "Installation error! The package already exists."); } else if (result.equals("INSTALL_FAILED_INVALID_APK")) { //$NON-NLS-1$ AdtPlugin.printErrorToConsole(launchInfo.getProject(), "Installation failed due to invalid APK file!", "Please check logcat output for more details."); } else if (result.equals("INSTALL_FAILED_INVALID_URI")) { //$NON-NLS-1$ AdtPlugin.printErrorToConsole(launchInfo.getProject(), "Installation failed due to invalid URI!", "Please check logcat output for more details."); } else if (result.equals("INSTALL_FAILED_COULDNT_COPY")) { //$NON-NLS-1$ AdtPlugin.printErrorToConsole(launchInfo.getProject(), String.format("Installation failed: Could not copy %1$s to its final location!", launchInfo.getPackageFile().getName()), "Please check logcat output for more details."); } else if (result.equals("INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES")) { AdtPlugin.printErrorToConsole(launchInfo.getProject(), "Re-installation failed due to different application signatures.", "You must perform a full uninstall of the application. WARNING: This will remove the application data!", String.format("Please execute 'adb uninstall %1$s' in a shell.", launchInfo.getPackageName())); } else { AdtPlugin.printErrorToConsole(launchInfo.getProject(), String.format("Installation error: %1$s", result), "Please check logcat output for more details."); } return false; } /** * Performs the uninstallation of an application. * @param device the device on which to install the application. * @param launchInfo the {@link DelayedLaunchInfo}. * @return a {@link String} with an error code, or <code>null</code> if success. * @throws IOException */ @SuppressWarnings("unused") private String doUninstall(IDevice device, DelayedLaunchInfo launchInfo) throws IOException { try { return device.uninstallPackage(launchInfo.getPackageName()); } catch (IOException e) { String msg = String.format( "Failed to uninstall %1$s: %2$s", launchInfo.getPackageName(), e.getMessage()); AdtPlugin.printErrorToConsole(launchInfo.getProject(), msg); throw e; } } /** * Performs the installation of an application whose package has been uploaded on the device. * * @param launchInfo the {@link DelayedLaunchInfo}. * @param remotePath the path of the application package in the device tmp folder. * @param device the device on which to install the application. * @param reinstall * @return a {@link String} with an error code, or <code>null</code> if success. * @throws IOException */ private String doInstall(DelayedLaunchInfo launchInfo, final String remotePath, final IDevice device, boolean reinstall) throws IOException { return device.installRemotePackage(remotePath, reinstall); } /** * launches an application on a device or emulator * * @param info the {@link DelayedLaunchInfo} that indicates the launch action * @param device the device or emulator to launch the application on */ public void launchApp(final DelayedLaunchInfo info, IDevice device) { if (info.isDebugMode()) { synchronized (sListLock) { if (mWaitingForDebuggerApplications.contains(info) == false) { mWaitingForDebuggerApplications.add(info); } } } if (info.getLaunchAction().doLaunchAction(info, device)) { // if the app is not a debug app, we need to do some clean up, as // the process is done! if (info.isDebugMode() == false) { // stop the launch object, since there's no debug, and it can't // provide any control over the app stopLaunch(info); } } else { // something went wrong or no further launch action needed // lets stop the Launch stopLaunch(info); } } private boolean launchEmulator(AndroidLaunchConfiguration config, AvdInfo avdToLaunch) { // split the custom command line in segments ArrayList<String> customArgs = new ArrayList<String>(); boolean hasWipeData = false; if (config.mEmulatorCommandLine != null && config.mEmulatorCommandLine.length() > 0) { String[] segments = config.mEmulatorCommandLine.split("\\s+"); //$NON-NLS-1$ // we need to remove the empty strings for (String s : segments) { if (s.length() > 0) { customArgs.add(s); if (!hasWipeData && s.equals(FLAG_WIPE_DATA)) { hasWipeData = true; } } } } boolean needsWipeData = config.mWipeData && !hasWipeData; if (needsWipeData) { if (!AdtPlugin.displayPrompt("Android Launch", "Are you sure you want to wipe all user data when starting this emulator?")) { needsWipeData = false; } } // build the command line based on the available parameters. ArrayList<String> list = new ArrayList<String>(); list.add(AdtPlugin.getOsAbsoluteEmulator()); list.add(FLAG_AVD); list.add(avdToLaunch.getName()); if (config.mNetworkSpeed != null) { list.add(FLAG_NETSPEED); list.add(config.mNetworkSpeed); } if (config.mNetworkDelay != null) { list.add(FLAG_NETDELAY); list.add(config.mNetworkDelay); } if (needsWipeData) { list.add(FLAG_WIPE_DATA); } if (config.mNoBootAnim) { list.add(FLAG_NO_BOOT_ANIM); } list.addAll(customArgs); // convert the list into an array for the call to exec. String[] command = list.toArray(new String[list.size()]); // launch the emulator try { Process process = Runtime.getRuntime().exec(command); grabEmulatorOutput(process); } catch (IOException e) { return false; } return true; } /** * Looks for and returns an existing {@link ILaunchConfiguration} object for a * specified project. * @param manager The {@link ILaunchManager}. * @param type The {@link ILaunchConfigurationType}. * @param projectName The name of the project * @return an existing <code>ILaunchConfiguration</code> object matching the project, or * <code>null</code>. */ private static ILaunchConfiguration findConfig(ILaunchManager manager, ILaunchConfigurationType type, String projectName) { try { ILaunchConfiguration[] configs = manager.getLaunchConfigurations(type); for (ILaunchConfiguration config : configs) { if (config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, "").equals(projectName)) { //$NON-NLS-1$ return config; } } } catch (CoreException e) { MessageDialog.openError(AdtPlugin.getDisplay().getActiveShell(), "Launch Error", e.getStatus().getMessage()); } // didn't find anything that matches. Return null return null; } /** * Connects a remote debugger on the specified port. * @param debugPort The port to connect the debugger to * @param launch The associated AndroidLaunch object. * @param monitor A Progress monitor * @return false if cancelled by the monitor * @throws CoreException */ public static boolean connectRemoteDebugger(int debugPort, AndroidLaunch launch, IProgressMonitor monitor) throws CoreException { // get some default parameters. int connectTimeout = JavaRuntime.getPreferences().getInt(JavaRuntime.PREF_CONNECT_TIMEOUT); HashMap<String, String> newMap = new HashMap<String, String>(); newMap.put("hostname", "localhost"); //$NON-NLS-1$ //$NON-NLS-2$ newMap.put("port", Integer.toString(debugPort)); //$NON-NLS-1$ newMap.put("timeout", Integer.toString(connectTimeout)); // get the default VM connector IVMConnector connector = JavaRuntime.getDefaultVMConnector(); // connect to remote VM connector.connect(newMap, monitor, launch); // check for cancellation if (monitor.isCanceled()) { IDebugTarget[] debugTargets = launch.getDebugTargets(); for (IDebugTarget target : debugTargets) { if (target.canDisconnect()) { target.disconnect(); } } return false; } return true; } /** * Launch a new thread that connects a remote debugger on the specified port. * @param debugPort The port to connect the debugger to * @param androidLaunch The associated AndroidLaunch object. * @param monitor A Progress monitor * @see #connectRemoteDebugger(int, AndroidLaunch, IProgressMonitor) */ public static void launchRemoteDebugger(final int debugPort, final AndroidLaunch androidLaunch, final IProgressMonitor monitor) { new Thread("Debugger connection") { //$NON-NLS-1$ @Override public void run() { try { connectRemoteDebugger(debugPort, androidLaunch, monitor); } catch (CoreException e) { androidLaunch.stopLaunch(); } monitor.done(); } }.start(); } /** * Sent when a new {@link AndroidDebugBridge} is started. * <p/> * This is sent from a non UI thread. * @param bridge the new {@link AndroidDebugBridge} object. * * @see IDebugBridgeChangeListener#bridgeChanged(AndroidDebugBridge) */ public void bridgeChanged(AndroidDebugBridge bridge) { // The adb server has changed. We cancel any pending launches. String message = "adb server change: cancelling '%1$s'!"; synchronized (sListLock) { for (DelayedLaunchInfo launchInfo : mWaitingForReadyEmulatorList) { AdtPlugin.printErrorToConsole(launchInfo.getProject(), String.format(message, launchInfo.getLaunchAction().getLaunchDescription())); stopLaunch(launchInfo); } for (DelayedLaunchInfo launchInfo : mWaitingForDebuggerApplications) { AdtPlugin.printErrorToConsole(launchInfo.getProject(), String.format(message, launchInfo.getLaunchAction().getLaunchDescription())); stopLaunch(launchInfo); } mWaitingForReadyEmulatorList.clear(); mWaitingForDebuggerApplications.clear(); } } /** * Sent when the a device is connected to the {@link AndroidDebugBridge}. * <p/> * This is sent from a non UI thread. * @param device the new device. * * @see IDeviceChangeListener#deviceConnected(IDevice) */ public void deviceConnected(IDevice device) { synchronized (sListLock) { // look if there's an app waiting for a device if (mWaitingForEmulatorLaunches.size() > 0) { // get/remove first launch item from the list // FIXME: what if we have multiple launches waiting? DelayedLaunchInfo launchInfo = mWaitingForEmulatorLaunches.get(0); mWaitingForEmulatorLaunches.remove(0); // give the launch item its device for later use. launchInfo.setDevice(device); // and move it to the other list mWaitingForReadyEmulatorList.add(launchInfo); // and tell the user about it AdtPlugin.printToConsole(launchInfo.getProject(), String.format("New emulator found: %1$s", device.getSerialNumber())); AdtPlugin.printToConsole(launchInfo.getProject(), String.format("Waiting for HOME ('%1$s') to be launched...", AdtPlugin.getDefault().getPreferenceStore().getString( AdtPrefs.PREFS_HOME_PACKAGE))); } } } /** * Sent when the a device is connected to the {@link AndroidDebugBridge}. * <p/> * This is sent from a non UI thread. * @param device the new device. * * @see IDeviceChangeListener#deviceDisconnected(IDevice) */ @SuppressWarnings("unchecked") public void deviceDisconnected(IDevice device) { // any pending launch on this device must be canceled. String message = "%1$s disconnected! Cancelling '%2$s'!"; synchronized (sListLock) { ArrayList<DelayedLaunchInfo> copyList = (ArrayList<DelayedLaunchInfo>) mWaitingForReadyEmulatorList.clone(); for (DelayedLaunchInfo launchInfo : copyList) { if (launchInfo.getDevice() == device) { AdtPlugin.printErrorToConsole(launchInfo.getProject(), String.format(message, device.getSerialNumber(), launchInfo.getLaunchAction().getLaunchDescription())); stopLaunch(launchInfo); } } copyList = (ArrayList<DelayedLaunchInfo>) mWaitingForDebuggerApplications.clone(); for (DelayedLaunchInfo launchInfo : copyList) { if (launchInfo.getDevice() == device) { AdtPlugin.printErrorToConsole(launchInfo.getProject(), String.format(message, device.getSerialNumber(), launchInfo.getLaunchAction().getLaunchDescription())); stopLaunch(launchInfo); } } } } /** * Sent when a device data changed, or when clients are started/terminated on the device. * <p/> * This is sent from a non UI thread. * @param device the device that was updated. * @param changeMask the mask indicating what changed. * * @see IDeviceChangeListener#deviceChanged(IDevice, int) */ public void deviceChanged(IDevice device, int changeMask) { // We could check if any starting device we care about is now ready, but we can wait for // its home app to show up, so... } /** * Sent when an existing client information changed. * <p/> * This is sent from a non UI thread. * @param client the updated client. * @param changeMask the bit mask describing the changed properties. It can contain * any of the following values: {@link Client#CHANGE_INFO}, {@link Client#CHANGE_NAME} * {@link Client#CHANGE_DEBUGGER_STATUS}, {@link Client#CHANGE_THREAD_MODE}, * {@link Client#CHANGE_THREAD_DATA}, {@link Client#CHANGE_HEAP_MODE}, * {@link Client#CHANGE_HEAP_DATA}, {@link Client#CHANGE_NATIVE_HEAP_DATA} * * @see IClientChangeListener#clientChanged(Client, int) */ public void clientChanged(final Client client, int changeMask) { boolean connectDebugger = false; if ((changeMask & Client.CHANGE_NAME) == Client.CHANGE_NAME) { String applicationName = client.getClientData().getClientDescription(); if (applicationName != null) { IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore(); String home = store.getString(AdtPrefs.PREFS_HOME_PACKAGE); if (home.equals(applicationName)) { // looks like home is up, get its device IDevice device = client.getDevice(); // look for application waiting for home synchronized (sListLock) { for (int i = 0; i < mWaitingForReadyEmulatorList.size(); ) { DelayedLaunchInfo launchInfo = mWaitingForReadyEmulatorList.get(i); if (launchInfo.getDevice() == device) { // it's match, remove from the list mWaitingForReadyEmulatorList.remove(i); // We couldn't check earlier the API level of the device // (it's asynchronous when the device boot, and usually // deviceConnected is called before it's queried for its build info) // so we check now if (checkBuildInfo(launchInfo, device) == false) { // device is not the proper API! AdtPlugin.printErrorToConsole(launchInfo.getProject(), "Launch canceled!"); stopLaunch(launchInfo); return; } AdtPlugin.printToConsole(launchInfo.getProject(), String.format("HOME is up on device '%1$s'", device.getSerialNumber())); // attempt to sync the new package onto the device. if (syncApp(launchInfo, device)) { // application package is sync'ed, lets attempt to launch it. launchApp(launchInfo, device); } else { // failure! Cancel and return AdtPlugin.printErrorToConsole(launchInfo.getProject(), "Launch canceled!"); stopLaunch(launchInfo); } break; } else { i++; } } } } // check if it's already waiting for a debugger, and if so we connect to it. if (client.getClientData().getDebuggerConnectionStatus() == DebuggerStatus.WAITING) { // search for this client in the list; synchronized (sListLock) { int index = mUnknownClientsWaitingForDebugger.indexOf(client); if (index != -1) { connectDebugger = true; mUnknownClientsWaitingForDebugger.remove(client); } } } } } // if it's not home, it could be an app that is now in debugger mode that we're waiting for // lets check it if ((changeMask & Client.CHANGE_DEBUGGER_STATUS) == Client.CHANGE_DEBUGGER_STATUS) { ClientData clientData = client.getClientData(); String applicationName = client.getClientData().getClientDescription(); if (clientData.getDebuggerConnectionStatus() == DebuggerStatus.WAITING) { // Get the application name, and make sure its valid. if (applicationName == null) { // looks like we don't have the client yet, so we keep it around for when its // name becomes available. synchronized (sListLock) { mUnknownClientsWaitingForDebugger.add(client); } return; } else { connectDebugger = true; } } } if (connectDebugger) { Log.d("adt", "Debugging " + client); // now check it against the apps waiting for a debugger String applicationName = client.getClientData().getClientDescription(); Log.d("adt", "App Name: " + applicationName); synchronized (sListLock) { for (int i = 0; i < mWaitingForDebuggerApplications.size(); ) { final DelayedLaunchInfo launchInfo = mWaitingForDebuggerApplications.get(i); if (client.getDevice() == launchInfo.getDevice() && applicationName.equals(launchInfo.getDebugPackageName())) { // this is a match. We remove the launch info from the list mWaitingForDebuggerApplications.remove(i); // and connect the debugger. String msg = String.format( "Attempting to connect debugger to '%1$s' on port %2$d", launchInfo.getDebugPackageName(), client.getDebuggerListenPort()); AdtPlugin.printToConsole(launchInfo.getProject(), msg); new Thread("Debugger Connection") { //$NON-NLS-1$ @Override public void run() { try { if (connectRemoteDebugger( client.getDebuggerListenPort(), launchInfo.getLaunch(), launchInfo.getMonitor()) == false) { return; } } catch (CoreException e) { // well something went wrong. AdtPlugin.printErrorToConsole(launchInfo.getProject(), String.format("Launch error: %s", e.getMessage())); // stop the launch stopLaunch(launchInfo); } launchInfo.getMonitor().done(); } }.start(); // we're done processing this client. return; } else { i++; } } } // if we get here, we haven't found an app that we were launching, so we look // for opened android projects that contains the app asking for a debugger. // If we find one, we automatically connect to it. IProject project = ProjectHelper.findAndroidProjectByAppName(applicationName); if (project != null) { debugRunningApp(project, client.getDebuggerListenPort()); } } } /** * Get the stderr/stdout outputs of a process and return when the process is done. * Both <b>must</b> be read or the process will block on windows. * @param process The process to get the output from */ private void grabEmulatorOutput(final Process process) { // read the lines as they come. if null is returned, it's // because the process finished new Thread("") { //$NON-NLS-1$ @Override public void run() { // create a buffer to read the stderr output InputStreamReader is = new InputStreamReader(process.getErrorStream()); BufferedReader errReader = new BufferedReader(is); try { while (true) { String line = errReader.readLine(); if (line != null) { AdtPlugin.printErrorToConsole("Emulator", line); } else { break; } } } catch (IOException e) { // do nothing. } } }.start(); new Thread("") { //$NON-NLS-1$ @Override public void run() { InputStreamReader is = new InputStreamReader(process.getInputStream()); BufferedReader outReader = new BufferedReader(is); try { while (true) { String line = outReader.readLine(); if (line != null) { AdtPlugin.printToConsole("Emulator", line); } else { break; } } } catch (IOException e) { // do nothing. } } }.start(); } /* (non-Javadoc) * @see com.android.ide.eclipse.adt.launch.ILaunchController#stopLaunch(com.android.ide.eclipse.adt.launch.AndroidLaunchController.DelayedLaunchInfo) */ public void stopLaunch(DelayedLaunchInfo launchInfo) { launchInfo.getLaunch().stopLaunch(); synchronized (sListLock) { mWaitingForReadyEmulatorList.remove(launchInfo); mWaitingForDebuggerApplications.remove(launchInfo); } } }
true
true
public void launch(final IProject project, String mode, IFile apk, String packageName, String debugPackageName, Boolean debuggable, String requiredApiVersionNumber, final IAndroidLaunchAction launchAction, final AndroidLaunchConfiguration config, final AndroidLaunch launch, IProgressMonitor monitor) { String message = String.format("Performing %1$s", launchAction.getLaunchDescription()); AdtPlugin.printToConsole(project, message); // create the launch info final DelayedLaunchInfo launchInfo = new DelayedLaunchInfo(project, packageName, debugPackageName, launchAction, apk, debuggable, requiredApiVersionNumber, launch, monitor); // set the debug mode launchInfo.setDebugMode(mode.equals(ILaunchManager.DEBUG_MODE)); // get the SDK Sdk currentSdk = Sdk.getCurrent(); AvdManager avdManager = currentSdk.getAvdManager(); // reload the AVDs to make sure we are up to date try { avdManager.reloadAvds(NullSdkLog.getLogger()); } catch (AndroidLocationException e1) { // this happens if the AVD Manager failed to find the folder in which the AVDs are // stored. This is unlikely to happen, but if it does, we should force to go manual // to allow using physical devices. config.mTargetMode = TargetMode.MANUAL; } // get the project target final IAndroidTarget projectTarget = currentSdk.getTarget(project); // FIXME: check errors on missing sdk, AVD manager, or project target. // device chooser response object. final DeviceChooserResponse response = new DeviceChooserResponse(); /* * Launch logic: * - Manually Mode * Always display a UI that lets a user see the current running emulators/devices. * The UI must show which devices are compatibles, and allow launching new emulators * with compatible (and not yet running) AVD. * - Automatic Way * * Preferred AVD set. * If Preferred AVD is not running: launch it. * Launch the application on the preferred AVD. * * No preferred AVD. * Count the number of compatible emulators/devices. * If != 1, display a UI similar to manual mode. * If == 1, launch the application on this AVD/device. */ if (config.mTargetMode == TargetMode.AUTO) { // if we are in automatic target mode, we need to find the current devices IDevice[] devices = AndroidDebugBridge.getBridge().getDevices(); // first check if we have a preferred AVD name, and if it actually exists, and is valid // (ie able to run the project). // We need to check this in case the AVD was recreated with a different target that is // not compatible. AvdInfo preferredAvd = null; if (config.mAvdName != null) { preferredAvd = avdManager.getAvd(config.mAvdName, true /*validAvdOnly*/); if (projectTarget.isCompatibleBaseFor(preferredAvd.getTarget()) == false) { preferredAvd = null; AdtPlugin.printErrorToConsole(project, String.format( "Preferred AVD '%1$s' is not compatible with the project target '%2$s'. Looking for a compatible AVD...", config.mAvdName, projectTarget.getName())); } } if (preferredAvd != null) { // look for a matching device for (IDevice d : devices) { String deviceAvd = d.getAvdName(); if (deviceAvd != null && deviceAvd.equals(config.mAvdName)) { response.setDeviceToUse(d); AdtPlugin.printToConsole(project, String.format( "Automatic Target Mode: Preferred AVD '%1$s' is available on emulator '%2$s'", config.mAvdName, d)); continueLaunch(response, project, launch, launchInfo, config); return; } } // at this point we have a valid preferred AVD that is not running. // We need to start it. response.setAvdToLaunch(preferredAvd); AdtPlugin.printToConsole(project, String.format( "Automatic Target Mode: Preferred AVD '%1$s' is not available. Launching new emulator.", config.mAvdName)); continueLaunch(response, project, launch, launchInfo, config); return; } // no (valid) preferred AVD? look for one. HashMap<IDevice, AvdInfo> compatibleRunningAvds = new HashMap<IDevice, AvdInfo>(); boolean hasDevice = false; // if there's 1+ device running, we may force manual mode, // as we cannot always detect proper compatibility with // devices. This is the case if the project target is not // a standard platform for (IDevice d : devices) { String deviceAvd = d.getAvdName(); if (deviceAvd != null) { // physical devices return null. AvdInfo info = avdManager.getAvd(deviceAvd, true /*validAvdOnly*/); if (info != null && projectTarget.isCompatibleBaseFor(info.getTarget())) { compatibleRunningAvds.put(d, info); } } else { if (projectTarget.isPlatform()) { // means this can run on any device as long // as api level is high enough AndroidVersion deviceVersion = Sdk.getDeviceVersion(d); if (deviceVersion.canRun(projectTarget.getVersion())) { // device is compatible with project compatibleRunningAvds.put(d, null); continue; } } else { // for non project platform, we can't be sure if a device can // run an application or not, since we don't query the device // for the list of optional libraries that it supports. } hasDevice = true; } } // depending on the number of devices, we'll simulate an automatic choice // from the device chooser or simply show up the device chooser. if (hasDevice == false && compatibleRunningAvds.size() == 0) { // if zero emulators/devices, we launch an emulator. // We need to figure out which AVD first. // we are going to take the closest AVD. ie a compatible AVD that has the API level // closest to the project target. AvdInfo defaultAvd = findMatchingAvd(avdManager, projectTarget); if (defaultAvd != null) { response.setAvdToLaunch(defaultAvd); AdtPlugin.printToConsole(project, String.format( "Automatic Target Mode: launching new emulator with compatible AVD '%1$s'", defaultAvd.getName())); continueLaunch(response, project, launch, launchInfo, config); return; } else { AdtPlugin.printToConsole(project, String.format( "Failed to find an AVD compatible with target '%1$s'.", projectTarget.getName())); final Display display = AdtPlugin.getDisplay(); final boolean[] searchAgain = new boolean[] { false }; // ask the user to create a new one. display.syncExec(new Runnable() { public void run() { Shell shell = display.getActiveShell(); if (MessageDialog.openQuestion(shell, "Android AVD Error", "No compatible targets were found. Do you wish to a add new Android Virtual Device?")) { AvdManagerAction action = new AvdManagerAction(); action.run(null /*action*/); searchAgain[0] = true; } } }); if (searchAgain[0]) { // attempt to reload the AVDs and find one compatible. defaultAvd = findMatchingAvd(avdManager, projectTarget); if (defaultAvd == null) { AdtPlugin.printErrorToConsole(project, String.format( "Still no compatible AVDs with target '%1$s': Aborting launch.", projectTarget.getName())); stopLaunch(launchInfo); } else { response.setAvdToLaunch(defaultAvd); AdtPlugin.printToConsole(project, String.format( "Launching new emulator with compatible AVD '%1$s'", defaultAvd.getName())); continueLaunch(response, project, launch, launchInfo, config); return; } } } } else if (hasDevice == false && compatibleRunningAvds.size() == 1) { Entry<IDevice, AvdInfo> e = compatibleRunningAvds.entrySet().iterator().next(); response.setDeviceToUse(e.getKey()); // get the AvdInfo, if null, the device is a physical device. AvdInfo avdInfo = e.getValue(); if (avdInfo != null) { message = String.format("Automatic Target Mode: using existing emulator '%1$s' running compatible AVD '%2$s'", response.getDeviceToUse(), e.getValue().getName()); } else { message = String.format("Automatic Target Mode: using device '%1$s'", response.getDeviceToUse()); } AdtPlugin.printToConsole(project, message); continueLaunch(response, project, launch, launchInfo, config); return; } // if more than one device, we'll bring up the DeviceChooser dialog below. if (compatibleRunningAvds.size() >= 2) { message = "Automatic Target Mode: Several compatible targets. Please select a target device."; } else if (hasDevice) { message = "Automatic Target Mode: Unable to detect device compatibility. Please select a target device."; } AdtPlugin.printToConsole(project, message); } // bring up the device chooser. AdtPlugin.getDisplay().asyncExec(new Runnable() { public void run() { try { // open the chooser dialog. It'll fill 'response' with the device to use // or the AVD to launch. DeviceChooserDialog dialog = new DeviceChooserDialog( AdtPlugin.getDisplay().getActiveShell(), response, launchInfo.getPackageName(), projectTarget); if (dialog.open() == Dialog.OK) { AndroidLaunchController.this.continueLaunch(response, project, launch, launchInfo, config); } else { AdtPlugin.printErrorToConsole(project, "Launch canceled!"); stopLaunch(launchInfo); return; } } catch (Exception e) { // there seems to be some case where the shell will be null. (might be // an OS X bug). Because of this the creation of the dialog will throw // and IllegalArg exception interrupting the launch with no user feedback. // So we trap all the exception and display something. String msg = e.getMessage(); if (msg == null) { msg = e.getClass().getCanonicalName(); } AdtPlugin.printErrorToConsole(project, String.format("Error during launch: %s", msg)); stopLaunch(launchInfo); } } }); }
public void launch(final IProject project, String mode, IFile apk, String packageName, String debugPackageName, Boolean debuggable, String requiredApiVersionNumber, final IAndroidLaunchAction launchAction, final AndroidLaunchConfiguration config, final AndroidLaunch launch, IProgressMonitor monitor) { String message = String.format("Performing %1$s", launchAction.getLaunchDescription()); AdtPlugin.printToConsole(project, message); // create the launch info final DelayedLaunchInfo launchInfo = new DelayedLaunchInfo(project, packageName, debugPackageName, launchAction, apk, debuggable, requiredApiVersionNumber, launch, monitor); // set the debug mode launchInfo.setDebugMode(mode.equals(ILaunchManager.DEBUG_MODE)); // get the SDK Sdk currentSdk = Sdk.getCurrent(); AvdManager avdManager = currentSdk.getAvdManager(); // reload the AVDs to make sure we are up to date try { avdManager.reloadAvds(NullSdkLog.getLogger()); } catch (AndroidLocationException e1) { // this happens if the AVD Manager failed to find the folder in which the AVDs are // stored. This is unlikely to happen, but if it does, we should force to go manual // to allow using physical devices. config.mTargetMode = TargetMode.MANUAL; } // get the project target final IAndroidTarget projectTarget = currentSdk.getTarget(project); // FIXME: check errors on missing sdk, AVD manager, or project target. // device chooser response object. final DeviceChooserResponse response = new DeviceChooserResponse(); /* * Launch logic: * - Manually Mode * Always display a UI that lets a user see the current running emulators/devices. * The UI must show which devices are compatibles, and allow launching new emulators * with compatible (and not yet running) AVD. * - Automatic Way * * Preferred AVD set. * If Preferred AVD is not running: launch it. * Launch the application on the preferred AVD. * * No preferred AVD. * Count the number of compatible emulators/devices. * If != 1, display a UI similar to manual mode. * If == 1, launch the application on this AVD/device. */ if (config.mTargetMode == TargetMode.AUTO) { // if we are in automatic target mode, we need to find the current devices IDevice[] devices = AndroidDebugBridge.getBridge().getDevices(); // first check if we have a preferred AVD name, and if it actually exists, and is valid // (ie able to run the project). // We need to check this in case the AVD was recreated with a different target that is // not compatible. AvdInfo preferredAvd = null; if (config.mAvdName != null) { preferredAvd = avdManager.getAvd(config.mAvdName, true /*validAvdOnly*/); if (projectTarget.isCompatibleBaseFor(preferredAvd.getTarget()) == false) { preferredAvd = null; AdtPlugin.printErrorToConsole(project, String.format( "Preferred AVD '%1$s' is not compatible with the project target '%2$s'. Looking for a compatible AVD...", config.mAvdName, projectTarget.getName())); } } if (preferredAvd != null) { // look for a matching device for (IDevice d : devices) { String deviceAvd = d.getAvdName(); if (deviceAvd != null && deviceAvd.equals(config.mAvdName)) { response.setDeviceToUse(d); AdtPlugin.printToConsole(project, String.format( "Automatic Target Mode: Preferred AVD '%1$s' is available on emulator '%2$s'", config.mAvdName, d)); continueLaunch(response, project, launch, launchInfo, config); return; } } // at this point we have a valid preferred AVD that is not running. // We need to start it. response.setAvdToLaunch(preferredAvd); AdtPlugin.printToConsole(project, String.format( "Automatic Target Mode: Preferred AVD '%1$s' is not available. Launching new emulator.", config.mAvdName)); continueLaunch(response, project, launch, launchInfo, config); return; } // no (valid) preferred AVD? look for one. HashMap<IDevice, AvdInfo> compatibleRunningAvds = new HashMap<IDevice, AvdInfo>(); boolean hasDevice = false; // if there's 1+ device running, we may force manual mode, // as we cannot always detect proper compatibility with // devices. This is the case if the project target is not // a standard platform for (IDevice d : devices) { String deviceAvd = d.getAvdName(); if (deviceAvd != null) { // physical devices return null. AvdInfo info = avdManager.getAvd(deviceAvd, true /*validAvdOnly*/); if (info != null && projectTarget.isCompatibleBaseFor(info.getTarget())) { compatibleRunningAvds.put(d, info); } } else { if (projectTarget.isPlatform()) { // means this can run on any device as long // as api level is high enough AndroidVersion deviceVersion = Sdk.getDeviceVersion(d); // the deviceVersion may be null if it wasn't yet queried (device just // plugged in or emulator just booting up. if (deviceVersion != null && deviceVersion.canRun(projectTarget.getVersion())) { // device is compatible with project compatibleRunningAvds.put(d, null); continue; } } else { // for non project platform, we can't be sure if a device can // run an application or not, since we don't query the device // for the list of optional libraries that it supports. } hasDevice = true; } } // depending on the number of devices, we'll simulate an automatic choice // from the device chooser or simply show up the device chooser. if (hasDevice == false && compatibleRunningAvds.size() == 0) { // if zero emulators/devices, we launch an emulator. // We need to figure out which AVD first. // we are going to take the closest AVD. ie a compatible AVD that has the API level // closest to the project target. AvdInfo defaultAvd = findMatchingAvd(avdManager, projectTarget); if (defaultAvd != null) { response.setAvdToLaunch(defaultAvd); AdtPlugin.printToConsole(project, String.format( "Automatic Target Mode: launching new emulator with compatible AVD '%1$s'", defaultAvd.getName())); continueLaunch(response, project, launch, launchInfo, config); return; } else { AdtPlugin.printToConsole(project, String.format( "Failed to find an AVD compatible with target '%1$s'.", projectTarget.getName())); final Display display = AdtPlugin.getDisplay(); final boolean[] searchAgain = new boolean[] { false }; // ask the user to create a new one. display.syncExec(new Runnable() { public void run() { Shell shell = display.getActiveShell(); if (MessageDialog.openQuestion(shell, "Android AVD Error", "No compatible targets were found. Do you wish to a add new Android Virtual Device?")) { AvdManagerAction action = new AvdManagerAction(); action.run(null /*action*/); searchAgain[0] = true; } } }); if (searchAgain[0]) { // attempt to reload the AVDs and find one compatible. defaultAvd = findMatchingAvd(avdManager, projectTarget); if (defaultAvd == null) { AdtPlugin.printErrorToConsole(project, String.format( "Still no compatible AVDs with target '%1$s': Aborting launch.", projectTarget.getName())); stopLaunch(launchInfo); } else { response.setAvdToLaunch(defaultAvd); AdtPlugin.printToConsole(project, String.format( "Launching new emulator with compatible AVD '%1$s'", defaultAvd.getName())); continueLaunch(response, project, launch, launchInfo, config); return; } } } } else if (hasDevice == false && compatibleRunningAvds.size() == 1) { Entry<IDevice, AvdInfo> e = compatibleRunningAvds.entrySet().iterator().next(); response.setDeviceToUse(e.getKey()); // get the AvdInfo, if null, the device is a physical device. AvdInfo avdInfo = e.getValue(); if (avdInfo != null) { message = String.format("Automatic Target Mode: using existing emulator '%1$s' running compatible AVD '%2$s'", response.getDeviceToUse(), e.getValue().getName()); } else { message = String.format("Automatic Target Mode: using device '%1$s'", response.getDeviceToUse()); } AdtPlugin.printToConsole(project, message); continueLaunch(response, project, launch, launchInfo, config); return; } // if more than one device, we'll bring up the DeviceChooser dialog below. if (compatibleRunningAvds.size() >= 2) { message = "Automatic Target Mode: Several compatible targets. Please select a target device."; } else if (hasDevice) { message = "Automatic Target Mode: Unable to detect device compatibility. Please select a target device."; } AdtPlugin.printToConsole(project, message); } // bring up the device chooser. AdtPlugin.getDisplay().asyncExec(new Runnable() { public void run() { try { // open the chooser dialog. It'll fill 'response' with the device to use // or the AVD to launch. DeviceChooserDialog dialog = new DeviceChooserDialog( AdtPlugin.getDisplay().getActiveShell(), response, launchInfo.getPackageName(), projectTarget); if (dialog.open() == Dialog.OK) { AndroidLaunchController.this.continueLaunch(response, project, launch, launchInfo, config); } else { AdtPlugin.printErrorToConsole(project, "Launch canceled!"); stopLaunch(launchInfo); return; } } catch (Exception e) { // there seems to be some case where the shell will be null. (might be // an OS X bug). Because of this the creation of the dialog will throw // and IllegalArg exception interrupting the launch with no user feedback. // So we trap all the exception and display something. String msg = e.getMessage(); if (msg == null) { msg = e.getClass().getCanonicalName(); } AdtPlugin.printErrorToConsole(project, String.format("Error during launch: %s", msg)); stopLaunch(launchInfo); } } }); }
diff --git a/src/com/github/pickncrop/MainActivity.java b/src/com/github/pickncrop/MainActivity.java index ee0e1f6..8812c8a 100644 --- a/src/com/github/pickncrop/MainActivity.java +++ b/src/com/github/pickncrop/MainActivity.java @@ -1,202 +1,206 @@ /* * Copyright 2012 Dmytro Titov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pickncrop; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.UUID; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.Matrix; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.view.Display; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup.LayoutParams; import android.view.ViewManager; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.RelativeLayout; import android.widget.Toast; import android.widget.ZoomButtonsController; import android.widget.ZoomButtonsController.OnZoomListener; public class MainActivity extends Activity { private ImageView imageView; private ViewManager viewManager; private Matrix matrix; private int size; private final int outputSize = 100; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight(); size = width < height ? width : height; size -= 50; imageView = (ImageView) findViewById(R.id.imageViewCrop); imageView.getLayoutParams().width = size; imageView.getLayoutParams().height = size; viewManager = (ViewManager) imageView.getParent(); - if (!getPackageManager().hasSystemFeature( + if (getPackageManager().hasSystemFeature( PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH)) { createZoomControls(); } imageView.setOnTouchListener(new OnTouchListener() { float initX; float initY; + float midX; + float midY; float scale; float initDistance; float currentDistance; boolean isMultitouch = false; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: initX = event.getX(); initY = event.getY(); break; case MotionEvent.ACTION_POINTER_DOWN: isMultitouch = true; initDistance = (float) Math.sqrt(Math.pow( initX - event.getX(1), 2) + Math.pow(initY - event.getY(1), 2)); break; case MotionEvent.ACTION_MOVE: if (isMultitouch) { matrix = imageView.getImageMatrix(); currentDistance = (float) Math.sqrt(Math.pow(initX - event.getX(1), 2) + Math.pow(initY - event.getY(1), 2)); scale = 1 + 0.001f * (currentDistance - initDistance); - matrix.postScale(scale, scale, 0.5f * size, 0.5f * size); + midX = 0.5f * (initX + event.getX(1)); + midY = 0.5f * (initY + event.getY(1)); + matrix.postScale(scale, scale, midX, midY); imageView.setImageMatrix(matrix); imageView.invalidate(); } else { imageView.scrollBy((int) (initX - event.getX()), (int) (initY - event.getY())); initX = event.getX(); initY = event.getY(); } break; case MotionEvent.ACTION_UP: isMultitouch = false; break; case MotionEvent.ACTION_POINTER_UP: isMultitouch = false; break; } return true; } }); } public void createZoomControls() { ZoomButtonsController zoomButtonsController = new ZoomButtonsController( imageView); zoomButtonsController.setVisible(true); zoomButtonsController.setAutoDismissed(false); zoomButtonsController.setOnZoomListener(new OnZoomListener() { @Override public void onZoom(boolean zoomIn) { matrix = imageView.getImageMatrix(); if (zoomIn) { matrix.postScale(1.05f, 1.05f, 0.5f * size, 0.5f * size); imageView.setImageMatrix(matrix); } else { matrix.postScale(0.95f, 0.95f, 0.5f * size, 0.5f * size); imageView.setImageMatrix(matrix); } imageView.invalidate(); } @Override public void onVisibilityChanged(boolean visible) { } }); RelativeLayout.LayoutParams zoomLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); zoomLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); zoomLayoutParams.addRule(RelativeLayout.BELOW, R.id.imageViewCrop); viewManager.addView(zoomButtonsController.getContainer(), zoomLayoutParams); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { Toast.makeText(this, R.string.info, 5).show(); return super.onMenuItemSelected(featureId, item); } public void buttonPickClick(View view) { Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, 0); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (resultCode) { case RESULT_OK: Uri targetUri = data.getData(); imageView.setScaleType(ScaleType.CENTER_INSIDE); imageView.scrollTo(0, 0); imageView.setImageURI(targetUri); imageView.setScaleType(ScaleType.MATRIX); break; } } public void buttonCropClick(View view) throws IOException { imageView.setDrawingCacheEnabled(true); imageView.buildDrawingCache(true); File imageFile = new File(Environment.getExternalStorageDirectory(), "Pictures/" + UUID.randomUUID().toString() + ".jpg"); FileOutputStream fileOutputStream = new FileOutputStream(imageFile); Bitmap.createScaledBitmap(imageView.getDrawingCache(true), outputSize, outputSize, false).compress(CompressFormat.JPEG, 100, fileOutputStream); fileOutputStream.close(); imageView.setDrawingCacheEnabled(false); } }
false
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight(); size = width < height ? width : height; size -= 50; imageView = (ImageView) findViewById(R.id.imageViewCrop); imageView.getLayoutParams().width = size; imageView.getLayoutParams().height = size; viewManager = (ViewManager) imageView.getParent(); if (!getPackageManager().hasSystemFeature( PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH)) { createZoomControls(); } imageView.setOnTouchListener(new OnTouchListener() { float initX; float initY; float scale; float initDistance; float currentDistance; boolean isMultitouch = false; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: initX = event.getX(); initY = event.getY(); break; case MotionEvent.ACTION_POINTER_DOWN: isMultitouch = true; initDistance = (float) Math.sqrt(Math.pow( initX - event.getX(1), 2) + Math.pow(initY - event.getY(1), 2)); break; case MotionEvent.ACTION_MOVE: if (isMultitouch) { matrix = imageView.getImageMatrix(); currentDistance = (float) Math.sqrt(Math.pow(initX - event.getX(1), 2) + Math.pow(initY - event.getY(1), 2)); scale = 1 + 0.001f * (currentDistance - initDistance); matrix.postScale(scale, scale, 0.5f * size, 0.5f * size); imageView.setImageMatrix(matrix); imageView.invalidate(); } else { imageView.scrollBy((int) (initX - event.getX()), (int) (initY - event.getY())); initX = event.getX(); initY = event.getY(); } break; case MotionEvent.ACTION_UP: isMultitouch = false; break; case MotionEvent.ACTION_POINTER_UP: isMultitouch = false; break; } return true; } }); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight(); size = width < height ? width : height; size -= 50; imageView = (ImageView) findViewById(R.id.imageViewCrop); imageView.getLayoutParams().width = size; imageView.getLayoutParams().height = size; viewManager = (ViewManager) imageView.getParent(); if (getPackageManager().hasSystemFeature( PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH)) { createZoomControls(); } imageView.setOnTouchListener(new OnTouchListener() { float initX; float initY; float midX; float midY; float scale; float initDistance; float currentDistance; boolean isMultitouch = false; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: initX = event.getX(); initY = event.getY(); break; case MotionEvent.ACTION_POINTER_DOWN: isMultitouch = true; initDistance = (float) Math.sqrt(Math.pow( initX - event.getX(1), 2) + Math.pow(initY - event.getY(1), 2)); break; case MotionEvent.ACTION_MOVE: if (isMultitouch) { matrix = imageView.getImageMatrix(); currentDistance = (float) Math.sqrt(Math.pow(initX - event.getX(1), 2) + Math.pow(initY - event.getY(1), 2)); scale = 1 + 0.001f * (currentDistance - initDistance); midX = 0.5f * (initX + event.getX(1)); midY = 0.5f * (initY + event.getY(1)); matrix.postScale(scale, scale, midX, midY); imageView.setImageMatrix(matrix); imageView.invalidate(); } else { imageView.scrollBy((int) (initX - event.getX()), (int) (initY - event.getY())); initX = event.getX(); initY = event.getY(); } break; case MotionEvent.ACTION_UP: isMultitouch = false; break; case MotionEvent.ACTION_POINTER_UP: isMultitouch = false; break; } return true; } }); }
diff --git a/src/org/apache/xpath/compiler/Lexer.java b/src/org/apache/xpath/compiler/Lexer.java index 14ede5ae..6ff2b9d8 100644 --- a/src/org/apache/xpath/compiler/Lexer.java +++ b/src/org/apache/xpath/compiler/Lexer.java @@ -1,688 +1,688 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, Lotus * Development Corporation., http://www.lotus.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xpath.compiler; import org.apache.xml.utils.PrefixResolver; import java.util.Vector; import org.apache.xpath.res.XPATHErrorResources; import org.apache.xpath.XPath; import org.apache.xpath.compiler.Compiler; import org.apache.xpath.compiler.OpCodes; import org.apache.xpath.compiler.XPathParser; /** * This class is in charge of lexical processing of the XPath * expression into tokens. */ class Lexer { /** * The target XPath. */ private Compiler m_compiler; /** * The prefix resolver to map prefixes to namespaces in the XPath. */ PrefixResolver m_namespaceContext; /** * The XPath processor object. */ XPathParser m_processor; /** * This value is added to each element name in the TARGETEXTRA * that is a 'target' (right-most top-level element name). */ static final int TARGETEXTRA = 10000; /** * Ignore this, it is going away. * This holds a map to the m_tokenQueue that tells where the top-level elements are. * It is used for pattern matching so the m_tokenQueue can be walked backwards. * Each element that is a 'target', (right-most top level element name) has * TARGETEXTRA added to it. * */ private int m_patternMap[] = new int[100]; /** * Ignore this, it is going away. * The number of elements that m_patternMap maps; */ private int m_patternMapSize; /** * Create a Lexer object. * * @param compiler The owning compiler for this lexer. * @param resolver The prefix resolver for mapping qualified name prefixes * to namespace URIs. * @param xpathProcessor The parser that is processing strings to opcodes. */ Lexer(Compiler compiler, PrefixResolver resolver, XPathParser xpathProcessor) { m_compiler = compiler; m_namespaceContext = resolver; m_processor = xpathProcessor; } /** * Walk through the expression and build a token queue, and a map of the top-level * elements. * @param pat XSLT Expression. * * @throws javax.xml.transform.TransformerException */ void tokenize(String pat) throws javax.xml.transform.TransformerException { tokenize(pat, null); } /** * Walk through the expression and build a token queue, and a map of the top-level * elements. * @param pat XSLT Expression. * @param targetStrings Vector to hold Strings, may be null. * * @throws javax.xml.transform.TransformerException */ void tokenize(String pat, Vector targetStrings) throws javax.xml.transform.TransformerException { m_compiler.m_tokenQueueSize = 0; m_compiler.m_currentPattern = pat; m_patternMapSize = 0; m_compiler.m_opMap = new int[OpMap.MAXTOKENQUEUESIZE * 5]; int nChars = pat.length(); int startSubstring = -1; int posOfNSSep = -1; boolean isStartOfPat = true; boolean isAttrName = false; boolean isNum = false; // Nesting of '[' so we can know if the given element should be // counted inside the m_patternMap. int nesting = 0; // char[] chars = pat.toCharArray(); for (int i = 0; i < nChars; i++) { char c = pat.charAt(i); switch (c) { case '\"' : { if (startSubstring != -1) { isNum = false; isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName); isAttrName = false; if (-1 != posOfNSSep) { posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i); } else { addToTokenQueue(pat.substring(startSubstring, i)); } } startSubstring = i; for (i++; (i < nChars) && ((c = pat.charAt(i)) != '\"'); i++); - if (c == '\"') + if (c == '\"' && i < nChars) { addToTokenQueue(pat.substring(startSubstring, i + 1)); startSubstring = -1; } else { m_processor.error(XPATHErrorResources.ER_EXPECTED_DOUBLE_QUOTE, null); //"misquoted literal... expected double quote!"); } } break; case '\'' : if (startSubstring != -1) { isNum = false; isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName); isAttrName = false; if (-1 != posOfNSSep) { posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i); } else { addToTokenQueue(pat.substring(startSubstring, i)); } } startSubstring = i; for (i++; (i < nChars) && ((c = pat.charAt(i)) != '\''); i++); - if (c == '\'') + if (c == '\'' && i < nChars) { addToTokenQueue(pat.substring(startSubstring, i + 1)); startSubstring = -1; } else { m_processor.error(XPATHErrorResources.ER_EXPECTED_SINGLE_QUOTE, null); //"misquoted literal... expected single quote!"); } break; case 0x0A : case 0x0D : case ' ' : case '\t' : if (startSubstring != -1) { isNum = false; isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName); isAttrName = false; if (-1 != posOfNSSep) { posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i); } else { addToTokenQueue(pat.substring(startSubstring, i)); } startSubstring = -1; } break; case '@' : isAttrName = true; // fall-through on purpose case '-' : if ('-' == c) { if (!(isNum || (startSubstring == -1))) { break; } isNum = false; } // fall-through on purpose case '(' : case '[' : case ')' : case ']' : case '|' : case '/' : case '*' : case '+' : case '=' : case ',' : case '\\' : // Unused at the moment case '^' : // Unused at the moment case '!' : // Unused at the moment case '$' : case '<' : case '>' : if (startSubstring != -1) { isNum = false; isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName); isAttrName = false; if (-1 != posOfNSSep) { posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i); } else { addToTokenQueue(pat.substring(startSubstring, i)); } startSubstring = -1; } else if (('/' == c) && isStartOfPat) { isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName); } else if ('*' == c) { isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName); isAttrName = false; } if (0 == nesting) { if ('|' == c) { if (null != targetStrings) { recordTokenString(targetStrings); } isStartOfPat = true; } } if ((')' == c) || (']' == c)) { nesting--; } else if (('(' == c) || ('[' == c)) { nesting++; } addToTokenQueue(pat.substring(i, i + 1)); break; case ':' : if (posOfNSSep == (i - 1)) { if (startSubstring != -1) { if (startSubstring < (i - 1)) addToTokenQueue(pat.substring(startSubstring, i - 1)); } isNum = false; isAttrName = false; startSubstring = -1; posOfNSSep = -1; addToTokenQueue(pat.substring(i - 1, i + 1)); break; } else { posOfNSSep = i; } // fall through on purpose default : if (-1 == startSubstring) { startSubstring = i; isNum = Character.isDigit(c); } else if (isNum) { isNum = Character.isDigit(c); } } } if (startSubstring != -1) { isNum = false; isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName); if (-1 != posOfNSSep) { posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, nChars); } else { addToTokenQueue(pat.substring(startSubstring, nChars)); } } if (0 == m_compiler.m_tokenQueueSize) { m_processor.error(XPATHErrorResources.ER_EMPTY_EXPRESSION, null); //"Empty expression!"); } else if (null != targetStrings) { recordTokenString(targetStrings); } m_processor.m_queueMark = 0; } /** * Record the current position on the token queue as long as * this is a top-level element. Must be called before the * next token is added to the m_tokenQueue. * * @param nesting The nesting count for the pattern element. * @param isStart true if this is the start of a pattern. * @param isAttrName true if we have determined that this is an attribute name. * * @return true if this is the start of a pattern. */ private boolean mapPatternElemPos(int nesting, boolean isStart, boolean isAttrName) { if (0 == nesting) { if(m_patternMapSize >= m_patternMap.length) { int patternMap[] = m_patternMap; int len = m_patternMap.length; m_patternMap = new int[m_patternMapSize + 100]; System.arraycopy(patternMap, 0, m_patternMap, 0, len); } if (!isStart) { m_patternMap[m_patternMapSize - 1] -= TARGETEXTRA; } m_patternMap[m_patternMapSize] = (m_compiler.m_tokenQueueSize - (isAttrName ? 1 : 0)) + TARGETEXTRA; m_patternMapSize++; isStart = false; } return isStart; } /** * Given a map pos, return the corresponding token queue pos. * * @param i The index in the m_patternMap. * * @return the token queue position. */ private int getTokenQueuePosFromMap(int i) { int pos = m_patternMap[i]; return (pos >= TARGETEXTRA) ? (pos - TARGETEXTRA) : pos; } /** * Reset token queue mark and m_token to a * given position. * @param mark The new position. */ private final void resetTokenMark(int mark) { int qsz = m_compiler.m_tokenQueueSize; m_processor.m_queueMark = (mark > 0) ? ((mark <= qsz) ? mark - 1 : mark) : 0; if (m_processor.m_queueMark < qsz) { m_processor.m_token = (String) m_compiler.m_tokenQueue[m_processor.m_queueMark++]; m_processor.m_tokenChar = m_processor.m_token.charAt(0); } else { m_processor.m_token = null; m_processor.m_tokenChar = 0; } } /** * Given a string, return the corresponding keyword token. * * @param key The keyword. * * @return An opcode value. */ final int getKeywordToken(String key) { int tok; try { Integer itok = (Integer) Keywords.m_keywords.get(key); tok = (null != itok) ? itok.intValue() : 0; } catch (NullPointerException npe) { tok = 0; } catch (ClassCastException cce) { tok = 0; } return tok; } /** * Record the current token in the passed vector. * * @param targetStrings Vector of string. */ private void recordTokenString(Vector targetStrings) { int tokPos = getTokenQueuePosFromMap(m_patternMapSize - 1); resetTokenMark(tokPos + 1); if (m_processor.lookahead('(', 1)) { int tok = getKeywordToken(m_processor.m_token); switch (tok) { case OpCodes.NODETYPE_COMMENT : targetStrings.addElement(PsuedoNames.PSEUDONAME_COMMENT); break; case OpCodes.NODETYPE_TEXT : targetStrings.addElement(PsuedoNames.PSEUDONAME_TEXT); break; case OpCodes.NODETYPE_NODE : targetStrings.addElement(PsuedoNames.PSEUDONAME_ANY); break; case OpCodes.NODETYPE_ROOT : targetStrings.addElement(PsuedoNames.PSEUDONAME_ROOT); break; case OpCodes.NODETYPE_ANYELEMENT : targetStrings.addElement(PsuedoNames.PSEUDONAME_ANY); break; case OpCodes.NODETYPE_PI : targetStrings.addElement(PsuedoNames.PSEUDONAME_ANY); break; default : targetStrings.addElement(PsuedoNames.PSEUDONAME_ANY); } } else { if (m_processor.tokenIs('@')) { tokPos++; resetTokenMark(tokPos + 1); } if (m_processor.lookahead(':', 1)) { tokPos += 2; } targetStrings.addElement(m_compiler.m_tokenQueue[tokPos]); } } /** * Add a token to the token queue. * * * @param s The token. */ private final void addToTokenQueue(String s) { m_compiler.m_tokenQueue[m_compiler.m_tokenQueueSize++] = s; } /** * When a seperator token is found, see if there's a element name or * the like to map. * * @param pat The XPath name string. * @param startSubstring The start of the name string. * @param posOfNSSep The position of the namespace seperator (':'). * @param posOfScan The end of the name index. * * @throws javax.xml.transform.TransformerException * * @return -1 always. */ private int mapNSTokens(String pat, int startSubstring, int posOfNSSep, int posOfScan) throws javax.xml.transform.TransformerException { String prefix = pat.substring(startSubstring, posOfNSSep); String uName; if ((null != m_namespaceContext) &&!prefix.equals("*") &&!prefix.equals("xmlns")) { try { if (prefix.length() > 0) uName = ((PrefixResolver) m_namespaceContext).getNamespaceForPrefix( prefix); else { // Assume last was wildcard. This is not legal according // to the draft. Set the below to true to make namespace // wildcards work. if (false) { addToTokenQueue(":"); String s = pat.substring(posOfNSSep + 1, posOfScan); if (s.length() > 0) addToTokenQueue(s); return -1; } else { uName = ((PrefixResolver) m_namespaceContext).getNamespaceForPrefix( prefix); } } } catch (ClassCastException cce) { uName = m_namespaceContext.getNamespaceForPrefix(prefix); } } else { uName = prefix; } if ((null != uName) && (uName.length() > 0)) { addToTokenQueue(uName); addToTokenQueue(":"); String s = pat.substring(posOfNSSep + 1, posOfScan); if (s.length() > 0) addToTokenQueue(s); } else { // error("Could not locate namespace for prefix: "+prefix); m_processor.error(XPATHErrorResources.ER_PREFIX_MUST_RESOLVE, new String[] {prefix}); //"Prefix must resolve to a namespace: {0}"; /*** Old code commented out 10-Jan-2001 addToTokenQueue(prefix); addToTokenQueue(":"); String s = pat.substring(posOfNSSep + 1, posOfScan); if (s.length() > 0) addToTokenQueue(s); ***/ } return -1; } }
false
true
void tokenize(String pat, Vector targetStrings) throws javax.xml.transform.TransformerException { m_compiler.m_tokenQueueSize = 0; m_compiler.m_currentPattern = pat; m_patternMapSize = 0; m_compiler.m_opMap = new int[OpMap.MAXTOKENQUEUESIZE * 5]; int nChars = pat.length(); int startSubstring = -1; int posOfNSSep = -1; boolean isStartOfPat = true; boolean isAttrName = false; boolean isNum = false; // Nesting of '[' so we can know if the given element should be // counted inside the m_patternMap. int nesting = 0; // char[] chars = pat.toCharArray(); for (int i = 0; i < nChars; i++) { char c = pat.charAt(i); switch (c) { case '\"' : { if (startSubstring != -1) { isNum = false; isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName); isAttrName = false; if (-1 != posOfNSSep) { posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i); } else { addToTokenQueue(pat.substring(startSubstring, i)); } } startSubstring = i; for (i++; (i < nChars) && ((c = pat.charAt(i)) != '\"'); i++); if (c == '\"') { addToTokenQueue(pat.substring(startSubstring, i + 1)); startSubstring = -1; } else { m_processor.error(XPATHErrorResources.ER_EXPECTED_DOUBLE_QUOTE, null); //"misquoted literal... expected double quote!"); } } break; case '\'' : if (startSubstring != -1) { isNum = false; isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName); isAttrName = false; if (-1 != posOfNSSep) { posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i); } else { addToTokenQueue(pat.substring(startSubstring, i)); } } startSubstring = i; for (i++; (i < nChars) && ((c = pat.charAt(i)) != '\''); i++); if (c == '\'') { addToTokenQueue(pat.substring(startSubstring, i + 1)); startSubstring = -1; } else { m_processor.error(XPATHErrorResources.ER_EXPECTED_SINGLE_QUOTE, null); //"misquoted literal... expected single quote!"); } break; case 0x0A : case 0x0D : case ' ' : case '\t' : if (startSubstring != -1) { isNum = false; isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName); isAttrName = false; if (-1 != posOfNSSep) { posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i); } else { addToTokenQueue(pat.substring(startSubstring, i)); } startSubstring = -1; } break; case '@' : isAttrName = true; // fall-through on purpose case '-' : if ('-' == c) { if (!(isNum || (startSubstring == -1))) { break; } isNum = false; } // fall-through on purpose case '(' : case '[' : case ')' : case ']' : case '|' : case '/' : case '*' : case '+' : case '=' : case ',' : case '\\' : // Unused at the moment case '^' : // Unused at the moment case '!' : // Unused at the moment case '$' : case '<' : case '>' : if (startSubstring != -1) { isNum = false; isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName); isAttrName = false; if (-1 != posOfNSSep) { posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i); } else { addToTokenQueue(pat.substring(startSubstring, i)); } startSubstring = -1; } else if (('/' == c) && isStartOfPat) { isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName); } else if ('*' == c) { isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName); isAttrName = false; } if (0 == nesting) { if ('|' == c) { if (null != targetStrings) { recordTokenString(targetStrings); } isStartOfPat = true; } } if ((')' == c) || (']' == c)) { nesting--; } else if (('(' == c) || ('[' == c)) { nesting++; } addToTokenQueue(pat.substring(i, i + 1)); break; case ':' : if (posOfNSSep == (i - 1)) { if (startSubstring != -1) { if (startSubstring < (i - 1)) addToTokenQueue(pat.substring(startSubstring, i - 1)); } isNum = false; isAttrName = false; startSubstring = -1; posOfNSSep = -1; addToTokenQueue(pat.substring(i - 1, i + 1)); break; } else { posOfNSSep = i; } // fall through on purpose default : if (-1 == startSubstring) { startSubstring = i; isNum = Character.isDigit(c); } else if (isNum) { isNum = Character.isDigit(c); } } } if (startSubstring != -1) { isNum = false; isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName); if (-1 != posOfNSSep) { posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, nChars); } else { addToTokenQueue(pat.substring(startSubstring, nChars)); } } if (0 == m_compiler.m_tokenQueueSize) { m_processor.error(XPATHErrorResources.ER_EMPTY_EXPRESSION, null); //"Empty expression!"); } else if (null != targetStrings) { recordTokenString(targetStrings); } m_processor.m_queueMark = 0; }
void tokenize(String pat, Vector targetStrings) throws javax.xml.transform.TransformerException { m_compiler.m_tokenQueueSize = 0; m_compiler.m_currentPattern = pat; m_patternMapSize = 0; m_compiler.m_opMap = new int[OpMap.MAXTOKENQUEUESIZE * 5]; int nChars = pat.length(); int startSubstring = -1; int posOfNSSep = -1; boolean isStartOfPat = true; boolean isAttrName = false; boolean isNum = false; // Nesting of '[' so we can know if the given element should be // counted inside the m_patternMap. int nesting = 0; // char[] chars = pat.toCharArray(); for (int i = 0; i < nChars; i++) { char c = pat.charAt(i); switch (c) { case '\"' : { if (startSubstring != -1) { isNum = false; isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName); isAttrName = false; if (-1 != posOfNSSep) { posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i); } else { addToTokenQueue(pat.substring(startSubstring, i)); } } startSubstring = i; for (i++; (i < nChars) && ((c = pat.charAt(i)) != '\"'); i++); if (c == '\"' && i < nChars) { addToTokenQueue(pat.substring(startSubstring, i + 1)); startSubstring = -1; } else { m_processor.error(XPATHErrorResources.ER_EXPECTED_DOUBLE_QUOTE, null); //"misquoted literal... expected double quote!"); } } break; case '\'' : if (startSubstring != -1) { isNum = false; isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName); isAttrName = false; if (-1 != posOfNSSep) { posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i); } else { addToTokenQueue(pat.substring(startSubstring, i)); } } startSubstring = i; for (i++; (i < nChars) && ((c = pat.charAt(i)) != '\''); i++); if (c == '\'' && i < nChars) { addToTokenQueue(pat.substring(startSubstring, i + 1)); startSubstring = -1; } else { m_processor.error(XPATHErrorResources.ER_EXPECTED_SINGLE_QUOTE, null); //"misquoted literal... expected single quote!"); } break; case 0x0A : case 0x0D : case ' ' : case '\t' : if (startSubstring != -1) { isNum = false; isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName); isAttrName = false; if (-1 != posOfNSSep) { posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i); } else { addToTokenQueue(pat.substring(startSubstring, i)); } startSubstring = -1; } break; case '@' : isAttrName = true; // fall-through on purpose case '-' : if ('-' == c) { if (!(isNum || (startSubstring == -1))) { break; } isNum = false; } // fall-through on purpose case '(' : case '[' : case ')' : case ']' : case '|' : case '/' : case '*' : case '+' : case '=' : case ',' : case '\\' : // Unused at the moment case '^' : // Unused at the moment case '!' : // Unused at the moment case '$' : case '<' : case '>' : if (startSubstring != -1) { isNum = false; isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName); isAttrName = false; if (-1 != posOfNSSep) { posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i); } else { addToTokenQueue(pat.substring(startSubstring, i)); } startSubstring = -1; } else if (('/' == c) && isStartOfPat) { isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName); } else if ('*' == c) { isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName); isAttrName = false; } if (0 == nesting) { if ('|' == c) { if (null != targetStrings) { recordTokenString(targetStrings); } isStartOfPat = true; } } if ((')' == c) || (']' == c)) { nesting--; } else if (('(' == c) || ('[' == c)) { nesting++; } addToTokenQueue(pat.substring(i, i + 1)); break; case ':' : if (posOfNSSep == (i - 1)) { if (startSubstring != -1) { if (startSubstring < (i - 1)) addToTokenQueue(pat.substring(startSubstring, i - 1)); } isNum = false; isAttrName = false; startSubstring = -1; posOfNSSep = -1; addToTokenQueue(pat.substring(i - 1, i + 1)); break; } else { posOfNSSep = i; } // fall through on purpose default : if (-1 == startSubstring) { startSubstring = i; isNum = Character.isDigit(c); } else if (isNum) { isNum = Character.isDigit(c); } } } if (startSubstring != -1) { isNum = false; isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName); if (-1 != posOfNSSep) { posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, nChars); } else { addToTokenQueue(pat.substring(startSubstring, nChars)); } } if (0 == m_compiler.m_tokenQueueSize) { m_processor.error(XPATHErrorResources.ER_EMPTY_EXPRESSION, null); //"Empty expression!"); } else if (null != targetStrings) { recordTokenString(targetStrings); } m_processor.m_queueMark = 0; }
diff --git a/zanata-common-api/src/test/java/org/zanata/rest/dto/v1/SerializationTests.java b/zanata-common-api/src/test/java/org/zanata/rest/dto/v1/SerializationTests.java index 3567ac3..2907808 100644 --- a/zanata-common-api/src/test/java/org/zanata/rest/dto/v1/SerializationTests.java +++ b/zanata-common-api/src/test/java/org/zanata/rest/dto/v1/SerializationTests.java @@ -1,224 +1,223 @@ package org.zanata.rest.dto.v1; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import java.io.IOException; import javax.xml.bind.JAXBException; import javax.xml.bind.ValidationException; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zanata.common.ContentState; import org.zanata.common.ContentType; import org.zanata.common.LocaleId; import org.zanata.common.ResourceType; import org.zanata.rest.JaxbUtil; import org.zanata.rest.dto.Person; import org.zanata.rest.dto.extensions.comment.SimpleComment; import org.zanata.rest.dto.extensions.gettext.HeaderEntry; import org.zanata.rest.dto.extensions.gettext.PoHeader; import org.zanata.rest.dto.extensions.gettext.PoTargetHeader; import org.zanata.rest.dto.extensions.gettext.PotEntryHeader; import org.zanata.rest.dto.extensions.gettext.TextFlowExtension; import org.zanata.rest.dto.extensions.gettext.TextFlowTargetExtension; import org.zanata.rest.dto.resource.Resource; import org.zanata.rest.dto.resource.ResourceMeta; import org.zanata.rest.dto.resource.TextFlow; import org.zanata.rest.dto.resource.TextFlowTarget; import org.zanata.rest.dto.resource.TranslationsResource; public class SerializationTests { protected ObjectMapper mapper; private final Logger log = LoggerFactory.getLogger(SerializationTests.class); @Before public void setup() { mapper = new ObjectMapper(); // AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(); // mapper.getDeserializationConfig().setAnnotationIntrospector(introspector); // mapper.getSerializationConfig().setAnnotationIntrospector(introspector); } private Person createPerson() { return new Person("id", "name"); } @Test public void serializeAndDeserializePerson() throws JAXBException, JsonGenerationException, JsonMappingException, IOException { Person p = createPerson(); JaxbUtil.validateXml(p); String output = mapper.writeValueAsString(p); Person p2 = mapper.readValue(output, Person.class); assertThat(p2, notNullValue()); JaxbUtil.validateXml(p2); p2 = JaxbTestUtil.roundTripXml(p); assertThat(p2, notNullValue()); } private PoHeader createPoHeader() { return new PoHeader("hello world"); } @Test public void serializeAndDeserializeExtension() throws JsonGenerationException, JsonMappingException, IOException, JAXBException { // TODO are we actually trying to test serializing an extension where the type is not known? PoHeader e = createPoHeader(); JaxbUtil.validateXml(e); String output = mapper.writeValueAsString(e); PoHeader e2 = mapper.readValue(output, PoHeader.class); JaxbUtil.validateXml(e2); assertThat(e2, instanceOf(PoHeader.class)); e2 = JaxbTestUtil.roundTripXml(e, PoHeader.class); assertThat(e2, instanceOf(PoHeader.class)); } @Test public void serializeAndDeserializeTranslationResource() throws JsonGenerationException, JsonMappingException, IOException, JAXBException { ResourceMeta res = new ResourceMeta("id"); res.getExtensions(true).add(new PoHeader("comment", new HeaderEntry("h1", "v1"), new HeaderEntry("h2", "v2"))); JaxbUtil.validateXml(res, PoHeader.class); String output = mapper.writeValueAsString(res); ResourceMeta res2 = mapper.readValue(output, ResourceMeta.class); assertThat(res2.getExtensions().size(), is(1)); assertThat(res2.getExtensions().iterator().next(), instanceOf(PoHeader.class)); assertThat(((PoHeader) res2.getExtensions().iterator().next()).getComment(), is("comment")); res2 = JaxbTestUtil.roundTripXml(res, PoHeader.class); assertThat(res2, notNullValue()); assertThat(res2.getExtensions().size(), is(1)); assertThat(res2.getExtensions().iterator().next(), instanceOf(PoHeader.class)); } @Test public void serializeSourceResource() throws JsonGenerationException, JsonMappingException, IOException, JAXBException { Resource sourceResource = new Resource("Acls.pot"); sourceResource.setType(ResourceType.FILE); sourceResource.setContentType(ContentType.PO); sourceResource.setLang(LocaleId.EN); TextFlow tf = new TextFlow(); tf.setContent("ttff"); TextFlow tf2 = new TextFlow(); tf2.setContent("ttff2"); sourceResource.getTextFlows().add(tf); sourceResource.getTextFlows().add(tf2); sourceResource.getExtensions(true).add(new PoHeader("comment", new HeaderEntry("h1", "v1"), new HeaderEntry("h2", "v2"))); JaxbUtil.validateXml(sourceResource, Resource.class); String output = mapper.writeValueAsString(sourceResource); log.info(output); Resource res2 = mapper.readValue(output, Resource.class); assertThat(res2.getExtensions().size(), is(1)); assertThat(res2.getExtensions().iterator().next(), instanceOf(PoHeader.class)); assertThat(((PoHeader) res2.getExtensions().iterator().next()).getComment(), is("comment")); } @Test public void serializeAndDeserializeTextFlow() throws ValidationException, JsonGenerationException, JsonMappingException, IOException { TextFlow tf = new TextFlow(); tf.setContent("ttff"); SimpleComment comment = new SimpleComment("test"); PotEntryHeader pot = new PotEntryHeader(); pot.setContext("context"); pot.getReferences().add("fff"); - pot.setExtractedComment("extractedComment"); tf.getExtensions(true).add(comment); tf.getExtensions(true).add(pot); JaxbUtil.validateXml(tf, TextFlow.class); String output = mapper.writeValueAsString(tf); TextFlow res2 = mapper.readValue(output, TextFlow.class); assertThat(res2.getExtensions(true).size(), is(2)); for (TextFlowExtension e : res2.getExtensions()) { if (e instanceof SimpleComment) { assertThat(((SimpleComment) e).getValue(), is("test")); } if (e instanceof PotEntryHeader) { assertThat(((PotEntryHeader) e).getContext(), is("context")); } } } @Test public void serializeAndDeserializeTextFlowTarget() throws ValidationException, JsonGenerationException, JsonMappingException, IOException { TextFlowTarget tf = new TextFlowTarget(); tf.setTranslator(createPerson()); tf.setContent("ttff"); SimpleComment comment = new SimpleComment("testcomment"); tf.getExtensions(true).add(comment); JaxbUtil.validateXml(tf, TextFlowTarget.class); String output = mapper.writeValueAsString(tf); TextFlowTarget res2 = mapper.readValue(output, TextFlowTarget.class); assertThat(res2.getExtensions(true).size(), is(1)); for (TextFlowTargetExtension e : res2.getExtensions()) { if (e instanceof SimpleComment) { assertThat(((SimpleComment) e).getValue(), is("testcomment")); } } } @Test public void serializeAndDeserializeTranslation() throws JsonGenerationException, JsonMappingException, IOException, JAXBException { TranslationsResource entity = new TranslationsResource(); TextFlowTarget target = new TextFlowTarget("rest1"); target.setContent("hello world"); target.setState(ContentState.Approved); target.setTranslator(new Person("root@localhost", "Admin user")); // for the convenience of test entity.getTextFlowTargets().add(target); entity.getExtensions(true); PoTargetHeader poTargetHeader = new PoTargetHeader("target header comment", new HeaderEntry("ht", "vt1"), new HeaderEntry("th2", "tv2")); entity.getExtensions(true).add(poTargetHeader); JaxbUtil.validateXml(entity, TranslationsResource.class); String output = mapper.writeValueAsString(entity); TranslationsResource res2 = mapper.readValue(output, TranslationsResource.class); assertThat(res2.getExtensions().size(), is(1)); assertThat(res2.getExtensions().iterator().next(), instanceOf(PoTargetHeader.class)); assertThat(((PoTargetHeader) res2.getExtensions().iterator().next()).getComment(), is("target header comment")); } }
true
true
public void serializeAndDeserializeTextFlow() throws ValidationException, JsonGenerationException, JsonMappingException, IOException { TextFlow tf = new TextFlow(); tf.setContent("ttff"); SimpleComment comment = new SimpleComment("test"); PotEntryHeader pot = new PotEntryHeader(); pot.setContext("context"); pot.getReferences().add("fff"); pot.setExtractedComment("extractedComment"); tf.getExtensions(true).add(comment); tf.getExtensions(true).add(pot); JaxbUtil.validateXml(tf, TextFlow.class); String output = mapper.writeValueAsString(tf); TextFlow res2 = mapper.readValue(output, TextFlow.class); assertThat(res2.getExtensions(true).size(), is(2)); for (TextFlowExtension e : res2.getExtensions()) { if (e instanceof SimpleComment) { assertThat(((SimpleComment) e).getValue(), is("test")); } if (e instanceof PotEntryHeader) { assertThat(((PotEntryHeader) e).getContext(), is("context")); } } }
public void serializeAndDeserializeTextFlow() throws ValidationException, JsonGenerationException, JsonMappingException, IOException { TextFlow tf = new TextFlow(); tf.setContent("ttff"); SimpleComment comment = new SimpleComment("test"); PotEntryHeader pot = new PotEntryHeader(); pot.setContext("context"); pot.getReferences().add("fff"); tf.getExtensions(true).add(comment); tf.getExtensions(true).add(pot); JaxbUtil.validateXml(tf, TextFlow.class); String output = mapper.writeValueAsString(tf); TextFlow res2 = mapper.readValue(output, TextFlow.class); assertThat(res2.getExtensions(true).size(), is(2)); for (TextFlowExtension e : res2.getExtensions()) { if (e instanceof SimpleComment) { assertThat(((SimpleComment) e).getValue(), is("test")); } if (e instanceof PotEntryHeader) { assertThat(((PotEntryHeader) e).getContext(), is("context")); } } }
diff --git a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/TaskListFilterTest.java b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/TaskListFilterTest.java index 27feb91..d68277d 100644 --- a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/TaskListFilterTest.java +++ b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/TaskListFilterTest.java @@ -1,109 +1,109 @@ /******************************************************************************* * Copyright (c) 2004 - 2006 University Of British Columbia and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylar.tests.integration; import java.util.Calendar; import java.util.List; import java.util.Set; import junit.framework.TestCase; import org.eclipse.mylar.context.tests.UiTestUtil; import org.eclipse.mylar.internal.context.ui.TaskListInterestFilter; import org.eclipse.mylar.internal.tasks.ui.AbstractTaskListFilter; import org.eclipse.mylar.internal.tasks.ui.views.TaskListView; import org.eclipse.mylar.tasks.core.ITask; import org.eclipse.mylar.tasks.core.Task; import org.eclipse.mylar.tasks.ui.TaskListManager; import org.eclipse.mylar.tasks.ui.TasksUiPlugin; /** * @author Mik Kersten */ public class TaskListFilterTest extends TestCase { private TaskListView view = TaskListView.openInActivePerspective(); private TaskListManager manager = TasksUiPlugin.getTaskListManager(); private Set<AbstractTaskListFilter> previousFilters; private ITask taskCompleted; private ITask taskIncomplete; private ITask taskOverdue; private ITask taskDueToday; private ITask taskCompletedToday; @Override protected void setUp() throws Exception { super.setUp(); assertNotNull(view); previousFilters = view.getFilters(); view.clearFilters(true); manager.getTaskList().reset(); assertEquals(0, manager.getTaskList().getAllTasks().size()); taskCompleted = new Task("completed-1", "completed", true); taskCompleted.setCompleted(true); taskCompleted.setCompletionDate(manager.setSecheduledIn(Calendar.getInstance(), -1).getTime()); manager.getTaskList().addTask(taskCompleted, manager.getTaskList().getRootCategory()); taskIncomplete = new Task("incomplete-2", "t-incomplete", true); manager.getTaskList().addTask(taskIncomplete, manager.getTaskList().getRootCategory()); taskOverdue = new Task("overdue-3", "t-overdue", true); - taskOverdue.setReminderDate(manager.setSecheduledIn(Calendar.getInstance(), -1).getTime()); + taskOverdue.setScheduledForDate(manager.setSecheduledIn(Calendar.getInstance(), -1).getTime()); manager.getTaskList().addTask(taskOverdue, manager.getTaskList().getRootCategory()); taskDueToday = new Task("today-4", "t-today", true); - taskDueToday.setReminderDate(manager.setScheduledToday(Calendar.getInstance()).getTime()); + taskDueToday.setScheduledForDate(manager.setScheduledToday(Calendar.getInstance()).getTime()); manager.getTaskList().addTask(taskDueToday, manager.getTaskList().getRootCategory()); taskCompletedToday = new Task("donetoday-5", "t-donetoday", true); - taskCompletedToday.setReminderDate(manager.setScheduledToday(Calendar.getInstance()).getTime()); + taskCompletedToday.setScheduledForDate(manager.setScheduledToday(Calendar.getInstance()).getTime()); taskCompletedToday.setCompleted(true); manager.getTaskList().addTask(taskCompletedToday, manager.getTaskList().getRootCategory()); } @Override protected void tearDown() throws Exception { super.tearDown(); view.clearFilters(true); for (AbstractTaskListFilter filter : previousFilters) { view.addFilter(filter); } } public void testInterestFilter() { TaskListInterestFilter interestFilter = new TaskListInterestFilter(); view.addFilter(interestFilter); view.getViewer().refresh(); List<Object> items = UiTestUtil.getAllData(view.getViewer().getTree()); assertFalse(items.contains(taskCompleted)); assertFalse(items.contains(taskIncomplete)); assertTrue(items.contains(taskOverdue)); assertTrue(items.contains(taskDueToday)); assertTrue(items.contains(taskCompletedToday)); view.removeFilter(interestFilter); } public void testNoFilters() { assertEquals("has archive filter", 1, view.getFilters().size()); view.getViewer().refresh(); assertEquals(5, view.getViewer().getTree().getItemCount()); } }
false
true
protected void setUp() throws Exception { super.setUp(); assertNotNull(view); previousFilters = view.getFilters(); view.clearFilters(true); manager.getTaskList().reset(); assertEquals(0, manager.getTaskList().getAllTasks().size()); taskCompleted = new Task("completed-1", "completed", true); taskCompleted.setCompleted(true); taskCompleted.setCompletionDate(manager.setSecheduledIn(Calendar.getInstance(), -1).getTime()); manager.getTaskList().addTask(taskCompleted, manager.getTaskList().getRootCategory()); taskIncomplete = new Task("incomplete-2", "t-incomplete", true); manager.getTaskList().addTask(taskIncomplete, manager.getTaskList().getRootCategory()); taskOverdue = new Task("overdue-3", "t-overdue", true); taskOverdue.setReminderDate(manager.setSecheduledIn(Calendar.getInstance(), -1).getTime()); manager.getTaskList().addTask(taskOverdue, manager.getTaskList().getRootCategory()); taskDueToday = new Task("today-4", "t-today", true); taskDueToday.setReminderDate(manager.setScheduledToday(Calendar.getInstance()).getTime()); manager.getTaskList().addTask(taskDueToday, manager.getTaskList().getRootCategory()); taskCompletedToday = new Task("donetoday-5", "t-donetoday", true); taskCompletedToday.setReminderDate(manager.setScheduledToday(Calendar.getInstance()).getTime()); taskCompletedToday.setCompleted(true); manager.getTaskList().addTask(taskCompletedToday, manager.getTaskList().getRootCategory()); }
protected void setUp() throws Exception { super.setUp(); assertNotNull(view); previousFilters = view.getFilters(); view.clearFilters(true); manager.getTaskList().reset(); assertEquals(0, manager.getTaskList().getAllTasks().size()); taskCompleted = new Task("completed-1", "completed", true); taskCompleted.setCompleted(true); taskCompleted.setCompletionDate(manager.setSecheduledIn(Calendar.getInstance(), -1).getTime()); manager.getTaskList().addTask(taskCompleted, manager.getTaskList().getRootCategory()); taskIncomplete = new Task("incomplete-2", "t-incomplete", true); manager.getTaskList().addTask(taskIncomplete, manager.getTaskList().getRootCategory()); taskOverdue = new Task("overdue-3", "t-overdue", true); taskOverdue.setScheduledForDate(manager.setSecheduledIn(Calendar.getInstance(), -1).getTime()); manager.getTaskList().addTask(taskOverdue, manager.getTaskList().getRootCategory()); taskDueToday = new Task("today-4", "t-today", true); taskDueToday.setScheduledForDate(manager.setScheduledToday(Calendar.getInstance()).getTime()); manager.getTaskList().addTask(taskDueToday, manager.getTaskList().getRootCategory()); taskCompletedToday = new Task("donetoday-5", "t-donetoday", true); taskCompletedToday.setScheduledForDate(manager.setScheduledToday(Calendar.getInstance()).getTime()); taskCompletedToday.setCompleted(true); manager.getTaskList().addTask(taskCompletedToday, manager.getTaskList().getRootCategory()); }
diff --git a/src/com/android/exchange/service/CalendarSyncAdapterService.java b/src/com/android/exchange/service/CalendarSyncAdapterService.java index a6919c5d..876b1c4c 100644 --- a/src/com/android/exchange/service/CalendarSyncAdapterService.java +++ b/src/com/android/exchange/service/CalendarSyncAdapterService.java @@ -1,127 +1,131 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.exchange.service; import android.accounts.Account; import android.content.AbstractThreadedSyncAdapter; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.Context; import android.content.SyncResult; import android.database.Cursor; import android.os.Bundle; import android.provider.CalendarContract.Events; import com.android.emailcommon.provider.EmailContent; import com.android.emailcommon.provider.EmailContent.AccountColumns; import com.android.emailcommon.provider.EmailContent.MailboxColumns; import com.android.emailcommon.provider.Mailbox; import com.android.exchange.Eas; import com.android.mail.utils.LogUtils; public class CalendarSyncAdapterService extends AbstractSyncAdapterService { private static final String TAG = "EASCalSyncAdaptSvc"; private static final String ACCOUNT_AND_TYPE_CALENDAR = MailboxColumns.ACCOUNT_KEY + "=? AND " + MailboxColumns.TYPE + '=' + Mailbox.TYPE_CALENDAR; private static final String DIRTY_IN_ACCOUNT = Events.DIRTY + "=1 AND " + Events.ACCOUNT_NAME + "=?"; public CalendarSyncAdapterService() { super(); } @Override protected AbstractThreadedSyncAdapter newSyncAdapter() { return new SyncAdapterImpl(this); } private static class SyncAdapterImpl extends AbstractThreadedSyncAdapter { public SyncAdapterImpl(Context context) { super(context, true /* autoInitialize */); } @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { CalendarSyncAdapterService.performSync(getContext(), account, extras); } } /** * Partial integration with system SyncManager; we tell our EAS ExchangeService to start a * calendar sync when we get the signal from SyncManager. * The missing piece at this point is integration with the push/ping mechanism in EAS; this will * be put in place at a later time. */ private static void performSync(Context context, Account account, Bundle extras) { - ContentResolver cr = context.getContentResolver(); - boolean logging = Eas.USER_LOG; + final ContentResolver cr = context.getContentResolver(); + final boolean logging = Eas.USER_LOG; if (extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD)) { - Cursor c = cr.query(Events.CONTENT_URI, + final Cursor c = cr.query(Events.CONTENT_URI, new String[] {Events._ID}, DIRTY_IN_ACCOUNT, new String[] {account.name}, null); + if (c == null) { + LogUtils.e(TAG, "Null changes cursor in CalendarSyncAdapterService"); + return; + } try { if (!c.moveToFirst()) { if (logging) { LogUtils.d(TAG, "No changes for " + account.name); } return; } } finally { c.close(); } } // Find the (EmailProvider) account associated with this email address final Cursor accountCursor = cr.query(com.android.emailcommon.provider.Account.CONTENT_URI, EmailContent.ID_PROJECTION, AccountColumns.EMAIL_ADDRESS + "=?", new String[] {account.name}, null); if (accountCursor == null) { LogUtils.e(TAG, "Null account cursor in CalendarSyncAdapterService"); return; } try { if (accountCursor.moveToFirst()) { final long accountId = accountCursor.getLong(0); // Now, find the calendar mailbox associated with the account final Cursor mailboxCursor = cr.query(Mailbox.CONTENT_URI, Mailbox.ID_PROJECTION, ACCOUNT_AND_TYPE_CALENDAR, new String[] {Long.toString(accountId)}, null); try { if (mailboxCursor.moveToFirst()) { if (logging) { LogUtils.d(TAG, "Upload sync requested for " + account.name); } // TODO: Currently just bouncing this to Email sync; eventually streamline. final long mailboxId = mailboxCursor.getLong(Mailbox.ID_PROJECTION_COLUMN); // TODO: Should we be using the existing extras and just adding our bits? final Bundle mailboxExtras = new Bundle(4); mailboxExtras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); mailboxExtras.putBoolean(ContentResolver.SYNC_EXTRAS_DO_NOT_RETRY, true); mailboxExtras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); mailboxExtras.putLong(Mailbox.SYNC_EXTRA_MAILBOX_ID, mailboxId); ContentResolver.requestSync(account, EmailContent.AUTHORITY, mailboxExtras); } } finally { mailboxCursor.close(); } } } finally { accountCursor.close(); } } }
false
true
private static void performSync(Context context, Account account, Bundle extras) { ContentResolver cr = context.getContentResolver(); boolean logging = Eas.USER_LOG; if (extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD)) { Cursor c = cr.query(Events.CONTENT_URI, new String[] {Events._ID}, DIRTY_IN_ACCOUNT, new String[] {account.name}, null); try { if (!c.moveToFirst()) { if (logging) { LogUtils.d(TAG, "No changes for " + account.name); } return; } } finally { c.close(); } } // Find the (EmailProvider) account associated with this email address final Cursor accountCursor = cr.query(com.android.emailcommon.provider.Account.CONTENT_URI, EmailContent.ID_PROJECTION, AccountColumns.EMAIL_ADDRESS + "=?", new String[] {account.name}, null); if (accountCursor == null) { LogUtils.e(TAG, "Null account cursor in CalendarSyncAdapterService"); return; } try { if (accountCursor.moveToFirst()) { final long accountId = accountCursor.getLong(0); // Now, find the calendar mailbox associated with the account final Cursor mailboxCursor = cr.query(Mailbox.CONTENT_URI, Mailbox.ID_PROJECTION, ACCOUNT_AND_TYPE_CALENDAR, new String[] {Long.toString(accountId)}, null); try { if (mailboxCursor.moveToFirst()) { if (logging) { LogUtils.d(TAG, "Upload sync requested for " + account.name); } // TODO: Currently just bouncing this to Email sync; eventually streamline. final long mailboxId = mailboxCursor.getLong(Mailbox.ID_PROJECTION_COLUMN); // TODO: Should we be using the existing extras and just adding our bits? final Bundle mailboxExtras = new Bundle(4); mailboxExtras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); mailboxExtras.putBoolean(ContentResolver.SYNC_EXTRAS_DO_NOT_RETRY, true); mailboxExtras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); mailboxExtras.putLong(Mailbox.SYNC_EXTRA_MAILBOX_ID, mailboxId); ContentResolver.requestSync(account, EmailContent.AUTHORITY, mailboxExtras); } } finally { mailboxCursor.close(); } } } finally { accountCursor.close(); } }
private static void performSync(Context context, Account account, Bundle extras) { final ContentResolver cr = context.getContentResolver(); final boolean logging = Eas.USER_LOG; if (extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD)) { final Cursor c = cr.query(Events.CONTENT_URI, new String[] {Events._ID}, DIRTY_IN_ACCOUNT, new String[] {account.name}, null); if (c == null) { LogUtils.e(TAG, "Null changes cursor in CalendarSyncAdapterService"); return; } try { if (!c.moveToFirst()) { if (logging) { LogUtils.d(TAG, "No changes for " + account.name); } return; } } finally { c.close(); } } // Find the (EmailProvider) account associated with this email address final Cursor accountCursor = cr.query(com.android.emailcommon.provider.Account.CONTENT_URI, EmailContent.ID_PROJECTION, AccountColumns.EMAIL_ADDRESS + "=?", new String[] {account.name}, null); if (accountCursor == null) { LogUtils.e(TAG, "Null account cursor in CalendarSyncAdapterService"); return; } try { if (accountCursor.moveToFirst()) { final long accountId = accountCursor.getLong(0); // Now, find the calendar mailbox associated with the account final Cursor mailboxCursor = cr.query(Mailbox.CONTENT_URI, Mailbox.ID_PROJECTION, ACCOUNT_AND_TYPE_CALENDAR, new String[] {Long.toString(accountId)}, null); try { if (mailboxCursor.moveToFirst()) { if (logging) { LogUtils.d(TAG, "Upload sync requested for " + account.name); } // TODO: Currently just bouncing this to Email sync; eventually streamline. final long mailboxId = mailboxCursor.getLong(Mailbox.ID_PROJECTION_COLUMN); // TODO: Should we be using the existing extras and just adding our bits? final Bundle mailboxExtras = new Bundle(4); mailboxExtras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); mailboxExtras.putBoolean(ContentResolver.SYNC_EXTRAS_DO_NOT_RETRY, true); mailboxExtras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); mailboxExtras.putLong(Mailbox.SYNC_EXTRA_MAILBOX_ID, mailboxId); ContentResolver.requestSync(account, EmailContent.AUTHORITY, mailboxExtras); } } finally { mailboxCursor.close(); } } } finally { accountCursor.close(); } }
diff --git a/lttng/org.eclipse.linuxtools.tmf.analysis.xml.ui.tests/src/org/eclipse/linuxtools/tmf/analysis/xml/ui/tests/module/XmlAnalysisModuleSourceTest.java b/lttng/org.eclipse.linuxtools.tmf.analysis.xml.ui.tests/src/org/eclipse/linuxtools/tmf/analysis/xml/ui/tests/module/XmlAnalysisModuleSourceTest.java index c35a44c85..8a4246690 100644 --- a/lttng/org.eclipse.linuxtools.tmf.analysis.xml.ui.tests/src/org/eclipse/linuxtools/tmf/analysis/xml/ui/tests/module/XmlAnalysisModuleSourceTest.java +++ b/lttng/org.eclipse.linuxtools.tmf.analysis.xml.ui.tests/src/org/eclipse/linuxtools/tmf/analysis/xml/ui/tests/module/XmlAnalysisModuleSourceTest.java @@ -1,126 +1,126 @@ /******************************************************************************* * Copyright (c) 2014 École Polytechnique de Montréal * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Geneviève Bastien - Initial implementation *******************************************************************************/ package org.eclipse.linuxtools.tmf.analysis.xml.ui.tests.module; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.util.Map; import org.eclipse.linuxtools.tmf.analysis.xml.core.module.XmlUtils; import org.eclipse.linuxtools.tmf.analysis.xml.core.tests.common.TmfXmlTestFiles; import org.eclipse.linuxtools.tmf.analysis.xml.ui.module.XmlAnalysisModuleSource; import org.eclipse.linuxtools.tmf.core.analysis.IAnalysisModuleHelper; import org.eclipse.linuxtools.tmf.core.analysis.TmfAnalysisManager; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Test suite for the {@link XmlAnalysisModuleSource} class * * @author Geneviève Bastien */ public class XmlAnalysisModuleSourceTest { private static final String SS_MODULE = "polymtl.kernel.sp"; private static void emptyXmlFolder() { File fFolder = XmlUtils.getXmlFilesPath().toFile(); if (!(fFolder.isDirectory() && fFolder.exists())) { return; } for (File xmlFile : fFolder.listFiles()) { xmlFile.delete(); } XmlAnalysisModuleSource.notifyModuleChange(); } /** * Empty the XML directory before the test, just in case */ @Before public void setUp() { emptyXmlFolder(); } /** * Empty the XML directory after the test */ @After public void cleanUp() { emptyXmlFolder(); } /** * Test the {@link XmlAnalysisModuleSource#getAnalysisModules()} method */ @Test public void testPopulateModules() { XmlAnalysisModuleSource module = new XmlAnalysisModuleSource(); Iterable<IAnalysisModuleHelper> modules = module.getAnalysisModules(); assertFalse(modules.iterator().hasNext()); /* use the valid XML test file */ File testXmlFile = TmfXmlTestFiles.VALID_FILE.getFile(); if ((testXmlFile == null) || !testXmlFile.exists()) { fail("XML test file does not exist"); } XmlUtils.addXmlFile(testXmlFile); XmlAnalysisModuleSource.notifyModuleChange(); modules = module.getAnalysisModules(); assertTrue(modules.iterator().hasNext()); assertTrue(findStateSystemModule(modules)); } private static boolean findStateSystemModule(Iterable<IAnalysisModuleHelper> modules) { for (IAnalysisModuleHelper helper : modules) { if (SS_MODULE.equals(helper.getId())) { return true; } } return false; } /** * Test that XML modules are available through the analysis manager */ @Test public void testPopulateModulesWithAnalysisManager() { /* * Make sure module sources are initialized. When run as unit test, the * XML module source is sometimes missing */ - TmfAnalysisManager.initializeModuleSources(); + TmfAnalysisManager.initialize(); Map<String, IAnalysisModuleHelper> modules = TmfAnalysisManager.getAnalysisModules(); assertFalse(findStateSystemModule(modules.values())); /* use the valid XML test file */ File testXmlFile = TmfXmlTestFiles.VALID_FILE.getFile(); if ((testXmlFile == null) || !testXmlFile.exists()) { fail("XML test file does not exist"); } XmlUtils.addXmlFile(testXmlFile); XmlAnalysisModuleSource.notifyModuleChange(); modules = TmfAnalysisManager.getAnalysisModules(); assertTrue(findStateSystemModule(modules.values())); } }
true
true
public void testPopulateModulesWithAnalysisManager() { /* * Make sure module sources are initialized. When run as unit test, the * XML module source is sometimes missing */ TmfAnalysisManager.initializeModuleSources(); Map<String, IAnalysisModuleHelper> modules = TmfAnalysisManager.getAnalysisModules(); assertFalse(findStateSystemModule(modules.values())); /* use the valid XML test file */ File testXmlFile = TmfXmlTestFiles.VALID_FILE.getFile(); if ((testXmlFile == null) || !testXmlFile.exists()) { fail("XML test file does not exist"); } XmlUtils.addXmlFile(testXmlFile); XmlAnalysisModuleSource.notifyModuleChange(); modules = TmfAnalysisManager.getAnalysisModules(); assertTrue(findStateSystemModule(modules.values())); }
public void testPopulateModulesWithAnalysisManager() { /* * Make sure module sources are initialized. When run as unit test, the * XML module source is sometimes missing */ TmfAnalysisManager.initialize(); Map<String, IAnalysisModuleHelper> modules = TmfAnalysisManager.getAnalysisModules(); assertFalse(findStateSystemModule(modules.values())); /* use the valid XML test file */ File testXmlFile = TmfXmlTestFiles.VALID_FILE.getFile(); if ((testXmlFile == null) || !testXmlFile.exists()) { fail("XML test file does not exist"); } XmlUtils.addXmlFile(testXmlFile); XmlAnalysisModuleSource.notifyModuleChange(); modules = TmfAnalysisManager.getAnalysisModules(); assertTrue(findStateSystemModule(modules.values())); }
diff --git a/servers/java/coweb-server/src/main/java/org/coweb/CollabDelegate.java b/servers/java/coweb-server/src/main/java/org/coweb/CollabDelegate.java index 21988e7..ada5987 100644 --- a/servers/java/coweb-server/src/main/java/org/coweb/CollabDelegate.java +++ b/servers/java/coweb-server/src/main/java/org/coweb/CollabDelegate.java @@ -1,479 +1,481 @@ /** * Copyright (c) The Dojo Foundation 2011. All Rights Reserved. * Copyright (c) IBM Corporation 2008, 2011. All Rights Reserved. */ package org.coweb; import java.math.BigInteger; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import org.cometd.bayeux.Message; import org.cometd.bayeux.server.ServerMessage; import org.cometd.bayeux.server.ServerSession; import org.cometd.bayeux.server.ServerChannel; import org.cometd.bayeux.server.ConfigurableServerChannel; import org.cometd.bayeux.server.BayeuxServer; public class CollabDelegate extends DefaultDelegate { private Map<String,ServerSession> updatees = new HashMap<String, ServerSession>(); private Map<String,List<String>> updaters = new HashMap<String, List<String>>(); /** * List of available siteids. An index with a null value * is an available siteid, otherwise the slot is filled with * ServerSession's clientid. */ private ArrayList<String> siteids = new ArrayList<String>(5); private Object[] lastState = null; /** * Map of bayeux client id to ServerSession */ private Map<String,ServerSession> clientids = new HashMap<String,ServerSession>(); public CollabDelegate() { super(); this.siteids.add(0, "reserved"); for(int i=1; i<5; i++) { this.siteids.add(i, null); } } @Override public boolean onSync(ServerSession client, Message message) { if(this.ensureUpdater(client)) { this.clearLastState(); } else { //System.out.println("CollabDelegate::onSync remove bad client"); this.sessionHandler.removeBadClient(client); return false; } return super.onSync(client, message); } @Override public void onClientJoin(ServerSession client, Message message) { System.out.println("CollabDelegate::onClientJoin *************"); int siteId = this.getSiteForClient(client); if(siteId == -1) { siteId = this.addSiteForClient(client); } System.out.println("siteId = " + siteId); Map<Integer,String> roster = this.getRosterList(client); //ArrayList<Object>data = new ArrayList<Object>(); Object[]data = new Object[0]; //System.out.println("data = " + data); boolean sendState = false; Map<String, Object> ext = message.getExt(); @SuppressWarnings("unchecked") Map<String, Object> cobwebData = (Map<String, Object>)ext.get("coweb"); String updaterType = (String)cobwebData.get("updaterType"); client.setAttribute("updaterType", updaterType); System.out.println("updaterType = "+updaterType); if(this.updaters.isEmpty()) { this.addUpdater(client, false); sendState = true; } else if(this.lastState == null) { this.assignUpdater(client, updaterType); sendState = false; } else { data = this.lastState; sendState = true; } client.batch(new BatchUpdateMessage(client, data, roster, siteId, sendState)); } @Override public void onUpdaterSendState(ServerSession client, Message message) { String clientId = client.getId(); Map<String, Object> data = message.getDataAsMap(); String token = (String)data.get("token"); if(token == null) { this.sessionHandler.removeBadClient(client); return; } List<String> tokens = this.updaters.get(clientId); if(tokens == null) { this.sessionHandler.removeBadClient(client); return; } if(!tokens.remove(token)) { this.sessionHandler.removeBadClient(client); return; } ServerSession updatee = this.updatees.get(token); if(updatee == null) return; this.updatees.remove(token); if (this.cacheState) { this.lastState = (Object[])data.get("state"); } ServerMessage.Mutable msg = this.sessionManager.getBayeux().newMessage(); msg.setChannel("/service/session/join/state"); if (this.cacheState) { msg.setData(this.lastState); } else { msg.setData((Object[])data.get("state")); } msg.setLazy(false); updatee.deliver(this.sessionManager.getServerSession(), msg); } @Override public void onUpdaterSubscribe(ServerSession client, Message message) { this.addUpdater(client, true); } /** * returns true if this was the last updater. */ @Override public boolean onClientRemove(ServerSession client) { System.out.println("CollabDelegate::onClientRemove ********"); System.out.println("siteId = " + client.getAttribute("siteid")); super.onClientRemove(client); this.removeUpdater(client); if(this.getUpdaterCount() == 0) { System.out.println("removing last updater, ending coweb session"); return true; } return false; } @Override public boolean onEndSession() { this.updatees.clear(); this.updaters.clear(); this.siteids.clear(); this.lastState = null; this.clientids.clear(); return true; } private void addUpdater(ServerSession serverSession, boolean notify) { String clientId = serverSession.getId(); //check if this client is already an updater and ignore unless this is //the first updater if(this.updaters.containsKey(clientId) && !this.updaters.isEmpty()) { return; } //serverSession.setAttribute("username", clientId); //System.out.println("adding " + clientId + " to list of updaters"); this.updaters.put(clientId, new ArrayList<String>()); if(notify) { this.sendRosterAvailable(serverSession); } } private void sendRosterAvailable(ServerSession client) { //System.out.println("CollabSessionHandler::sendRosterAvailable"); /* create channel */ BayeuxServer server = this.sessionManager.getBayeux(); ServerChannel.Initializer initializer = new ServerChannel.Initializer() { @Override public void configureChannel(ConfigurableServerChannel channel) { channel.setPersistent(true); } }; server.createIfAbsent("/session/roster/available", initializer); ServerChannel channel = server.getChannel("/session/roster/available"); if(channel == null) { //System.out.println("channel is null shit"); return; } ServerSession from = this.sessionManager.getServerSession(); Integer siteId = (Integer)client.getAttribute("siteid"); String username = (String)client.getAttribute("username"); Map<String, Object> data = new HashMap<String,Object>(); data.put("siteId", siteId); data.put("username", username); //System.out.println(data); channel.publish(from, data, null); } private void sendRosterUnavailable(ServerSession client) { //System.out.println("CollabSessionHandler::sendRosterAvailable"); /* create channel */ BayeuxServer server = this.sessionManager.getBayeux(); ServerChannel.Initializer initializer = new ServerChannel.Initializer() { @Override public void configureChannel(ConfigurableServerChannel channel) { channel.setPersistent(true); } }; server.createIfAbsent("/session/roster/unavailable", initializer); ServerChannel channel = server.getChannel("/session/roster/unavailable"); if(channel == null) { //System.out.println("channel is null shit"); return; } ServerSession from = this.sessionManager.getServerSession(); Integer siteId = (Integer)client.getAttribute("siteid"); String username = (String)client.getAttribute("username"); Map<String, Object> data = new HashMap<String,Object>(); data.put("siteId", siteId); data.put("username", username); //System.out.println(data); channel.publish(from, data, null); } public String toString() { return "CollabSessionHandler"; } private int getSiteForClient(ServerSession client) { if(this.siteids.contains(client.getId())) { return this.siteids.indexOf(client.getId()); } return -1; } private int addSiteForClient(ServerSession client) { int index = this.siteids.indexOf(null); if(index == -1) { index = this.siteids.size(); this.siteids.ensureCapacity(this.siteids.size() + 1); this.siteids.add(index, client.getId()); } else this.siteids.set(index, client.getId()); client.setAttribute("siteid", new Integer(index)); this.clientids.put(client.getId(), client); return index; } private int removeSiteForClient(ServerSession client) { if(client == null) { System.out.println("CollabDelegate::removeSiteForClient ******* client is null *******"); return -1; } int siteid = this.siteids.indexOf(client.getId()); if(siteid == -1) { System.out.println("CollabDelegate::removeSiteForClient ****** Cannot find client in siteids list *******"); Integer i = (Integer)client.getAttribute("siteid"); if(i == null) { System.out.println("******* Client Does not have siteId attribute - Ghost *******"); } return -1; } this.siteids.set(siteid, null); return siteid; } private Map<Integer, String> getRosterList(ServerSession client) { Map<Integer, String> roster = new HashMap<Integer,String>(); for(String clientId : this.updaters.keySet()) { ServerSession c = this.clientids.get(clientId); Integer siteId = (Integer)c.getAttribute("siteid"); roster.put(siteId, (String)c.getAttribute("username")); } return roster; } private void assignUpdater(ServerSession updatee, String updaterType) { System.out.println("CollabDelegate::assignUpdater *****************"); ServerSession from = this.sessionManager.getServerSession(); if(this.updaters.isEmpty()) { this.addUpdater(updatee, false); updatee.deliver(from, "/service/session/join/state", new ArrayList<String>(), null); return; } String updaterId = null; ServerSession updater = null; if (!updaterType.equals("default")) { String matchedType = updaterTypeMatcher.match(updaterType, getAvailableUpdaterTypes()); - for (String id : this.updaters.keySet()) { - updater = this.clientids.get(id); - if (updater.getAttribute("updaterType").equals(matchedType)) { - updaterId = id; - System.out.println("found an updater type matched to ["+matchedType+"]"); - break; + if (matchedType != null) { + for (String id : this.updaters.keySet()) { + updater = this.clientids.get(id); + if (updater.getAttribute("updaterType").equals(matchedType)) { + updaterId = id; + System.out.println("found an updater type matched to ["+matchedType+"]"); + break; + } } } } if (updaterId == null) { Random r = new Random(); int idx = r.nextInt(this.updaters.size()); System.out.println("using default updater type"); Object[] keys = this.updaters.keySet().toArray(); updaterId = (String)keys[idx]; updater = this.clientids.get(updaterId); } System.out.println("assigning updater " + updater.getAttribute("siteid") + " to " + updatee.getAttribute("siteid")); SecureRandom s = new SecureRandom(); String token = new BigInteger(130, s).toString(32); //.println("found updater " + updaterId); (this.updaters.get(updaterId)).add(token); this.updatees.put(token, updatee); updater.deliver(from, "/service/session/updater", token, null); } private boolean ensureUpdater(ServerSession serverSession) { return this.updaters.containsKey(serverSession.getId()); } private void clearLastState() { this.lastState = null; } private void removeUpdater(ServerSession client) { //System.out.println("CollabDelegate::removeUpdater " + client); this.removeSiteForClient(client); List<String> tokenList = this.updaters.get(client.getId()); this.updaters.remove(client.getId()); if(tokenList == null) { for(String token: this.updatees.keySet()) { ServerSession updatee = this.updatees.get(token); if(updatee.getId().equals(client.getId())) { this.updatees.remove(token); } } } else { //System.out.println("sending roster unavailable"); this.sendRosterUnavailable(client); if(!tokenList.isEmpty()) { //System.out.println("this updater was updating someone"); for(String token: tokenList) { ServerSession updatee = this.updatees.get(token); if(updatee == null) continue; //this.updatees.remove(token); String updaterType = (String)client.getAttribute("updaterType"); if (updaterType == null) { updaterType = "default"; } this.assignUpdater(updatee, updaterType); } } } } private int getUpdaterCount() { return this.updaters.size(); } private List<String> getAvailableUpdaterTypes() { List<String> availableUpdaterTypes = new ArrayList<String>(); for (String id : this.updaters.keySet()) { ServerSession updater = this.clientids.get(id); availableUpdaterTypes.add((String)updater.getAttribute("updaterType")); } return availableUpdaterTypes; } private class BatchUpdateMessage implements Runnable { private ServerSession client = null; private Object[] data = null; private Map<Integer,String> roster = null; private int siteId = -1; private boolean sendState = false; BatchUpdateMessage(ServerSession client, Object[] data, Map<Integer,String> roster, int siteId, boolean sendState) { this.client = client; this.data = data; this.roster = roster; this.siteId = siteId; this.sendState = sendState; } @Override public void run() { SessionManager manager = SessionManager.getInstance(); ServerSession server = manager.getServerSession(); this.client.deliver(server, "/service/session/join/siteid", this.siteId, null); this.client.deliver(server, "/service/session/join/roster", this.roster, null); if(this.sendState) { this.client.deliver(server, "/service/session/join/state", this.data, null); } } } }
true
true
private void assignUpdater(ServerSession updatee, String updaterType) { System.out.println("CollabDelegate::assignUpdater *****************"); ServerSession from = this.sessionManager.getServerSession(); if(this.updaters.isEmpty()) { this.addUpdater(updatee, false); updatee.deliver(from, "/service/session/join/state", new ArrayList<String>(), null); return; } String updaterId = null; ServerSession updater = null; if (!updaterType.equals("default")) { String matchedType = updaterTypeMatcher.match(updaterType, getAvailableUpdaterTypes()); for (String id : this.updaters.keySet()) { updater = this.clientids.get(id); if (updater.getAttribute("updaterType").equals(matchedType)) { updaterId = id; System.out.println("found an updater type matched to ["+matchedType+"]"); break; } } } if (updaterId == null) { Random r = new Random(); int idx = r.nextInt(this.updaters.size()); System.out.println("using default updater type"); Object[] keys = this.updaters.keySet().toArray(); updaterId = (String)keys[idx]; updater = this.clientids.get(updaterId); } System.out.println("assigning updater " + updater.getAttribute("siteid") + " to " + updatee.getAttribute("siteid")); SecureRandom s = new SecureRandom(); String token = new BigInteger(130, s).toString(32); //.println("found updater " + updaterId); (this.updaters.get(updaterId)).add(token); this.updatees.put(token, updatee); updater.deliver(from, "/service/session/updater", token, null); }
private void assignUpdater(ServerSession updatee, String updaterType) { System.out.println("CollabDelegate::assignUpdater *****************"); ServerSession from = this.sessionManager.getServerSession(); if(this.updaters.isEmpty()) { this.addUpdater(updatee, false); updatee.deliver(from, "/service/session/join/state", new ArrayList<String>(), null); return; } String updaterId = null; ServerSession updater = null; if (!updaterType.equals("default")) { String matchedType = updaterTypeMatcher.match(updaterType, getAvailableUpdaterTypes()); if (matchedType != null) { for (String id : this.updaters.keySet()) { updater = this.clientids.get(id); if (updater.getAttribute("updaterType").equals(matchedType)) { updaterId = id; System.out.println("found an updater type matched to ["+matchedType+"]"); break; } } } } if (updaterId == null) { Random r = new Random(); int idx = r.nextInt(this.updaters.size()); System.out.println("using default updater type"); Object[] keys = this.updaters.keySet().toArray(); updaterId = (String)keys[idx]; updater = this.clientids.get(updaterId); } System.out.println("assigning updater " + updater.getAttribute("siteid") + " to " + updatee.getAttribute("siteid")); SecureRandom s = new SecureRandom(); String token = new BigInteger(130, s).toString(32); //.println("found updater " + updaterId); (this.updaters.get(updaterId)).add(token); this.updatees.put(token, updatee); updater.deliver(from, "/service/session/updater", token, null); }