@Override protected void addCustomMetadata(Product product) throws IOException { // add bitmasks for ATSR active fires, see http://dup.esrin.esa.it/ionia/wfa/algorithm.asp final String nadirBand = EnvisatConstants.AATSR_L1B_BTEMP_NADIR_0370_BAND_NAME; final String fwardBand = EnvisatConstants.AATSR_L1B_BTEMP_FWARD_0370_BAND_NAME; ProductNodeGroup<Mask> maskGroup = product.getMaskGroup(); if (product.containsBand(nadirBand)) { maskGroup.add( mask( "fire_nadir_1", "ATSR active fire (ALGO1)", nadirBand + " > 312.0", Color.RED, 0.5f)); maskGroup.add( mask( "fire_nadir_2", "ATSR active fire (ALGO2)", nadirBand + " > 308.0", Color.RED.darker(), 0.5f)); } if (product.containsBand(fwardBand)) { maskGroup.add( mask( "fire_fward_1", "ATSR active fire (ALGO1)", fwardBand + " > 312.0", Color.RED, 0.5f)); maskGroup.add( mask( "fire_fward_2", "ATSR active fire (ALGO2)", fwardBand + " > 308.0", Color.RED.darker(), 0.5f)); } }
private void paintHelyxProgressBar(Graphics g) { int leftPadding = 15; int topPadding = 205; int splashWidth = getSplashScreen().getSize().width; int width = Math.min(10 * counter, splashWidth - (leftPadding * 2)); g.setColor(isHelyxOS ? Color.BLUE.darker() : Color.RED.darker()); g.fillRect(leftPadding, topPadding, width, 2); g.setColor(isHelyxOS ? Color.BLUE.brighter() : Color.RED.brighter()); g.fillRect(leftPadding, topPadding, width, 1); }
public static void main(String[] args) { Robot Maria = new Robot("batman"); Maria.setWindowColor(Color.RED.darker()); Maria.setPenColor(Color.white); Maria.penDown(); Maria.sparkle(); for (int i = 0; i < 4; i++) { Maria.move(50); Maria.turn(90); } }
/* Color.toString() is not great so we need a way to convert a * Color to some easily readable format, since we only * support black, white, blue, green, red, & yellow we can * easily check these by looking at the RGB values of the * color found by calling Color.getRGB(). */ public String colorToString(Color color) { if (color.getRGB() == Color.BLACK.getRGB()) { return "Black"; } else if (color.getRGB() == Color.BLUE.getRGB()) { return "Blue"; } else if (color.getRGB() == Color.GREEN.getRGB()) { return "Green"; } else if (color.getRGB() == Color.RED.getRGB()) { return "Red"; } else if (color.getRGB() == Color.YELLOW.getRGB()) { return "Yellow"; } else { return "No Color Information"; } }
@Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; synchronized (clicks) { g2.setColor(Color.RED.darker()); for (Ellipse2D ellipse : clicks) { g2.fill(ellipse); } } g2.setColor(Color.GREEN.darker()); synchronized (points) { for (Ellipse2D ellipse : points.values()) { g2.fill(ellipse); } } }
@Override public Component getListCellRendererComponent( JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { final MagicDeck deck = (MagicDeck) value; final Component c = super.getListCellRendererComponent(list, deck.getName(), index, isSelected, cellHasFocus); if (deck.isValid() == false) { if (invalidDeckFont == null) { final Map<TextAttribute, Object> attributes = new HashMap<>(); attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON); invalidDeckFont = c.getFont().deriveFont(attributes); } c.setFont(invalidDeckFont); c.setForeground(isSelected ? list.getSelectionForeground() : Color.RED.darker()); } return c; }
void updateView(TicketItemModifier ticketItemModifier) { if (ticketItemModifier == null || ticketItemModifier.getModifierType() == TicketItemModifier.MODIFIER_NOT_INITIALIZED) { setBackground(null); // setIcon(null); return; } if (ticketItemModifier.getModifierType() == TicketItemModifier.NORMAL_MODIFIER) { // setIcon(normalIcon); setBackground(Color.GREEN.darker()); } else if (ticketItemModifier.getModifierType() == TicketItemModifier.NO_MODIFIER) { // setIcon(noIcon); setBackground(Color.RED.darker()); } else if (ticketItemModifier.getModifierType() == TicketItemModifier.EXTRA_MODIFIER) { // setIcon(extraIcon); setBackground(Color.ORANGE); } }
private static void paintInvariant( Graphics g, Invariant i, int size, int ulcx, int ulcy, int width, int height) { boolean b = i.check(); double w = width * (3 / 4.0) / size; if (i instanceof RegionInvariant) { RegionInvariant ri = (RegionInvariant) i; int A = ri.getA(); int B = ri.getB(); if (b) { g.setColor(Color.GREEN.brighter()); } else { g.setColor(Color.RED.brighter()); } // g.drawRect( 100 + (int)(A*w), 100, (int)((B-A+1)*w), 400 ); g.drawRect( (int) (ulcx + width / 8.0 + A * w), (int) (ulcy + height / 6.0), (int) ((B - A + 1) * w), (int) (height * 2 / 3.0)); } }
public void wdgmsg(Widget sender, String msg, Object... args) { if (sender == in) { if (args[0] != null || ((String) args[0]).length() > 0) { String cmdText = ((String) args[0]).trim().toUpperCase(); String cmd = cmdText.contains(" ") ? cmdText.substring(0, cmdText.indexOf(" ")).trim() : cmdText; cmdText = cmdText.contains(" ") ? cmdText.substring(cmdText.indexOf(" ")).trim() : ""; append("Command: " + cmd + "\nArguments: " + cmdText, Color.BLUE.darker()); String[] cmdArgs = cmdText.split(" "); in.settext(""); if (cmd.equals("NIGHTVISION")) { if (!cmdArgs[0].trim().equals("")) { if (cmdArgs[0].equals("ON") || cmdArgs[0].equals("TRUE")) CustomConfig.hasNightVision = true; if (cmdArgs[0].equals("OFF") || cmdArgs[0].equals("FALSE")) CustomConfig.hasNightVision = false; } else { append("NIGHTVISION - " + (CustomConfig.hasNightVision ? "ON" : "OFF")); } } else if (cmd.equals("IRC")) { if (!cmdArgs[0].trim().equals("")) { if (cmdArgs[0].equals("ON") || cmdArgs[0].equals("TRUE")) CustomConfig.isIRCOn = true; if (cmdArgs[0].equals("OFF") || cmdArgs[0].equals("FALSE")) CustomConfig.isIRCOn = false; } else { append("IRC - " + (CustomConfig.isIRCOn ? "ON" : "OFF")); } } if (cmd.equals("SCREENSIZE") || cmd.equals("WINDOWSIZE")) { if (!cmdArgs[0].trim().equals("") && cmdArgs.length >= 2) { try { int x = Integer.parseInt(cmdArgs[0]); int y = Integer.parseInt(cmdArgs[1]); if (x >= 800 && y >= 600) { CustomConfig.setWindowSize(x, y); } CustomConfig.saveSettings(); append( "Client must be restarted for new settings to take effect.", Color.RED.darker()); } catch (NumberFormatException e) { append("Dimensions must be numbers"); } } else { append("SCREENSIZE = " + CustomConfig.windowSize.toString()); } } else if (cmd.equals("SOUND")) { int vol = 0; if (!cmdArgs[0].trim().equals("")) { try { if (cmdArgs[0].equals("ON") || cmdArgs[0].equals("TRUE")) { CustomConfig.isSoundOn = true; } else if (cmdArgs[0].equals("OFF") || cmdArgs[0].equals("FALSE")) { CustomConfig.isSoundOn = false; } else if ((vol = Integer.parseInt(cmdArgs[0])) >= 0 && vol <= 100) { CustomConfig.sfxVol = vol; } else throw new NumberFormatException("vol = " + vol); } catch (NumberFormatException e) { append("Volume must be an integer between 0-100"); } } else { append( "SOUND = " + (CustomConfig.isSoundOn ? "ON " : "OFF ") + "VOLUME = " + CustomConfig.sfxVol); } } else if (cmd.equals("MUSIC")) { int vol = 0; if (!cmdArgs[0].trim().equals("")) { try { if (cmdArgs[0].equals("ON") || cmdArgs[0].equals("TRUE")) { CustomConfig.isMusicOn = true; } else if (cmdArgs[0].equals("OFF") || cmdArgs[0].equals("FALSE")) { CustomConfig.isMusicOn = false; } else if ((vol = Integer.parseInt(cmdArgs[0])) >= 0 && vol <= 100) { CustomConfig.musicVol = vol; } else throw new NumberFormatException("vol = " + vol); } catch (NumberFormatException e) { append("Volume must be an integer between 0-100"); } } else { append( "MUSIC = " + (CustomConfig.isMusicOn ? "ON " : "OFF ") + "VOLUME = " + CustomConfig.musicVol); } } else if (cmd.equals("SAVE")) { CustomConfig.saveSettings(); } else if (cmd.equals("FORCESAVE")) { CustomConfig.isSaveable = true; CustomConfig.saveSettings(); } else if (cmd.equals("DEBUG")) { if (!cmdArgs[0].trim().equals("")) { if (cmdArgs[0].equals("IRC")) { if (cmdArgs.length >= 2) { if (cmdArgs[1].equals("ON") || cmdArgs[1].equals("TRUE")) { CustomConfig.logIRC = true; } else if (cmdArgs[1].equals("OFF") || cmdArgs[1].equals("FALSE")) { CustomConfig.logIRC = false; } } else { append("DEBUG LOGS", Color.BLUE.darker()); append("IRC - " + (CustomConfig.logIRC ? "ON" : "OFF"), Color.GREEN.darker()); } } else if (cmdArgs[0].equals("SRVMSG")) { if (cmdArgs.length >= 2) { if (cmdArgs[1].equals("ON") || cmdArgs[1].equals("TRUE")) { CustomConfig.logServerMessages = true; } else if (cmdArgs[1].equals("OFF") || cmdArgs[1].equals("FALSE")) { CustomConfig.logServerMessages = false; } } else { append("DEBUG LOGS", Color.BLUE.darker()); append( "SRVMSG - " + (CustomConfig.logServerMessages ? "ON" : "OFF"), Color.GREEN.darker()); } } if (cmdArgs[0].equals("LOAD")) { if (cmdArgs.length >= 2) { if (cmdArgs[1].equals("ON") || cmdArgs[1].equals("TRUE")) { CustomConfig.logLoad = true; } else if (cmdArgs[1].equals("OFF") || cmdArgs[1].equals("FALSE")) { CustomConfig.logLoad = false; } } else { append("DEBUG LOGS", Color.BLUE.darker()); append("LOAD - " + (CustomConfig.logLoad ? "ON" : "OFF"), Color.GREEN.darker()); } } } else { append("DEBUG LOGS", Color.BLUE.darker()); append("IRC - " + (CustomConfig.logIRC ? "ON" : "OFF"), Color.GREEN.darker()); append("LOAD - " + (CustomConfig.logLoad ? "ON" : "OFF"), Color.GREEN.darker()); append( "SRVMSG - " + (CustomConfig.logServerMessages ? "ON" : "OFF"), Color.GREEN.darker()); } } else if (cmd.equals("HELP")) { append( "You can check the current status of each variable by " + "typing the command without arguments.", Color.RED.darker()); append("NIGHTVISION TRUE | FALSE | ON | OFF - Turns nightvision on or off"); append("SCREENSIZE #### #### - Sets the screensize to the specified size."); append( "SOUND TRUE | FALSE | ON | OFF | 0-100 - Turns the sound effects on/off, or sets " + "the volume to the specified level"); append( "MUSIC TRUE | FALSE | ON | OFF | 0-100 - Turns the music on/off, or sets " + "the volume to the specified level"); append("SAVE - Saves the current settings if they are saveable."); append( "FORCESAVE - Saves the current settings whether or not they are " + "saveable (Might cause errors)."); append( "DEBUG IRC | LOAD ON | OFF - Enables/disables debug text being dumped into the console " + "for the specified system."); append("HELP - Shows this text."); } else { append("Command not recognized. Type /help to see a list of commands."); } } } else { super.wdgmsg(sender, msg, args); } }
@Override protected void initConfig(WordsWithStyle wordsReservedLanguague) { /** ******************************************************** */ StyleHTML styleHTML = new StyleHTML(); styleHTML.setColor(Color.BLUE); styleHTML.setFontStyle(Font.ITALIC); styleHTML.setUnderline(true); wordsReservedLanguague.put("\\balgoritmo\\b", styleHTML); wordsReservedLanguague.put("\\bfimalgoritmo\\b", styleHTML); wordsReservedLanguague.put("\\bvar\\b", styleHTML); wordsReservedLanguague.put("\\bdos\\b", styleHTML); wordsReservedLanguague.put("\\binicio\\b", styleHTML); wordsReservedLanguague.put("\\bprocedimento\\b", styleHTML); wordsReservedLanguague.put("\\bfimprocedimento\\b", styleHTML); wordsReservedLanguague.put("\\bfuncao\\b", styleHTML); wordsReservedLanguague.put("\\bfimfuncao\\b", styleHTML); /** ******************************************************** */ StyleHTML styleComments = new StyleHTML(); styleComments.setColor(Color.GREEN.darker().darker()); styleComments.setFontStyle(Font.ITALIC); wordsReservedLanguague.put("(?m)//.*$", styleComments); /** ******************************************************** */ StyleHTML styleCommentsMultine = new StyleHTML(); styleCommentsMultine.setColor(Color.BLUE.brighter()); styleCommentsMultine.setFontStyle(Font.BOLD); wordsReservedLanguague.put("(?m)\\/\\*[\\s\\S]*?\\*\\/", styleCommentsMultine); /** ******************************************************** */ StyleHTML styleString = new StyleHTML(); styleString.setColor(Color.RED); wordsReservedLanguague.put("\\\"(?:\\.|(\\\\\\\")|[^\\\"\\\"\n])*\\\"", styleString); wordsReservedLanguague.put("\\'(?:\\.|(\\\\\\')|[^\\'\\'\n])*\\'", styleString); /** ******************************************************** */ StyleHTML styleNumber = new StyleHTML(); styleNumber.setColor(Color.RED); wordsReservedLanguague.put("\\b([\\d]+(\\.[\\d]+)?|0x[a-f0-9]+)\\b", styleNumber); wordsReservedLanguague.put("\\bfalso\\b", styleNumber); wordsReservedLanguague.put("\\bverdadeiro\\b", styleNumber); /** ******************************************************** */ StyleHTML styleTypes = new StyleHTML(); styleTypes.setColor(Color.RED.darker().darker().darker()); styleTypes.setUnderline(true); wordsReservedLanguague.put("\\binteiro\\b", styleTypes); wordsReservedLanguague.put("\\breal\\b", styleTypes); wordsReservedLanguague.put("\\bcaractere\\b", styleTypes); wordsReservedLanguague.put("\\bcaracter\\b", styleTypes); wordsReservedLanguague.put("\\blogico\\b", styleTypes); wordsReservedLanguague.put("\\bvetor\\b", styleTypes); /** ******************************************************** */ StyleHTML styleCode = new StyleHTML(); styleCode.setColor(Color.BLUE.darker().darker()); wordsReservedLanguague.put("\\bescreva\\b", styleCode); wordsReservedLanguague.put("\\bescreval\\b", styleCode); wordsReservedLanguague.put("\\bleia\\b", styleCode); wordsReservedLanguague.put("\\bse\\b", styleCode); wordsReservedLanguague.put("\\bentao\\b", styleCode); wordsReservedLanguague.put("\\bsenao\\b", styleCode); wordsReservedLanguague.put("\\bfimse\\b", styleCode); wordsReservedLanguague.put("\\bescolha\\b", styleCode); wordsReservedLanguague.put("\\bfimescolha\\b", styleCode); wordsReservedLanguague.put("\\bcaso\\b", styleCode); wordsReservedLanguague.put("\\boutrocaso\\b", styleCode); wordsReservedLanguague.put("\\bate\\b", styleCode); wordsReservedLanguague.put("\\bde\\b", styleCode); wordsReservedLanguague.put("\\bfaca\\b", styleCode); wordsReservedLanguague.put("\\bpara\\b", styleCode); wordsReservedLanguague.put("\\bfimpara\\b", styleCode); wordsReservedLanguague.put("\\bdiv\\b", styleCode); wordsReservedLanguague.put("\\brepita\\b", styleCode); /** ******************************************************** */ }
/** * A private constructor to create a new editor frame based on the specified prefs configuration. * * @param prefs: the configuration to use. */ private PreferencesGUIEditorFrame(final ClientPreferences prefs) { super("Crystal Configuration Editor"); Assert.assertNotNull(prefs); final ClientPreferences copyPrefs = prefs.clone(); final Map<JComponent, Boolean> changedComponents = new HashMap<JComponent, Boolean>(); final Map<JTextField, Boolean> validEditorText = new HashMap<JTextField, Boolean>(); final Map<ProjectPreferences, Map<JTextField, Boolean>> validTextSet = new HashMap<ProjectPreferences, Map<JTextField, Boolean>>(); final JFrame frame = this; frame.setIconImage( (new ImageIcon( Constants.class.getResource("/crystal/client/images/crystal-ball_blue_128.png"))) .getImage()); if (copyPrefs.getProjectPreference().isEmpty()) { // ClientPreferences client = new ClientPreferences("/usr/bin/hg/", "/tmp/crystalClient/"); ProjectPreferences newGuy = new ProjectPreferences( new DataSource("", "", DataSource.RepoKind.HG, false, null), copyPrefs); try { copyPrefs.addProjectPreferences(newGuy); copyPrefs.setChanged(true); } catch (DuplicateProjectNameException e) { // Just ignore the duplicate project name } } getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); // getContentPane().add(new JLabel("Closing this window will save the configuraion // settings.")); // JPanel hgPanel = new JPanel(); // hgPanel.setLayout(new BoxLayout(hgPanel, BoxLayout.X_AXIS)); // hgPanel.add(new JLabel("Path to hg executable:")); // final JTextField hgPath = new JTextField(prefs.getHgPath()); // hgPath.setSize(hgPath.getWidth(), 16); // hgPanel.add(hgPath); // hgPath.addKeyListener(new KeyListener() { // public void keyPressed(KeyEvent arg0) { // } // // public void keyTyped(KeyEvent arg0) { // } // // public void keyReleased(KeyEvent arg0) { // prefs.setHgPath(hgPath.getText()); // prefs.setChanged(true); // frame.pack(); // } // }); // // JButton hgButton = new JButton("find"); // hgPanel.add(hgButton); // hgButton.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // new MyPathChooser("Path to hg executable", hgPath, JFileChooser.FILES_ONLY); // prefs.setChanged(true); // } // }); // getContentPane().add(hgPanel); JPanel topPanel = new JPanel(); topPanel.setLayout(new SpringLayout()); for (int i = 0; i < 2; i++) { topPanel.add(new JLabel()); } topPanel.add(new JLabel("Valid?")); JPanel tempPanel = new JPanel(); tempPanel.setLayout(new BoxLayout(tempPanel, BoxLayout.X_AXIS)); topPanel.add(new JLabel("Path to scratch space: ")); final JTextField tempPath = new JTextField(copyPrefs.getTempDirectory()); final JLabel tempPathState = new JLabel(); tempPanel.add(tempPath); changedComponents.put(tempPath, false); boolean pathValid = ValidInputChecker.checkDirectoryPath(tempPath.getText()) || ValidInputChecker.checkUrl(tempPath.getText()); if (pathValid) { tempPathState.setText(" valid"); tempPathState.setForeground(Color.GREEN.darker()); } else { tempPathState.setText("invalid"); tempPathState.setForeground(Color.RED.darker()); } validEditorText.put(tempPath, pathValid); tempPath.addKeyListener( new KeyListener() { public void keyPressed(KeyEvent arg0) {} public void keyTyped(KeyEvent arg0) {} public void keyReleased(KeyEvent arg0) { // TODO check if text is valid text copyPrefs.setTempDirectory(tempPath.getText()); changedComponents.put(tempPath, !prefs.getTempDirectory().equals(tempPath.getText())); boolean pathValid = ValidInputChecker.checkDirectoryPath(tempPath.getText()) || ValidInputChecker.checkUrl(tempPath.getText()); validEditorText.put(tempPath, pathValid); if (pathValid) { tempPathState.setText(" valid"); tempPathState.setForeground(Color.GREEN.darker()); } else { tempPathState.setText("invalid"); tempPathState.setForeground(Color.RED.darker()); } // copyPrefs.setChanged(true); frame.pack(); } }); tempPath.addFocusListener( new FocusListener() { @Override public void focusGained(FocusEvent arg0) { tempPath.selectAll(); } @Override public void focusLost(FocusEvent arg0) {} }); JButton tempButton = new JButton("find"); tempPanel.add(tempButton); tempButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { new MyPathChooser("Path to scratch directory", tempPath, JFileChooser.DIRECTORIES_ONLY); // copyPrefs.setChanged(true); } }); topPanel.add(tempPanel); topPanel.add(tempPathState); topPanel.add(new JLabel("Refresh rate: ")); final JTextField refreshRate = new JTextField(String.valueOf(copyPrefs.getRefresh())); final JLabel rateState = new JLabel(" valid"); rateState.setForeground(Color.GREEN.darker()); topPanel.add(refreshRate); topPanel.add(rateState); changedComponents.put(refreshRate, false); validEditorText.put(refreshRate, true); refreshRate.addKeyListener( new KeyListener() { public void keyPressed(KeyEvent arg0) {} public void keyTyped(KeyEvent arg0) {} public void keyReleased(KeyEvent arg0) { changedComponents.put( refreshRate, !String.valueOf(prefs.getRefresh()).equals(refreshRate.getText())); try { copyPrefs.setRefresh(Long.valueOf(refreshRate.getText())); } catch (Exception e) { } boolean valid = ValidInputChecker.checkStringToLong(refreshRate.getText()); validEditorText.put(refreshRate, valid); if (valid) { rateState.setText(" valid"); rateState.setForeground(Color.GREEN.darker()); } else { rateState.setText("invalid"); rateState.setForeground(Color.RED.darker()); } // copyPrefs.setChanged(true); } }); SpringLayoutUtility.formGridInColumn(topPanel, 3, 3); getContentPane().add(topPanel); final JTabbedPane projectsTabs = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.SCROLL_TAB_LAYOUT); /* * projectsTabs.addChangeListener(new ChangeListener() { * * @Override public void stateChanged(ChangeEvent e) { frame.pack(); System.out.println("Tabs changed"); } }); */ for (final ProjectPreferences copyPref : copyPrefs.getProjectPreference()) { ProjectPanel current; try { Map<JTextField, Boolean> validPanel = new HashMap<JTextField, Boolean>(); validTextSet.put(copyPref, validPanel); current = new ProjectPanel( copyPref, copyPrefs, frame, projectsTabs, changedComponents, prefs.getProjectPreferences(copyPref.getName()), validPanel); projectsTabs.addTab(current.getName(), current); JPanel pnl = new JPanel(); JLabel tabName = new JLabel(current.getName()); pnl.setOpaque(false); pnl.add(tabName); pnl.add( new DeleteProjectButton( copyPrefs, projectsTabs, frame, current, copyPref, validTextSet)); projectsTabs.setTabComponentAt(projectsTabs.getTabCount() - 1, pnl); // projectsTabs.setTitleAt(projectsTabs.getTabCount() - 1, current.getName()); } catch (NonexistentProjectException e1) { // never happens } } final JButton newProjectButton = new JButton("Add New Project"); // final JButton deleteProjectButton = new JButton("Delete This Project"); newProjectButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { // deleteProjectButton.setEnabled(true); HashSet<String> shortNameLookup = new HashSet<String>(); for (ProjectPreferences current : copyPrefs.getProjectPreference()) { shortNameLookup.add(current.getName()); } int count = 1; while (shortNameLookup.contains("New_Project_" + count++)) ; final ProjectPreferences newGuy = new ProjectPreferences( new DataSource( "New_Project_" + --count, "", DataSource.RepoKind.HG, false, null), copyPrefs); try { copyPrefs.addProjectPreferences(newGuy); } catch (DuplicateProjectNameException e1) { // This should never happen because we just found a clean project name to use. throw new RuntimeException( "When I tried to create a new project, I found a nice, clean, unused name:\n" + "New_Project_" + count + "\nbut then the preferences told me that name was in use. \n" + "This should never happen!"); } Map<JTextField, Boolean> validPanel = new HashMap<JTextField, Boolean>(); validTextSet.put(newGuy, validPanel); final ProjectPanel newGuyPanel = new ProjectPanel( newGuy, copyPrefs, frame, projectsTabs, changedComponents, null, validPanel); projectsTabs.addTab("New_Project_" + count, newGuyPanel); JPanel pnl = new JPanel(); JLabel tabName = new JLabel(newGuy.getName()); pnl.setOpaque(false); pnl.add(tabName); pnl.add( new DeleteProjectButton( copyPrefs, projectsTabs, frame, newGuyPanel, newGuy, validTextSet)); projectsTabs.setTabComponentAt(projectsTabs.getTabCount() - 1, pnl); projectsTabs.setSelectedIndex(projectsTabs.getTabCount() - 1); copyPrefs.setChanged(true); frame.pack(); } }); /* deleteProjectButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int current = projectsTabs.getSelectedIndex(); int option = JOptionPane.showConfirmDialog(null, "Do you want to delete project \"" + projectsTabs.getTitleAt(current) + "\"?", "Empty cache", JOptionPane.YES_NO_OPTION); // TODO wait for the current refresh to finish or kill it if(option == JOptionPane.YES_OPTION) { prefs.removeProjectPreferencesAtIndex(current); projectsTabs.remove(current); if (prefs.getProjectPreference().isEmpty()) deleteProjectButton.setEnabled(false); prefs.setChanged(true); frame.pack(); } } }); */ getContentPane().add(newProjectButton); getContentPane().add(projectsTabs); // getContentPane().add(deleteProjectButton); JPanel savePanel = new JPanel(); savePanel.setLayout(new FlowLayout()); final JButton saveButton = new JButton("Save"); final JButton cancelButton = new JButton("Cancel"); savePanel.add(saveButton); savePanel.add(cancelButton); getContentPane().add(savePanel); saveButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { if (copyPrefs.hasChanged() || changedComponents.values().contains(true)) { boolean validPanelText = true; for (Map<JTextField, Boolean> map : validTextSet.values()) { if (map.values().contains(false)) { validPanelText = false; } } if (!validEditorText.values().contains(false) && validPanelText) { try { ClientPreferences.savePreferencesToDefaultXML(copyPrefs); } catch (FileNotFoundException fnfe) { _log.error("Could not write to the configuration file. " + fnfe); } // TODO copyPrefs.setChanged(false); frame.setVisible(false); } else { JOptionPane.showMessageDialog( null, "You have invalid input.", "Warning", JOptionPane.ERROR_MESSAGE); } } else { frame.setVisible(false); } } }); cancelButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { editorFrame = new PreferencesGUIEditorFrame(prefs); copyPrefs.setChanged(false); frame.setVisible(false); } }); addWindowListener( new WindowListener() { public void windowClosing(WindowEvent arg0) { setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); if (copyPrefs.hasChanged() || changedComponents.values().contains(true)) { int n = JOptionPane.showConfirmDialog( null, "Do you want to save your data?", "Saving data", JOptionPane.YES_NO_CANCEL_OPTION); if (n == JOptionPane.YES_OPTION) { boolean validPanelText = true; for (Map<JTextField, Boolean> map : validTextSet.values()) { if (map.values().contains(false)) { validPanelText = false; } } if (!validEditorText.values().contains(false) && validPanelText) { try { ClientPreferences.savePreferencesToDefaultXML(copyPrefs); } catch (FileNotFoundException fnfe) { _log.error("Could not write to the configuration file. " + fnfe); } // TODO copyPrefs.setChanged(false); } else { JOptionPane.showMessageDialog( null, "You have invalid input.", "Warning", JOptionPane.ERROR_MESSAGE); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); } } else if (n == JOptionPane.CANCEL_OPTION) { setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); } else { // option is no editorFrame = new PreferencesGUIEditorFrame(prefs); copyPrefs.setChanged(false); } } } public void windowActivated(WindowEvent arg0) {} public void windowClosed(WindowEvent arg0) {} public void windowDeactivated(WindowEvent arg0) { // Reload the preferences ConflictSystemTray.getInstance().loadPreferences(); } public void windowDeiconified(WindowEvent arg0) {} public void windowIconified(WindowEvent arg0) {} public void windowOpened(WindowEvent arg0) {} }); pack(); // setVisible(true); }
@Override public void glyph( final Graphics2D g, final Rectangle2D rect, final CachedDimRangeSymbolizer symbol, final MapLayer layer) { int[] ARGB = new int[] {Color.RED.getRGB(), Color.GREEN.getRGB(), Color.BLUE.getRGB()}; if (layer instanceof CoverageMapLayer) { final CoverageMapLayer cml = (CoverageMapLayer) layer; final CoverageReference ref = cml.getCoverageReference(); try { final GridCoverageReader reader = ref.acquireReader(); final GridCoverageReadParam param = new GridCoverageReadParam(); param.setResolution(1, 1); GridCoverage2D cov = (GridCoverage2D) reader.read(0, param); ref.recycle(reader); cov = cov.view(ViewType.NATIVE); RenderedImage img = cov.getRenderedImage(); ColorModel cm = img.getColorModel(); if (cm instanceof IndexColorModel) { final IndexColorModel icm = (IndexColorModel) cm; final GridSampleDimension sampleDim = cov.getSampleDimension(0); int size = icm.getMapSize(); ARGB = new int[size]; icm.getRGBs(ARGB); final double minVal = sampleDim.getMinimumValue(); final double maxVal = sampleDim.getMaximumValue(); final ColorMap colorMap = new ColorMap(); colorMap.setGeophysicsRange( ColorMap.ANY_QUANTITATIVE_CATEGORY, new MeasurementRange( NumberRange.create(minVal, true, maxVal, true), sampleDim.getUnits())); GridSampleDimension ret = colorMap.recolor(sampleDim, ARGB); } } catch (CoverageStoreException | CancellationException ex) { Logging.getLogger("org.geotoolkit.display2d.ext.dimrange").log(Level.WARNING, null, ex); } } final float[] space = new float[ARGB.length]; final Color[] colors = new Color[ARGB.length]; for (int i = 0; i < space.length; i++) { space[i] = (float) i / (space.length - 1); colors[i] = new Color(ARGB[i]); } final LinearGradientPaint paint = new LinearGradientPaint( (float) rect.getMinX(), (float) rect.getMinY(), (float) rect.getMaxX(), (float) rect.getMinY(), space, colors); g.setPaint(paint); g.fill(rect); }
/** * OSGI Shell command GUI. GUI access to the Apache Felix Shell service. * * @url http://felix.apache.org/site/apache-felix-shell.html * @author Nicolas Fortin */ public class PluginShell extends JPanel implements DockingPanel { private static final Logger LOGGER = Logger.getLogger("gui." + PluginShell.class); private static final String SHELL_SERVICE_REFERENCE = "org.apache.felix.shell.ShellService"; private DockingPanelParameters parameters = new DockingPanelParameters(); private static final I18n I18N = I18nFactory.getI18n(PluginShell.class); private final BundleContext hostBundle; private JTextField commandField = new JTextField(); private JTextPane outputField = new JTextPane(); private TextDocumentOutputStream info = new TextDocumentOutputStream(outputField, Color.BLACK); private TextDocumentOutputStream error = new TextDocumentOutputStream(outputField, Color.RED.darker()); public PluginShell(final BundleContext hostBundle) { super(new BorderLayout()); this.hostBundle = hostBundle; parameters.setName("plugin-shell"); parameters.setTitle(I18N.tr("Plugin Shell")); parameters.setTitleIcon(new ImageIcon(PluginShell.class.getResource("panel_icon.png"))); outputField.setEditable(false); outputField.setText(I18N.tr("Plugin shell, type \"help\" for command list.\n")); // Initialising components // The shell is composed by a logging part and a command line part add(new JScrollPane(outputField), BorderLayout.CENTER); add(commandField, BorderLayout.SOUTH); commandField.addActionListener( EventHandler.create(ActionListener.class, this, "onValidateCommand")); } /** User type enter on command input */ public void onValidateCommand() { final String command = commandField.getText(); SwingUtilities.invokeLater( new Runnable() { public void run() { executeCommand(command); } }); commandField.setText(""); } private void executeCommand(String command) { // Get shell service. ServiceReference ref = hostBundle.getServiceReference(SHELL_SERVICE_REFERENCE); if (ref == null) { LOGGER.error(I18N.tr("No shell service is available.")); return; } ShellService shell = (ShellService) hostBundle.getService(ref); try { // Print the command line in the output window. try { outputField .getDocument() .insertString(outputField.getDocument().getLength(), "osgi> " + command + "\n", null); } catch (BadLocationException ex) { LOGGER.debug(ex.getLocalizedMessage(), ex); // ignore } try { shell.executeCommand(command, new PrintStream(info), new PrintStream(error)); } catch (Exception ex) { LOGGER.error(ex.getLocalizedMessage(), ex); } finally { try { // Send messages to the window info.flush(); error.flush(); outputField.setCaretPosition(outputField.getDocument().getLength()); } catch (IOException ex) { LOGGER.error(ex.getLocalizedMessage(), ex); } } } finally { hostBundle.ungetService(ref); } } @Override public DockingPanelParameters getDockingParameters() { return parameters; } @Override public JComponent getComponent() { return this; } private class TextDocumentOutputStream extends OutputStream { private JTextComponent textComponent; private ByteArrayOutputStream buffer = new ByteArrayOutputStream(); // Current text Attribute for insertion, change whith style update private AttributeSet aset; public TextDocumentOutputStream(JTextComponent textComponent, Color textColor) { this.textComponent = textComponent; changeAttribute(textColor); } @Override public void write(int i) throws IOException { buffer.write(i); } @Override public void flush() throws IOException { super.flush(); // Fetch lines in the byte array String messages = buffer.toString(); if (!messages.isEmpty()) { Document doc = textComponent.getDocument(); try { doc.insertString(doc.getLength(), messages, aset); } catch (BadLocationException ex) { LOGGER.error(I18N.tr("Cannot show the log message"), ex); } } buffer.reset(); } private void changeAttribute(Color color) { StyleContext sc = StyleContext.getDefaultStyleContext(); aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, color); } } }
@Override public Color getColor() { return Color.RED.brighter(); }
/** * Attribute values for the nodes and edges. * * @author Arend rensink * @version $Revision $ */ public class Values { /** Dash pattern of absent graphs and transitions. */ public static final float[] ABSENT_DASH = new float[] {3.0f, 3.0f}; /** Dash pattern of abstract type nodes and edges. */ public static final float[] ABSTRACT_DASH = new float[] {6.0f, 2.0f}; /** Dash pattern of connect edges. */ public static final float[] CONNECT_DASH = new float[] {2f, 4f}; /** Dash pattern for verdict edges. */ public static final float[] VERDICT_DASH = new float[] {4.0f, 3.0f}; /** No dash pattern. */ public static final float[] NO_DASH = new float[] {10.f, 0.f}; /** Foreground colour of creator nodes and edges. */ public static final Color CREATOR_FOREGROUND = Color.green.darker(); /** Background colour of creator nodes and edges. */ public static final Color CREATOR_BACKGROUND = null; /** The default foreground colour used for edges and nodes. */ public static final Color DEFAULT_FOREGROUND = Color.black; /** The default background colour used for nodes. */ public static final Color DEFAULT_BACKGROUND = Colors.findColor("243 243 243"); /** Dash pattern of embargo nodes and edges. */ public static final float[] EMBARGO_DASH = new float[] {2f, 2f}; /** Foreground colour of embargo nodes and edges. */ public static final Color EMBARGO_FOREGROUND = Color.RED; /** Background colour of embargo nodes and edges. */ public static final Color EMBARGO_BACKGROUND = null; /** Dash pattern of eraser nodes and edges. */ public static final float[] ERASER_DASH = new float[] {4f, 4f}; /** Foreground colour of eraser nodes and edges. */ public static final Color ERASER_FOREGROUND = Color.BLUE; /** Background colour of eraser nodes and edges. */ public static final Color ERASER_BACKGROUND = Colors.findColor("200 240 255"); /** Dash pattern of nesting nodes and edges. */ public static final float[] NESTED_DASH = new float[] {2.0f, 3.0f}; /** Colour used for nesting nodes and states. */ public static final Color NESTED_COLOR = Colors.findColor("165 42 42"); /** Foreground colour of remark nodes and edges. */ public static final Color REMARK_FOREGROUND = Colors.findColor("255 140 0"); /** Background colour of remark nodes and edges. */ public static final Color REMARK_BACKGROUND = Colors.findColor("255 255 180"); /** Background colour of (normal) open states. */ public static final Color OPEN_BACKGROUND = Color.GRAY.brighter(); /** Background colour of final states. */ public static final Color FINAL_BACKGROUND = Colors.findColor("0 200 0"); /** Foreground colour of result states. */ public static final Color RESULT_FOREGROUND = JAttr.STATE_BACKGROUND; /** Background colour of result states. */ public static final Color RESULT_BACKGROUND = Colors.findColor("92 125 23"); /** Background colour of error states. */ public static final Color ERROR_BACKGROUND = Color.RED; /** Foreground colour of the start state. */ public static final Color START_FOREGROUND = JAttr.STATE_BACKGROUND; /** Background colour of the start state. */ public static final Color START_BACKGROUND = Color.BLACK; /** Background colour of the start state while it is still open. */ public static final Color START_OPEN_BACKGROUND = Color.GRAY.darker(); /** Foreground colour for active nodes and edges. */ public static final Color ACTIVE_COLOR = Color.BLUE; /** Foreground colour for the active start node. */ public static final Color ACTIVE_START_COLOR = Colors.findColor("40 200 255"); /** Foreground colour for an active final node. */ public static final Color ACTIVE_FINAL_COLOR = Colors.findColor("30 100 200"); /** Colour used for transient states. */ public static final Color RECIPE_COLOR = Colors.findColor("165 42 42"); /** Colour used for transient active states. */ public static final Color ACTIVE_RECIPE_COLOR = Colors.findColor("165 42 149"); /** Background colour used for selected items in focused lists. */ public static final Color FOCUS_BACKGROUND = Color.DARK_GRAY; /** Text colour used for selected items in focused lists. */ public static final Color FOCUS_FOREGROUND = Color.WHITE; /** Background colour used for selected items in non-focused lists. */ public static final Color SELECT_BACKGROUND = Color.LIGHT_GRAY; /** Text colour used for selected items in non-focused lists. */ public static final Color SELECT_FOREGROUND = Color.BLACK; /** Background colour used for non-selected items in lists. */ public static final Color NORMAL_BACKGROUND = Color.WHITE; /** Text colour used for non-selected items in lists. */ public static final Color NORMAL_FOREGROUND = Color.BLACK; /** Text display colours to be used in normal display mode. */ public static final Values.ColorSet NORMAL_COLORS = new Values.ColorSet(); static { NORMAL_COLORS.putColors(FOCUSED, FOCUS_FOREGROUND, FOCUS_BACKGROUND); NORMAL_COLORS.putColors(SELECTED, SELECT_FOREGROUND, SELECT_BACKGROUND); NORMAL_COLORS.putColors(NONE, NORMAL_FOREGROUND, NORMAL_BACKGROUND); } /** Colour used for indicating errors in graphs. */ public static final Color ERROR_COLOR = new Color(255, 50, 0, 40); /** Background colour used for focused error items in lists. */ public static final Color ERROR_FOCUS_BACKGROUND = Color.RED.darker().darker(); /** Text colour used for focused error items in lists. */ public static final Color ERROR_FOCUS_FOREGROUND = Color.WHITE; /** Background colour used for selected, non-focused error items in lists. */ public static final Color ERROR_SELECT_BACKGROUND = ERROR_COLOR; /** Text colour used for selected, non-focused error items in lists. */ public static final Color ERROR_SELECT_FOREGROUND = Color.RED; /** Background colour used for non-selected, non-focused error items in lists. */ public static final Color ERROR_NORMAL_BACKGROUND = Color.WHITE; /** Text colour used for non-selected, non-focused error items in lists. */ public static final Color ERROR_NORMAL_FOREGROUND = Color.RED; /** Text display colours to be used in error mode. */ public static final Values.ColorSet ERROR_COLORS = new Values.ColorSet(); static { ERROR_COLORS.putColors(FOCUSED, ERROR_FOCUS_FOREGROUND, ERROR_FOCUS_BACKGROUND); ERROR_COLORS.putColors(SELECTED, ERROR_SELECT_FOREGROUND, ERROR_SELECT_BACKGROUND); ERROR_COLORS.putColors(NONE, ERROR_NORMAL_FOREGROUND, ERROR_NORMAL_BACKGROUND); } /** Text display colours to be used for transient states. */ public static final Values.ColorSet RECIPE_COLORS = new Values.ColorSet(); static { RECIPE_COLORS.putColors(FOCUSED, Color.WHITE, RECIPE_COLOR.darker()); RECIPE_COLORS.putColors(SELECTED, RECIPE_COLOR.darker(), SELECT_BACKGROUND); RECIPE_COLORS.putColors(NONE, RECIPE_COLOR, NORMAL_BACKGROUND); } /** Colour of forbidden property labels. */ public static final Color FORBIDDEN_COLOR = ERROR_COLOR; /** Colour of invariant property labels. */ public static final Color INVARIANT_COLOR = CREATOR_FOREGROUND; /** Line style that always makes right edges. */ public static final int STYLE_MANHATTAN = 14; /** Cell selection modes in trees or lists. */ public static enum Mode { /** Focused selection. */ FOCUSED, /** Normal selection. */ SELECTED, /** No selection. */ NONE; /** Converts a pair of boolean values into a selection mode. */ public static Mode toMode(boolean selected, boolean focused) { if (focused) { return Mode.FOCUSED; } else if (selected) { return Mode.SELECTED; } else { return Mode.NONE; } } } /** Set of colours per selection mode. */ public static class ColorSet extends DefaultFixable { /** Adds the foreground and background colours for a given selection mode. */ public void putColors(Mode mode, Color foreground, Color background) { testFixed(false); Color oldFore = this.foreColors.put(mode, foreground); assert oldFore == null; Color oldBack = this.backColors.put(mode, background); assert oldBack == null; if (this.foreColors.size() == Mode.values().length) { setFixed(); } } /** * Returns the foreground colour for the mode indicated by the parameters. * * @param selected if {@code true}, use selection mode * @param focused if {@code true}, use focused mode * @return the colour for the relevant mode */ public Color getForeground(boolean selected, boolean focused) { return getColor(this.foreColors, selected, focused); } /** * Returns the foreground colour for the given selection mode * * @return the colour for the relevant mode */ public Color getForeground(Mode mode) { return this.foreColors.get(mode); } /** * Returns the background colour for the mode indicated by the parameters. * * @param selected if {@code true}, use selection mode * @param focused if {@code true}, use focused mode * @return the colour for the relevant mode */ public Color getBackground(boolean selected, boolean focused) { return getColor(this.backColors, selected, focused); } /** * Returns the background colour for the given selection mode * * @return the colour for the relevant mode */ public Color getBackground(Mode mode) { return this.backColors.get(mode); } private Color getColor(Map<Mode, Color> colors, boolean selected, boolean focused) { return colors.get(Mode.toMode(selected, focused)); } private final Map<Mode, Color> foreColors = new EnumMap<Mode, Color>(Mode.class); private final Map<Mode, Color> backColors = new EnumMap<Mode, Color>(Mode.class); } }
/** * Stockage RRD et graphiques statistiques. Cette classe utilise JRobin * (http://www.jrobin.org/index.php/Main_Page) qui est une librairie Java opensource (LGPL) * similaire à RRDTool (http://oss.oetiker.ch/rrdtool/). L'API et le tutorial JRobin sont à * http://oldwww.jrobin.org/api/index.html * * @author Emeric Vernat */ final class JRobin { static final int SMALL_HEIGHT = 50; private static final Color LIGHT_RED = Color.RED.brighter().brighter(); private static final Paint SMALL_GRADIENT = new GradientPaint(0, 0, LIGHT_RED, 0, SMALL_HEIGHT, Color.GREEN, false); private static final int HOUR = 60 * 60; private static final int DAY = 24 * HOUR; private static final int DEFAULT_OBSOLETE_GRAPHS_DAYS = 90; // pool of open RRD files private final RrdDbPool rrdPool = getRrdDbPool(); private final String application; private final String name; private final String rrdFileName; private final int step; private final String requestName; private static final class AppContextClassLoaderLeakPrevention { private AppContextClassLoaderLeakPrevention() { super(); } static { // issue 476: appContextProtection is disabled by default in JreMemoryLeakPreventionListener // since Tomcat 7.0.42, // so protect from sun.awt.AppContext ourselves final ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { // Use the system classloader as the victim for this ClassLoader pinning we're about to do. Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader()); // Trigger a call to sun.awt.AppContext.getAppContext(). // This will pin the system class loader in memory but that shouldn't be an issue. ImageIO.getCacheDirectory(); } catch (final Throwable t) { // NOPMD LOG.info("prevention of AppContext ClassLoader leak failed, skipping"); } finally { Thread.currentThread().setContextClassLoader(loader); } } static void dummy() { // just to initialize the class } } private JRobin(String application, String name, File rrdFile, int step, String requestName) throws RrdException, IOException { super(); assert application != null; assert name != null; assert rrdFile != null; assert step > 0; // requestName est null pour un compteur this.application = application; this.name = name; this.rrdFileName = rrdFile.getPath(); this.step = step; this.requestName = requestName; init(); } static void stop() { if (RrdNioBackend.getFileSyncTimer() != null) { RrdNioBackend.getFileSyncTimer().cancel(); } } /** * JavaMelody uses a custom RrdNioBackendFactory, in order to use its own and cancelable file sync * timer. * * @param timer Timer * @throws IOException e */ static void initBackendFactory(Timer timer) throws IOException { RrdNioBackend.setFileSyncTimer(timer); try { if (!RrdBackendFactory.getDefaultFactory() .getFactoryName() .equals(RrdNioBackendFactory.FACTORY_NAME)) { RrdBackendFactory.registerAndSetAsDefaultFactory(new RrdNioBackendFactory()); } } catch (final RrdException e) { throw createIOException(e); } } static JRobin createInstance(String application, String name, String requestName) throws IOException { final File dir = Parameters.getStorageDirectory(application); final File rrdFile = new File(dir, name + ".rrd"); final int step = Parameters.getResolutionSeconds(); try { return new JRobin(application, name, rrdFile, step, requestName); } catch (final RrdException e) { throw createIOException(e); } } private void init() throws IOException, RrdException { final File rrdFile = new File(rrdFileName); final File rrdDirectory = rrdFile.getParentFile(); if (!rrdDirectory.mkdirs() && !rrdDirectory.exists()) { throw new IOException("JavaMelody directory can't be created: " + rrdDirectory.getPath()); } // cf issue 41: rrdFile could have been created with length 0 if out of disk space // (fix IOException: Read failed, file xxx.rrd not mapped for I/O) if (!rrdFile.exists() || rrdFile.length() == 0) { // create RRD file since it does not exist (or is empty) final RrdDef rrdDef = new RrdDef(rrdFileName, step); // "startTime" décalé de "step" pour éviter que addValue appelée juste // après ne lance l'exception suivante la première fois // "Bad sample timestamp x. Last update time was x, at least one second step is required" rrdDef.setStartTime(Util.getTime() - step); // single gauge datasource final String dsType = "GAUGE"; // max time before "unknown value" final int heartbeat = step * 2; rrdDef.addDatasource(getDataSourceName(), dsType, heartbeat, 0, Double.NaN); // several archives final String average = "AVERAGE"; final String max = "MAX"; // 1 jour rrdDef.addArchive(average, 0.25, 1, DAY / step); rrdDef.addArchive(max, 0.25, 1, DAY / step); // 1 semaine rrdDef.addArchive(average, 0.25, HOUR / step, 7 * 24); rrdDef.addArchive(max, 0.25, HOUR / step, 7 * 24); // 1 mois rrdDef.addArchive(average, 0.25, 6 * HOUR / step, 31 * 4); rrdDef.addArchive(max, 0.25, 6 * HOUR / step, 31 * 4); // 2 ans (1 an pour période "1 an" et 2 ans pour période "tout") rrdDef.addArchive(average, 0.25, 8 * 6 * HOUR / step, 2 * 12 * 15); rrdDef.addArchive(max, 0.25, 8 * 6 * HOUR / step, 2 * 12 * 15); // create RRD file in the pool final RrdDb rrdDb = rrdPool.requestRrdDb(rrdDef); rrdPool.release(rrdDb); } } private void resetFile() throws IOException { deleteFile(); try { init(); } catch (final RrdException e) { throw createIOException(e); } } byte[] graph(Range range, int width, int height) throws IOException { return graph(range, width, height, false); } byte[] graph(Range range, int width, int height, boolean maxHidden) throws IOException { // static init of the AppContext ClassLoader AppContextClassLoaderLeakPrevention.dummy(); try { // Rq : il pourrait être envisagé de récupérer les données dans les fichiers rrd ou autre // stockage // puis de faire des courbes en sparklines html (sauvegardées dans la page html) // ou avec http://code.google.com/apis/chart/types.html#sparkline ou jfreechart // create common part of graph definition final RrdGraphDef graphDef = new RrdGraphDef(); if (Locale.CHINESE.getLanguage().equals(I18N.getResourceBundle().getLocale().getLanguage())) { graphDef.setSmallFont(new Font(Font.MONOSPACED, Font.PLAIN, 10)); graphDef.setLargeFont(new Font(Font.MONOSPACED, Font.BOLD, 12)); } initGraphSource(graphDef, height, maxHidden); initGraphPeriodAndSize(range, width, height, graphDef); graphDef.setImageFormat("png"); graphDef.setFilename("-"); // il faut utiliser le pool pour les performances // et pour éviter des erreurs d'accès concurrents sur les fichiers // entre différentes générations de graphs et aussi avec l'écriture des données graphDef.setPoolUsed(true); return new RrdGraph(graphDef).getRrdGraphInfo().getBytes(); } catch (final RrdException e) { throw createIOException(e); } } private void initGraphPeriodAndSize(Range range, int width, int height, RrdGraphDef graphDef) { // ending timestamp is the (current) timestamp in seconds // starting timestamp will be adjusted for each graph final long endTime; final long startTime; if (range.getPeriod() == null) { // si endDate à la date du jour, alors on ne dépasse pas l'heure courante endTime = Math.min(range.getEndDate().getTime() / 1000, Util.getTime()); startTime = range.getStartDate().getTime() / 1000; } else { endTime = Util.getTime(); startTime = endTime - range.getPeriod().getDurationSeconds(); } final String label = getLabel(); final String titleStart; if (label.length() > 31 && width <= 200) { // si le label est trop long, on raccourci le titre sinon il ne rentre pas titleStart = label; } else { titleStart = label + " - " + range.getLabel(); } final String titleEnd; if (width > 400) { if (range.getPeriod() == null) { titleEnd = " - " + I18N.getFormattedString("sur", getApplication()); } else { titleEnd = " - " + I18N.getCurrentDate() + ' ' + I18N.getFormattedString("sur", getApplication()); } } else { titleEnd = ""; if (range.getPeriod() == null) { // si période entre 2 dates et si pas de zoom, // alors on réduit de 2 point la fonte du titre pour qu'il rentre dans le cadre graphDef.setLargeFont( graphDef.getLargeFont().deriveFont(graphDef.getLargeFont().getSize2D() - 2f)); } } graphDef.setStartTime(startTime); graphDef.setEndTime(endTime); graphDef.setTitle(titleStart + titleEnd); graphDef.setFirstDayOfWeek(Calendar.getInstance(I18N.getCurrentLocale()).getFirstDayOfWeek()); // or if the user locale patch is merged we should do: // (https://sourceforge.net/tracker/?func=detail&aid=3403733&group_id=82668&atid=566807) // graphDef.setLocale(I18N.getCurrentLocale()); // rq : la largeur et la hauteur de l'image sont plus grandes que celles fournies // car jrobin ajoute la largeur et la hauteur des textes et autres graphDef.setWidth(width); graphDef.setHeight(height); if (width <= 100) { graphDef.setNoLegend(true); graphDef.setUnitsLength(0); graphDef.setShowSignature(false); graphDef.setTitle(null); } // graphDef.setColor(RrdGraphConstants.COLOR_BACK, new GradientPaint(0, 0, // RrdGraphConstants.DEFAULT_BACK_COLOR.brighter(), 0, height, // RrdGraphConstants.DEFAULT_BACK_COLOR)); } private void initGraphSource(RrdGraphDef graphDef, int height, boolean maxHidden) { final String dataSourceName = getDataSourceName(); final String average = "average"; graphDef.datasource(average, rrdFileName, dataSourceName, "AVERAGE"); graphDef.setMinValue(0); final String moyenneLabel = I18N.getString("Moyenne"); graphDef.area(average, getPaint(height), moyenneLabel); graphDef.gprint(average, "AVERAGE", moyenneLabel + ": %9.0f %S\\r"); // graphDef.gprint(average, "MIN", "Minimum: %9.0f %S\\r"); if (!maxHidden) { final String max = "max"; graphDef.datasource(max, rrdFileName, dataSourceName, "MAX"); final String maximumLabel = I18N.getString("Maximum"); graphDef.line(max, Color.BLUE, maximumLabel); graphDef.gprint(max, "MAX", maximumLabel + ": %9.0f %S\\r"); } // graphDef.comment("JRobin :: RRDTool Choice for the Java World"); } private static Paint getPaint(int height) { // si on avait la moyenne globale/glissante des valeurs et l'écart type // on pourrait mettre vert si < moyenne + 1 écart type puis orange puis rouge si > moyenne + 2 // écarts types, // en utilisant LinearGradientPaint par exemple, ou bien selon paramètres de plages de couleurs // par graphe if (height == SMALL_HEIGHT) { // design pattern fly-weight (poids-mouche) pour le cas des 9 ou 12 graphs // dans la page html de départ return SMALL_GRADIENT; } return new GradientPaint(0, 0, LIGHT_RED, 0, height, Color.GREEN, false); } void addValue(double value) throws IOException { try { // request RRD database reference from the pool final RrdDb rrdDb = rrdPool.requestRrdDb(rrdFileName); synchronized (rrdDb) { try { // create sample with the current timestamp final Sample sample = rrdDb.createSample(); // test pour éviter l'erreur suivante au redéploiement par exemple: // org.jrobin.core.RrdException: // Bad sample timestamp x. Last update time was x, at least one second step is required if (sample.getTime() > rrdDb.getLastUpdateTime()) { // set value for load datasource sample.setValue(getDataSourceName(), value); // update database sample.update(); } } finally { // release RRD database reference rrdPool.release(rrdDb); } } } catch (final FileNotFoundException e) { if (e.getMessage() != null && e.getMessage().endsWith("[non existent]")) { // cf issue 255 LOG.debug( "A JRobin file was deleted and created again: " + new File(rrdFileName).getPath()); resetFile(); addValue(value); } } catch (final RrdException e) { if (e.getMessage() != null && e.getMessage().startsWith("Invalid file header")) { // le fichier RRD a été corrompu, par exemple en tuant le process java au milieu // d'un write, donc on efface le fichier corrompu et on le recrée pour corriger // le problème LOG.debug( "A JRobin file was found corrupted and was reset: " + new File(rrdFileName).getPath()); resetFile(); addValue(value); } throw createIOException(e); } } double getLastValue() throws IOException { try { // request RRD database reference from the pool final RrdDb rrdDb = rrdPool.requestRrdDb(rrdFileName); try { return rrdDb.getLastDatasourceValue(getDataSourceName()); } finally { // release RRD database reference rrdPool.release(rrdDb); } } catch (final RrdException e) { throw createIOException(e); } } boolean deleteFile() { return new File(rrdFileName).delete(); } private String getApplication() { return application; } String getName() { return name; } private String getDataSourceName() { // RrdDef.addDatasource n'accepte pas un nom de datasource supérieur à 20 caractères return name.substring(0, Math.min(20, name.length())); } String getLabel() { if (requestName == null) { // c'est un jrobin global issu soit de JavaInformations soit d'un Counter dans le Collector return I18N.getString(getName()); } // c'est un jrobin issu d'un CounterRequest dans le Collector final String shortRequestName = requestName.substring(0, Math.min(30, requestName.length())); // plus nécessaire: if (getName().startsWith("error")) { // c'est un jrobin issu d'un CounterRequest du Counter "error" // return I18N.getString("Erreurs_par_minute_pour") + ' ' + shortRequestName; } return I18N.getFormattedString("Temps_moyens_de", shortRequestName); } private static IOException createIOException(Exception e) { // Rq: le constructeur de IOException avec message et cause n'existe qu'en jdk 1.6 return new IOException(e.getMessage(), e); } static long deleteObsoleteJRobinFiles(String application) throws IOException { final Calendar nowMinusThreeMonthsAndADay = Calendar.getInstance(); nowMinusThreeMonthsAndADay.add(Calendar.DAY_OF_YEAR, -getObsoleteGraphsDays()); nowMinusThreeMonthsAndADay.add(Calendar.DAY_OF_YEAR, -1); final long timestamp = Util.getTimestamp(nowMinusThreeMonthsAndADay); final RrdDbPool rrdPool = getRrdDbPool(); final int counterRequestIdLength = new CounterRequest("", "").getId().length(); long diskUsage = 0; for (final File file : listRrdFiles(application)) { // on ne supprime que les fichiers rrd de requêtes (les autres sont peu nombreux) if (file.getName().length() > counterRequestIdLength && file.lastModified() < nowMinusThreeMonthsAndADay.getTimeInMillis()) { try { final RrdDb rrdDb = rrdPool.requestRrdDb(file.getPath()); final boolean obsolete = rrdDb.getLastUpdateTime() < timestamp; rrdPool.release(rrdDb); boolean deleted = false; if (obsolete) { deleted = file.delete(); } if (!deleted) { diskUsage += file.length(); } } catch (final IOException e) { continue; } catch (final RrdException e) { continue; } } else { diskUsage += file.length(); } } // on retourne true si tous les fichiers .rrd obsolètes ont été supprimés, false sinon return diskUsage; } /** * @return Nombre de jours avant qu'un fichier de graphique JRobin (extension .rrd) qui n'est plus * utilisé, soit considéré comme obsolète et soit supprimé automatiquement, à minuit (90 par * défaut, soit 3 mois). */ private static int getObsoleteGraphsDays() { final String param = Parameters.getParameter(Parameter.OBSOLETE_GRAPHS_DAYS); if (param != null) { // lance une NumberFormatException si ce n'est pas un nombre final int result = Integer.parseInt(param); if (result <= 0) { throw new IllegalStateException( "The parameter obsolete-graphs-days should be > 0 (90 recommended)"); } return result; } return DEFAULT_OBSOLETE_GRAPHS_DAYS; } private static List<File> listRrdFiles(String application) { final File storageDir = Parameters.getStorageDirectory(application); // filtre pour ne garder que les fichiers d'extension .rrd et pour éviter d'instancier des File // inutiles final FilenameFilter filenameFilter = new FilenameFilter() { /** {@inheritDoc} */ @Override public boolean accept(File dir, String fileName) { return fileName.endsWith(".rrd"); } }; final File[] files = storageDir.listFiles(filenameFilter); if (files == null) { return Collections.emptyList(); } return Arrays.asList(files); } private static RrdDbPool getRrdDbPool() throws IOException { try { return RrdDbPool.getInstance(); } catch (final RrdException e) { throw createIOException(e); } } @Override public String toString() { return getClass().getSimpleName() + "[application=" + getApplication() + ", name=" + getName() + ']'; } // public void test() throws RrdException, IOException { // for (int i = 1000; i > 0; i--) { // // request RRD database reference from the pool // RrdDb rrdDb = rrdPool.requestRrdDb(rrdFileName); // // create sample with the current timestamp // Sample sample = rrdDb.createSample(Util.getTime() - 120 * i); // // set value for load datasource // // println(i + " " + new byte[5000]); // sample.setValue(name, Runtime.getRuntime().totalMemory() - // Runtime.getRuntime().freeMemory()); // // update database // sample.update(); // // release RRD database reference // rrdPool.release(rrdDb); // } // // graph(Period.JOUR); // graph(Period.SEMAINE); // graph(Period.MOIS); // graph(Period.ANNEE); // } // // public static void main(String[] args) throws IOException, RrdException { // new JRobin("Mémoire", "jrobin", 120).test(); // } }
/*Place the labels on top */ private void placeLabels() { /*Place label On Rent */ GLabel onRentLabel = new GLabel("ON RENT"); onRentLabel.setFont(new Font("Serif", Font.BOLD, BIGFONTSIZE)); onRentLabel.setColor(FONTCOLOR); add(onRentLabel, RENTX + RENTWIDTH / 2 - onRentLabel.getWidth() / 2, RENTY - EQUIPHEIGHT); /*Place label Available */ GLabel availForRentLabel = new GLabel("AVAILABLE FOR RENT"); availForRentLabel.setFont(new Font("Serif", Font.BOLD, BIGFONTSIZE)); availForRentLabel.setColor(FONTCOLOR); add( availForRentLabel, AVAILX + AVAILWIDTH / 2 - availForRentLabel.getWidth() / 2, AVAILY - EQUIPHEIGHT); /*Place label Shop */ GLabel shopLabel = new GLabel("SHOP"); shopLabel.setFont(new Font("Serif", Font.BOLD, BIGFONTSIZE)); shopLabel.setColor(FONTCOLOR); add(shopLabel, SHOPX + SHOPWIDTH / 2 - shopLabel.getWidth() / 2, SHOPY - EQUIPHEIGHT * 14); /*Place the lost sales label */ lostSalesLabel1 = new GLabel("Lost Sales HR = " + lostSales.get(0)); lostSalesLabel2 = new GLabel("Lost Sales MR = " + lostSales.get(1)); lostSalesLabel3 = new GLabel("Lost Sales LR = " + lostSales.get(2)); lostSalesLabel1.setFont(new Font("Serif", Font.BOLD, BIGFONTSIZE)); lostSalesLabel2.setFont(new Font("Serif", Font.BOLD, BIGFONTSIZE)); lostSalesLabel3.setFont(new Font("Serif", Font.BOLD, BIGFONTSIZE)); lostSalesLabel1.setColor(FONTCOLOR); lostSalesLabel2.setColor(FONTCOLOR); lostSalesLabel3.setColor(FONTCOLOR); add(lostSalesLabel1, START_X + 4 * EQUIPWIDTH, 4 * EQUIPHEIGHT); add( lostSalesLabel2, START_X + 4 * EQUIPWIDTH, 4 * EQUIPHEIGHT + lostSalesLabel1.getHeight() * 1.5); add( lostSalesLabel3, START_X + 4 * EQUIPWIDTH, 4 * EQUIPHEIGHT + lostSalesLabel2.getHeight() * 3); /*Place the days elapsed label */ daysElapsed = 0; daysElapsedLabel = new GLabel("DAY" + daysElapsed); daysElapsedLabel.setFont(new Font("Serif", Font.BOLD, 24)); daysElapsedLabel.setColor(Color.red.darker()); add(daysElapsedLabel, APPLICATION_WIDTH / 2, START_Y / 2); /*Place the sales Label */ sales = 0; salesLabel = new GLabel("SALES: $" + sales); salesLabel.setFont(new Font("Serif", Font.BOLD, 24)); salesLabel.setColor(Color.GREEN.darker()); add(salesLabel, APPLICATION_WIDTH / 2, daysElapsedLabel.getY() + daysElapsedLabel.getY()); /*Place the capitalInvested Label */ capitalInvested = 0; capitalLabel = new GLabel("Capital Invested: $" + capitalInvested); capitalLabel.setFont(new Font("Serif", Font.BOLD, 18)); capitalLabel.setColor(Color.RED.darker()); add( capitalLabel, lostSalesLabel1.getX(), lostSalesLabel3.getY() + lostSalesLabel3.getHeight() * 2); }